civetweb.c 378 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499
  1. /* Copyright (c) 2013-2016 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) && defined(USE_WEBSOCKET)
  54. #define USE_TIMERS
  55. #endif
  56. #if defined(_MSC_VER)
  57. /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
  58. #pragma warning(disable : 4306)
  59. /* conditional expression is constant: introduced by FD_SET(..) */
  60. #pragma warning(disable : 4127)
  61. /* non-constant aggregate initializer: issued due to missing C99 support */
  62. #pragma warning(disable : 4204)
  63. /* padding added after data member */
  64. #pragma warning(disable : 4820)
  65. /* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
  66. #pragma warning(disable : 4668)
  67. /* no function prototype given: converting '()' to '(void)' */
  68. #pragma warning(disable : 4255)
  69. /* function has been selected for automatic inline expansion */
  70. #pragma warning(disable : 4711)
  71. #endif
  72. /* This code uses static_assert to check some conditions.
  73. * Unfortunately some compilers still do not support it, so we have a
  74. * replacement function here. */
  75. #if defined(_MSC_VER) && (_MSC_VER >= 1600)
  76. #define mg_static_assert static_assert
  77. #elif defined(__cplusplus) && (__cplusplus >= 201103L)
  78. #define mg_static_assert static_assert
  79. #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)
  80. #define mg_static_assert _Static_assert
  81. #else
  82. char static_assert_replacement[1];
  83. #define mg_static_assert(cond, txt) \
  84. extern char static_assert_replacement[(cond) ? 1 : -1]
  85. #endif
  86. mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
  87. "int data type size check");
  88. mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
  89. "pointer data type size check");
  90. mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
  91. /* DTL -- including winsock2.h works better if lean and mean */
  92. #ifndef WIN32_LEAN_AND_MEAN
  93. #define WIN32_LEAN_AND_MEAN
  94. #endif
  95. #if defined(__SYMBIAN32__)
  96. #define NO_SSL /* SSL is not supported */
  97. #define NO_CGI /* CGI is not supported */
  98. #define PATH_MAX FILENAME_MAX
  99. #endif /* __SYMBIAN32__ */
  100. /* Include the header file here, so the CivetWeb interface is defined for the
  101. * entire implementation, including the following forward definitions. */
  102. #include "civetweb.h"
  103. #ifndef IGNORE_UNUSED_RESULT
  104. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  105. #endif
  106. #ifndef _WIN32_WCE /* Some ANSI #includes are not available on Windows CE */
  107. #include <sys/types.h>
  108. #include <sys/stat.h>
  109. #include <errno.h>
  110. #include <signal.h>
  111. #include <fcntl.h>
  112. #endif /* !_WIN32_WCE */
  113. #ifdef __clang__
  114. /* When using -Weverything, clang does not accept it's own headers
  115. * in a release build configuration. Disable what is too much in
  116. * -Weverything. */
  117. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  118. #endif
  119. #ifdef __MACH__ /* Apple OSX section */
  120. #ifdef __clang__
  121. /* Avoid warnings for Xopen 7.00 and higher */
  122. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  123. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  124. #endif
  125. #define CLOCK_MONOTONIC (1)
  126. #define CLOCK_REALTIME (2)
  127. #include <sys/errno.h>
  128. #include <sys/time.h>
  129. #include <mach/clock.h>
  130. #include <mach/mach.h>
  131. #include <mach/mach_time.h>
  132. #include <assert.h>
  133. /* clock_gettime is not implemented on OSX prior to 10.12 */
  134. int _civet_clock_gettime(int clk_id, struct timespec *t);
  135. int
  136. _civet_clock_gettime(int clk_id, struct timespec *t)
  137. {
  138. memset(t, 0, sizeof(*t));
  139. if (clk_id == CLOCK_REALTIME) {
  140. struct timeval now;
  141. int rv = gettimeofday(&now, NULL);
  142. if (rv) {
  143. return rv;
  144. }
  145. t->tv_sec = now.tv_sec;
  146. t->tv_nsec = now.tv_usec * 1000;
  147. return 0;
  148. } else if (clk_id == CLOCK_MONOTONIC) {
  149. static uint64_t clock_start_time = 0;
  150. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  151. uint64_t now = mach_absolute_time();
  152. if (clock_start_time == 0) {
  153. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  154. #if defined(DEBUG)
  155. assert(mach_status == KERN_SUCCESS);
  156. #else
  157. /* appease "unused variable" warning for release builds */
  158. (void)mach_status;
  159. #endif
  160. clock_start_time = now;
  161. }
  162. now = (uint64_t)((double)(now - clock_start_time)
  163. * (double)timebase_ifo.numer
  164. / (double)timebase_ifo.denom);
  165. t->tv_sec = now / 1000000000;
  166. t->tv_nsec = now % 1000000000;
  167. return 0;
  168. }
  169. return -1; /* EINVAL - Clock ID is unknown */
  170. }
  171. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  172. #ifdef __CLOCK_AVAILABILITY
  173. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  174. * declared
  175. * but it may be NULL at runtime. So we need to check before using it. */
  176. int _civet_safe_clock_gettime(int clk_id, struct timespec *t);
  177. 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. #ifndef WIN_PTHREADS_TIME_H
  338. static int
  339. clock_gettime(clockid_t clk_id, struct timespec *tp)
  340. {
  341. FILETIME ft;
  342. ULARGE_INTEGER li;
  343. BOOL ok = FALSE;
  344. double d;
  345. static double perfcnt_per_sec = 0.0;
  346. if (tp) {
  347. memset(tp, 0, sizeof(*tp));
  348. if (clk_id == CLOCK_REALTIME) {
  349. GetSystemTimeAsFileTime(&ft);
  350. li.LowPart = ft.dwLowDateTime;
  351. li.HighPart = ft.dwHighDateTime;
  352. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  353. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  354. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  355. ok = TRUE;
  356. } else if (clk_id == CLOCK_MONOTONIC) {
  357. if (perfcnt_per_sec == 0.0) {
  358. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  359. perfcnt_per_sec = 1.0 / li.QuadPart;
  360. }
  361. if (perfcnt_per_sec != 0.0) {
  362. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  363. d = li.QuadPart * perfcnt_per_sec;
  364. tp->tv_sec = (time_t)d;
  365. d -= tp->tv_sec;
  366. tp->tv_nsec = (long)(d * 1.0E9);
  367. ok = TRUE;
  368. }
  369. }
  370. }
  371. return ok ? 0 : -1;
  372. }
  373. #endif
  374. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  375. static int pthread_mutex_lock(pthread_mutex_t *);
  376. static int pthread_mutex_unlock(pthread_mutex_t *);
  377. static void path_to_unicode(const struct mg_connection *conn,
  378. const char *path,
  379. wchar_t *wbuf,
  380. size_t wbuf_len);
  381. /* All file operations need to be rewritten to solve #246. */
  382. #include "file_ops.inl"
  383. struct mg_file;
  384. static const char *
  385. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p);
  386. /* POSIX dirent interface */
  387. struct dirent {
  388. char d_name[PATH_MAX];
  389. };
  390. typedef struct DIR {
  391. HANDLE handle;
  392. WIN32_FIND_DATAW info;
  393. struct dirent result;
  394. } DIR;
  395. #if defined(_WIN32) && !defined(POLLIN)
  396. #ifndef HAVE_POLL
  397. struct pollfd {
  398. SOCKET fd;
  399. short events;
  400. short revents;
  401. };
  402. #define POLLIN (0x0300)
  403. #endif
  404. #endif
  405. /* Mark required libraries */
  406. #if defined(_MSC_VER)
  407. #pragma comment(lib, "Ws2_32.lib")
  408. #endif
  409. #else /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  410. WINDOWS / UNIX include block */
  411. #include <sys/wait.h>
  412. #include <sys/socket.h>
  413. #include <sys/poll.h>
  414. #include <netinet/in.h>
  415. #include <arpa/inet.h>
  416. #include <sys/time.h>
  417. #include <sys/utsname.h>
  418. #include <stdint.h>
  419. #include <inttypes.h>
  420. #include <netdb.h>
  421. #include <netinet/tcp.h>
  422. typedef const void *SOCK_OPT_TYPE;
  423. #if defined(ANDROID)
  424. typedef unsigned short int in_port_t;
  425. #endif
  426. #include <pwd.h>
  427. #include <unistd.h>
  428. #include <grp.h>
  429. #include <dirent.h>
  430. #define vsnprintf_impl vsnprintf
  431. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  432. #include <dlfcn.h>
  433. #endif
  434. #include <pthread.h>
  435. #if defined(__MACH__)
  436. #define SSL_LIB "libssl.dylib"
  437. #define CRYPTO_LIB "libcrypto.dylib"
  438. #else
  439. #if !defined(SSL_LIB)
  440. #define SSL_LIB "libssl.so"
  441. #endif
  442. #if !defined(CRYPTO_LIB)
  443. #define CRYPTO_LIB "libcrypto.so"
  444. #endif
  445. #endif
  446. #ifndef O_BINARY
  447. #define O_BINARY (0)
  448. #endif /* O_BINARY */
  449. #define closesocket(a) (close(a))
  450. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  451. #define mg_remove(conn, x) (remove(x))
  452. #define mg_sleep(x) (usleep((x)*1000))
  453. #define mg_opendir(conn, x) (opendir(x))
  454. #define mg_closedir(x) (closedir(x))
  455. #define mg_readdir(x) (readdir(x))
  456. #define ERRNO (errno)
  457. #define INVALID_SOCKET (-1)
  458. #define INT64_FMT PRId64
  459. #define UINT64_FMT PRIu64
  460. typedef int SOCKET;
  461. #define WINCDECL
  462. #if defined(__hpux)
  463. /* HPUX 11 does not have monotonic, fall back to realtime */
  464. #ifndef CLOCK_MONOTONIC
  465. #define CLOCK_MONOTONIC CLOCK_REALTIME
  466. #endif
  467. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  468. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  469. * the prototypes use int* rather than socklen_t* which matches the
  470. * actual library expectation. When called with the wrong size arg
  471. * accept() returns a zero client inet addr and check_acl() always
  472. * fails. Since socklen_t is widely used below, just force replace
  473. * their typedef with int. - DTL
  474. */
  475. #define socklen_t int
  476. #endif /* hpux */
  477. #endif /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  478. WINDOWS / UNIX include block */
  479. /* va_copy should always be a macro, C99 and C++11 - DTL */
  480. #ifndef va_copy
  481. #define va_copy(x, y) ((x) = (y))
  482. #endif
  483. #ifdef _WIN32
  484. /* Create substitutes for POSIX functions in Win32. */
  485. #if defined(__MINGW32__)
  486. /* Show no warning in case system functions are not used. */
  487. #pragma GCC diagnostic push
  488. #pragma GCC diagnostic ignored "-Wunused-function"
  489. #endif
  490. static CRITICAL_SECTION global_log_file_lock;
  491. static DWORD
  492. pthread_self(void)
  493. {
  494. return GetCurrentThreadId();
  495. }
  496. static int
  497. pthread_key_create(
  498. pthread_key_t *key,
  499. void (*_ignored)(void *) /* destructor not supported for Windows */
  500. )
  501. {
  502. (void)_ignored;
  503. if ((key != 0)) {
  504. *key = TlsAlloc();
  505. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  506. }
  507. return -2;
  508. }
  509. static int
  510. pthread_key_delete(pthread_key_t key)
  511. {
  512. return TlsFree(key) ? 0 : 1;
  513. }
  514. static int
  515. pthread_setspecific(pthread_key_t key, void *value)
  516. {
  517. return TlsSetValue(key, value) ? 0 : 1;
  518. }
  519. static void *
  520. pthread_getspecific(pthread_key_t key)
  521. {
  522. return TlsGetValue(key);
  523. }
  524. #if defined(__MINGW32__)
  525. /* Enable unused function warning again */
  526. #pragma GCC diagnostic pop
  527. #endif
  528. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  529. #else
  530. static pthread_mutexattr_t pthread_mutex_attr;
  531. #endif /* _WIN32 */
  532. #define PASSWORDS_FILE_NAME ".htpasswd"
  533. #define CGI_ENVIRONMENT_SIZE (4096)
  534. #define MAX_CGI_ENVIR_VARS (256)
  535. #define MG_BUF_LEN (8192)
  536. #ifndef MAX_REQUEST_SIZE
  537. #define MAX_REQUEST_SIZE (16384)
  538. #endif
  539. mg_static_assert(MAX_REQUEST_SIZE >= 256,
  540. "request size length must be a positive number");
  541. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  542. #if defined(_WIN32_WCE)
  543. /* Create substitutes for POSIX functions in Win32. */
  544. #if defined(__MINGW32__)
  545. /* Show no warning in case system functions are not used. */
  546. #pragma GCC diagnostic push
  547. #pragma GCC diagnostic ignored "-Wunused-function"
  548. #endif
  549. static time_t
  550. time(time_t *ptime)
  551. {
  552. time_t t;
  553. SYSTEMTIME st;
  554. FILETIME ft;
  555. GetSystemTime(&st);
  556. SystemTimeToFileTime(&st, &ft);
  557. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  558. if (ptime != NULL) {
  559. *ptime = t;
  560. }
  561. return t;
  562. }
  563. static struct tm *
  564. localtime_s(const time_t *ptime, struct tm *ptm)
  565. {
  566. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  567. FILETIME ft, lft;
  568. SYSTEMTIME st;
  569. TIME_ZONE_INFORMATION tzinfo;
  570. if (ptm == NULL) {
  571. return NULL;
  572. }
  573. *(int64_t *)&ft = t;
  574. FileTimeToLocalFileTime(&ft, &lft);
  575. FileTimeToSystemTime(&lft, &st);
  576. ptm->tm_year = st.wYear - 1900;
  577. ptm->tm_mon = st.wMonth - 1;
  578. ptm->tm_wday = st.wDayOfWeek;
  579. ptm->tm_mday = st.wDay;
  580. ptm->tm_hour = st.wHour;
  581. ptm->tm_min = st.wMinute;
  582. ptm->tm_sec = st.wSecond;
  583. ptm->tm_yday = 0; /* hope nobody uses this */
  584. ptm->tm_isdst =
  585. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  586. return ptm;
  587. }
  588. static struct tm *
  589. gmtime_s(const time_t *ptime, struct tm *ptm)
  590. {
  591. /* FIXME(lsm): fix this. */
  592. return localtime_s(ptime, ptm);
  593. }
  594. static int mg_atomic_inc(volatile int *addr);
  595. static struct tm tm_array[MAX_WORKER_THREADS];
  596. static int tm_index = 0;
  597. static struct tm *
  598. localtime(const time_t *ptime)
  599. {
  600. int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0]));
  601. return localtime_s(ptime, tm_array + i);
  602. }
  603. static struct tm *
  604. gmtime(const time_t *ptime)
  605. {
  606. int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  607. return gmtime_s(ptime, tm_array + i);
  608. }
  609. static size_t
  610. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  611. {
  612. /* TODO */ //(void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  613. // for WinCE");
  614. return 0;
  615. }
  616. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  617. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  618. #define remove(f) mg_remove(NULL, f)
  619. static int
  620. rename(const char *a, const char *b)
  621. {
  622. wchar_t wa[PATH_MAX];
  623. wchar_t wb[PATH_MAX];
  624. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  625. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  626. return MoveFileW(wa, wb) ? 0 : -1;
  627. }
  628. struct stat {
  629. int64_t st_size;
  630. time_t st_mtime;
  631. };
  632. static int
  633. stat(const char *name, struct stat *st)
  634. {
  635. wchar_t wbuf[PATH_MAX];
  636. WIN32_FILE_ATTRIBUTE_DATA attr;
  637. time_t creation_time, write_time;
  638. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  639. memset(&attr, 0, sizeof(attr));
  640. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  641. st->st_size =
  642. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  643. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  644. attr.ftLastWriteTime.dwHighDateTime);
  645. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  646. attr.ftCreationTime.dwHighDateTime);
  647. if (creation_time > write_time) {
  648. st->st_mtime = creation_time;
  649. } else {
  650. st->st_mtime = write_time;
  651. }
  652. return 0;
  653. }
  654. #define access(x, a) 1 /* not required anyway */
  655. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  656. #define EEXIST 1 /* TODO: See Windows error codes */
  657. #define EACCES 2 /* TODO: See Windows error codes */
  658. #define ENOENT 3 /* TODO: See Windows Error codes */
  659. #if defined(__MINGW32__)
  660. /* Enable unused function warning again */
  661. #pragma GCC diagnostic pop
  662. #endif
  663. #endif /* defined(_WIN32_WCE) */
  664. #if !defined(DEBUG_TRACE)
  665. #if defined(DEBUG)
  666. static void DEBUG_TRACE_FUNC(const char *func,
  667. unsigned line,
  668. PRINTF_FORMAT_STRING(const char *fmt),
  669. ...) PRINTF_ARGS(3, 4);
  670. static void
  671. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  672. {
  673. va_list args;
  674. struct timespec tsnow;
  675. uint64_t nsnow;
  676. static uint64_t nslast;
  677. clock_gettime(CLOCK_REALTIME, &tsnow);
  678. nsnow = (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  679. flockfile(stdout);
  680. printf("*** %lu.%09lu %12" INT64_FMT " %p %s:%u: ",
  681. (unsigned long)tsnow.tv_sec,
  682. (unsigned long)tsnow.tv_nsec,
  683. nsnow - nslast,
  684. (void *)pthread_self(),
  685. func,
  686. line);
  687. va_start(args, fmt);
  688. vprintf(fmt, args);
  689. va_end(args);
  690. putchar('\n');
  691. fflush(stdout);
  692. funlockfile(stdout);
  693. nslast = nsnow;
  694. }
  695. #define DEBUG_TRACE(fmt, ...) \
  696. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  697. #else
  698. #define DEBUG_TRACE(fmt, ...) \
  699. do { \
  700. } while (0)
  701. #endif /* DEBUG */
  702. #endif /* DEBUG_TRACE */
  703. #if defined(MEMORY_DEBUGGING)
  704. unsigned long mg_memory_debug_blockCount = 0;
  705. 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. #define MD5_STATIC static
  897. #include "md5.inl"
  898. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  899. #ifdef NO_SOCKLEN_T
  900. typedef int socklen_t;
  901. #endif /* NO_SOCKLEN_T */
  902. #define _DARWIN_UNLIMITED_SELECT
  903. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  904. #if !defined(MSG_NOSIGNAL)
  905. #define MSG_NOSIGNAL (0)
  906. #endif
  907. #if !defined(SOMAXCONN)
  908. #define SOMAXCONN (100)
  909. #endif
  910. /* Size of the accepted socket queue */
  911. #if !defined(MGSQLEN)
  912. #define MGSQLEN (20)
  913. #endif
  914. #if defined(NO_SSL)
  915. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  916. typedef struct SSL_CTX SSL_CTX;
  917. #else
  918. #if defined(NO_SSL_DL)
  919. #include <openssl/ssl.h>
  920. #include <openssl/err.h>
  921. #include <openssl/crypto.h>
  922. #include <openssl/x509.h>
  923. #include <openssl/pem.h>
  924. #include <openssl/engine.h>
  925. #include <openssl/conf.h>
  926. #include <openssl/dh.h>
  927. #else
  928. /* SSL loaded dynamically from DLL.
  929. * I put the prototypes here to be independent from OpenSSL source
  930. * installation. */
  931. typedef struct ssl_st SSL;
  932. typedef struct ssl_method_st SSL_METHOD;
  933. typedef struct ssl_ctx_st SSL_CTX;
  934. typedef struct x509_store_ctx_st X509_STORE_CTX;
  935. typedef struct x509_name X509_NAME;
  936. typedef struct asn1_integer ASN1_INTEGER;
  937. typedef struct evp_md EVP_MD;
  938. typedef struct x509 X509;
  939. #define SSL_CTRL_OPTIONS (32)
  940. #define SSL_CTRL_CLEAR_OPTIONS (77)
  941. #define SSL_CTRL_SET_ECDH_AUTO (94)
  942. #define SSL_VERIFY_NONE (0)
  943. #define SSL_VERIFY_PEER (1)
  944. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  945. #define SSL_VERIFY_CLIENT_ONCE (4)
  946. #define SSL_OP_ALL ((long)(0x80000BFFUL))
  947. #define SSL_OP_NO_SSLv2 (0x01000000L)
  948. #define SSL_OP_NO_SSLv3 (0x02000000L)
  949. #define SSL_OP_NO_TLSv1 (0x04000000L)
  950. #define SSL_OP_NO_TLSv1_2 (0x08000000L)
  951. #define SSL_OP_NO_TLSv1_1 (0x10000000L)
  952. #define SSL_OP_SINGLE_DH_USE (0x00100000L)
  953. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000L)
  954. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000L)
  955. #define SSL_ERROR_NONE (0)
  956. #define SSL_ERROR_SSL (1)
  957. #define SSL_ERROR_WANT_READ (2)
  958. #define SSL_ERROR_WANT_WRITE (3)
  959. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  960. #define SSL_ERROR_SYSCALL (5) /* see errno */
  961. #define SSL_ERROR_ZERO_RETURN (6)
  962. #define SSL_ERROR_WANT_CONNECT (7)
  963. #define SSL_ERROR_WANT_ACCEPT (8)
  964. struct ssl_func {
  965. const char *name; /* SSL function name */
  966. void (*ptr)(void); /* Function pointer */
  967. };
  968. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  969. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  970. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  971. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  972. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  973. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  974. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  975. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  976. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  977. #define SSLv23_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  978. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  979. #define SSL_CTX_use_PrivateKey_file \
  980. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  981. #define SSL_CTX_use_certificate_file \
  982. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  983. #define SSL_CTX_set_default_passwd_cb \
  984. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  985. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  986. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  987. #define SSL_CTX_use_certificate_chain_file \
  988. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  989. #define SSLv23_client_method (*(SSL_METHOD * (*)(void))ssl_sw[17].ptr)
  990. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  991. #define SSL_CTX_set_verify \
  992. (*(void (*)(SSL_CTX *, \
  993. int, \
  994. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19].ptr)
  995. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  996. #define SSL_CTX_load_verify_locations \
  997. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  998. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  999. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  1000. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[24].ptr)
  1001. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  1002. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[26].ptr)
  1003. #define SSL_CIPHER_get_name \
  1004. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  1005. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  1006. #define SSL_CTX_set_session_id_context \
  1007. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  1008. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  1009. #define SSL_CTX_set_cipher_list \
  1010. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  1011. #define SSL_CTX_set_options(ctx, op) \
  1012. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  1013. #define SSL_CTX_clear_options(ctx, op) \
  1014. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1015. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1016. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1017. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1018. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1019. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  1020. #define CRYPTO_set_locking_callback \
  1021. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  1022. #define CRYPTO_set_id_callback \
  1023. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  1024. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  1025. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  1026. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  1027. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  1028. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  1029. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  1030. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  1031. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  1032. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  1033. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[12].ptr)
  1034. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[13].ptr)
  1035. #define X509_NAME_oneline \
  1036. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  1037. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[15].ptr)
  1038. #define i2c_ASN1_INTEGER \
  1039. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  1040. #define EVP_get_digestbyname \
  1041. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1042. #define ASN1_digest \
  1043. (*(int (*)(int (*)(), \
  1044. const EVP_MD *, \
  1045. char *, \
  1046. unsigned char *, \
  1047. unsigned int *))crypto_sw[18].ptr)
  1048. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1049. /* set_ssl_option() function updates this array.
  1050. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1051. * of respective functions. The macros above (like SSL_connect()) are really
  1052. * just calling these functions indirectly via the pointer. */
  1053. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1054. {"SSL_accept", NULL},
  1055. {"SSL_connect", NULL},
  1056. {"SSL_read", NULL},
  1057. {"SSL_write", NULL},
  1058. {"SSL_get_error", NULL},
  1059. {"SSL_set_fd", NULL},
  1060. {"SSL_new", NULL},
  1061. {"SSL_CTX_new", NULL},
  1062. {"SSLv23_server_method", NULL},
  1063. {"SSL_library_init", NULL},
  1064. {"SSL_CTX_use_PrivateKey_file", NULL},
  1065. {"SSL_CTX_use_certificate_file", NULL},
  1066. {"SSL_CTX_set_default_passwd_cb", NULL},
  1067. {"SSL_CTX_free", NULL},
  1068. {"SSL_load_error_strings", NULL},
  1069. {"SSL_CTX_use_certificate_chain_file", NULL},
  1070. {"SSLv23_client_method", NULL},
  1071. {"SSL_pending", NULL},
  1072. {"SSL_CTX_set_verify", NULL},
  1073. {"SSL_shutdown", NULL},
  1074. {"SSL_CTX_load_verify_locations", NULL},
  1075. {"SSL_CTX_set_default_verify_paths", NULL},
  1076. {"SSL_CTX_set_verify_depth", NULL},
  1077. {"SSL_get_peer_certificate", NULL},
  1078. {"SSL_get_version", NULL},
  1079. {"SSL_get_current_cipher", NULL},
  1080. {"SSL_CIPHER_get_name", NULL},
  1081. {"SSL_CTX_check_private_key", NULL},
  1082. {"SSL_CTX_set_session_id_context", NULL},
  1083. {"SSL_CTX_ctrl", NULL},
  1084. {"SSL_CTX_set_cipher_list", NULL},
  1085. {NULL, NULL}};
  1086. /* Similar array as ssl_sw. These functions could be located in different
  1087. * lib. */
  1088. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  1089. {"CRYPTO_set_locking_callback", NULL},
  1090. {"CRYPTO_set_id_callback", NULL},
  1091. {"ERR_get_error", NULL},
  1092. {"ERR_error_string", NULL},
  1093. {"ERR_remove_state", NULL},
  1094. {"ERR_free_strings", NULL},
  1095. {"ENGINE_cleanup", NULL},
  1096. {"CONF_modules_unload", NULL},
  1097. {"CRYPTO_cleanup_all_ex_data", NULL},
  1098. {"EVP_cleanup", NULL},
  1099. {"X509_free", NULL},
  1100. {"X509_get_subject_name", NULL},
  1101. {"X509_get_issuer_name", NULL},
  1102. {"X509_NAME_oneline", NULL},
  1103. {"X509_get_serialNumber", NULL},
  1104. {"i2c_ASN1_INTEGER", NULL},
  1105. {"EVP_get_digestbyname", NULL},
  1106. {"ASN1_digest", NULL},
  1107. {"i2d_X509", NULL},
  1108. {NULL, NULL}};
  1109. #endif /* NO_SSL_DL */
  1110. #endif /* NO_SSL */
  1111. #if !defined(NO_CACHING)
  1112. static const char *month_names[] = {"Jan",
  1113. "Feb",
  1114. "Mar",
  1115. "Apr",
  1116. "May",
  1117. "Jun",
  1118. "Jul",
  1119. "Aug",
  1120. "Sep",
  1121. "Oct",
  1122. "Nov",
  1123. "Dec"};
  1124. #endif /* !NO_CACHING */
  1125. /* Unified socket address. For IPv6 support, add IPv6 address structure in the
  1126. * union u. */
  1127. union usa {
  1128. struct sockaddr sa;
  1129. struct sockaddr_in sin;
  1130. #if defined(USE_IPV6)
  1131. struct sockaddr_in6 sin6;
  1132. #endif
  1133. };
  1134. /* Describes a string (chunk of memory). */
  1135. struct vec {
  1136. const char *ptr;
  1137. size_t len;
  1138. };
  1139. struct mg_file_stat {
  1140. /* File properties filled by mg_stat: */
  1141. uint64_t size;
  1142. time_t last_modified;
  1143. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1144. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1145. * case we need a "Content-Eencoding: gzip" header */
  1146. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1147. };
  1148. struct mg_file_access {
  1149. /* File properties filled by mg_fopen: */
  1150. FILE *fp;
  1151. const char *membuf;
  1152. };
  1153. struct mg_file {
  1154. struct mg_file_stat stat;
  1155. struct mg_file_access access;
  1156. };
  1157. #define STRUCT_FILE_INITIALIZER \
  1158. { \
  1159. { \
  1160. (uint64_t)0, (time_t)0, 0, 0, 0 \
  1161. } \
  1162. , \
  1163. { \
  1164. (FILE *) NULL, (const char *)NULL \
  1165. } \
  1166. }
  1167. /* Describes listening socket, or socket which was accept()-ed by the master
  1168. * thread and queued for future handling by the worker thread. */
  1169. struct socket {
  1170. SOCKET sock; /* Listening socket */
  1171. union usa lsa; /* Local socket address */
  1172. union usa rsa; /* Remote socket address */
  1173. unsigned char is_ssl; /* Is port SSL-ed */
  1174. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1175. * port */
  1176. unsigned char in_use; /* Is valid */
  1177. };
  1178. /* NOTE(lsm): this enum shoulds be in sync with the config_options below. */
  1179. enum {
  1180. CGI_EXTENSIONS,
  1181. CGI_ENVIRONMENT,
  1182. PUT_DELETE_PASSWORDS_FILE,
  1183. CGI_INTERPRETER,
  1184. PROTECT_URI,
  1185. AUTHENTICATION_DOMAIN,
  1186. SSI_EXTENSIONS,
  1187. THROTTLE,
  1188. ACCESS_LOG_FILE,
  1189. ENABLE_DIRECTORY_LISTING,
  1190. ERROR_LOG_FILE,
  1191. GLOBAL_PASSWORDS_FILE,
  1192. INDEX_FILES,
  1193. ENABLE_KEEP_ALIVE,
  1194. ACCESS_CONTROL_LIST,
  1195. EXTRA_MIME_TYPES,
  1196. LISTENING_PORTS,
  1197. DOCUMENT_ROOT,
  1198. SSL_CERTIFICATE,
  1199. NUM_THREADS,
  1200. RUN_AS_USER,
  1201. REWRITE,
  1202. HIDE_FILES,
  1203. REQUEST_TIMEOUT,
  1204. KEEP_ALIVE_TIMEOUT,
  1205. SSL_DO_VERIFY_PEER,
  1206. SSL_CA_PATH,
  1207. SSL_CA_FILE,
  1208. SSL_VERIFY_DEPTH,
  1209. SSL_DEFAULT_VERIFY_PATHS,
  1210. SSL_CIPHER_LIST,
  1211. SSL_PROTOCOL_VERSION,
  1212. SSL_SHORT_TRUST,
  1213. #if defined(USE_WEBSOCKET)
  1214. WEBSOCKET_TIMEOUT,
  1215. #endif
  1216. DECODE_URL,
  1217. #if defined(USE_LUA)
  1218. LUA_PRELOAD_FILE,
  1219. LUA_SCRIPT_EXTENSIONS,
  1220. LUA_SERVER_PAGE_EXTENSIONS,
  1221. #endif
  1222. #if defined(USE_DUKTAPE)
  1223. DUKTAPE_SCRIPT_EXTENSIONS,
  1224. #endif
  1225. #if defined(USE_WEBSOCKET)
  1226. WEBSOCKET_ROOT,
  1227. #endif
  1228. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1229. LUA_WEBSOCKET_EXTENSIONS,
  1230. #endif
  1231. ACCESS_CONTROL_ALLOW_ORIGIN,
  1232. ERROR_PAGES,
  1233. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1234. * socket option typedef TCP_NODELAY. */
  1235. #if !defined(NO_CACHING)
  1236. STATIC_FILE_MAX_AGE,
  1237. #endif
  1238. #if defined(__linux__)
  1239. ALLOW_SENDFILE_CALL,
  1240. #endif
  1241. #if defined(_WIN32)
  1242. CASE_SENSITIVE_FILES,
  1243. #endif
  1244. NUM_OPTIONS
  1245. };
  1246. /* Config option name, config types, default value */
  1247. static struct mg_option config_options[] = {
  1248. {"cgi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1249. {"cgi_environment", CONFIG_TYPE_STRING, NULL},
  1250. {"put_delete_auth_file", CONFIG_TYPE_FILE, NULL},
  1251. {"cgi_interpreter", CONFIG_TYPE_FILE, NULL},
  1252. {"protect_uri", CONFIG_TYPE_STRING, NULL},
  1253. {"authentication_domain", CONFIG_TYPE_STRING, "mydomain.com"},
  1254. {"ssi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1255. {"throttle", CONFIG_TYPE_STRING, NULL},
  1256. {"access_log_file", CONFIG_TYPE_FILE, NULL},
  1257. {"enable_directory_listing", CONFIG_TYPE_BOOLEAN, "yes"},
  1258. {"error_log_file", CONFIG_TYPE_FILE, NULL},
  1259. {"global_auth_file", CONFIG_TYPE_FILE, NULL},
  1260. {"index_files",
  1261. CONFIG_TYPE_STRING,
  1262. #ifdef USE_LUA
  1263. "index.xhtml,index.html,index.htm,index.lp,index.lsp,index.lua,index.cgi,"
  1264. "index.shtml,index.php"},
  1265. #else
  1266. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1267. #endif
  1268. {"enable_keep_alive", CONFIG_TYPE_BOOLEAN, "no"},
  1269. {"access_control_list", CONFIG_TYPE_STRING, NULL},
  1270. {"extra_mime_types", CONFIG_TYPE_STRING, NULL},
  1271. {"listening_ports", CONFIG_TYPE_STRING, "8080"},
  1272. {"document_root", CONFIG_TYPE_DIRECTORY, NULL},
  1273. {"ssl_certificate", CONFIG_TYPE_FILE, NULL},
  1274. {"num_threads", CONFIG_TYPE_NUMBER, "50"},
  1275. {"run_as_user", CONFIG_TYPE_STRING, NULL},
  1276. {"url_rewrite_patterns", CONFIG_TYPE_STRING, NULL},
  1277. {"hide_files_patterns", CONFIG_TYPE_EXT_PATTERN, NULL},
  1278. {"request_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1279. {"keep_alive_timeout_ms", CONFIG_TYPE_NUMBER, "500"},
  1280. {"ssl_verify_peer", CONFIG_TYPE_BOOLEAN, "no"},
  1281. {"ssl_ca_path", CONFIG_TYPE_DIRECTORY, NULL},
  1282. {"ssl_ca_file", CONFIG_TYPE_FILE, NULL},
  1283. {"ssl_verify_depth", CONFIG_TYPE_NUMBER, "9"},
  1284. {"ssl_default_verify_paths", CONFIG_TYPE_BOOLEAN, "yes"},
  1285. {"ssl_cipher_list", CONFIG_TYPE_STRING, NULL},
  1286. {"ssl_protocol_version", CONFIG_TYPE_NUMBER, "0"},
  1287. {"ssl_short_trust", CONFIG_TYPE_BOOLEAN, "no"},
  1288. #if defined(USE_WEBSOCKET)
  1289. {"websocket_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1290. #endif
  1291. {"decode_url", CONFIG_TYPE_BOOLEAN, "yes"},
  1292. #if defined(USE_LUA)
  1293. {"lua_preload_file", CONFIG_TYPE_FILE, NULL},
  1294. {"lua_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1295. {"lua_server_page_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1296. #endif
  1297. #if defined(USE_DUKTAPE)
  1298. /* The support for duktape is still in alpha version state.
  1299. * The name of this config option might change. */
  1300. {"duktape_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1301. #endif
  1302. #if defined(USE_WEBSOCKET)
  1303. {"websocket_root", CONFIG_TYPE_DIRECTORY, NULL},
  1304. #endif
  1305. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1306. {"lua_websocket_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1307. #endif
  1308. {"access_control_allow_origin", CONFIG_TYPE_STRING, "*"},
  1309. {"error_pages", CONFIG_TYPE_DIRECTORY, NULL},
  1310. {"tcp_nodelay", CONFIG_TYPE_NUMBER, "0"},
  1311. #if !defined(NO_CACHING)
  1312. {"static_file_max_age", CONFIG_TYPE_NUMBER, "3600"},
  1313. #endif
  1314. #if defined(__linux__)
  1315. {"allow_sendfile_call", CONFIG_TYPE_BOOLEAN, "yes"},
  1316. #endif
  1317. #if defined(_WIN32)
  1318. {"case_sensitive", CONFIG_TYPE_BOOLEAN, "no"},
  1319. #endif
  1320. {NULL, CONFIG_TYPE_UNKNOWN, NULL}};
  1321. /* Check if the config_options and the corresponding enum have compatible
  1322. * sizes. */
  1323. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1324. == (NUM_OPTIONS + 1),
  1325. "config_options and enum not sync");
  1326. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1327. struct mg_handler_info {
  1328. /* Name/Pattern of the URI. */
  1329. char *uri;
  1330. size_t uri_len;
  1331. /* handler type */
  1332. int handler_type;
  1333. /* Handler for http/https or authorization requests. */
  1334. mg_request_handler handler;
  1335. /* Handler for ws/wss (websocket) requests. */
  1336. mg_websocket_connect_handler connect_handler;
  1337. mg_websocket_ready_handler ready_handler;
  1338. mg_websocket_data_handler data_handler;
  1339. mg_websocket_close_handler close_handler;
  1340. /* accepted subprotocols for ws/wss requests. */
  1341. struct mg_websocket_subprotocols *subprotocols;
  1342. /* Handler for authorization requests */
  1343. mg_authorization_handler auth_handler;
  1344. /* User supplied argument for the handler function. */
  1345. void *cbdata;
  1346. /* next handler in a linked list */
  1347. struct mg_handler_info *next;
  1348. };
  1349. struct mg_context {
  1350. volatile int stop_flag; /* Should we stop event loop */
  1351. SSL_CTX *ssl_ctx; /* SSL context */
  1352. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1353. struct mg_callbacks callbacks; /* User-defined callback function */
  1354. void *user_data; /* User-defined data */
  1355. int context_type; /* 1 = server context,
  1356. * 2 = ws/wss client context,
  1357. */
  1358. struct socket *listening_sockets;
  1359. struct pollfd *listening_socket_fds;
  1360. unsigned int num_listening_sockets;
  1361. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  1362. #ifdef ALTERNATIVE_QUEUE
  1363. struct socket *client_socks;
  1364. void **client_wait_events;
  1365. #else
  1366. struct socket queue[MGSQLEN]; /* Accepted sockets */
  1367. volatile int sq_head; /* Head of the socket queue */
  1368. volatile int sq_tail; /* Tail of the socket queue */
  1369. pthread_cond_t sq_full; /* Signaled when socket is produced */
  1370. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  1371. #endif
  1372. pthread_t masterthreadid; /* The master thread ID */
  1373. unsigned int
  1374. cfg_worker_threads; /* The number of configured worker threads. */
  1375. pthread_t *workerthreadids; /* The worker thread IDs */
  1376. time_t start_time; /* Server start time, used for authentication */
  1377. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1378. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  1379. unsigned long nonce_count; /* Used nonces, used for authentication */
  1380. char *systemName; /* What operating system is running */
  1381. /* linked list of uri handlers */
  1382. struct mg_handler_info *handlers;
  1383. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1384. /* linked list of shared lua websockets */
  1385. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1386. #endif
  1387. #ifdef USE_TIMERS
  1388. struct ttimers *timers;
  1389. #endif
  1390. };
  1391. struct mg_connection {
  1392. struct mg_request_info request_info;
  1393. struct mg_context *ctx;
  1394. SSL *ssl; /* SSL descriptor */
  1395. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  1396. struct socket client; /* Connected client */
  1397. time_t conn_birth_time; /* Time (wall clock) when connection was
  1398. * established */
  1399. struct timespec req_time; /* Time (since system start) when the request
  1400. * was received */
  1401. int64_t num_bytes_sent; /* Total bytes sent to client */
  1402. int64_t content_len; /* Content-Length header value */
  1403. int64_t consumed_content; /* How many bytes of content have been read */
  1404. int is_chunked; /* Transfer-Encoding is chunked: 0=no, 1=yes:
  1405. * data available, 2: all data read */
  1406. size_t chunk_remainder; /* Unread data from the last chunk */
  1407. char *buf; /* Buffer for received data */
  1408. char *path_info; /* PATH_INFO part of the URL */
  1409. int must_close; /* 1 if connection must be closed */
  1410. int in_error_handler; /* 1 if in handler for user defined error
  1411. * pages */
  1412. int handled_requests; /* Number of requests handled by this connection */
  1413. int buf_size; /* Buffer size */
  1414. int request_len; /* Size of the request + headers in a buffer */
  1415. int data_len; /* Total size of data in a buffer */
  1416. int status_code; /* HTTP reply status code, e.g. 200 */
  1417. int throttle; /* Throttling, bytes/sec. <= 0 means no
  1418. * throttle */
  1419. time_t last_throttle_time; /* Last time throttled data was sent */
  1420. int64_t last_throttle_bytes; /* Bytes sent this second */
  1421. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  1422. * atomic transmissions for websockets */
  1423. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1424. void *lua_websocket_state; /* Lua_State for a websocket connection */
  1425. #endif
  1426. int thread_index; /* Thread index within ctx */
  1427. };
  1428. static pthread_key_t sTlsKey; /* Thread local storage index */
  1429. static int sTlsInit = 0;
  1430. static int thread_idx_max = 0;
  1431. struct mg_workerTLS {
  1432. int is_master;
  1433. unsigned long thread_idx;
  1434. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1435. HANDLE pthread_cond_helper_mutex;
  1436. struct mg_workerTLS *next_waiting_thread;
  1437. #endif
  1438. };
  1439. /* Directory entry */
  1440. struct de {
  1441. struct mg_connection *conn;
  1442. char *file_name;
  1443. struct mg_file_stat file;
  1444. };
  1445. #if defined(USE_WEBSOCKET)
  1446. static int is_websocket_protocol(const struct mg_connection *conn);
  1447. #else
  1448. #define is_websocket_protocol(conn) (0)
  1449. #endif
  1450. static int
  1451. mg_atomic_inc(volatile int *addr)
  1452. {
  1453. int ret;
  1454. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1455. /* Depending on the SDK, this function uses either
  1456. * (volatile unsigned int *) or (volatile LONG *),
  1457. * so whatever you use, the other SDK is likely to raise a warning. */
  1458. ret = InterlockedIncrement((volatile long *)addr);
  1459. #elif defined(__GNUC__) \
  1460. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  1461. ret = __sync_add_and_fetch(addr, 1);
  1462. #else
  1463. ret = (++(*addr));
  1464. #endif
  1465. return ret;
  1466. }
  1467. static int
  1468. mg_atomic_dec(volatile int *addr)
  1469. {
  1470. int ret;
  1471. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1472. /* Depending on the SDK, this function uses either
  1473. * (volatile unsigned int *) or (volatile LONG *),
  1474. * so whatever you use, the other SDK is likely to raise a warning. */
  1475. ret = InterlockedDecrement((volatile long *)addr);
  1476. #elif defined(__GNUC__) \
  1477. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  1478. ret = __sync_sub_and_fetch(addr, 1);
  1479. #else
  1480. ret = (--(*addr));
  1481. #endif
  1482. return ret;
  1483. }
  1484. #if !defined(NO_THREAD_NAME)
  1485. #if defined(_WIN32) && defined(_MSC_VER)
  1486. /* Set the thread name for debugging purposes in Visual Studio
  1487. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  1488. */
  1489. #pragma pack(push, 8)
  1490. typedef struct tagTHREADNAME_INFO {
  1491. DWORD dwType; /* Must be 0x1000. */
  1492. LPCSTR szName; /* Pointer to name (in user addr space). */
  1493. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  1494. DWORD dwFlags; /* Reserved for future use, must be zero. */
  1495. } THREADNAME_INFO;
  1496. #pragma pack(pop)
  1497. #elif defined(__linux__)
  1498. #include <sys/prctl.h>
  1499. #include <sys/sendfile.h>
  1500. #include <sys/eventfd.h>
  1501. #if defined(ALTERNATIVE_QUEUE)
  1502. static void *
  1503. event_create(void)
  1504. {
  1505. int ret = eventfd(0, EFD_CLOEXEC);
  1506. if (ret == -1) {
  1507. /* Linux uses -1 on error, Windows NULL. */
  1508. /* However, Linux does not return 0 on success either. */
  1509. return 0;
  1510. }
  1511. return (void *)ret;
  1512. }
  1513. static int
  1514. event_wait(void *eventhdl)
  1515. {
  1516. uint64_t u;
  1517. int s = (int)read((int)eventhdl, &u, sizeof(u));
  1518. if (s != sizeof(uint64_t)) {
  1519. /* error */
  1520. return 0;
  1521. }
  1522. (void)u; /* the value is not required */
  1523. return 1;
  1524. }
  1525. static int
  1526. event_signal(void *eventhdl)
  1527. {
  1528. uint64_t u = 1;
  1529. int s = (int)write((int)eventhdl, &u, sizeof(u));
  1530. if (s != sizeof(uint64_t)) {
  1531. /* error */
  1532. return 0;
  1533. }
  1534. return 1;
  1535. }
  1536. static void
  1537. event_destroy(void *eventhdl)
  1538. {
  1539. close((int)eventhdl);
  1540. }
  1541. #endif
  1542. #endif
  1543. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  1544. struct posix_event {
  1545. pthread_mutex_t mutex;
  1546. pthread_cond_t cond;
  1547. };
  1548. static void *
  1549. event_create(void)
  1550. {
  1551. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  1552. if (ret == 0) {
  1553. /* out of memory */
  1554. return 0;
  1555. }
  1556. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  1557. /* pthread mutex not available */
  1558. mg_free(ret);
  1559. return 0;
  1560. }
  1561. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  1562. /* pthread cond not available */
  1563. pthread_mutex_destroy(&(ret->mutex));
  1564. mg_free(ret);
  1565. return 0;
  1566. }
  1567. return (void *)ret;
  1568. }
  1569. static int
  1570. event_wait(void *eventhdl)
  1571. {
  1572. struct posix_event *ev = (struct posix_event *)eventhdl;
  1573. pthread_mutex_lock(&(ev->mutex));
  1574. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  1575. pthread_mutex_unlock(&(ev->mutex));
  1576. return 1;
  1577. }
  1578. static int
  1579. event_signal(void *eventhdl)
  1580. {
  1581. struct posix_event *ev = (struct posix_event *)eventhdl;
  1582. pthread_mutex_lock(&(ev->mutex));
  1583. pthread_cond_signal(&(ev->cond));
  1584. pthread_mutex_unlock(&(ev->mutex));
  1585. return 1;
  1586. }
  1587. static void
  1588. event_destroy(void *eventhdl)
  1589. {
  1590. struct posix_event *ev = (struct posix_event *)eventhdl;
  1591. pthread_cond_destroy(&(ev->cond));
  1592. pthread_mutex_destroy(&(ev->mutex));
  1593. mg_free(ev);
  1594. }
  1595. #endif
  1596. static void
  1597. mg_set_thread_name(const char *name)
  1598. {
  1599. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  1600. mg_snprintf(
  1601. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  1602. #if defined(_WIN32)
  1603. #if defined(_MSC_VER)
  1604. /* Windows and Visual Studio Compiler */
  1605. __try
  1606. {
  1607. THREADNAME_INFO info;
  1608. info.dwType = 0x1000;
  1609. info.szName = threadName;
  1610. info.dwThreadID = ~0U;
  1611. info.dwFlags = 0;
  1612. RaiseException(0x406D1388,
  1613. 0,
  1614. sizeof(info) / sizeof(ULONG_PTR),
  1615. (ULONG_PTR *)&info);
  1616. }
  1617. __except(EXCEPTION_EXECUTE_HANDLER)
  1618. {
  1619. }
  1620. #elif defined(__MINGW32__)
  1621. /* No option known to set thread name for MinGW */
  1622. #endif
  1623. #elif defined(__GLIBC__) \
  1624. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  1625. /* pthread_setname_np first appeared in glibc in version 2.12*/
  1626. (void)pthread_setname_np(pthread_self(), threadName);
  1627. #elif defined(__linux__)
  1628. /* on linux we can use the old prctl function */
  1629. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  1630. #endif
  1631. }
  1632. #else /* !defined(NO_THREAD_NAME) */
  1633. void
  1634. mg_set_thread_name(const char *threadName)
  1635. {
  1636. }
  1637. #endif
  1638. #if defined(MG_LEGACY_INTERFACE)
  1639. const char **
  1640. mg_get_valid_option_names(void)
  1641. {
  1642. /* This function is deprecated. Use mg_get_valid_options instead. */
  1643. static const char *
  1644. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  1645. int i;
  1646. for (i = 0; config_options[i].name != NULL; i++) {
  1647. data[i * 2] = config_options[i].name;
  1648. data[i * 2 + 1] = config_options[i].default_value;
  1649. }
  1650. return data;
  1651. }
  1652. #endif
  1653. const struct mg_option *
  1654. mg_get_valid_options(void)
  1655. {
  1656. return config_options;
  1657. }
  1658. /* If a file is in memory, set all "stat" members and the membuf pointer of
  1659. * output filep and return 1, otherwise return 0 and don't modify anything. */
  1660. static int
  1661. open_file_in_memory(const struct mg_connection *conn,
  1662. const char *path,
  1663. struct mg_file *filep)
  1664. {
  1665. size_t size = 0;
  1666. const char *buf = NULL;
  1667. if (!conn) {
  1668. return 0;
  1669. }
  1670. if (conn->ctx->callbacks.open_file) {
  1671. buf = conn->ctx->callbacks.open_file(conn, path, &size);
  1672. if (buf != NULL) {
  1673. if (filep == NULL) {
  1674. /* This is a file in memory, but we cannot store the properties
  1675. * now.
  1676. * Called from "is_file_in_memory" function. */
  1677. return 1;
  1678. }
  1679. /* NOTE: override filep->size only on success. Otherwise, it might
  1680. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  1681. filep->access.membuf = buf;
  1682. filep->access.fp = NULL;
  1683. /* Size was set by the callback */
  1684. filep->stat.size = size;
  1685. /* Assume the data may change during runtime by setting
  1686. * last_modified = now */
  1687. filep->stat.last_modified = time(NULL);
  1688. filep->stat.is_directory = 0;
  1689. filep->stat.is_gzipped = 0;
  1690. }
  1691. }
  1692. return (buf != NULL);
  1693. }
  1694. static int
  1695. is_file_in_memory(const struct mg_connection *conn, const char *path)
  1696. {
  1697. return open_file_in_memory(conn, path, NULL);
  1698. }
  1699. static int
  1700. is_file_opened(const struct mg_file_access *fileacc)
  1701. {
  1702. if (!fileacc) {
  1703. return 0;
  1704. }
  1705. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  1706. }
  1707. static int mg_stat(const struct mg_connection *conn,
  1708. const char *path,
  1709. struct mg_file_stat *filep);
  1710. #define MG_FOPEN_MODE_READ (1)
  1711. #define MG_FOPEN_MODE_WRITE (2)
  1712. #define MG_FOPEN_MODE_APPEND (4)
  1713. /* mg_fopen will open a file either in memory or on the disk.
  1714. * The input parameter path is a string in UTF-8 encoding.
  1715. * The input parameter mode is MG_FOPEN_MODE_*
  1716. * Either fp or membuf will be set in the output struct file.
  1717. * The function returns 1 on success, 0 on error. */
  1718. static int
  1719. mg_fopen(const struct mg_connection *conn,
  1720. const char *path,
  1721. int mode,
  1722. struct mg_file *filep)
  1723. {
  1724. int found;
  1725. if (!filep) {
  1726. return 0;
  1727. }
  1728. filep->access.fp = NULL;
  1729. filep->access.membuf = NULL;
  1730. if (!is_file_in_memory(conn, path)) {
  1731. /* filep is initialized in mg_stat: all fields with memset to,
  1732. * some fields like size and modification date with values */
  1733. found = mg_stat(conn, path, &(filep->stat));
  1734. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  1735. /* file does not exist and will not be created */
  1736. return 0;
  1737. }
  1738. #ifdef _WIN32
  1739. {
  1740. wchar_t wbuf[PATH_MAX];
  1741. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  1742. switch (mode) {
  1743. case MG_FOPEN_MODE_READ:
  1744. filep->access.fp = _wfopen(wbuf, L"rb");
  1745. break;
  1746. case MG_FOPEN_MODE_WRITE:
  1747. filep->access.fp = _wfopen(wbuf, L"wb");
  1748. break;
  1749. case MG_FOPEN_MODE_APPEND:
  1750. filep->access.fp = _wfopen(wbuf, L"ab");
  1751. break;
  1752. }
  1753. }
  1754. #else
  1755. /* Linux et al already use unicode. No need to convert. */
  1756. switch (mode) {
  1757. case MG_FOPEN_MODE_READ:
  1758. filep->access.fp = fopen(path, "r");
  1759. break;
  1760. case MG_FOPEN_MODE_WRITE:
  1761. filep->access.fp = fopen(path, "w");
  1762. break;
  1763. case MG_FOPEN_MODE_APPEND:
  1764. filep->access.fp = fopen(path, "a");
  1765. break;
  1766. }
  1767. #endif
  1768. if (!found) {
  1769. /* File did not exist before fopen was called.
  1770. * Maybe it has been created now. Get stat info
  1771. * like creation time now. */
  1772. found = mg_stat(conn, path, &(filep->stat));
  1773. (void)found;
  1774. }
  1775. /* file is on disk */
  1776. return (filep->access.fp != NULL);
  1777. } else {
  1778. if (open_file_in_memory(conn, path, filep)) {
  1779. /* file is in memory */
  1780. return (filep->access.membuf != NULL);
  1781. }
  1782. }
  1783. /* Open failed */
  1784. return 0;
  1785. }
  1786. /* return 0 on success, just like fclose */
  1787. static int
  1788. mg_fclose(struct mg_file_access *fileacc)
  1789. {
  1790. int ret = -1;
  1791. if (fileacc != NULL) {
  1792. if (fileacc->fp != NULL) {
  1793. ret = fclose(fileacc->fp);
  1794. } else if (fileacc->membuf != NULL) {
  1795. ret = 0;
  1796. }
  1797. /* reset all members of fileacc */
  1798. memset(fileacc, 0, sizeof(*fileacc));
  1799. }
  1800. return ret;
  1801. }
  1802. static void
  1803. mg_strlcpy(register char *dst, register const char *src, size_t n)
  1804. {
  1805. for (; *src != '\0' && n > 1; n--) {
  1806. *dst++ = *src++;
  1807. }
  1808. *dst = '\0';
  1809. }
  1810. static int
  1811. lowercase(const char *s)
  1812. {
  1813. return tolower(*(const unsigned char *)s);
  1814. }
  1815. int
  1816. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  1817. {
  1818. int diff = 0;
  1819. if (len > 0) {
  1820. do {
  1821. diff = lowercase(s1++) - lowercase(s2++);
  1822. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  1823. }
  1824. return diff;
  1825. }
  1826. int
  1827. mg_strcasecmp(const char *s1, const char *s2)
  1828. {
  1829. int diff;
  1830. do {
  1831. diff = lowercase(s1++) - lowercase(s2++);
  1832. } while (diff == 0 && s1[-1] != '\0');
  1833. return diff;
  1834. }
  1835. static char *
  1836. mg_strndup(const char *ptr, size_t len)
  1837. {
  1838. char *p;
  1839. if ((p = (char *)mg_malloc(len + 1)) != NULL) {
  1840. mg_strlcpy(p, ptr, len + 1);
  1841. }
  1842. return p;
  1843. }
  1844. static char *
  1845. mg_strdup(const char *str)
  1846. {
  1847. return mg_strndup(str, strlen(str));
  1848. }
  1849. static const char *
  1850. mg_strcasestr(const char *big_str, const char *small_str)
  1851. {
  1852. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  1853. if (big_len >= small_len) {
  1854. for (i = 0; i <= (big_len - small_len); i++) {
  1855. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  1856. return big_str + i;
  1857. }
  1858. }
  1859. }
  1860. return NULL;
  1861. }
  1862. /* Return null terminated string of given maximum length.
  1863. * Report errors if length is exceeded. */
  1864. static void
  1865. mg_vsnprintf(const struct mg_connection *conn,
  1866. int *truncated,
  1867. char *buf,
  1868. size_t buflen,
  1869. const char *fmt,
  1870. va_list ap)
  1871. {
  1872. int n, ok;
  1873. if (buflen == 0) {
  1874. return;
  1875. }
  1876. #ifdef __clang__
  1877. #pragma clang diagnostic push
  1878. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  1879. /* Using fmt as a non-literal is intended here, since it is mostly called
  1880. * indirectly by mg_snprintf */
  1881. #endif
  1882. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  1883. ok = (n >= 0) && ((size_t)n < buflen);
  1884. #ifdef __clang__
  1885. #pragma clang diagnostic pop
  1886. #endif
  1887. if (ok) {
  1888. if (truncated) {
  1889. *truncated = 0;
  1890. }
  1891. } else {
  1892. if (truncated) {
  1893. *truncated = 1;
  1894. }
  1895. mg_cry(conn,
  1896. "truncating vsnprintf buffer: [%.*s]",
  1897. (int)((buflen > 200) ? 200 : (buflen - 1)),
  1898. buf);
  1899. n = (int)buflen - 1;
  1900. }
  1901. buf[n] = '\0';
  1902. }
  1903. static void
  1904. mg_snprintf(const struct mg_connection *conn,
  1905. int *truncated,
  1906. char *buf,
  1907. size_t buflen,
  1908. const char *fmt,
  1909. ...)
  1910. {
  1911. va_list ap;
  1912. va_start(ap, fmt);
  1913. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  1914. va_end(ap);
  1915. }
  1916. static int
  1917. get_option_index(const char *name)
  1918. {
  1919. int i;
  1920. for (i = 0; config_options[i].name != NULL; i++) {
  1921. if (strcmp(config_options[i].name, name) == 0) {
  1922. return i;
  1923. }
  1924. }
  1925. return -1;
  1926. }
  1927. const char *
  1928. mg_get_option(const struct mg_context *ctx, const char *name)
  1929. {
  1930. int i;
  1931. if ((i = get_option_index(name)) == -1) {
  1932. return NULL;
  1933. } else if (!ctx || ctx->config[i] == NULL) {
  1934. return "";
  1935. } else {
  1936. return ctx->config[i];
  1937. }
  1938. }
  1939. struct mg_context *
  1940. mg_get_context(const struct mg_connection *conn)
  1941. {
  1942. return (conn == NULL) ? (struct mg_context *)NULL : (conn->ctx);
  1943. }
  1944. void *
  1945. mg_get_user_data(const struct mg_context *ctx)
  1946. {
  1947. return (ctx == NULL) ? NULL : ctx->user_data;
  1948. }
  1949. void
  1950. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  1951. {
  1952. if (conn != NULL) {
  1953. conn->request_info.conn_data = data;
  1954. }
  1955. }
  1956. void *
  1957. mg_get_user_connection_data(const struct mg_connection *conn)
  1958. {
  1959. if (conn != NULL) {
  1960. return conn->request_info.conn_data;
  1961. }
  1962. return NULL;
  1963. }
  1964. size_t
  1965. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  1966. {
  1967. size_t i;
  1968. if (!ctx) {
  1969. return 0;
  1970. }
  1971. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  1972. ssl[i] = ctx->listening_sockets[i].is_ssl;
  1973. ports[i] =
  1974. #if defined(USE_IPV6)
  1975. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  1976. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  1977. :
  1978. #endif
  1979. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  1980. }
  1981. return i;
  1982. }
  1983. int
  1984. mg_get_server_ports(const struct mg_context *ctx,
  1985. int size,
  1986. struct mg_server_ports *ports)
  1987. {
  1988. int i, cnt = 0;
  1989. if (size <= 0) {
  1990. return -1;
  1991. }
  1992. memset(ports, 0, sizeof(*ports) * (size_t)size);
  1993. if (!ctx) {
  1994. return -1;
  1995. }
  1996. if (!ctx->listening_sockets) {
  1997. return -1;
  1998. }
  1999. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  2000. ports[cnt].port =
  2001. #if defined(USE_IPV6)
  2002. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2003. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2004. :
  2005. #endif
  2006. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2007. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  2008. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  2009. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  2010. /* IPv4 */
  2011. ports[cnt].protocol = 1;
  2012. cnt++;
  2013. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  2014. /* IPv6 */
  2015. ports[cnt].protocol = 3;
  2016. cnt++;
  2017. }
  2018. }
  2019. return cnt;
  2020. }
  2021. static void
  2022. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  2023. {
  2024. buf[0] = '\0';
  2025. if (!usa) {
  2026. return;
  2027. }
  2028. if (usa->sa.sa_family == AF_INET) {
  2029. getnameinfo(&usa->sa,
  2030. sizeof(usa->sin),
  2031. buf,
  2032. (unsigned)len,
  2033. NULL,
  2034. 0,
  2035. NI_NUMERICHOST);
  2036. }
  2037. #if defined(USE_IPV6)
  2038. else if (usa->sa.sa_family == AF_INET6) {
  2039. getnameinfo(&usa->sa,
  2040. sizeof(usa->sin6),
  2041. buf,
  2042. (unsigned)len,
  2043. NULL,
  2044. 0,
  2045. NI_NUMERICHOST);
  2046. }
  2047. #endif
  2048. }
  2049. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  2050. * included in all responses other than 100, 101, 5xx. */
  2051. static void
  2052. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  2053. {
  2054. struct tm *tm;
  2055. tm = ((t != NULL) ? gmtime(t) : NULL);
  2056. if (tm != NULL) {
  2057. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  2058. } else {
  2059. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  2060. buf[buf_len - 1] = '\0';
  2061. }
  2062. }
  2063. /* difftime for struct timespec. Return value is in seconds. */
  2064. static double
  2065. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  2066. {
  2067. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  2068. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  2069. }
  2070. /* Print error message to the opened error log stream. */
  2071. void
  2072. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  2073. {
  2074. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  2075. va_list ap;
  2076. struct mg_file fi;
  2077. time_t timestamp;
  2078. va_start(ap, fmt);
  2079. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  2080. va_end(ap);
  2081. buf[sizeof(buf) - 1] = 0;
  2082. if (!conn) {
  2083. puts(buf);
  2084. return;
  2085. }
  2086. /* Do not lock when getting the callback value, here and below.
  2087. * I suppose this is fine, since function cannot disappear in the
  2088. * same way string option can. */
  2089. if ((conn->ctx->callbacks.log_message == NULL)
  2090. || (conn->ctx->callbacks.log_message(conn, buf) == 0)) {
  2091. if (conn->ctx->config[ERROR_LOG_FILE] != NULL) {
  2092. if (mg_fopen(conn,
  2093. conn->ctx->config[ERROR_LOG_FILE],
  2094. MG_FOPEN_MODE_APPEND,
  2095. &fi) == 0) {
  2096. fi.access.fp = NULL;
  2097. }
  2098. } else {
  2099. fi.access.fp = NULL;
  2100. }
  2101. if (fi.access.fp != NULL) {
  2102. flockfile(fi.access.fp);
  2103. timestamp = time(NULL);
  2104. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  2105. fprintf(fi.access.fp,
  2106. "[%010lu] [error] [client %s] ",
  2107. (unsigned long)timestamp,
  2108. src_addr);
  2109. if (conn->request_info.request_method != NULL) {
  2110. fprintf(fi.access.fp,
  2111. "%s %s: ",
  2112. conn->request_info.request_method,
  2113. conn->request_info.request_uri);
  2114. }
  2115. fprintf(fi.access.fp, "%s", buf);
  2116. fputc('\n', fi.access.fp);
  2117. fflush(fi.access.fp);
  2118. funlockfile(fi.access.fp);
  2119. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  2120. * mg_cry here anyway ;-) */
  2121. }
  2122. }
  2123. }
  2124. /* Return fake connection structure. Used for logging, if connection
  2125. * is not applicable at the moment of logging. */
  2126. static struct mg_connection *
  2127. fc(struct mg_context *ctx)
  2128. {
  2129. static struct mg_connection fake_connection;
  2130. fake_connection.ctx = ctx;
  2131. return &fake_connection;
  2132. }
  2133. const char *
  2134. mg_version(void)
  2135. {
  2136. return CIVETWEB_VERSION;
  2137. }
  2138. const struct mg_request_info *
  2139. mg_get_request_info(const struct mg_connection *conn)
  2140. {
  2141. if (!conn) {
  2142. return NULL;
  2143. }
  2144. return &conn->request_info;
  2145. }
  2146. /* Skip the characters until one of the delimiters characters found.
  2147. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  2148. * Advance pointer to buffer to the next word. Return found 0-terminated word.
  2149. * Delimiters can be quoted with quotechar. */
  2150. static char *
  2151. skip_quoted(char **buf,
  2152. const char *delimiters,
  2153. const char *whitespace,
  2154. char quotechar)
  2155. {
  2156. char *p, *begin_word, *end_word, *end_whitespace;
  2157. begin_word = *buf;
  2158. end_word = begin_word + strcspn(begin_word, delimiters);
  2159. /* Check for quotechar */
  2160. if (end_word > begin_word) {
  2161. p = end_word - 1;
  2162. while (*p == quotechar) {
  2163. /* While the delimiter is quoted, look for the next delimiter. */
  2164. /* This happens, e.g., in calls from parse_auth_header,
  2165. * if the user name contains a " character. */
  2166. /* If there is anything beyond end_word, copy it. */
  2167. if (*end_word != '\0') {
  2168. size_t end_off = strcspn(end_word + 1, delimiters);
  2169. memmove(p, end_word, end_off + 1);
  2170. p += end_off; /* p must correspond to end_word - 1 */
  2171. end_word += end_off + 1;
  2172. } else {
  2173. *p = '\0';
  2174. break;
  2175. }
  2176. }
  2177. for (p++; p < end_word; p++) {
  2178. *p = '\0';
  2179. }
  2180. }
  2181. if (*end_word == '\0') {
  2182. *buf = end_word;
  2183. } else {
  2184. #if defined(__GNUC__) || defined(__MINGW32__)
  2185. /* Disable spurious conversion warning for GCC */
  2186. #pragma GCC diagnostic push
  2187. #pragma GCC diagnostic ignored "-Wsign-conversion"
  2188. #endif
  2189. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  2190. #if defined(__GNUC__) || defined(__MINGW32__)
  2191. #pragma GCC diagnostic pop
  2192. #endif
  2193. for (p = end_word; p < end_whitespace; p++) {
  2194. *p = '\0';
  2195. }
  2196. *buf = end_whitespace;
  2197. }
  2198. return begin_word;
  2199. }
  2200. /* Simplified version of skip_quoted without quote char
  2201. * and whitespace == delimiters */
  2202. static char *
  2203. skip(char **buf, const char *delimiters)
  2204. {
  2205. return skip_quoted(buf, delimiters, delimiters, 0);
  2206. }
  2207. /* Return HTTP header value, or NULL if not found. */
  2208. static const char *
  2209. get_header(const struct mg_request_info *ri, const char *name)
  2210. {
  2211. int i;
  2212. if (ri) {
  2213. for (i = 0; i < ri->num_headers; i++) {
  2214. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  2215. return ri->http_headers[i].value;
  2216. }
  2217. }
  2218. }
  2219. return NULL;
  2220. }
  2221. const char *
  2222. mg_get_header(const struct mg_connection *conn, const char *name)
  2223. {
  2224. if (!conn) {
  2225. return NULL;
  2226. }
  2227. return get_header(&conn->request_info, name);
  2228. }
  2229. /* A helper function for traversing a comma separated list of values.
  2230. * It returns a list pointer shifted to the next value, or NULL if the end
  2231. * of the list found.
  2232. * Value is stored in val vector. If value has form "x=y", then eq_val
  2233. * vector is initialized to point to the "y" part, and val vector length
  2234. * is adjusted to point only to "x". */
  2235. static const char *
  2236. next_option(const char *list, struct vec *val, struct vec *eq_val)
  2237. {
  2238. int end;
  2239. reparse:
  2240. if (val == NULL || list == NULL || *list == '\0') {
  2241. /* End of the list */
  2242. list = NULL;
  2243. } else {
  2244. /* Skip over leading LWS */
  2245. while (*list == ' ' || *list == '\t')
  2246. list++;
  2247. val->ptr = list;
  2248. if ((list = strchr(val->ptr, ',')) != NULL) {
  2249. /* Comma found. Store length and shift the list ptr */
  2250. val->len = ((size_t)(list - val->ptr));
  2251. list++;
  2252. } else {
  2253. /* This value is the last one */
  2254. list = val->ptr + strlen(val->ptr);
  2255. val->len = ((size_t)(list - val->ptr));
  2256. }
  2257. /* Adjust length for trailing LWS */
  2258. end = (int)val->len - 1;
  2259. while (end >= 0 && (val->ptr[end] == ' ' || val->ptr[end] == '\t'))
  2260. end--;
  2261. val->len = (size_t)(end + 1);
  2262. if (val->len == 0) {
  2263. /* Ignore any empty entries. */
  2264. goto reparse;
  2265. }
  2266. if (eq_val != NULL) {
  2267. /* Value has form "x=y", adjust pointers and lengths
  2268. * so that val points to "x", and eq_val points to "y". */
  2269. eq_val->len = 0;
  2270. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  2271. if (eq_val->ptr != NULL) {
  2272. eq_val->ptr++; /* Skip over '=' character */
  2273. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  2274. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  2275. }
  2276. }
  2277. }
  2278. return list;
  2279. }
  2280. /* A helper function for checking if a comma separated list of values contains
  2281. * the given option (case insensitvely).
  2282. * 'header' can be NULL, in which case false is returned. */
  2283. static int
  2284. header_has_option(const char *header, const char *option)
  2285. {
  2286. struct vec opt_vec;
  2287. struct vec eq_vec;
  2288. assert(option != NULL);
  2289. assert(option[0] != '\0');
  2290. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  2291. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  2292. return 1;
  2293. }
  2294. return 0;
  2295. }
  2296. /* Perform case-insensitive match of string against pattern */
  2297. static int
  2298. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  2299. {
  2300. const char *or_str;
  2301. size_t i;
  2302. int j, len, res;
  2303. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  2304. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  2305. return (res > 0) ? res : match_prefix(or_str + 1,
  2306. (size_t)((pattern + pattern_len)
  2307. - (or_str + 1)),
  2308. str);
  2309. }
  2310. for (i = 0, j = 0; i < pattern_len; i++, j++) {
  2311. if (pattern[i] == '?' && str[j] != '\0') {
  2312. continue;
  2313. } else if (pattern[i] == '$') {
  2314. return (str[j] == '\0') ? j : -1;
  2315. } else if (pattern[i] == '*') {
  2316. i++;
  2317. if (pattern[i] == '*') {
  2318. i++;
  2319. len = (int)strlen(str + j);
  2320. } else {
  2321. len = (int)strcspn(str + j, "/");
  2322. }
  2323. if (i == pattern_len) {
  2324. return j + len;
  2325. }
  2326. do {
  2327. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  2328. } while (res == -1 && len-- > 0);
  2329. return (res == -1) ? -1 : j + res + len;
  2330. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  2331. return -1;
  2332. }
  2333. }
  2334. return j;
  2335. }
  2336. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  2337. * This function must tolerate situations when connection info is not
  2338. * set up, for example if request parsing failed. */
  2339. static int
  2340. should_keep_alive(const struct mg_connection *conn)
  2341. {
  2342. if (conn != NULL) {
  2343. const char *http_version = conn->request_info.http_version;
  2344. const char *header = mg_get_header(conn, "Connection");
  2345. if (conn->must_close || conn->status_code == 401
  2346. || mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0
  2347. || (header != NULL && !header_has_option(header, "keep-alive"))
  2348. || (header == NULL && http_version
  2349. && 0 != strcmp(http_version, "1.1"))) {
  2350. return 0;
  2351. }
  2352. return 1;
  2353. }
  2354. return 0;
  2355. }
  2356. static int
  2357. should_decode_url(const struct mg_connection *conn)
  2358. {
  2359. if (!conn || !conn->ctx) {
  2360. return 0;
  2361. }
  2362. return (mg_strcasecmp(conn->ctx->config[DECODE_URL], "yes") == 0);
  2363. }
  2364. static const char *
  2365. suggest_connection_header(const struct mg_connection *conn)
  2366. {
  2367. return should_keep_alive(conn) ? "keep-alive" : "close";
  2368. }
  2369. static int
  2370. send_no_cache_header(struct mg_connection *conn)
  2371. {
  2372. /* Send all current and obsolete cache opt-out directives. */
  2373. return mg_printf(conn,
  2374. "Cache-Control: no-cache, no-store, "
  2375. "must-revalidate, private, max-age=0\r\n"
  2376. "Pragma: no-cache\r\n"
  2377. "Expires: 0\r\n");
  2378. }
  2379. static int
  2380. send_static_cache_header(struct mg_connection *conn)
  2381. {
  2382. #if !defined(NO_CACHING)
  2383. /* Read the server config to check how long a file may be cached.
  2384. * The configuration is in seconds. */
  2385. int max_age = atoi(conn->ctx->config[STATIC_FILE_MAX_AGE]);
  2386. if (max_age <= 0) {
  2387. /* 0 means "do not cache". All values <0 are reserved
  2388. * and may be used differently in the future. */
  2389. /* If a file should not be cached, do not only send
  2390. * max-age=0, but also pragmas and Expires headers. */
  2391. return send_no_cache_header(conn);
  2392. }
  2393. /* Use "Cache-Control: max-age" instead of "Expires" header.
  2394. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  2395. /* See also https://www.mnot.net/cache_docs/ */
  2396. /* According to RFC 2616, Section 14.21, caching times should not exceed
  2397. * one year. A year with 365 days corresponds to 31536000 seconds, a leap
  2398. * year to 31622400 seconds. For the moment, we just send whatever has
  2399. * been configured, still the behavior for >1 year should be considered
  2400. * as undefined. */
  2401. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  2402. #else /* NO_CACHING */
  2403. return send_no_cache_header(conn);
  2404. #endif /* !NO_CACHING */
  2405. }
  2406. static void handle_file_based_request(struct mg_connection *conn,
  2407. const char *path,
  2408. struct mg_file *filep);
  2409. const char *
  2410. mg_get_response_code_text(struct mg_connection *conn, int response_code)
  2411. {
  2412. /* See IANA HTTP status code assignment:
  2413. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  2414. */
  2415. switch (response_code) {
  2416. /* RFC2616 Section 10.1 - Informational 1xx */
  2417. case 100:
  2418. return "Continue"; /* RFC2616 Section 10.1.1 */
  2419. case 101:
  2420. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  2421. case 102:
  2422. return "Processing"; /* RFC2518 Section 10.1 */
  2423. /* RFC2616 Section 10.2 - Successful 2xx */
  2424. case 200:
  2425. return "OK"; /* RFC2616 Section 10.2.1 */
  2426. case 201:
  2427. return "Created"; /* RFC2616 Section 10.2.2 */
  2428. case 202:
  2429. return "Accepted"; /* RFC2616 Section 10.2.3 */
  2430. case 203:
  2431. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  2432. case 204:
  2433. return "No Content"; /* RFC2616 Section 10.2.5 */
  2434. case 205:
  2435. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  2436. case 206:
  2437. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  2438. case 207:
  2439. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1 */
  2440. case 208:
  2441. return "Already Reported"; /* RFC5842 Section 7.1 */
  2442. case 226:
  2443. return "IM used"; /* RFC3229 Section 10.4.1 */
  2444. /* RFC2616 Section 10.3 - Redirection 3xx */
  2445. case 300:
  2446. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  2447. case 301:
  2448. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  2449. case 302:
  2450. return "Found"; /* RFC2616 Section 10.3.3 */
  2451. case 303:
  2452. return "See Other"; /* RFC2616 Section 10.3.4 */
  2453. case 304:
  2454. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  2455. case 305:
  2456. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  2457. case 307:
  2458. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  2459. case 308:
  2460. return "Permanent Redirect"; /* RFC7238 Section 3 */
  2461. /* RFC2616 Section 10.4 - Client Error 4xx */
  2462. case 400:
  2463. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  2464. case 401:
  2465. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  2466. case 402:
  2467. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  2468. case 403:
  2469. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  2470. case 404:
  2471. return "Not Found"; /* RFC2616 Section 10.4.5 */
  2472. case 405:
  2473. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  2474. case 406:
  2475. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  2476. case 407:
  2477. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  2478. case 408:
  2479. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  2480. case 409:
  2481. return "Conflict"; /* RFC2616 Section 10.4.10 */
  2482. case 410:
  2483. return "Gone"; /* RFC2616 Section 10.4.11 */
  2484. case 411:
  2485. return "Length Required"; /* RFC2616 Section 10.4.12 */
  2486. case 412:
  2487. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  2488. case 413:
  2489. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  2490. case 414:
  2491. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  2492. case 415:
  2493. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  2494. case 416:
  2495. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17 */
  2496. case 417:
  2497. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  2498. case 421:
  2499. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  2500. case 422:
  2501. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  2502. * Section 11.2 */
  2503. case 423:
  2504. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  2505. case 424:
  2506. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  2507. * Section 11.4 */
  2508. case 426:
  2509. return "Upgrade Required"; /* RFC 2817 Section 4 */
  2510. case 428:
  2511. return "Precondition Required"; /* RFC 6585, Section 3 */
  2512. case 429:
  2513. return "Too Many Requests"; /* RFC 6585, Section 4 */
  2514. case 431:
  2515. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  2516. case 451:
  2517. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  2518. * Section 3 */
  2519. /* RFC2616 Section 10.5 - Server Error 5xx */
  2520. case 500:
  2521. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  2522. case 501:
  2523. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  2524. case 502:
  2525. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  2526. case 503:
  2527. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  2528. case 504:
  2529. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  2530. case 505:
  2531. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  2532. case 506:
  2533. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  2534. case 507:
  2535. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  2536. * Section 11.5 */
  2537. case 508:
  2538. return "Loop Detected"; /* RFC5842 Section 7.1 */
  2539. case 510:
  2540. return "Not Extended"; /* RFC 2774, Section 7 */
  2541. case 511:
  2542. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  2543. /* Other status codes, not shown in the IANA HTTP status code assignment.
  2544. * E.g., "de facto" standards due to common use, ... */
  2545. case 418:
  2546. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  2547. case 419:
  2548. return "Authentication Timeout"; /* common use */
  2549. case 420:
  2550. return "Enhance Your Calm"; /* common use */
  2551. case 440:
  2552. return "Login Timeout"; /* common use */
  2553. case 509:
  2554. return "Bandwidth Limit Exceeded"; /* common use */
  2555. default:
  2556. /* This error code is unknown. This should not happen. */
  2557. if (conn) {
  2558. mg_cry(conn, "Unknown HTTP response code: %u", response_code);
  2559. }
  2560. /* Return at least a category according to RFC 2616 Section 10. */
  2561. if (response_code >= 100 && response_code < 200) {
  2562. /* Unknown informational status code */
  2563. return "Information";
  2564. }
  2565. if (response_code >= 200 && response_code < 300) {
  2566. /* Unknown success code */
  2567. return "Success";
  2568. }
  2569. if (response_code >= 300 && response_code < 400) {
  2570. /* Unknown redirection code */
  2571. return "Redirection";
  2572. }
  2573. if (response_code >= 400 && response_code < 500) {
  2574. /* Unknown request error code */
  2575. return "Client Error";
  2576. }
  2577. if (response_code >= 500 && response_code < 600) {
  2578. /* Unknown server error code */
  2579. return "Server Error";
  2580. }
  2581. /* Response code not even within reasonable range */
  2582. return "";
  2583. }
  2584. }
  2585. static void send_http_error(struct mg_connection *,
  2586. int,
  2587. PRINTF_FORMAT_STRING(const char *fmt),
  2588. ...) PRINTF_ARGS(3, 4);
  2589. static void
  2590. send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  2591. {
  2592. char buf[MG_BUF_LEN];
  2593. va_list ap;
  2594. int len, i, page_handler_found, scope, truncated, has_body;
  2595. char date[64];
  2596. time_t curtime = time(NULL);
  2597. const char *error_handler = NULL;
  2598. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  2599. const char *error_page_file_ext, *tstr;
  2600. const char *status_text = mg_get_response_code_text(conn, status);
  2601. if (conn == NULL) {
  2602. return;
  2603. }
  2604. conn->status_code = status;
  2605. if (conn->in_error_handler || conn->ctx->callbacks.http_error == NULL
  2606. || conn->ctx->callbacks.http_error(conn, status)) {
  2607. if (!conn->in_error_handler) {
  2608. /* Send user defined error pages, if defined */
  2609. error_handler = conn->ctx->config[ERROR_PAGES];
  2610. error_page_file_ext = conn->ctx->config[INDEX_FILES];
  2611. page_handler_found = 0;
  2612. if (error_handler != NULL) {
  2613. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  2614. switch (scope) {
  2615. case 1: /* Handler for specific error, e.g. 404 error */
  2616. mg_snprintf(conn,
  2617. &truncated,
  2618. buf,
  2619. sizeof(buf) - 32,
  2620. "%serror%03u.",
  2621. error_handler,
  2622. status);
  2623. break;
  2624. case 2: /* Handler for error group, e.g., 5xx error handler
  2625. * for all server errors (500-599) */
  2626. mg_snprintf(conn,
  2627. &truncated,
  2628. buf,
  2629. sizeof(buf) - 32,
  2630. "%serror%01uxx.",
  2631. error_handler,
  2632. status / 100);
  2633. break;
  2634. default: /* Handler for all errors */
  2635. mg_snprintf(conn,
  2636. &truncated,
  2637. buf,
  2638. sizeof(buf) - 32,
  2639. "%serror.",
  2640. error_handler);
  2641. break;
  2642. }
  2643. /* String truncation in buf may only occur if error_handler
  2644. * is too long. This string is from the config, not from a
  2645. * client. */
  2646. (void)truncated;
  2647. len = (int)strlen(buf);
  2648. tstr = strchr(error_page_file_ext, '.');
  2649. while (tstr) {
  2650. for (i = 1; i < 32 && tstr[i] != 0 && tstr[i] != ',';
  2651. i++)
  2652. buf[len + i - 1] = tstr[i];
  2653. buf[len + i - 1] = 0;
  2654. if (mg_stat(conn, buf, &error_page_file.stat)) {
  2655. page_handler_found = 1;
  2656. break;
  2657. }
  2658. tstr = strchr(tstr + i, '.');
  2659. }
  2660. }
  2661. }
  2662. if (page_handler_found) {
  2663. conn->in_error_handler = 1;
  2664. handle_file_based_request(conn, buf, &error_page_file);
  2665. conn->in_error_handler = 0;
  2666. return;
  2667. }
  2668. }
  2669. /* No custom error page. Send default error page. */
  2670. gmt_time_string(date, sizeof(date), &curtime);
  2671. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  2672. has_body = (status > 199 && status != 204 && status != 304);
  2673. conn->must_close = 1;
  2674. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  2675. send_no_cache_header(conn);
  2676. if (has_body) {
  2677. mg_printf(conn,
  2678. "%s",
  2679. "Content-Type: text/plain; charset=utf-8\r\n");
  2680. }
  2681. mg_printf(conn,
  2682. "Date: %s\r\n"
  2683. "Connection: close\r\n\r\n",
  2684. date);
  2685. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  2686. if (has_body) {
  2687. mg_printf(conn, "Error %d: %s\n", status, status_text);
  2688. if (fmt != NULL) {
  2689. va_start(ap, fmt);
  2690. mg_vsnprintf(conn, NULL, buf, sizeof(buf), fmt, ap);
  2691. va_end(ap);
  2692. mg_write(conn, buf, strlen(buf));
  2693. DEBUG_TRACE("Error %i - [%s]", status, buf);
  2694. }
  2695. } else {
  2696. /* No body allowed. Close the connection. */
  2697. DEBUG_TRACE("Error %i", status);
  2698. }
  2699. }
  2700. }
  2701. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  2702. /* Create substitutes for POSIX functions in Win32. */
  2703. #if defined(__MINGW32__)
  2704. /* Show no warning in case system functions are not used. */
  2705. #pragma GCC diagnostic push
  2706. #pragma GCC diagnostic ignored "-Wunused-function"
  2707. #endif
  2708. static int
  2709. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  2710. {
  2711. (void)unused;
  2712. *mutex = CreateMutex(NULL, FALSE, NULL);
  2713. return (*mutex == NULL) ? -1 : 0;
  2714. }
  2715. static int
  2716. pthread_mutex_destroy(pthread_mutex_t *mutex)
  2717. {
  2718. return (CloseHandle(*mutex) == 0) ? -1 : 0;
  2719. }
  2720. static int
  2721. pthread_mutex_lock(pthread_mutex_t *mutex)
  2722. {
  2723. return (WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0) ? 0 : -1;
  2724. }
  2725. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  2726. static int
  2727. pthread_mutex_trylock(pthread_mutex_t *mutex)
  2728. {
  2729. switch (WaitForSingleObject(*mutex, 0)) {
  2730. case WAIT_OBJECT_0:
  2731. return 0;
  2732. case WAIT_TIMEOUT:
  2733. return -2; /* EBUSY */
  2734. }
  2735. return -1;
  2736. }
  2737. #endif
  2738. static int
  2739. pthread_mutex_unlock(pthread_mutex_t *mutex)
  2740. {
  2741. return (ReleaseMutex(*mutex) == 0) ? -1 : 0;
  2742. }
  2743. static int
  2744. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  2745. {
  2746. (void)unused;
  2747. InitializeCriticalSection(&cv->threadIdSec);
  2748. cv->waiting_thread = NULL;
  2749. return 0;
  2750. }
  2751. static int
  2752. pthread_cond_timedwait(pthread_cond_t *cv,
  2753. pthread_mutex_t *mutex,
  2754. const struct timespec *abstime)
  2755. {
  2756. struct mg_workerTLS **ptls,
  2757. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2758. int ok;
  2759. struct timespec tsnow;
  2760. int64_t nsnow, nswaitabs, nswaitrel;
  2761. DWORD mswaitrel;
  2762. EnterCriticalSection(&cv->threadIdSec);
  2763. /* Add this thread to cv's waiting list */
  2764. ptls = &cv->waiting_thread;
  2765. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  2766. ;
  2767. tls->next_waiting_thread = NULL;
  2768. *ptls = tls;
  2769. LeaveCriticalSection(&cv->threadIdSec);
  2770. if (abstime) {
  2771. clock_gettime(CLOCK_REALTIME, &tsnow);
  2772. nsnow = (((int64_t)tsnow.tv_sec) * 1000000000) + tsnow.tv_nsec;
  2773. nswaitabs =
  2774. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  2775. nswaitrel = nswaitabs - nsnow;
  2776. if (nswaitrel < 0) {
  2777. nswaitrel = 0;
  2778. }
  2779. mswaitrel = (DWORD)(nswaitrel / 1000000);
  2780. } else {
  2781. mswaitrel = INFINITE;
  2782. }
  2783. pthread_mutex_unlock(mutex);
  2784. ok = (WAIT_OBJECT_0
  2785. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  2786. if (!ok) {
  2787. ok = 1;
  2788. EnterCriticalSection(&cv->threadIdSec);
  2789. ptls = &cv->waiting_thread;
  2790. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  2791. if (*ptls == tls) {
  2792. *ptls = tls->next_waiting_thread;
  2793. ok = 0;
  2794. break;
  2795. }
  2796. }
  2797. LeaveCriticalSection(&cv->threadIdSec);
  2798. if (ok) {
  2799. WaitForSingleObject(tls->pthread_cond_helper_mutex, INFINITE);
  2800. }
  2801. }
  2802. /* This thread has been removed from cv's waiting list */
  2803. pthread_mutex_lock(mutex);
  2804. return ok ? 0 : -1;
  2805. }
  2806. static int
  2807. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  2808. {
  2809. return pthread_cond_timedwait(cv, mutex, NULL);
  2810. }
  2811. static int
  2812. pthread_cond_signal(pthread_cond_t *cv)
  2813. {
  2814. HANDLE wkup = NULL;
  2815. BOOL ok = FALSE;
  2816. EnterCriticalSection(&cv->threadIdSec);
  2817. if (cv->waiting_thread) {
  2818. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  2819. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  2820. ok = SetEvent(wkup);
  2821. assert(ok);
  2822. }
  2823. LeaveCriticalSection(&cv->threadIdSec);
  2824. return ok ? 0 : 1;
  2825. }
  2826. static int
  2827. pthread_cond_broadcast(pthread_cond_t *cv)
  2828. {
  2829. EnterCriticalSection(&cv->threadIdSec);
  2830. while (cv->waiting_thread) {
  2831. pthread_cond_signal(cv);
  2832. }
  2833. LeaveCriticalSection(&cv->threadIdSec);
  2834. return 0;
  2835. }
  2836. static int
  2837. pthread_cond_destroy(pthread_cond_t *cv)
  2838. {
  2839. EnterCriticalSection(&cv->threadIdSec);
  2840. assert(cv->waiting_thread == NULL);
  2841. LeaveCriticalSection(&cv->threadIdSec);
  2842. DeleteCriticalSection(&cv->threadIdSec);
  2843. return 0;
  2844. }
  2845. #ifdef ALTERNATIVE_QUEUE
  2846. static void *
  2847. event_create(void)
  2848. {
  2849. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  2850. }
  2851. static int
  2852. event_wait(void *eventhdl)
  2853. {
  2854. int res = WaitForSingleObject((HANDLE)eventhdl, INFINITE);
  2855. return (res == WAIT_OBJECT_0);
  2856. }
  2857. static int
  2858. event_signal(void *eventhdl)
  2859. {
  2860. return (int)SetEvent((HANDLE)eventhdl);
  2861. }
  2862. static void
  2863. event_destroy(void *eventhdl)
  2864. {
  2865. CloseHandle((HANDLE)eventhdl);
  2866. }
  2867. #endif
  2868. #if defined(__MINGW32__)
  2869. /* Enable unused function warning again */
  2870. #pragma GCC diagnostic pop
  2871. #endif
  2872. /* For Windows, change all slashes to backslashes in path names. */
  2873. static void
  2874. change_slashes_to_backslashes(char *path)
  2875. {
  2876. int i;
  2877. for (i = 0; path[i] != '\0'; i++) {
  2878. if (path[i] == '/') {
  2879. path[i] = '\\';
  2880. }
  2881. /* remove double backslash (check i > 0 to preserve UNC paths,
  2882. * like \\server\file.txt) */
  2883. if ((path[i] == '\\') && (i > 0)) {
  2884. while (path[i + 1] == '\\' || path[i + 1] == '/') {
  2885. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  2886. }
  2887. }
  2888. }
  2889. }
  2890. static int
  2891. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  2892. {
  2893. int diff;
  2894. do {
  2895. diff = tolower(*s1) - tolower(*s2);
  2896. s1++;
  2897. s2++;
  2898. } while (diff == 0 && s1[-1] != '\0');
  2899. return diff;
  2900. }
  2901. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  2902. * wbuf and wbuf_len is a target buffer and its length. */
  2903. static void
  2904. path_to_unicode(const struct mg_connection *conn,
  2905. const char *path,
  2906. wchar_t *wbuf,
  2907. size_t wbuf_len)
  2908. {
  2909. char buf[PATH_MAX], buf2[PATH_MAX];
  2910. wchar_t wbuf2[MAX_PATH + 1];
  2911. DWORD long_len, err;
  2912. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  2913. mg_strlcpy(buf, path, sizeof(buf));
  2914. change_slashes_to_backslashes(buf);
  2915. /* Convert to Unicode and back. If doubly-converted string does not
  2916. * match the original, something is fishy, reject. */
  2917. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  2918. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  2919. WideCharToMultiByte(
  2920. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  2921. if (strcmp(buf, buf2) != 0) {
  2922. wbuf[0] = L'\0';
  2923. }
  2924. /* Windows file systems are not case sensitive, but you can still use
  2925. * uppercase and lowercase letters (on all modern file systems).
  2926. * The server can check if the URI uses the same upper/lowercase
  2927. * letters an the file system, effectively making Windows servers
  2928. * case sensitive (like Linux servers are). It is still not possible
  2929. * to use two files with the same name in different cases on Windows
  2930. * (like /a and /A) - this would be possible in Linux.
  2931. * As a default, Windows is not case sensitive, but the case sensitive
  2932. * file name check can be activated by an additional configuration. */
  2933. if (conn) {
  2934. if (conn->ctx->config[CASE_SENSITIVE_FILES]
  2935. && !mg_strcasecmp(conn->ctx->config[CASE_SENSITIVE_FILES], "yes")) {
  2936. /* Use case sensitive compare function */
  2937. fcompare = wcscmp;
  2938. }
  2939. }
  2940. (void)conn; /* conn is currently unused */
  2941. #if !defined(_WIN32_WCE)
  2942. /* Only accept a full file path, not a Windows short (8.3) path. */
  2943. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  2944. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  2945. if (long_len == 0) {
  2946. err = GetLastError();
  2947. if (err == ERROR_FILE_NOT_FOUND) {
  2948. /* File does not exist. This is not always a problem here. */
  2949. return;
  2950. }
  2951. }
  2952. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  2953. /* Short name is used. */
  2954. wbuf[0] = L'\0';
  2955. }
  2956. #else
  2957. (void)long_len;
  2958. (void)wbuf2;
  2959. (void)err;
  2960. if (strchr(path, '~')) {
  2961. wbuf[0] = L'\0';
  2962. }
  2963. #endif
  2964. }
  2965. /* Windows happily opens files with some garbage at the end of file name.
  2966. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  2967. * "a.cgi", despite one would expect an error back.
  2968. * This function returns non-0 if path ends with some garbage. */
  2969. static int
  2970. path_cannot_disclose_cgi(const char *path)
  2971. {
  2972. static const char *allowed_last_characters = "_-";
  2973. int last = path[strlen(path) - 1];
  2974. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  2975. }
  2976. static int
  2977. mg_stat(const struct mg_connection *conn,
  2978. const char *path,
  2979. struct mg_file_stat *filep)
  2980. {
  2981. wchar_t wbuf[PATH_MAX];
  2982. WIN32_FILE_ATTRIBUTE_DATA info;
  2983. time_t creation_time;
  2984. if (!filep) {
  2985. return 0;
  2986. }
  2987. memset(filep, 0, sizeof(*filep));
  2988. if (conn && is_file_in_memory(conn, path)) {
  2989. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  2990. * memset */
  2991. filep->last_modified = time(NULL); /* xxxxxxxx */
  2992. /* last_modified = now ... assumes the file may change during runtime,
  2993. * so every mg_fopen call may return different data */
  2994. /* last_modified = conn->ctx.start_time;
  2995. * May be used it the data does not change during runtime. This allows
  2996. * browser caching. Since we do not know, we have to assume the file
  2997. * in memory may change. */
  2998. return 1;
  2999. }
  3000. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3001. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  3002. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  3003. filep->last_modified =
  3004. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  3005. info.ftLastWriteTime.dwHighDateTime);
  3006. /* On Windows, the file creation time can be higher than the
  3007. * modification time, e.g. when a file is copied.
  3008. * Since the Last-Modified timestamp is used for caching
  3009. * it should be based on the most recent timestamp. */
  3010. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  3011. info.ftCreationTime.dwHighDateTime);
  3012. if (creation_time > filep->last_modified) {
  3013. filep->last_modified = creation_time;
  3014. }
  3015. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  3016. /* If file name is fishy, reset the file structure and return
  3017. * error.
  3018. * Note it is important to reset, not just return the error, cause
  3019. * functions like is_file_opened() check the struct. */
  3020. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  3021. memset(filep, 0, sizeof(*filep));
  3022. return 0;
  3023. }
  3024. return 1;
  3025. }
  3026. return 0;
  3027. }
  3028. static int
  3029. mg_remove(const struct mg_connection *conn, const char *path)
  3030. {
  3031. wchar_t wbuf[PATH_MAX];
  3032. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3033. return DeleteFileW(wbuf) ? 0 : -1;
  3034. }
  3035. static int
  3036. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  3037. {
  3038. wchar_t wbuf[PATH_MAX];
  3039. (void)mode;
  3040. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3041. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  3042. }
  3043. /* Create substitutes for POSIX functions in Win32. */
  3044. #if defined(__MINGW32__)
  3045. /* Show no warning in case system functions are not used. */
  3046. #pragma GCC diagnostic push
  3047. #pragma GCC diagnostic ignored "-Wunused-function"
  3048. #endif
  3049. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  3050. static DIR *
  3051. mg_opendir(const struct mg_connection *conn, const char *name)
  3052. {
  3053. DIR *dir = NULL;
  3054. wchar_t wpath[PATH_MAX];
  3055. DWORD attrs;
  3056. if (name == NULL) {
  3057. SetLastError(ERROR_BAD_ARGUMENTS);
  3058. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  3059. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  3060. } else {
  3061. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  3062. attrs = GetFileAttributesW(wpath);
  3063. if (attrs != 0xFFFFFFFF && ((attrs & FILE_ATTRIBUTE_DIRECTORY)
  3064. == FILE_ATTRIBUTE_DIRECTORY)) {
  3065. (void)wcscat(wpath, L"\\*");
  3066. dir->handle = FindFirstFileW(wpath, &dir->info);
  3067. dir->result.d_name[0] = '\0';
  3068. } else {
  3069. mg_free(dir);
  3070. dir = NULL;
  3071. }
  3072. }
  3073. return dir;
  3074. }
  3075. static int
  3076. mg_closedir(DIR *dir)
  3077. {
  3078. int result = 0;
  3079. if (dir != NULL) {
  3080. if (dir->handle != INVALID_HANDLE_VALUE)
  3081. result = FindClose(dir->handle) ? 0 : -1;
  3082. mg_free(dir);
  3083. } else {
  3084. result = -1;
  3085. SetLastError(ERROR_BAD_ARGUMENTS);
  3086. }
  3087. return result;
  3088. }
  3089. static struct dirent *
  3090. mg_readdir(DIR *dir)
  3091. {
  3092. struct dirent *result = 0;
  3093. if (dir) {
  3094. if (dir->handle != INVALID_HANDLE_VALUE) {
  3095. result = &dir->result;
  3096. (void)WideCharToMultiByte(CP_UTF8,
  3097. 0,
  3098. dir->info.cFileName,
  3099. -1,
  3100. result->d_name,
  3101. sizeof(result->d_name),
  3102. NULL,
  3103. NULL);
  3104. if (!FindNextFileW(dir->handle, &dir->info)) {
  3105. (void)FindClose(dir->handle);
  3106. dir->handle = INVALID_HANDLE_VALUE;
  3107. }
  3108. } else {
  3109. SetLastError(ERROR_FILE_NOT_FOUND);
  3110. }
  3111. } else {
  3112. SetLastError(ERROR_BAD_ARGUMENTS);
  3113. }
  3114. return result;
  3115. }
  3116. #ifndef HAVE_POLL
  3117. static int
  3118. poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  3119. {
  3120. struct timeval tv;
  3121. fd_set set;
  3122. unsigned int i;
  3123. int result;
  3124. SOCKET maxfd = 0;
  3125. memset(&tv, 0, sizeof(tv));
  3126. tv.tv_sec = milliseconds / 1000;
  3127. tv.tv_usec = (milliseconds % 1000) * 1000;
  3128. FD_ZERO(&set);
  3129. for (i = 0; i < n; i++) {
  3130. FD_SET((SOCKET)pfd[i].fd, &set);
  3131. pfd[i].revents = 0;
  3132. if (pfd[i].fd > maxfd) {
  3133. maxfd = pfd[i].fd;
  3134. }
  3135. }
  3136. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  3137. for (i = 0; i < n; i++) {
  3138. if (FD_ISSET(pfd[i].fd, &set)) {
  3139. pfd[i].revents = POLLIN;
  3140. }
  3141. }
  3142. }
  3143. /* We should subtract the time used in select from remaining
  3144. * "milliseconds", in particular if called from mg_poll with a
  3145. * timeout quantum.
  3146. * Unfortunately, the remaining time is not stored in "tv" in all
  3147. * implementations, so the result in "tv" must be considered undefined.
  3148. * See http://man7.org/linux/man-pages/man2/select.2.html */
  3149. return result;
  3150. }
  3151. #endif /* HAVE_POLL */
  3152. #if defined(__MINGW32__)
  3153. /* Enable unused function warning again */
  3154. #pragma GCC diagnostic pop
  3155. #endif
  3156. static void
  3157. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  3158. {
  3159. (void)conn; /* Unused. */
  3160. #if defined(_WIN32_WCE)
  3161. (void)sock;
  3162. #else
  3163. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  3164. #endif
  3165. }
  3166. int
  3167. mg_start_thread(mg_thread_func_t f, void *p)
  3168. {
  3169. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3170. /* Compile-time option to control stack size, e.g. -DUSE_STACK_SIZE=16384
  3171. */
  3172. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  3173. == ((uintptr_t)(-1L)))
  3174. ? -1
  3175. : 0);
  3176. #else
  3177. return (
  3178. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  3179. ? -1
  3180. : 0);
  3181. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3182. }
  3183. /* Start a thread storing the thread context. */
  3184. static int
  3185. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  3186. void *p,
  3187. pthread_t *threadidptr)
  3188. {
  3189. uintptr_t uip;
  3190. HANDLE threadhandle;
  3191. int result = -1;
  3192. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  3193. threadhandle = (HANDLE)uip;
  3194. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  3195. *threadidptr = threadhandle;
  3196. result = 0;
  3197. }
  3198. return result;
  3199. }
  3200. /* Wait for a thread to finish. */
  3201. static int
  3202. mg_join_thread(pthread_t threadid)
  3203. {
  3204. int result;
  3205. DWORD dwevent;
  3206. result = -1;
  3207. dwevent = WaitForSingleObject(threadid, INFINITE);
  3208. if (dwevent == WAIT_FAILED) {
  3209. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  3210. } else {
  3211. if (dwevent == WAIT_OBJECT_0) {
  3212. CloseHandle(threadid);
  3213. result = 0;
  3214. }
  3215. }
  3216. return result;
  3217. }
  3218. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  3219. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  3220. /* Create substitutes for POSIX functions in Win32. */
  3221. #if defined(__MINGW32__)
  3222. /* Show no warning in case system functions are not used. */
  3223. #pragma GCC diagnostic push
  3224. #pragma GCC diagnostic ignored "-Wunused-function"
  3225. #endif
  3226. static HANDLE
  3227. dlopen(const char *dll_name, int flags)
  3228. {
  3229. wchar_t wbuf[PATH_MAX];
  3230. (void)flags;
  3231. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  3232. return LoadLibraryW(wbuf);
  3233. }
  3234. static int
  3235. dlclose(void *handle)
  3236. {
  3237. int result;
  3238. if (FreeLibrary((HMODULE)handle) != 0) {
  3239. result = 0;
  3240. } else {
  3241. result = -1;
  3242. }
  3243. return result;
  3244. }
  3245. #if defined(__MINGW32__)
  3246. /* Enable unused function warning again */
  3247. #pragma GCC diagnostic pop
  3248. #endif
  3249. #endif
  3250. #if !defined(NO_CGI)
  3251. #define SIGKILL (0)
  3252. static int
  3253. kill(pid_t pid, int sig_num)
  3254. {
  3255. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  3256. (void)CloseHandle((HANDLE)pid);
  3257. return 0;
  3258. }
  3259. static void
  3260. trim_trailing_whitespaces(char *s)
  3261. {
  3262. char *e = s + strlen(s) - 1;
  3263. while (e > s && isspace(*(unsigned char *)e)) {
  3264. *e-- = '\0';
  3265. }
  3266. }
  3267. static pid_t
  3268. spawn_process(struct mg_connection *conn,
  3269. const char *prog,
  3270. char *envblk,
  3271. char *envp[],
  3272. int fdin[2],
  3273. int fdout[2],
  3274. int fderr[2],
  3275. const char *dir)
  3276. {
  3277. HANDLE me;
  3278. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  3279. cmdline[PATH_MAX], buf[PATH_MAX];
  3280. int truncated;
  3281. struct mg_file file = STRUCT_FILE_INITIALIZER;
  3282. STARTUPINFOA si;
  3283. PROCESS_INFORMATION pi = {0};
  3284. (void)envp;
  3285. memset(&si, 0, sizeof(si));
  3286. si.cb = sizeof(si);
  3287. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  3288. si.wShowWindow = SW_HIDE;
  3289. me = GetCurrentProcess();
  3290. DuplicateHandle(me,
  3291. (HANDLE)_get_osfhandle(fdin[0]),
  3292. me,
  3293. &si.hStdInput,
  3294. 0,
  3295. TRUE,
  3296. DUPLICATE_SAME_ACCESS);
  3297. DuplicateHandle(me,
  3298. (HANDLE)_get_osfhandle(fdout[1]),
  3299. me,
  3300. &si.hStdOutput,
  3301. 0,
  3302. TRUE,
  3303. DUPLICATE_SAME_ACCESS);
  3304. DuplicateHandle(me,
  3305. (HANDLE)_get_osfhandle(fderr[1]),
  3306. me,
  3307. &si.hStdError,
  3308. 0,
  3309. TRUE,
  3310. DUPLICATE_SAME_ACCESS);
  3311. /* Mark handles that should not be inherited. See
  3312. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  3313. */
  3314. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  3315. HANDLE_FLAG_INHERIT,
  3316. 0);
  3317. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  3318. HANDLE_FLAG_INHERIT,
  3319. 0);
  3320. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  3321. HANDLE_FLAG_INHERIT,
  3322. 0);
  3323. /* If CGI file is a script, try to read the interpreter line */
  3324. interp = conn->ctx->config[CGI_INTERPRETER];
  3325. if (interp == NULL) {
  3326. buf[0] = buf[1] = '\0';
  3327. /* Read the first line of the script into the buffer */
  3328. mg_snprintf(
  3329. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  3330. if (truncated) {
  3331. pi.hProcess = (pid_t)-1;
  3332. goto spawn_cleanup;
  3333. }
  3334. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  3335. p = (char *)file.access.membuf;
  3336. mg_fgets(buf, sizeof(buf), &file, &p);
  3337. (void)mg_fclose(&file.access); /* ignore error on read only file */
  3338. buf[sizeof(buf) - 1] = '\0';
  3339. }
  3340. if (buf[0] == '#' && buf[1] == '!') {
  3341. trim_trailing_whitespaces(buf + 2);
  3342. } else {
  3343. buf[2] = '\0';
  3344. }
  3345. interp = buf + 2;
  3346. }
  3347. if (interp[0] != '\0') {
  3348. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  3349. interp = full_interp;
  3350. }
  3351. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  3352. if (interp[0] != '\0') {
  3353. mg_snprintf(conn,
  3354. &truncated,
  3355. cmdline,
  3356. sizeof(cmdline),
  3357. "\"%s\" \"%s\\%s\"",
  3358. interp,
  3359. full_dir,
  3360. prog);
  3361. } else {
  3362. mg_snprintf(conn,
  3363. &truncated,
  3364. cmdline,
  3365. sizeof(cmdline),
  3366. "\"%s\\%s\"",
  3367. full_dir,
  3368. prog);
  3369. }
  3370. if (truncated) {
  3371. pi.hProcess = (pid_t)-1;
  3372. goto spawn_cleanup;
  3373. }
  3374. DEBUG_TRACE("Running [%s]", cmdline);
  3375. if (CreateProcessA(NULL,
  3376. cmdline,
  3377. NULL,
  3378. NULL,
  3379. TRUE,
  3380. CREATE_NEW_PROCESS_GROUP,
  3381. envblk,
  3382. NULL,
  3383. &si,
  3384. &pi) == 0) {
  3385. mg_cry(
  3386. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  3387. pi.hProcess = (pid_t)-1;
  3388. /* goto spawn_cleanup; */
  3389. }
  3390. spawn_cleanup:
  3391. (void)CloseHandle(si.hStdOutput);
  3392. (void)CloseHandle(si.hStdError);
  3393. (void)CloseHandle(si.hStdInput);
  3394. if (pi.hThread != NULL) {
  3395. (void)CloseHandle(pi.hThread);
  3396. }
  3397. return (pid_t)pi.hProcess;
  3398. }
  3399. #endif /* !NO_CGI */
  3400. static int
  3401. set_blocking_mode(SOCKET sock, int blocking)
  3402. {
  3403. unsigned long non_blocking = !blocking;
  3404. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  3405. }
  3406. #else
  3407. static int
  3408. mg_stat(const struct mg_connection *conn,
  3409. const char *path,
  3410. struct mg_file_stat *filep)
  3411. {
  3412. struct stat st;
  3413. if (!filep) {
  3414. return 0;
  3415. }
  3416. memset(filep, 0, sizeof(*filep));
  3417. if (conn && is_file_in_memory(conn, path)) {
  3418. return 1;
  3419. }
  3420. if (0 == stat(path, &st)) {
  3421. filep->size = (uint64_t)(st.st_size);
  3422. filep->last_modified = st.st_mtime;
  3423. filep->is_directory = S_ISDIR(st.st_mode);
  3424. return 1;
  3425. }
  3426. return 0;
  3427. }
  3428. static void
  3429. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  3430. {
  3431. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  3432. if (conn) {
  3433. mg_cry(conn,
  3434. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  3435. __func__,
  3436. strerror(ERRNO));
  3437. }
  3438. }
  3439. }
  3440. int
  3441. mg_start_thread(mg_thread_func_t func, void *param)
  3442. {
  3443. pthread_t thread_id;
  3444. pthread_attr_t attr;
  3445. int result;
  3446. (void)pthread_attr_init(&attr);
  3447. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  3448. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3449. /* Compile-time option to control stack size,
  3450. * e.g. -DUSE_STACK_SIZE=16384 */
  3451. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3452. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3453. result = pthread_create(&thread_id, &attr, func, param);
  3454. pthread_attr_destroy(&attr);
  3455. return result;
  3456. }
  3457. /* Start a thread storing the thread context. */
  3458. static int
  3459. mg_start_thread_with_id(mg_thread_func_t func,
  3460. void *param,
  3461. pthread_t *threadidptr)
  3462. {
  3463. pthread_t thread_id;
  3464. pthread_attr_t attr;
  3465. int result;
  3466. (void)pthread_attr_init(&attr);
  3467. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3468. /* Compile-time option to control stack size,
  3469. * e.g. -DUSE_STACK_SIZE=16384 */
  3470. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3471. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  3472. result = pthread_create(&thread_id, &attr, func, param);
  3473. pthread_attr_destroy(&attr);
  3474. if ((result == 0) && (threadidptr != NULL)) {
  3475. *threadidptr = thread_id;
  3476. }
  3477. return result;
  3478. }
  3479. /* Wait for a thread to finish. */
  3480. static int
  3481. mg_join_thread(pthread_t threadid)
  3482. {
  3483. int result;
  3484. result = pthread_join(threadid, NULL);
  3485. return result;
  3486. }
  3487. #ifndef NO_CGI
  3488. static pid_t
  3489. spawn_process(struct mg_connection *conn,
  3490. const char *prog,
  3491. char *envblk,
  3492. char *envp[],
  3493. int fdin[2],
  3494. int fdout[2],
  3495. int fderr[2],
  3496. const char *dir)
  3497. {
  3498. pid_t pid;
  3499. const char *interp;
  3500. (void)envblk;
  3501. if (conn == NULL) {
  3502. return 0;
  3503. }
  3504. if ((pid = fork()) == -1) {
  3505. /* Parent */
  3506. send_http_error(conn,
  3507. 500,
  3508. "Error: Creating CGI process\nfork(): %s",
  3509. strerror(ERRNO));
  3510. } else if (pid == 0) {
  3511. /* Child */
  3512. if (chdir(dir) != 0) {
  3513. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  3514. } else if (dup2(fdin[0], 0) == -1) {
  3515. mg_cry(conn,
  3516. "%s: dup2(%d, 0): %s",
  3517. __func__,
  3518. fdin[0],
  3519. strerror(ERRNO));
  3520. } else if (dup2(fdout[1], 1) == -1) {
  3521. mg_cry(conn,
  3522. "%s: dup2(%d, 1): %s",
  3523. __func__,
  3524. fdout[1],
  3525. strerror(ERRNO));
  3526. } else if (dup2(fderr[1], 2) == -1) {
  3527. mg_cry(conn,
  3528. "%s: dup2(%d, 2): %s",
  3529. __func__,
  3530. fderr[1],
  3531. strerror(ERRNO));
  3532. } else {
  3533. /* Keep stderr and stdout in two different pipes.
  3534. * Stdout will be sent back to the client,
  3535. * stderr should go into a server error log. */
  3536. (void)close(fdin[0]);
  3537. (void)close(fdout[1]);
  3538. (void)close(fderr[1]);
  3539. /* Close write end fdin and read end fdout and fderr */
  3540. (void)close(fdin[1]);
  3541. (void)close(fdout[0]);
  3542. (void)close(fderr[0]);
  3543. /* After exec, all signal handlers are restored to their default
  3544. * values, with one exception of SIGCHLD. According to
  3545. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler will
  3546. * leave unchanged after exec if it was set to be ignored. Restore
  3547. * it to default action. */
  3548. signal(SIGCHLD, SIG_DFL);
  3549. interp = conn->ctx->config[CGI_INTERPRETER];
  3550. if (interp == NULL) {
  3551. (void)execle(prog, prog, NULL, envp);
  3552. mg_cry(conn,
  3553. "%s: execle(%s): %s",
  3554. __func__,
  3555. prog,
  3556. strerror(ERRNO));
  3557. } else {
  3558. (void)execle(interp, interp, prog, NULL, envp);
  3559. mg_cry(conn,
  3560. "%s: execle(%s %s): %s",
  3561. __func__,
  3562. interp,
  3563. prog,
  3564. strerror(ERRNO));
  3565. }
  3566. }
  3567. exit(EXIT_FAILURE);
  3568. }
  3569. return pid;
  3570. }
  3571. #endif /* !NO_CGI */
  3572. static int
  3573. set_blocking_mode(SOCKET sock, int blocking)
  3574. {
  3575. int flags;
  3576. flags = fcntl(sock, F_GETFL, 0);
  3577. if (blocking) {
  3578. (void)fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  3579. } else {
  3580. (void)fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK)));
  3581. }
  3582. return 0;
  3583. }
  3584. #endif /* _WIN32 */
  3585. /* End of initial operating system specific define block. */
  3586. /* Get a random number (independent of C rand function) */
  3587. static uint64_t
  3588. get_random(void)
  3589. {
  3590. static uint64_t lfsr = 0; /* Linear feedback shift register */
  3591. static uint64_t lcg = 0; /* Linear congruential generator */
  3592. struct timespec now;
  3593. memset(&now, 0, sizeof(now));
  3594. clock_gettime(CLOCK_MONOTONIC, &now);
  3595. if (lfsr == 0) {
  3596. /* lfsr will be only 0 if has not been initialized,
  3597. * so this code is called only once. */
  3598. lfsr = (((uint64_t)now.tv_sec) << 21) ^ ((uint64_t)now.tv_nsec)
  3599. ^ ((uint64_t)(ptrdiff_t)&now) ^ (((uint64_t)time(NULL)) << 33);
  3600. lcg = (((uint64_t)now.tv_sec) << 25) + (uint64_t)now.tv_nsec
  3601. + (uint64_t)(ptrdiff_t)&now;
  3602. } else {
  3603. /* Get the next step of both random number generators. */
  3604. lfsr = (lfsr >> 1)
  3605. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  3606. << 63);
  3607. lcg = lcg * 6364136223846793005 + 1442695040888963407;
  3608. }
  3609. /* Combining two pseudo-random number generators and a high resolution part
  3610. * of the current server time will make it hard (impossible?) to guess the
  3611. * next number. */
  3612. return (lfsr ^ lcg ^ (uint64_t)now.tv_nsec);
  3613. }
  3614. static int
  3615. mg_poll(struct pollfd *pfd,
  3616. unsigned int n,
  3617. int milliseconds,
  3618. volatile int *stop_server)
  3619. {
  3620. int ms_now, result;
  3621. /* Call poll, but only for a maximum time of a few seconds.
  3622. * This will allow to stop the server after some seconds, instead
  3623. * of having to wait for a long socket timeout. */
  3624. ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  3625. do {
  3626. if (*stop_server) {
  3627. /* Shut down signal */
  3628. return -2;
  3629. }
  3630. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  3631. ms_now = milliseconds;
  3632. }
  3633. result = poll(pfd, n, ms_now);
  3634. if (result != 0) {
  3635. /* Poll returned either success (1) or error (-1).
  3636. * Forward both to the caller. */
  3637. return result;
  3638. }
  3639. /* Poll returned timeout (0). */
  3640. if (milliseconds > 0) {
  3641. milliseconds -= ms_now;
  3642. }
  3643. } while (milliseconds != 0);
  3644. return result;
  3645. }
  3646. /* Write data to the IO channel - opened file descriptor, socket or SSL
  3647. * descriptor. Return number of bytes written. */
  3648. static int
  3649. push(struct mg_context *ctx,
  3650. FILE *fp,
  3651. SOCKET sock,
  3652. SSL *ssl,
  3653. const char *buf,
  3654. int len,
  3655. double timeout)
  3656. {
  3657. struct timespec start, now;
  3658. int n, err;
  3659. #ifdef _WIN32
  3660. typedef int len_t;
  3661. #else
  3662. typedef size_t len_t;
  3663. #endif
  3664. if (timeout > 0) {
  3665. memset(&start, 0, sizeof(start));
  3666. memset(&now, 0, sizeof(now));
  3667. clock_gettime(CLOCK_MONOTONIC, &start);
  3668. }
  3669. if (ctx == NULL) {
  3670. return -1;
  3671. }
  3672. #ifdef NO_SSL
  3673. if (ssl) {
  3674. return -1;
  3675. }
  3676. #endif
  3677. do {
  3678. #ifndef NO_SSL
  3679. if (ssl != NULL) {
  3680. n = SSL_write(ssl, buf, len);
  3681. if (n <= 0) {
  3682. err = SSL_get_error(ssl, n);
  3683. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  3684. err = ERRNO;
  3685. } else if ((err == SSL_ERROR_WANT_READ)
  3686. || (err == SSL_ERROR_WANT_WRITE)) {
  3687. n = 0;
  3688. } else {
  3689. DEBUG_TRACE("SSL_write() failed, error %d", err);
  3690. return -1;
  3691. }
  3692. } else {
  3693. err = 0;
  3694. }
  3695. } else
  3696. #endif
  3697. if (fp != NULL) {
  3698. n = (int)fwrite(buf, 1, (size_t)len, fp);
  3699. if (ferror(fp)) {
  3700. n = -1;
  3701. err = ERRNO;
  3702. } else {
  3703. err = 0;
  3704. }
  3705. } else {
  3706. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  3707. err = (n < 0) ? ERRNO : 0;
  3708. if (n <= 0) {
  3709. /* shutdown of the socket at client side */
  3710. return -1;
  3711. }
  3712. #if defined(TEMPORARY_INSTRUMENTATION)
  3713. {
  3714. FILE *f = fopen("r:\\all.txt", "ab");
  3715. fprintf(f, "\r\n%010u SEND:\r\n", GetTickCount());
  3716. fwrite(buf, 1, n, f);
  3717. fclose(f);
  3718. }
  3719. #endif
  3720. }
  3721. if (ctx->stop_flag) {
  3722. return -1;
  3723. }
  3724. if ((n > 0) || (n == 0 && len == 0)) {
  3725. /* some data has been read, or no data was requested */
  3726. return n;
  3727. }
  3728. if (n < 0) {
  3729. /* socket error - check errno */
  3730. DEBUG_TRACE("send() failed, error %d", err);
  3731. /* TODO: error handling depending on the error code.
  3732. * These codes are different between Windows and Linux.
  3733. */
  3734. return -1;
  3735. }
  3736. /* Only in case n=0 (timeout), repeat calling the write function */
  3737. if (timeout > 0) {
  3738. clock_gettime(CLOCK_MONOTONIC, &now);
  3739. }
  3740. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  3741. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  3742. used */
  3743. return -1;
  3744. }
  3745. static int64_t
  3746. push_all(struct mg_context *ctx,
  3747. FILE *fp,
  3748. SOCKET sock,
  3749. SSL *ssl,
  3750. const char *buf,
  3751. int64_t len)
  3752. {
  3753. double timeout = -1.0;
  3754. int64_t n, nwritten = 0;
  3755. if (ctx == NULL) {
  3756. return -1;
  3757. }
  3758. if (ctx->config[REQUEST_TIMEOUT]) {
  3759. timeout = atoi(ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  3760. }
  3761. while (len > 0 && ctx->stop_flag == 0) {
  3762. n = push(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  3763. if (n < 0) {
  3764. if (nwritten == 0) {
  3765. nwritten = n; /* Propagate the error */
  3766. }
  3767. break;
  3768. } else if (n == 0) {
  3769. break; /* No more data to write */
  3770. } else {
  3771. nwritten += n;
  3772. len -= n;
  3773. }
  3774. }
  3775. return nwritten;
  3776. }
  3777. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  3778. * Return negative value on error, or number of bytes read on success. */
  3779. static int
  3780. pull(FILE *fp, struct mg_connection *conn, char *buf, int len, double timeout)
  3781. {
  3782. int nread, err = 0;
  3783. #ifdef _WIN32
  3784. typedef int len_t;
  3785. #else
  3786. typedef size_t len_t;
  3787. #endif
  3788. if (fp != NULL) {
  3789. #if !defined(_WIN32_WCE)
  3790. /* Use read() instead of fread(), because if we're reading from the
  3791. * CGI pipe, fread() may block until IO buffer is filled up. We
  3792. * cannot afford to block and must pass all read bytes immediately
  3793. * to the client. */
  3794. nread = (int)read(fileno(fp), buf, (size_t)len);
  3795. #else
  3796. /* WinCE does not support CGI pipes */
  3797. nread = (int)fread(buf, 1, (size_t)len, fp);
  3798. #endif
  3799. err = (nread < 0) ? ERRNO : 0;
  3800. #ifndef NO_SSL
  3801. } else if (conn->ssl != NULL) {
  3802. struct pollfd pfd[1];
  3803. int pollres;
  3804. pfd[0].fd = conn->client.sock;
  3805. pfd[0].events = POLLIN;
  3806. pollres =
  3807. mg_poll(pfd, 1, (int)(timeout * 1000.0), &(conn->ctx->stop_flag));
  3808. if (conn->ctx->stop_flag) {
  3809. return -1;
  3810. }
  3811. if (pollres > 0) {
  3812. nread = SSL_read(conn->ssl, buf, len);
  3813. if (nread <= 0) {
  3814. err = SSL_get_error(conn->ssl, nread);
  3815. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  3816. err = ERRNO;
  3817. } else if ((err == SSL_ERROR_WANT_READ)
  3818. || (err == SSL_ERROR_WANT_WRITE)) {
  3819. nread = 0;
  3820. } else {
  3821. DEBUG_TRACE("SSL_read() failed, error %d", err);
  3822. return -1;
  3823. }
  3824. } else {
  3825. err = 0;
  3826. }
  3827. } else if (pollres < 0) {
  3828. /* Error */
  3829. return -1;
  3830. } else {
  3831. /* pollres = 0 means timeout */
  3832. nread = 0;
  3833. }
  3834. #endif
  3835. } else {
  3836. struct pollfd pfd[1];
  3837. int pollres;
  3838. pfd[0].fd = conn->client.sock;
  3839. pfd[0].events = POLLIN;
  3840. pollres =
  3841. mg_poll(pfd, 1, (int)(timeout * 1000.0), &(conn->ctx->stop_flag));
  3842. if (conn->ctx->stop_flag) {
  3843. return -1;
  3844. }
  3845. if (pollres > 0) {
  3846. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  3847. err = (nread < 0) ? ERRNO : 0;
  3848. if (nread <= 0) {
  3849. /* shutdown of the socket at client side */
  3850. return -1;
  3851. }
  3852. #if defined(TEMPORARY_INSTRUMENTATION)
  3853. {
  3854. FILE *f = fopen("r:\\all.txt", "ab");
  3855. fprintf(f, "\r\n%010u RECV:\r\n", GetTickCount());
  3856. fwrite(buf, 1, nread, f);
  3857. fclose(f);
  3858. }
  3859. #endif
  3860. } else if (pollres < 0) {
  3861. /* error callint poll */
  3862. return -1;
  3863. } else {
  3864. /* pollres = 0 means timeout */
  3865. nread = 0;
  3866. }
  3867. }
  3868. if (conn->ctx->stop_flag) {
  3869. return -1;
  3870. }
  3871. if ((nread > 0) || (nread == 0 && len == 0)) {
  3872. /* some data has been read, or no data was requested */
  3873. return nread;
  3874. }
  3875. if (nread < 0) {
  3876. /* socket error - check errno */
  3877. #ifdef _WIN32
  3878. if (err == WSAEWOULDBLOCK) {
  3879. /* TODO: check if this is still required */
  3880. /* standard case if called from close_socket_gracefully */
  3881. return -1;
  3882. } else if (err == WSAETIMEDOUT) {
  3883. /* TODO: check if this is still required */
  3884. /* timeout is handled by the while loop */
  3885. return 0;
  3886. } else if (err == WSAECONNABORTED) {
  3887. /* See https://www.chilkatsoft.com/p/p_299.asp */
  3888. return -1;
  3889. } else {
  3890. DEBUG_TRACE("recv() failed, error %d", err);
  3891. return -1;
  3892. }
  3893. #else
  3894. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  3895. * if the timeout is reached and if the socket was set to non-
  3896. * blocking in close_socket_gracefully, so we can not distinguish
  3897. * here. We have to wait for the timeout in both cases for now.
  3898. */
  3899. if (err == EAGAIN || err == EWOULDBLOCK || err == EINTR) {
  3900. /* TODO: check if this is still required */
  3901. /* EAGAIN/EWOULDBLOCK:
  3902. * standard case if called from close_socket_gracefully
  3903. * => should return -1 */
  3904. /* or timeout occured
  3905. * => the code must stay in the while loop */
  3906. /* EINTR can be generated on a socket with a timeout set even
  3907. * when SA_RESTART is effective for all relevant signals
  3908. * (see signal(7)).
  3909. * => stay in the while loop */
  3910. } else {
  3911. DEBUG_TRACE("recv() failed, error %d", err);
  3912. return -1;
  3913. }
  3914. #endif
  3915. }
  3916. /* Timeout occured, but no data available. */
  3917. return -1;
  3918. }
  3919. static int
  3920. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  3921. {
  3922. int n, nread = 0;
  3923. double timeout = -1.0;
  3924. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  3925. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  3926. }
  3927. while (len > 0 && conn->ctx->stop_flag == 0) {
  3928. n = pull(fp, conn, buf + nread, len, timeout);
  3929. if (n < 0) {
  3930. if (nread == 0) {
  3931. nread = n; /* Propagate the error */
  3932. }
  3933. break;
  3934. } else if (n == 0) {
  3935. break; /* No more data to read */
  3936. } else {
  3937. conn->consumed_content += n;
  3938. nread += n;
  3939. len -= n;
  3940. }
  3941. }
  3942. return nread;
  3943. }
  3944. static void
  3945. discard_unread_request_data(struct mg_connection *conn)
  3946. {
  3947. char buf[MG_BUF_LEN];
  3948. size_t to_read;
  3949. int nread;
  3950. if (conn == NULL) {
  3951. return;
  3952. }
  3953. to_read = sizeof(buf);
  3954. if (conn->is_chunked) {
  3955. /* Chunked encoding: 1=chunk not read completely, 2=chunk read
  3956. * completely */
  3957. while (conn->is_chunked == 1) {
  3958. nread = mg_read(conn, buf, to_read);
  3959. if (nread <= 0) {
  3960. break;
  3961. }
  3962. }
  3963. } else {
  3964. /* Not chunked: content length is known */
  3965. while (conn->consumed_content < conn->content_len) {
  3966. if (to_read
  3967. > (size_t)(conn->content_len - conn->consumed_content)) {
  3968. to_read = (size_t)(conn->content_len - conn->consumed_content);
  3969. }
  3970. nread = mg_read(conn, buf, to_read);
  3971. if (nread <= 0) {
  3972. break;
  3973. }
  3974. }
  3975. }
  3976. }
  3977. static int
  3978. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  3979. {
  3980. int64_t n, buffered_len, nread;
  3981. int64_t len64 =
  3982. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  3983. * int, we may not read more
  3984. * bytes */
  3985. const char *body;
  3986. if (conn == NULL) {
  3987. return 0;
  3988. }
  3989. /* If Content-Length is not set for a PUT or POST request, read until
  3990. * socket is closed */
  3991. if (conn->consumed_content == 0 && conn->content_len == -1) {
  3992. conn->content_len = INT64_MAX;
  3993. conn->must_close = 1;
  3994. }
  3995. nread = 0;
  3996. if (conn->consumed_content < conn->content_len) {
  3997. /* Adjust number of bytes to read. */
  3998. int64_t left_to_read = conn->content_len - conn->consumed_content;
  3999. if (left_to_read < len64) {
  4000. /* Do not read more than the total content length of the request.
  4001. */
  4002. len64 = left_to_read;
  4003. }
  4004. /* Return buffered data */
  4005. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  4006. - conn->consumed_content;
  4007. if (buffered_len > 0) {
  4008. if (len64 < buffered_len) {
  4009. buffered_len = len64;
  4010. }
  4011. body = conn->buf + conn->request_len + conn->consumed_content;
  4012. memcpy(buf, body, (size_t)buffered_len);
  4013. len64 -= buffered_len;
  4014. conn->consumed_content += buffered_len;
  4015. nread += buffered_len;
  4016. buf = (char *)buf + buffered_len;
  4017. }
  4018. /* We have returned all buffered data. Read new data from the remote
  4019. * socket.
  4020. */
  4021. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  4022. nread += n;
  4023. } else {
  4024. nread = ((nread > 0) ? nread : n);
  4025. }
  4026. }
  4027. return (int)nread;
  4028. }
  4029. static char
  4030. mg_getc(struct mg_connection *conn)
  4031. {
  4032. char c;
  4033. if (conn == NULL) {
  4034. return 0;
  4035. }
  4036. conn->content_len++;
  4037. if (mg_read_inner(conn, &c, 1) <= 0) {
  4038. return (char)0;
  4039. }
  4040. return c;
  4041. }
  4042. int
  4043. mg_read(struct mg_connection *conn, void *buf, size_t len)
  4044. {
  4045. if (len > INT_MAX) {
  4046. len = INT_MAX;
  4047. }
  4048. if (conn == NULL) {
  4049. return 0;
  4050. }
  4051. if (conn->is_chunked) {
  4052. size_t all_read = 0;
  4053. while (len > 0) {
  4054. if (conn->is_chunked == 2) {
  4055. /* No more data left to read */
  4056. return 0;
  4057. }
  4058. if (conn->chunk_remainder) {
  4059. /* copy from the remainder of the last received chunk */
  4060. long read_ret;
  4061. size_t read_now =
  4062. ((conn->chunk_remainder > len) ? (len)
  4063. : (conn->chunk_remainder));
  4064. conn->content_len += (int)read_now;
  4065. read_ret =
  4066. mg_read_inner(conn, (char *)buf + all_read, read_now);
  4067. if (read_ret < 1) {
  4068. /* read error */
  4069. return -1;
  4070. }
  4071. all_read += (size_t)read_ret;
  4072. conn->chunk_remainder -= (size_t)read_ret;
  4073. len -= (size_t)read_ret;
  4074. if (conn->chunk_remainder == 0) {
  4075. /* Add data bytes in the current chunk have been read,
  4076. * so we are expecting \r\n now. */
  4077. char x1 = mg_getc(conn);
  4078. char x2 = mg_getc(conn);
  4079. if ((x1 != '\r') || (x2 != '\n')) {
  4080. /* Protocol violation */
  4081. return -1;
  4082. }
  4083. }
  4084. } else {
  4085. /* fetch a new chunk */
  4086. int i = 0;
  4087. char lenbuf[64];
  4088. char *end = 0;
  4089. unsigned long chunkSize = 0;
  4090. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  4091. lenbuf[i] = mg_getc(conn);
  4092. if (i > 0 && lenbuf[i] == '\r' && lenbuf[i - 1] != '\r') {
  4093. continue;
  4094. }
  4095. if (i > 1 && lenbuf[i] == '\n' && lenbuf[i - 1] == '\r') {
  4096. lenbuf[i + 1] = 0;
  4097. chunkSize = strtoul(lenbuf, &end, 16);
  4098. if (chunkSize == 0) {
  4099. /* regular end of content */
  4100. conn->is_chunked = 2;
  4101. }
  4102. break;
  4103. }
  4104. if (!isxdigit(lenbuf[i])) {
  4105. /* illegal character for chunk length */
  4106. return -1;
  4107. }
  4108. }
  4109. if ((end == NULL) || (*end != '\r')) {
  4110. /* chunksize not set correctly */
  4111. return -1;
  4112. }
  4113. if (chunkSize == 0) {
  4114. break;
  4115. }
  4116. conn->chunk_remainder = chunkSize;
  4117. }
  4118. }
  4119. return (int)all_read;
  4120. }
  4121. return mg_read_inner(conn, buf, len);
  4122. }
  4123. int
  4124. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  4125. {
  4126. time_t now;
  4127. int64_t n, total, allowed;
  4128. if (conn == NULL) {
  4129. return 0;
  4130. }
  4131. if (conn->throttle > 0) {
  4132. if ((now = time(NULL)) != conn->last_throttle_time) {
  4133. conn->last_throttle_time = now;
  4134. conn->last_throttle_bytes = 0;
  4135. }
  4136. allowed = conn->throttle - conn->last_throttle_bytes;
  4137. if (allowed > (int64_t)len) {
  4138. allowed = (int64_t)len;
  4139. }
  4140. if ((total = push_all(conn->ctx,
  4141. NULL,
  4142. conn->client.sock,
  4143. conn->ssl,
  4144. (const char *)buf,
  4145. (int64_t)allowed)) == allowed) {
  4146. buf = (const char *)buf + total;
  4147. conn->last_throttle_bytes += total;
  4148. while (total < (int64_t)len && conn->ctx->stop_flag == 0) {
  4149. allowed = (conn->throttle > ((int64_t)len - total))
  4150. ? (int64_t)len - total
  4151. : conn->throttle;
  4152. if ((n = push_all(conn->ctx,
  4153. NULL,
  4154. conn->client.sock,
  4155. conn->ssl,
  4156. (const char *)buf,
  4157. (int64_t)allowed)) != allowed) {
  4158. break;
  4159. }
  4160. sleep(1);
  4161. conn->last_throttle_bytes = allowed;
  4162. conn->last_throttle_time = time(NULL);
  4163. buf = (const char *)buf + n;
  4164. total += n;
  4165. }
  4166. }
  4167. } else {
  4168. total = push_all(conn->ctx,
  4169. NULL,
  4170. conn->client.sock,
  4171. conn->ssl,
  4172. (const char *)buf,
  4173. (int64_t)len);
  4174. }
  4175. return (int)total;
  4176. }
  4177. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  4178. static int
  4179. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  4180. {
  4181. va_list ap_copy;
  4182. size_t size = MG_BUF_LEN / 4;
  4183. int len = -1;
  4184. *buf = NULL;
  4185. while (len < 0) {
  4186. if (*buf) {
  4187. mg_free(*buf);
  4188. }
  4189. size *= 4;
  4190. *buf = (char *)mg_malloc(size);
  4191. if (!*buf) {
  4192. break;
  4193. }
  4194. va_copy(ap_copy, ap);
  4195. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  4196. va_end(ap_copy);
  4197. (*buf)[size - 1] = 0;
  4198. }
  4199. return len;
  4200. }
  4201. /* Print message to buffer. If buffer is large enough to hold the message,
  4202. * return buffer. If buffer is to small, allocate large enough buffer on heap,
  4203. * and return allocated buffer. */
  4204. static int
  4205. alloc_vprintf(char **out_buf,
  4206. char *prealloc_buf,
  4207. size_t prealloc_size,
  4208. const char *fmt,
  4209. va_list ap)
  4210. {
  4211. va_list ap_copy;
  4212. int len;
  4213. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  4214. * buffer is too small. Also, older versions of msvcrt.dll do not have
  4215. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  4216. * Therefore, we make two passes: on first pass, get required message
  4217. * length.
  4218. * On second pass, actually print the message. */
  4219. va_copy(ap_copy, ap);
  4220. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  4221. va_end(ap_copy);
  4222. if (len < 0) {
  4223. /* C runtime is not standard compliant, vsnprintf() returned -1.
  4224. * Switch to alternative code path that uses incremental allocations.
  4225. */
  4226. va_copy(ap_copy, ap);
  4227. len = alloc_vprintf2(out_buf, fmt, ap);
  4228. va_end(ap_copy);
  4229. } else if ((size_t)(len) >= prealloc_size) {
  4230. /* The pre-allocated buffer not large enough. */
  4231. /* Allocate a new buffer. */
  4232. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  4233. if (!*out_buf) {
  4234. /* Allocation failed. Return -1 as "out of memory" error. */
  4235. return -1;
  4236. }
  4237. /* Buffer allocation successful. Store the string there. */
  4238. va_copy(ap_copy, ap);
  4239. IGNORE_UNUSED_RESULT(
  4240. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  4241. va_end(ap_copy);
  4242. } else {
  4243. /* The pre-allocated buffer is large enough.
  4244. * Use it to store the string and return the address. */
  4245. va_copy(ap_copy, ap);
  4246. IGNORE_UNUSED_RESULT(
  4247. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  4248. va_end(ap_copy);
  4249. *out_buf = prealloc_buf;
  4250. }
  4251. return len;
  4252. }
  4253. static int
  4254. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  4255. {
  4256. char mem[MG_BUF_LEN];
  4257. char *buf = NULL;
  4258. int len;
  4259. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  4260. len = mg_write(conn, buf, (size_t)len);
  4261. }
  4262. if (buf != mem && buf != NULL) {
  4263. mg_free(buf);
  4264. }
  4265. return len;
  4266. }
  4267. int
  4268. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  4269. {
  4270. va_list ap;
  4271. int result;
  4272. va_start(ap, fmt);
  4273. result = mg_vprintf(conn, fmt, ap);
  4274. va_end(ap);
  4275. return result;
  4276. }
  4277. int
  4278. mg_url_decode(const char *src,
  4279. int src_len,
  4280. char *dst,
  4281. int dst_len,
  4282. int is_form_url_encoded)
  4283. {
  4284. int i, j, a, b;
  4285. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  4286. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  4287. if (i < src_len - 2 && src[i] == '%'
  4288. && isxdigit(*(const unsigned char *)(src + i + 1))
  4289. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  4290. a = tolower(*(const unsigned char *)(src + i + 1));
  4291. b = tolower(*(const unsigned char *)(src + i + 2));
  4292. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  4293. i += 2;
  4294. } else if (is_form_url_encoded && src[i] == '+') {
  4295. dst[j] = ' ';
  4296. } else {
  4297. dst[j] = src[i];
  4298. }
  4299. }
  4300. dst[j] = '\0'; /* Null-terminate the destination */
  4301. return (i >= src_len) ? j : -1;
  4302. }
  4303. int
  4304. mg_get_var(const char *data,
  4305. size_t data_len,
  4306. const char *name,
  4307. char *dst,
  4308. size_t dst_len)
  4309. {
  4310. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  4311. }
  4312. int
  4313. mg_get_var2(const char *data,
  4314. size_t data_len,
  4315. const char *name,
  4316. char *dst,
  4317. size_t dst_len,
  4318. size_t occurrence)
  4319. {
  4320. const char *p, *e, *s;
  4321. size_t name_len;
  4322. int len;
  4323. if (dst == NULL || dst_len == 0) {
  4324. len = -2;
  4325. } else if (data == NULL || name == NULL || data_len == 0) {
  4326. len = -1;
  4327. dst[0] = '\0';
  4328. } else {
  4329. name_len = strlen(name);
  4330. e = data + data_len;
  4331. len = -1;
  4332. dst[0] = '\0';
  4333. /* data is "var1=val1&var2=val2...". Find variable first */
  4334. for (p = data; p + name_len < e; p++) {
  4335. if ((p == data || p[-1] == '&') && p[name_len] == '='
  4336. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  4337. /* Point p to variable value */
  4338. p += name_len + 1;
  4339. /* Point s to the end of the value */
  4340. s = (const char *)memchr(p, '&', (size_t)(e - p));
  4341. if (s == NULL) {
  4342. s = e;
  4343. }
  4344. /* assert(s >= p); */
  4345. if (s < p) {
  4346. return -3;
  4347. }
  4348. /* Decode variable into destination buffer */
  4349. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  4350. /* Redirect error code from -1 to -2 (destination buffer too
  4351. * small). */
  4352. if (len == -1) {
  4353. len = -2;
  4354. }
  4355. break;
  4356. }
  4357. }
  4358. }
  4359. return len;
  4360. }
  4361. /* HCP24: some changes to compare hole var_name */
  4362. int
  4363. mg_get_cookie(const char *cookie_header,
  4364. const char *var_name,
  4365. char *dst,
  4366. size_t dst_size)
  4367. {
  4368. const char *s, *p, *end;
  4369. int name_len, len = -1;
  4370. if (dst == NULL || dst_size == 0) {
  4371. return -2;
  4372. }
  4373. dst[0] = '\0';
  4374. if (var_name == NULL || (s = cookie_header) == NULL) {
  4375. return -1;
  4376. }
  4377. name_len = (int)strlen(var_name);
  4378. end = s + strlen(s);
  4379. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  4380. if (s[name_len] == '=') {
  4381. /* HCP24: now check is it a substring or a full cookie name */
  4382. if ((s == cookie_header) || (s[-1] == ' ')) {
  4383. s += name_len + 1;
  4384. if ((p = strchr(s, ' ')) == NULL) {
  4385. p = end;
  4386. }
  4387. if (p[-1] == ';') {
  4388. p--;
  4389. }
  4390. if (*s == '"' && p[-1] == '"' && p > s + 1) {
  4391. s++;
  4392. p--;
  4393. }
  4394. if ((size_t)(p - s) < dst_size) {
  4395. len = (int)(p - s);
  4396. mg_strlcpy(dst, s, (size_t)len + 1);
  4397. } else {
  4398. len = -3;
  4399. }
  4400. break;
  4401. }
  4402. }
  4403. }
  4404. return len;
  4405. }
  4406. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  4407. static void
  4408. base64_encode(const unsigned char *src, int src_len, char *dst)
  4409. {
  4410. static const char *b64 =
  4411. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  4412. int i, j, a, b, c;
  4413. for (i = j = 0; i < src_len; i += 3) {
  4414. a = src[i];
  4415. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  4416. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  4417. dst[j++] = b64[a >> 2];
  4418. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  4419. if (i + 1 < src_len) {
  4420. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  4421. }
  4422. if (i + 2 < src_len) {
  4423. dst[j++] = b64[c & 63];
  4424. }
  4425. }
  4426. while (j % 4 != 0) {
  4427. dst[j++] = '=';
  4428. }
  4429. dst[j++] = '\0';
  4430. }
  4431. #endif
  4432. #if defined(USE_LUA)
  4433. static unsigned char
  4434. b64reverse(char letter)
  4435. {
  4436. if (letter >= 'A' && letter <= 'Z') {
  4437. return letter - 'A';
  4438. }
  4439. if (letter >= 'a' && letter <= 'z') {
  4440. return letter - 'a' + 26;
  4441. }
  4442. if (letter >= '0' && letter <= '9') {
  4443. return letter - '0' + 52;
  4444. }
  4445. if (letter == '+') {
  4446. return 62;
  4447. }
  4448. if (letter == '/') {
  4449. return 63;
  4450. }
  4451. if (letter == '=') {
  4452. return 255; /* normal end */
  4453. }
  4454. return 254; /* error */
  4455. }
  4456. static int
  4457. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  4458. {
  4459. int i;
  4460. unsigned char a, b, c, d;
  4461. *dst_len = 0;
  4462. for (i = 0; i < src_len; i += 4) {
  4463. a = b64reverse(src[i]);
  4464. if (a >= 254) {
  4465. return i;
  4466. }
  4467. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  4468. if (b >= 254) {
  4469. return i + 1;
  4470. }
  4471. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  4472. if (c == 254) {
  4473. return i + 2;
  4474. }
  4475. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  4476. if (d == 254) {
  4477. return i + 3;
  4478. }
  4479. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  4480. if (c != 255) {
  4481. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  4482. if (d != 255) {
  4483. dst[(*dst_len)++] = (c << 6) + d;
  4484. }
  4485. }
  4486. }
  4487. return -1;
  4488. }
  4489. #endif
  4490. static int
  4491. is_put_or_delete_method(const struct mg_connection *conn)
  4492. {
  4493. if (conn) {
  4494. const char *s = conn->request_info.request_method;
  4495. return s != NULL && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  4496. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  4497. }
  4498. return 0;
  4499. }
  4500. static void
  4501. interpret_uri(struct mg_connection *conn, /* in: request (must be valid) */
  4502. char *filename, /* out: filename */
  4503. size_t filename_buf_len, /* in: size of filename buffer */
  4504. struct mg_file_stat *filestat, /* out: file structure */
  4505. int *is_found, /* out: file found (directly) */
  4506. int *is_script_resource, /* out: handled by a script? */
  4507. int *is_websocket_request, /* out: websocket connetion? */
  4508. int *is_put_or_delete_request /* out: put/delete a file? */
  4509. )
  4510. {
  4511. /* TODO (high): Restructure this function */
  4512. #if !defined(NO_FILES)
  4513. const char *uri = conn->request_info.local_uri;
  4514. const char *root = conn->ctx->config[DOCUMENT_ROOT];
  4515. const char *rewrite;
  4516. struct vec a, b;
  4517. int match_len;
  4518. char gz_path[PATH_MAX];
  4519. char const *accept_encoding;
  4520. int truncated;
  4521. #if !defined(NO_CGI) || defined(USE_LUA)
  4522. char *p;
  4523. #endif
  4524. #else
  4525. (void)filename_buf_len; /* unused if NO_FILES is defined */
  4526. #endif
  4527. memset(filestat, 0, sizeof(*filestat));
  4528. *filename = 0;
  4529. *is_found = 0;
  4530. *is_script_resource = 0;
  4531. *is_put_or_delete_request = is_put_or_delete_method(conn);
  4532. #if defined(USE_WEBSOCKET)
  4533. *is_websocket_request = is_websocket_protocol(conn);
  4534. #if !defined(NO_FILES)
  4535. if (*is_websocket_request && conn->ctx->config[WEBSOCKET_ROOT]) {
  4536. root = conn->ctx->config[WEBSOCKET_ROOT];
  4537. }
  4538. #endif /* !NO_FILES */
  4539. #else /* USE_WEBSOCKET */
  4540. *is_websocket_request = 0;
  4541. #endif /* USE_WEBSOCKET */
  4542. #if !defined(NO_FILES)
  4543. /* Note that root == NULL is a regular use case here. This occurs,
  4544. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  4545. * config is not required. */
  4546. if (root == NULL) {
  4547. /* all file related outputs have already been set to 0, just return
  4548. */
  4549. return;
  4550. }
  4551. /* Using buf_len - 1 because memmove() for PATH_INFO may shift part
  4552. * of the path one byte on the right.
  4553. * If document_root is NULL, leave the file empty. */
  4554. mg_snprintf(
  4555. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  4556. if (truncated) {
  4557. goto interpret_cleanup;
  4558. }
  4559. rewrite = conn->ctx->config[REWRITE];
  4560. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  4561. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  4562. mg_snprintf(conn,
  4563. &truncated,
  4564. filename,
  4565. filename_buf_len - 1,
  4566. "%.*s%s",
  4567. (int)b.len,
  4568. b.ptr,
  4569. uri + match_len);
  4570. break;
  4571. }
  4572. }
  4573. if (truncated) {
  4574. goto interpret_cleanup;
  4575. }
  4576. /* Local file path and name, corresponding to requested URI
  4577. * is now stored in "filename" variable. */
  4578. if (mg_stat(conn, filename, filestat)) {
  4579. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  4580. /* File exists. Check if it is a script type. */
  4581. if (0
  4582. #if !defined(NO_CGI)
  4583. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  4584. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4585. filename) > 0
  4586. #endif
  4587. #if defined(USE_LUA)
  4588. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  4589. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  4590. filename) > 0
  4591. #endif
  4592. #if defined(USE_DUKTAPE)
  4593. || match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  4594. strlen(
  4595. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  4596. filename) > 0
  4597. #endif
  4598. ) {
  4599. /* The request addresses a CGI script or a Lua script. The URI
  4600. * corresponds to the script itself (like /path/script.cgi),
  4601. * and there is no additional resource path
  4602. * (like /path/script.cgi/something).
  4603. * Requests that modify (replace or delete) a resource, like
  4604. * PUT and DELETE requests, should replace/delete the script
  4605. * file.
  4606. * Requests that read or write from/to a resource, like GET and
  4607. * POST requests, should call the script and return the
  4608. * generated response. */
  4609. *is_script_resource = !*is_put_or_delete_request;
  4610. }
  4611. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  4612. *is_found = 1;
  4613. return;
  4614. }
  4615. /* If we can't find the actual file, look for the file
  4616. * with the same name but a .gz extension. If we find it,
  4617. * use that and set the gzipped flag in the file struct
  4618. * to indicate that the response need to have the content-
  4619. * encoding: gzip header.
  4620. * We can only do this if the browser declares support. */
  4621. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  4622. if (strstr(accept_encoding, "gzip") != NULL) {
  4623. mg_snprintf(
  4624. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  4625. if (truncated) {
  4626. goto interpret_cleanup;
  4627. }
  4628. if (mg_stat(conn, gz_path, filestat)) {
  4629. if (filestat) {
  4630. filestat->is_gzipped = 1;
  4631. *is_found = 1;
  4632. }
  4633. /* Currently gz files can not be scripts. */
  4634. return;
  4635. }
  4636. }
  4637. }
  4638. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  4639. /* Support PATH_INFO for CGI scripts. */
  4640. for (p = filename + strlen(filename); p > filename + 1; p--) {
  4641. if (*p == '/') {
  4642. *p = '\0';
  4643. if ((0
  4644. #if !defined(NO_CGI)
  4645. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  4646. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4647. filename) > 0
  4648. #endif
  4649. #if defined(USE_LUA)
  4650. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  4651. strlen(
  4652. conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  4653. filename) > 0
  4654. #endif
  4655. #if defined(USE_DUKTAPE)
  4656. || match_prefix(
  4657. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  4658. strlen(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  4659. filename) > 0
  4660. #endif
  4661. ) && mg_stat(conn, filename, filestat)) {
  4662. /* Shift PATH_INFO block one character right, e.g.
  4663. * "/x.cgi/foo/bar\x00" => "/x.cgi\x00/foo/bar\x00"
  4664. * conn->path_info is pointing to the local variable "path"
  4665. * declared in handle_request(), so PATH_INFO is not valid
  4666. * after handle_request returns. */
  4667. conn->path_info = p + 1;
  4668. memmove(p + 2, p + 1, strlen(p + 1) + 1); /* +1 is for
  4669. * trailing \0 */
  4670. p[1] = '/';
  4671. *is_script_resource = 1;
  4672. break;
  4673. } else {
  4674. *p = '/';
  4675. }
  4676. }
  4677. }
  4678. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  4679. #endif /* !defined(NO_FILES) */
  4680. return;
  4681. #if !defined(NO_FILES)
  4682. /* Reset all outputs */
  4683. interpret_cleanup:
  4684. memset(filestat, 0, sizeof(*filestat));
  4685. *filename = 0;
  4686. *is_found = 0;
  4687. *is_script_resource = 0;
  4688. *is_websocket_request = 0;
  4689. *is_put_or_delete_request = 0;
  4690. #endif /* !defined(NO_FILES) */
  4691. }
  4692. /* Check whether full request is buffered. Return:
  4693. * -1 if request is malformed
  4694. * 0 if request is not yet fully buffered
  4695. * >0 actual request length, including last \r\n\r\n */
  4696. static int
  4697. get_request_len(const char *buf, int buflen)
  4698. {
  4699. const char *s, *e;
  4700. int len = 0;
  4701. for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
  4702. /* Control characters are not allowed but >=128 is. */
  4703. if (!isprint(*(const unsigned char *)s) && *s != '\r' && *s != '\n'
  4704. && *(const unsigned char *)s < 128) {
  4705. len = -1;
  4706. break; /* [i_a] abort scan as soon as one malformed character is
  4707. * found; */
  4708. /* don't let subsequent \r\n\r\n win us over anyhow */
  4709. } else if (s[0] == '\n' && s[1] == '\n') {
  4710. len = (int)(s - buf) + 2;
  4711. } else if (s[0] == '\n' && &s[1] < e && s[1] == '\r' && s[2] == '\n') {
  4712. len = (int)(s - buf) + 3;
  4713. }
  4714. return len;
  4715. }
  4716. #if !defined(NO_CACHING)
  4717. /* Convert month to the month number. Return -1 on error, or month number */
  4718. static int
  4719. get_month_index(const char *s)
  4720. {
  4721. size_t i;
  4722. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  4723. if (!strcmp(s, month_names[i])) {
  4724. return (int)i;
  4725. }
  4726. }
  4727. return -1;
  4728. }
  4729. /* Parse UTC date-time string, and return the corresponding time_t value. */
  4730. static time_t
  4731. parse_date_string(const char *datetime)
  4732. {
  4733. char month_str[32] = {0};
  4734. int second, minute, hour, day, month, year;
  4735. time_t result = (time_t)0;
  4736. struct tm tm;
  4737. if ((sscanf(datetime,
  4738. "%d/%3s/%d %d:%d:%d",
  4739. &day,
  4740. month_str,
  4741. &year,
  4742. &hour,
  4743. &minute,
  4744. &second) == 6) || (sscanf(datetime,
  4745. "%d %3s %d %d:%d:%d",
  4746. &day,
  4747. month_str,
  4748. &year,
  4749. &hour,
  4750. &minute,
  4751. &second) == 6)
  4752. || (sscanf(datetime,
  4753. "%*3s, %d %3s %d %d:%d:%d",
  4754. &day,
  4755. month_str,
  4756. &year,
  4757. &hour,
  4758. &minute,
  4759. &second) == 6) || (sscanf(datetime,
  4760. "%d-%3s-%d %d:%d:%d",
  4761. &day,
  4762. month_str,
  4763. &year,
  4764. &hour,
  4765. &minute,
  4766. &second) == 6)) {
  4767. month = get_month_index(month_str);
  4768. if ((month >= 0) && (year >= 1970)) {
  4769. memset(&tm, 0, sizeof(tm));
  4770. tm.tm_year = year - 1900;
  4771. tm.tm_mon = month;
  4772. tm.tm_mday = day;
  4773. tm.tm_hour = hour;
  4774. tm.tm_min = minute;
  4775. tm.tm_sec = second;
  4776. result = timegm(&tm);
  4777. }
  4778. }
  4779. return result;
  4780. }
  4781. #endif /* !NO_CACHING */
  4782. /* Protect against directory disclosure attack by removing '..',
  4783. * excessive '/' and '\' characters */
  4784. static void
  4785. remove_double_dots_and_double_slashes(char *s)
  4786. {
  4787. char *p = s;
  4788. while ((s[0] == '.') && (s[1] == '.')) {
  4789. s++;
  4790. }
  4791. while (*s != '\0') {
  4792. *p++ = *s++;
  4793. if (s[-1] == '/' || s[-1] == '\\') {
  4794. /* Skip all following slashes, backslashes and double-dots */
  4795. while (s[0] != '\0') {
  4796. if (s[0] == '/' || s[0] == '\\') {
  4797. s++;
  4798. } else if (s[0] == '.' && s[1] == '.') {
  4799. s += 2;
  4800. } else {
  4801. break;
  4802. }
  4803. }
  4804. }
  4805. }
  4806. *p = '\0';
  4807. }
  4808. static const struct {
  4809. const char *extension;
  4810. size_t ext_len;
  4811. const char *mime_type;
  4812. } builtin_mime_types[] = {
  4813. /* IANA registered MIME types (http://www.iana.org/assignments/media-types)
  4814. * application types */
  4815. {".doc", 4, "application/msword"},
  4816. {".eps", 4, "application/postscript"},
  4817. {".exe", 4, "application/octet-stream"},
  4818. {".js", 3, "application/javascript"},
  4819. {".json", 5, "application/json"},
  4820. {".pdf", 4, "application/pdf"},
  4821. {".ps", 3, "application/postscript"},
  4822. {".rtf", 4, "application/rtf"},
  4823. {".xhtml", 6, "application/xhtml+xml"},
  4824. {".xsl", 4, "application/xml"},
  4825. {".xslt", 5, "application/xml"},
  4826. /* fonts */
  4827. {".ttf", 4, "application/font-sfnt"},
  4828. {".cff", 4, "application/font-sfnt"},
  4829. {".otf", 4, "application/font-sfnt"},
  4830. {".aat", 4, "application/font-sfnt"},
  4831. {".sil", 4, "application/font-sfnt"},
  4832. {".pfr", 4, "application/font-tdpfr"},
  4833. {".woff", 5, "application/font-woff"},
  4834. /* audio */
  4835. {".mp3", 4, "audio/mpeg"},
  4836. {".oga", 4, "audio/ogg"},
  4837. {".ogg", 4, "audio/ogg"},
  4838. /* image */
  4839. {".gif", 4, "image/gif"},
  4840. {".ief", 4, "image/ief"},
  4841. {".jpeg", 5, "image/jpeg"},
  4842. {".jpg", 4, "image/jpeg"},
  4843. {".jpm", 4, "image/jpm"},
  4844. {".jpx", 4, "image/jpx"},
  4845. {".png", 4, "image/png"},
  4846. {".svg", 4, "image/svg+xml"},
  4847. {".tif", 4, "image/tiff"},
  4848. {".tiff", 5, "image/tiff"},
  4849. /* model */
  4850. {".wrl", 4, "model/vrml"},
  4851. /* text */
  4852. {".css", 4, "text/css"},
  4853. {".csv", 4, "text/csv"},
  4854. {".htm", 4, "text/html"},
  4855. {".html", 5, "text/html"},
  4856. {".sgm", 4, "text/sgml"},
  4857. {".shtm", 5, "text/html"},
  4858. {".shtml", 6, "text/html"},
  4859. {".txt", 4, "text/plain"},
  4860. {".xml", 4, "text/xml"},
  4861. /* video */
  4862. {".mov", 4, "video/quicktime"},
  4863. {".mp4", 4, "video/mp4"},
  4864. {".mpeg", 5, "video/mpeg"},
  4865. {".mpg", 4, "video/mpeg"},
  4866. {".ogv", 4, "video/ogg"},
  4867. {".qt", 3, "video/quicktime"},
  4868. /* not registered types
  4869. * (http://reference.sitepoint.com/html/mime-types-full,
  4870. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  4871. {".arj", 4, "application/x-arj-compressed"},
  4872. {".gz", 3, "application/x-gunzip"},
  4873. {".rar", 4, "application/x-arj-compressed"},
  4874. {".swf", 4, "application/x-shockwave-flash"},
  4875. {".tar", 4, "application/x-tar"},
  4876. {".tgz", 4, "application/x-tar-gz"},
  4877. {".torrent", 8, "application/x-bittorrent"},
  4878. {".ppt", 4, "application/x-mspowerpoint"},
  4879. {".xls", 4, "application/x-msexcel"},
  4880. {".zip", 4, "application/x-zip-compressed"},
  4881. {".aac",
  4882. 4,
  4883. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  4884. {".aif", 4, "audio/x-aif"},
  4885. {".m3u", 4, "audio/x-mpegurl"},
  4886. {".mid", 4, "audio/x-midi"},
  4887. {".ra", 3, "audio/x-pn-realaudio"},
  4888. {".ram", 4, "audio/x-pn-realaudio"},
  4889. {".wav", 4, "audio/x-wav"},
  4890. {".bmp", 4, "image/bmp"},
  4891. {".ico", 4, "image/x-icon"},
  4892. {".pct", 4, "image/x-pct"},
  4893. {".pict", 5, "image/pict"},
  4894. {".rgb", 4, "image/x-rgb"},
  4895. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  4896. {".asf", 4, "video/x-ms-asf"},
  4897. {".avi", 4, "video/x-msvideo"},
  4898. {".m4v", 4, "video/x-m4v"},
  4899. {NULL, 0, NULL}};
  4900. const char *
  4901. mg_get_builtin_mime_type(const char *path)
  4902. {
  4903. const char *ext;
  4904. size_t i, path_len;
  4905. path_len = strlen(path);
  4906. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  4907. ext = path + (path_len - builtin_mime_types[i].ext_len);
  4908. if (path_len > builtin_mime_types[i].ext_len
  4909. && mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {
  4910. return builtin_mime_types[i].mime_type;
  4911. }
  4912. }
  4913. return "text/plain";
  4914. }
  4915. /* Look at the "path" extension and figure what mime type it has.
  4916. * Store mime type in the vector. */
  4917. static void
  4918. get_mime_type(struct mg_context *ctx, const char *path, struct vec *vec)
  4919. {
  4920. struct vec ext_vec, mime_vec;
  4921. const char *list, *ext;
  4922. size_t path_len;
  4923. path_len = strlen(path);
  4924. if (ctx == NULL || vec == NULL) {
  4925. return;
  4926. }
  4927. /* Scan user-defined mime types first, in case user wants to
  4928. * override default mime types. */
  4929. list = ctx->config[EXTRA_MIME_TYPES];
  4930. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  4931. /* ext now points to the path suffix */
  4932. ext = path + path_len - ext_vec.len;
  4933. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  4934. *vec = mime_vec;
  4935. return;
  4936. }
  4937. }
  4938. vec->ptr = mg_get_builtin_mime_type(path);
  4939. vec->len = strlen(vec->ptr);
  4940. }
  4941. /* Stringify binary data. Output buffer must be twice as big as input,
  4942. * because each byte takes 2 bytes in string representation */
  4943. static void
  4944. bin2str(char *to, const unsigned char *p, size_t len)
  4945. {
  4946. static const char *hex = "0123456789abcdef";
  4947. for (; len--; p++) {
  4948. *to++ = hex[p[0] >> 4];
  4949. *to++ = hex[p[0] & 0x0f];
  4950. }
  4951. *to = '\0';
  4952. }
  4953. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes. */
  4954. char *
  4955. mg_md5(char buf[33], ...)
  4956. {
  4957. md5_byte_t hash[16];
  4958. const char *p;
  4959. va_list ap;
  4960. md5_state_t ctx;
  4961. md5_init(&ctx);
  4962. va_start(ap, buf);
  4963. while ((p = va_arg(ap, const char *)) != NULL) {
  4964. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  4965. }
  4966. va_end(ap);
  4967. md5_finish(&ctx, hash);
  4968. bin2str(buf, hash, sizeof(hash));
  4969. return buf;
  4970. }
  4971. /* Check the user's password, return 1 if OK */
  4972. static int
  4973. check_password(const char *method,
  4974. const char *ha1,
  4975. const char *uri,
  4976. const char *nonce,
  4977. const char *nc,
  4978. const char *cnonce,
  4979. const char *qop,
  4980. const char *response)
  4981. {
  4982. char ha2[32 + 1], expected_response[32 + 1];
  4983. /* Some of the parameters may be NULL */
  4984. if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL
  4985. || qop == NULL
  4986. || response == NULL) {
  4987. return 0;
  4988. }
  4989. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  4990. if (strlen(response) != 32) {
  4991. return 0;
  4992. }
  4993. mg_md5(ha2, method, ":", uri, NULL);
  4994. mg_md5(expected_response,
  4995. ha1,
  4996. ":",
  4997. nonce,
  4998. ":",
  4999. nc,
  5000. ":",
  5001. cnonce,
  5002. ":",
  5003. qop,
  5004. ":",
  5005. ha2,
  5006. NULL);
  5007. return mg_strcasecmp(response, expected_response) == 0;
  5008. }
  5009. /* Use the global passwords file, if specified by auth_gpass option,
  5010. * or search for .htpasswd in the requested directory. */
  5011. static void
  5012. open_auth_file(struct mg_connection *conn,
  5013. const char *path,
  5014. struct mg_file *filep)
  5015. {
  5016. if (conn != NULL && conn->ctx != NULL) {
  5017. char name[PATH_MAX];
  5018. const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
  5019. int truncated;
  5020. if (gpass != NULL) {
  5021. /* Use global passwords file */
  5022. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  5023. #ifdef DEBUG
  5024. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  5025. #endif
  5026. }
  5027. /* Important: using local struct mg_file to test path for
  5028. * is_directory
  5029. * flag. If filep is used, mg_stat() makes it appear as if auth file
  5030. * was opened. TODO: mg_stat must not make anything appear to be
  5031. * opened */
  5032. } else if (mg_stat(conn, path, &filep->stat)
  5033. && filep->stat.is_directory) {
  5034. mg_snprintf(conn,
  5035. &truncated,
  5036. name,
  5037. sizeof(name),
  5038. "%s/%s",
  5039. path,
  5040. PASSWORDS_FILE_NAME);
  5041. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  5042. #ifdef DEBUG
  5043. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  5044. #endif
  5045. }
  5046. } else {
  5047. /* Try to find .htpasswd in requested directory. */
  5048. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  5049. if (e[0] == '/') {
  5050. break;
  5051. }
  5052. }
  5053. mg_snprintf(conn,
  5054. &truncated,
  5055. name,
  5056. sizeof(name),
  5057. "%.*s/%s",
  5058. (int)(e - p),
  5059. p,
  5060. PASSWORDS_FILE_NAME);
  5061. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  5062. #ifdef DEBUG
  5063. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  5064. #endif
  5065. }
  5066. }
  5067. }
  5068. }
  5069. /* Parsed Authorization header */
  5070. struct ah {
  5071. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  5072. };
  5073. /* Return 1 on success. Always initializes the ah structure. */
  5074. static int
  5075. parse_auth_header(struct mg_connection *conn,
  5076. char *buf,
  5077. size_t buf_size,
  5078. struct ah *ah)
  5079. {
  5080. char *name, *value, *s;
  5081. const char *auth_header;
  5082. uint64_t nonce;
  5083. if (!ah || !conn) {
  5084. return 0;
  5085. }
  5086. (void)memset(ah, 0, sizeof(*ah));
  5087. if ((auth_header = mg_get_header(conn, "Authorization")) == NULL
  5088. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  5089. return 0;
  5090. }
  5091. /* Make modifiable copy of the auth header */
  5092. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  5093. s = buf;
  5094. /* Parse authorization header */
  5095. for (;;) {
  5096. /* Gobble initial spaces */
  5097. while (isspace(*(unsigned char *)s)) {
  5098. s++;
  5099. }
  5100. name = skip_quoted(&s, "=", " ", 0);
  5101. /* Value is either quote-delimited, or ends at first comma or space. */
  5102. if (s[0] == '\"') {
  5103. s++;
  5104. value = skip_quoted(&s, "\"", " ", '\\');
  5105. if (s[0] == ',') {
  5106. s++;
  5107. }
  5108. } else {
  5109. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  5110. * spaces */
  5111. }
  5112. if (*name == '\0') {
  5113. break;
  5114. }
  5115. if (!strcmp(name, "username")) {
  5116. ah->user = value;
  5117. } else if (!strcmp(name, "cnonce")) {
  5118. ah->cnonce = value;
  5119. } else if (!strcmp(name, "response")) {
  5120. ah->response = value;
  5121. } else if (!strcmp(name, "uri")) {
  5122. ah->uri = value;
  5123. } else if (!strcmp(name, "qop")) {
  5124. ah->qop = value;
  5125. } else if (!strcmp(name, "nc")) {
  5126. ah->nc = value;
  5127. } else if (!strcmp(name, "nonce")) {
  5128. ah->nonce = value;
  5129. }
  5130. }
  5131. #ifndef NO_NONCE_CHECK
  5132. /* Read the nonce from the response. */
  5133. if (ah->nonce == NULL) {
  5134. return 0;
  5135. }
  5136. s = NULL;
  5137. nonce = strtoull(ah->nonce, &s, 10);
  5138. if ((s == NULL) || (*s != 0)) {
  5139. return 0;
  5140. }
  5141. /* Convert the nonce from the client to a number. */
  5142. nonce ^= conn->ctx->auth_nonce_mask;
  5143. /* The converted number corresponds to the time the nounce has been
  5144. * created. This should not be earlier than the server start. */
  5145. /* Server side nonce check is valuable in all situations but one:
  5146. * if the server restarts frequently, but the client should not see
  5147. * that, so the server should accept nonces from previous starts. */
  5148. /* However, the reasonable default is to not accept a nonce from a
  5149. * previous start, so if anyone changed the access rights between
  5150. * two restarts, a new login is required. */
  5151. if (nonce < (uint64_t)conn->ctx->start_time) {
  5152. /* nonce is from a previous start of the server and no longer valid
  5153. * (replay attack?) */
  5154. return 0;
  5155. }
  5156. /* Check if the nonce is too high, so it has not (yet) been used by the
  5157. * server. */
  5158. if (nonce >= ((uint64_t)conn->ctx->start_time + conn->ctx->nonce_count)) {
  5159. return 0;
  5160. }
  5161. #else
  5162. (void)nonce;
  5163. #endif
  5164. /* CGI needs it as REMOTE_USER */
  5165. if (ah->user != NULL) {
  5166. conn->request_info.remote_user = mg_strdup(ah->user);
  5167. } else {
  5168. return 0;
  5169. }
  5170. return 1;
  5171. }
  5172. static const char *
  5173. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  5174. {
  5175. const char *eof;
  5176. size_t len;
  5177. const char *memend;
  5178. if (!filep) {
  5179. return NULL;
  5180. }
  5181. if (filep->access.membuf != NULL && *p != NULL) {
  5182. memend = (const char *)&filep->access.membuf[filep->stat.size];
  5183. /* Search for \n from p till the end of stream */
  5184. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  5185. if (eof != NULL) {
  5186. eof += 1; /* Include \n */
  5187. } else {
  5188. eof = memend; /* Copy remaining data */
  5189. }
  5190. len =
  5191. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  5192. memcpy(buf, *p, len);
  5193. buf[len] = '\0';
  5194. *p += len;
  5195. return len ? eof : NULL;
  5196. } else if (filep->access.fp != NULL) {
  5197. return fgets(buf, (int)size, filep->access.fp);
  5198. } else {
  5199. return NULL;
  5200. }
  5201. }
  5202. struct read_auth_file_struct {
  5203. struct mg_connection *conn;
  5204. struct ah ah;
  5205. char *domain;
  5206. char buf[256 + 256 + 40];
  5207. char *f_user;
  5208. char *f_domain;
  5209. char *f_ha1;
  5210. };
  5211. static int
  5212. read_auth_file(struct mg_file *filep, struct read_auth_file_struct *workdata)
  5213. {
  5214. char *p;
  5215. int is_authorized = 0;
  5216. struct mg_file fp;
  5217. size_t l;
  5218. if (!filep || !workdata) {
  5219. return 0;
  5220. }
  5221. /* Loop over passwords file */
  5222. p = (char *)filep->access.membuf;
  5223. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  5224. l = strlen(workdata->buf);
  5225. while (l > 0) {
  5226. if (isspace(workdata->buf[l - 1])
  5227. || iscntrl(workdata->buf[l - 1])) {
  5228. l--;
  5229. workdata->buf[l] = 0;
  5230. } else
  5231. break;
  5232. }
  5233. if (l < 1) {
  5234. continue;
  5235. }
  5236. workdata->f_user = workdata->buf;
  5237. if (workdata->f_user[0] == ':') {
  5238. /* user names may not contain a ':' and may not be empty,
  5239. * so lines starting with ':' may be used for a special purpose */
  5240. if (workdata->f_user[1] == '#') {
  5241. /* :# is a comment */
  5242. continue;
  5243. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  5244. if (mg_fopen(workdata->conn,
  5245. workdata->f_user + 9,
  5246. MG_FOPEN_MODE_READ,
  5247. &fp)) {
  5248. is_authorized = read_auth_file(&fp, workdata);
  5249. (void)mg_fclose(
  5250. &fp.access); /* ignore error on read only file */
  5251. } else {
  5252. mg_cry(workdata->conn,
  5253. "%s: cannot open authorization file: %s",
  5254. __func__,
  5255. workdata->buf);
  5256. }
  5257. continue;
  5258. }
  5259. /* everything is invalid for the moment (might change in the
  5260. * future) */
  5261. mg_cry(workdata->conn,
  5262. "%s: syntax error in authorization file: %s",
  5263. __func__,
  5264. workdata->buf);
  5265. continue;
  5266. }
  5267. workdata->f_domain = strchr(workdata->f_user, ':');
  5268. if (workdata->f_domain == NULL) {
  5269. mg_cry(workdata->conn,
  5270. "%s: syntax error in authorization file: %s",
  5271. __func__,
  5272. workdata->buf);
  5273. continue;
  5274. }
  5275. *(workdata->f_domain) = 0;
  5276. (workdata->f_domain)++;
  5277. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  5278. if (workdata->f_ha1 == NULL) {
  5279. mg_cry(workdata->conn,
  5280. "%s: syntax error in authorization file: %s",
  5281. __func__,
  5282. workdata->buf);
  5283. continue;
  5284. }
  5285. *(workdata->f_ha1) = 0;
  5286. (workdata->f_ha1)++;
  5287. if (!strcmp(workdata->ah.user, workdata->f_user)
  5288. && !strcmp(workdata->domain, workdata->f_domain)) {
  5289. return check_password(workdata->conn->request_info.request_method,
  5290. workdata->f_ha1,
  5291. workdata->ah.uri,
  5292. workdata->ah.nonce,
  5293. workdata->ah.nc,
  5294. workdata->ah.cnonce,
  5295. workdata->ah.qop,
  5296. workdata->ah.response);
  5297. }
  5298. }
  5299. return is_authorized;
  5300. }
  5301. /* Authorize against the opened passwords file. Return 1 if authorized. */
  5302. static int
  5303. authorize(struct mg_connection *conn, struct mg_file *filep)
  5304. {
  5305. struct read_auth_file_struct workdata;
  5306. char buf[MG_BUF_LEN];
  5307. if (!conn || !conn->ctx) {
  5308. return 0;
  5309. }
  5310. memset(&workdata, 0, sizeof(workdata));
  5311. workdata.conn = conn;
  5312. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  5313. return 0;
  5314. }
  5315. workdata.domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  5316. return read_auth_file(filep, &workdata);
  5317. }
  5318. /* Return 1 if request is authorised, 0 otherwise. */
  5319. static int
  5320. check_authorization(struct mg_connection *conn, const char *path)
  5321. {
  5322. char fname[PATH_MAX];
  5323. struct vec uri_vec, filename_vec;
  5324. const char *list;
  5325. struct mg_file file = STRUCT_FILE_INITIALIZER;
  5326. int authorized = 1, truncated;
  5327. if (!conn || !conn->ctx) {
  5328. return 0;
  5329. }
  5330. list = conn->ctx->config[PROTECT_URI];
  5331. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  5332. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  5333. mg_snprintf(conn,
  5334. &truncated,
  5335. fname,
  5336. sizeof(fname),
  5337. "%.*s",
  5338. (int)filename_vec.len,
  5339. filename_vec.ptr);
  5340. if (truncated
  5341. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  5342. mg_cry(conn,
  5343. "%s: cannot open %s: %s",
  5344. __func__,
  5345. fname,
  5346. strerror(errno));
  5347. }
  5348. break;
  5349. }
  5350. }
  5351. if (!is_file_opened(&file.access)) {
  5352. open_auth_file(conn, path, &file);
  5353. }
  5354. if (is_file_opened(&file.access)) {
  5355. authorized = authorize(conn, &file);
  5356. (void)mg_fclose(&file.access); /* ignore error on read only file */
  5357. }
  5358. return authorized;
  5359. }
  5360. static void
  5361. send_authorization_request(struct mg_connection *conn)
  5362. {
  5363. char date[64];
  5364. time_t curtime = time(NULL);
  5365. if (conn && conn->ctx) {
  5366. uint64_t nonce = (uint64_t)(conn->ctx->start_time);
  5367. (void)pthread_mutex_lock(&conn->ctx->nonce_mutex);
  5368. nonce += conn->ctx->nonce_count;
  5369. ++conn->ctx->nonce_count;
  5370. (void)pthread_mutex_unlock(&conn->ctx->nonce_mutex);
  5371. nonce ^= conn->ctx->auth_nonce_mask;
  5372. conn->status_code = 401;
  5373. conn->must_close = 1;
  5374. gmt_time_string(date, sizeof(date), &curtime);
  5375. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  5376. send_no_cache_header(conn);
  5377. mg_printf(conn,
  5378. "Date: %s\r\n"
  5379. "Connection: %s\r\n"
  5380. "Content-Length: 0\r\n"
  5381. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  5382. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  5383. date,
  5384. suggest_connection_header(conn),
  5385. conn->ctx->config[AUTHENTICATION_DOMAIN],
  5386. nonce);
  5387. }
  5388. }
  5389. #if !defined(NO_FILES)
  5390. static int
  5391. is_authorized_for_put(struct mg_connection *conn)
  5392. {
  5393. if (conn) {
  5394. struct mg_file file = STRUCT_FILE_INITIALIZER;
  5395. const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
  5396. int ret = 0;
  5397. if (passfile != NULL
  5398. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  5399. ret = authorize(conn, &file);
  5400. (void)mg_fclose(&file.access); /* ignore error on read only file */
  5401. }
  5402. return ret;
  5403. }
  5404. return 0;
  5405. }
  5406. #endif
  5407. int
  5408. mg_modify_passwords_file(const char *fname,
  5409. const char *domain,
  5410. const char *user,
  5411. const char *pass)
  5412. {
  5413. int found, i;
  5414. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  5415. FILE *fp, *fp2;
  5416. found = 0;
  5417. fp = fp2 = NULL;
  5418. /* Regard empty password as no password - remove user record. */
  5419. if (pass != NULL && pass[0] == '\0') {
  5420. pass = NULL;
  5421. }
  5422. /* Other arguments must not be empty */
  5423. if (fname == NULL || domain == NULL || user == NULL) {
  5424. return 0;
  5425. }
  5426. /* Using the given file format, user name and domain must not contain ':'
  5427. */
  5428. if (strchr(user, ':') != NULL) {
  5429. return 0;
  5430. }
  5431. if (strchr(domain, ':') != NULL) {
  5432. return 0;
  5433. }
  5434. /* Do not allow control characters like newline in user name and domain.
  5435. * Do not allow excessively long names either. */
  5436. for (i = 0; i < 255 && user[i] != 0; i++) {
  5437. if (iscntrl(user[i])) {
  5438. return 0;
  5439. }
  5440. }
  5441. if (user[i]) {
  5442. return 0;
  5443. }
  5444. for (i = 0; i < 255 && domain[i] != 0; i++) {
  5445. if (iscntrl(domain[i])) {
  5446. return 0;
  5447. }
  5448. }
  5449. if (domain[i]) {
  5450. return 0;
  5451. }
  5452. /* The maximum length of the path to the password file is limited */
  5453. if ((strlen(fname) + 4) >= PATH_MAX) {
  5454. return 0;
  5455. }
  5456. /* Create a temporary file name. Length has been checked before. */
  5457. strcpy(tmp, fname);
  5458. strcat(tmp, ".tmp");
  5459. /* Create the file if does not exist */
  5460. /* Use of fopen here is OK, since fname is only ASCII */
  5461. if ((fp = fopen(fname, "a+")) != NULL) {
  5462. (void)fclose(fp);
  5463. }
  5464. /* Open the given file and temporary file */
  5465. if ((fp = fopen(fname, "r")) == NULL) {
  5466. return 0;
  5467. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  5468. fclose(fp);
  5469. return 0;
  5470. }
  5471. /* Copy the stuff to temporary file */
  5472. while (fgets(line, sizeof(line), fp) != NULL) {
  5473. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  5474. continue;
  5475. }
  5476. u[255] = 0;
  5477. d[255] = 0;
  5478. if (!strcmp(u, user) && !strcmp(d, domain)) {
  5479. found++;
  5480. if (pass != NULL) {
  5481. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  5482. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  5483. }
  5484. } else {
  5485. fprintf(fp2, "%s", line);
  5486. }
  5487. }
  5488. /* If new user, just add it */
  5489. if (!found && pass != NULL) {
  5490. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  5491. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  5492. }
  5493. /* Close files */
  5494. fclose(fp);
  5495. fclose(fp2);
  5496. /* Put the temp file in place of real file */
  5497. IGNORE_UNUSED_RESULT(remove(fname));
  5498. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  5499. return 1;
  5500. }
  5501. static int
  5502. is_valid_port(unsigned long port)
  5503. {
  5504. return port < 0xffff;
  5505. }
  5506. static int
  5507. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  5508. {
  5509. struct addrinfo hints, *res, *ressave;
  5510. int func_ret = 0;
  5511. int gai_ret;
  5512. memset(&hints, 0, sizeof(struct addrinfo));
  5513. hints.ai_family = af;
  5514. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  5515. if (gai_ret != 0) {
  5516. /* gai_strerror could be used to convert gai_ret to a string */
  5517. /* POSIX return values: see
  5518. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  5519. */
  5520. /* Windows return values: see
  5521. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  5522. */
  5523. return 0;
  5524. }
  5525. ressave = res;
  5526. while (res) {
  5527. if (dstlen >= res->ai_addrlen) {
  5528. memcpy(dst, res->ai_addr, res->ai_addrlen);
  5529. func_ret = 1;
  5530. }
  5531. res = res->ai_next;
  5532. }
  5533. freeaddrinfo(ressave);
  5534. return func_ret;
  5535. }
  5536. static int
  5537. connect_socket(struct mg_context *ctx /* may be NULL */,
  5538. const char *host,
  5539. int port,
  5540. int use_ssl,
  5541. char *ebuf,
  5542. size_t ebuf_len,
  5543. SOCKET *sock /* output: socket, must not be NULL */,
  5544. union usa *sa /* output: socket address, must not be NULL */
  5545. )
  5546. {
  5547. int ip_ver = 0;
  5548. *sock = INVALID_SOCKET;
  5549. memset(sa, 0, sizeof(*sa));
  5550. if (ebuf_len > 0) {
  5551. *ebuf = 0;
  5552. }
  5553. if (host == NULL) {
  5554. mg_snprintf(NULL,
  5555. NULL, /* No truncation check for ebuf */
  5556. ebuf,
  5557. ebuf_len,
  5558. "%s",
  5559. "NULL host");
  5560. return 0;
  5561. }
  5562. if (port < 0 || !is_valid_port((unsigned)port)) {
  5563. mg_snprintf(NULL,
  5564. NULL, /* No truncation check for ebuf */
  5565. ebuf,
  5566. ebuf_len,
  5567. "%s",
  5568. "invalid port");
  5569. return 0;
  5570. }
  5571. #if !defined(NO_SSL)
  5572. if (use_ssl && (SSLv23_client_method == NULL)) {
  5573. mg_snprintf(NULL,
  5574. NULL, /* No truncation check for ebuf */
  5575. ebuf,
  5576. ebuf_len,
  5577. "%s",
  5578. "SSL is not initialized");
  5579. return 0;
  5580. }
  5581. #else
  5582. (void)use_ssl;
  5583. #endif
  5584. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  5585. sa->sin.sin_port = htons((uint16_t)port);
  5586. ip_ver = 4;
  5587. #ifdef USE_IPV6
  5588. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  5589. sa->sin6.sin6_port = htons((uint16_t)port);
  5590. ip_ver = 6;
  5591. } else if (host[0] == '[') {
  5592. /* While getaddrinfo on Windows will work with [::1],
  5593. * getaddrinfo on Linux only works with ::1 (without []). */
  5594. size_t l = strlen(host + 1);
  5595. char *h = (l > 1) ? mg_strdup(host + 1) : NULL;
  5596. if (h) {
  5597. h[l - 1] = 0;
  5598. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  5599. sa->sin6.sin6_port = htons((uint16_t)port);
  5600. ip_ver = 6;
  5601. }
  5602. mg_free(h);
  5603. }
  5604. #endif
  5605. }
  5606. if (ip_ver == 0) {
  5607. mg_snprintf(NULL,
  5608. NULL, /* No truncation check for ebuf */
  5609. ebuf,
  5610. ebuf_len,
  5611. "%s",
  5612. "host not found");
  5613. return 0;
  5614. }
  5615. if (ip_ver == 4) {
  5616. *sock = socket(PF_INET, SOCK_STREAM, 0);
  5617. }
  5618. #ifdef USE_IPV6
  5619. else if (ip_ver == 6) {
  5620. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  5621. }
  5622. #endif
  5623. if (*sock == INVALID_SOCKET) {
  5624. mg_snprintf(NULL,
  5625. NULL, /* No truncation check for ebuf */
  5626. ebuf,
  5627. ebuf_len,
  5628. "socket(): %s",
  5629. strerror(ERRNO));
  5630. return 0;
  5631. }
  5632. set_close_on_exec(*sock, fc(ctx));
  5633. if ((ip_ver == 4)
  5634. && (connect(*sock, (struct sockaddr *)&sa->sin, sizeof(sa->sin))
  5635. == 0)) {
  5636. /* connected with IPv4 */
  5637. set_blocking_mode(*sock, 0);
  5638. return 1;
  5639. }
  5640. #ifdef USE_IPV6
  5641. if ((ip_ver == 6)
  5642. && (connect(*sock, (struct sockaddr *)&sa->sin6, sizeof(sa->sin6))
  5643. == 0)) {
  5644. /* connected with IPv6 */
  5645. set_blocking_mode(*sock, 0);
  5646. return 1;
  5647. }
  5648. #endif
  5649. /* Not connected */
  5650. mg_snprintf(NULL,
  5651. NULL, /* No truncation check for ebuf */
  5652. ebuf,
  5653. ebuf_len,
  5654. "connect(%s:%d): %s",
  5655. host,
  5656. port,
  5657. strerror(ERRNO));
  5658. closesocket(*sock);
  5659. *sock = INVALID_SOCKET;
  5660. return 0;
  5661. }
  5662. int
  5663. mg_url_encode(const char *src, char *dst, size_t dst_len)
  5664. {
  5665. static const char *dont_escape = "._-$,;~()";
  5666. static const char *hex = "0123456789abcdef";
  5667. char *pos = dst;
  5668. const char *end = dst + dst_len - 1;
  5669. for (; *src != '\0' && pos < end; src++, pos++) {
  5670. if (isalnum(*(const unsigned char *)src)
  5671. || strchr(dont_escape, *(const unsigned char *)src) != NULL) {
  5672. *pos = *src;
  5673. } else if (pos + 2 < end) {
  5674. pos[0] = '%';
  5675. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  5676. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  5677. pos += 2;
  5678. } else {
  5679. break;
  5680. }
  5681. }
  5682. *pos = '\0';
  5683. return (*src == '\0') ? (int)(pos - dst) : -1;
  5684. }
  5685. static void
  5686. print_dir_entry(struct de *de)
  5687. {
  5688. char size[64], mod[64], href[PATH_MAX * 3 /* worst case */];
  5689. struct tm *tm;
  5690. if (de->file.is_directory) {
  5691. mg_snprintf(de->conn,
  5692. NULL, /* Buffer is big enough */
  5693. size,
  5694. sizeof(size),
  5695. "%s",
  5696. "[DIRECTORY]");
  5697. } else {
  5698. /* We use (signed) cast below because MSVC 6 compiler cannot
  5699. * convert unsigned __int64 to double. Sigh. */
  5700. if (de->file.size < 1024) {
  5701. mg_snprintf(de->conn,
  5702. NULL, /* Buffer is big enough */
  5703. size,
  5704. sizeof(size),
  5705. "%d",
  5706. (int)de->file.size);
  5707. } else if (de->file.size < 0x100000) {
  5708. mg_snprintf(de->conn,
  5709. NULL, /* Buffer is big enough */
  5710. size,
  5711. sizeof(size),
  5712. "%.1fk",
  5713. (double)de->file.size / 1024.0);
  5714. } else if (de->file.size < 0x40000000) {
  5715. mg_snprintf(de->conn,
  5716. NULL, /* Buffer is big enough */
  5717. size,
  5718. sizeof(size),
  5719. "%.1fM",
  5720. (double)de->file.size / 1048576);
  5721. } else {
  5722. mg_snprintf(de->conn,
  5723. NULL, /* Buffer is big enough */
  5724. size,
  5725. sizeof(size),
  5726. "%.1fG",
  5727. (double)de->file.size / 1073741824);
  5728. }
  5729. }
  5730. /* Note: mg_snprintf will not cause a buffer overflow above.
  5731. * So, string truncation checks are not required here. */
  5732. tm = localtime(&de->file.last_modified);
  5733. if (tm != NULL) {
  5734. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  5735. } else {
  5736. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  5737. mod[sizeof(mod) - 1] = '\0';
  5738. }
  5739. mg_url_encode(de->file_name, href, sizeof(href));
  5740. de->conn->num_bytes_sent +=
  5741. mg_printf(de->conn,
  5742. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  5743. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  5744. de->conn->request_info.local_uri,
  5745. href,
  5746. de->file.is_directory ? "/" : "",
  5747. de->file_name,
  5748. de->file.is_directory ? "/" : "",
  5749. mod,
  5750. size);
  5751. }
  5752. /* This function is called from send_directory() and used for
  5753. * sorting directory entries by size, or name, or modification time.
  5754. * On windows, __cdecl specification is needed in case if project is built
  5755. * with __stdcall convention. qsort always requires __cdels callback. */
  5756. static int WINCDECL
  5757. compare_dir_entries(const void *p1, const void *p2)
  5758. {
  5759. if (p1 && p2) {
  5760. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  5761. const char *query_string = a->conn->request_info.query_string;
  5762. int cmp_result = 0;
  5763. if (query_string == NULL) {
  5764. query_string = "na";
  5765. }
  5766. if (a->file.is_directory && !b->file.is_directory) {
  5767. return -1; /* Always put directories on top */
  5768. } else if (!a->file.is_directory && b->file.is_directory) {
  5769. return 1; /* Always put directories on top */
  5770. } else if (*query_string == 'n') {
  5771. cmp_result = strcmp(a->file_name, b->file_name);
  5772. } else if (*query_string == 's') {
  5773. cmp_result = (a->file.size == b->file.size)
  5774. ? 0
  5775. : ((a->file.size > b->file.size) ? 1 : -1);
  5776. } else if (*query_string == 'd') {
  5777. cmp_result =
  5778. (a->file.last_modified == b->file.last_modified)
  5779. ? 0
  5780. : ((a->file.last_modified > b->file.last_modified) ? 1
  5781. : -1);
  5782. }
  5783. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  5784. }
  5785. return 0;
  5786. }
  5787. static int
  5788. must_hide_file(struct mg_connection *conn, const char *path)
  5789. {
  5790. if (conn && conn->ctx) {
  5791. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  5792. const char *pattern = conn->ctx->config[HIDE_FILES];
  5793. return match_prefix(pw_pattern, strlen(pw_pattern), path) > 0
  5794. || (pattern != NULL
  5795. && match_prefix(pattern, strlen(pattern), path) > 0);
  5796. }
  5797. return 0;
  5798. }
  5799. static int
  5800. scan_directory(struct mg_connection *conn,
  5801. const char *dir,
  5802. void *data,
  5803. void (*cb)(struct de *, void *))
  5804. {
  5805. char path[PATH_MAX];
  5806. struct dirent *dp;
  5807. DIR *dirp;
  5808. struct de de;
  5809. int truncated;
  5810. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  5811. return 0;
  5812. } else {
  5813. de.conn = conn;
  5814. while ((dp = mg_readdir(dirp)) != NULL) {
  5815. /* Do not show current dir and hidden files */
  5816. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  5817. || must_hide_file(conn, dp->d_name)) {
  5818. continue;
  5819. }
  5820. mg_snprintf(
  5821. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  5822. /* If we don't memset stat structure to zero, mtime will have
  5823. * garbage and strftime() will segfault later on in
  5824. * print_dir_entry(). memset is required only if mg_stat()
  5825. * fails. For more details, see
  5826. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  5827. memset(&de.file, 0, sizeof(de.file));
  5828. if (truncated) {
  5829. /* If the path is not complete, skip processing. */
  5830. continue;
  5831. }
  5832. if (!mg_stat(conn, path, &de.file)) {
  5833. mg_cry(conn,
  5834. "%s: mg_stat(%s) failed: %s",
  5835. __func__,
  5836. path,
  5837. strerror(ERRNO));
  5838. }
  5839. de.file_name = dp->d_name;
  5840. cb(&de, data);
  5841. }
  5842. (void)mg_closedir(dirp);
  5843. }
  5844. return 1;
  5845. }
  5846. #if !defined(NO_FILES)
  5847. static int
  5848. remove_directory(struct mg_connection *conn, const char *dir)
  5849. {
  5850. char path[PATH_MAX];
  5851. struct dirent *dp;
  5852. DIR *dirp;
  5853. struct de de;
  5854. int truncated;
  5855. int ok = 1;
  5856. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  5857. return 0;
  5858. } else {
  5859. de.conn = conn;
  5860. while ((dp = mg_readdir(dirp)) != NULL) {
  5861. /* Do not show current dir (but show hidden files as they will
  5862. * also be removed) */
  5863. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  5864. continue;
  5865. }
  5866. mg_snprintf(
  5867. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  5868. /* If we don't memset stat structure to zero, mtime will have
  5869. * garbage and strftime() will segfault later on in
  5870. * print_dir_entry(). memset is required only if mg_stat()
  5871. * fails. For more details, see
  5872. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  5873. memset(&de.file, 0, sizeof(de.file));
  5874. if (truncated) {
  5875. /* Do not delete anything shorter */
  5876. ok = 0;
  5877. continue;
  5878. }
  5879. if (!mg_stat(conn, path, &de.file)) {
  5880. mg_cry(conn,
  5881. "%s: mg_stat(%s) failed: %s",
  5882. __func__,
  5883. path,
  5884. strerror(ERRNO));
  5885. ok = 0;
  5886. }
  5887. if (de.file.is_directory) {
  5888. if (remove_directory(conn, path) == 0) {
  5889. ok = 0;
  5890. }
  5891. } else {
  5892. /* This will fail file is the file is in memory */
  5893. if (mg_remove(conn, path) == 0) {
  5894. ok = 0;
  5895. }
  5896. }
  5897. }
  5898. (void)mg_closedir(dirp);
  5899. IGNORE_UNUSED_RESULT(rmdir(dir));
  5900. }
  5901. return ok;
  5902. }
  5903. #endif
  5904. struct dir_scan_data {
  5905. struct de *entries;
  5906. unsigned int num_entries;
  5907. unsigned int arr_size;
  5908. };
  5909. /* Behaves like realloc(), but frees original pointer on failure */
  5910. static void *
  5911. realloc2(void *ptr, size_t size)
  5912. {
  5913. void *new_ptr = mg_realloc(ptr, size);
  5914. if (new_ptr == NULL) {
  5915. mg_free(ptr);
  5916. }
  5917. return new_ptr;
  5918. }
  5919. static void
  5920. dir_scan_callback(struct de *de, void *data)
  5921. {
  5922. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  5923. if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {
  5924. dsd->arr_size *= 2;
  5925. dsd->entries =
  5926. (struct de *)realloc2(dsd->entries,
  5927. dsd->arr_size * sizeof(dsd->entries[0]));
  5928. }
  5929. if (dsd->entries == NULL) {
  5930. /* TODO(lsm, low): propagate an error to the caller */
  5931. dsd->num_entries = 0;
  5932. } else {
  5933. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  5934. dsd->entries[dsd->num_entries].file = de->file;
  5935. dsd->entries[dsd->num_entries].conn = de->conn;
  5936. dsd->num_entries++;
  5937. }
  5938. }
  5939. static void
  5940. handle_directory_request(struct mg_connection *conn, const char *dir)
  5941. {
  5942. unsigned int i;
  5943. int sort_direction;
  5944. struct dir_scan_data data = {NULL, 0, 128};
  5945. char date[64];
  5946. time_t curtime = time(NULL);
  5947. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  5948. send_http_error(conn,
  5949. 500,
  5950. "Error: Cannot open directory\nopendir(%s): %s",
  5951. dir,
  5952. strerror(ERRNO));
  5953. return;
  5954. }
  5955. gmt_time_string(date, sizeof(date), &curtime);
  5956. if (!conn) {
  5957. return;
  5958. }
  5959. sort_direction = ((conn->request_info.query_string != NULL)
  5960. && (conn->request_info.query_string[1] == 'd'))
  5961. ? 'a'
  5962. : 'd';
  5963. conn->must_close = 1;
  5964. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  5965. send_static_cache_header(conn);
  5966. mg_printf(conn,
  5967. "Date: %s\r\n"
  5968. "Connection: close\r\n"
  5969. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  5970. date);
  5971. conn->num_bytes_sent +=
  5972. mg_printf(conn,
  5973. "<html><head><title>Index of %s</title>"
  5974. "<style>th {text-align: left;}</style></head>"
  5975. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  5976. "<tr><th><a href=\"?n%c\">Name</a></th>"
  5977. "<th><a href=\"?d%c\">Modified</a></th>"
  5978. "<th><a href=\"?s%c\">Size</a></th></tr>"
  5979. "<tr><td colspan=\"3\"><hr></td></tr>",
  5980. conn->request_info.local_uri,
  5981. conn->request_info.local_uri,
  5982. sort_direction,
  5983. sort_direction,
  5984. sort_direction);
  5985. /* Print first entry - link to a parent directory */
  5986. conn->num_bytes_sent +=
  5987. mg_printf(conn,
  5988. "<tr><td><a href=\"%s%s\">%s</a></td>"
  5989. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  5990. conn->request_info.local_uri,
  5991. "..",
  5992. "Parent directory",
  5993. "-",
  5994. "-");
  5995. /* Sort and print directory entries */
  5996. if (data.entries != NULL) {
  5997. qsort(data.entries,
  5998. (size_t)data.num_entries,
  5999. sizeof(data.entries[0]),
  6000. compare_dir_entries);
  6001. for (i = 0; i < data.num_entries; i++) {
  6002. print_dir_entry(&data.entries[i]);
  6003. mg_free(data.entries[i].file_name);
  6004. }
  6005. mg_free(data.entries);
  6006. }
  6007. conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");
  6008. conn->status_code = 200;
  6009. }
  6010. /* Send len bytes from the opened file to the client. */
  6011. static void
  6012. send_file_data(struct mg_connection *conn,
  6013. struct mg_file *filep,
  6014. int64_t offset,
  6015. int64_t len)
  6016. {
  6017. char buf[MG_BUF_LEN];
  6018. int to_read, num_read, num_written;
  6019. int64_t size;
  6020. if (!filep || !conn) {
  6021. return;
  6022. }
  6023. /* Sanity check the offset */
  6024. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  6025. : (int64_t)(filep->stat.size);
  6026. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  6027. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  6028. /* file stored in memory */
  6029. if (len > size - offset) {
  6030. len = size - offset;
  6031. }
  6032. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  6033. } else if (len > 0 && filep->access.fp != NULL) {
  6034. /* file stored on disk */
  6035. #if defined(__linux__)
  6036. /* sendfile is only available for Linux */
  6037. if ((conn->ssl == 0) && (conn->throttle == 0)
  6038. && (!mg_strcasecmp(conn->ctx->config[ALLOW_SENDFILE_CALL],
  6039. "yes"))) {
  6040. off_t sf_offs = (off_t)offset;
  6041. ssize_t sf_sent;
  6042. int sf_file = fileno(filep->access.fp);
  6043. int loop_cnt = 0;
  6044. do {
  6045. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  6046. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  6047. size_t sf_tosend =
  6048. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  6049. sf_sent =
  6050. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  6051. if (sf_sent > 0) {
  6052. conn->num_bytes_sent += sf_sent;
  6053. len -= sf_sent;
  6054. offset += sf_sent;
  6055. } else if (loop_cnt == 0) {
  6056. /* This file can not be sent using sendfile.
  6057. * This might be the case for pseudo-files in the
  6058. * /sys/ and /proc/ file system.
  6059. * Use the regular user mode copy code instead. */
  6060. break;
  6061. } else if (sf_sent == 0) {
  6062. /* No error, but 0 bytes sent. May be EOF? */
  6063. return;
  6064. }
  6065. loop_cnt++;
  6066. } while ((len > 0) && (sf_sent >= 0));
  6067. if (sf_sent > 0) {
  6068. return; /* OK */
  6069. }
  6070. /* sf_sent<0 means error, thus fall back to the classic way */
  6071. /* This is always the case, if sf_file is not a "normal" file,
  6072. * e.g., for sending data from the output of a CGI process. */
  6073. offset = (int64_t)sf_offs;
  6074. }
  6075. #endif
  6076. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  6077. mg_cry(conn, "%s: fseeko() failed: %s", __func__, strerror(ERRNO));
  6078. send_http_error(
  6079. conn,
  6080. 500,
  6081. "%s",
  6082. "Error: Unable to access file at requested position.");
  6083. } else {
  6084. while (len > 0) {
  6085. /* Calculate how much to read from the file in the buffer */
  6086. to_read = sizeof(buf);
  6087. if ((int64_t)to_read > len) {
  6088. to_read = (int)len;
  6089. }
  6090. /* Read from file, exit the loop on error */
  6091. if ((num_read =
  6092. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  6093. <= 0) {
  6094. break;
  6095. }
  6096. /* Send read bytes to the client, exit the loop on error */
  6097. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  6098. != num_read) {
  6099. break;
  6100. }
  6101. /* Both read and were successful, adjust counters */
  6102. conn->num_bytes_sent += num_written;
  6103. len -= num_written;
  6104. }
  6105. }
  6106. }
  6107. }
  6108. static int
  6109. parse_range_header(const char *header, int64_t *a, int64_t *b)
  6110. {
  6111. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  6112. }
  6113. static void
  6114. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  6115. {
  6116. if (filestat != NULL && buf != NULL) {
  6117. mg_snprintf(NULL,
  6118. NULL, /* All calls to construct_etag use 64 byte buffer */
  6119. buf,
  6120. buf_len,
  6121. "\"%lx.%" INT64_FMT "\"",
  6122. (unsigned long)filestat->last_modified,
  6123. filestat->size);
  6124. }
  6125. }
  6126. static void
  6127. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  6128. {
  6129. if (filep != NULL && filep->fp != NULL) {
  6130. #ifdef _WIN32
  6131. (void)conn; /* Unused. */
  6132. #else
  6133. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  6134. mg_cry(conn,
  6135. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  6136. __func__,
  6137. strerror(ERRNO));
  6138. }
  6139. #endif
  6140. }
  6141. }
  6142. static void
  6143. handle_static_file_request(struct mg_connection *conn,
  6144. const char *path,
  6145. struct mg_file *filep,
  6146. const char *mime_type,
  6147. const char *additional_headers)
  6148. {
  6149. char date[64], lm[64], etag[64];
  6150. char range[128]; /* large enough, so there will be no overflow */
  6151. const char *msg = "OK", *hdr;
  6152. time_t curtime = time(NULL);
  6153. int64_t cl, r1, r2;
  6154. struct vec mime_vec;
  6155. int n, truncated;
  6156. char gz_path[PATH_MAX];
  6157. const char *encoding = "";
  6158. const char *cors1, *cors2, *cors3;
  6159. if (conn == NULL || conn->ctx == NULL || filep == NULL) {
  6160. return;
  6161. }
  6162. if (mime_type == NULL) {
  6163. get_mime_type(conn->ctx, path, &mime_vec);
  6164. } else {
  6165. mime_vec.ptr = mime_type;
  6166. mime_vec.len = strlen(mime_type);
  6167. }
  6168. if (filep->stat.size > INT64_MAX) {
  6169. send_http_error(conn,
  6170. 500,
  6171. "Error: File size is too large to send\n%" INT64_FMT,
  6172. filep->stat.size);
  6173. }
  6174. cl = (int64_t)filep->stat.size;
  6175. conn->status_code = 200;
  6176. range[0] = '\0';
  6177. /* if this file is in fact a pre-gzipped file, rewrite its filename
  6178. * it's important to rewrite the filename after resolving
  6179. * the mime type from it, to preserve the actual file's type */
  6180. if (filep->stat.is_gzipped) {
  6181. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  6182. if (truncated) {
  6183. send_http_error(conn,
  6184. 500,
  6185. "Error: Path of zipped file too long (%s)",
  6186. path);
  6187. return;
  6188. }
  6189. path = gz_path;
  6190. encoding = "Content-Encoding: gzip\r\n";
  6191. }
  6192. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  6193. send_http_error(conn,
  6194. 500,
  6195. "Error: Cannot open file\nfopen(%s): %s",
  6196. path,
  6197. strerror(ERRNO));
  6198. return;
  6199. }
  6200. fclose_on_exec(&filep->access, conn);
  6201. /* If Range: header specified, act accordingly */
  6202. r1 = r2 = 0;
  6203. hdr = mg_get_header(conn, "Range");
  6204. if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 && r1 >= 0
  6205. && r2 >= 0) {
  6206. /* actually, range requests don't play well with a pre-gzipped
  6207. * file (since the range is specified in the uncompressed space) */
  6208. if (filep->stat.is_gzipped) {
  6209. send_http_error(
  6210. conn,
  6211. 501,
  6212. "%s",
  6213. "Error: Range requests in gzipped files are not supported");
  6214. (void)mg_fclose(
  6215. &filep->access); /* ignore error on read only file */
  6216. return;
  6217. }
  6218. conn->status_code = 206;
  6219. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  6220. mg_snprintf(conn,
  6221. NULL, /* range buffer is big enough */
  6222. range,
  6223. sizeof(range),
  6224. "Content-Range: bytes "
  6225. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  6226. r1,
  6227. r1 + cl - 1,
  6228. filep->stat.size);
  6229. msg = "Partial Content";
  6230. }
  6231. hdr = mg_get_header(conn, "Origin");
  6232. if (hdr) {
  6233. /* Cross-origin resource sharing (CORS), see
  6234. * http://www.html5rocks.com/en/tutorials/cors/,
  6235. * http://www.html5rocks.com/static/images/cors_server_flowchart.png -
  6236. * preflight is not supported for files. */
  6237. cors1 = "Access-Control-Allow-Origin: ";
  6238. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  6239. cors3 = "\r\n";
  6240. } else {
  6241. cors1 = cors2 = cors3 = "";
  6242. }
  6243. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
  6244. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  6245. gmt_time_string(date, sizeof(date), &curtime);
  6246. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  6247. construct_etag(etag, sizeof(etag), &filep->stat);
  6248. (void)mg_printf(conn,
  6249. "HTTP/1.1 %d %s\r\n"
  6250. "%s%s%s"
  6251. "Date: %s\r\n",
  6252. conn->status_code,
  6253. msg,
  6254. cors1,
  6255. cors2,
  6256. cors3,
  6257. date);
  6258. send_static_cache_header(conn);
  6259. (void)mg_printf(conn,
  6260. "Last-Modified: %s\r\n"
  6261. "Etag: %s\r\n"
  6262. "Content-Type: %.*s\r\n"
  6263. "Content-Length: %" INT64_FMT "\r\n"
  6264. "Connection: %s\r\n"
  6265. "Accept-Ranges: bytes\r\n"
  6266. "%s%s",
  6267. lm,
  6268. etag,
  6269. (int)mime_vec.len,
  6270. mime_vec.ptr,
  6271. cl,
  6272. suggest_connection_header(conn),
  6273. range,
  6274. encoding);
  6275. /* The previous code must not add any header starting with X- to make
  6276. * sure no one of the additional_headers is included twice */
  6277. if (additional_headers != NULL) {
  6278. (void)mg_printf(conn,
  6279. "%.*s\r\n\r\n",
  6280. (int)strlen(additional_headers),
  6281. additional_headers);
  6282. } else {
  6283. (void)mg_printf(conn, "\r\n");
  6284. }
  6285. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  6286. send_file_data(conn, filep, r1, cl);
  6287. }
  6288. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  6289. }
  6290. #if !defined(NO_CACHING)
  6291. static void
  6292. handle_not_modified_static_file_request(struct mg_connection *conn,
  6293. struct mg_file *filep)
  6294. {
  6295. char date[64], lm[64], etag[64];
  6296. time_t curtime = time(NULL);
  6297. if (conn == NULL || filep == NULL) {
  6298. return;
  6299. }
  6300. conn->status_code = 304;
  6301. gmt_time_string(date, sizeof(date), &curtime);
  6302. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  6303. construct_etag(etag, sizeof(etag), &filep->stat);
  6304. (void)mg_printf(conn,
  6305. "HTTP/1.1 %d %s\r\n"
  6306. "Date: %s\r\n",
  6307. conn->status_code,
  6308. mg_get_response_code_text(conn, conn->status_code),
  6309. date);
  6310. send_static_cache_header(conn);
  6311. (void)mg_printf(conn,
  6312. "Last-Modified: %s\r\n"
  6313. "Etag: %s\r\n"
  6314. "Connection: %s\r\n"
  6315. "\r\n",
  6316. lm,
  6317. etag,
  6318. suggest_connection_header(conn));
  6319. }
  6320. #endif
  6321. void
  6322. mg_send_file(struct mg_connection *conn, const char *path)
  6323. {
  6324. mg_send_mime_file(conn, path, NULL);
  6325. }
  6326. void
  6327. mg_send_mime_file(struct mg_connection *conn,
  6328. const char *path,
  6329. const char *mime_type)
  6330. {
  6331. mg_send_mime_file2(conn, path, mime_type, NULL);
  6332. }
  6333. void
  6334. mg_send_mime_file2(struct mg_connection *conn,
  6335. const char *path,
  6336. const char *mime_type,
  6337. const char *additional_headers)
  6338. {
  6339. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6340. if (mg_stat(conn, path, &file.stat)) {
  6341. if (file.stat.is_directory) {
  6342. if (!conn) {
  6343. return;
  6344. }
  6345. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  6346. "yes")) {
  6347. handle_directory_request(conn, path);
  6348. } else {
  6349. send_http_error(conn,
  6350. 403,
  6351. "%s",
  6352. "Error: Directory listing denied");
  6353. }
  6354. } else {
  6355. handle_static_file_request(
  6356. conn, path, &file, mime_type, additional_headers);
  6357. }
  6358. } else {
  6359. send_http_error(conn, 404, "%s", "Error: File not found");
  6360. }
  6361. }
  6362. /* For a given PUT path, create all intermediate subdirectories.
  6363. * Return 0 if the path itself is a directory.
  6364. * Return 1 if the path leads to a file.
  6365. * Return -1 for if the path is too long.
  6366. * Return -2 if path can not be created.
  6367. */
  6368. static int
  6369. put_dir(struct mg_connection *conn, const char *path)
  6370. {
  6371. char buf[PATH_MAX];
  6372. const char *s, *p;
  6373. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6374. size_t len;
  6375. int res = 1;
  6376. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  6377. len = (size_t)(p - path);
  6378. if (len >= sizeof(buf)) {
  6379. /* path too long */
  6380. res = -1;
  6381. break;
  6382. }
  6383. memcpy(buf, path, len);
  6384. buf[len] = '\0';
  6385. /* Try to create intermediate directory */
  6386. DEBUG_TRACE("mkdir(%s)", buf);
  6387. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  6388. /* path does not exixt and can not be created */
  6389. res = -2;
  6390. break;
  6391. }
  6392. /* Is path itself a directory? */
  6393. if (p[1] == '\0') {
  6394. res = 0;
  6395. }
  6396. }
  6397. return res;
  6398. }
  6399. static void
  6400. remove_bad_file(const struct mg_connection *conn, const char *path)
  6401. {
  6402. int r = mg_remove(conn, path);
  6403. if (r != 0) {
  6404. mg_cry(conn, "%s: Cannot remove invalid file %s", __func__, path);
  6405. }
  6406. }
  6407. long long
  6408. mg_store_body(struct mg_connection *conn, const char *path)
  6409. {
  6410. char buf[MG_BUF_LEN];
  6411. long long len = 0;
  6412. int ret, n;
  6413. struct mg_file fi;
  6414. if (conn->consumed_content != 0) {
  6415. mg_cry(conn, "%s: Contents already consumed", __func__);
  6416. return -11;
  6417. }
  6418. ret = put_dir(conn, path);
  6419. if (ret < 0) {
  6420. /* -1 for path too long,
  6421. * -2 for path can not be created. */
  6422. return ret;
  6423. }
  6424. if (ret != 1) {
  6425. /* Return 0 means, path itself is a directory. */
  6426. return 0;
  6427. }
  6428. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  6429. return -12;
  6430. }
  6431. ret = mg_read(conn, buf, sizeof(buf));
  6432. while (ret > 0) {
  6433. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  6434. if (n != ret) {
  6435. (void)mg_fclose(
  6436. &fi.access); /* File is bad and will be removed anyway. */
  6437. remove_bad_file(conn, path);
  6438. return -13;
  6439. }
  6440. ret = mg_read(conn, buf, sizeof(buf));
  6441. }
  6442. /* File is open for writing. If fclose fails, there was probably an
  6443. * error flushing the buffer to disk, so the file on disk might be
  6444. * broken. Delete it and return an error to the caller. */
  6445. if (mg_fclose(&fi.access) != 0) {
  6446. remove_bad_file(conn, path);
  6447. return -14;
  6448. }
  6449. return len;
  6450. }
  6451. /* Parse HTTP headers from the given buffer, advance buf pointer
  6452. * to the point where parsing stopped.
  6453. * All parameters must be valid pointers (not NULL).
  6454. * Return <0 on error. */
  6455. static int
  6456. parse_http_headers(char **buf, struct mg_request_info *ri)
  6457. {
  6458. int i;
  6459. ri->num_headers = 0;
  6460. for (i = 0; i < (int)ARRAY_SIZE(ri->http_headers); i++) {
  6461. char *dp = *buf;
  6462. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  6463. dp++;
  6464. }
  6465. if (dp == *buf) {
  6466. /* End of headers reached. */
  6467. break;
  6468. }
  6469. if (*dp != ':') {
  6470. /* This is not a valid field. */
  6471. return -1;
  6472. }
  6473. /* End of header key (*dp == ':') */
  6474. /* Truncate here and set the key name */
  6475. *dp = 0;
  6476. ri->http_headers[i].name = *buf;
  6477. do {
  6478. dp++;
  6479. } while (*dp == ' ');
  6480. /* The rest of the line is the value */
  6481. ri->http_headers[i].value = dp;
  6482. *buf = dp + strcspn(dp, "\r\n");
  6483. if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) {
  6484. *buf = NULL;
  6485. }
  6486. ri->num_headers = i + 1;
  6487. if (*buf) {
  6488. (*buf)[0] = 0;
  6489. (*buf)[1] = 0;
  6490. *buf += 2;
  6491. } else {
  6492. *buf = dp;
  6493. break;
  6494. }
  6495. if ((*buf)[0] == '\r') {
  6496. /* This is the end of the header */
  6497. break;
  6498. }
  6499. }
  6500. return ri->num_headers;
  6501. }
  6502. static int
  6503. is_valid_http_method(const char *method)
  6504. {
  6505. return !strcmp(method, "GET") /* HTTP (RFC 2616) */
  6506. || !strcmp(method, "POST") /* HTTP (RFC 2616) */
  6507. || !strcmp(method, "HEAD") /* HTTP (RFC 2616) */
  6508. || !strcmp(method, "PUT") /* HTTP (RFC 2616) */
  6509. || !strcmp(method, "DELETE") /* HTTP (RFC 2616) */
  6510. || !strcmp(method, "OPTIONS") /* HTTP (RFC 2616) */
  6511. /* TRACE method (RFC 2616) is not supported for security reasons */
  6512. || !strcmp(method, "CONNECT") /* HTTP (RFC 2616) */
  6513. || !strcmp(method, "PROPFIND") /* WEBDAV (RFC 2518) */
  6514. || !strcmp(method, "MKCOL") /* WEBDAV (RFC 2518) */
  6515. /* Unsupported WEBDAV Methods: */
  6516. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  6517. /* + 11 methods from RFC 3253 */
  6518. /* ORDERPATCH (RFC 3648) */
  6519. /* ACL (RFC 3744) */
  6520. /* SEARCH (RFC 5323) */
  6521. /* + MicroSoft extensions
  6522. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  6523. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  6524. || !strcmp(method, "PATCH"); /* PATCH method (RFC 5789) */
  6525. }
  6526. /* Parse HTTP request, fill in mg_request_info structure.
  6527. * This function modifies the buffer by NUL-terminating
  6528. * HTTP request components, header names and header values.
  6529. * Parameters:
  6530. * buf (in/out): pointer to the HTTP header to parse and split
  6531. * len (in): length of HTTP header buffer
  6532. * re (out): parsed header as mg_request_info
  6533. * buf and ri must be valid pointers (not NULL), len>0.
  6534. * Returns <0 on error. */
  6535. static int
  6536. parse_http_message(char *buf, int len, struct mg_request_info *ri)
  6537. {
  6538. int is_request, request_length;
  6539. char *start_line;
  6540. request_length = get_request_len(buf, len);
  6541. if (request_length > 0) {
  6542. /* Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_addr,
  6543. * remote_port */
  6544. ri->remote_user = ri->request_method = ri->request_uri =
  6545. ri->http_version = NULL;
  6546. ri->num_headers = 0;
  6547. buf[request_length - 1] = '\0';
  6548. /* RFC says that all initial whitespaces should be ingored */
  6549. while (*buf != '\0' && isspace(*(unsigned char *)buf)) {
  6550. buf++;
  6551. }
  6552. start_line = skip(&buf, "\r\n");
  6553. ri->request_method = skip(&start_line, " ");
  6554. ri->request_uri = skip(&start_line, " ");
  6555. ri->http_version = start_line;
  6556. /* HTTP message could be either HTTP request:
  6557. * "GET / HTTP/1.0 ..."
  6558. * or a HTTP response:
  6559. * "HTTP/1.0 200 OK ..."
  6560. * otherwise it is invalid.
  6561. */
  6562. is_request = is_valid_http_method(ri->request_method);
  6563. if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0)
  6564. || (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
  6565. /* Not a valid request or response: invalid */
  6566. return -1;
  6567. }
  6568. if (is_request) {
  6569. ri->http_version += 5;
  6570. }
  6571. if (parse_http_headers(&buf, ri) < 0) {
  6572. /* Error while parsing headers */
  6573. return -1;
  6574. }
  6575. }
  6576. return request_length;
  6577. }
  6578. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  6579. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  6580. * buffer (which marks the end of HTTP request). Buffer buf may already
  6581. * have some data. The length of the data is stored in nread.
  6582. * Upon every read operation, increase nread by the number of bytes read. */
  6583. static int
  6584. read_request(FILE *fp,
  6585. struct mg_connection *conn,
  6586. char *buf,
  6587. int bufsiz,
  6588. int *nread)
  6589. {
  6590. int request_len, n = 0;
  6591. struct timespec last_action_time;
  6592. double request_timeout;
  6593. if (!conn) {
  6594. return 0;
  6595. }
  6596. memset(&last_action_time, 0, sizeof(last_action_time));
  6597. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  6598. /* value of request_timeout is in seconds, config in milliseconds */
  6599. request_timeout = atof(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  6600. } else {
  6601. request_timeout = -1.0;
  6602. }
  6603. if (conn->handled_requests > 0) {
  6604. if (conn->ctx->config[KEEP_ALIVE_TIMEOUT]) {
  6605. request_timeout =
  6606. atof(conn->ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  6607. }
  6608. }
  6609. request_len = get_request_len(buf, *nread);
  6610. /* first time reading from this connection */
  6611. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  6612. while (request_len == 0) {
  6613. /* Full request not yet received */
  6614. if (conn->ctx->stop_flag != 0) {
  6615. /* Server is to be stopped. */
  6616. return -1;
  6617. }
  6618. if (*nread >= bufsiz) {
  6619. /* Request too long */
  6620. return -2;
  6621. }
  6622. n = pull(fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  6623. if (n < 0) {
  6624. /* Receive error */
  6625. return -1;
  6626. }
  6627. *nread += n;
  6628. request_len = get_request_len(buf, *nread);
  6629. if ((request_len == 0) && (request_timeout >= 0)) {
  6630. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  6631. > request_timeout) {
  6632. /* Timeout */
  6633. return -1;
  6634. }
  6635. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  6636. }
  6637. }
  6638. return request_len;
  6639. }
  6640. #if !defined(NO_FILES)
  6641. /* For given directory path, substitute it to valid index file.
  6642. * Return 1 if index file has been found, 0 if not found.
  6643. * If the file is found, it's stats is returned in stp. */
  6644. static int
  6645. substitute_index_file(struct mg_connection *conn,
  6646. char *path,
  6647. size_t path_len,
  6648. struct mg_file *filep)
  6649. {
  6650. if (conn && conn->ctx) {
  6651. const char *list = conn->ctx->config[INDEX_FILES];
  6652. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6653. struct vec filename_vec;
  6654. size_t n = strlen(path);
  6655. int found = 0;
  6656. /* The 'path' given to us points to the directory. Remove all trailing
  6657. * directory separator characters from the end of the path, and
  6658. * then append single directory separator character. */
  6659. while (n > 0 && path[n - 1] == '/') {
  6660. n--;
  6661. }
  6662. path[n] = '/';
  6663. /* Traverse index files list. For each entry, append it to the given
  6664. * path and see if the file exists. If it exists, break the loop */
  6665. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6666. /* Ignore too long entries that may overflow path buffer */
  6667. if (filename_vec.len > path_len - (n + 2)) {
  6668. continue;
  6669. }
  6670. /* Prepare full path to the index file */
  6671. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6672. /* Does it exist? */
  6673. if (mg_stat(conn, path, &file.stat)) {
  6674. /* Yes it does, break the loop */
  6675. *filep = file;
  6676. found = 1;
  6677. break;
  6678. }
  6679. }
  6680. /* If no index file exists, restore directory path */
  6681. if (!found) {
  6682. path[n] = '\0';
  6683. }
  6684. return found;
  6685. }
  6686. return 0;
  6687. }
  6688. #endif
  6689. #if !defined(NO_CACHING)
  6690. /* Return True if we should reply 304 Not Modified. */
  6691. static int
  6692. is_not_modified(const struct mg_connection *conn,
  6693. const struct mg_file_stat *filestat)
  6694. {
  6695. char etag[64];
  6696. const char *ims = mg_get_header(conn, "If-Modified-Since");
  6697. const char *inm = mg_get_header(conn, "If-None-Match");
  6698. construct_etag(etag, sizeof(etag), filestat);
  6699. return (inm != NULL && !mg_strcasecmp(etag, inm))
  6700. || ((ims != NULL)
  6701. && (filestat->last_modified <= parse_date_string(ims)));
  6702. }
  6703. #endif /* !NO_CACHING */
  6704. #if !defined(NO_CGI) || !defined(NO_FILES)
  6705. static int
  6706. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  6707. {
  6708. const char *expect, *body;
  6709. char buf[MG_BUF_LEN];
  6710. int to_read, nread, success = 0;
  6711. int64_t buffered_len;
  6712. double timeout = -1.0;
  6713. if (!conn) {
  6714. return 0;
  6715. }
  6716. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  6717. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  6718. }
  6719. expect = mg_get_header(conn, "Expect");
  6720. /* assert(fp != NULL); */
  6721. if (!fp) {
  6722. send_http_error(conn, 500, "%s", "Error: NULL File");
  6723. return 0;
  6724. }
  6725. if (conn->content_len == -1 && !conn->is_chunked) {
  6726. /* Content length is not specified by the client. */
  6727. send_http_error(conn,
  6728. 411,
  6729. "%s",
  6730. "Error: Client did not specify content length");
  6731. } else if ((expect != NULL)
  6732. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  6733. /* Client sent an "Expect: xyz" header and xyz is not 100-continue. */
  6734. send_http_error(conn,
  6735. 417,
  6736. "Error: Can not fulfill expectation %s",
  6737. expect);
  6738. } else {
  6739. if (expect != NULL) {
  6740. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  6741. conn->status_code = 100;
  6742. } else {
  6743. conn->status_code = 200;
  6744. }
  6745. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  6746. - conn->consumed_content;
  6747. /* assert(buffered_len >= 0); */
  6748. /* assert(conn->consumed_content == 0); */
  6749. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  6750. send_http_error(conn, 500, "%s", "Error: Size mismatch");
  6751. return 0;
  6752. }
  6753. if (buffered_len > 0) {
  6754. if ((int64_t)buffered_len > conn->content_len) {
  6755. buffered_len = (int)conn->content_len;
  6756. }
  6757. body = conn->buf + conn->request_len + conn->consumed_content;
  6758. push_all(conn->ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  6759. conn->consumed_content += buffered_len;
  6760. }
  6761. nread = 0;
  6762. while (conn->consumed_content < conn->content_len) {
  6763. to_read = sizeof(buf);
  6764. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  6765. to_read = (int)(conn->content_len - conn->consumed_content);
  6766. }
  6767. nread = pull(NULL, conn, buf, to_read, timeout);
  6768. if (nread <= 0
  6769. || push_all(conn->ctx, fp, sock, ssl, buf, nread) != nread) {
  6770. break;
  6771. }
  6772. conn->consumed_content += nread;
  6773. }
  6774. if (conn->consumed_content == conn->content_len) {
  6775. success = (nread >= 0);
  6776. }
  6777. /* Each error code path in this function must send an error */
  6778. if (!success) {
  6779. /* NOTE: Maybe some data has already been sent. */
  6780. /* TODO (low): If some data has been sent, a correct error
  6781. * reply can no longer be sent, so just close the connection */
  6782. send_http_error(conn, 500, "%s", "");
  6783. }
  6784. }
  6785. return success;
  6786. }
  6787. #endif
  6788. #if !defined(NO_CGI)
  6789. /* This structure helps to create an environment for the spawned CGI program.
  6790. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  6791. * last element must be NULL.
  6792. * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  6793. * strings must reside in a contiguous buffer. The end of the buffer is
  6794. * marked by two '\0' characters.
  6795. * We satisfy both worlds: we create an envp array (which is vars), all
  6796. * entries are actually pointers inside buf. */
  6797. struct cgi_environment {
  6798. struct mg_connection *conn;
  6799. /* Data block */
  6800. char *buf; /* Environment buffer */
  6801. size_t buflen; /* Space available in buf */
  6802. size_t bufused; /* Space taken in buf */
  6803. /* Index block */
  6804. char **var; /* char **envp */
  6805. size_t varlen; /* Number of variables available in var */
  6806. size_t varused; /* Number of variables stored in var */
  6807. };
  6808. static void addenv(struct cgi_environment *env,
  6809. PRINTF_FORMAT_STRING(const char *fmt),
  6810. ...) PRINTF_ARGS(2, 3);
  6811. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  6812. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  6813. static void
  6814. addenv(struct cgi_environment *env, const char *fmt, ...)
  6815. {
  6816. size_t n, space;
  6817. int truncated = 0;
  6818. char *added;
  6819. va_list ap;
  6820. /* Calculate how much space is left in the buffer */
  6821. space = (env->buflen - env->bufused);
  6822. /* Calculate an estimate for the required space */
  6823. n = strlen(fmt) + 2 + 128;
  6824. do {
  6825. if (space <= n) {
  6826. /* Allocate new buffer */
  6827. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  6828. added = (char *)mg_realloc(env->buf, n);
  6829. if (!added) {
  6830. /* Out of memory */
  6831. mg_cry(env->conn,
  6832. "%s: Cannot allocate memory for CGI variable [%s]",
  6833. __func__,
  6834. fmt);
  6835. return;
  6836. }
  6837. env->buf = added;
  6838. env->buflen = n;
  6839. space = (env->buflen - env->bufused);
  6840. }
  6841. /* Make a pointer to the free space int the buffer */
  6842. added = env->buf + env->bufused;
  6843. /* Copy VARIABLE=VALUE\0 string into the free space */
  6844. va_start(ap, fmt);
  6845. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  6846. va_end(ap);
  6847. /* Do not add truncated strings to the environment */
  6848. if (truncated) {
  6849. /* Reallocate the buffer */
  6850. space = 0;
  6851. n = 1;
  6852. }
  6853. } while (truncated);
  6854. /* Calculate number of bytes added to the environment */
  6855. n = strlen(added) + 1;
  6856. env->bufused += n;
  6857. /* Now update the variable index */
  6858. space = (env->varlen - env->varused);
  6859. if (space < 2) {
  6860. mg_cry(env->conn,
  6861. "%s: Cannot register CGI variable [%s]",
  6862. __func__,
  6863. fmt);
  6864. return;
  6865. }
  6866. /* Append a pointer to the added string into the envp array */
  6867. env->var[env->varused] = added;
  6868. env->varused++;
  6869. }
  6870. static void
  6871. prepare_cgi_environment(struct mg_connection *conn,
  6872. const char *prog,
  6873. struct cgi_environment *env)
  6874. {
  6875. const char *s;
  6876. struct vec var_vec;
  6877. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  6878. int i, truncated;
  6879. if (conn == NULL || prog == NULL || env == NULL) {
  6880. return;
  6881. }
  6882. env->conn = conn;
  6883. env->buflen = CGI_ENVIRONMENT_SIZE;
  6884. env->bufused = 0;
  6885. env->buf = (char *)mg_malloc(env->buflen);
  6886. env->varlen = MAX_CGI_ENVIR_VARS;
  6887. env->varused = 0;
  6888. env->var = (char **)mg_malloc(env->buflen * sizeof(char *));
  6889. addenv(env, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  6890. addenv(env, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6891. addenv(env, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6892. addenv(env, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  6893. /* Prepare the environment block */
  6894. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  6895. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  6896. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  6897. #if defined(USE_IPV6)
  6898. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  6899. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  6900. } else
  6901. #endif
  6902. {
  6903. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  6904. }
  6905. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  6906. addenv(env, "REMOTE_ADDR=%s", src_addr);
  6907. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  6908. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  6909. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  6910. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  6911. /* SCRIPT_NAME */
  6912. addenv(env,
  6913. "SCRIPT_NAME=%.*s",
  6914. (int)strlen(conn->request_info.local_uri)
  6915. - ((conn->path_info == NULL) ? 0 : (int)strlen(conn->path_info)),
  6916. conn->request_info.local_uri);
  6917. addenv(env, "SCRIPT_FILENAME=%s", prog);
  6918. if (conn->path_info == NULL) {
  6919. addenv(env, "PATH_TRANSLATED=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6920. } else {
  6921. addenv(env,
  6922. "PATH_TRANSLATED=%s%s",
  6923. conn->ctx->config[DOCUMENT_ROOT],
  6924. conn->path_info);
  6925. }
  6926. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  6927. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  6928. addenv(env, "CONTENT_TYPE=%s", s);
  6929. }
  6930. if (conn->request_info.query_string != NULL) {
  6931. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  6932. }
  6933. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  6934. addenv(env, "CONTENT_LENGTH=%s", s);
  6935. }
  6936. if ((s = getenv("PATH")) != NULL) {
  6937. addenv(env, "PATH=%s", s);
  6938. }
  6939. if (conn->path_info != NULL) {
  6940. addenv(env, "PATH_INFO=%s", conn->path_info);
  6941. }
  6942. if (conn->status_code > 0) {
  6943. /* CGI error handler should show the status code */
  6944. addenv(env, "STATUS=%d", conn->status_code);
  6945. }
  6946. #if defined(_WIN32)
  6947. if ((s = getenv("COMSPEC")) != NULL) {
  6948. addenv(env, "COMSPEC=%s", s);
  6949. }
  6950. if ((s = getenv("SYSTEMROOT")) != NULL) {
  6951. addenv(env, "SYSTEMROOT=%s", s);
  6952. }
  6953. if ((s = getenv("SystemDrive")) != NULL) {
  6954. addenv(env, "SystemDrive=%s", s);
  6955. }
  6956. if ((s = getenv("ProgramFiles")) != NULL) {
  6957. addenv(env, "ProgramFiles=%s", s);
  6958. }
  6959. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  6960. addenv(env, "ProgramFiles(x86)=%s", s);
  6961. }
  6962. #else
  6963. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  6964. addenv(env, "LD_LIBRARY_PATH=%s", s);
  6965. }
  6966. #endif /* _WIN32 */
  6967. if ((s = getenv("PERLLIB")) != NULL) {
  6968. addenv(env, "PERLLIB=%s", s);
  6969. }
  6970. if (conn->request_info.remote_user != NULL) {
  6971. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  6972. addenv(env, "%s", "AUTH_TYPE=Digest");
  6973. }
  6974. /* Add all headers as HTTP_* variables */
  6975. for (i = 0; i < conn->request_info.num_headers; i++) {
  6976. (void)mg_snprintf(conn,
  6977. &truncated,
  6978. http_var_name,
  6979. sizeof(http_var_name),
  6980. "HTTP_%s",
  6981. conn->request_info.http_headers[i].name);
  6982. if (truncated) {
  6983. mg_cry(conn,
  6984. "%s: HTTP header variable too long [%s]",
  6985. __func__,
  6986. conn->request_info.http_headers[i].name);
  6987. continue;
  6988. }
  6989. /* Convert variable name into uppercase, and change - to _ */
  6990. for (p = http_var_name; *p != '\0'; p++) {
  6991. if (*p == '-') {
  6992. *p = '_';
  6993. }
  6994. *p = (char)toupper(*(unsigned char *)p);
  6995. }
  6996. addenv(env,
  6997. "%s=%s",
  6998. http_var_name,
  6999. conn->request_info.http_headers[i].value);
  7000. }
  7001. /* Add user-specified variables */
  7002. s = conn->ctx->config[CGI_ENVIRONMENT];
  7003. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  7004. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  7005. }
  7006. env->var[env->varused] = NULL;
  7007. env->buf[env->bufused] = '\0';
  7008. }
  7009. static void
  7010. handle_cgi_request(struct mg_connection *conn, const char *prog)
  7011. {
  7012. char *buf;
  7013. size_t buflen;
  7014. int headers_len, data_len, i, truncated;
  7015. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  7016. const char *status, *status_text, *connection_state;
  7017. char *pbuf, dir[PATH_MAX], *p;
  7018. struct mg_request_info ri;
  7019. struct cgi_environment blk;
  7020. FILE *in = NULL, *out = NULL, *err = NULL;
  7021. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  7022. pid_t pid = (pid_t)-1;
  7023. if (conn == NULL) {
  7024. return;
  7025. }
  7026. buf = NULL;
  7027. buflen = 16384;
  7028. prepare_cgi_environment(conn, prog, &blk);
  7029. /* CGI must be executed in its own directory. 'dir' must point to the
  7030. * directory containing executable program, 'p' must point to the
  7031. * executable program name relative to 'dir'. */
  7032. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  7033. if (truncated) {
  7034. mg_cry(conn, "Error: CGI program \"%s\": Path too long", prog);
  7035. send_http_error(conn, 500, "Error: %s", "CGI path too long");
  7036. goto done;
  7037. }
  7038. if ((p = strrchr(dir, '/')) != NULL) {
  7039. *p++ = '\0';
  7040. } else {
  7041. dir[0] = '.', dir[1] = '\0';
  7042. p = (char *)prog;
  7043. }
  7044. if (pipe(fdin) != 0 || pipe(fdout) != 0 || pipe(fderr) != 0) {
  7045. status = strerror(ERRNO);
  7046. mg_cry(conn,
  7047. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  7048. prog,
  7049. status);
  7050. send_http_error(conn, 500, "Error: Cannot create CGI pipe: %s", status);
  7051. goto done;
  7052. }
  7053. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  7054. if (pid == (pid_t)-1) {
  7055. status = strerror(ERRNO);
  7056. mg_cry(conn,
  7057. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  7058. prog,
  7059. status);
  7060. send_http_error(conn,
  7061. 500,
  7062. "Error: Cannot spawn CGI process [%s]: %s",
  7063. prog,
  7064. status);
  7065. goto done;
  7066. }
  7067. /* Make sure child closes all pipe descriptors. It must dup them to 0,1 */
  7068. set_close_on_exec((SOCKET)fdin[0], conn); /* stdin read */
  7069. set_close_on_exec((SOCKET)fdout[1], conn); /* stdout write */
  7070. set_close_on_exec((SOCKET)fderr[1], conn); /* stderr write */
  7071. set_close_on_exec((SOCKET)fdin[1], conn); /* stdin write */
  7072. set_close_on_exec((SOCKET)fdout[0], conn); /* stdout read */
  7073. set_close_on_exec((SOCKET)fderr[0], conn); /* stderr read */
  7074. /* Parent closes only one side of the pipes.
  7075. * If we don't mark them as closed, close() attempt before
  7076. * return from this function throws an exception on Windows.
  7077. * Windows does not like when closed descriptor is closed again. */
  7078. (void)close(fdin[0]);
  7079. (void)close(fdout[1]);
  7080. (void)close(fderr[1]);
  7081. fdin[0] = fdout[1] = fderr[1] = -1;
  7082. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  7083. status = strerror(ERRNO);
  7084. mg_cry(conn,
  7085. "Error: CGI program \"%s\": Can not open stdin: %s",
  7086. prog,
  7087. status);
  7088. send_http_error(conn,
  7089. 500,
  7090. "Error: CGI can not open fdin\nfopen: %s",
  7091. status);
  7092. goto done;
  7093. }
  7094. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  7095. status = strerror(ERRNO);
  7096. mg_cry(conn,
  7097. "Error: CGI program \"%s\": Can not open stdout: %s",
  7098. prog,
  7099. status);
  7100. send_http_error(conn,
  7101. 500,
  7102. "Error: CGI can not open fdout\nfopen: %s",
  7103. status);
  7104. goto done;
  7105. }
  7106. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  7107. status = strerror(ERRNO);
  7108. mg_cry(conn,
  7109. "Error: CGI program \"%s\": Can not open stderr: %s",
  7110. prog,
  7111. status);
  7112. send_http_error(conn,
  7113. 500,
  7114. "Error: CGI can not open fdout\nfopen: %s",
  7115. status);
  7116. goto done;
  7117. }
  7118. setbuf(in, NULL);
  7119. setbuf(out, NULL);
  7120. setbuf(err, NULL);
  7121. fout.access.fp = out;
  7122. if ((conn->request_info.content_length > 0) || conn->is_chunked) {
  7123. /* This is a POST/PUT request, or another request with body data. */
  7124. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  7125. /* Error sending the body data */
  7126. mg_cry(conn,
  7127. "Error: CGI program \"%s\": Forward body data failed",
  7128. prog);
  7129. goto done;
  7130. }
  7131. }
  7132. /* Close so child gets an EOF. */
  7133. fclose(in);
  7134. in = NULL;
  7135. fdin[1] = -1;
  7136. /* Now read CGI reply into a buffer. We need to set correct
  7137. * status code, thus we need to see all HTTP headers first.
  7138. * Do not send anything back to client, until we buffer in all
  7139. * HTTP headers. */
  7140. data_len = 0;
  7141. buf = (char *)mg_malloc(buflen);
  7142. if (buf == NULL) {
  7143. send_http_error(conn,
  7144. 500,
  7145. "Error: Not enough memory for CGI buffer (%u bytes)",
  7146. (unsigned int)buflen);
  7147. mg_cry(conn,
  7148. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  7149. "bytes)",
  7150. prog,
  7151. (unsigned int)buflen);
  7152. goto done;
  7153. }
  7154. headers_len = read_request(out, conn, buf, (int)buflen, &data_len);
  7155. if (headers_len <= 0) {
  7156. /* Could not parse the CGI response. Check if some error message on
  7157. * stderr. */
  7158. i = pull_all(err, conn, buf, (int)buflen);
  7159. if (i > 0) {
  7160. mg_cry(conn,
  7161. "Error: CGI program \"%s\" sent error "
  7162. "message: [%.*s]",
  7163. prog,
  7164. i,
  7165. buf);
  7166. send_http_error(conn,
  7167. 500,
  7168. "Error: CGI program \"%s\" sent error "
  7169. "message: [%.*s]",
  7170. prog,
  7171. i,
  7172. buf);
  7173. } else {
  7174. mg_cry(conn,
  7175. "Error: CGI program sent malformed or too big "
  7176. "(>%u bytes) HTTP headers: [%.*s]",
  7177. (unsigned)buflen,
  7178. data_len,
  7179. buf);
  7180. send_http_error(conn,
  7181. 500,
  7182. "Error: CGI program sent malformed or too big "
  7183. "(>%u bytes) HTTP headers: [%.*s]",
  7184. (unsigned)buflen,
  7185. data_len,
  7186. buf);
  7187. }
  7188. goto done;
  7189. }
  7190. pbuf = buf;
  7191. buf[headers_len - 1] = '\0';
  7192. parse_http_headers(&pbuf, &ri);
  7193. /* Make up and send the status line */
  7194. status_text = "OK";
  7195. if ((status = get_header(&ri, "Status")) != NULL) {
  7196. conn->status_code = atoi(status);
  7197. status_text = status;
  7198. while (isdigit(*(const unsigned char *)status_text)
  7199. || *status_text == ' ') {
  7200. status_text++;
  7201. }
  7202. } else if (get_header(&ri, "Location") != NULL) {
  7203. conn->status_code = 302;
  7204. } else {
  7205. conn->status_code = 200;
  7206. }
  7207. connection_state = get_header(&ri, "Connection");
  7208. if (!header_has_option(connection_state, "keep-alive")) {
  7209. conn->must_close = 1;
  7210. }
  7211. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  7212. /* Send headers */
  7213. for (i = 0; i < ri.num_headers; i++) {
  7214. mg_printf(conn,
  7215. "%s: %s\r\n",
  7216. ri.http_headers[i].name,
  7217. ri.http_headers[i].value);
  7218. }
  7219. mg_write(conn, "\r\n", 2);
  7220. /* Send chunk of data that may have been read after the headers */
  7221. conn->num_bytes_sent +=
  7222. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  7223. /* Read the rest of CGI output and send to the client */
  7224. send_file_data(conn, &fout, 0, INT64_MAX);
  7225. done:
  7226. mg_free(blk.var);
  7227. mg_free(blk.buf);
  7228. if (pid != (pid_t)-1) {
  7229. kill(pid, SIGKILL);
  7230. #if !defined(_WIN32)
  7231. {
  7232. int st;
  7233. while (waitpid(pid, &st, 0) != -1)
  7234. ; /* clean zombies */
  7235. }
  7236. #endif
  7237. }
  7238. if (fdin[0] != -1) {
  7239. close(fdin[0]);
  7240. }
  7241. if (fdout[1] != -1) {
  7242. close(fdout[1]);
  7243. }
  7244. if (in != NULL) {
  7245. fclose(in);
  7246. } else if (fdin[1] != -1) {
  7247. close(fdin[1]);
  7248. }
  7249. if (out != NULL) {
  7250. fclose(out);
  7251. } else if (fdout[0] != -1) {
  7252. close(fdout[0]);
  7253. }
  7254. if (err != NULL) {
  7255. fclose(err);
  7256. } else if (fderr[0] != -1) {
  7257. close(fderr[0]);
  7258. }
  7259. if (buf != NULL) {
  7260. mg_free(buf);
  7261. }
  7262. }
  7263. #endif /* !NO_CGI */
  7264. #if !defined(NO_FILES)
  7265. static void
  7266. mkcol(struct mg_connection *conn, const char *path)
  7267. {
  7268. int rc, body_len;
  7269. struct de de;
  7270. char date[64];
  7271. time_t curtime = time(NULL);
  7272. if (conn == NULL) {
  7273. return;
  7274. }
  7275. /* TODO (mid): Check the send_http_error situations in this function */
  7276. memset(&de.file, 0, sizeof(de.file));
  7277. if (!mg_stat(conn, path, &de.file)) {
  7278. mg_cry(conn,
  7279. "%s: mg_stat(%s) failed: %s",
  7280. __func__,
  7281. path,
  7282. strerror(ERRNO));
  7283. }
  7284. if (de.file.last_modified) {
  7285. /* TODO (high): This check does not seem to make any sense ! */
  7286. send_http_error(
  7287. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7288. return;
  7289. }
  7290. body_len = conn->data_len - conn->request_len;
  7291. if (body_len > 0) {
  7292. send_http_error(
  7293. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7294. return;
  7295. }
  7296. rc = mg_mkdir(conn, path, 0755);
  7297. if (rc == 0) {
  7298. conn->status_code = 201;
  7299. gmt_time_string(date, sizeof(date), &curtime);
  7300. mg_printf(conn,
  7301. "HTTP/1.1 %d Created\r\n"
  7302. "Date: %s\r\n",
  7303. conn->status_code,
  7304. date);
  7305. send_static_cache_header(conn);
  7306. mg_printf(conn,
  7307. "Content-Length: 0\r\n"
  7308. "Connection: %s\r\n\r\n",
  7309. suggest_connection_header(conn));
  7310. } else if (rc == -1) {
  7311. if (errno == EEXIST) {
  7312. send_http_error(
  7313. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7314. } else if (errno == EACCES) {
  7315. send_http_error(
  7316. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7317. } else if (errno == ENOENT) {
  7318. send_http_error(
  7319. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7320. } else {
  7321. send_http_error(conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  7322. }
  7323. }
  7324. }
  7325. static void
  7326. put_file(struct mg_connection *conn, const char *path)
  7327. {
  7328. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7329. const char *range;
  7330. int64_t r1, r2;
  7331. int rc;
  7332. char date[64];
  7333. time_t curtime = time(NULL);
  7334. if (conn == NULL) {
  7335. return;
  7336. }
  7337. if (mg_stat(conn, path, &file.stat)) {
  7338. /* File already exists */
  7339. conn->status_code = 200;
  7340. if (file.stat.is_directory) {
  7341. /* This is an already existing directory,
  7342. * so there is nothing to do for the server. */
  7343. rc = 0;
  7344. } else {
  7345. /* File exists and is not a directory. */
  7346. /* Can it be replaced? */
  7347. if (file.access.membuf != NULL) {
  7348. /* This is an "in-memory" file, that can not be replaced */
  7349. send_http_error(
  7350. conn,
  7351. 405,
  7352. "Error: Put not possible\nReplacing %s is not supported",
  7353. path);
  7354. return;
  7355. }
  7356. /* Check if the server may write this file */
  7357. if (access(path, W_OK) == 0) {
  7358. /* Access granted */
  7359. conn->status_code = 200;
  7360. rc = 1;
  7361. } else {
  7362. send_http_error(
  7363. conn,
  7364. 403,
  7365. "Error: Put not possible\nReplacing %s is not allowed",
  7366. path);
  7367. return;
  7368. }
  7369. }
  7370. } else {
  7371. /* File should be created */
  7372. conn->status_code = 201;
  7373. rc = put_dir(conn, path);
  7374. }
  7375. if (rc == 0) {
  7376. /* put_dir returns 0 if path is a directory */
  7377. gmt_time_string(date, sizeof(date), &curtime);
  7378. mg_printf(conn,
  7379. "HTTP/1.1 %d %s\r\n",
  7380. conn->status_code,
  7381. mg_get_response_code_text(NULL, conn->status_code));
  7382. send_no_cache_header(conn);
  7383. mg_printf(conn,
  7384. "Date: %s\r\n"
  7385. "Content-Length: 0\r\n"
  7386. "Connection: %s\r\n\r\n",
  7387. date,
  7388. suggest_connection_header(conn));
  7389. /* Request to create a directory has been fulfilled successfully.
  7390. * No need to put a file. */
  7391. return;
  7392. }
  7393. if (rc == -1) {
  7394. /* put_dir returns -1 if the path is too long */
  7395. send_http_error(conn,
  7396. 414,
  7397. "Error: Path too long\nput_dir(%s): %s",
  7398. path,
  7399. strerror(ERRNO));
  7400. return;
  7401. }
  7402. if (rc == -2) {
  7403. /* put_dir returns -2 if the directory can not be created */
  7404. send_http_error(conn,
  7405. 500,
  7406. "Error: Can not create directory\nput_dir(%s): %s",
  7407. path,
  7408. strerror(ERRNO));
  7409. return;
  7410. }
  7411. /* A file should be created or overwritten. */
  7412. /* TODO: Test if write or write+read is required. */
  7413. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  7414. || file.access.fp == NULL) {
  7415. (void)mg_fclose(&file.access);
  7416. send_http_error(conn,
  7417. 500,
  7418. "Error: Can not create file\nfopen(%s): %s",
  7419. path,
  7420. strerror(ERRNO));
  7421. return;
  7422. }
  7423. fclose_on_exec(&file.access, conn);
  7424. range = mg_get_header(conn, "Content-Range");
  7425. r1 = r2 = 0;
  7426. if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
  7427. conn->status_code = 206; /* Partial content */
  7428. fseeko(file.access.fp, r1, SEEK_SET);
  7429. }
  7430. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  7431. /* forward_body_data failed.
  7432. * The error code has already been sent to the client,
  7433. * and conn->status_code is already set. */
  7434. (void)mg_fclose(&file.access);
  7435. return;
  7436. }
  7437. if (mg_fclose(&file.access) != 0) {
  7438. /* fclose failed. This might have different reasons, but a likely
  7439. * one is "no space on disk", http 507. */
  7440. conn->status_code = 507;
  7441. }
  7442. gmt_time_string(date, sizeof(date), &curtime);
  7443. mg_printf(conn,
  7444. "HTTP/1.1 %d %s\r\n",
  7445. conn->status_code,
  7446. mg_get_response_code_text(NULL, conn->status_code));
  7447. send_no_cache_header(conn);
  7448. mg_printf(conn,
  7449. "Date: %s\r\n"
  7450. "Content-Length: 0\r\n"
  7451. "Connection: %s\r\n\r\n",
  7452. date,
  7453. suggest_connection_header(conn));
  7454. }
  7455. static void
  7456. delete_file(struct mg_connection *conn, const char *path)
  7457. {
  7458. struct de de;
  7459. memset(&de.file, 0, sizeof(de.file));
  7460. if (!mg_stat(conn, path, &de.file)) {
  7461. /* mg_stat returns 0 if the file does not exist */
  7462. send_http_error(conn,
  7463. 404,
  7464. "Error: Cannot delete file\nFile %s not found",
  7465. path);
  7466. return;
  7467. }
  7468. #if 0 /* Ignore if a file in memory is inside a folder */
  7469. if (de.access.membuf != NULL) {
  7470. /* the file is cached in memory */
  7471. send_http_error(
  7472. conn,
  7473. 405,
  7474. "Error: Delete not possible\nDeleting %s is not supported",
  7475. path);
  7476. return;
  7477. }
  7478. #endif
  7479. if (de.file.is_directory) {
  7480. if (remove_directory(conn, path)) {
  7481. /* Delete is successful: Return 204 without content. */
  7482. send_http_error(conn, 204, "%s", "");
  7483. } else {
  7484. /* Delete is not successful: Return 500 (Server error). */
  7485. send_http_error(conn, 500, "Error: Could not delete %s", path);
  7486. }
  7487. return;
  7488. }
  7489. /* This is an existing file (not a directory).
  7490. * Check if write permission is granted. */
  7491. if (access(path, W_OK) != 0) {
  7492. /* File is read only */
  7493. send_http_error(
  7494. conn,
  7495. 403,
  7496. "Error: Delete not possible\nDeleting %s is not allowed",
  7497. path);
  7498. return;
  7499. }
  7500. /* Try to delete it. */
  7501. if (mg_remove(conn, path) == 0) {
  7502. /* Delete was successful: Return 204 without content. */
  7503. send_http_error(conn, 204, "%s", "");
  7504. } else {
  7505. /* Delete not successful (file locked). */
  7506. send_http_error(conn,
  7507. 423,
  7508. "Error: Cannot delete file\nremove(%s): %s",
  7509. path,
  7510. strerror(ERRNO));
  7511. }
  7512. }
  7513. #endif /* !NO_FILES */
  7514. static void
  7515. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  7516. static void
  7517. do_ssi_include(struct mg_connection *conn,
  7518. const char *ssi,
  7519. char *tag,
  7520. int include_level)
  7521. {
  7522. char file_name[MG_BUF_LEN], path[512], *p;
  7523. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7524. size_t len;
  7525. int truncated = 0;
  7526. if (conn == NULL) {
  7527. return;
  7528. }
  7529. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  7530. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  7531. * always < MG_BUF_LEN. */
  7532. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  7533. /* File name is relative to the webserver root */
  7534. file_name[511] = 0;
  7535. (void)mg_snprintf(conn,
  7536. &truncated,
  7537. path,
  7538. sizeof(path),
  7539. "%s/%s",
  7540. conn->ctx->config[DOCUMENT_ROOT],
  7541. file_name);
  7542. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  7543. /* File name is relative to the webserver working directory
  7544. * or it is absolute system path */
  7545. file_name[511] = 0;
  7546. (void)
  7547. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  7548. } else if (sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1
  7549. || sscanf(tag, " \"%511[^\"]\"", file_name) == 1) {
  7550. /* File name is relative to the currect document */
  7551. file_name[511] = 0;
  7552. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  7553. if (!truncated) {
  7554. if ((p = strrchr(path, '/')) != NULL) {
  7555. p[1] = '\0';
  7556. }
  7557. len = strlen(path);
  7558. (void)mg_snprintf(conn,
  7559. &truncated,
  7560. path + len,
  7561. sizeof(path) - len,
  7562. "%s",
  7563. file_name);
  7564. }
  7565. } else {
  7566. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  7567. return;
  7568. }
  7569. if (truncated) {
  7570. mg_cry(conn, "SSI #include path length overflow: [%s]", tag);
  7571. return;
  7572. }
  7573. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  7574. mg_cry(conn,
  7575. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  7576. tag,
  7577. path,
  7578. strerror(ERRNO));
  7579. } else {
  7580. fclose_on_exec(&file.access, conn);
  7581. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  7582. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  7583. path) > 0) {
  7584. send_ssi_file(conn, path, &file, include_level + 1);
  7585. } else {
  7586. send_file_data(conn, &file, 0, INT64_MAX);
  7587. }
  7588. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  7589. }
  7590. }
  7591. #if !defined(NO_POPEN)
  7592. static void
  7593. do_ssi_exec(struct mg_connection *conn, char *tag)
  7594. {
  7595. char cmd[1024] = "";
  7596. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7597. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  7598. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  7599. } else {
  7600. cmd[1023] = 0;
  7601. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  7602. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  7603. } else {
  7604. send_file_data(conn, &file, 0, INT64_MAX);
  7605. pclose(file.access.fp);
  7606. }
  7607. }
  7608. }
  7609. #endif /* !NO_POPEN */
  7610. static int
  7611. mg_fgetc(struct mg_file *filep, int offset)
  7612. {
  7613. if (filep == NULL) {
  7614. return EOF;
  7615. }
  7616. if (filep->access.membuf != NULL && offset >= 0
  7617. && ((unsigned int)(offset)) < filep->stat.size) {
  7618. return ((const unsigned char *)filep->access.membuf)[offset];
  7619. } else if (filep->access.fp != NULL) {
  7620. return fgetc(filep->access.fp);
  7621. } else {
  7622. return EOF;
  7623. }
  7624. }
  7625. static void
  7626. send_ssi_file(struct mg_connection *conn,
  7627. const char *path,
  7628. struct mg_file *filep,
  7629. int include_level)
  7630. {
  7631. char buf[MG_BUF_LEN];
  7632. int ch, offset, len, in_ssi_tag;
  7633. if (include_level > 10) {
  7634. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  7635. return;
  7636. }
  7637. in_ssi_tag = len = offset = 0;
  7638. while ((ch = mg_fgetc(filep, offset)) != EOF) {
  7639. if (in_ssi_tag && ch == '>') {
  7640. in_ssi_tag = 0;
  7641. buf[len++] = (char)ch;
  7642. buf[len] = '\0';
  7643. /* assert(len <= (int) sizeof(buf)); */
  7644. if (len > (int)sizeof(buf)) {
  7645. break;
  7646. }
  7647. if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
  7648. /* Not an SSI tag, pass it */
  7649. (void)mg_write(conn, buf, (size_t)len);
  7650. } else {
  7651. if (!memcmp(buf + 5, "include", 7)) {
  7652. do_ssi_include(conn, path, buf + 12, include_level);
  7653. #if !defined(NO_POPEN)
  7654. } else if (!memcmp(buf + 5, "exec", 4)) {
  7655. do_ssi_exec(conn, buf + 9);
  7656. #endif /* !NO_POPEN */
  7657. } else {
  7658. mg_cry(conn,
  7659. "%s: unknown SSI "
  7660. "command: \"%s\"",
  7661. path,
  7662. buf);
  7663. }
  7664. }
  7665. len = 0;
  7666. } else if (in_ssi_tag) {
  7667. if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
  7668. /* Not an SSI tag */
  7669. in_ssi_tag = 0;
  7670. } else if (len == (int)sizeof(buf) - 2) {
  7671. mg_cry(conn, "%s: SSI tag is too large", path);
  7672. len = 0;
  7673. }
  7674. buf[len++] = (char)(ch & 0xff);
  7675. } else if (ch == '<') {
  7676. in_ssi_tag = 1;
  7677. if (len > 0) {
  7678. mg_write(conn, buf, (size_t)len);
  7679. }
  7680. len = 0;
  7681. buf[len++] = (char)(ch & 0xff);
  7682. } else {
  7683. buf[len++] = (char)(ch & 0xff);
  7684. if (len == (int)sizeof(buf)) {
  7685. mg_write(conn, buf, (size_t)len);
  7686. len = 0;
  7687. }
  7688. }
  7689. }
  7690. /* Send the rest of buffered data */
  7691. if (len > 0) {
  7692. mg_write(conn, buf, (size_t)len);
  7693. }
  7694. }
  7695. static void
  7696. handle_ssi_file_request(struct mg_connection *conn,
  7697. const char *path,
  7698. struct mg_file *filep)
  7699. {
  7700. char date[64];
  7701. time_t curtime = time(NULL);
  7702. const char *cors1, *cors2, *cors3;
  7703. if (conn == NULL || path == NULL || filep == NULL) {
  7704. return;
  7705. }
  7706. if (mg_get_header(conn, "Origin")) {
  7707. /* Cross-origin resource sharing (CORS). */
  7708. cors1 = "Access-Control-Allow-Origin: ";
  7709. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  7710. cors3 = "\r\n";
  7711. } else {
  7712. cors1 = cors2 = cors3 = "";
  7713. }
  7714. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  7715. /* File exists (precondition for calling this function),
  7716. * but can not be opened by the server. */
  7717. send_http_error(conn,
  7718. 500,
  7719. "Error: Cannot read file\nfopen(%s): %s",
  7720. path,
  7721. strerror(ERRNO));
  7722. } else {
  7723. conn->must_close = 1;
  7724. gmt_time_string(date, sizeof(date), &curtime);
  7725. fclose_on_exec(&filep->access, conn);
  7726. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  7727. send_no_cache_header(conn);
  7728. mg_printf(conn,
  7729. "%s%s%s"
  7730. "Date: %s\r\n"
  7731. "Content-Type: text/html\r\n"
  7732. "Connection: %s\r\n\r\n",
  7733. cors1,
  7734. cors2,
  7735. cors3,
  7736. date,
  7737. suggest_connection_header(conn));
  7738. send_ssi_file(conn, path, filep, 0);
  7739. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  7740. }
  7741. }
  7742. #if !defined(NO_FILES)
  7743. static void
  7744. send_options(struct mg_connection *conn)
  7745. {
  7746. char date[64];
  7747. time_t curtime = time(NULL);
  7748. if (!conn) {
  7749. return;
  7750. }
  7751. conn->status_code = 200;
  7752. conn->must_close = 1;
  7753. gmt_time_string(date, sizeof(date), &curtime);
  7754. mg_printf(conn,
  7755. "HTTP/1.1 200 OK\r\n"
  7756. "Date: %s\r\n"
  7757. /* TODO: "Cache-Control" (?) */
  7758. "Connection: %s\r\n"
  7759. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  7760. "PROPFIND, MKCOL\r\n"
  7761. "DAV: 1\r\n\r\n",
  7762. date,
  7763. suggest_connection_header(conn));
  7764. }
  7765. /* Writes PROPFIND properties for a collection element */
  7766. static void
  7767. print_props(struct mg_connection *conn,
  7768. const char *uri,
  7769. struct mg_file_stat *filep)
  7770. {
  7771. char mtime[64];
  7772. if (conn == NULL || uri == NULL || filep == NULL) {
  7773. return;
  7774. }
  7775. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  7776. conn->num_bytes_sent +=
  7777. mg_printf(conn,
  7778. "<d:response>"
  7779. "<d:href>%s</d:href>"
  7780. "<d:propstat>"
  7781. "<d:prop>"
  7782. "<d:resourcetype>%s</d:resourcetype>"
  7783. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  7784. "<d:getlastmodified>%s</d:getlastmodified>"
  7785. "</d:prop>"
  7786. "<d:status>HTTP/1.1 200 OK</d:status>"
  7787. "</d:propstat>"
  7788. "</d:response>\n",
  7789. uri,
  7790. filep->is_directory ? "<d:collection/>" : "",
  7791. filep->size,
  7792. mtime);
  7793. }
  7794. static void
  7795. print_dav_dir_entry(struct de *de, void *data)
  7796. {
  7797. char href[PATH_MAX];
  7798. char href_encoded[PATH_MAX * 3 /* worst case */];
  7799. int truncated;
  7800. struct mg_connection *conn = (struct mg_connection *)data;
  7801. if (!de || !conn) {
  7802. return;
  7803. }
  7804. mg_snprintf(conn,
  7805. &truncated,
  7806. href,
  7807. sizeof(href),
  7808. "%s%s",
  7809. conn->request_info.local_uri,
  7810. de->file_name);
  7811. if (!truncated) {
  7812. mg_url_encode(href, href_encoded, PATH_MAX * 3);
  7813. print_props(conn, href_encoded, &de->file);
  7814. }
  7815. }
  7816. static void
  7817. handle_propfind(struct mg_connection *conn,
  7818. const char *path,
  7819. struct mg_file_stat *filep)
  7820. {
  7821. const char *depth = mg_get_header(conn, "Depth");
  7822. char date[64];
  7823. time_t curtime = time(NULL);
  7824. gmt_time_string(date, sizeof(date), &curtime);
  7825. if (!conn || !path || !filep || !conn->ctx) {
  7826. return;
  7827. }
  7828. conn->must_close = 1;
  7829. conn->status_code = 207;
  7830. mg_printf(conn,
  7831. "HTTP/1.1 207 Multi-Status\r\n"
  7832. "Date: %s\r\n",
  7833. date);
  7834. send_static_cache_header(conn);
  7835. mg_printf(conn,
  7836. "Connection: %s\r\n"
  7837. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  7838. suggest_connection_header(conn));
  7839. conn->num_bytes_sent +=
  7840. mg_printf(conn,
  7841. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  7842. "<d:multistatus xmlns:d='DAV:'>\n");
  7843. /* Print properties for the requested resource itself */
  7844. print_props(conn, conn->request_info.local_uri, filep);
  7845. /* If it is a directory, print directory entries too if Depth is not 0 */
  7846. if (filep && filep->is_directory
  7847. && !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")
  7848. && (depth == NULL || strcmp(depth, "0") != 0)) {
  7849. scan_directory(conn, path, conn, &print_dav_dir_entry);
  7850. }
  7851. conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");
  7852. }
  7853. #endif
  7854. void
  7855. mg_lock_connection(struct mg_connection *conn)
  7856. {
  7857. if (conn) {
  7858. (void)pthread_mutex_lock(&conn->mutex);
  7859. }
  7860. }
  7861. void
  7862. mg_unlock_connection(struct mg_connection *conn)
  7863. {
  7864. if (conn) {
  7865. (void)pthread_mutex_unlock(&conn->mutex);
  7866. }
  7867. }
  7868. void
  7869. mg_lock_context(struct mg_context *ctx)
  7870. {
  7871. if (ctx) {
  7872. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  7873. }
  7874. }
  7875. void
  7876. mg_unlock_context(struct mg_context *ctx)
  7877. {
  7878. if (ctx) {
  7879. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  7880. }
  7881. }
  7882. #if defined(USE_TIMERS)
  7883. #include "timer.inl"
  7884. #endif /* USE_TIMERS */
  7885. #ifdef USE_LUA
  7886. #include "mod_lua.inl"
  7887. #endif /* USE_LUA */
  7888. #ifdef USE_DUKTAPE
  7889. #include "mod_duktape.inl"
  7890. #endif /* USE_DUKTAPE */
  7891. #if defined(USE_WEBSOCKET)
  7892. /* START OF SHA-1 code
  7893. * Copyright(c) By Steve Reid <steve@edmweb.com> */
  7894. #define SHA1HANDSOFF
  7895. /* According to current tests (May 2015), the <solarisfixes.h> is not required.
  7896. *
  7897. * #if defined(__sun)
  7898. * #include "solarisfixes.h"
  7899. * #endif
  7900. */
  7901. static int
  7902. is_big_endian(void)
  7903. {
  7904. static const int n = 1;
  7905. return ((char *)&n)[0] == 0;
  7906. }
  7907. union char64long16 {
  7908. unsigned char c[64];
  7909. uint32_t l[16];
  7910. };
  7911. #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
  7912. static uint32_t
  7913. blk0(union char64long16 *block, int i)
  7914. {
  7915. /* Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN */
  7916. if (!is_big_endian()) {
  7917. block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00)
  7918. | (rol(block->l[i], 8) & 0x00FF00FF);
  7919. }
  7920. return block->l[i];
  7921. }
  7922. #define blk(i) \
  7923. (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] \
  7924. ^ block->l[(i + 2) & 15] ^ block->l[i & 15], \
  7925. 1))
  7926. #define R0(v, w, x, y, z, i) \
  7927. z += ((w & (x ^ y)) ^ y) + blk0(block, i) + 0x5A827999 + rol(v, 5); \
  7928. w = rol(w, 30);
  7929. #define R1(v, w, x, y, z, i) \
  7930. z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \
  7931. w = rol(w, 30);
  7932. #define R2(v, w, x, y, z, i) \
  7933. z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \
  7934. w = rol(w, 30);
  7935. #define R3(v, w, x, y, z, i) \
  7936. z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \
  7937. w = rol(w, 30);
  7938. #define R4(v, w, x, y, z, i) \
  7939. z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \
  7940. w = rol(w, 30);
  7941. typedef struct {
  7942. uint32_t state[5];
  7943. uint32_t count[2];
  7944. unsigned char buffer[64];
  7945. } SHA1_CTX;
  7946. static void
  7947. SHA1Transform(uint32_t state[5], const unsigned char buffer[64])
  7948. {
  7949. uint32_t a, b, c, d, e;
  7950. union char64long16 block[1];
  7951. memcpy(block, buffer, 64);
  7952. a = state[0];
  7953. b = state[1];
  7954. c = state[2];
  7955. d = state[3];
  7956. e = state[4];
  7957. R0(a, b, c, d, e, 0);
  7958. R0(e, a, b, c, d, 1);
  7959. R0(d, e, a, b, c, 2);
  7960. R0(c, d, e, a, b, 3);
  7961. R0(b, c, d, e, a, 4);
  7962. R0(a, b, c, d, e, 5);
  7963. R0(e, a, b, c, d, 6);
  7964. R0(d, e, a, b, c, 7);
  7965. R0(c, d, e, a, b, 8);
  7966. R0(b, c, d, e, a, 9);
  7967. R0(a, b, c, d, e, 10);
  7968. R0(e, a, b, c, d, 11);
  7969. R0(d, e, a, b, c, 12);
  7970. R0(c, d, e, a, b, 13);
  7971. R0(b, c, d, e, a, 14);
  7972. R0(a, b, c, d, e, 15);
  7973. R1(e, a, b, c, d, 16);
  7974. R1(d, e, a, b, c, 17);
  7975. R1(c, d, e, a, b, 18);
  7976. R1(b, c, d, e, a, 19);
  7977. R2(a, b, c, d, e, 20);
  7978. R2(e, a, b, c, d, 21);
  7979. R2(d, e, a, b, c, 22);
  7980. R2(c, d, e, a, b, 23);
  7981. R2(b, c, d, e, a, 24);
  7982. R2(a, b, c, d, e, 25);
  7983. R2(e, a, b, c, d, 26);
  7984. R2(d, e, a, b, c, 27);
  7985. R2(c, d, e, a, b, 28);
  7986. R2(b, c, d, e, a, 29);
  7987. R2(a, b, c, d, e, 30);
  7988. R2(e, a, b, c, d, 31);
  7989. R2(d, e, a, b, c, 32);
  7990. R2(c, d, e, a, b, 33);
  7991. R2(b, c, d, e, a, 34);
  7992. R2(a, b, c, d, e, 35);
  7993. R2(e, a, b, c, d, 36);
  7994. R2(d, e, a, b, c, 37);
  7995. R2(c, d, e, a, b, 38);
  7996. R2(b, c, d, e, a, 39);
  7997. R3(a, b, c, d, e, 40);
  7998. R3(e, a, b, c, d, 41);
  7999. R3(d, e, a, b, c, 42);
  8000. R3(c, d, e, a, b, 43);
  8001. R3(b, c, d, e, a, 44);
  8002. R3(a, b, c, d, e, 45);
  8003. R3(e, a, b, c, d, 46);
  8004. R3(d, e, a, b, c, 47);
  8005. R3(c, d, e, a, b, 48);
  8006. R3(b, c, d, e, a, 49);
  8007. R3(a, b, c, d, e, 50);
  8008. R3(e, a, b, c, d, 51);
  8009. R3(d, e, a, b, c, 52);
  8010. R3(c, d, e, a, b, 53);
  8011. R3(b, c, d, e, a, 54);
  8012. R3(a, b, c, d, e, 55);
  8013. R3(e, a, b, c, d, 56);
  8014. R3(d, e, a, b, c, 57);
  8015. R3(c, d, e, a, b, 58);
  8016. R3(b, c, d, e, a, 59);
  8017. R4(a, b, c, d, e, 60);
  8018. R4(e, a, b, c, d, 61);
  8019. R4(d, e, a, b, c, 62);
  8020. R4(c, d, e, a, b, 63);
  8021. R4(b, c, d, e, a, 64);
  8022. R4(a, b, c, d, e, 65);
  8023. R4(e, a, b, c, d, 66);
  8024. R4(d, e, a, b, c, 67);
  8025. R4(c, d, e, a, b, 68);
  8026. R4(b, c, d, e, a, 69);
  8027. R4(a, b, c, d, e, 70);
  8028. R4(e, a, b, c, d, 71);
  8029. R4(d, e, a, b, c, 72);
  8030. R4(c, d, e, a, b, 73);
  8031. R4(b, c, d, e, a, 74);
  8032. R4(a, b, c, d, e, 75);
  8033. R4(e, a, b, c, d, 76);
  8034. R4(d, e, a, b, c, 77);
  8035. R4(c, d, e, a, b, 78);
  8036. R4(b, c, d, e, a, 79);
  8037. state[0] += a;
  8038. state[1] += b;
  8039. state[2] += c;
  8040. state[3] += d;
  8041. state[4] += e;
  8042. a = b = c = d = e = 0;
  8043. memset(block, '\0', sizeof(block));
  8044. }
  8045. static void
  8046. SHA1Init(SHA1_CTX *context)
  8047. {
  8048. context->state[0] = 0x67452301;
  8049. context->state[1] = 0xEFCDAB89;
  8050. context->state[2] = 0x98BADCFE;
  8051. context->state[3] = 0x10325476;
  8052. context->state[4] = 0xC3D2E1F0;
  8053. context->count[0] = context->count[1] = 0;
  8054. }
  8055. static void
  8056. SHA1Update(SHA1_CTX *context, const unsigned char *data, uint32_t len)
  8057. {
  8058. uint32_t i, j;
  8059. j = context->count[0];
  8060. if ((context->count[0] += len << 3) < j) {
  8061. context->count[1]++;
  8062. }
  8063. context->count[1] += (len >> 29);
  8064. j = (j >> 3) & 63;
  8065. if ((j + len) > 63) {
  8066. memcpy(&context->buffer[j], data, (i = 64 - j));
  8067. SHA1Transform(context->state, context->buffer);
  8068. for (; i + 63 < len; i += 64) {
  8069. SHA1Transform(context->state, &data[i]);
  8070. }
  8071. j = 0;
  8072. } else
  8073. i = 0;
  8074. memcpy(&context->buffer[j], &data[i], len - i);
  8075. }
  8076. static void
  8077. SHA1Final(unsigned char digest[20], SHA1_CTX *context)
  8078. {
  8079. unsigned i;
  8080. unsigned char finalcount[8], c;
  8081. for (i = 0; i < 8; i++) {
  8082. finalcount[i] = (unsigned char)((context->count[(i >= 4) ? 0 : 1]
  8083. >> ((3 - (i & 3)) * 8)) & 255);
  8084. }
  8085. c = 0200;
  8086. SHA1Update(context, &c, 1);
  8087. while ((context->count[0] & 504) != 448) {
  8088. c = 0000;
  8089. SHA1Update(context, &c, 1);
  8090. }
  8091. SHA1Update(context, finalcount, 8);
  8092. for (i = 0; i < 20; i++) {
  8093. digest[i] = (unsigned char)((context->state[i >> 2]
  8094. >> ((3 - (i & 3)) * 8)) & 255);
  8095. }
  8096. memset(context, '\0', sizeof(*context));
  8097. memset(&finalcount, '\0', sizeof(finalcount));
  8098. }
  8099. /* END OF SHA1 CODE */
  8100. static int
  8101. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  8102. {
  8103. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  8104. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  8105. SHA1_CTX sha_ctx;
  8106. int truncated;
  8107. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  8108. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  8109. if (truncated) {
  8110. conn->must_close = 1;
  8111. return 0;
  8112. }
  8113. SHA1Init(&sha_ctx);
  8114. SHA1Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  8115. SHA1Final((unsigned char *)sha, &sha_ctx);
  8116. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  8117. mg_printf(conn,
  8118. "HTTP/1.1 101 Switching Protocols\r\n"
  8119. "Upgrade: websocket\r\n"
  8120. "Connection: Upgrade\r\n"
  8121. "Sec-WebSocket-Accept: %s\r\n",
  8122. b64_sha);
  8123. if (conn->request_info.acceptedWebSocketSubprotocol) {
  8124. mg_printf(conn,
  8125. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  8126. conn->request_info.acceptedWebSocketSubprotocol);
  8127. } else {
  8128. mg_printf(conn, "%s", "\r\n");
  8129. }
  8130. return 1;
  8131. }
  8132. static void
  8133. read_websocket(struct mg_connection *conn,
  8134. mg_websocket_data_handler ws_data_handler,
  8135. void *callback_data)
  8136. {
  8137. /* Pointer to the beginning of the portion of the incoming websocket
  8138. * message queue.
  8139. * The original websocket upgrade request is never removed, so the queue
  8140. * begins after it. */
  8141. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  8142. int n, error, exit_by_callback;
  8143. /* body_len is the length of the entire queue in bytes
  8144. * len is the length of the current message
  8145. * data_len is the length of the current message's data payload
  8146. * header_len is the length of the current message's header */
  8147. size_t i, len, mask_len = 0, data_len = 0, header_len, body_len;
  8148. /* "The masking key is a 32-bit value chosen at random by the client."
  8149. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  8150. */
  8151. unsigned char mask[4];
  8152. /* data points to the place where the message is stored when passed to
  8153. * the
  8154. * websocket_data callback. This is either mem on the stack, or a
  8155. * dynamically allocated buffer if it is too large. */
  8156. unsigned char mem[4096];
  8157. unsigned char *data = mem;
  8158. unsigned char mop; /* mask flag and opcode */
  8159. double timeout = -1.0;
  8160. if (conn->ctx->config[WEBSOCKET_TIMEOUT]) {
  8161. timeout = atoi(conn->ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  8162. }
  8163. if ((timeout <= 0.0) && (conn->ctx->config[REQUEST_TIMEOUT])) {
  8164. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  8165. }
  8166. mg_set_thread_name("wsock");
  8167. /* Loop continuously, reading messages from the socket, invoking the
  8168. * callback, and waiting repeatedly until an error occurs. */
  8169. while (!conn->ctx->stop_flag) {
  8170. header_len = 0;
  8171. assert(conn->data_len >= conn->request_len);
  8172. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  8173. len = buf[1] & 127;
  8174. mask_len = (buf[1] & 128) ? 4 : 0;
  8175. if ((len < 126) && (body_len >= mask_len)) {
  8176. data_len = len;
  8177. header_len = 2 + mask_len;
  8178. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  8179. header_len = 4 + mask_len;
  8180. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  8181. } else if (body_len >= (10 + mask_len)) {
  8182. header_len = 10 + mask_len;
  8183. data_len = (((uint64_t)ntohl(*(uint32_t *)(void *)&buf[2]))
  8184. << 32) + ntohl(*(uint32_t *)(void *)&buf[6]);
  8185. }
  8186. }
  8187. if (header_len > 0 && body_len >= header_len) {
  8188. /* Allocate space to hold websocket payload */
  8189. data = mem;
  8190. if (data_len > sizeof(mem)) {
  8191. data = (unsigned char *)mg_malloc(data_len);
  8192. if (data == NULL) {
  8193. /* Allocation failed, exit the loop and then close the
  8194. * connection */
  8195. mg_cry(conn, "websocket out of memory; closing connection");
  8196. break;
  8197. }
  8198. }
  8199. /* Copy the mask before we shift the queue and destroy it */
  8200. if (mask_len > 0) {
  8201. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  8202. } else {
  8203. memset(mask, 0, sizeof(mask));
  8204. }
  8205. /* Read frame payload from the first message in the queue into
  8206. * data and advance the queue by moving the memory in place. */
  8207. assert(body_len >= header_len);
  8208. if (data_len + header_len > body_len) {
  8209. mop = buf[0]; /* current mask and opcode */
  8210. /* Overflow case */
  8211. len = body_len - header_len;
  8212. memcpy(data, buf + header_len, len);
  8213. error = 0;
  8214. while (len < data_len) {
  8215. n = pull(NULL,
  8216. conn,
  8217. (char *)(data + len),
  8218. (int)(data_len - len),
  8219. timeout);
  8220. if (n <= 0) {
  8221. error = 1;
  8222. break;
  8223. }
  8224. len += (size_t)n;
  8225. }
  8226. if (error) {
  8227. mg_cry(conn, "Websocket pull failed; closing connection");
  8228. break;
  8229. }
  8230. conn->data_len = conn->request_len;
  8231. } else {
  8232. mop = buf[0]; /* current mask and opcode, overwritten by
  8233. * memmove() */
  8234. /* Length of the message being read at the front of the
  8235. * queue */
  8236. len = data_len + header_len;
  8237. /* Copy the data payload into the data pointer for the
  8238. * callback */
  8239. memcpy(data, buf + header_len, data_len);
  8240. /* Move the queue forward len bytes */
  8241. memmove(buf, buf + len, body_len - len);
  8242. /* Mark the queue as advanced */
  8243. conn->data_len -= (int)len;
  8244. }
  8245. /* Apply mask if necessary */
  8246. if (mask_len > 0) {
  8247. for (i = 0; i < data_len; ++i) {
  8248. data[i] ^= mask[i & 3];
  8249. }
  8250. }
  8251. /* Exit the loop if callback signals to exit (server side),
  8252. * or "connection close" opcode received (client side). */
  8253. exit_by_callback = 0;
  8254. if ((ws_data_handler != NULL)
  8255. && !ws_data_handler(
  8256. conn, mop, (char *)data, data_len, callback_data)) {
  8257. exit_by_callback = 1;
  8258. }
  8259. if (data != mem) {
  8260. mg_free(data);
  8261. }
  8262. if (exit_by_callback
  8263. || ((mop & 0xf) == WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  8264. /* Opcode == 8, connection close */
  8265. break;
  8266. }
  8267. /* Not breaking the loop, process next websocket frame. */
  8268. } else {
  8269. /* Read from the socket into the next available location in the
  8270. * message queue. */
  8271. if ((n = pull(NULL,
  8272. conn,
  8273. conn->buf + conn->data_len,
  8274. conn->buf_size - conn->data_len,
  8275. timeout)) <= 0) {
  8276. /* Error, no bytes read */
  8277. break;
  8278. }
  8279. conn->data_len += n;
  8280. }
  8281. }
  8282. mg_set_thread_name("worker");
  8283. }
  8284. static int
  8285. mg_websocket_write_exec(struct mg_connection *conn,
  8286. int opcode,
  8287. const char *data,
  8288. size_t dataLen,
  8289. uint32_t masking_key)
  8290. {
  8291. unsigned char header[14];
  8292. size_t headerLen = 1;
  8293. int retval = -1;
  8294. #if defined(__GNUC__) || defined(__MINGW32__)
  8295. /* Disable spurious conversion warning for GCC */
  8296. #pragma GCC diagnostic push
  8297. #pragma GCC diagnostic ignored "-Wconversion"
  8298. #endif
  8299. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  8300. #if defined(__GNUC__) || defined(__MINGW32__)
  8301. #pragma GCC diagnostic pop
  8302. #endif
  8303. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  8304. if (dataLen < 126) {
  8305. /* inline 7-bit length field */
  8306. header[1] = (unsigned char)dataLen;
  8307. headerLen = 2;
  8308. } else if (dataLen <= 0xFFFF) {
  8309. /* 16-bit length field */
  8310. uint16_t len = htons((uint16_t)dataLen);
  8311. header[1] = 126;
  8312. memcpy(header + 2, &len, 2);
  8313. headerLen = 4;
  8314. } else {
  8315. /* 64-bit length field */
  8316. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  8317. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  8318. header[1] = 127;
  8319. memcpy(header + 2, &len1, 4);
  8320. memcpy(header + 6, &len2, 4);
  8321. headerLen = 10;
  8322. }
  8323. if (masking_key) {
  8324. /* add mask */
  8325. header[1] |= 0x80;
  8326. memcpy(header + headerLen, &masking_key, 4);
  8327. headerLen += 4;
  8328. }
  8329. /* Note that POSIX/Winsock's send() is threadsafe
  8330. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  8331. * but mongoose's mg_printf/mg_write is not (because of the loop in
  8332. * push(), although that is only a problem if the packet is large or
  8333. * outgoing buffer is full). */
  8334. (void)mg_lock_connection(conn);
  8335. retval = mg_write(conn, header, headerLen);
  8336. if (dataLen > 0) {
  8337. retval = mg_write(conn, data, dataLen);
  8338. }
  8339. mg_unlock_connection(conn);
  8340. return retval;
  8341. }
  8342. int
  8343. mg_websocket_write(struct mg_connection *conn,
  8344. int opcode,
  8345. const char *data,
  8346. size_t dataLen)
  8347. {
  8348. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  8349. }
  8350. static void
  8351. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  8352. {
  8353. size_t i = 0;
  8354. i = 0;
  8355. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  8356. /* Convert in 32 bit words, if data is 4 byte aligned */
  8357. while (i < (in_len - 3)) {
  8358. *(uint32_t *)(void *)(out + i) =
  8359. *(uint32_t *)(void *)(in + i) ^ masking_key;
  8360. i += 4;
  8361. }
  8362. }
  8363. if (i != in_len) {
  8364. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  8365. while (i < in_len) {
  8366. *(uint8_t *)(void *)(out + i) =
  8367. *(uint8_t *)(void *)(in + i)
  8368. ^ *(((uint8_t *)&masking_key) + (i % 4));
  8369. i++;
  8370. }
  8371. }
  8372. }
  8373. int
  8374. mg_websocket_client_write(struct mg_connection *conn,
  8375. int opcode,
  8376. const char *data,
  8377. size_t dataLen)
  8378. {
  8379. int retval = -1;
  8380. char *masked_data = (char *)mg_malloc(((dataLen + 7) / 4) * 4);
  8381. uint32_t masking_key = (uint32_t)get_random();
  8382. if (masked_data == NULL) {
  8383. /* Return -1 in an error case */
  8384. mg_cry(conn,
  8385. "Cannot allocate buffer for masked websocket response: "
  8386. "Out of memory");
  8387. return -1;
  8388. }
  8389. mask_data(data, dataLen, masking_key, masked_data);
  8390. retval = mg_websocket_write_exec(
  8391. conn, opcode, masked_data, dataLen, masking_key);
  8392. mg_free(masked_data);
  8393. return retval;
  8394. }
  8395. static void
  8396. handle_websocket_request(struct mg_connection *conn,
  8397. const char *path,
  8398. int is_callback_resource,
  8399. struct mg_websocket_subprotocols *subprotocols,
  8400. mg_websocket_connect_handler ws_connect_handler,
  8401. mg_websocket_ready_handler ws_ready_handler,
  8402. mg_websocket_data_handler ws_data_handler,
  8403. mg_websocket_close_handler ws_close_handler,
  8404. void *cbData)
  8405. {
  8406. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  8407. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  8408. int lua_websock = 0;
  8409. #if !defined(USE_LUA)
  8410. (void)path;
  8411. #endif
  8412. /* Step 1: Check websocket protocol version. */
  8413. /* Step 1.1: Check Sec-WebSocket-Key. */
  8414. if (!websock_key) {
  8415. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  8416. * requires a Sec-WebSocket-Key header.
  8417. */
  8418. /* It could be the hixie draft version
  8419. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  8420. */
  8421. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  8422. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  8423. char key3[8];
  8424. if ((key1 != NULL) && (key2 != NULL)) {
  8425. /* This version uses 8 byte body data in a GET request */
  8426. conn->content_len = 8;
  8427. if (8 == mg_read(conn, key3, 8)) {
  8428. /* This is the hixie version */
  8429. send_http_error(conn,
  8430. 426,
  8431. "%s",
  8432. "Protocol upgrade to RFC 6455 required");
  8433. return;
  8434. }
  8435. }
  8436. /* This is an unknown version */
  8437. send_http_error(conn, 400, "%s", "Malformed websocket request");
  8438. return;
  8439. }
  8440. /* Step 1.2: Check websocket protocol version. */
  8441. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  8442. if (version == NULL || strcmp(version, "13") != 0) {
  8443. /* Reject wrong versions */
  8444. send_http_error(conn, 426, "%s", "Protocol upgrade required");
  8445. return;
  8446. }
  8447. /* Step 1.3: Could check for "Host", but we do not really nead this
  8448. * value for anything, so just ignore it. */
  8449. /* Step 2: If a callback is responsible, call it. */
  8450. if (is_callback_resource) {
  8451. /* Step 2.1 check and select subprotocol */
  8452. const char *protocol = mg_get_header(conn, "Sec-WebSocket-Protocol");
  8453. if (protocol && subprotocols) {
  8454. int idx;
  8455. unsigned long len;
  8456. const char *sep, *curSubProtocol,
  8457. *acceptedWebSocketSubprotocol = NULL;
  8458. /* look for matching subprotocol */
  8459. do {
  8460. sep = strchr(protocol, ',');
  8461. curSubProtocol = protocol;
  8462. len = sep ? (unsigned long)(sep - protocol) : strlen(protocol);
  8463. while (sep && isspace(*++sep))
  8464. ; // ignore leading whitespaces
  8465. protocol = sep;
  8466. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  8467. if ((strlen(subprotocols->subprotocols[idx]) == len)
  8468. && (strncmp(curSubProtocol,
  8469. subprotocols->subprotocols[idx],
  8470. len) == 0)) {
  8471. acceptedWebSocketSubprotocol =
  8472. subprotocols->subprotocols[idx];
  8473. break;
  8474. }
  8475. }
  8476. } while (sep && !acceptedWebSocketSubprotocol);
  8477. conn->request_info.acceptedWebSocketSubprotocol =
  8478. acceptedWebSocketSubprotocol;
  8479. } else if (protocol) {
  8480. /* keep legacy behavior */
  8481. /* The protocol is a comma seperated list of names. */
  8482. /* The server must only return one value from this list. */
  8483. /* First check if it is a list or just a single value. */
  8484. const char *sep = strrchr(protocol, ',');
  8485. if (sep == NULL) {
  8486. /* Just a single protocol -> accept it. */
  8487. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  8488. } else {
  8489. /* Multiple protocols -> accept the last one. */
  8490. /* This is just a quick fix if the client offers multiple
  8491. * protocols. The handler should have a list of accepted
  8492. * protocols on his own
  8493. * and use it to select one protocol among those the client has
  8494. * offered.
  8495. */
  8496. while (isspace(*++sep))
  8497. ; // ignore leading whitespaces
  8498. conn->request_info.acceptedWebSocketSubprotocol = sep;
  8499. }
  8500. }
  8501. if (ws_connect_handler != NULL
  8502. && ws_connect_handler(conn, cbData) != 0) {
  8503. /* C callback has returned non-zero, do not proceed with
  8504. * handshake.
  8505. */
  8506. /* Note that C callbacks are no longer called when Lua is
  8507. * responsible, so C can no longer filter callbacks for Lua. */
  8508. return;
  8509. }
  8510. }
  8511. #if defined(USE_LUA)
  8512. /* Step 3: No callback. Check if Lua is responsible. */
  8513. else {
  8514. /* Step 3.1: Check if Lua is responsible. */
  8515. if (conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  8516. lua_websock =
  8517. match_prefix(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  8518. strlen(
  8519. conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  8520. path);
  8521. }
  8522. if (lua_websock) {
  8523. /* Step 3.2: Lua is responsible: call it. */
  8524. conn->lua_websocket_state = lua_websocket_new(path, conn);
  8525. if (!conn->lua_websocket_state) {
  8526. /* Lua rejected the new client */
  8527. return;
  8528. }
  8529. }
  8530. }
  8531. #endif
  8532. /* Step 4: Check if there is a responsible websocket handler. */
  8533. if (!is_callback_resource && !lua_websock) {
  8534. /* There is no callback, and Lua is not responsible either. */
  8535. /* Reply with a 404 Not Found or with nothing at all?
  8536. * TODO (mid): check the websocket standards, how to reply to
  8537. * requests to invalid websocket addresses. */
  8538. send_http_error(conn, 404, "%s", "Not found");
  8539. return;
  8540. }
  8541. /* Step 5: The websocket connection has been accepted */
  8542. if (!send_websocket_handshake(conn, websock_key)) {
  8543. send_http_error(conn, 500, "%s", "Websocket handshake failed");
  8544. return;
  8545. }
  8546. /* Step 6: Call the ready handler */
  8547. if (is_callback_resource) {
  8548. if (ws_ready_handler != NULL) {
  8549. ws_ready_handler(conn, cbData);
  8550. }
  8551. #if defined(USE_LUA)
  8552. } else if (lua_websock) {
  8553. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  8554. /* the ready handler returned false */
  8555. return;
  8556. }
  8557. #endif
  8558. }
  8559. /* Step 7: Enter the read loop */
  8560. if (is_callback_resource) {
  8561. read_websocket(conn, ws_data_handler, cbData);
  8562. #if defined(USE_LUA)
  8563. } else if (lua_websock) {
  8564. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  8565. #endif
  8566. }
  8567. /* Step 8: Call the close handler */
  8568. if (ws_close_handler) {
  8569. ws_close_handler(conn, cbData);
  8570. }
  8571. }
  8572. static int
  8573. is_websocket_protocol(const struct mg_connection *conn)
  8574. {
  8575. const char *upgrade, *connection;
  8576. /* A websocket protocoll has the following HTTP headers:
  8577. *
  8578. * Connection: Upgrade
  8579. * Upgrade: Websocket
  8580. */
  8581. upgrade = mg_get_header(conn, "Upgrade");
  8582. if (upgrade == NULL) {
  8583. return 0; /* fail early, don't waste time checking other header
  8584. * fields
  8585. */
  8586. }
  8587. if (!mg_strcasestr(upgrade, "websocket")) {
  8588. return 0;
  8589. }
  8590. connection = mg_get_header(conn, "Connection");
  8591. if (connection == NULL) {
  8592. return 0;
  8593. }
  8594. if (!mg_strcasestr(connection, "upgrade")) {
  8595. return 0;
  8596. }
  8597. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  8598. * "Sec-WebSocket-Version" are also required.
  8599. * Don't check them here, since even an unsupported websocket protocol
  8600. * request still IS a websocket request (in contrast to a standard HTTP
  8601. * request). It will fail later in handle_websocket_request.
  8602. */
  8603. return 1;
  8604. }
  8605. #endif /* !USE_WEBSOCKET */
  8606. static int
  8607. isbyte(int n)
  8608. {
  8609. return n >= 0 && n <= 255;
  8610. }
  8611. static int
  8612. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  8613. {
  8614. int n, a, b, c, d, slash = 32, len = 0;
  8615. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5
  8616. || sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) && isbyte(a)
  8617. && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0
  8618. && slash < 33) {
  8619. len = n;
  8620. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  8621. | (uint32_t)d;
  8622. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  8623. }
  8624. return len;
  8625. }
  8626. static int
  8627. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  8628. {
  8629. int throttle = 0;
  8630. struct vec vec, val;
  8631. uint32_t net, mask;
  8632. char mult;
  8633. double v;
  8634. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  8635. mult = ',';
  8636. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  8637. || (v < 0) || ((lowercase(&mult) != 'k')
  8638. && (lowercase(&mult) != 'm') && (mult != ','))) {
  8639. continue;
  8640. }
  8641. v *= (lowercase(&mult) == 'k')
  8642. ? 1024
  8643. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  8644. if (vec.len == 1 && vec.ptr[0] == '*') {
  8645. throttle = (int)v;
  8646. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  8647. if ((remote_ip & mask) == net) {
  8648. throttle = (int)v;
  8649. }
  8650. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  8651. throttle = (int)v;
  8652. }
  8653. }
  8654. return throttle;
  8655. }
  8656. static uint32_t
  8657. get_remote_ip(const struct mg_connection *conn)
  8658. {
  8659. if (!conn) {
  8660. return 0;
  8661. }
  8662. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  8663. }
  8664. /* The mg_upload function is superseeded by mg_handle_form_request. */
  8665. #include "handle_form.inl"
  8666. #if defined(MG_LEGACY_INTERFACE)
  8667. /* Implement the deprecated mg_upload function by calling the new
  8668. * mg_handle_form_request function. While mg_upload could only handle
  8669. * HTML forms sent as POST request in multipart/form-data format
  8670. * containing only file input elements, mg_handle_form_request can
  8671. * handle all form input elements and all standard request methods. */
  8672. struct mg_upload_user_data {
  8673. struct mg_connection *conn;
  8674. const char *destination_dir;
  8675. int num_uploaded_files;
  8676. };
  8677. /* Helper function for deprecated mg_upload. */
  8678. static int
  8679. mg_upload_field_found(const char *key,
  8680. const char *filename,
  8681. char *path,
  8682. size_t pathlen,
  8683. void *user_data)
  8684. {
  8685. int truncated = 0;
  8686. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  8687. (void)key;
  8688. if (!filename) {
  8689. mg_cry(fud->conn, "%s: No filename set", __func__);
  8690. return FORM_FIELD_STORAGE_ABORT;
  8691. }
  8692. mg_snprintf(fud->conn,
  8693. &truncated,
  8694. path,
  8695. pathlen - 1,
  8696. "%s/%s",
  8697. fud->destination_dir,
  8698. filename);
  8699. if (!truncated) {
  8700. mg_cry(fud->conn, "%s: File path too long", __func__);
  8701. return FORM_FIELD_STORAGE_ABORT;
  8702. }
  8703. return FORM_FIELD_STORAGE_STORE;
  8704. }
  8705. /* Helper function for deprecated mg_upload. */
  8706. static int
  8707. mg_upload_field_get(const char *key,
  8708. const char *value,
  8709. size_t value_size,
  8710. void *user_data)
  8711. {
  8712. /* Function should never be called */
  8713. (void)key;
  8714. (void)value;
  8715. (void)value_size;
  8716. (void)user_data;
  8717. return 0;
  8718. }
  8719. /* Helper function for deprecated mg_upload. */
  8720. static int
  8721. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  8722. {
  8723. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  8724. (void)file_size;
  8725. fud->num_uploaded_files++;
  8726. fud->conn->ctx->callbacks.upload(fud->conn, path);
  8727. return 0;
  8728. }
  8729. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  8730. int
  8731. mg_upload(struct mg_connection *conn, const char *destination_dir)
  8732. {
  8733. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  8734. struct mg_form_data_handler fdh = {mg_upload_field_found,
  8735. mg_upload_field_get,
  8736. mg_upload_field_stored,
  8737. 0};
  8738. int ret;
  8739. fdh.user_data = (void *)&fud;
  8740. ret = mg_handle_form_request(conn, &fdh);
  8741. if (ret < 0) {
  8742. mg_cry(conn, "%s: Error while parsing the request", __func__);
  8743. }
  8744. return fud.num_uploaded_files;
  8745. }
  8746. #endif
  8747. static int
  8748. get_first_ssl_listener_index(const struct mg_context *ctx)
  8749. {
  8750. unsigned int i;
  8751. int idx = -1;
  8752. if (ctx) {
  8753. for (i = 0; idx == -1 && i < ctx->num_listening_sockets; i++) {
  8754. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  8755. }
  8756. }
  8757. return idx;
  8758. }
  8759. static void
  8760. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  8761. {
  8762. char host[1025];
  8763. const char *host_header;
  8764. size_t hostlen;
  8765. host_header = mg_get_header(conn, "Host");
  8766. hostlen = sizeof(host);
  8767. if (host_header != NULL) {
  8768. char *pos;
  8769. mg_strlcpy(host, host_header, hostlen);
  8770. host[hostlen - 1] = '\0';
  8771. pos = strchr(host, ':');
  8772. if (pos != NULL) {
  8773. *pos = '\0';
  8774. }
  8775. } else {
  8776. /* Cannot get host from the Host: header.
  8777. * Fallback to our IP address. */
  8778. if (conn) {
  8779. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  8780. }
  8781. }
  8782. /* Send host, port, uri and (if it exists) ?query_string */
  8783. if (conn) {
  8784. mg_printf(conn,
  8785. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  8786. host,
  8787. #if defined(USE_IPV6)
  8788. (conn->ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  8789. == AF_INET6)
  8790. ? (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  8791. .lsa.sin6.sin6_port)
  8792. :
  8793. #endif
  8794. (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  8795. .lsa.sin.sin_port),
  8796. conn->request_info.local_uri,
  8797. (conn->request_info.query_string == NULL) ? "" : "?",
  8798. (conn->request_info.query_string == NULL)
  8799. ? ""
  8800. : conn->request_info.query_string);
  8801. }
  8802. }
  8803. static void
  8804. mg_set_handler_type(struct mg_context *ctx,
  8805. const char *uri,
  8806. int handler_type,
  8807. int is_delete_request,
  8808. mg_request_handler handler,
  8809. struct mg_websocket_subprotocols *subprotocols,
  8810. mg_websocket_connect_handler connect_handler,
  8811. mg_websocket_ready_handler ready_handler,
  8812. mg_websocket_data_handler data_handler,
  8813. mg_websocket_close_handler close_handler,
  8814. mg_authorization_handler auth_handler,
  8815. void *cbdata)
  8816. {
  8817. struct mg_handler_info *tmp_rh, **lastref;
  8818. size_t urilen = strlen(uri);
  8819. if (handler_type == WEBSOCKET_HANDLER) {
  8820. /* assert(handler == NULL); */
  8821. /* assert(is_delete_request || connect_handler!=NULL ||
  8822. * ready_handler!=NULL || data_handler!=NULL ||
  8823. * close_handler!=NULL);
  8824. */
  8825. /* assert(auth_handler == NULL); */
  8826. if (handler != NULL) {
  8827. return;
  8828. }
  8829. if (!is_delete_request && connect_handler == NULL
  8830. && ready_handler == NULL
  8831. && data_handler == NULL
  8832. && close_handler == NULL) {
  8833. return;
  8834. }
  8835. if (auth_handler != NULL) {
  8836. return;
  8837. }
  8838. } else if (handler_type == REQUEST_HANDLER) {
  8839. /* assert(connect_handler==NULL && ready_handler==NULL &&
  8840. * data_handler==NULL && close_handler==NULL); */
  8841. /* assert(is_delete_request || (handler!=NULL));
  8842. */
  8843. /* assert(auth_handler == NULL); */
  8844. if (connect_handler != NULL || ready_handler != NULL
  8845. || data_handler != NULL
  8846. || close_handler != NULL) {
  8847. return;
  8848. }
  8849. if (!is_delete_request && (handler == NULL)) {
  8850. return;
  8851. }
  8852. if (auth_handler != NULL) {
  8853. return;
  8854. }
  8855. } else { /* AUTH_HANDLER */
  8856. /* assert(handler == NULL); */
  8857. /* assert(connect_handler==NULL && ready_handler==NULL &&
  8858. * data_handler==NULL && close_handler==NULL); */
  8859. /* assert(auth_handler != NULL); */
  8860. if (handler != NULL) {
  8861. return;
  8862. }
  8863. if (connect_handler != NULL || ready_handler != NULL
  8864. || data_handler != NULL
  8865. || close_handler != NULL) {
  8866. return;
  8867. }
  8868. if (!is_delete_request && (auth_handler == NULL)) {
  8869. return;
  8870. }
  8871. }
  8872. if (!ctx) {
  8873. return;
  8874. }
  8875. mg_lock_context(ctx);
  8876. /* first try to find an existing handler */
  8877. lastref = &(ctx->handlers);
  8878. for (tmp_rh = ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  8879. if (tmp_rh->handler_type == handler_type) {
  8880. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  8881. if (!is_delete_request) {
  8882. /* update existing handler */
  8883. if (handler_type == REQUEST_HANDLER) {
  8884. tmp_rh->handler = handler;
  8885. } else if (handler_type == WEBSOCKET_HANDLER) {
  8886. tmp_rh->subprotocols = subprotocols;
  8887. tmp_rh->connect_handler = connect_handler;
  8888. tmp_rh->ready_handler = ready_handler;
  8889. tmp_rh->data_handler = data_handler;
  8890. tmp_rh->close_handler = close_handler;
  8891. } else { /* AUTH_HANDLER */
  8892. tmp_rh->auth_handler = auth_handler;
  8893. }
  8894. tmp_rh->cbdata = cbdata;
  8895. } else {
  8896. /* remove existing handler */
  8897. *lastref = tmp_rh->next;
  8898. mg_free(tmp_rh->uri);
  8899. mg_free(tmp_rh);
  8900. }
  8901. mg_unlock_context(ctx);
  8902. return;
  8903. }
  8904. }
  8905. lastref = &(tmp_rh->next);
  8906. }
  8907. if (is_delete_request) {
  8908. /* no handler to set, this was a remove request to a non-existing
  8909. * handler */
  8910. mg_unlock_context(ctx);
  8911. return;
  8912. }
  8913. tmp_rh =
  8914. (struct mg_handler_info *)mg_calloc(sizeof(struct mg_handler_info), 1);
  8915. if (tmp_rh == NULL) {
  8916. mg_unlock_context(ctx);
  8917. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  8918. return;
  8919. }
  8920. tmp_rh->uri = mg_strdup(uri);
  8921. if (!tmp_rh->uri) {
  8922. mg_unlock_context(ctx);
  8923. mg_free(tmp_rh);
  8924. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  8925. return;
  8926. }
  8927. tmp_rh->uri_len = urilen;
  8928. if (handler_type == REQUEST_HANDLER) {
  8929. tmp_rh->handler = handler;
  8930. } else if (handler_type == WEBSOCKET_HANDLER) {
  8931. tmp_rh->subprotocols = subprotocols;
  8932. tmp_rh->connect_handler = connect_handler;
  8933. tmp_rh->ready_handler = ready_handler;
  8934. tmp_rh->data_handler = data_handler;
  8935. tmp_rh->close_handler = close_handler;
  8936. } else { /* AUTH_HANDLER */
  8937. tmp_rh->auth_handler = auth_handler;
  8938. }
  8939. tmp_rh->cbdata = cbdata;
  8940. tmp_rh->handler_type = handler_type;
  8941. tmp_rh->next = NULL;
  8942. *lastref = tmp_rh;
  8943. mg_unlock_context(ctx);
  8944. }
  8945. void
  8946. mg_set_request_handler(struct mg_context *ctx,
  8947. const char *uri,
  8948. mg_request_handler handler,
  8949. void *cbdata)
  8950. {
  8951. mg_set_handler_type(ctx,
  8952. uri,
  8953. REQUEST_HANDLER,
  8954. handler == NULL,
  8955. handler,
  8956. NULL,
  8957. NULL,
  8958. NULL,
  8959. NULL,
  8960. NULL,
  8961. NULL,
  8962. cbdata);
  8963. }
  8964. void
  8965. mg_set_websocket_handler(struct mg_context *ctx,
  8966. const char *uri,
  8967. mg_websocket_connect_handler connect_handler,
  8968. mg_websocket_ready_handler ready_handler,
  8969. mg_websocket_data_handler data_handler,
  8970. mg_websocket_close_handler close_handler,
  8971. void *cbdata)
  8972. {
  8973. mg_set_websocket_handler_with_subprotocols(ctx,
  8974. uri,
  8975. NULL,
  8976. connect_handler,
  8977. ready_handler,
  8978. data_handler,
  8979. close_handler,
  8980. cbdata);
  8981. }
  8982. void
  8983. mg_set_websocket_handler_with_subprotocols(
  8984. struct mg_context *ctx,
  8985. const char *uri,
  8986. struct mg_websocket_subprotocols *subprotocols,
  8987. mg_websocket_connect_handler connect_handler,
  8988. mg_websocket_ready_handler ready_handler,
  8989. mg_websocket_data_handler data_handler,
  8990. mg_websocket_close_handler close_handler,
  8991. void *cbdata)
  8992. {
  8993. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  8994. && (data_handler == NULL)
  8995. && (close_handler == NULL);
  8996. mg_set_handler_type(ctx,
  8997. uri,
  8998. WEBSOCKET_HANDLER,
  8999. is_delete_request,
  9000. NULL,
  9001. subprotocols,
  9002. connect_handler,
  9003. ready_handler,
  9004. data_handler,
  9005. close_handler,
  9006. NULL,
  9007. cbdata);
  9008. }
  9009. void
  9010. mg_set_auth_handler(struct mg_context *ctx,
  9011. const char *uri,
  9012. mg_request_handler handler,
  9013. void *cbdata)
  9014. {
  9015. mg_set_handler_type(ctx,
  9016. uri,
  9017. AUTH_HANDLER,
  9018. handler == NULL,
  9019. NULL,
  9020. NULL,
  9021. NULL,
  9022. NULL,
  9023. NULL,
  9024. NULL,
  9025. handler,
  9026. cbdata);
  9027. }
  9028. static int
  9029. get_request_handler(struct mg_connection *conn,
  9030. int handler_type,
  9031. mg_request_handler *handler,
  9032. struct mg_websocket_subprotocols **subprotocols,
  9033. mg_websocket_connect_handler *connect_handler,
  9034. mg_websocket_ready_handler *ready_handler,
  9035. mg_websocket_data_handler *data_handler,
  9036. mg_websocket_close_handler *close_handler,
  9037. mg_authorization_handler *auth_handler,
  9038. void **cbdata)
  9039. {
  9040. const struct mg_request_info *request_info = mg_get_request_info(conn);
  9041. if (request_info) {
  9042. const char *uri = request_info->local_uri;
  9043. size_t urilen = strlen(uri);
  9044. struct mg_handler_info *tmp_rh;
  9045. if (!conn || !conn->ctx) {
  9046. return 0;
  9047. }
  9048. mg_lock_context(conn->ctx);
  9049. /* first try for an exact match */
  9050. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  9051. tmp_rh = tmp_rh->next) {
  9052. if (tmp_rh->handler_type == handler_type) {
  9053. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  9054. if (handler_type == WEBSOCKET_HANDLER) {
  9055. *subprotocols = tmp_rh->subprotocols;
  9056. *connect_handler = tmp_rh->connect_handler;
  9057. *ready_handler = tmp_rh->ready_handler;
  9058. *data_handler = tmp_rh->data_handler;
  9059. *close_handler = tmp_rh->close_handler;
  9060. } else if (handler_type == REQUEST_HANDLER) {
  9061. *handler = tmp_rh->handler;
  9062. } else { /* AUTH_HANDLER */
  9063. *auth_handler = tmp_rh->auth_handler;
  9064. }
  9065. *cbdata = tmp_rh->cbdata;
  9066. mg_unlock_context(conn->ctx);
  9067. return 1;
  9068. }
  9069. }
  9070. }
  9071. /* next try for a partial match, we will accept uri/something */
  9072. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  9073. tmp_rh = tmp_rh->next) {
  9074. if (tmp_rh->handler_type == handler_type) {
  9075. if (tmp_rh->uri_len < urilen && uri[tmp_rh->uri_len] == '/'
  9076. && memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0) {
  9077. if (handler_type == WEBSOCKET_HANDLER) {
  9078. *subprotocols = tmp_rh->subprotocols;
  9079. *connect_handler = tmp_rh->connect_handler;
  9080. *ready_handler = tmp_rh->ready_handler;
  9081. *data_handler = tmp_rh->data_handler;
  9082. *close_handler = tmp_rh->close_handler;
  9083. } else if (handler_type == REQUEST_HANDLER) {
  9084. *handler = tmp_rh->handler;
  9085. } else { /* AUTH_HANDLER */
  9086. *auth_handler = tmp_rh->auth_handler;
  9087. }
  9088. *cbdata = tmp_rh->cbdata;
  9089. mg_unlock_context(conn->ctx);
  9090. return 1;
  9091. }
  9092. }
  9093. }
  9094. /* finally try for pattern match */
  9095. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  9096. tmp_rh = tmp_rh->next) {
  9097. if (tmp_rh->handler_type == handler_type) {
  9098. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  9099. if (handler_type == WEBSOCKET_HANDLER) {
  9100. *subprotocols = tmp_rh->subprotocols;
  9101. *connect_handler = tmp_rh->connect_handler;
  9102. *ready_handler = tmp_rh->ready_handler;
  9103. *data_handler = tmp_rh->data_handler;
  9104. *close_handler = tmp_rh->close_handler;
  9105. } else if (handler_type == REQUEST_HANDLER) {
  9106. *handler = tmp_rh->handler;
  9107. } else { /* AUTH_HANDLER */
  9108. *auth_handler = tmp_rh->auth_handler;
  9109. }
  9110. *cbdata = tmp_rh->cbdata;
  9111. mg_unlock_context(conn->ctx);
  9112. return 1;
  9113. }
  9114. }
  9115. }
  9116. mg_unlock_context(conn->ctx);
  9117. }
  9118. return 0; /* none found */
  9119. }
  9120. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  9121. static int
  9122. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  9123. void *cbdata)
  9124. {
  9125. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9126. if (pcallbacks->websocket_connect) {
  9127. return pcallbacks->websocket_connect(conn);
  9128. }
  9129. /* No handler set - assume "OK" */
  9130. return 0;
  9131. }
  9132. static void
  9133. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  9134. {
  9135. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9136. if (pcallbacks->websocket_ready) {
  9137. pcallbacks->websocket_ready(conn);
  9138. }
  9139. }
  9140. static int
  9141. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  9142. int bits,
  9143. char *data,
  9144. size_t len,
  9145. void *cbdata)
  9146. {
  9147. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9148. if (pcallbacks->websocket_data) {
  9149. return pcallbacks->websocket_data(conn, bits, data, len);
  9150. }
  9151. /* No handler set - assume "OK" */
  9152. return 1;
  9153. }
  9154. #endif
  9155. /* This is the heart of the Civetweb's logic.
  9156. * This function is called when the request is read, parsed and validated,
  9157. * and Civetweb must decide what action to take: serve a file, or
  9158. * a directory, or call embedded function, etcetera. */
  9159. static void
  9160. handle_request(struct mg_connection *conn)
  9161. {
  9162. if (conn) {
  9163. struct mg_request_info *ri = &conn->request_info;
  9164. char path[PATH_MAX];
  9165. int uri_len, ssl_index;
  9166. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  9167. is_put_or_delete_request = 0, is_callback_resource = 0;
  9168. int i;
  9169. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9170. mg_request_handler callback_handler = NULL;
  9171. struct mg_websocket_subprotocols *subprotocols;
  9172. mg_websocket_connect_handler ws_connect_handler = NULL;
  9173. mg_websocket_ready_handler ws_ready_handler = NULL;
  9174. mg_websocket_data_handler ws_data_handler = NULL;
  9175. mg_websocket_close_handler ws_close_handler = NULL;
  9176. void *callback_data = NULL;
  9177. mg_authorization_handler auth_handler = NULL;
  9178. void *auth_callback_data = NULL;
  9179. #if !defined(NO_FILES)
  9180. time_t curtime = time(NULL);
  9181. char date[64];
  9182. #endif
  9183. path[0] = 0;
  9184. if (!ri) {
  9185. return;
  9186. }
  9187. /* 1. get the request url */
  9188. /* 1.1. split into url and query string */
  9189. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  9190. != NULL) {
  9191. *((char *)conn->request_info.query_string++) = '\0';
  9192. }
  9193. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  9194. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  9195. ssl_index = get_first_ssl_listener_index(conn->ctx);
  9196. if (ssl_index >= 0) {
  9197. redirect_to_https_port(conn, ssl_index);
  9198. } else {
  9199. /* A http to https forward port has been specified,
  9200. * but no https port to forward to. */
  9201. send_http_error(conn,
  9202. 503,
  9203. "%s",
  9204. "Error: SSL forward not configured properly");
  9205. mg_cry(conn, "Can not redirect to SSL, no SSL port available");
  9206. }
  9207. return;
  9208. }
  9209. uri_len = (int)strlen(ri->local_uri);
  9210. /* 1.3. decode url (if config says so) */
  9211. if (should_decode_url(conn)) {
  9212. mg_url_decode(
  9213. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  9214. }
  9215. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  9216. * not possible */
  9217. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  9218. /* step 1. completed, the url is known now */
  9219. uri_len = (int)strlen(ri->local_uri);
  9220. DEBUG_TRACE("URL: %s", ri->local_uri);
  9221. /* 3. if this ip has limited speed, set it for this connection */
  9222. conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
  9223. get_remote_ip(conn),
  9224. ri->local_uri);
  9225. /* 4. call a "handle everything" callback, if registered */
  9226. if (conn->ctx->callbacks.begin_request != NULL) {
  9227. /* Note that since V1.7 the "begin_request" function is called
  9228. * before an authorization check. If an authorization check is
  9229. * required, use a request_handler instead. */
  9230. i = conn->ctx->callbacks.begin_request(conn);
  9231. if (i > 0) {
  9232. /* callback already processed the request. Store the
  9233. return value as a status code for the access log. */
  9234. conn->status_code = i;
  9235. discard_unread_request_data(conn);
  9236. return;
  9237. } else if (i == 0) {
  9238. /* civetweb should process the request */
  9239. } else {
  9240. /* unspecified - may change with the next version */
  9241. return;
  9242. }
  9243. }
  9244. /* request not yet handled by a handler or redirect, so the request
  9245. * is processed here */
  9246. /* 5. interpret the url to find out how the request must be handled
  9247. */
  9248. /* 5.1. first test, if the request targets the regular http(s)://
  9249. * protocol namespace or the websocket ws(s):// protocol namespace.
  9250. */
  9251. is_websocket_request = is_websocket_protocol(conn);
  9252. /* 5.2. check if the request will be handled by a callback */
  9253. if (get_request_handler(conn,
  9254. is_websocket_request ? WEBSOCKET_HANDLER
  9255. : REQUEST_HANDLER,
  9256. &callback_handler,
  9257. &subprotocols,
  9258. &ws_connect_handler,
  9259. &ws_ready_handler,
  9260. &ws_data_handler,
  9261. &ws_close_handler,
  9262. NULL,
  9263. &callback_data)) {
  9264. /* 5.2.1. A callback will handle this request. All requests
  9265. * handled
  9266. * by a callback have to be considered as requests to a script
  9267. * resource. */
  9268. is_callback_resource = 1;
  9269. is_script_resource = 1;
  9270. is_put_or_delete_request = is_put_or_delete_method(conn);
  9271. } else {
  9272. no_callback_resource:
  9273. /* 5.2.2. No callback is responsible for this request. The URI
  9274. * addresses a file based resource (static content or Lua/cgi
  9275. * scripts in the file system). */
  9276. is_callback_resource = 0;
  9277. interpret_uri(conn,
  9278. path,
  9279. sizeof(path),
  9280. &file.stat,
  9281. &is_found,
  9282. &is_script_resource,
  9283. &is_websocket_request,
  9284. &is_put_or_delete_request);
  9285. }
  9286. /* 6. authorization check */
  9287. /* 6.1. a custom authorization handler is installed */
  9288. if (get_request_handler(conn,
  9289. AUTH_HANDLER,
  9290. NULL,
  9291. NULL,
  9292. NULL,
  9293. NULL,
  9294. NULL,
  9295. NULL,
  9296. &auth_handler,
  9297. &auth_callback_data)) {
  9298. if (!auth_handler(conn, auth_callback_data)) {
  9299. return;
  9300. }
  9301. } else if (is_put_or_delete_request && !is_script_resource
  9302. && !is_callback_resource) {
  9303. /* 6.2. this request is a PUT/DELETE to a real file */
  9304. /* 6.2.1. thus, the server must have real files */
  9305. #if defined(NO_FILES)
  9306. if (1) {
  9307. #else
  9308. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  9309. #endif
  9310. /* This server does not have any real files, thus the
  9311. * PUT/DELETE methods are not valid. */
  9312. send_http_error(conn,
  9313. 405,
  9314. "%s method not allowed",
  9315. conn->request_info.request_method);
  9316. return;
  9317. }
  9318. #if !defined(NO_FILES)
  9319. /* 6.2.2. Check if put authorization for static files is
  9320. * available.
  9321. */
  9322. if (!is_authorized_for_put(conn)) {
  9323. send_authorization_request(conn);
  9324. return;
  9325. }
  9326. #endif
  9327. } else {
  9328. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  9329. * or it is a PUT or DELETE request to a resource that does not
  9330. * correspond to a file. Check authorization. */
  9331. if (!check_authorization(conn, path)) {
  9332. send_authorization_request(conn);
  9333. return;
  9334. }
  9335. }
  9336. /* request is authorized or does not need authorization */
  9337. /* 7. check if there are request handlers for this uri */
  9338. if (is_callback_resource) {
  9339. if (!is_websocket_request) {
  9340. i = callback_handler(conn, callback_data);
  9341. if (i > 0) {
  9342. /* Do nothing, callback has served the request. Store
  9343. * the
  9344. * return value as status code for the log and discard
  9345. * all
  9346. * data from the client not used by the callback. */
  9347. conn->status_code = i;
  9348. discard_unread_request_data(conn);
  9349. } else {
  9350. /* TODO (high): what if the handler did NOT handle the
  9351. * request */
  9352. /* The last version did handle this as a file request,
  9353. * but
  9354. * since a file request is not always a script resource,
  9355. * the authorization check might be different */
  9356. interpret_uri(conn,
  9357. path,
  9358. sizeof(path),
  9359. &file.stat,
  9360. &is_found,
  9361. &is_script_resource,
  9362. &is_websocket_request,
  9363. &is_put_or_delete_request);
  9364. callback_handler = NULL;
  9365. /* TODO (very low): goto is deprecated but for the
  9366. * moment,
  9367. * a goto is simpler than some curious loop. */
  9368. /* The situation "callback does not handle the request"
  9369. * needs to be reconsidered anyway. */
  9370. goto no_callback_resource;
  9371. }
  9372. } else {
  9373. #if defined(USE_WEBSOCKET)
  9374. handle_websocket_request(conn,
  9375. path,
  9376. is_callback_resource,
  9377. subprotocols,
  9378. ws_connect_handler,
  9379. ws_ready_handler,
  9380. ws_data_handler,
  9381. ws_close_handler,
  9382. callback_data);
  9383. #endif
  9384. }
  9385. return;
  9386. }
  9387. /* 8. handle websocket requests */
  9388. #if defined(USE_WEBSOCKET)
  9389. if (is_websocket_request) {
  9390. if (is_script_resource) {
  9391. /* Websocket Lua script */
  9392. handle_websocket_request(conn,
  9393. path,
  9394. 0 /* Lua Script */,
  9395. NULL,
  9396. NULL,
  9397. NULL,
  9398. NULL,
  9399. NULL,
  9400. &conn->ctx->callbacks);
  9401. } else {
  9402. #if defined(MG_LEGACY_INTERFACE)
  9403. handle_websocket_request(
  9404. conn,
  9405. path,
  9406. !is_script_resource /* could be deprecated global callback */,
  9407. NULL,
  9408. deprecated_websocket_connect_wrapper,
  9409. deprecated_websocket_ready_wrapper,
  9410. deprecated_websocket_data_wrapper,
  9411. NULL,
  9412. &conn->ctx->callbacks);
  9413. #else
  9414. send_http_error(conn, 404, "%s", "Not found");
  9415. #endif
  9416. }
  9417. return;
  9418. } else
  9419. #endif
  9420. #if defined(NO_FILES)
  9421. /* 9a. In case the server uses only callbacks, this uri is
  9422. * unknown.
  9423. * Then, all request handling ends here. */
  9424. send_http_error(conn, 404, "%s", "Not Found");
  9425. #else
  9426. /* 9b. This request is either for a static file or resource handled
  9427. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  9428. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  9429. send_http_error(conn, 404, "%s", "Not Found");
  9430. return;
  9431. }
  9432. /* 10. File is handled by a script. */
  9433. if (is_script_resource) {
  9434. handle_file_based_request(conn, path, &file);
  9435. return;
  9436. }
  9437. /* 11. Handle put/delete/mkcol requests */
  9438. if (is_put_or_delete_request) {
  9439. /* 11.1. PUT method */
  9440. if (!strcmp(ri->request_method, "PUT")) {
  9441. put_file(conn, path);
  9442. return;
  9443. }
  9444. /* 11.2. DELETE method */
  9445. if (!strcmp(ri->request_method, "DELETE")) {
  9446. delete_file(conn, path);
  9447. return;
  9448. }
  9449. /* 11.3. MKCOL method */
  9450. if (!strcmp(ri->request_method, "MKCOL")) {
  9451. mkcol(conn, path);
  9452. return;
  9453. }
  9454. /* 11.4. PATCH method
  9455. * This method is not supported for static resources,
  9456. * only for scripts (Lua, CGI) and callbacks. */
  9457. send_http_error(conn,
  9458. 405,
  9459. "%s method not allowed",
  9460. conn->request_info.request_method);
  9461. return;
  9462. }
  9463. /* 11. File does not exist, or it was configured that it should be
  9464. * hidden */
  9465. if (!is_found || (must_hide_file(conn, path))) {
  9466. send_http_error(conn, 404, "%s", "Not found");
  9467. return;
  9468. }
  9469. /* 12. Directory uris should end with a slash */
  9470. if (file.stat.is_directory && (uri_len > 0)
  9471. && (ri->local_uri[uri_len - 1] != '/')) {
  9472. gmt_time_string(date, sizeof(date), &curtime);
  9473. mg_printf(conn,
  9474. "HTTP/1.1 301 Moved Permanently\r\n"
  9475. "Location: %s/\r\n"
  9476. "Date: %s\r\n"
  9477. /* "Cache-Control: private\r\n" (= default) */
  9478. "Content-Length: 0\r\n"
  9479. "Connection: %s\r\n\r\n",
  9480. ri->request_uri,
  9481. date,
  9482. suggest_connection_header(conn));
  9483. return;
  9484. }
  9485. /* 13. Handle other methods than GET/HEAD */
  9486. /* 13.1. Handle PROPFIND */
  9487. if (!strcmp(ri->request_method, "PROPFIND")) {
  9488. handle_propfind(conn, path, &file.stat);
  9489. return;
  9490. }
  9491. /* 13.2. Handle OPTIONS for files */
  9492. if (!strcmp(ri->request_method, "OPTIONS")) {
  9493. /* This standard handler is only used for real files.
  9494. * Scripts should support the OPTIONS method themselves, to allow a
  9495. * maximum flexibility.
  9496. * Lua and CGI scripts may fully support CORS this way (including
  9497. * preflights). */
  9498. send_options(conn);
  9499. return;
  9500. }
  9501. /* 13.3. everything but GET and HEAD (e.g. POST) */
  9502. if (0 != strcmp(ri->request_method, "GET")
  9503. && 0 != strcmp(ri->request_method, "HEAD")) {
  9504. send_http_error(conn,
  9505. 405,
  9506. "%s method not allowed",
  9507. conn->request_info.request_method);
  9508. return;
  9509. }
  9510. /* 14. directories */
  9511. if (file.stat.is_directory) {
  9512. if (substitute_index_file(conn, path, sizeof(path), &file)) {
  9513. /* 14.1. use a substitute file */
  9514. /* TODO (high): substitute index may be a script resource.
  9515. * define what should be possible in this case. */
  9516. } else {
  9517. /* 14.2. no substitute file */
  9518. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  9519. "yes")) {
  9520. handle_directory_request(conn, path);
  9521. } else {
  9522. send_http_error(conn,
  9523. 403,
  9524. "%s",
  9525. "Error: Directory listing denied");
  9526. }
  9527. return;
  9528. }
  9529. }
  9530. handle_file_based_request(conn, path, &file);
  9531. #endif /* !defined(NO_FILES) */
  9532. #if 0
  9533. /* Perform redirect and auth checks before calling begin_request()
  9534. * handler.
  9535. * Otherwise, begin_request() would need to perform auth checks and
  9536. * redirects. */
  9537. #endif
  9538. }
  9539. return;
  9540. }
  9541. static void
  9542. handle_file_based_request(struct mg_connection *conn,
  9543. const char *path,
  9544. struct mg_file *file)
  9545. {
  9546. if (!conn || !conn->ctx) {
  9547. return;
  9548. }
  9549. if (0) {
  9550. #ifdef USE_LUA
  9551. } else if (match_prefix(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  9552. strlen(
  9553. conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  9554. path) > 0) {
  9555. /* Lua server page: an SSI like page containing mostly plain html
  9556. * code
  9557. * plus some tags with server generated contents. */
  9558. handle_lsp_request(conn, path, file, NULL);
  9559. } else if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  9560. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  9561. path) > 0) {
  9562. /* Lua in-server module script: a CGI like script used to generate
  9563. * the
  9564. * entire reply. */
  9565. mg_exec_lua_script(conn, path, NULL);
  9566. #endif
  9567. #if defined(USE_DUKTAPE)
  9568. } else if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  9569. strlen(
  9570. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  9571. path) > 0) {
  9572. /* Call duktape to generate the page */
  9573. mg_exec_duktape_script(conn, path);
  9574. #endif
  9575. #if !defined(NO_CGI)
  9576. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  9577. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  9578. path) > 0) {
  9579. /* CGI scripts may support all HTTP methods */
  9580. handle_cgi_request(conn, path);
  9581. #endif /* !NO_CGI */
  9582. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  9583. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  9584. path) > 0) {
  9585. handle_ssi_file_request(conn, path, file);
  9586. #if !defined(NO_CACHING)
  9587. } else if ((!conn->in_error_handler)
  9588. && is_not_modified(conn, &file->stat)) {
  9589. /* Send 304 "Not Modified" - this must not send any body data */
  9590. handle_not_modified_static_file_request(conn, file);
  9591. #endif /* !NO_CACHING */
  9592. } else {
  9593. handle_static_file_request(conn, path, file, NULL, NULL);
  9594. }
  9595. }
  9596. static void
  9597. close_all_listening_sockets(struct mg_context *ctx)
  9598. {
  9599. unsigned int i;
  9600. if (!ctx) {
  9601. return;
  9602. }
  9603. for (i = 0; i < ctx->num_listening_sockets; i++) {
  9604. closesocket(ctx->listening_sockets[i].sock);
  9605. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  9606. }
  9607. mg_free(ctx->listening_sockets);
  9608. ctx->listening_sockets = NULL;
  9609. mg_free(ctx->listening_socket_fds);
  9610. ctx->listening_socket_fds = NULL;
  9611. }
  9612. /* Valid listening port specification is: [ip_address:]port[s]
  9613. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  9614. * Examples for IPv6: [::]:80, [::1]:80,
  9615. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  9616. * see https://tools.ietf.org/html/rfc3513#section-2.2
  9617. * In order to bind to both, IPv4 and IPv6, you can either add
  9618. * both ports using 8080,[::]:8080, or the short form +8080.
  9619. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  9620. * one only accepting IPv4 the other only IPv6. +8080 creates
  9621. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  9622. * environment, they might work differently, or might not work
  9623. * at all - it must be tested what options work best in the
  9624. * relevant network environment.
  9625. */
  9626. static int
  9627. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  9628. {
  9629. unsigned int a, b, c, d, port;
  9630. int ch, len;
  9631. #if defined(USE_IPV6)
  9632. char buf[100] = {0};
  9633. #endif
  9634. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  9635. * Also, all-zeroes in the socket address means binding to all addresses
  9636. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  9637. memset(so, 0, sizeof(*so));
  9638. so->lsa.sin.sin_family = AF_INET;
  9639. *ip_version = 0;
  9640. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  9641. == 5) {
  9642. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  9643. so->lsa.sin.sin_addr.s_addr =
  9644. htonl((a << 24) | (b << 16) | (c << 8) | d);
  9645. so->lsa.sin.sin_port = htons((uint16_t)port);
  9646. *ip_version = 4;
  9647. #if defined(USE_IPV6)
  9648. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  9649. && mg_inet_pton(
  9650. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  9651. /* IPv6 address, examples: see above */
  9652. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  9653. */
  9654. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  9655. *ip_version = 6;
  9656. #endif
  9657. } else if ((vec->ptr[0] == '+')
  9658. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  9659. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  9660. /* Add 1 to len for the + character we skipped before */
  9661. len++;
  9662. #if defined(USE_IPV6)
  9663. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  9664. so->lsa.sin6.sin6_family = AF_INET6;
  9665. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  9666. *ip_version = 4 + 6;
  9667. #else
  9668. /* Bind to IPv4 only, since IPv6 is not built in. */
  9669. so->lsa.sin.sin_port = htons((uint16_t)port);
  9670. *ip_version = 4;
  9671. #endif
  9672. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  9673. /* If only port is specified, bind to IPv4, INADDR_ANY */
  9674. so->lsa.sin.sin_port = htons((uint16_t)port);
  9675. *ip_version = 4;
  9676. } else {
  9677. /* Parsing failure. Make port invalid. */
  9678. port = 0;
  9679. len = 0;
  9680. }
  9681. /* sscanf and the option splitting code ensure the following condition
  9682. */
  9683. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  9684. *ip_version = 0;
  9685. return 0;
  9686. }
  9687. ch = vec->ptr[len]; /* Next character after the port number */
  9688. so->is_ssl = (ch == 's');
  9689. so->ssl_redir = (ch == 'r');
  9690. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  9691. if (is_valid_port(port)
  9692. && (ch == '\0' || ch == 's' || ch == 'r' || ch == ',')) {
  9693. return 1;
  9694. }
  9695. /* Reset ip_version to 0 of there is an error */
  9696. *ip_version = 0;
  9697. return 0;
  9698. }
  9699. static int
  9700. set_ports_option(struct mg_context *ctx)
  9701. {
  9702. const char *list;
  9703. int on = 1;
  9704. #if defined(USE_IPV6)
  9705. int off = 0;
  9706. #endif
  9707. struct vec vec;
  9708. struct socket so, *ptr;
  9709. struct pollfd *pfd;
  9710. union usa usa;
  9711. socklen_t len;
  9712. int ip_version;
  9713. int portsTotal = 0;
  9714. int portsOk = 0;
  9715. if (!ctx) {
  9716. return 0;
  9717. }
  9718. memset(&so, 0, sizeof(so));
  9719. memset(&usa, 0, sizeof(usa));
  9720. len = sizeof(usa);
  9721. list = ctx->config[LISTENING_PORTS];
  9722. while ((list = next_option(list, &vec, NULL)) != NULL) {
  9723. portsTotal++;
  9724. if (!parse_port_string(&vec, &so, &ip_version)) {
  9725. mg_cry(fc(ctx),
  9726. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  9727. (int)vec.len,
  9728. vec.ptr,
  9729. portsTotal,
  9730. "[IP_ADDRESS:]PORT[s|r]");
  9731. continue;
  9732. }
  9733. #if !defined(NO_SSL)
  9734. if (so.is_ssl && ctx->ssl_ctx == NULL) {
  9735. mg_cry(fc(ctx),
  9736. "Cannot add SSL socket (entry %i). Is -ssl_certificate "
  9737. "option set?",
  9738. portsTotal);
  9739. continue;
  9740. }
  9741. #endif
  9742. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  9743. == INVALID_SOCKET) {
  9744. mg_cry(fc(ctx), "cannot create socket (entry %i)", portsTotal);
  9745. continue;
  9746. }
  9747. #ifdef _WIN32
  9748. /* Windows SO_REUSEADDR lets many procs binds to a
  9749. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  9750. * if someone already has the socket -- DTL */
  9751. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  9752. * Windows might need a few seconds before
  9753. * the same port can be used again in the
  9754. * same process, so a short Sleep may be
  9755. * required between mg_stop and mg_start.
  9756. */
  9757. if (setsockopt(so.sock,
  9758. SOL_SOCKET,
  9759. SO_EXCLUSIVEADDRUSE,
  9760. (SOCK_OPT_TYPE)&on,
  9761. sizeof(on)) != 0) {
  9762. /* Set reuse option, but don't abort on errors. */
  9763. mg_cry(fc(ctx),
  9764. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  9765. portsTotal);
  9766. }
  9767. #else
  9768. if (setsockopt(so.sock,
  9769. SOL_SOCKET,
  9770. SO_REUSEADDR,
  9771. (SOCK_OPT_TYPE)&on,
  9772. sizeof(on)) != 0) {
  9773. /* Set reuse option, but don't abort on errors. */
  9774. mg_cry(fc(ctx),
  9775. "cannot set socket option SO_REUSEADDR (entry %i)",
  9776. portsTotal);
  9777. }
  9778. #endif
  9779. if (ip_version > 4) {
  9780. #if defined(USE_IPV6)
  9781. if (ip_version == 6) {
  9782. if (so.lsa.sa.sa_family == AF_INET6
  9783. && setsockopt(so.sock,
  9784. IPPROTO_IPV6,
  9785. IPV6_V6ONLY,
  9786. (void *)&off,
  9787. sizeof(off)) != 0) {
  9788. /* Set IPv6 only option, but don't abort on errors. */
  9789. mg_cry(fc(ctx),
  9790. "cannot set socket option IPV6_V6ONLY (entry %i)",
  9791. portsTotal);
  9792. }
  9793. }
  9794. #else
  9795. mg_cry(fc(ctx), "IPv6 not available");
  9796. closesocket(so.sock);
  9797. so.sock = INVALID_SOCKET;
  9798. continue;
  9799. #endif
  9800. }
  9801. if (so.lsa.sa.sa_family == AF_INET) {
  9802. len = sizeof(so.lsa.sin);
  9803. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  9804. mg_cry(fc(ctx),
  9805. "cannot bind to %.*s: %d (%s)",
  9806. (int)vec.len,
  9807. vec.ptr,
  9808. (int)ERRNO,
  9809. strerror(errno));
  9810. closesocket(so.sock);
  9811. so.sock = INVALID_SOCKET;
  9812. continue;
  9813. }
  9814. }
  9815. #if defined(USE_IPV6)
  9816. else if (so.lsa.sa.sa_family == AF_INET6) {
  9817. len = sizeof(so.lsa.sin6);
  9818. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  9819. mg_cry(fc(ctx),
  9820. "cannot bind to IPv6 %.*s: %d (%s)",
  9821. (int)vec.len,
  9822. vec.ptr,
  9823. (int)ERRNO,
  9824. strerror(errno));
  9825. closesocket(so.sock);
  9826. so.sock = INVALID_SOCKET;
  9827. continue;
  9828. }
  9829. }
  9830. #endif
  9831. else {
  9832. mg_cry(fc(ctx),
  9833. "cannot bind: address family not supported (entry %i)",
  9834. portsTotal);
  9835. continue;
  9836. }
  9837. if (listen(so.sock, SOMAXCONN) != 0) {
  9838. mg_cry(fc(ctx),
  9839. "cannot listen to %.*s: %d (%s)",
  9840. (int)vec.len,
  9841. vec.ptr,
  9842. (int)ERRNO,
  9843. strerror(errno));
  9844. closesocket(so.sock);
  9845. so.sock = INVALID_SOCKET;
  9846. continue;
  9847. }
  9848. if (getsockname(so.sock, &(usa.sa), &len) != 0
  9849. || usa.sa.sa_family != so.lsa.sa.sa_family) {
  9850. int err = (int)ERRNO;
  9851. mg_cry(fc(ctx),
  9852. "call to getsockname failed %.*s: %d (%s)",
  9853. (int)vec.len,
  9854. vec.ptr,
  9855. err,
  9856. strerror(errno));
  9857. closesocket(so.sock);
  9858. so.sock = INVALID_SOCKET;
  9859. continue;
  9860. }
  9861. /* Update lsa port in case of random free ports */
  9862. #if defined(USE_IPV6)
  9863. if (so.lsa.sa.sa_family == AF_INET6) {
  9864. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  9865. } else
  9866. #endif
  9867. {
  9868. so.lsa.sin.sin_port = usa.sin.sin_port;
  9869. }
  9870. if ((ptr = (struct socket *)
  9871. mg_realloc(ctx->listening_sockets,
  9872. (ctx->num_listening_sockets + 1)
  9873. * sizeof(ctx->listening_sockets[0]))) == NULL) {
  9874. mg_cry(fc(ctx), "%s", "Out of memory");
  9875. closesocket(so.sock);
  9876. so.sock = INVALID_SOCKET;
  9877. continue;
  9878. }
  9879. if ((pfd = (struct pollfd *)mg_realloc(
  9880. ctx->listening_socket_fds,
  9881. (ctx->num_listening_sockets + 1)
  9882. * sizeof(ctx->listening_socket_fds[0]))) == NULL) {
  9883. mg_cry(fc(ctx), "%s", "Out of memory");
  9884. closesocket(so.sock);
  9885. so.sock = INVALID_SOCKET;
  9886. mg_free(ptr);
  9887. continue;
  9888. }
  9889. set_close_on_exec(so.sock, fc(ctx));
  9890. ctx->listening_sockets = ptr;
  9891. ctx->listening_sockets[ctx->num_listening_sockets] = so;
  9892. ctx->listening_socket_fds = pfd;
  9893. ctx->num_listening_sockets++;
  9894. portsOk++;
  9895. }
  9896. if (portsOk != portsTotal) {
  9897. close_all_listening_sockets(ctx);
  9898. portsOk = 0;
  9899. }
  9900. return portsOk;
  9901. }
  9902. static const char *
  9903. header_val(const struct mg_connection *conn, const char *header)
  9904. {
  9905. const char *header_value;
  9906. if ((header_value = mg_get_header(conn, header)) == NULL) {
  9907. return "-";
  9908. } else {
  9909. return header_value;
  9910. }
  9911. }
  9912. static void
  9913. log_access(const struct mg_connection *conn)
  9914. {
  9915. const struct mg_request_info *ri;
  9916. struct mg_file fi;
  9917. char date[64], src_addr[IP_ADDR_STR_LEN];
  9918. struct tm *tm;
  9919. const char *referer;
  9920. const char *user_agent;
  9921. char buf[4096];
  9922. if (!conn || !conn->ctx) {
  9923. return;
  9924. }
  9925. if (conn->ctx->config[ACCESS_LOG_FILE] != NULL) {
  9926. if (mg_fopen(conn,
  9927. conn->ctx->config[ACCESS_LOG_FILE],
  9928. MG_FOPEN_MODE_APPEND,
  9929. &fi) == 0) {
  9930. fi.access.fp = NULL;
  9931. }
  9932. } else {
  9933. fi.access.fp = NULL;
  9934. }
  9935. /* Log is written to a file and/or a callback. If both are not set,
  9936. * executing the rest of the function is pointless. */
  9937. if ((fi.access.fp == NULL) && (conn->ctx->callbacks.log_access == NULL)) {
  9938. return;
  9939. }
  9940. tm = localtime(&conn->conn_birth_time);
  9941. if (tm != NULL) {
  9942. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  9943. } else {
  9944. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  9945. date[sizeof(date) - 1] = '\0';
  9946. }
  9947. ri = &conn->request_info;
  9948. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9949. referer = header_val(conn, "Referer");
  9950. user_agent = header_val(conn, "User-Agent");
  9951. mg_snprintf(conn,
  9952. NULL, /* Ignore truncation in access log */
  9953. buf,
  9954. sizeof(buf),
  9955. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  9956. src_addr,
  9957. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  9958. date,
  9959. ri->request_method ? ri->request_method : "-",
  9960. ri->request_uri ? ri->request_uri : "-",
  9961. ri->query_string ? "?" : "",
  9962. ri->query_string ? ri->query_string : "",
  9963. ri->http_version,
  9964. conn->status_code,
  9965. conn->num_bytes_sent,
  9966. referer,
  9967. user_agent);
  9968. if (conn->ctx->callbacks.log_access) {
  9969. conn->ctx->callbacks.log_access(conn, buf);
  9970. }
  9971. if (fi.access.fp) {
  9972. int ok = 1;
  9973. flockfile(fi.access.fp);
  9974. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  9975. ok = 0;
  9976. }
  9977. if (fflush(fi.access.fp) != 0) {
  9978. ok = 0;
  9979. }
  9980. funlockfile(fi.access.fp);
  9981. if (mg_fclose(&fi.access) != 0) {
  9982. ok = 0;
  9983. }
  9984. if (!ok) {
  9985. mg_cry(conn,
  9986. "Error writing log file %s",
  9987. conn->ctx->config[ACCESS_LOG_FILE]);
  9988. }
  9989. }
  9990. }
  9991. /* Verify given socket address against the ACL.
  9992. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  9993. */
  9994. static int
  9995. check_acl(struct mg_context *ctx, uint32_t remote_ip)
  9996. {
  9997. int allowed, flag;
  9998. uint32_t net, mask;
  9999. struct vec vec;
  10000. if (ctx) {
  10001. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  10002. /* If any ACL is set, deny by default */
  10003. allowed = (list == NULL) ? '+' : '-';
  10004. while ((list = next_option(list, &vec, NULL)) != NULL) {
  10005. flag = vec.ptr[0];
  10006. if ((flag != '+' && flag != '-')
  10007. || parse_net(&vec.ptr[1], &net, &mask) == 0) {
  10008. mg_cry(fc(ctx),
  10009. "%s: subnet must be [+|-]x.x.x.x[/x]",
  10010. __func__);
  10011. return -1;
  10012. }
  10013. if (net == (remote_ip & mask)) {
  10014. allowed = flag;
  10015. }
  10016. }
  10017. return allowed == '+';
  10018. }
  10019. return -1;
  10020. }
  10021. #if !defined(_WIN32)
  10022. static int
  10023. set_uid_option(struct mg_context *ctx)
  10024. {
  10025. struct passwd *pw;
  10026. if (ctx) {
  10027. const char *uid = ctx->config[RUN_AS_USER];
  10028. int success = 0;
  10029. if (uid == NULL) {
  10030. success = 1;
  10031. } else {
  10032. if ((pw = getpwnam(uid)) == NULL) {
  10033. mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  10034. } else if (setgid(pw->pw_gid) == -1) {
  10035. mg_cry(fc(ctx),
  10036. "%s: setgid(%s): %s",
  10037. __func__,
  10038. uid,
  10039. strerror(errno));
  10040. } else if (setgroups(0, NULL)) {
  10041. mg_cry(fc(ctx),
  10042. "%s: setgroups(): %s",
  10043. __func__,
  10044. strerror(errno));
  10045. } else if (setuid(pw->pw_uid) == -1) {
  10046. mg_cry(fc(ctx),
  10047. "%s: setuid(%s): %s",
  10048. __func__,
  10049. uid,
  10050. strerror(errno));
  10051. } else {
  10052. success = 1;
  10053. }
  10054. }
  10055. return success;
  10056. }
  10057. return 0;
  10058. }
  10059. #endif /* !_WIN32 */
  10060. static void
  10061. tls_dtor(void *key)
  10062. {
  10063. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  10064. /* key == pthread_getspecific(sTlsKey); */
  10065. if (tls) {
  10066. if (tls->is_master == 2) {
  10067. tls->is_master = -3; /* Mark memory as dead */
  10068. mg_free(tls);
  10069. }
  10070. }
  10071. pthread_setspecific(sTlsKey, NULL);
  10072. }
  10073. #if !defined(NO_SSL)
  10074. /* Must be set if sizeof(pthread_t) > sizeof(unsigned long) */
  10075. static unsigned long
  10076. ssl_id_callback(void)
  10077. {
  10078. #ifdef _WIN32
  10079. return GetCurrentThreadId();
  10080. #else
  10081. #ifdef __clang__
  10082. #pragma clang diagnostic push
  10083. #pragma clang diagnostic ignored "-Wunreachable-code"
  10084. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  10085. * or not, so one of the two conditions will be unreachable by construction.
  10086. * Unfortunately the C standard does not define a way to check this at
  10087. * compile time, since the #if preprocessor conditions can not use the sizeof
  10088. * operator as an argument. */
  10089. #endif
  10090. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  10091. /* This is the problematic case for CRYPTO_set_id_callback:
  10092. * The OS pthread_t can not be cast to unsigned long. */
  10093. struct mg_workerTLS *tls =
  10094. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  10095. if (tls == NULL) {
  10096. /* SSL called from an unknown thread: Create some thread index.
  10097. */
  10098. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  10099. tls->is_master = -2; /* -2 means "3rd party thread" */
  10100. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  10101. pthread_setspecific(sTlsKey, tls);
  10102. }
  10103. return tls->thread_idx;
  10104. } else {
  10105. /* pthread_t may be any data type, so a simple cast to unsigned long
  10106. * can rise a warning/error, depending on the platform.
  10107. * Here memcpy is used as an anything-to-anything cast. */
  10108. unsigned long ret = 0;
  10109. pthread_t t = pthread_self();
  10110. memcpy(&ret, &t, sizeof(pthread_t));
  10111. return ret;
  10112. }
  10113. #ifdef __clang__
  10114. #pragma clang diagnostic pop
  10115. #endif
  10116. #endif
  10117. }
  10118. static int ssl_use_pem_file(struct mg_context *ctx, const char *pem);
  10119. static const char *ssl_error(void);
  10120. static int
  10121. refresh_trust(struct mg_connection *conn)
  10122. {
  10123. static int reload_lock = 0;
  10124. static long int data_check = 0;
  10125. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  10126. struct stat cert_buf;
  10127. long int t;
  10128. char *pem;
  10129. int should_verify_peer;
  10130. if ((pem = conn->ctx->config[SSL_CERTIFICATE]) == NULL) {
  10131. /* If peem is NULL and conn->ctx->callbacks.init_ssl is not,
  10132. * refresh_trust still can not work. */
  10133. return 0;
  10134. }
  10135. t = data_check;
  10136. if (stat(pem, &cert_buf) != -1) {
  10137. t = (long int)cert_buf.st_mtime;
  10138. }
  10139. if (data_check != t) {
  10140. data_check = t;
  10141. should_verify_peer =
  10142. (conn->ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  10143. && (mg_strcasecmp(conn->ctx->config[SSL_DO_VERIFY_PEER], "yes")
  10144. == 0);
  10145. if (should_verify_peer) {
  10146. char *ca_path = conn->ctx->config[SSL_CA_PATH];
  10147. char *ca_file = conn->ctx->config[SSL_CA_FILE];
  10148. if (SSL_CTX_load_verify_locations(conn->ctx->ssl_ctx,
  10149. ca_file,
  10150. ca_path) != 1) {
  10151. mg_cry(fc(conn->ctx),
  10152. "SSL_CTX_load_verify_locations error: %s "
  10153. "ssl_verify_peer requires setting "
  10154. "either ssl_ca_path or ssl_ca_file. Is any of them "
  10155. "present in "
  10156. "the .conf file?",
  10157. ssl_error());
  10158. return 0;
  10159. }
  10160. }
  10161. if (1 == mg_atomic_inc(p_reload_lock)) {
  10162. if (ssl_use_pem_file(conn->ctx, pem) == 0) {
  10163. return 0;
  10164. }
  10165. *p_reload_lock = 0;
  10166. }
  10167. }
  10168. /* lock while cert is reloading */
  10169. while (*p_reload_lock) {
  10170. sleep(1);
  10171. }
  10172. return 1;
  10173. }
  10174. static pthread_mutex_t *ssl_mutexes;
  10175. static int
  10176. sslize(struct mg_connection *conn,
  10177. SSL_CTX *s,
  10178. int (*func)(SSL *),
  10179. volatile int *stop_server)
  10180. {
  10181. int ret, err;
  10182. int short_trust;
  10183. unsigned i;
  10184. if (!conn) {
  10185. return 0;
  10186. }
  10187. short_trust =
  10188. (conn->ctx->config[SSL_SHORT_TRUST] != NULL)
  10189. && (mg_strcasecmp(conn->ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  10190. if (short_trust) {
  10191. int trust_ret = refresh_trust(conn);
  10192. if (!trust_ret) {
  10193. return trust_ret;
  10194. }
  10195. }
  10196. conn->ssl = SSL_new(s);
  10197. if (conn->ssl == NULL) {
  10198. return 0;
  10199. }
  10200. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  10201. if (ret != 1) {
  10202. err = SSL_get_error(conn->ssl, ret);
  10203. (void)err; /* TODO: set some error message */
  10204. SSL_free(conn->ssl);
  10205. conn->ssl = NULL;
  10206. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  10207. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  10208. ERR_remove_state(0);
  10209. return 0;
  10210. }
  10211. /* SSL functions may fail and require to be called again:
  10212. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  10213. * Here "func" could be SSL_connect or SSL_accept. */
  10214. for (i = 16; i <= 1024; i *= 2) {
  10215. ret = func(conn->ssl);
  10216. if (ret != 1) {
  10217. err = SSL_get_error(conn->ssl, ret);
  10218. if ((err == SSL_ERROR_WANT_CONNECT)
  10219. || (err == SSL_ERROR_WANT_ACCEPT)
  10220. || (err == SSL_ERROR_WANT_READ)
  10221. || (err == SSL_ERROR_WANT_WRITE)) {
  10222. /* Need to retry the function call "later".
  10223. * See https://linux.die.net/man/3/ssl_get_error
  10224. * This is typical for non-blocking sockets. */
  10225. if (*stop_server) {
  10226. /* Don't wait if the server is going to be stopped. */
  10227. break;
  10228. }
  10229. mg_sleep(i);
  10230. } else if (err == SSL_ERROR_SYSCALL) {
  10231. /* This is an IO error. Look at errno. */
  10232. err = errno;
  10233. /* TODO: set some error message */
  10234. break;
  10235. } else {
  10236. /* This is an SSL specific error */
  10237. /* TODO: set some error message */
  10238. break;
  10239. }
  10240. } else {
  10241. /* success */
  10242. break;
  10243. }
  10244. }
  10245. if (ret != 1) {
  10246. SSL_free(conn->ssl);
  10247. conn->ssl = NULL;
  10248. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  10249. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  10250. ERR_remove_state(0);
  10251. return 0;
  10252. }
  10253. return 1;
  10254. }
  10255. /* Return OpenSSL error message (from CRYPTO lib) */
  10256. static const char *
  10257. ssl_error(void)
  10258. {
  10259. unsigned long err;
  10260. err = ERR_get_error();
  10261. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  10262. }
  10263. static int
  10264. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  10265. {
  10266. int i;
  10267. const char hexdigit[] = "0123456789abcdef";
  10268. if (memlen <= 0 || buflen <= 0) {
  10269. return 0;
  10270. }
  10271. if (buflen < (3 * memlen)) {
  10272. return 0;
  10273. }
  10274. for (i = 0; i < memlen; i++) {
  10275. if (i > 0) {
  10276. buf[3 * i - 1] = ' ';
  10277. }
  10278. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  10279. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  10280. }
  10281. buf[3 * memlen - 1] = 0;
  10282. return 1;
  10283. }
  10284. static void
  10285. ssl_get_client_cert_info(struct mg_connection *conn)
  10286. {
  10287. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  10288. if (cert) {
  10289. char str_subject[1024];
  10290. char str_issuer[1024];
  10291. char str_serial[1024];
  10292. char str_finger[1024];
  10293. unsigned char buf[256];
  10294. int len;
  10295. unsigned int ulen;
  10296. /* Handle to algorithm used for fingerprint */
  10297. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  10298. /* Get Subject and issuer */
  10299. X509_NAME *subj = X509_get_subject_name(cert);
  10300. X509_NAME *iss = X509_get_issuer_name(cert);
  10301. /* Get serial number */
  10302. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  10303. /* Translate subject and issuer to a string */
  10304. (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
  10305. (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
  10306. /* Translate serial number to a hex string */
  10307. len = i2c_ASN1_INTEGER(serial, NULL);
  10308. if ((len > 0) && ((unsigned)len < (unsigned)sizeof(buf))) {
  10309. unsigned char *pbuf = buf;
  10310. int len2 = i2c_ASN1_INTEGER(serial, &pbuf);
  10311. if (!hexdump2string(
  10312. buf, len2, str_serial, (int)sizeof(str_serial))) {
  10313. *str_serial = 0;
  10314. }
  10315. } else {
  10316. *str_serial = 0;
  10317. }
  10318. /* Calculate SHA1 fingerprint and store as a hex string */
  10319. ulen = 0;
  10320. ASN1_digest((int (*)())i2d_X509, digest, (char *)cert, buf, &ulen);
  10321. if (!hexdump2string(
  10322. buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
  10323. *str_finger = 0;
  10324. }
  10325. conn->request_info.client_cert =
  10326. (struct client_cert *)mg_malloc(sizeof(struct client_cert));
  10327. if (conn->request_info.client_cert) {
  10328. conn->request_info.client_cert->subject = mg_strdup(str_subject);
  10329. conn->request_info.client_cert->issuer = mg_strdup(str_issuer);
  10330. conn->request_info.client_cert->serial = mg_strdup(str_serial);
  10331. conn->request_info.client_cert->finger = mg_strdup(str_finger);
  10332. } else {
  10333. /* TODO: write some OOM message */
  10334. }
  10335. X509_free(cert);
  10336. }
  10337. }
  10338. static void
  10339. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  10340. {
  10341. (void)line;
  10342. (void)file;
  10343. if (mode & 1) {
  10344. /* 1 is CRYPTO_LOCK */
  10345. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  10346. } else {
  10347. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  10348. }
  10349. }
  10350. #if !defined(NO_SSL_DL)
  10351. static void *
  10352. load_dll(struct mg_context *ctx, const char *dll_name, struct ssl_func *sw)
  10353. {
  10354. union {
  10355. void *p;
  10356. void (*fp)(void);
  10357. } u;
  10358. void *dll_handle;
  10359. struct ssl_func *fp;
  10360. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  10361. mg_cry(fc(ctx), "%s: cannot load %s", __func__, dll_name);
  10362. return NULL;
  10363. }
  10364. for (fp = sw; fp->name != NULL; fp++) {
  10365. #ifdef _WIN32
  10366. /* GetProcAddress() returns pointer to function */
  10367. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  10368. #else
  10369. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  10370. * pointers to function pointers. We need to use a union to make a
  10371. * cast. */
  10372. u.p = dlsym(dll_handle, fp->name);
  10373. #endif /* _WIN32 */
  10374. if (u.fp == NULL) {
  10375. mg_cry(fc(ctx),
  10376. "%s: %s: cannot find %s",
  10377. __func__,
  10378. dll_name,
  10379. fp->name);
  10380. dlclose(dll_handle);
  10381. return NULL;
  10382. } else {
  10383. fp->ptr = u.fp;
  10384. }
  10385. }
  10386. return dll_handle;
  10387. }
  10388. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  10389. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  10390. #endif /* NO_SSL_DL */
  10391. #if defined(SSL_ALREADY_INITIALIZED)
  10392. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  10393. #else
  10394. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  10395. #endif
  10396. static int
  10397. initialize_ssl(struct mg_context *ctx)
  10398. {
  10399. int i;
  10400. size_t size;
  10401. #if !defined(NO_SSL_DL)
  10402. if (!cryptolib_dll_handle) {
  10403. cryptolib_dll_handle = load_dll(ctx, CRYPTO_LIB, crypto_sw);
  10404. if (!cryptolib_dll_handle) {
  10405. return 0;
  10406. }
  10407. }
  10408. #endif /* NO_SSL_DL */
  10409. if (mg_atomic_inc(&cryptolib_users) > 1) {
  10410. return 1;
  10411. }
  10412. /* Initialize locking callbacks, needed for thread safety.
  10413. * http://www.openssl.org/support/faq.html#PROG1
  10414. */
  10415. i = CRYPTO_num_locks();
  10416. if (i < 0) {
  10417. i = 0;
  10418. }
  10419. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  10420. if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  10421. mg_cry(fc(ctx),
  10422. "%s: cannot allocate mutexes: %s",
  10423. __func__,
  10424. ssl_error());
  10425. return 0;
  10426. }
  10427. for (i = 0; i < CRYPTO_num_locks(); i++) {
  10428. pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr);
  10429. }
  10430. CRYPTO_set_locking_callback(&ssl_locking_callback);
  10431. CRYPTO_set_id_callback(&ssl_id_callback);
  10432. return 1;
  10433. }
  10434. static int
  10435. ssl_use_pem_file(struct mg_context *ctx, const char *pem)
  10436. {
  10437. if (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0) {
  10438. mg_cry(fc(ctx),
  10439. "%s: cannot open certificate file %s: %s",
  10440. __func__,
  10441. pem,
  10442. ssl_error());
  10443. return 0;
  10444. }
  10445. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  10446. if (SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0) {
  10447. mg_cry(fc(ctx),
  10448. "%s: cannot open private key file %s: %s",
  10449. __func__,
  10450. pem,
  10451. ssl_error());
  10452. return 0;
  10453. }
  10454. if (SSL_CTX_check_private_key(ctx->ssl_ctx) == 0) {
  10455. mg_cry(fc(ctx),
  10456. "%s: certificate and private key do not match: %s",
  10457. __func__,
  10458. pem);
  10459. return 0;
  10460. }
  10461. if (SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem) == 0) {
  10462. mg_cry(fc(ctx),
  10463. "%s: cannot use certificate chain file %s: %s",
  10464. __func__,
  10465. pem,
  10466. ssl_error());
  10467. return 0;
  10468. }
  10469. return 1;
  10470. }
  10471. static long
  10472. ssl_get_protocol(int version_id)
  10473. {
  10474. long ret = SSL_OP_ALL;
  10475. if (version_id > 0)
  10476. ret |= SSL_OP_NO_SSLv2;
  10477. if (version_id > 1)
  10478. ret |= SSL_OP_NO_SSLv3;
  10479. if (version_id > 2)
  10480. ret |= SSL_OP_NO_TLSv1;
  10481. if (version_id > 3)
  10482. ret |= SSL_OP_NO_TLSv1_1;
  10483. return ret;
  10484. }
  10485. /* Dynamically load SSL library. Set up ctx->ssl_ctx pointer. */
  10486. static int
  10487. set_ssl_option(struct mg_context *ctx)
  10488. {
  10489. const char *pem;
  10490. int callback_ret;
  10491. int should_verify_peer;
  10492. const char *ca_path;
  10493. const char *ca_file;
  10494. int use_default_verify_paths;
  10495. int verify_depth;
  10496. time_t now_rt = time(NULL);
  10497. struct timespec now_mt;
  10498. md5_byte_t ssl_context_id[16];
  10499. md5_state_t md5state;
  10500. int protocol_ver;
  10501. /* If PEM file is not specified and the init_ssl callback
  10502. * is not specified, skip SSL initialization. */
  10503. if (!ctx) {
  10504. return 0;
  10505. }
  10506. if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL
  10507. && ctx->callbacks.init_ssl == NULL) {
  10508. return 1;
  10509. }
  10510. if (!initialize_ssl(ctx)) {
  10511. return 0;
  10512. }
  10513. #if !defined(NO_SSL_DL)
  10514. if (!ssllib_dll_handle) {
  10515. ssllib_dll_handle = load_dll(ctx, SSL_LIB, ssl_sw);
  10516. if (!ssllib_dll_handle) {
  10517. return 0;
  10518. }
  10519. }
  10520. #endif /* NO_SSL_DL */
  10521. /* Initialize SSL library */
  10522. SSL_library_init();
  10523. SSL_load_error_strings();
  10524. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  10525. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  10526. return 0;
  10527. }
  10528. SSL_CTX_clear_options(ctx->ssl_ctx,
  10529. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  10530. | SSL_OP_NO_TLSv1_1);
  10531. protocol_ver = atoi(ctx->config[SSL_PROTOCOL_VERSION]);
  10532. SSL_CTX_set_options(ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  10533. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  10534. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  10535. SSL_CTX_set_ecdh_auto(ctx->ssl_ctx, 1);
  10536. /* If a callback has been specified, call it. */
  10537. callback_ret =
  10538. (ctx->callbacks.init_ssl == NULL)
  10539. ? 0
  10540. : (ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data));
  10541. /* If callback returns 0, civetweb sets up the SSL certificate.
  10542. * If it returns 1, civetweb assumes the calback already did this.
  10543. * If it returns -1, initializing ssl fails. */
  10544. if (callback_ret < 0) {
  10545. mg_cry(fc(ctx), "SSL callback returned error: %i", callback_ret);
  10546. return 0;
  10547. }
  10548. if (callback_ret > 0) {
  10549. if (pem != NULL) {
  10550. (void)SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
  10551. }
  10552. return 1;
  10553. }
  10554. /* Use some UID as session context ID. */
  10555. md5_init(&md5state);
  10556. md5_append(&md5state, (const md5_byte_t *)&now_rt, sizeof(now_rt));
  10557. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  10558. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  10559. md5_append(&md5state,
  10560. (const md5_byte_t *)ctx->config[LISTENING_PORTS],
  10561. strlen(ctx->config[LISTENING_PORTS]));
  10562. md5_append(&md5state, (const md5_byte_t *)ctx, sizeof(*ctx));
  10563. md5_finish(&md5state, ssl_context_id);
  10564. SSL_CTX_set_session_id_context(ctx->ssl_ctx,
  10565. (const unsigned char *)&ssl_context_id,
  10566. sizeof(ssl_context_id));
  10567. if (pem != NULL) {
  10568. if (!ssl_use_pem_file(ctx, pem)) {
  10569. return 0;
  10570. }
  10571. }
  10572. should_verify_peer =
  10573. (ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  10574. && (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0);
  10575. use_default_verify_paths =
  10576. (ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  10577. && (mg_strcasecmp(ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes") == 0);
  10578. if (should_verify_peer) {
  10579. ca_path = ctx->config[SSL_CA_PATH];
  10580. ca_file = ctx->config[SSL_CA_FILE];
  10581. if (SSL_CTX_load_verify_locations(ctx->ssl_ctx, ca_file, ca_path)
  10582. != 1) {
  10583. mg_cry(fc(ctx),
  10584. "SSL_CTX_load_verify_locations error: %s "
  10585. "ssl_verify_peer requires setting "
  10586. "either ssl_ca_path or ssl_ca_file. Is any of them "
  10587. "present in "
  10588. "the .conf file?",
  10589. ssl_error());
  10590. return 0;
  10591. }
  10592. SSL_CTX_set_verify(ctx->ssl_ctx,
  10593. SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  10594. NULL);
  10595. if (use_default_verify_paths
  10596. && SSL_CTX_set_default_verify_paths(ctx->ssl_ctx) != 1) {
  10597. mg_cry(fc(ctx),
  10598. "SSL_CTX_set_default_verify_paths error: %s",
  10599. ssl_error());
  10600. return 0;
  10601. }
  10602. if (ctx->config[SSL_VERIFY_DEPTH]) {
  10603. verify_depth = atoi(ctx->config[SSL_VERIFY_DEPTH]);
  10604. SSL_CTX_set_verify_depth(ctx->ssl_ctx, verify_depth);
  10605. }
  10606. }
  10607. if (ctx->config[SSL_CIPHER_LIST] != NULL) {
  10608. if (SSL_CTX_set_cipher_list(ctx->ssl_ctx, ctx->config[SSL_CIPHER_LIST])
  10609. != 1) {
  10610. mg_cry(fc(ctx), "SSL_CTX_set_cipher_list error: %s", ssl_error());
  10611. }
  10612. }
  10613. return 1;
  10614. }
  10615. static void
  10616. uninitialize_ssl(struct mg_context *ctx)
  10617. {
  10618. int i;
  10619. (void)ctx;
  10620. if (mg_atomic_dec(&cryptolib_users) == 0) {
  10621. /* Shutdown according to
  10622. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  10623. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  10624. */
  10625. CRYPTO_set_locking_callback(NULL);
  10626. CRYPTO_set_id_callback(NULL);
  10627. ENGINE_cleanup();
  10628. CONF_modules_unload(1);
  10629. ERR_free_strings();
  10630. EVP_cleanup();
  10631. CRYPTO_cleanup_all_ex_data();
  10632. ERR_remove_state(0);
  10633. for (i = 0; i < CRYPTO_num_locks(); i++) {
  10634. pthread_mutex_destroy(&ssl_mutexes[i]);
  10635. }
  10636. mg_free(ssl_mutexes);
  10637. ssl_mutexes = NULL;
  10638. }
  10639. }
  10640. #endif /* !NO_SSL */
  10641. static int
  10642. set_gpass_option(struct mg_context *ctx)
  10643. {
  10644. if (ctx) {
  10645. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10646. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  10647. if (path != NULL && !mg_stat(fc(ctx), path, &file.stat)) {
  10648. mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  10649. return 0;
  10650. }
  10651. return 1;
  10652. }
  10653. return 0;
  10654. }
  10655. static int
  10656. set_acl_option(struct mg_context *ctx)
  10657. {
  10658. return check_acl(ctx, (uint32_t)0x7f000001UL) != -1;
  10659. }
  10660. static void
  10661. reset_per_request_attributes(struct mg_connection *conn)
  10662. {
  10663. if (!conn) {
  10664. return;
  10665. }
  10666. conn->path_info = NULL;
  10667. conn->num_bytes_sent = conn->consumed_content = 0;
  10668. conn->status_code = -1;
  10669. conn->is_chunked = 0;
  10670. conn->must_close = conn->request_len = conn->throttle = 0;
  10671. conn->request_info.content_length = -1;
  10672. conn->request_info.remote_user = NULL;
  10673. conn->request_info.request_method = NULL;
  10674. conn->request_info.request_uri = NULL;
  10675. conn->request_info.local_uri = NULL;
  10676. conn->request_info.uri = NULL; /* TODO: cleanup uri,
  10677. * local_uri and request_uri */
  10678. conn->request_info.http_version = NULL;
  10679. conn->request_info.num_headers = 0;
  10680. conn->data_len = 0;
  10681. conn->chunk_remainder = 0;
  10682. }
  10683. static int
  10684. set_sock_timeout(SOCKET sock, int milliseconds)
  10685. {
  10686. int r0 = 0, r1, r2;
  10687. #ifdef _WIN32
  10688. /* Windows specific */
  10689. DWORD tv = (DWORD)milliseconds;
  10690. #else
  10691. /* Linux, ... (not Windows) */
  10692. struct timeval tv;
  10693. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  10694. * max. time waiting for the acknowledged of TCP data before the connection
  10695. * will be forcefully closed and ETIMEDOUT is returned to the application.
  10696. * If this option is not set, the default timeout of 20-30 minutes is used.
  10697. */
  10698. /* #define TCP_USER_TIMEOUT (18) */
  10699. #if defined(TCP_USER_TIMEOUT)
  10700. unsigned int uto = (unsigned int)milliseconds;
  10701. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  10702. #endif
  10703. memset(&tv, 0, sizeof(tv));
  10704. tv.tv_sec = milliseconds / 1000;
  10705. tv.tv_usec = (milliseconds * 1000) % 1000000;
  10706. #endif /* _WIN32 */
  10707. r1 = setsockopt(
  10708. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  10709. r2 = setsockopt(
  10710. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  10711. return r0 || r1 || r2;
  10712. }
  10713. static int
  10714. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  10715. {
  10716. if (setsockopt(sock,
  10717. IPPROTO_TCP,
  10718. TCP_NODELAY,
  10719. (SOCK_OPT_TYPE)&nodelay_on,
  10720. sizeof(nodelay_on)) != 0) {
  10721. /* Error */
  10722. return 1;
  10723. }
  10724. /* OK */
  10725. return 0;
  10726. }
  10727. static void
  10728. close_socket_gracefully(struct mg_connection *conn)
  10729. {
  10730. #if defined(_WIN32)
  10731. char buf[MG_BUF_LEN];
  10732. int n;
  10733. #endif
  10734. struct linger linger;
  10735. int error_code = 0;
  10736. socklen_t opt_len = sizeof(error_code);
  10737. if (!conn) {
  10738. return;
  10739. }
  10740. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  10741. * "Note that enabling a nonzero timeout on a nonblocking socket
  10742. * is not recommended.", so set it to blocking now */
  10743. set_blocking_mode(conn->client.sock, 1);
  10744. /* Send FIN to the client */
  10745. shutdown(conn->client.sock, SHUTDOWN_WR);
  10746. #if defined(_WIN32)
  10747. /* Read and discard pending incoming data. If we do not do that and
  10748. * close
  10749. * the socket, the data in the send buffer may be discarded. This
  10750. * behaviour is seen on Windows, when client keeps sending data
  10751. * when server decides to close the connection; then when client
  10752. * does recv() it gets no data back. */
  10753. do {
  10754. n = pull(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  10755. } while (n > 0);
  10756. #endif
  10757. /* Set linger option to avoid socket hanging out after close. This
  10758. * prevent ephemeral port exhaust problem under high QPS. */
  10759. linger.l_onoff = 1;
  10760. linger.l_linger = 1;
  10761. if (getsockopt(conn->client.sock,
  10762. SOL_SOCKET,
  10763. SO_ERROR,
  10764. (char *)&error_code,
  10765. &opt_len) != 0) {
  10766. /* Cannot determine if socket is already closed. This should
  10767. * not occur and never did in a test. Log an error message
  10768. * and continue. */
  10769. mg_cry(conn,
  10770. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  10771. __func__,
  10772. strerror(ERRNO));
  10773. } else if (error_code == ECONNRESET) {
  10774. /* Socket already closed by client/peer, close socket without linger */
  10775. } else {
  10776. /* Set linger timeout */
  10777. if (setsockopt(conn->client.sock,
  10778. SOL_SOCKET,
  10779. SO_LINGER,
  10780. (char *)&linger,
  10781. sizeof(linger)) != 0) {
  10782. mg_cry(conn,
  10783. "%s: setsockopt(SOL_SOCKET SO_LINGER) failed: %s",
  10784. __func__,
  10785. strerror(ERRNO));
  10786. }
  10787. }
  10788. /* Now we know that our FIN is ACK-ed, safe to close */
  10789. closesocket(conn->client.sock);
  10790. conn->client.sock = INVALID_SOCKET;
  10791. }
  10792. static void
  10793. close_connection(struct mg_connection *conn)
  10794. {
  10795. if (!conn || !conn->ctx) {
  10796. return;
  10797. }
  10798. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  10799. if (conn->lua_websocket_state) {
  10800. lua_websocket_close(conn, conn->lua_websocket_state);
  10801. conn->lua_websocket_state = NULL;
  10802. }
  10803. #endif
  10804. /* call the connection_close callback if assigned */
  10805. if ((conn->ctx->callbacks.connection_close != NULL)
  10806. && (conn->ctx->context_type == 1)) {
  10807. conn->ctx->callbacks.connection_close(conn);
  10808. }
  10809. mg_lock_connection(conn);
  10810. conn->must_close = 1;
  10811. #ifndef NO_SSL
  10812. if (conn->ssl != NULL) {
  10813. /* Run SSL_shutdown twice to ensure completly close SSL connection
  10814. */
  10815. SSL_shutdown(conn->ssl);
  10816. SSL_free(conn->ssl);
  10817. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  10818. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  10819. ERR_remove_state(0);
  10820. conn->ssl = NULL;
  10821. }
  10822. #endif
  10823. if (conn->client.sock != INVALID_SOCKET) {
  10824. close_socket_gracefully(conn);
  10825. conn->client.sock = INVALID_SOCKET;
  10826. }
  10827. mg_unlock_connection(conn);
  10828. }
  10829. void
  10830. mg_close_connection(struct mg_connection *conn)
  10831. {
  10832. struct mg_context *client_ctx = NULL;
  10833. if (conn == NULL) {
  10834. return;
  10835. }
  10836. #if defined(USE_WEBSOCKET)
  10837. if (conn->ctx->context_type == 2) {
  10838. unsigned int i;
  10839. /* ws/wss client */
  10840. client_ctx = conn->ctx;
  10841. /* client context: loops must end */
  10842. conn->ctx->stop_flag = 1;
  10843. /* We need to get the client thread out of the select/recv call here. */
  10844. /* Since we use a sleep quantum of some seconds to check for recv
  10845. * timeouts, we will just wait a few seconds in mg_join_thread. */
  10846. /* join worker thread */
  10847. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  10848. if (client_ctx->workerthreadids[i] != 0) {
  10849. mg_join_thread(client_ctx->workerthreadids[i]);
  10850. }
  10851. }
  10852. }
  10853. #else
  10854. (void)client_ctx;
  10855. #endif
  10856. close_connection(conn);
  10857. #ifndef NO_SSL
  10858. if (conn->client_ssl_ctx != NULL) {
  10859. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  10860. }
  10861. #endif
  10862. if (client_ctx != NULL) {
  10863. /* free context */
  10864. mg_free(client_ctx->workerthreadids);
  10865. mg_free(client_ctx);
  10866. (void)pthread_mutex_destroy(&conn->mutex);
  10867. mg_free(conn);
  10868. }
  10869. }
  10870. static struct mg_connection *
  10871. mg_connect_client_impl(const struct mg_client_options *client_options,
  10872. int use_ssl,
  10873. char *ebuf,
  10874. size_t ebuf_len)
  10875. {
  10876. static struct mg_context fake_ctx;
  10877. struct mg_connection *conn = NULL;
  10878. SOCKET sock;
  10879. union usa sa;
  10880. if (!connect_socket(&fake_ctx,
  10881. client_options->host,
  10882. client_options->port,
  10883. use_ssl,
  10884. ebuf,
  10885. ebuf_len,
  10886. &sock,
  10887. &sa)) {
  10888. ;
  10889. } else if ((conn = (struct mg_connection *)
  10890. mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) {
  10891. mg_snprintf(NULL,
  10892. NULL, /* No truncation check for ebuf */
  10893. ebuf,
  10894. ebuf_len,
  10895. "calloc(): %s",
  10896. strerror(ERRNO));
  10897. closesocket(sock);
  10898. #ifndef NO_SSL
  10899. } else if (use_ssl
  10900. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  10901. == NULL) {
  10902. mg_snprintf(NULL,
  10903. NULL, /* No truncation check for ebuf */
  10904. ebuf,
  10905. ebuf_len,
  10906. "SSL_CTX_new error");
  10907. closesocket(sock);
  10908. mg_free(conn);
  10909. conn = NULL;
  10910. #endif /* NO_SSL */
  10911. } else {
  10912. #ifdef USE_IPV6
  10913. socklen_t len = (sa.sa.sa_family == AF_INET)
  10914. ? sizeof(conn->client.rsa.sin)
  10915. : sizeof(conn->client.rsa.sin6);
  10916. struct sockaddr *psa =
  10917. (sa.sa.sa_family == AF_INET)
  10918. ? (struct sockaddr *)&(conn->client.rsa.sin)
  10919. : (struct sockaddr *)&(conn->client.rsa.sin6);
  10920. #else
  10921. socklen_t len = sizeof(conn->client.rsa.sin);
  10922. struct sockaddr *psa = (struct sockaddr *)&(conn->client.rsa.sin);
  10923. #endif
  10924. conn->buf_size = MAX_REQUEST_SIZE;
  10925. conn->buf = (char *)(conn + 1);
  10926. conn->ctx = &fake_ctx;
  10927. conn->client.sock = sock;
  10928. conn->client.lsa = sa;
  10929. if (getsockname(sock, psa, &len) != 0) {
  10930. mg_cry(conn,
  10931. "%s: getsockname() failed: %s",
  10932. __func__,
  10933. strerror(ERRNO));
  10934. }
  10935. conn->client.is_ssl = use_ssl ? 1 : 0;
  10936. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  10937. #ifndef NO_SSL
  10938. if (use_ssl) {
  10939. fake_ctx.ssl_ctx = conn->client_ssl_ctx;
  10940. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  10941. * SSL_CTX_set_verify call is needed to switch off server
  10942. * certificate checking, which is off by default in OpenSSL and
  10943. * on in yaSSL. */
  10944. /* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  10945. * SSL_VERIFY_PEER, verify_ssl_server); */
  10946. if (client_options->client_cert) {
  10947. if (!ssl_use_pem_file(&fake_ctx, client_options->client_cert)) {
  10948. mg_snprintf(NULL,
  10949. NULL, /* No truncation check for ebuf */
  10950. ebuf,
  10951. ebuf_len,
  10952. "Can not use SSL client certificate");
  10953. SSL_CTX_free(conn->client_ssl_ctx);
  10954. closesocket(sock);
  10955. mg_free(conn);
  10956. conn = NULL;
  10957. }
  10958. }
  10959. if (client_options->server_cert) {
  10960. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  10961. client_options->server_cert,
  10962. NULL);
  10963. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  10964. } else {
  10965. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  10966. }
  10967. if (!sslize(conn,
  10968. conn->client_ssl_ctx,
  10969. SSL_connect,
  10970. &(conn->ctx->stop_flag))) {
  10971. mg_snprintf(NULL,
  10972. NULL, /* No truncation check for ebuf */
  10973. ebuf,
  10974. ebuf_len,
  10975. "SSL connection error");
  10976. SSL_CTX_free(conn->client_ssl_ctx);
  10977. closesocket(sock);
  10978. mg_free(conn);
  10979. conn = NULL;
  10980. }
  10981. }
  10982. #endif
  10983. }
  10984. return conn;
  10985. }
  10986. CIVETWEB_API struct mg_connection *
  10987. mg_connect_client_secure(const struct mg_client_options *client_options,
  10988. char *error_buffer,
  10989. size_t error_buffer_size)
  10990. {
  10991. return mg_connect_client_impl(client_options,
  10992. 1,
  10993. error_buffer,
  10994. error_buffer_size);
  10995. }
  10996. struct mg_connection *
  10997. mg_connect_client(const char *host,
  10998. int port,
  10999. int use_ssl,
  11000. char *error_buffer,
  11001. size_t error_buffer_size)
  11002. {
  11003. struct mg_client_options opts;
  11004. memset(&opts, 0, sizeof(opts));
  11005. opts.host = host;
  11006. opts.port = port;
  11007. return mg_connect_client_impl(&opts,
  11008. use_ssl,
  11009. error_buffer,
  11010. error_buffer_size);
  11011. }
  11012. static const struct {
  11013. const char *proto;
  11014. size_t proto_len;
  11015. unsigned default_port;
  11016. } abs_uri_protocols[] = {{"http://", 7, 80},
  11017. {"https://", 8, 443},
  11018. {"ws://", 5, 80},
  11019. {"wss://", 6, 443},
  11020. {NULL, 0, 0}};
  11021. /* Check if the uri is valid.
  11022. * return 0 for invalid uri,
  11023. * return 1 for *,
  11024. * return 2 for relative uri,
  11025. * return 3 for absolute uri without port,
  11026. * return 4 for absolute uri with port */
  11027. static int
  11028. get_uri_type(const char *uri)
  11029. {
  11030. int i;
  11031. char *hostend, *portbegin, *portend;
  11032. unsigned long port;
  11033. /* According to the HTTP standard
  11034. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  11035. * URI can be an asterisk (*) or should start with slash (relative uri),
  11036. * or it should start with the protocol (absolute uri). */
  11037. if (uri[0] == '*' && uri[1] == '\0') {
  11038. /* asterisk */
  11039. return 1;
  11040. }
  11041. /* Valid URIs according to RFC 3986
  11042. * (https://www.ietf.org/rfc/rfc3986.txt)
  11043. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  11044. * and unreserved characters A-Z a-z 0-9 and -._~
  11045. * and % encoded symbols.
  11046. */
  11047. for (i = 0; uri[i] != 0; i++) {
  11048. if (uri[i] < 33) {
  11049. /* control characters and spaces are invalid */
  11050. return 0;
  11051. }
  11052. if (uri[i] > 126) {
  11053. /* non-ascii characters must be % encoded */
  11054. return 0;
  11055. } else {
  11056. switch (uri[i]) {
  11057. case '"': /* 34 */
  11058. case '<': /* 60 */
  11059. case '>': /* 62 */
  11060. case '\\': /* 92 */
  11061. case '^': /* 94 */
  11062. case '`': /* 96 */
  11063. case '{': /* 123 */
  11064. case '|': /* 124 */
  11065. case '}': /* 125 */
  11066. return 0;
  11067. default:
  11068. /* character is ok */
  11069. break;
  11070. }
  11071. }
  11072. }
  11073. /* A relative uri starts with a / character */
  11074. if (uri[0] == '/') {
  11075. /* relative uri */
  11076. return 2;
  11077. }
  11078. /* It could be an absolute uri: */
  11079. /* This function only checks if the uri is valid, not if it is
  11080. * addressing the current server. So civetweb can also be used
  11081. * as a proxy server. */
  11082. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  11083. if (mg_strncasecmp(uri,
  11084. abs_uri_protocols[i].proto,
  11085. abs_uri_protocols[i].proto_len) == 0) {
  11086. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  11087. if (!hostend) {
  11088. return 0;
  11089. }
  11090. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  11091. if (!portbegin) {
  11092. return 3;
  11093. }
  11094. port = strtoul(portbegin + 1, &portend, 10);
  11095. if ((portend != hostend) || !port || !is_valid_port(port)) {
  11096. return 0;
  11097. }
  11098. return 4;
  11099. }
  11100. }
  11101. return 0;
  11102. }
  11103. /* Return NULL or the relative uri at the current server */
  11104. static const char *
  11105. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  11106. {
  11107. const char *server_domain;
  11108. size_t server_domain_len;
  11109. size_t request_domain_len = 0;
  11110. unsigned long port = 0;
  11111. int i;
  11112. const char *hostbegin = NULL;
  11113. const char *hostend = NULL;
  11114. const char *portbegin;
  11115. char *portend;
  11116. /* DNS is case insensitive, so use case insensitive string compare here
  11117. */
  11118. server_domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  11119. if (!server_domain) {
  11120. return 0;
  11121. }
  11122. server_domain_len = strlen(server_domain);
  11123. if (!server_domain_len) {
  11124. return 0;
  11125. }
  11126. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  11127. if (mg_strncasecmp(uri,
  11128. abs_uri_protocols[i].proto,
  11129. abs_uri_protocols[i].proto_len) == 0) {
  11130. hostbegin = uri + abs_uri_protocols[i].proto_len;
  11131. hostend = strchr(hostbegin, '/');
  11132. if (!hostend) {
  11133. return 0;
  11134. }
  11135. portbegin = strchr(hostbegin, ':');
  11136. if ((!portbegin) || (portbegin > hostend)) {
  11137. port = abs_uri_protocols[i].default_port;
  11138. request_domain_len = (size_t)(hostend - hostbegin);
  11139. } else {
  11140. port = strtoul(portbegin + 1, &portend, 10);
  11141. if ((portend != hostend) || !port || !is_valid_port(port)) {
  11142. return 0;
  11143. }
  11144. request_domain_len = (size_t)(portbegin - hostbegin);
  11145. }
  11146. /* protocol found, port set */
  11147. break;
  11148. }
  11149. }
  11150. if (!port) {
  11151. /* port remains 0 if the protocol is not found */
  11152. return 0;
  11153. }
  11154. /* Check if the request is directed to a different server. */
  11155. /* First check if the port is the same (IPv4 and IPv6). */
  11156. #if defined(USE_IPV6)
  11157. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  11158. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  11159. /* Request is directed to a different port */
  11160. return 0;
  11161. }
  11162. } else
  11163. #endif
  11164. {
  11165. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  11166. /* Request is directed to a different port */
  11167. return 0;
  11168. }
  11169. }
  11170. /* Finally check if the server corresponds to the authentication
  11171. * domain of the server (the server domain).
  11172. * Allow full matches (like http://mydomain.com/path/file.ext), and
  11173. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  11174. * but do not allow substrings (like http://notmydomain.com/path/file.ext
  11175. * or http://mydomain.com.fake/path/file.ext).
  11176. */
  11177. if ((request_domain_len == server_domain_len)
  11178. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  11179. /* Request is directed to this server - full name match. */
  11180. } else {
  11181. if (request_domain_len < (server_domain_len + 2)) {
  11182. /* Request is directed to another server: The server name is longer
  11183. * than
  11184. * the request name. Drop this case here to avoid overflows in the
  11185. * following checks. */
  11186. return 0;
  11187. }
  11188. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  11189. /* Request is directed to another server: It could be a substring
  11190. * like notmyserver.com */
  11191. return 0;
  11192. }
  11193. if (0 != memcmp(server_domain,
  11194. hostbegin + request_domain_len - server_domain_len,
  11195. server_domain_len)) {
  11196. /* Request is directed to another server:
  11197. * The server name is different. */
  11198. return 0;
  11199. }
  11200. }
  11201. return hostend;
  11202. }
  11203. static int
  11204. getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  11205. {
  11206. const char *cl;
  11207. if (ebuf_len > 0) {
  11208. ebuf[0] = '\0';
  11209. }
  11210. *err = 0;
  11211. reset_per_request_attributes(conn);
  11212. if (!conn) {
  11213. mg_snprintf(conn,
  11214. NULL, /* No truncation check for ebuf */
  11215. ebuf,
  11216. ebuf_len,
  11217. "%s",
  11218. "Internal error");
  11219. *err = 500;
  11220. return 0;
  11221. }
  11222. /* Set the time the request was received. This value should be used for
  11223. * timeouts. */
  11224. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  11225. conn->request_len =
  11226. read_request(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  11227. /* assert(conn->request_len < 0 || conn->data_len >= conn->request_len);
  11228. */
  11229. if (conn->request_len >= 0 && conn->data_len < conn->request_len) {
  11230. mg_snprintf(conn,
  11231. NULL, /* No truncation check for ebuf */
  11232. ebuf,
  11233. ebuf_len,
  11234. "%s",
  11235. "Invalid request size");
  11236. *err = 500;
  11237. return 0;
  11238. }
  11239. if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
  11240. mg_snprintf(conn,
  11241. NULL, /* No truncation check for ebuf */
  11242. ebuf,
  11243. ebuf_len,
  11244. "%s",
  11245. "Request Too Large");
  11246. *err = 413;
  11247. return 0;
  11248. } else if (conn->request_len <= 0) {
  11249. if (conn->data_len > 0) {
  11250. mg_snprintf(conn,
  11251. NULL, /* No truncation check for ebuf */
  11252. ebuf,
  11253. ebuf_len,
  11254. "%s",
  11255. "Client sent malformed request");
  11256. *err = 400;
  11257. } else {
  11258. /* Server did not recv anything -> just close the connection */
  11259. conn->must_close = 1;
  11260. mg_snprintf(conn,
  11261. NULL, /* No truncation check for ebuf */
  11262. ebuf,
  11263. ebuf_len,
  11264. "%s",
  11265. "Client did not send a request");
  11266. *err = 0;
  11267. }
  11268. return 0;
  11269. } else if (parse_http_message(conn->buf,
  11270. conn->buf_size,
  11271. &conn->request_info) <= 0) {
  11272. mg_snprintf(conn,
  11273. NULL, /* No truncation check for ebuf */
  11274. ebuf,
  11275. ebuf_len,
  11276. "%s",
  11277. "Bad Request");
  11278. *err = 400;
  11279. return 0;
  11280. } else {
  11281. /* Message is a valid request or response */
  11282. if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) {
  11283. /* Request/response has content length set */
  11284. char *endptr = NULL;
  11285. conn->content_len = strtoll(cl, &endptr, 10);
  11286. if (endptr == cl) {
  11287. mg_snprintf(conn,
  11288. NULL, /* No truncation check for ebuf */
  11289. ebuf,
  11290. ebuf_len,
  11291. "%s",
  11292. "Bad Request");
  11293. *err = 411;
  11294. return 0;
  11295. }
  11296. /* Publish the content length back to the request info. */
  11297. conn->request_info.content_length = conn->content_len;
  11298. } else if ((cl = get_header(&conn->request_info, "Transfer-Encoding"))
  11299. != NULL
  11300. && !mg_strcasecmp(cl, "chunked")) {
  11301. conn->is_chunked = 1;
  11302. } else if (!mg_strcasecmp(conn->request_info.request_method, "POST")
  11303. || !mg_strcasecmp(conn->request_info.request_method,
  11304. "PUT")) {
  11305. /* POST or PUT request without content length set */
  11306. conn->content_len = -1;
  11307. } else if (!mg_strncasecmp(conn->request_info.request_method,
  11308. "HTTP/",
  11309. 5)) {
  11310. /* Response without content length set */
  11311. conn->content_len = -1;
  11312. } else {
  11313. /* Other request */
  11314. conn->content_len = 0;
  11315. }
  11316. }
  11317. return 1;
  11318. }
  11319. int
  11320. mg_get_response(struct mg_connection *conn,
  11321. char *ebuf,
  11322. size_t ebuf_len,
  11323. int timeout)
  11324. {
  11325. if (conn) {
  11326. /* Implementation of API function for HTTP clients */
  11327. int err, ret;
  11328. struct mg_context *octx = conn->ctx;
  11329. struct mg_context rctx = *(conn->ctx);
  11330. char txt[32]; /* will not overflow */
  11331. if (timeout >= 0) {
  11332. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  11333. rctx.config[REQUEST_TIMEOUT] = txt;
  11334. set_sock_timeout(conn->client.sock, timeout);
  11335. } else {
  11336. rctx.config[REQUEST_TIMEOUT] = NULL;
  11337. }
  11338. conn->ctx = &rctx;
  11339. ret = getreq(conn, ebuf, ebuf_len, &err);
  11340. conn->ctx = octx;
  11341. /* TODO: 1) uri is deprecated;
  11342. * 2) here, ri.uri is the http response code */
  11343. conn->request_info.uri = conn->request_info.request_uri;
  11344. /* TODO (mid): Define proper return values - maybe return length?
  11345. * For the first test use <0 for error and >0 for OK */
  11346. return (ret == 0) ? -1 : +1;
  11347. }
  11348. return -1;
  11349. }
  11350. struct mg_connection *
  11351. mg_download(const char *host,
  11352. int port,
  11353. int use_ssl,
  11354. char *ebuf,
  11355. size_t ebuf_len,
  11356. const char *fmt,
  11357. ...)
  11358. {
  11359. struct mg_connection *conn;
  11360. va_list ap;
  11361. int i;
  11362. int reqerr;
  11363. va_start(ap, fmt);
  11364. ebuf[0] = '\0';
  11365. /* open a connection */
  11366. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  11367. if (conn != NULL) {
  11368. i = mg_vprintf(conn, fmt, ap);
  11369. if (i <= 0) {
  11370. mg_snprintf(conn,
  11371. NULL, /* No truncation check for ebuf */
  11372. ebuf,
  11373. ebuf_len,
  11374. "%s",
  11375. "Error sending request");
  11376. } else {
  11377. getreq(conn, ebuf, ebuf_len, &reqerr);
  11378. /* TODO: 1) uri is deprecated;
  11379. * 2) here, ri.uri is the http response code */
  11380. conn->request_info.uri = conn->request_info.request_uri;
  11381. }
  11382. }
  11383. /* if an error occured, close the connection */
  11384. if (ebuf[0] != '\0' && conn != NULL) {
  11385. mg_close_connection(conn);
  11386. conn = NULL;
  11387. }
  11388. va_end(ap);
  11389. return conn;
  11390. }
  11391. struct websocket_client_thread_data {
  11392. struct mg_connection *conn;
  11393. mg_websocket_data_handler data_handler;
  11394. mg_websocket_close_handler close_handler;
  11395. void *callback_data;
  11396. };
  11397. #if defined(USE_WEBSOCKET)
  11398. #ifdef _WIN32
  11399. static unsigned __stdcall websocket_client_thread(void *data)
  11400. #else
  11401. static void *
  11402. websocket_client_thread(void *data)
  11403. #endif
  11404. {
  11405. struct websocket_client_thread_data *cdata =
  11406. (struct websocket_client_thread_data *)data;
  11407. mg_set_thread_name("ws-clnt");
  11408. if (cdata->conn->ctx) {
  11409. if (cdata->conn->ctx->callbacks.init_thread) {
  11410. /* 3 indicates a websocket client thread */
  11411. /* TODO: check if conn->ctx can be set */
  11412. cdata->conn->ctx->callbacks.init_thread(cdata->conn->ctx, 3);
  11413. }
  11414. }
  11415. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  11416. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  11417. if (cdata->close_handler != NULL) {
  11418. cdata->close_handler(cdata->conn, cdata->callback_data);
  11419. }
  11420. /* The websocket_client context has only this thread. If it runs out,
  11421. set the stop_flag to 2 (= "stopped"). */
  11422. cdata->conn->ctx->stop_flag = 2;
  11423. mg_free((void *)cdata);
  11424. #ifdef _WIN32
  11425. return 0;
  11426. #else
  11427. return NULL;
  11428. #endif
  11429. }
  11430. #endif
  11431. struct mg_connection *
  11432. mg_connect_websocket_client(const char *host,
  11433. int port,
  11434. int use_ssl,
  11435. char *error_buffer,
  11436. size_t error_buffer_size,
  11437. const char *path,
  11438. const char *origin,
  11439. mg_websocket_data_handler data_func,
  11440. mg_websocket_close_handler close_func,
  11441. void *user_data)
  11442. {
  11443. struct mg_connection *conn = NULL;
  11444. #if defined(USE_WEBSOCKET)
  11445. struct mg_context *newctx = NULL;
  11446. struct websocket_client_thread_data *thread_data;
  11447. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  11448. static const char *handshake_req;
  11449. if (origin != NULL) {
  11450. handshake_req = "GET %s HTTP/1.1\r\n"
  11451. "Host: %s\r\n"
  11452. "Upgrade: websocket\r\n"
  11453. "Connection: Upgrade\r\n"
  11454. "Sec-WebSocket-Key: %s\r\n"
  11455. "Sec-WebSocket-Version: 13\r\n"
  11456. "Origin: %s\r\n"
  11457. "\r\n";
  11458. } else {
  11459. handshake_req = "GET %s HTTP/1.1\r\n"
  11460. "Host: %s\r\n"
  11461. "Upgrade: websocket\r\n"
  11462. "Connection: Upgrade\r\n"
  11463. "Sec-WebSocket-Key: %s\r\n"
  11464. "Sec-WebSocket-Version: 13\r\n"
  11465. "\r\n";
  11466. }
  11467. /* Establish the client connection and request upgrade */
  11468. conn = mg_download(host,
  11469. port,
  11470. use_ssl,
  11471. error_buffer,
  11472. error_buffer_size,
  11473. handshake_req,
  11474. path,
  11475. host,
  11476. magic,
  11477. origin);
  11478. /* Connection object will be null if something goes wrong */
  11479. if (conn == NULL || (strcmp(conn->request_info.request_uri, "101") != 0)) {
  11480. if (!*error_buffer) {
  11481. /* if there is a connection, but it did not return 101,
  11482. * error_buffer is not yet set */
  11483. mg_snprintf(conn,
  11484. NULL, /* No truncation check for ebuf */
  11485. error_buffer,
  11486. error_buffer_size,
  11487. "Unexpected server reply");
  11488. }
  11489. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  11490. if (conn != NULL) {
  11491. mg_free(conn);
  11492. conn = NULL;
  11493. }
  11494. return conn;
  11495. }
  11496. /* For client connections, mg_context is fake. Since we need to set a
  11497. * callback function, we need to create a copy and modify it. */
  11498. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  11499. memcpy(newctx, conn->ctx, sizeof(struct mg_context));
  11500. newctx->user_data = user_data;
  11501. newctx->context_type = 2; /* ws/wss client context type */
  11502. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  11503. newctx->workerthreadids =
  11504. (pthread_t *)mg_calloc(newctx->cfg_worker_threads, sizeof(pthread_t));
  11505. conn->ctx = newctx;
  11506. thread_data = (struct websocket_client_thread_data *)
  11507. mg_calloc(sizeof(struct websocket_client_thread_data), 1);
  11508. thread_data->conn = conn;
  11509. thread_data->data_handler = data_func;
  11510. thread_data->close_handler = close_func;
  11511. thread_data->callback_data = NULL;
  11512. /* Start a thread to read the websocket client connection
  11513. * This thread will automatically stop when mg_disconnect is
  11514. * called on the client connection */
  11515. if (mg_start_thread_with_id(websocket_client_thread,
  11516. (void *)thread_data,
  11517. newctx->workerthreadids) != 0) {
  11518. mg_free((void *)thread_data);
  11519. mg_free((void *)newctx->workerthreadids);
  11520. mg_free((void *)newctx);
  11521. mg_free((void *)conn);
  11522. conn = NULL;
  11523. DEBUG_TRACE("%s",
  11524. "Websocket client connect thread could not be started\r\n");
  11525. }
  11526. #else
  11527. /* Appease "unused parameter" warnings */
  11528. (void)host;
  11529. (void)port;
  11530. (void)use_ssl;
  11531. (void)error_buffer;
  11532. (void)error_buffer_size;
  11533. (void)path;
  11534. (void)origin;
  11535. (void)user_data;
  11536. (void)data_func;
  11537. (void)close_func;
  11538. #endif
  11539. return conn;
  11540. }
  11541. static void
  11542. process_new_connection(struct mg_connection *conn)
  11543. {
  11544. if (conn && conn->ctx) {
  11545. struct mg_request_info *ri = &conn->request_info;
  11546. int keep_alive_enabled, keep_alive, discard_len;
  11547. char ebuf[100];
  11548. const char *hostend;
  11549. int reqerr, uri_type;
  11550. keep_alive_enabled =
  11551. !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  11552. /* Important: on new connection, reset the receiving buffer. Credit
  11553. * goes to crule42. */
  11554. conn->data_len = 0;
  11555. conn->handled_requests = 0;
  11556. do {
  11557. DEBUG_TRACE("calling getreq (%i times for this connection)",
  11558. conn->handled_requests + 1);
  11559. if (!getreq(conn, ebuf, sizeof(ebuf), &reqerr)) {
  11560. /* The request sent by the client could not be understood by
  11561. * the server, or it was incomplete or a timeout. Send an
  11562. * error message and close the connection. */
  11563. if (reqerr > 0) {
  11564. /*assert(ebuf[0] != '\0');*/
  11565. send_http_error(conn, reqerr, "%s", ebuf);
  11566. }
  11567. } else if (strcmp(ri->http_version, "1.0")
  11568. && strcmp(ri->http_version, "1.1")) {
  11569. mg_snprintf(conn,
  11570. NULL, /* No truncation check for ebuf */
  11571. ebuf,
  11572. sizeof(ebuf),
  11573. "Bad HTTP version: [%s]",
  11574. ri->http_version);
  11575. send_http_error(conn, 505, "%s", ebuf);
  11576. }
  11577. if (ebuf[0] == '\0') {
  11578. uri_type = get_uri_type(conn->request_info.request_uri);
  11579. switch (uri_type) {
  11580. case 1:
  11581. /* Asterisk */
  11582. conn->request_info.local_uri = NULL;
  11583. break;
  11584. case 2:
  11585. /* relative uri */
  11586. conn->request_info.local_uri =
  11587. conn->request_info.request_uri;
  11588. break;
  11589. case 3:
  11590. case 4:
  11591. /* absolute uri (with/without port) */
  11592. hostend = get_rel_url_at_current_server(
  11593. conn->request_info.request_uri, conn);
  11594. if (hostend) {
  11595. conn->request_info.local_uri = hostend;
  11596. } else {
  11597. conn->request_info.local_uri = NULL;
  11598. }
  11599. break;
  11600. default:
  11601. mg_snprintf(conn,
  11602. NULL, /* No truncation check for ebuf */
  11603. ebuf,
  11604. sizeof(ebuf),
  11605. "Invalid URI");
  11606. send_http_error(conn, 400, "%s", ebuf);
  11607. conn->request_info.local_uri = NULL;
  11608. break;
  11609. }
  11610. /* TODO: cleanup uri, local_uri and request_uri */
  11611. conn->request_info.uri = conn->request_info.local_uri;
  11612. }
  11613. DEBUG_TRACE("http: %s, error: %s",
  11614. (ri->http_version ? ri->http_version : "none"),
  11615. (ebuf[0] ? ebuf : "none"));
  11616. if (ebuf[0] == '\0') {
  11617. if (conn->request_info.local_uri) {
  11618. /* handle request to local server */
  11619. handle_request(conn);
  11620. DEBUG_TRACE("%s", "handle_request done");
  11621. if (conn->ctx->callbacks.end_request != NULL) {
  11622. conn->ctx->callbacks.end_request(conn,
  11623. conn->status_code);
  11624. DEBUG_TRACE("%s", "end_request callback done");
  11625. }
  11626. log_access(conn);
  11627. } else {
  11628. /* TODO: handle non-local request (PROXY) */
  11629. conn->must_close = 1;
  11630. }
  11631. } else {
  11632. conn->must_close = 1;
  11633. }
  11634. if (ri->remote_user != NULL) {
  11635. mg_free((void *)ri->remote_user);
  11636. /* Important! When having connections with and without auth
  11637. * would cause double free and then crash */
  11638. ri->remote_user = NULL;
  11639. }
  11640. /* NOTE(lsm): order is important here. should_keep_alive() call
  11641. * is
  11642. * using parsed request, which will be invalid after memmove's
  11643. * below.
  11644. * Therefore, memorize should_keep_alive() result now for later
  11645. * use
  11646. * in loop exit condition. */
  11647. keep_alive = (conn->ctx->stop_flag == 0) && keep_alive_enabled
  11648. && (conn->content_len >= 0) && should_keep_alive(conn);
  11649. /* Discard all buffered data for this request */
  11650. discard_len = ((conn->content_len >= 0) && (conn->request_len > 0)
  11651. && ((conn->request_len + conn->content_len)
  11652. < (int64_t)conn->data_len))
  11653. ? (int)(conn->request_len + conn->content_len)
  11654. : conn->data_len;
  11655. /*assert(discard_len >= 0);*/
  11656. if (discard_len < 0) {
  11657. DEBUG_TRACE("internal error: discard_len = %li",
  11658. (long int)discard_len);
  11659. break;
  11660. }
  11661. conn->data_len -= discard_len;
  11662. if (conn->data_len > 0) {
  11663. DEBUG_TRACE("discard_len = %lu", (long unsigned)discard_len);
  11664. memmove(conn->buf,
  11665. conn->buf + discard_len,
  11666. (size_t)conn->data_len);
  11667. }
  11668. /* assert(conn->data_len >= 0); */
  11669. /* assert(conn->data_len <= conn->buf_size); */
  11670. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  11671. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  11672. (long int)conn->data_len,
  11673. (long int)conn->buf_size);
  11674. break;
  11675. }
  11676. conn->handled_requests++;
  11677. } while (keep_alive);
  11678. }
  11679. }
  11680. #if defined(ALTERNATIVE_QUEUE)
  11681. static void
  11682. produce_socket(struct mg_context *ctx, const struct socket *sp)
  11683. {
  11684. unsigned int i;
  11685. for (;;) {
  11686. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  11687. /* find a free worker slot and signal it */
  11688. if (ctx->client_socks[i].in_use == 0) {
  11689. ctx->client_socks[i] = *sp;
  11690. ctx->client_socks[i].in_use = 1;
  11691. event_signal(ctx->client_wait_events[i]);
  11692. return;
  11693. }
  11694. }
  11695. /* queue is full */
  11696. mg_sleep(1);
  11697. }
  11698. }
  11699. static int
  11700. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  11701. {
  11702. DEBUG_TRACE("%s", "going idle");
  11703. ctx->client_socks[thread_index].in_use = 0;
  11704. event_wait(ctx->client_wait_events[thread_index]);
  11705. *sp = ctx->client_socks[thread_index];
  11706. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  11707. return !ctx->stop_flag;
  11708. }
  11709. #else /* ALTERNATIVE_QUEUE */
  11710. /* Worker threads take accepted socket from the queue */
  11711. static int
  11712. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  11713. {
  11714. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  11715. (void)thread_index;
  11716. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11717. DEBUG_TRACE("%s", "going idle");
  11718. /* If the queue is empty, wait. We're idle at this point. */
  11719. while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
  11720. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  11721. }
  11722. /* If we're stopping, sq_head may be equal to sq_tail. */
  11723. if (ctx->sq_head > ctx->sq_tail) {
  11724. /* Copy socket from the queue and increment tail */
  11725. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  11726. ctx->sq_tail++;
  11727. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  11728. /* Wrap pointers if needed */
  11729. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  11730. ctx->sq_tail -= QUEUE_SIZE(ctx);
  11731. ctx->sq_head -= QUEUE_SIZE(ctx);
  11732. }
  11733. }
  11734. (void)pthread_cond_signal(&ctx->sq_empty);
  11735. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11736. return !ctx->stop_flag;
  11737. #undef QUEUE_SIZE
  11738. }
  11739. /* Master thread adds accepted socket to a queue */
  11740. static void
  11741. produce_socket(struct mg_context *ctx, const struct socket *sp)
  11742. {
  11743. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  11744. if (!ctx) {
  11745. return;
  11746. }
  11747. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11748. /* If the queue is full, wait */
  11749. while (ctx->stop_flag == 0
  11750. && ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx)) {
  11751. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  11752. }
  11753. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  11754. /* Copy socket to the queue and increment head */
  11755. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  11756. ctx->sq_head++;
  11757. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  11758. }
  11759. (void)pthread_cond_signal(&ctx->sq_full);
  11760. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11761. #undef QUEUE_SIZE
  11762. }
  11763. #endif /* ALTERNATIVE_QUEUE */
  11764. struct worker_thread_args {
  11765. struct mg_context *ctx;
  11766. int index;
  11767. };
  11768. static void *
  11769. worker_thread_run(struct worker_thread_args *thread_args)
  11770. {
  11771. struct mg_context *ctx = thread_args->ctx;
  11772. struct mg_connection *conn;
  11773. struct mg_workerTLS tls;
  11774. #if defined(MG_LEGACY_INTERFACE)
  11775. uint32_t addr;
  11776. #endif
  11777. mg_set_thread_name("worker");
  11778. tls.is_master = 0;
  11779. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  11780. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11781. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  11782. #endif
  11783. if (ctx->callbacks.init_thread) {
  11784. /* call init_thread for a worker thread (type 1) */
  11785. ctx->callbacks.init_thread(ctx, 1);
  11786. }
  11787. conn =
  11788. (struct mg_connection *)mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE);
  11789. if (conn == NULL) {
  11790. mg_cry(fc(ctx), "%s", "Cannot create new connection struct, OOM");
  11791. } else {
  11792. pthread_setspecific(sTlsKey, &tls);
  11793. conn->buf_size = MAX_REQUEST_SIZE;
  11794. conn->buf = (char *)(conn + 1);
  11795. conn->ctx = ctx;
  11796. conn->thread_index = thread_args->index;
  11797. conn->request_info.user_data = ctx->user_data;
  11798. /* Allocate a mutex for this connection to allow communication both
  11799. * within the request handler and from elsewhere in the application
  11800. */
  11801. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  11802. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  11803. * signal sq_empty condvar to wake up the master waiting in
  11804. * produce_socket() */
  11805. while (consume_socket(ctx, &conn->client, conn->thread_index)) {
  11806. conn->conn_birth_time = time(NULL);
  11807. /* Fill in IP, port info early so even if SSL setup below fails,
  11808. * error handler would have the corresponding info.
  11809. * Thanks to Johannes Winkelmann for the patch.
  11810. */
  11811. #if defined(USE_IPV6)
  11812. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  11813. conn->request_info.remote_port =
  11814. ntohs(conn->client.rsa.sin6.sin6_port);
  11815. } else
  11816. #endif
  11817. {
  11818. conn->request_info.remote_port =
  11819. ntohs(conn->client.rsa.sin.sin_port);
  11820. }
  11821. sockaddr_to_string(conn->request_info.remote_addr,
  11822. sizeof(conn->request_info.remote_addr),
  11823. &conn->client.rsa);
  11824. DEBUG_TRACE("Start processing connection from %s",
  11825. conn->request_info.remote_addr);
  11826. #if defined(MG_LEGACY_INTERFACE)
  11827. /* This legacy interface only works for the IPv4 case */
  11828. addr = ntohl(conn->client.rsa.sin.sin_addr.s_addr);
  11829. memcpy(&conn->request_info.remote_ip, &addr, 4);
  11830. #endif
  11831. conn->request_info.is_ssl = conn->client.is_ssl;
  11832. if (conn->client.is_ssl) {
  11833. #ifndef NO_SSL
  11834. /* HTTPS connection */
  11835. if (sslize(conn,
  11836. conn->ctx->ssl_ctx,
  11837. SSL_accept,
  11838. &(conn->ctx->stop_flag))) {
  11839. /* Get SSL client certificate information (if set) */
  11840. ssl_get_client_cert_info(conn);
  11841. /* process HTTPS connection */
  11842. process_new_connection(conn);
  11843. /* Free client certificate info */
  11844. if (conn->request_info.client_cert) {
  11845. mg_free(
  11846. (void *)(conn->request_info.client_cert->subject));
  11847. mg_free(
  11848. (void *)(conn->request_info.client_cert->issuer));
  11849. mg_free(
  11850. (void *)(conn->request_info.client_cert->serial));
  11851. mg_free(
  11852. (void *)(conn->request_info.client_cert->finger));
  11853. conn->request_info.client_cert->subject = 0;
  11854. conn->request_info.client_cert->issuer = 0;
  11855. conn->request_info.client_cert->serial = 0;
  11856. conn->request_info.client_cert->finger = 0;
  11857. mg_free(conn->request_info.client_cert);
  11858. conn->request_info.client_cert = 0;
  11859. }
  11860. }
  11861. #endif
  11862. } else {
  11863. /* process HTTP connection */
  11864. process_new_connection(conn);
  11865. }
  11866. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  11867. conn->request_info.remote_addr,
  11868. difftime(time(NULL), conn->conn_birth_time));
  11869. close_connection(conn);
  11870. DEBUG_TRACE("%s", "Connection closed");
  11871. }
  11872. }
  11873. pthread_setspecific(sTlsKey, NULL);
  11874. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11875. CloseHandle(tls.pthread_cond_helper_mutex);
  11876. #endif
  11877. pthread_mutex_destroy(&conn->mutex);
  11878. mg_free(conn);
  11879. DEBUG_TRACE("%s", "exiting");
  11880. return NULL;
  11881. }
  11882. /* Threads have different return types on Windows and Unix. */
  11883. #ifdef _WIN32
  11884. static unsigned __stdcall worker_thread(void *thread_func_param)
  11885. {
  11886. struct worker_thread_args *pwta =
  11887. (struct worker_thread_args *)thread_func_param;
  11888. worker_thread_run(pwta);
  11889. mg_free(thread_func_param);
  11890. return 0;
  11891. }
  11892. #else
  11893. static void *
  11894. worker_thread(void *thread_func_param)
  11895. {
  11896. struct worker_thread_args *pwta =
  11897. (struct worker_thread_args *)thread_func_param;
  11898. worker_thread_run(pwta);
  11899. mg_free(thread_func_param);
  11900. return NULL;
  11901. }
  11902. #endif /* _WIN32 */
  11903. static void
  11904. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  11905. {
  11906. struct socket so;
  11907. char src_addr[IP_ADDR_STR_LEN];
  11908. socklen_t len = sizeof(so.rsa);
  11909. int on = 1;
  11910. int timeout;
  11911. if (!listener) {
  11912. return;
  11913. }
  11914. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  11915. == INVALID_SOCKET) {
  11916. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  11917. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  11918. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  11919. closesocket(so.sock);
  11920. so.sock = INVALID_SOCKET;
  11921. } else {
  11922. /* Put so socket structure into the queue */
  11923. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  11924. set_close_on_exec(so.sock, fc(ctx));
  11925. so.is_ssl = listener->is_ssl;
  11926. so.ssl_redir = listener->ssl_redir;
  11927. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  11928. mg_cry(fc(ctx),
  11929. "%s: getsockname() failed: %s",
  11930. __func__,
  11931. strerror(ERRNO));
  11932. }
  11933. /* Set TCP keep-alive. This is needed because if HTTP-level
  11934. * keep-alive
  11935. * is enabled, and client resets the connection, server won't get
  11936. * TCP FIN or RST and will keep the connection open forever. With
  11937. * TCP keep-alive, next keep-alive handshake will figure out that
  11938. * the client is down and will close the server end.
  11939. * Thanks to Igor Klopov who suggested the patch. */
  11940. if (setsockopt(so.sock,
  11941. SOL_SOCKET,
  11942. SO_KEEPALIVE,
  11943. (SOCK_OPT_TYPE)&on,
  11944. sizeof(on)) != 0) {
  11945. mg_cry(fc(ctx),
  11946. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  11947. __func__,
  11948. strerror(ERRNO));
  11949. }
  11950. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  11951. * to effectively fill up the underlying IP packet payload and
  11952. * reduce the overhead of sending lots of small buffers. However
  11953. * this hurts the server's throughput (ie. operations per second)
  11954. * when HTTP 1.1 persistent connections are used and the responses
  11955. * are relatively small (eg. less than 1400 bytes).
  11956. */
  11957. if ((ctx != NULL) && (ctx->config[CONFIG_TCP_NODELAY] != NULL)
  11958. && (!strcmp(ctx->config[CONFIG_TCP_NODELAY], "1"))) {
  11959. if (set_tcp_nodelay(so.sock, 1) != 0) {
  11960. mg_cry(fc(ctx),
  11961. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  11962. __func__,
  11963. strerror(ERRNO));
  11964. }
  11965. }
  11966. if (ctx && ctx->config[REQUEST_TIMEOUT]) {
  11967. timeout = atoi(ctx->config[REQUEST_TIMEOUT]);
  11968. } else {
  11969. timeout = -1;
  11970. }
  11971. /* TODO: if non blocking sockets are used, timeouts are implemented
  11972. * differently */
  11973. // if (timeout > 0) {
  11974. // set_sock_timeout(so.sock, timeout);
  11975. //}
  11976. (void)timeout;
  11977. set_blocking_mode(so.sock, 0);
  11978. produce_socket(ctx, &so);
  11979. }
  11980. }
  11981. static void
  11982. master_thread_run(void *thread_func_param)
  11983. {
  11984. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  11985. struct mg_workerTLS tls;
  11986. struct pollfd *pfd;
  11987. unsigned int i;
  11988. unsigned int workerthreadcount;
  11989. if (!ctx) {
  11990. return;
  11991. }
  11992. mg_set_thread_name("master");
  11993. /* Increase priority of the master thread */
  11994. #if defined(_WIN32)
  11995. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  11996. #elif defined(USE_MASTER_THREAD_PRIORITY)
  11997. int min_prio = sched_get_priority_min(SCHED_RR);
  11998. int max_prio = sched_get_priority_max(SCHED_RR);
  11999. if ((min_prio >= 0) && (max_prio >= 0)
  12000. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  12001. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  12002. struct sched_param sched_param = {0};
  12003. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  12004. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  12005. }
  12006. #endif
  12007. /* Initialize thread local storage */
  12008. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12009. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  12010. #endif
  12011. tls.is_master = 1;
  12012. pthread_setspecific(sTlsKey, &tls);
  12013. if (ctx->callbacks.init_thread) {
  12014. /* Callback for the master thread (type 0) */
  12015. ctx->callbacks.init_thread(ctx, 0);
  12016. }
  12017. /* Server starts *now* */
  12018. ctx->start_time = time(NULL);
  12019. /* Start the server */
  12020. pfd = ctx->listening_socket_fds;
  12021. while (ctx->stop_flag == 0) {
  12022. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12023. pfd[i].fd = ctx->listening_sockets[i].sock;
  12024. pfd[i].events = POLLIN;
  12025. }
  12026. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  12027. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12028. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  12029. * successful poll, and POLLIN is defined as
  12030. * (POLLRDNORM | POLLRDBAND)
  12031. * Therefore, we're checking pfd[i].revents & POLLIN, not
  12032. * pfd[i].revents == POLLIN. */
  12033. if (ctx->stop_flag == 0 && (pfd[i].revents & POLLIN)) {
  12034. accept_new_connection(&ctx->listening_sockets[i], ctx);
  12035. }
  12036. }
  12037. }
  12038. }
  12039. /* Here stop_flag is 1 - Initiate shutdown. */
  12040. DEBUG_TRACE("%s", "stopping workers");
  12041. /* Stop signal received: somebody called mg_stop. Quit. */
  12042. close_all_listening_sockets(ctx);
  12043. /* Wakeup workers that are waiting for connections to handle. */
  12044. (void)pthread_mutex_lock(&ctx->thread_mutex);
  12045. #if defined(ALTERNATIVE_QUEUE)
  12046. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  12047. event_signal(ctx->client_wait_events[i]);
  12048. /* Since we know all sockets, we can shutdown the connections. */
  12049. if (ctx->client_socks[i].in_use) {
  12050. shutdown(ctx->client_socks[i].sock, SHUTDOWN_BOTH);
  12051. }
  12052. }
  12053. #else
  12054. pthread_cond_broadcast(&ctx->sq_full);
  12055. #endif
  12056. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  12057. /* Join all worker threads to avoid leaking threads. */
  12058. workerthreadcount = ctx->cfg_worker_threads;
  12059. for (i = 0; i < workerthreadcount; i++) {
  12060. if (ctx->workerthreadids[i] != 0) {
  12061. mg_join_thread(ctx->workerthreadids[i]);
  12062. }
  12063. }
  12064. #if !defined(NO_SSL)
  12065. if (ctx->ssl_ctx != NULL) {
  12066. uninitialize_ssl(ctx);
  12067. }
  12068. #endif
  12069. DEBUG_TRACE("%s", "exiting");
  12070. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12071. CloseHandle(tls.pthread_cond_helper_mutex);
  12072. #endif
  12073. pthread_setspecific(sTlsKey, NULL);
  12074. /* Signal mg_stop() that we're done.
  12075. * WARNING: This must be the very last thing this
  12076. * thread does, as ctx becomes invalid after this line. */
  12077. ctx->stop_flag = 2;
  12078. }
  12079. /* Threads have different return types on Windows and Unix. */
  12080. #ifdef _WIN32
  12081. static unsigned __stdcall master_thread(void *thread_func_param)
  12082. {
  12083. master_thread_run(thread_func_param);
  12084. return 0;
  12085. }
  12086. #else
  12087. static void *
  12088. master_thread(void *thread_func_param)
  12089. {
  12090. master_thread_run(thread_func_param);
  12091. return NULL;
  12092. }
  12093. #endif /* _WIN32 */
  12094. static void
  12095. free_context(struct mg_context *ctx)
  12096. {
  12097. int i;
  12098. struct mg_handler_info *tmp_rh;
  12099. if (ctx == NULL) {
  12100. return;
  12101. }
  12102. if (ctx->callbacks.exit_context) {
  12103. ctx->callbacks.exit_context(ctx);
  12104. }
  12105. /* All threads exited, no sync is needed. Destroy thread mutex and
  12106. * condvars
  12107. */
  12108. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  12109. #if defined(ALTERNATIVE_QUEUE)
  12110. mg_free(ctx->client_socks);
  12111. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  12112. event_destroy(ctx->client_wait_events[i]);
  12113. }
  12114. mg_free(ctx->client_wait_events);
  12115. #else
  12116. (void)pthread_cond_destroy(&ctx->sq_empty);
  12117. (void)pthread_cond_destroy(&ctx->sq_full);
  12118. #endif
  12119. /* Destroy other context global data structures mutex */
  12120. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  12121. #if defined(USE_TIMERS)
  12122. timers_exit(ctx);
  12123. #endif
  12124. /* Deallocate config parameters */
  12125. for (i = 0; i < NUM_OPTIONS; i++) {
  12126. if (ctx->config[i] != NULL) {
  12127. #if defined(_MSC_VER)
  12128. #pragma warning(suppress : 6001)
  12129. #endif
  12130. mg_free(ctx->config[i]);
  12131. }
  12132. }
  12133. /* Deallocate request handlers */
  12134. while (ctx->handlers) {
  12135. tmp_rh = ctx->handlers;
  12136. ctx->handlers = tmp_rh->next;
  12137. mg_free(tmp_rh->uri);
  12138. mg_free(tmp_rh);
  12139. }
  12140. #ifndef NO_SSL
  12141. /* Deallocate SSL context */
  12142. if (ctx->ssl_ctx != NULL) {
  12143. SSL_CTX_free(ctx->ssl_ctx);
  12144. }
  12145. #endif /* !NO_SSL */
  12146. /* Deallocate worker thread ID array */
  12147. if (ctx->workerthreadids != NULL) {
  12148. mg_free(ctx->workerthreadids);
  12149. }
  12150. /* Deallocate the tls variable */
  12151. if (mg_atomic_dec(&sTlsInit) == 0) {
  12152. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12153. DeleteCriticalSection(&global_log_file_lock);
  12154. #endif /* _WIN32 && !__SYMBIAN32__ */
  12155. #if !defined(_WIN32)
  12156. pthread_mutexattr_destroy(&pthread_mutex_attr);
  12157. #endif
  12158. pthread_key_delete(sTlsKey);
  12159. #if defined(USE_LUA)
  12160. lua_exit_optional_libraries();
  12161. #endif
  12162. }
  12163. /* deallocate system name string */
  12164. mg_free(ctx->systemName);
  12165. /* Deallocate context itself */
  12166. mg_free(ctx);
  12167. }
  12168. void
  12169. mg_stop(struct mg_context *ctx)
  12170. {
  12171. pthread_t mt;
  12172. if (!ctx) {
  12173. return;
  12174. }
  12175. /* We don't use a lock here. Calling mg_stop with the same ctx from
  12176. * two threads is not allowed. */
  12177. mt = ctx->masterthreadid;
  12178. if (mt == 0) {
  12179. return;
  12180. }
  12181. ctx->masterthreadid = 0;
  12182. /* Set stop flag, so all threads know they have to exit. */
  12183. ctx->stop_flag = 1;
  12184. /* Wait until everything has stopped. */
  12185. while (ctx->stop_flag != 2) {
  12186. (void)mg_sleep(10);
  12187. }
  12188. mg_join_thread(mt);
  12189. free_context(ctx);
  12190. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12191. (void)WSACleanup();
  12192. #endif /* _WIN32 && !__SYMBIAN32__ */
  12193. }
  12194. static void
  12195. get_system_name(char **sysName)
  12196. {
  12197. #if defined(_WIN32)
  12198. #if !defined(__SYMBIAN32__)
  12199. #if defined(_WIN32_WCE)
  12200. *sysName = mg_strdup("WinCE");
  12201. #else
  12202. char name[128];
  12203. DWORD dwVersion = 0;
  12204. DWORD dwMajorVersion = 0;
  12205. DWORD dwMinorVersion = 0;
  12206. DWORD dwBuild = 0;
  12207. #ifdef _MSC_VER
  12208. #pragma warning(push)
  12209. /* GetVersion was declared deprecated */
  12210. #pragma warning(disable : 4996)
  12211. #endif
  12212. dwVersion = GetVersion();
  12213. #ifdef _MSC_VER
  12214. #pragma warning(pop)
  12215. #endif
  12216. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  12217. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  12218. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  12219. (void)dwBuild;
  12220. sprintf(name,
  12221. "Windows %u.%u",
  12222. (unsigned)dwMajorVersion,
  12223. (unsigned)dwMinorVersion);
  12224. *sysName = mg_strdup(name);
  12225. #endif
  12226. #else
  12227. *sysName = mg_strdup("Symbian");
  12228. #endif
  12229. #else
  12230. struct utsname name;
  12231. memset(&name, 0, sizeof(name));
  12232. uname(&name);
  12233. *sysName = mg_strdup(name.sysname);
  12234. #endif
  12235. }
  12236. struct mg_context *
  12237. mg_start(const struct mg_callbacks *callbacks,
  12238. void *user_data,
  12239. const char **options)
  12240. {
  12241. struct mg_context *ctx;
  12242. const char *name, *value, *default_value;
  12243. int idx, ok, workerthreadcount;
  12244. unsigned int i;
  12245. void (*exit_callback)(const struct mg_context *ctx) = 0;
  12246. struct mg_workerTLS tls;
  12247. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12248. WSADATA data;
  12249. WSAStartup(MAKEWORD(2, 2), &data);
  12250. #endif /* _WIN32 && !__SYMBIAN32__ */
  12251. /* Allocate context and initialize reasonable general case defaults. */
  12252. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  12253. return NULL;
  12254. }
  12255. /* Random number generator will initialize at the first call */
  12256. ctx->auth_nonce_mask =
  12257. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  12258. if (mg_atomic_inc(&sTlsInit) == 1) {
  12259. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12260. InitializeCriticalSection(&global_log_file_lock);
  12261. #endif /* _WIN32 && !__SYMBIAN32__ */
  12262. #if !defined(_WIN32)
  12263. pthread_mutexattr_init(&pthread_mutex_attr);
  12264. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  12265. #endif
  12266. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  12267. /* Fatal error - abort start. However, this situation should
  12268. * never
  12269. * occur in practice. */
  12270. mg_atomic_dec(&sTlsInit);
  12271. mg_cry(fc(ctx), "Cannot initialize thread local storage");
  12272. mg_free(ctx);
  12273. return NULL;
  12274. }
  12275. #if defined(USE_LUA)
  12276. lua_init_optional_libraries();
  12277. #endif
  12278. } else {
  12279. /* TODO (low): istead of sleeping, check if sTlsKey is already
  12280. * initialized. */
  12281. mg_sleep(1);
  12282. }
  12283. tls.is_master = -1;
  12284. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  12285. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12286. tls.pthread_cond_helper_mutex = NULL;
  12287. #endif
  12288. pthread_setspecific(sTlsKey, &tls);
  12289. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr);
  12290. #if !defined(ALTERNATIVE_QUEUE)
  12291. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  12292. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  12293. #endif
  12294. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr);
  12295. if (!ok) {
  12296. /* Fatal error - abort start. However, this situation should never
  12297. * occur in practice. */
  12298. mg_cry(fc(ctx), "Cannot initialize thread synchronization objects");
  12299. mg_free(ctx);
  12300. pthread_setspecific(sTlsKey, NULL);
  12301. return NULL;
  12302. }
  12303. if (callbacks) {
  12304. ctx->callbacks = *callbacks;
  12305. exit_callback = callbacks->exit_context;
  12306. ctx->callbacks.exit_context = 0;
  12307. }
  12308. ctx->user_data = user_data;
  12309. ctx->handlers = NULL;
  12310. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  12311. ctx->shared_lua_websockets = 0;
  12312. #endif
  12313. while (options && (name = *options++) != NULL) {
  12314. if ((idx = get_option_index(name)) == -1) {
  12315. mg_cry(fc(ctx), "Invalid option: %s", name);
  12316. free_context(ctx);
  12317. pthread_setspecific(sTlsKey, NULL);
  12318. return NULL;
  12319. } else if ((value = *options++) == NULL) {
  12320. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  12321. free_context(ctx);
  12322. pthread_setspecific(sTlsKey, NULL);
  12323. return NULL;
  12324. }
  12325. if (ctx->config[idx] != NULL) {
  12326. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  12327. mg_free(ctx->config[idx]);
  12328. }
  12329. ctx->config[idx] = mg_strdup(value);
  12330. DEBUG_TRACE("[%s] -> [%s]", name, value);
  12331. }
  12332. /* Set default value if needed */
  12333. for (i = 0; config_options[i].name != NULL; i++) {
  12334. default_value = config_options[i].default_value;
  12335. if (ctx->config[i] == NULL && default_value != NULL) {
  12336. ctx->config[i] = mg_strdup(default_value);
  12337. }
  12338. }
  12339. #if defined(NO_FILES)
  12340. if (ctx->config[DOCUMENT_ROOT] != NULL) {
  12341. mg_cry(fc(ctx), "%s", "Document root must not be set");
  12342. free_context(ctx);
  12343. pthread_setspecific(sTlsKey, NULL);
  12344. return NULL;
  12345. }
  12346. #endif
  12347. get_system_name(&ctx->systemName);
  12348. /* NOTE(lsm): order is important here. SSL certificates must
  12349. * be initialized before listening ports. UID must be set last. */
  12350. if (!set_gpass_option(ctx) ||
  12351. #if !defined(NO_SSL)
  12352. !set_ssl_option(ctx) ||
  12353. #endif
  12354. !set_ports_option(ctx) ||
  12355. #if !defined(_WIN32)
  12356. !set_uid_option(ctx) ||
  12357. #endif
  12358. !set_acl_option(ctx)) {
  12359. free_context(ctx);
  12360. pthread_setspecific(sTlsKey, NULL);
  12361. return NULL;
  12362. }
  12363. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  12364. /* Ignore SIGPIPE signal, so if browser cancels the request, it
  12365. * won't kill the whole process. */
  12366. (void)signal(SIGPIPE, SIG_IGN);
  12367. #endif /* !_WIN32 && !__SYMBIAN32__ */
  12368. workerthreadcount = atoi(ctx->config[NUM_THREADS]);
  12369. if (workerthreadcount > MAX_WORKER_THREADS) {
  12370. mg_cry(fc(ctx), "Too many worker threads");
  12371. free_context(ctx);
  12372. pthread_setspecific(sTlsKey, NULL);
  12373. return NULL;
  12374. }
  12375. if (workerthreadcount > 0) {
  12376. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  12377. ctx->workerthreadids =
  12378. (pthread_t *)mg_calloc(ctx->cfg_worker_threads, sizeof(pthread_t));
  12379. if (ctx->workerthreadids == NULL) {
  12380. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  12381. free_context(ctx);
  12382. pthread_setspecific(sTlsKey, NULL);
  12383. return NULL;
  12384. }
  12385. #if defined(ALTERNATIVE_QUEUE)
  12386. ctx->client_wait_events = mg_calloc(sizeof(ctx->client_wait_events[0]),
  12387. ctx->cfg_worker_threads);
  12388. if (ctx->client_wait_events == NULL) {
  12389. mg_cry(fc(ctx), "Not enough memory for worker event array");
  12390. mg_free(ctx->workerthreadids);
  12391. free_context(ctx);
  12392. pthread_setspecific(sTlsKey, NULL);
  12393. return NULL;
  12394. }
  12395. ctx->client_socks =
  12396. mg_calloc(sizeof(ctx->client_socks[0]), ctx->cfg_worker_threads);
  12397. if (ctx->client_wait_events == NULL) {
  12398. mg_cry(fc(ctx), "Not enough memory for worker socket array");
  12399. mg_free(ctx->client_socks);
  12400. mg_free(ctx->workerthreadids);
  12401. free_context(ctx);
  12402. pthread_setspecific(sTlsKey, NULL);
  12403. return NULL;
  12404. }
  12405. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  12406. ctx->client_wait_events[i] = event_create();
  12407. if (ctx->client_wait_events[i] == 0) {
  12408. mg_cry(fc(ctx), "Error creating worker event %i", i);
  12409. /* TODO: clean all and exit */
  12410. }
  12411. }
  12412. #endif
  12413. }
  12414. #if defined(USE_TIMERS)
  12415. if (timers_init(ctx) != 0) {
  12416. mg_cry(fc(ctx), "Error creating timers");
  12417. free_context(ctx);
  12418. pthread_setspecific(sTlsKey, NULL);
  12419. return NULL;
  12420. }
  12421. #endif
  12422. /* Context has been created - init user libraries */
  12423. if (ctx->callbacks.init_context) {
  12424. ctx->callbacks.init_context(ctx);
  12425. }
  12426. ctx->callbacks.exit_context = exit_callback;
  12427. ctx->context_type = 1; /* server context */
  12428. /* Start master (listening) thread */
  12429. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  12430. /* Start worker threads */
  12431. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  12432. struct worker_thread_args *wta =
  12433. mg_malloc(sizeof(struct worker_thread_args));
  12434. if (wta) {
  12435. wta->ctx = ctx;
  12436. wta->index = (int)i;
  12437. }
  12438. if ((wta == NULL)
  12439. || (mg_start_thread_with_id(worker_thread,
  12440. wta,
  12441. &ctx->workerthreadids[i]) != 0)) {
  12442. /* thread was not created */
  12443. if (wta != NULL) {
  12444. mg_free(wta);
  12445. }
  12446. if (i > 0) {
  12447. mg_cry(fc(ctx),
  12448. "Cannot start worker thread %i: error %ld",
  12449. i + 1,
  12450. (long)ERRNO);
  12451. } else {
  12452. mg_cry(fc(ctx),
  12453. "Cannot create threads: error %ld",
  12454. (long)ERRNO);
  12455. free_context(ctx);
  12456. pthread_setspecific(sTlsKey, NULL);
  12457. return NULL;
  12458. }
  12459. break;
  12460. }
  12461. }
  12462. pthread_setspecific(sTlsKey, NULL);
  12463. return ctx;
  12464. }
  12465. /* Feature check API function */
  12466. unsigned
  12467. mg_check_feature(unsigned feature)
  12468. {
  12469. static const unsigned feature_set = 0
  12470. /* Set bits for available features according to API documentation.
  12471. * This bit mask is created at compile time, according to the active
  12472. * preprocessor defines. It is a single const value at runtime. */
  12473. #if !defined(NO_FILES)
  12474. | 0x0001u
  12475. #endif
  12476. #if !defined(NO_SSL)
  12477. | 0x0002u
  12478. #endif
  12479. #if !defined(NO_CGI)
  12480. | 0x0004u
  12481. #endif
  12482. #if defined(USE_IPV6)
  12483. | 0x0008u
  12484. #endif
  12485. #if defined(USE_WEBSOCKET)
  12486. | 0x0010u
  12487. #endif
  12488. #if defined(USE_LUA)
  12489. | 0x0020u
  12490. #endif
  12491. #if defined(USE_DUKTAPE)
  12492. | 0x0040u
  12493. #endif
  12494. #if !defined(NO_CACHING)
  12495. | 0x0080u
  12496. #endif
  12497. /* Set some extra bits not defined in the API documentation.
  12498. * These bits may change without further notice. */
  12499. #if defined(MG_LEGACY_INTERFACE)
  12500. | 0x8000u
  12501. #endif
  12502. #if defined(MEMORY_DEBUGGING)
  12503. | 0x0100u
  12504. #endif
  12505. #if defined(USE_TIMERS)
  12506. | 0x0200u
  12507. #endif
  12508. #if !defined(NO_NONCE_CHECK)
  12509. | 0x0400u
  12510. #endif
  12511. #if !defined(NO_POPEN)
  12512. | 0x0800u
  12513. #endif
  12514. ;
  12515. return (feature & feature_set);
  12516. }