civetweb.c 377 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430
  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. static int
  135. _civet_clock_gettime(int clk_id, struct timespec *t)
  136. {
  137. memset(t, 0, sizeof(*t));
  138. if (clk_id == CLOCK_REALTIME) {
  139. struct timeval now;
  140. int rv = gettimeofday(&now, NULL);
  141. if (rv) {
  142. return rv;
  143. }
  144. t->tv_sec = now.tv_sec;
  145. t->tv_nsec = now.tv_usec * 1000;
  146. return 0;
  147. } else if (clk_id == CLOCK_MONOTONIC) {
  148. static uint64_t clock_start_time = 0;
  149. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  150. uint64_t now = mach_absolute_time();
  151. if (clock_start_time == 0) {
  152. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  153. #if defined(DEBUG)
  154. assert(mach_status == KERN_SUCCESS);
  155. #else
  156. /* appease "unused variable" warning for release builds */
  157. (void)mach_status;
  158. #endif
  159. clock_start_time = now;
  160. }
  161. now = (uint64_t)((double)(now - clock_start_time)
  162. * (double)timebase_ifo.numer
  163. / (double)timebase_ifo.denom);
  164. t->tv_sec = now / 1000000000;
  165. t->tv_nsec = now % 1000000000;
  166. return 0;
  167. }
  168. return -1; /* EINVAL - Clock ID is unknown */
  169. }
  170. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  171. #ifdef __CLOCK_AVAILABILITY
  172. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  173. * declared but it may be NULL at runtime. So we need to check before using
  174. * it. */
  175. static int
  176. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  177. {
  178. if (clock_gettime) {
  179. return clock_gettime(clk_id, t);
  180. }
  181. return _civet_clock_gettime(clk_id, t);
  182. }
  183. #define clock_gettime _civet_safe_clock_gettime
  184. #else
  185. #define clock_gettime _civet_clock_gettime
  186. #endif
  187. #endif
  188. #include <time.h>
  189. #include <stdlib.h>
  190. #include <stdarg.h>
  191. #include <assert.h>
  192. #include <string.h>
  193. #include <ctype.h>
  194. #include <limits.h>
  195. #include <stddef.h>
  196. #include <stdio.h>
  197. #include <stdint.h>
  198. #ifndef INT64_MAX
  199. #define INT64_MAX (9223372036854775807)
  200. #endif
  201. #ifndef MAX_WORKER_THREADS
  202. #define MAX_WORKER_THREADS (1024 * 64)
  203. #endif
  204. #ifndef SOCKET_TIMEOUT_QUANTUM /* in ms */
  205. #define SOCKET_TIMEOUT_QUANTUM (2000)
  206. #endif
  207. #define SHUTDOWN_RD (0)
  208. #define SHUTDOWN_WR (1)
  209. #define SHUTDOWN_BOTH (2)
  210. mg_static_assert(MAX_WORKER_THREADS >= 1,
  211. "worker threads must be a positive number");
  212. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  213. "size_t data type size check");
  214. #if defined(_WIN32) \
  215. && !defined(__SYMBIAN32__) /* WINDOWS / UNIX include block */
  216. #include <windows.h>
  217. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  218. #include <ws2tcpip.h>
  219. typedef const char *SOCK_OPT_TYPE;
  220. #if !defined(PATH_MAX)
  221. #define PATH_MAX (MAX_PATH)
  222. #endif
  223. #if !defined(PATH_MAX)
  224. #define PATH_MAX (4096)
  225. #endif
  226. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  227. #ifndef _IN_PORT_T
  228. #ifndef in_port_t
  229. #define in_port_t u_short
  230. #endif
  231. #endif
  232. #ifndef _WIN32_WCE
  233. #include <process.h>
  234. #include <direct.h>
  235. #include <io.h>
  236. #else /* _WIN32_WCE */
  237. #define NO_CGI /* WinCE has no pipes */
  238. #define NO_POPEN /* WinCE has no popen */
  239. typedef long off_t;
  240. #define errno ((int)(GetLastError()))
  241. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  242. #endif /* _WIN32_WCE */
  243. #define MAKEUQUAD(lo, hi) \
  244. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  245. #define RATE_DIFF (10000000) /* 100 nsecs */
  246. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  247. #define SYS2UNIX_TIME(lo, hi) \
  248. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  249. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  250. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  251. * Also use _strtoui64 on modern M$ compilers */
  252. #if defined(_MSC_VER)
  253. #if (_MSC_VER < 1300)
  254. #define STRX(x) #x
  255. #define STR(x) STRX(x)
  256. #define __func__ __FILE__ ":" STR(__LINE__)
  257. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  258. #define strtoll(x, y, z) (_atoi64(x))
  259. #else
  260. #define __func__ __FUNCTION__
  261. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  262. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  263. #endif
  264. #endif /* _MSC_VER */
  265. #define ERRNO ((int)(GetLastError()))
  266. #define NO_SOCKLEN_T
  267. #if defined(_WIN64) || defined(__MINGW64__)
  268. #define SSL_LIB "ssleay64.dll"
  269. #define CRYPTO_LIB "libeay64.dll"
  270. #else
  271. #define SSL_LIB "ssleay32.dll"
  272. #define CRYPTO_LIB "libeay32.dll"
  273. #endif
  274. #define O_NONBLOCK (0)
  275. #ifndef W_OK
  276. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  277. #endif
  278. #if !defined(EWOULDBLOCK)
  279. #define EWOULDBLOCK WSAEWOULDBLOCK
  280. #endif /* !EWOULDBLOCK */
  281. #define _POSIX_
  282. #define INT64_FMT "I64d"
  283. #define UINT64_FMT "I64u"
  284. #define WINCDECL __cdecl
  285. #define vsnprintf_impl _vsnprintf
  286. #define access _access
  287. #define mg_sleep(x) (Sleep(x))
  288. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  289. #ifndef popen
  290. #define popen(x, y) (_popen(x, y))
  291. #endif
  292. #ifndef pclose
  293. #define pclose(x) (_pclose(x))
  294. #endif
  295. #define close(x) (_close(x))
  296. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  297. #define RTLD_LAZY (0)
  298. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  299. #define fdopen(x, y) (_fdopen((x), (y)))
  300. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  301. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  302. #define flockfile(x) (EnterCriticalSection(&global_log_file_lock))
  303. #define funlockfile(x) (LeaveCriticalSection(&global_log_file_lock))
  304. #define sleep(x) (Sleep((x)*1000))
  305. #define rmdir(x) (_rmdir(x))
  306. #define timegm(x) (_mkgmtime(x))
  307. #if !defined(fileno)
  308. #define fileno(x) (_fileno(x))
  309. #endif /* !fileno MINGW #defines fileno */
  310. typedef HANDLE pthread_mutex_t;
  311. typedef DWORD pthread_key_t;
  312. typedef HANDLE pthread_t;
  313. typedef struct {
  314. CRITICAL_SECTION threadIdSec;
  315. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  316. } pthread_cond_t;
  317. #ifndef __clockid_t_defined
  318. typedef DWORD clockid_t;
  319. #endif
  320. #ifndef CLOCK_MONOTONIC
  321. #define CLOCK_MONOTONIC (1)
  322. #endif
  323. #ifndef CLOCK_REALTIME
  324. #define CLOCK_REALTIME (2)
  325. #endif
  326. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  327. #define _TIMESPEC_DEFINED
  328. #endif
  329. #ifndef _TIMESPEC_DEFINED
  330. struct timespec {
  331. time_t tv_sec; /* seconds */
  332. long tv_nsec; /* nanoseconds */
  333. };
  334. #endif
  335. #if !defined(WIN_PTHREADS_TIME_H)
  336. #define MUST_IMPLEMENT_CLOCK_GETTIME
  337. #endif
  338. #ifdef MUST_IMPLEMENT_CLOCK_GETTIME
  339. #define clock_gettime mg_clock_gettime
  340. static int
  341. clock_gettime(clockid_t clk_id, struct timespec *tp)
  342. {
  343. FILETIME ft;
  344. ULARGE_INTEGER li;
  345. BOOL ok = FALSE;
  346. double d;
  347. static double perfcnt_per_sec = 0.0;
  348. if (tp) {
  349. memset(tp, 0, sizeof(*tp));
  350. if (clk_id == CLOCK_REALTIME) {
  351. GetSystemTimeAsFileTime(&ft);
  352. li.LowPart = ft.dwLowDateTime;
  353. li.HighPart = ft.dwHighDateTime;
  354. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  355. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  356. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  357. ok = TRUE;
  358. } else if (clk_id == CLOCK_MONOTONIC) {
  359. if (perfcnt_per_sec == 0.0) {
  360. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  361. perfcnt_per_sec = 1.0 / li.QuadPart;
  362. }
  363. if (perfcnt_per_sec != 0.0) {
  364. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  365. d = li.QuadPart * perfcnt_per_sec;
  366. tp->tv_sec = (time_t)d;
  367. d -= tp->tv_sec;
  368. tp->tv_nsec = (long)(d * 1.0E9);
  369. ok = TRUE;
  370. }
  371. }
  372. }
  373. return ok ? 0 : -1;
  374. }
  375. #endif
  376. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  377. static int pthread_mutex_lock(pthread_mutex_t *);
  378. static int pthread_mutex_unlock(pthread_mutex_t *);
  379. static void path_to_unicode(const struct mg_connection *conn,
  380. const char *path,
  381. wchar_t *wbuf,
  382. size_t wbuf_len);
  383. /* All file operations need to be rewritten to solve #246. */
  384. #include "file_ops.inl"
  385. struct mg_file;
  386. static const char *
  387. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p);
  388. /* POSIX dirent interface */
  389. struct dirent {
  390. char d_name[PATH_MAX];
  391. };
  392. typedef struct DIR {
  393. HANDLE handle;
  394. WIN32_FIND_DATAW info;
  395. struct dirent result;
  396. } DIR;
  397. #if defined(_WIN32) && !defined(POLLIN)
  398. #ifndef HAVE_POLL
  399. struct pollfd {
  400. SOCKET fd;
  401. short events;
  402. short revents;
  403. };
  404. #define POLLIN (0x0300)
  405. #endif
  406. #endif
  407. /* Mark required libraries */
  408. #if defined(_MSC_VER)
  409. #pragma comment(lib, "Ws2_32.lib")
  410. #endif
  411. #else /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  412. WINDOWS / UNIX include block */
  413. #include <sys/wait.h>
  414. #include <sys/socket.h>
  415. #include <sys/poll.h>
  416. #include <netinet/in.h>
  417. #include <arpa/inet.h>
  418. #include <sys/time.h>
  419. #include <sys/utsname.h>
  420. #include <stdint.h>
  421. #include <inttypes.h>
  422. #include <netdb.h>
  423. #include <netinet/tcp.h>
  424. typedef const void *SOCK_OPT_TYPE;
  425. #if defined(ANDROID)
  426. typedef unsigned short int in_port_t;
  427. #endif
  428. #include <pwd.h>
  429. #include <unistd.h>
  430. #include <grp.h>
  431. #include <dirent.h>
  432. #define vsnprintf_impl vsnprintf
  433. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  434. #include <dlfcn.h>
  435. #endif
  436. #include <pthread.h>
  437. #if defined(__MACH__)
  438. #define SSL_LIB "libssl.dylib"
  439. #define CRYPTO_LIB "libcrypto.dylib"
  440. #else
  441. #if !defined(SSL_LIB)
  442. #define SSL_LIB "libssl.so"
  443. #endif
  444. #if !defined(CRYPTO_LIB)
  445. #define CRYPTO_LIB "libcrypto.so"
  446. #endif
  447. #endif
  448. #ifndef O_BINARY
  449. #define O_BINARY (0)
  450. #endif /* O_BINARY */
  451. #define closesocket(a) (close(a))
  452. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  453. #define mg_remove(conn, x) (remove(x))
  454. #define mg_sleep(x) (usleep((x)*1000))
  455. #define mg_opendir(conn, x) (opendir(x))
  456. #define mg_closedir(x) (closedir(x))
  457. #define mg_readdir(x) (readdir(x))
  458. #define ERRNO (errno)
  459. #define INVALID_SOCKET (-1)
  460. #define INT64_FMT PRId64
  461. #define UINT64_FMT PRIu64
  462. typedef int SOCKET;
  463. #define WINCDECL
  464. #if defined(__hpux)
  465. /* HPUX 11 does not have monotonic, fall back to realtime */
  466. #ifndef CLOCK_MONOTONIC
  467. #define CLOCK_MONOTONIC CLOCK_REALTIME
  468. #endif
  469. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  470. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  471. * the prototypes use int* rather than socklen_t* which matches the
  472. * actual library expectation. When called with the wrong size arg
  473. * accept() returns a zero client inet addr and check_acl() always
  474. * fails. Since socklen_t is widely used below, just force replace
  475. * their typedef with int. - DTL
  476. */
  477. #define socklen_t int
  478. #endif /* hpux */
  479. #endif /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  480. WINDOWS / UNIX include block */
  481. /* va_copy should always be a macro, C99 and C++11 - DTL */
  482. #ifndef va_copy
  483. #define va_copy(x, y) ((x) = (y))
  484. #endif
  485. #ifdef _WIN32
  486. /* Create substitutes for POSIX functions in Win32. */
  487. #if defined(__MINGW32__)
  488. /* Show no warning in case system functions are not used. */
  489. #pragma GCC diagnostic push
  490. #pragma GCC diagnostic ignored "-Wunused-function"
  491. #endif
  492. static CRITICAL_SECTION global_log_file_lock;
  493. static DWORD
  494. pthread_self(void)
  495. {
  496. return GetCurrentThreadId();
  497. }
  498. static int
  499. pthread_key_create(
  500. pthread_key_t *key,
  501. void (*_ignored)(void *) /* destructor not supported for Windows */
  502. )
  503. {
  504. (void)_ignored;
  505. if ((key != 0)) {
  506. *key = TlsAlloc();
  507. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  508. }
  509. return -2;
  510. }
  511. static int
  512. pthread_key_delete(pthread_key_t key)
  513. {
  514. return TlsFree(key) ? 0 : 1;
  515. }
  516. static int
  517. pthread_setspecific(pthread_key_t key, void *value)
  518. {
  519. return TlsSetValue(key, value) ? 0 : 1;
  520. }
  521. static void *
  522. pthread_getspecific(pthread_key_t key)
  523. {
  524. return TlsGetValue(key);
  525. }
  526. #if defined(__MINGW32__)
  527. /* Enable unused function warning again */
  528. #pragma GCC diagnostic pop
  529. #endif
  530. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  531. #else
  532. static pthread_mutexattr_t pthread_mutex_attr;
  533. #endif /* _WIN32 */
  534. #define PASSWORDS_FILE_NAME ".htpasswd"
  535. #define CGI_ENVIRONMENT_SIZE (4096)
  536. #define MAX_CGI_ENVIR_VARS (256)
  537. #define MG_BUF_LEN (8192)
  538. #ifndef MAX_REQUEST_SIZE
  539. #define MAX_REQUEST_SIZE (16384)
  540. #endif
  541. mg_static_assert(MAX_REQUEST_SIZE >= 256,
  542. "request size length must be a positive number");
  543. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  544. #if defined(_WIN32_WCE)
  545. /* Create substitutes for POSIX functions in Win32. */
  546. #if defined(__MINGW32__)
  547. /* Show no warning in case system functions are not used. */
  548. #pragma GCC diagnostic push
  549. #pragma GCC diagnostic ignored "-Wunused-function"
  550. #endif
  551. static time_t
  552. time(time_t *ptime)
  553. {
  554. time_t t;
  555. SYSTEMTIME st;
  556. FILETIME ft;
  557. GetSystemTime(&st);
  558. SystemTimeToFileTime(&st, &ft);
  559. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  560. if (ptime != NULL) {
  561. *ptime = t;
  562. }
  563. return t;
  564. }
  565. static struct tm *
  566. localtime_s(const time_t *ptime, struct tm *ptm)
  567. {
  568. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  569. FILETIME ft, lft;
  570. SYSTEMTIME st;
  571. TIME_ZONE_INFORMATION tzinfo;
  572. if (ptm == NULL) {
  573. return NULL;
  574. }
  575. *(int64_t *)&ft = t;
  576. FileTimeToLocalFileTime(&ft, &lft);
  577. FileTimeToSystemTime(&lft, &st);
  578. ptm->tm_year = st.wYear - 1900;
  579. ptm->tm_mon = st.wMonth - 1;
  580. ptm->tm_wday = st.wDayOfWeek;
  581. ptm->tm_mday = st.wDay;
  582. ptm->tm_hour = st.wHour;
  583. ptm->tm_min = st.wMinute;
  584. ptm->tm_sec = st.wSecond;
  585. ptm->tm_yday = 0; /* hope nobody uses this */
  586. ptm->tm_isdst =
  587. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  588. return ptm;
  589. }
  590. static struct tm *
  591. gmtime_s(const time_t *ptime, struct tm *ptm)
  592. {
  593. /* FIXME(lsm): fix this. */
  594. return localtime_s(ptime, ptm);
  595. }
  596. static int mg_atomic_inc(volatile int *addr);
  597. static struct tm tm_array[MAX_WORKER_THREADS];
  598. static int tm_index = 0;
  599. static struct tm *
  600. localtime(const time_t *ptime)
  601. {
  602. int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0]));
  603. return localtime_s(ptime, tm_array + i);
  604. }
  605. static struct tm *
  606. gmtime(const time_t *ptime)
  607. {
  608. int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  609. return gmtime_s(ptime, tm_array + i);
  610. }
  611. static size_t
  612. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  613. {
  614. /* TODO */ //(void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  615. // for WinCE");
  616. return 0;
  617. }
  618. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  619. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  620. #define remove(f) mg_remove(NULL, f)
  621. static int
  622. rename(const char *a, const char *b)
  623. {
  624. wchar_t wa[PATH_MAX];
  625. wchar_t wb[PATH_MAX];
  626. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  627. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  628. return MoveFileW(wa, wb) ? 0 : -1;
  629. }
  630. struct stat {
  631. int64_t st_size;
  632. time_t st_mtime;
  633. };
  634. static int
  635. stat(const char *name, struct stat *st)
  636. {
  637. wchar_t wbuf[PATH_MAX];
  638. WIN32_FILE_ATTRIBUTE_DATA attr;
  639. time_t creation_time, write_time;
  640. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  641. memset(&attr, 0, sizeof(attr));
  642. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  643. st->st_size =
  644. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  645. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  646. attr.ftLastWriteTime.dwHighDateTime);
  647. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  648. attr.ftCreationTime.dwHighDateTime);
  649. if (creation_time > write_time) {
  650. st->st_mtime = creation_time;
  651. } else {
  652. st->st_mtime = write_time;
  653. }
  654. return 0;
  655. }
  656. #define access(x, a) 1 /* not required anyway */
  657. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  658. #define EEXIST 1 /* TODO: See Windows error codes */
  659. #define EACCES 2 /* TODO: See Windows error codes */
  660. #define ENOENT 3 /* TODO: See Windows Error codes */
  661. #if defined(__MINGW32__)
  662. /* Enable unused function warning again */
  663. #pragma GCC diagnostic pop
  664. #endif
  665. #endif /* defined(_WIN32_WCE) */
  666. static int
  667. mg_atomic_inc(volatile int *addr)
  668. {
  669. int ret;
  670. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  671. /* Depending on the SDK, this function uses either
  672. * (volatile unsigned int *) or (volatile LONG *),
  673. * so whatever you use, the other SDK is likely to raise a warning. */
  674. ret = InterlockedIncrement((volatile long *)addr);
  675. #elif defined(__GNUC__) \
  676. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  677. ret = __sync_add_and_fetch(addr, 1);
  678. #else
  679. ret = (++(*addr));
  680. #endif
  681. return ret;
  682. }
  683. static int
  684. mg_atomic_dec(volatile int *addr)
  685. {
  686. int ret;
  687. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  688. /* Depending on the SDK, this function uses either
  689. * (volatile unsigned int *) or (volatile LONG *),
  690. * so whatever you use, the other SDK is likely to raise a warning. */
  691. ret = InterlockedDecrement((volatile long *)addr);
  692. #elif defined(__GNUC__) \
  693. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  694. ret = __sync_sub_and_fetch(addr, 1);
  695. #else
  696. ret = (--(*addr));
  697. #endif
  698. return ret;
  699. }
  700. #if defined(MEMORY_DEBUGGING)
  701. static unsigned long mg_memory_debug_blockCount = 0;
  702. static unsigned long mg_memory_debug_totalMemUsed = 0;
  703. static void *
  704. mg_malloc_ex(size_t size, const char *file, unsigned line)
  705. {
  706. void *data = malloc(size + sizeof(size_t));
  707. void *memory = 0;
  708. char mallocStr[256];
  709. if (data) {
  710. *(size_t *)data = size;
  711. mg_memory_debug_totalMemUsed += size;
  712. mg_memory_debug_blockCount++;
  713. memory = (void *)(((char *)data) + sizeof(size_t));
  714. }
  715. sprintf(mallocStr,
  716. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  717. memory,
  718. (unsigned long)size,
  719. mg_memory_debug_totalMemUsed,
  720. mg_memory_debug_blockCount,
  721. file,
  722. line);
  723. #if defined(_WIN32)
  724. OutputDebugStringA(mallocStr);
  725. #else
  726. DEBUG_TRACE("%s", mallocStr);
  727. #endif
  728. return memory;
  729. }
  730. static void *
  731. mg_calloc_ex(size_t count, size_t size, const char *file, unsigned line)
  732. {
  733. void *data = mg_malloc_ex(size * count, file, line);
  734. if (data) {
  735. memset(data, 0, size * count);
  736. }
  737. return data;
  738. }
  739. static void
  740. mg_free_ex(void *memory, const char *file, unsigned line)
  741. {
  742. char mallocStr[256];
  743. void *data = (void *)(((char *)memory) - sizeof(size_t));
  744. size_t size;
  745. if (memory) {
  746. size = *(size_t *)data;
  747. mg_memory_debug_totalMemUsed -= size;
  748. mg_memory_debug_blockCount--;
  749. sprintf(mallocStr,
  750. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  751. memory,
  752. (unsigned long)size,
  753. mg_memory_debug_totalMemUsed,
  754. mg_memory_debug_blockCount,
  755. file,
  756. line);
  757. #if defined(_WIN32)
  758. OutputDebugStringA(mallocStr);
  759. #else
  760. DEBUG_TRACE("%s", mallocStr);
  761. #endif
  762. free(data);
  763. }
  764. }
  765. static void *
  766. mg_realloc_ex(void *memory, size_t newsize, const char *file, unsigned line)
  767. {
  768. char mallocStr[256];
  769. void *data;
  770. void *_realloc;
  771. size_t oldsize;
  772. if (newsize) {
  773. if (memory) {
  774. data = (void *)(((char *)memory) - sizeof(size_t));
  775. oldsize = *(size_t *)data;
  776. _realloc = realloc(data, newsize + sizeof(size_t));
  777. if (_realloc) {
  778. data = _realloc;
  779. mg_memory_debug_totalMemUsed -= oldsize;
  780. sprintf(mallocStr,
  781. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  782. memory,
  783. (unsigned long)oldsize,
  784. mg_memory_debug_totalMemUsed,
  785. mg_memory_debug_blockCount,
  786. file,
  787. line);
  788. #if defined(_WIN32)
  789. OutputDebugStringA(mallocStr);
  790. #else
  791. DEBUG_TRACE("%s", mallocStr);
  792. #endif
  793. mg_memory_debug_totalMemUsed += newsize;
  794. sprintf(mallocStr,
  795. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  796. memory,
  797. (unsigned long)newsize,
  798. mg_memory_debug_totalMemUsed,
  799. mg_memory_debug_blockCount,
  800. file,
  801. line);
  802. #if defined(_WIN32)
  803. OutputDebugStringA(mallocStr);
  804. #else
  805. DEBUG_TRACE("%s", mallocStr);
  806. #endif
  807. *(size_t *)data = newsize;
  808. data = (void *)(((char *)data) + sizeof(size_t));
  809. } else {
  810. #if defined(_WIN32)
  811. OutputDebugStringA("MEM: realloc failed\n");
  812. #else
  813. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  814. #endif
  815. return _realloc;
  816. }
  817. } else {
  818. data = mg_malloc_ex(newsize, file, line);
  819. }
  820. } else {
  821. data = 0;
  822. mg_free_ex(memory, file, line);
  823. }
  824. return data;
  825. }
  826. #define mg_malloc(a) mg_malloc_ex(a, __FILE__, __LINE__)
  827. #define mg_calloc(a, b) mg_calloc_ex(a, b, __FILE__, __LINE__)
  828. #define mg_realloc(a, b) mg_realloc_ex(a, b, __FILE__, __LINE__)
  829. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  830. #else
  831. static __inline void *
  832. mg_malloc(size_t a)
  833. {
  834. return malloc(a);
  835. }
  836. static __inline void *
  837. mg_calloc(size_t a, size_t b)
  838. {
  839. return calloc(a, b);
  840. }
  841. static __inline void *
  842. mg_realloc(void *a, size_t b)
  843. {
  844. return realloc(a, b);
  845. }
  846. static __inline void
  847. mg_free(void *a)
  848. {
  849. free(a);
  850. }
  851. #endif
  852. static void mg_vsnprintf(const struct mg_connection *conn,
  853. int *truncated,
  854. char *buf,
  855. size_t buflen,
  856. const char *fmt,
  857. va_list ap);
  858. static void mg_snprintf(const struct mg_connection *conn,
  859. int *truncated,
  860. char *buf,
  861. size_t buflen,
  862. PRINTF_FORMAT_STRING(const char *fmt),
  863. ...) PRINTF_ARGS(5, 6);
  864. /* This following lines are just meant as a reminder to use the mg-functions
  865. * for memory management */
  866. #ifdef malloc
  867. #undef malloc
  868. #endif
  869. #ifdef calloc
  870. #undef calloc
  871. #endif
  872. #ifdef realloc
  873. #undef realloc
  874. #endif
  875. #ifdef free
  876. #undef free
  877. #endif
  878. #ifdef snprintf
  879. #undef snprintf
  880. #endif
  881. #ifdef vsnprintf
  882. #undef vsnprintf
  883. #endif
  884. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  885. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  886. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  887. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  888. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  889. #ifdef _WIN32 /* vsnprintf must not be used in any system, * \ \ \ \
  890. * but this define only works well for Windows. */
  891. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  892. #endif
  893. static pthread_key_t sTlsKey; /* Thread local storage index */
  894. static int sTlsInit = 0;
  895. static int thread_idx_max = 0;
  896. struct mg_workerTLS {
  897. int is_master;
  898. unsigned long thread_idx;
  899. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  900. HANDLE pthread_cond_helper_mutex;
  901. struct mg_workerTLS *next_waiting_thread;
  902. #endif
  903. };
  904. #if defined(__GNUC__) || defined(__MINGW32__)
  905. /* Show no warning in case system functions are not used. */
  906. #pragma GCC diagnostic push
  907. #pragma GCC diagnostic ignored "-Wunused-function"
  908. #endif
  909. #if defined(__clang__)
  910. /* Show no warning in case system functions are not used. */
  911. #pragma clang diagnostic push
  912. #pragma clang diagnostic ignored "-Wunused-function"
  913. #endif
  914. /* Get a unique thread ID as unsigned long, independent from the data type
  915. * of thread IDs defined by the operating system API.
  916. * If two calls to mg_current_thread_id return the same value, they calls
  917. * are done from the same thread. If they return different values, they are
  918. * done from different threads. (Provided this function is used in the same
  919. * process context and threads are not repeatedly created and deleted, but
  920. * CivetWeb does not do that).
  921. * This function must match the signature required for SSL id callbacks:
  922. * CRYPTO_set_id_callback
  923. */
  924. static unsigned long
  925. mg_current_thread_id(void)
  926. {
  927. #ifdef _WIN32
  928. return GetCurrentThreadId();
  929. #else
  930. #ifdef __clang__
  931. #pragma clang diagnostic push
  932. #pragma clang diagnostic ignored "-Wunreachable-code"
  933. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  934. * or not, so one of the two conditions will be unreachable by construction.
  935. * Unfortunately the C standard does not define a way to check this at
  936. * compile time, since the #if preprocessor conditions can not use the sizeof
  937. * operator as an argument. */
  938. #endif
  939. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  940. /* This is the problematic case for CRYPTO_set_id_callback:
  941. * The OS pthread_t can not be cast to unsigned long. */
  942. struct mg_workerTLS *tls =
  943. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  944. if (tls == NULL) {
  945. /* SSL called from an unknown thread: Create some thread index.
  946. */
  947. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  948. tls->is_master = -2; /* -2 means "3rd party thread" */
  949. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  950. pthread_setspecific(sTlsKey, tls);
  951. }
  952. return tls->thread_idx;
  953. } else {
  954. /* pthread_t may be any data type, so a simple cast to unsigned long
  955. * can rise a warning/error, depending on the platform.
  956. * Here memcpy is used as an anything-to-anything cast. */
  957. unsigned long ret = 0;
  958. pthread_t t = pthread_self();
  959. memcpy(&ret, &t, sizeof(pthread_t));
  960. return ret;
  961. }
  962. #ifdef __clang__
  963. #pragma clang diagnostic pop
  964. #endif
  965. #endif
  966. }
  967. #if defined(__GNUC__)
  968. /* Show no warning in case system functions are not used. */
  969. #pragma GCC diagnostic pop
  970. #endif
  971. #if defined(__clang__)
  972. /* Show no warning in case system functions are not used. */
  973. #pragma clang diagnostic pop
  974. #endif
  975. #if !defined(DEBUG_TRACE)
  976. #if defined(DEBUG)
  977. static void DEBUG_TRACE_FUNC(const char *func,
  978. unsigned line,
  979. PRINTF_FORMAT_STRING(const char *fmt),
  980. ...) PRINTF_ARGS(3, 4);
  981. static void
  982. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  983. {
  984. va_list args;
  985. struct timespec tsnow;
  986. uint64_t nsnow;
  987. static uint64_t nslast;
  988. /* Get some operating system independent thread id */
  989. unsigned long thread_id = mg_current_thread_id();
  990. clock_gettime(CLOCK_REALTIME, &tsnow);
  991. nsnow = (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  992. flockfile(stdout);
  993. printf("*** %lu.%09lu %12" INT64_FMT " %lu %s:%u: ",
  994. (unsigned long)tsnow.tv_sec,
  995. (unsigned long)tsnow.tv_nsec,
  996. nsnow - nslast,
  997. thread_id,
  998. func,
  999. line);
  1000. va_start(args, fmt);
  1001. vprintf(fmt, args);
  1002. va_end(args);
  1003. putchar('\n');
  1004. fflush(stdout);
  1005. funlockfile(stdout);
  1006. nslast = nsnow;
  1007. }
  1008. #define DEBUG_TRACE(fmt, ...) \
  1009. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  1010. #else
  1011. #define DEBUG_TRACE(fmt, ...) \
  1012. do { \
  1013. } while (0)
  1014. #endif /* DEBUG */
  1015. #endif /* DEBUG_TRACE */
  1016. #define MD5_STATIC static
  1017. #include "md5.inl"
  1018. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1019. #ifdef NO_SOCKLEN_T
  1020. typedef int socklen_t;
  1021. #endif /* NO_SOCKLEN_T */
  1022. #define _DARWIN_UNLIMITED_SELECT
  1023. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1024. #if !defined(MSG_NOSIGNAL)
  1025. #define MSG_NOSIGNAL (0)
  1026. #endif
  1027. #if !defined(SOMAXCONN)
  1028. #define SOMAXCONN (100)
  1029. #endif
  1030. /* Size of the accepted socket queue */
  1031. #if !defined(MGSQLEN)
  1032. #define MGSQLEN (20)
  1033. #endif
  1034. #if defined(NO_SSL)
  1035. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1036. typedef struct SSL_CTX SSL_CTX;
  1037. #else
  1038. #if defined(NO_SSL_DL)
  1039. #include <openssl/ssl.h>
  1040. #include <openssl/err.h>
  1041. #include <openssl/crypto.h>
  1042. #include <openssl/x509.h>
  1043. #include <openssl/pem.h>
  1044. #include <openssl/engine.h>
  1045. #include <openssl/conf.h>
  1046. #include <openssl/dh.h>
  1047. #else
  1048. /* SSL loaded dynamically from DLL.
  1049. * I put the prototypes here to be independent from OpenSSL source
  1050. * installation. */
  1051. typedef struct ssl_st SSL;
  1052. typedef struct ssl_method_st SSL_METHOD;
  1053. typedef struct ssl_ctx_st SSL_CTX;
  1054. typedef struct x509_store_ctx_st X509_STORE_CTX;
  1055. typedef struct x509_name X509_NAME;
  1056. typedef struct asn1_integer ASN1_INTEGER;
  1057. typedef struct evp_md EVP_MD;
  1058. typedef struct x509 X509;
  1059. #define SSL_CTRL_OPTIONS (32)
  1060. #define SSL_CTRL_CLEAR_OPTIONS (77)
  1061. #define SSL_CTRL_SET_ECDH_AUTO (94)
  1062. #define SSL_VERIFY_NONE (0)
  1063. #define SSL_VERIFY_PEER (1)
  1064. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  1065. #define SSL_VERIFY_CLIENT_ONCE (4)
  1066. #define SSL_OP_ALL ((long)(0x80000BFFUL))
  1067. #define SSL_OP_NO_SSLv2 (0x01000000L)
  1068. #define SSL_OP_NO_SSLv3 (0x02000000L)
  1069. #define SSL_OP_NO_TLSv1 (0x04000000L)
  1070. #define SSL_OP_NO_TLSv1_2 (0x08000000L)
  1071. #define SSL_OP_NO_TLSv1_1 (0x10000000L)
  1072. #define SSL_OP_SINGLE_DH_USE (0x00100000L)
  1073. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000L)
  1074. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000L)
  1075. #define SSL_ERROR_NONE (0)
  1076. #define SSL_ERROR_SSL (1)
  1077. #define SSL_ERROR_WANT_READ (2)
  1078. #define SSL_ERROR_WANT_WRITE (3)
  1079. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  1080. #define SSL_ERROR_SYSCALL (5) /* see errno */
  1081. #define SSL_ERROR_ZERO_RETURN (6)
  1082. #define SSL_ERROR_WANT_CONNECT (7)
  1083. #define SSL_ERROR_WANT_ACCEPT (8)
  1084. struct ssl_func {
  1085. const char *name; /* SSL function name */
  1086. void (*ptr)(void); /* Function pointer */
  1087. };
  1088. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1089. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1090. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1091. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1092. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1093. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1094. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1095. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  1096. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  1097. #define SSLv23_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  1098. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  1099. #define SSL_CTX_use_PrivateKey_file \
  1100. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1101. #define SSL_CTX_use_certificate_file \
  1102. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1103. #define SSL_CTX_set_default_passwd_cb \
  1104. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1105. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1106. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  1107. #define SSL_CTX_use_certificate_chain_file \
  1108. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  1109. #define SSLv23_client_method (*(SSL_METHOD * (*)(void))ssl_sw[17].ptr)
  1110. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  1111. #define SSL_CTX_set_verify \
  1112. (*(void (*)(SSL_CTX *, \
  1113. int, \
  1114. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19].ptr)
  1115. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  1116. #define SSL_CTX_load_verify_locations \
  1117. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  1118. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  1119. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  1120. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[24].ptr)
  1121. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  1122. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[26].ptr)
  1123. #define SSL_CIPHER_get_name \
  1124. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  1125. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  1126. #define SSL_CTX_set_session_id_context \
  1127. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  1128. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  1129. #define SSL_CTX_set_cipher_list \
  1130. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  1131. #define SSL_CTX_set_options(ctx, op) \
  1132. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  1133. #define SSL_CTX_clear_options(ctx, op) \
  1134. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1135. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1136. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1137. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1138. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1139. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  1140. #define CRYPTO_set_locking_callback \
  1141. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  1142. #define CRYPTO_set_id_callback \
  1143. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  1144. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  1145. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  1146. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  1147. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  1148. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  1149. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  1150. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  1151. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  1152. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  1153. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[12].ptr)
  1154. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[13].ptr)
  1155. #define X509_NAME_oneline \
  1156. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  1157. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[15].ptr)
  1158. #define i2c_ASN1_INTEGER \
  1159. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  1160. #define EVP_get_digestbyname \
  1161. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1162. #define ASN1_digest \
  1163. (*(int (*)(int (*)(), \
  1164. const EVP_MD *, \
  1165. char *, \
  1166. unsigned char *, \
  1167. unsigned int *))crypto_sw[18].ptr)
  1168. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1169. /* set_ssl_option() function updates this array.
  1170. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1171. * of respective functions. The macros above (like SSL_connect()) are really
  1172. * just calling these functions indirectly via the pointer. */
  1173. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1174. {"SSL_accept", NULL},
  1175. {"SSL_connect", NULL},
  1176. {"SSL_read", NULL},
  1177. {"SSL_write", NULL},
  1178. {"SSL_get_error", NULL},
  1179. {"SSL_set_fd", NULL},
  1180. {"SSL_new", NULL},
  1181. {"SSL_CTX_new", NULL},
  1182. {"SSLv23_server_method", NULL},
  1183. {"SSL_library_init", NULL},
  1184. {"SSL_CTX_use_PrivateKey_file", NULL},
  1185. {"SSL_CTX_use_certificate_file", NULL},
  1186. {"SSL_CTX_set_default_passwd_cb", NULL},
  1187. {"SSL_CTX_free", NULL},
  1188. {"SSL_load_error_strings", NULL},
  1189. {"SSL_CTX_use_certificate_chain_file", NULL},
  1190. {"SSLv23_client_method", NULL},
  1191. {"SSL_pending", NULL},
  1192. {"SSL_CTX_set_verify", NULL},
  1193. {"SSL_shutdown", NULL},
  1194. {"SSL_CTX_load_verify_locations", NULL},
  1195. {"SSL_CTX_set_default_verify_paths", NULL},
  1196. {"SSL_CTX_set_verify_depth", NULL},
  1197. {"SSL_get_peer_certificate", NULL},
  1198. {"SSL_get_version", NULL},
  1199. {"SSL_get_current_cipher", NULL},
  1200. {"SSL_CIPHER_get_name", NULL},
  1201. {"SSL_CTX_check_private_key", NULL},
  1202. {"SSL_CTX_set_session_id_context", NULL},
  1203. {"SSL_CTX_ctrl", NULL},
  1204. {"SSL_CTX_set_cipher_list", NULL},
  1205. {NULL, NULL}};
  1206. /* Similar array as ssl_sw. These functions could be located in different
  1207. * lib. */
  1208. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  1209. {"CRYPTO_set_locking_callback", NULL},
  1210. {"CRYPTO_set_id_callback", NULL},
  1211. {"ERR_get_error", NULL},
  1212. {"ERR_error_string", NULL},
  1213. {"ERR_remove_state", NULL},
  1214. {"ERR_free_strings", NULL},
  1215. {"ENGINE_cleanup", NULL},
  1216. {"CONF_modules_unload", NULL},
  1217. {"CRYPTO_cleanup_all_ex_data", NULL},
  1218. {"EVP_cleanup", NULL},
  1219. {"X509_free", NULL},
  1220. {"X509_get_subject_name", NULL},
  1221. {"X509_get_issuer_name", NULL},
  1222. {"X509_NAME_oneline", NULL},
  1223. {"X509_get_serialNumber", NULL},
  1224. {"i2c_ASN1_INTEGER", NULL},
  1225. {"EVP_get_digestbyname", NULL},
  1226. {"ASN1_digest", NULL},
  1227. {"i2d_X509", NULL},
  1228. {NULL, NULL}};
  1229. #endif /* NO_SSL_DL */
  1230. #endif /* NO_SSL */
  1231. #if !defined(NO_CACHING)
  1232. static const char *month_names[] = {"Jan",
  1233. "Feb",
  1234. "Mar",
  1235. "Apr",
  1236. "May",
  1237. "Jun",
  1238. "Jul",
  1239. "Aug",
  1240. "Sep",
  1241. "Oct",
  1242. "Nov",
  1243. "Dec"};
  1244. #endif /* !NO_CACHING */
  1245. /* Unified socket address. For IPv6 support, add IPv6 address structure in the
  1246. * union u. */
  1247. union usa {
  1248. struct sockaddr sa;
  1249. struct sockaddr_in sin;
  1250. #if defined(USE_IPV6)
  1251. struct sockaddr_in6 sin6;
  1252. #endif
  1253. };
  1254. /* Describes a string (chunk of memory). */
  1255. struct vec {
  1256. const char *ptr;
  1257. size_t len;
  1258. };
  1259. struct mg_file_stat {
  1260. /* File properties filled by mg_stat: */
  1261. uint64_t size;
  1262. time_t last_modified;
  1263. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1264. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1265. * case we need a "Content-Eencoding: gzip" header */
  1266. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1267. };
  1268. struct mg_file_in_memory {
  1269. char *p;
  1270. uint32_t pos;
  1271. char mode;
  1272. };
  1273. struct mg_file_access {
  1274. /* File properties filled by mg_fopen: */
  1275. FILE *fp;
  1276. /* TODO: struct mg_file_in_memory *mf; */
  1277. const char *membuf; /* TODO: remove */
  1278. };
  1279. struct mg_file {
  1280. struct mg_file_stat stat;
  1281. struct mg_file_access access;
  1282. };
  1283. #define STRUCT_FILE_INITIALIZER \
  1284. { \
  1285. { \
  1286. (uint64_t)0, (time_t)0, 0, 0, 0 \
  1287. } \
  1288. , \
  1289. { \
  1290. (FILE *) NULL, (const char *)NULL \
  1291. } \
  1292. }
  1293. /* Describes listening socket, or socket which was accept()-ed by the master
  1294. * thread and queued for future handling by the worker thread. */
  1295. struct socket {
  1296. SOCKET sock; /* Listening socket */
  1297. union usa lsa; /* Local socket address */
  1298. union usa rsa; /* Remote socket address */
  1299. unsigned char is_ssl; /* Is port SSL-ed */
  1300. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1301. * port */
  1302. unsigned char in_use; /* Is valid */
  1303. };
  1304. /* NOTE(lsm): this enum shoulds be in sync with the config_options below. */
  1305. enum {
  1306. CGI_EXTENSIONS,
  1307. CGI_ENVIRONMENT,
  1308. PUT_DELETE_PASSWORDS_FILE,
  1309. CGI_INTERPRETER,
  1310. PROTECT_URI,
  1311. AUTHENTICATION_DOMAIN,
  1312. SSI_EXTENSIONS,
  1313. THROTTLE,
  1314. ACCESS_LOG_FILE,
  1315. ENABLE_DIRECTORY_LISTING,
  1316. ERROR_LOG_FILE,
  1317. GLOBAL_PASSWORDS_FILE,
  1318. INDEX_FILES,
  1319. ENABLE_KEEP_ALIVE,
  1320. ACCESS_CONTROL_LIST,
  1321. EXTRA_MIME_TYPES,
  1322. LISTENING_PORTS,
  1323. DOCUMENT_ROOT,
  1324. SSL_CERTIFICATE,
  1325. NUM_THREADS,
  1326. RUN_AS_USER,
  1327. REWRITE,
  1328. HIDE_FILES,
  1329. REQUEST_TIMEOUT,
  1330. KEEP_ALIVE_TIMEOUT,
  1331. LINGER_TIMEOUT,
  1332. SSL_DO_VERIFY_PEER,
  1333. SSL_CA_PATH,
  1334. SSL_CA_FILE,
  1335. SSL_VERIFY_DEPTH,
  1336. SSL_DEFAULT_VERIFY_PATHS,
  1337. SSL_CIPHER_LIST,
  1338. SSL_PROTOCOL_VERSION,
  1339. SSL_SHORT_TRUST,
  1340. #if defined(USE_WEBSOCKET)
  1341. WEBSOCKET_TIMEOUT,
  1342. #endif
  1343. DECODE_URL,
  1344. #if defined(USE_LUA)
  1345. LUA_PRELOAD_FILE,
  1346. LUA_SCRIPT_EXTENSIONS,
  1347. LUA_SERVER_PAGE_EXTENSIONS,
  1348. #endif
  1349. #if defined(USE_DUKTAPE)
  1350. DUKTAPE_SCRIPT_EXTENSIONS,
  1351. #endif
  1352. #if defined(USE_WEBSOCKET)
  1353. WEBSOCKET_ROOT,
  1354. #endif
  1355. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1356. LUA_WEBSOCKET_EXTENSIONS,
  1357. #endif
  1358. ACCESS_CONTROL_ALLOW_ORIGIN,
  1359. ERROR_PAGES,
  1360. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1361. * socket option typedef TCP_NODELAY. */
  1362. #if !defined(NO_CACHING)
  1363. STATIC_FILE_MAX_AGE,
  1364. #endif
  1365. #if defined(__linux__)
  1366. ALLOW_SENDFILE_CALL,
  1367. #endif
  1368. #if defined(_WIN32)
  1369. CASE_SENSITIVE_FILES,
  1370. #endif
  1371. NUM_OPTIONS
  1372. };
  1373. /* Config option name, config types, default value */
  1374. static struct mg_option config_options[] = {
  1375. {"cgi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1376. {"cgi_environment", CONFIG_TYPE_STRING, NULL},
  1377. {"put_delete_auth_file", CONFIG_TYPE_FILE, NULL},
  1378. {"cgi_interpreter", CONFIG_TYPE_FILE, NULL},
  1379. {"protect_uri", CONFIG_TYPE_STRING, NULL},
  1380. {"authentication_domain", CONFIG_TYPE_STRING, "mydomain.com"},
  1381. {"ssi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1382. {"throttle", CONFIG_TYPE_STRING, NULL},
  1383. {"access_log_file", CONFIG_TYPE_FILE, NULL},
  1384. {"enable_directory_listing", CONFIG_TYPE_BOOLEAN, "yes"},
  1385. {"error_log_file", CONFIG_TYPE_FILE, NULL},
  1386. {"global_auth_file", CONFIG_TYPE_FILE, NULL},
  1387. {"index_files",
  1388. CONFIG_TYPE_STRING,
  1389. #ifdef USE_LUA
  1390. "index.xhtml,index.html,index.htm,index.lp,index.lsp,index.lua,index.cgi,"
  1391. "index.shtml,index.php"},
  1392. #else
  1393. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1394. #endif
  1395. {"enable_keep_alive", CONFIG_TYPE_BOOLEAN, "no"},
  1396. {"access_control_list", CONFIG_TYPE_STRING, NULL},
  1397. {"extra_mime_types", CONFIG_TYPE_STRING, NULL},
  1398. {"listening_ports", CONFIG_TYPE_STRING, "8080"},
  1399. {"document_root", CONFIG_TYPE_DIRECTORY, NULL},
  1400. {"ssl_certificate", CONFIG_TYPE_FILE, NULL},
  1401. {"num_threads", CONFIG_TYPE_NUMBER, "50"},
  1402. {"run_as_user", CONFIG_TYPE_STRING, NULL},
  1403. {"url_rewrite_patterns", CONFIG_TYPE_STRING, NULL},
  1404. {"hide_files_patterns", CONFIG_TYPE_EXT_PATTERN, NULL},
  1405. {"request_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1406. {"keep_alive_timeout_ms", CONFIG_TYPE_NUMBER, "500"},
  1407. {"linger_timeout_ms", CONFIG_TYPE_NUMBER, NULL},
  1408. {"ssl_verify_peer", CONFIG_TYPE_BOOLEAN, "no"},
  1409. {"ssl_ca_path", CONFIG_TYPE_DIRECTORY, NULL},
  1410. {"ssl_ca_file", CONFIG_TYPE_FILE, NULL},
  1411. {"ssl_verify_depth", CONFIG_TYPE_NUMBER, "9"},
  1412. {"ssl_default_verify_paths", CONFIG_TYPE_BOOLEAN, "yes"},
  1413. {"ssl_cipher_list", CONFIG_TYPE_STRING, NULL},
  1414. {"ssl_protocol_version", CONFIG_TYPE_NUMBER, "0"},
  1415. {"ssl_short_trust", CONFIG_TYPE_BOOLEAN, "no"},
  1416. #if defined(USE_WEBSOCKET)
  1417. {"websocket_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1418. #endif
  1419. {"decode_url", CONFIG_TYPE_BOOLEAN, "yes"},
  1420. #if defined(USE_LUA)
  1421. {"lua_preload_file", CONFIG_TYPE_FILE, NULL},
  1422. {"lua_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1423. {"lua_server_page_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1424. #endif
  1425. #if defined(USE_DUKTAPE)
  1426. /* The support for duktape is still in alpha version state.
  1427. * The name of this config option might change. */
  1428. {"duktape_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1429. #endif
  1430. #if defined(USE_WEBSOCKET)
  1431. {"websocket_root", CONFIG_TYPE_DIRECTORY, NULL},
  1432. #endif
  1433. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1434. {"lua_websocket_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1435. #endif
  1436. {"access_control_allow_origin", CONFIG_TYPE_STRING, "*"},
  1437. {"error_pages", CONFIG_TYPE_DIRECTORY, NULL},
  1438. {"tcp_nodelay", CONFIG_TYPE_NUMBER, "0"},
  1439. #if !defined(NO_CACHING)
  1440. {"static_file_max_age", CONFIG_TYPE_NUMBER, "3600"},
  1441. #endif
  1442. #if defined(__linux__)
  1443. {"allow_sendfile_call", CONFIG_TYPE_BOOLEAN, "yes"},
  1444. #endif
  1445. #if defined(_WIN32)
  1446. {"case_sensitive", CONFIG_TYPE_BOOLEAN, "no"},
  1447. #endif
  1448. {NULL, CONFIG_TYPE_UNKNOWN, NULL}};
  1449. /* Check if the config_options and the corresponding enum have compatible
  1450. * sizes. */
  1451. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1452. == (NUM_OPTIONS + 1),
  1453. "config_options and enum not sync");
  1454. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1455. struct mg_handler_info {
  1456. /* Name/Pattern of the URI. */
  1457. char *uri;
  1458. size_t uri_len;
  1459. /* handler type */
  1460. int handler_type;
  1461. /* Handler for http/https or authorization requests. */
  1462. mg_request_handler handler;
  1463. /* Handler for ws/wss (websocket) requests. */
  1464. mg_websocket_connect_handler connect_handler;
  1465. mg_websocket_ready_handler ready_handler;
  1466. mg_websocket_data_handler data_handler;
  1467. mg_websocket_close_handler close_handler;
  1468. /* accepted subprotocols for ws/wss requests. */
  1469. struct mg_websocket_subprotocols *subprotocols;
  1470. /* Handler for authorization requests */
  1471. mg_authorization_handler auth_handler;
  1472. /* User supplied argument for the handler function. */
  1473. void *cbdata;
  1474. /* next handler in a linked list */
  1475. struct mg_handler_info *next;
  1476. };
  1477. struct mg_context {
  1478. volatile int stop_flag; /* Should we stop event loop */
  1479. SSL_CTX *ssl_ctx; /* SSL context */
  1480. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1481. struct mg_callbacks callbacks; /* User-defined callback function */
  1482. void *user_data; /* User-defined data */
  1483. int context_type; /* 1 = server context,
  1484. * 2 = ws/wss client context,
  1485. */
  1486. struct socket *listening_sockets;
  1487. struct pollfd *listening_socket_fds;
  1488. unsigned int num_listening_sockets;
  1489. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  1490. #ifdef ALTERNATIVE_QUEUE
  1491. struct socket *client_socks;
  1492. void **client_wait_events;
  1493. #else
  1494. struct socket queue[MGSQLEN]; /* Accepted sockets */
  1495. volatile int sq_head; /* Head of the socket queue */
  1496. volatile int sq_tail; /* Tail of the socket queue */
  1497. pthread_cond_t sq_full; /* Signaled when socket is produced */
  1498. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  1499. #endif
  1500. pthread_t masterthreadid; /* The master thread ID */
  1501. unsigned int
  1502. cfg_worker_threads; /* The number of configured worker threads. */
  1503. pthread_t *workerthreadids; /* The worker thread IDs */
  1504. time_t start_time; /* Server start time, used for authentication */
  1505. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1506. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  1507. unsigned long nonce_count; /* Used nonces, used for authentication */
  1508. char *systemName; /* What operating system is running */
  1509. /* linked list of uri handlers */
  1510. struct mg_handler_info *handlers;
  1511. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1512. /* linked list of shared lua websockets */
  1513. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1514. #endif
  1515. #ifdef USE_TIMERS
  1516. struct ttimers *timers;
  1517. #endif
  1518. };
  1519. struct mg_connection {
  1520. struct mg_request_info request_info;
  1521. struct mg_context *ctx;
  1522. SSL *ssl; /* SSL descriptor */
  1523. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  1524. struct socket client; /* Connected client */
  1525. time_t conn_birth_time; /* Time (wall clock) when connection was
  1526. * established */
  1527. struct timespec req_time; /* Time (since system start) when the request
  1528. * was received */
  1529. int64_t num_bytes_sent; /* Total bytes sent to client */
  1530. int64_t content_len; /* Content-Length header value */
  1531. int64_t consumed_content; /* How many bytes of content have been read */
  1532. int is_chunked; /* Transfer-Encoding is chunked: 0=no, 1=yes:
  1533. * data available, 2: all data read */
  1534. size_t chunk_remainder; /* Unread data from the last chunk */
  1535. char *buf; /* Buffer for received data */
  1536. char *path_info; /* PATH_INFO part of the URL */
  1537. int must_close; /* 1 if connection must be closed */
  1538. int in_error_handler; /* 1 if in handler for user defined error
  1539. * pages */
  1540. int handled_requests; /* Number of requests handled by this connection */
  1541. int buf_size; /* Buffer size */
  1542. int request_len; /* Size of the request + headers in a buffer */
  1543. int data_len; /* Total size of data in a buffer */
  1544. int status_code; /* HTTP reply status code, e.g. 200 */
  1545. int throttle; /* Throttling, bytes/sec. <= 0 means no
  1546. * throttle */
  1547. time_t last_throttle_time; /* Last time throttled data was sent */
  1548. int64_t last_throttle_bytes; /* Bytes sent this second */
  1549. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  1550. * atomic transmissions for websockets */
  1551. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1552. void *lua_websocket_state; /* Lua_State for a websocket connection */
  1553. #endif
  1554. int thread_index; /* Thread index within ctx */
  1555. };
  1556. /* Directory entry */
  1557. struct de {
  1558. struct mg_connection *conn;
  1559. char *file_name;
  1560. struct mg_file_stat file;
  1561. };
  1562. #if defined(USE_WEBSOCKET)
  1563. static int is_websocket_protocol(const struct mg_connection *conn);
  1564. #else
  1565. #define is_websocket_protocol(conn) (0)
  1566. #endif
  1567. #if !defined(NO_THREAD_NAME)
  1568. #if defined(_WIN32) && defined(_MSC_VER)
  1569. /* Set the thread name for debugging purposes in Visual Studio
  1570. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  1571. */
  1572. #pragma pack(push, 8)
  1573. typedef struct tagTHREADNAME_INFO {
  1574. DWORD dwType; /* Must be 0x1000. */
  1575. LPCSTR szName; /* Pointer to name (in user addr space). */
  1576. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  1577. DWORD dwFlags; /* Reserved for future use, must be zero. */
  1578. } THREADNAME_INFO;
  1579. #pragma pack(pop)
  1580. #elif defined(__linux__)
  1581. #include <sys/prctl.h>
  1582. #include <sys/sendfile.h>
  1583. #include <sys/eventfd.h>
  1584. #if defined(ALTERNATIVE_QUEUE)
  1585. static void *
  1586. event_create(void)
  1587. {
  1588. int ret = eventfd(0, EFD_CLOEXEC);
  1589. if (ret == -1) {
  1590. /* Linux uses -1 on error, Windows NULL. */
  1591. /* However, Linux does not return 0 on success either. */
  1592. return 0;
  1593. }
  1594. return (void *)ret;
  1595. }
  1596. static int
  1597. event_wait(void *eventhdl)
  1598. {
  1599. uint64_t u;
  1600. int s = (int)read((int)eventhdl, &u, sizeof(u));
  1601. if (s != sizeof(uint64_t)) {
  1602. /* error */
  1603. return 0;
  1604. }
  1605. (void)u; /* the value is not required */
  1606. return 1;
  1607. }
  1608. static int
  1609. event_signal(void *eventhdl)
  1610. {
  1611. uint64_t u = 1;
  1612. int s = (int)write((int)eventhdl, &u, sizeof(u));
  1613. if (s != sizeof(uint64_t)) {
  1614. /* error */
  1615. return 0;
  1616. }
  1617. return 1;
  1618. }
  1619. static void
  1620. event_destroy(void *eventhdl)
  1621. {
  1622. close((int)eventhdl);
  1623. }
  1624. #endif
  1625. #endif
  1626. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  1627. struct posix_event {
  1628. pthread_mutex_t mutex;
  1629. pthread_cond_t cond;
  1630. };
  1631. static void *
  1632. event_create(void)
  1633. {
  1634. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  1635. if (ret == 0) {
  1636. /* out of memory */
  1637. return 0;
  1638. }
  1639. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  1640. /* pthread mutex not available */
  1641. mg_free(ret);
  1642. return 0;
  1643. }
  1644. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  1645. /* pthread cond not available */
  1646. pthread_mutex_destroy(&(ret->mutex));
  1647. mg_free(ret);
  1648. return 0;
  1649. }
  1650. return (void *)ret;
  1651. }
  1652. static int
  1653. event_wait(void *eventhdl)
  1654. {
  1655. struct posix_event *ev = (struct posix_event *)eventhdl;
  1656. pthread_mutex_lock(&(ev->mutex));
  1657. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  1658. pthread_mutex_unlock(&(ev->mutex));
  1659. return 1;
  1660. }
  1661. static int
  1662. event_signal(void *eventhdl)
  1663. {
  1664. struct posix_event *ev = (struct posix_event *)eventhdl;
  1665. pthread_mutex_lock(&(ev->mutex));
  1666. pthread_cond_signal(&(ev->cond));
  1667. pthread_mutex_unlock(&(ev->mutex));
  1668. return 1;
  1669. }
  1670. static void
  1671. event_destroy(void *eventhdl)
  1672. {
  1673. struct posix_event *ev = (struct posix_event *)eventhdl;
  1674. pthread_cond_destroy(&(ev->cond));
  1675. pthread_mutex_destroy(&(ev->mutex));
  1676. mg_free(ev);
  1677. }
  1678. #endif
  1679. static void
  1680. mg_set_thread_name(const char *name)
  1681. {
  1682. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  1683. mg_snprintf(
  1684. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  1685. #if defined(_WIN32)
  1686. #if defined(_MSC_VER)
  1687. /* Windows and Visual Studio Compiler */
  1688. __try
  1689. {
  1690. THREADNAME_INFO info;
  1691. info.dwType = 0x1000;
  1692. info.szName = threadName;
  1693. info.dwThreadID = ~0U;
  1694. info.dwFlags = 0;
  1695. RaiseException(0x406D1388,
  1696. 0,
  1697. sizeof(info) / sizeof(ULONG_PTR),
  1698. (ULONG_PTR *)&info);
  1699. }
  1700. __except(EXCEPTION_EXECUTE_HANDLER)
  1701. {
  1702. }
  1703. #elif defined(__MINGW32__)
  1704. /* No option known to set thread name for MinGW */
  1705. #endif
  1706. #elif defined(__GLIBC__) \
  1707. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  1708. /* pthread_setname_np first appeared in glibc in version 2.12*/
  1709. (void)pthread_setname_np(pthread_self(), threadName);
  1710. #elif defined(__linux__)
  1711. /* on linux we can use the old prctl function */
  1712. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  1713. #endif
  1714. }
  1715. #else /* !defined(NO_THREAD_NAME) */
  1716. void
  1717. mg_set_thread_name(const char *threadName)
  1718. {
  1719. }
  1720. #endif
  1721. #if defined(MG_LEGACY_INTERFACE)
  1722. const char **
  1723. mg_get_valid_option_names(void)
  1724. {
  1725. /* This function is deprecated. Use mg_get_valid_options instead. */
  1726. static const char *
  1727. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  1728. int i;
  1729. for (i = 0; config_options[i].name != NULL; i++) {
  1730. data[i * 2] = config_options[i].name;
  1731. data[i * 2 + 1] = config_options[i].default_value;
  1732. }
  1733. return data;
  1734. }
  1735. #endif
  1736. const struct mg_option *
  1737. mg_get_valid_options(void)
  1738. {
  1739. return config_options;
  1740. }
  1741. /* Do not open file (used in is_file_in_memory) */
  1742. #define MG_FOPEN_MODE_NONE (0)
  1743. /* Open file for read only access */
  1744. #define MG_FOPEN_MODE_READ (1)
  1745. /* Open file for writing, create and overwrite */
  1746. #define MG_FOPEN_MODE_WRITE (2)
  1747. /* Open file for writing, create and append */
  1748. #define MG_FOPEN_MODE_APPEND (4)
  1749. /* If a file is in memory, set all "stat" members and the membuf pointer of
  1750. * output filep and return 1, otherwise return 0 and don't modify anything. */
  1751. static int
  1752. open_file_in_memory(const struct mg_connection *conn,
  1753. const char *path,
  1754. struct mg_file *filep,
  1755. int mode)
  1756. {
  1757. size_t size = 0;
  1758. const char *buf = NULL;
  1759. if (!conn) {
  1760. return 0;
  1761. }
  1762. if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
  1763. return 0;
  1764. }
  1765. if (conn->ctx->callbacks.open_file) {
  1766. buf = conn->ctx->callbacks.open_file(conn, path, &size);
  1767. if (buf != NULL) {
  1768. if (filep == NULL) {
  1769. /* This is a file in memory, but we cannot store the properties
  1770. * now.
  1771. * Called from "is_file_in_memory" function. */
  1772. return 1;
  1773. }
  1774. /* NOTE: override filep->size only on success. Otherwise, it might
  1775. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  1776. filep->access.membuf = buf;
  1777. filep->access.fp = NULL;
  1778. /* Size was set by the callback */
  1779. filep->stat.size = size;
  1780. /* Assume the data may change during runtime by setting
  1781. * last_modified = now */
  1782. filep->stat.last_modified = time(NULL);
  1783. filep->stat.is_directory = 0;
  1784. filep->stat.is_gzipped = 0;
  1785. }
  1786. }
  1787. return (buf != NULL);
  1788. }
  1789. static int
  1790. is_file_in_memory(const struct mg_connection *conn, const char *path)
  1791. {
  1792. return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
  1793. }
  1794. static int
  1795. is_file_opened(const struct mg_file_access *fileacc)
  1796. {
  1797. if (!fileacc) {
  1798. return 0;
  1799. }
  1800. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  1801. }
  1802. static int mg_stat(const struct mg_connection *conn,
  1803. const char *path,
  1804. struct mg_file_stat *filep);
  1805. /* mg_fopen will open a file either in memory or on the disk.
  1806. * The input parameter path is a string in UTF-8 encoding.
  1807. * The input parameter mode is MG_FOPEN_MODE_*
  1808. * On success, either fp or membuf will be set in the output
  1809. * struct file. All status members will also be set.
  1810. * The function returns 1 on success, 0 on error. */
  1811. static int
  1812. mg_fopen(const struct mg_connection *conn,
  1813. const char *path,
  1814. int mode,
  1815. struct mg_file *filep)
  1816. {
  1817. int found;
  1818. if (!filep) {
  1819. return 0;
  1820. }
  1821. filep->access.fp = NULL;
  1822. filep->access.membuf = NULL;
  1823. if (!is_file_in_memory(conn, path)) {
  1824. /* filep is initialized in mg_stat: all fields with memset to,
  1825. * some fields like size and modification date with values */
  1826. found = mg_stat(conn, path, &(filep->stat));
  1827. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  1828. /* file does not exist and will not be created */
  1829. return 0;
  1830. }
  1831. #ifdef _WIN32
  1832. {
  1833. wchar_t wbuf[PATH_MAX];
  1834. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  1835. switch (mode) {
  1836. case MG_FOPEN_MODE_READ:
  1837. filep->access.fp = _wfopen(wbuf, L"rb");
  1838. break;
  1839. case MG_FOPEN_MODE_WRITE:
  1840. filep->access.fp = _wfopen(wbuf, L"wb");
  1841. break;
  1842. case MG_FOPEN_MODE_APPEND:
  1843. filep->access.fp = _wfopen(wbuf, L"ab");
  1844. break;
  1845. }
  1846. }
  1847. #else
  1848. /* Linux et al already use unicode. No need to convert. */
  1849. switch (mode) {
  1850. case MG_FOPEN_MODE_READ:
  1851. filep->access.fp = fopen(path, "r");
  1852. break;
  1853. case MG_FOPEN_MODE_WRITE:
  1854. filep->access.fp = fopen(path, "w");
  1855. break;
  1856. case MG_FOPEN_MODE_APPEND:
  1857. filep->access.fp = fopen(path, "a");
  1858. break;
  1859. }
  1860. #endif
  1861. if (!found) {
  1862. /* File did not exist before fopen was called.
  1863. * Maybe it has been created now. Get stat info
  1864. * like creation time now. */
  1865. found = mg_stat(conn, path, &(filep->stat));
  1866. (void)found;
  1867. }
  1868. /* file is on disk */
  1869. return (filep->access.fp != NULL);
  1870. } else {
  1871. /* is_file_in_memory returned true */
  1872. if (open_file_in_memory(conn, path, filep, mode)) {
  1873. /* file is in memory */
  1874. return (filep->access.membuf != NULL);
  1875. }
  1876. }
  1877. /* Open failed */
  1878. return 0;
  1879. }
  1880. /* return 0 on success, just like fclose */
  1881. static int
  1882. mg_fclose(struct mg_file_access *fileacc)
  1883. {
  1884. int ret = -1;
  1885. if (fileacc != NULL) {
  1886. if (fileacc->fp != NULL) {
  1887. ret = fclose(fileacc->fp);
  1888. } else if (fileacc->membuf != NULL) {
  1889. ret = 0;
  1890. }
  1891. /* reset all members of fileacc */
  1892. memset(fileacc, 0, sizeof(*fileacc));
  1893. }
  1894. return ret;
  1895. }
  1896. static void
  1897. mg_strlcpy(register char *dst, register const char *src, size_t n)
  1898. {
  1899. for (; *src != '\0' && n > 1; n--) {
  1900. *dst++ = *src++;
  1901. }
  1902. *dst = '\0';
  1903. }
  1904. static int
  1905. lowercase(const char *s)
  1906. {
  1907. return tolower(*(const unsigned char *)s);
  1908. }
  1909. int
  1910. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  1911. {
  1912. int diff = 0;
  1913. if (len > 0) {
  1914. do {
  1915. diff = lowercase(s1++) - lowercase(s2++);
  1916. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  1917. }
  1918. return diff;
  1919. }
  1920. int
  1921. mg_strcasecmp(const char *s1, const char *s2)
  1922. {
  1923. int diff;
  1924. do {
  1925. diff = lowercase(s1++) - lowercase(s2++);
  1926. } while (diff == 0 && s1[-1] != '\0');
  1927. return diff;
  1928. }
  1929. static char *
  1930. mg_strndup(const char *ptr, size_t len)
  1931. {
  1932. char *p;
  1933. if ((p = (char *)mg_malloc(len + 1)) != NULL) {
  1934. mg_strlcpy(p, ptr, len + 1);
  1935. }
  1936. return p;
  1937. }
  1938. static char *
  1939. mg_strdup(const char *str)
  1940. {
  1941. return mg_strndup(str, strlen(str));
  1942. }
  1943. static const char *
  1944. mg_strcasestr(const char *big_str, const char *small_str)
  1945. {
  1946. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  1947. if (big_len >= small_len) {
  1948. for (i = 0; i <= (big_len - small_len); i++) {
  1949. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  1950. return big_str + i;
  1951. }
  1952. }
  1953. }
  1954. return NULL;
  1955. }
  1956. /* Return null terminated string of given maximum length.
  1957. * Report errors if length is exceeded. */
  1958. static void
  1959. mg_vsnprintf(const struct mg_connection *conn,
  1960. int *truncated,
  1961. char *buf,
  1962. size_t buflen,
  1963. const char *fmt,
  1964. va_list ap)
  1965. {
  1966. int n, ok;
  1967. if (buflen == 0) {
  1968. return;
  1969. }
  1970. #ifdef __clang__
  1971. #pragma clang diagnostic push
  1972. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  1973. /* Using fmt as a non-literal is intended here, since it is mostly called
  1974. * indirectly by mg_snprintf */
  1975. #endif
  1976. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  1977. ok = (n >= 0) && ((size_t)n < buflen);
  1978. #ifdef __clang__
  1979. #pragma clang diagnostic pop
  1980. #endif
  1981. if (ok) {
  1982. if (truncated) {
  1983. *truncated = 0;
  1984. }
  1985. } else {
  1986. if (truncated) {
  1987. *truncated = 1;
  1988. }
  1989. mg_cry(conn,
  1990. "truncating vsnprintf buffer: [%.*s]",
  1991. (int)((buflen > 200) ? 200 : (buflen - 1)),
  1992. buf);
  1993. n = (int)buflen - 1;
  1994. }
  1995. buf[n] = '\0';
  1996. }
  1997. static void
  1998. mg_snprintf(const struct mg_connection *conn,
  1999. int *truncated,
  2000. char *buf,
  2001. size_t buflen,
  2002. const char *fmt,
  2003. ...)
  2004. {
  2005. va_list ap;
  2006. va_start(ap, fmt);
  2007. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2008. va_end(ap);
  2009. }
  2010. static int
  2011. get_option_index(const char *name)
  2012. {
  2013. int i;
  2014. for (i = 0; config_options[i].name != NULL; i++) {
  2015. if (strcmp(config_options[i].name, name) == 0) {
  2016. return i;
  2017. }
  2018. }
  2019. return -1;
  2020. }
  2021. const char *
  2022. mg_get_option(const struct mg_context *ctx, const char *name)
  2023. {
  2024. int i;
  2025. if ((i = get_option_index(name)) == -1) {
  2026. return NULL;
  2027. } else if (!ctx || ctx->config[i] == NULL) {
  2028. return "";
  2029. } else {
  2030. return ctx->config[i];
  2031. }
  2032. }
  2033. struct mg_context *
  2034. mg_get_context(const struct mg_connection *conn)
  2035. {
  2036. return (conn == NULL) ? (struct mg_context *)NULL : (conn->ctx);
  2037. }
  2038. void *
  2039. mg_get_user_data(const struct mg_context *ctx)
  2040. {
  2041. return (ctx == NULL) ? NULL : ctx->user_data;
  2042. }
  2043. void
  2044. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  2045. {
  2046. if (conn != NULL) {
  2047. conn->request_info.conn_data = data;
  2048. }
  2049. }
  2050. void *
  2051. mg_get_user_connection_data(const struct mg_connection *conn)
  2052. {
  2053. if (conn != NULL) {
  2054. return conn->request_info.conn_data;
  2055. }
  2056. return NULL;
  2057. }
  2058. size_t
  2059. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  2060. {
  2061. size_t i;
  2062. if (!ctx) {
  2063. return 0;
  2064. }
  2065. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  2066. ssl[i] = ctx->listening_sockets[i].is_ssl;
  2067. ports[i] =
  2068. #if defined(USE_IPV6)
  2069. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2070. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2071. :
  2072. #endif
  2073. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2074. }
  2075. return i;
  2076. }
  2077. int
  2078. mg_get_server_ports(const struct mg_context *ctx,
  2079. int size,
  2080. struct mg_server_ports *ports)
  2081. {
  2082. int i, cnt = 0;
  2083. if (size <= 0) {
  2084. return -1;
  2085. }
  2086. memset(ports, 0, sizeof(*ports) * (size_t)size);
  2087. if (!ctx) {
  2088. return -1;
  2089. }
  2090. if (!ctx->listening_sockets) {
  2091. return -1;
  2092. }
  2093. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  2094. ports[cnt].port =
  2095. #if defined(USE_IPV6)
  2096. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2097. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2098. :
  2099. #endif
  2100. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2101. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  2102. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  2103. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  2104. /* IPv4 */
  2105. ports[cnt].protocol = 1;
  2106. cnt++;
  2107. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  2108. /* IPv6 */
  2109. ports[cnt].protocol = 3;
  2110. cnt++;
  2111. }
  2112. }
  2113. return cnt;
  2114. }
  2115. static void
  2116. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  2117. {
  2118. buf[0] = '\0';
  2119. if (!usa) {
  2120. return;
  2121. }
  2122. if (usa->sa.sa_family == AF_INET) {
  2123. getnameinfo(&usa->sa,
  2124. sizeof(usa->sin),
  2125. buf,
  2126. (unsigned)len,
  2127. NULL,
  2128. 0,
  2129. NI_NUMERICHOST);
  2130. }
  2131. #if defined(USE_IPV6)
  2132. else if (usa->sa.sa_family == AF_INET6) {
  2133. getnameinfo(&usa->sa,
  2134. sizeof(usa->sin6),
  2135. buf,
  2136. (unsigned)len,
  2137. NULL,
  2138. 0,
  2139. NI_NUMERICHOST);
  2140. }
  2141. #endif
  2142. }
  2143. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  2144. * included in all responses other than 100, 101, 5xx. */
  2145. static void
  2146. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  2147. {
  2148. struct tm *tm;
  2149. tm = ((t != NULL) ? gmtime(t) : NULL);
  2150. if (tm != NULL) {
  2151. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  2152. } else {
  2153. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  2154. buf[buf_len - 1] = '\0';
  2155. }
  2156. }
  2157. /* difftime for struct timespec. Return value is in seconds. */
  2158. static double
  2159. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  2160. {
  2161. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  2162. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  2163. }
  2164. /* Print error message to the opened error log stream. */
  2165. void
  2166. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  2167. {
  2168. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  2169. va_list ap;
  2170. struct mg_file fi;
  2171. time_t timestamp;
  2172. va_start(ap, fmt);
  2173. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  2174. va_end(ap);
  2175. buf[sizeof(buf) - 1] = 0;
  2176. if (!conn) {
  2177. puts(buf);
  2178. return;
  2179. }
  2180. /* Do not lock when getting the callback value, here and below.
  2181. * I suppose this is fine, since function cannot disappear in the
  2182. * same way string option can. */
  2183. if ((conn->ctx->callbacks.log_message == NULL)
  2184. || (conn->ctx->callbacks.log_message(conn, buf) == 0)) {
  2185. if (conn->ctx->config[ERROR_LOG_FILE] != NULL) {
  2186. if (mg_fopen(conn,
  2187. conn->ctx->config[ERROR_LOG_FILE],
  2188. MG_FOPEN_MODE_APPEND,
  2189. &fi) == 0) {
  2190. fi.access.fp = NULL;
  2191. }
  2192. } else {
  2193. fi.access.fp = NULL;
  2194. }
  2195. if (fi.access.fp != NULL) {
  2196. flockfile(fi.access.fp);
  2197. timestamp = time(NULL);
  2198. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  2199. fprintf(fi.access.fp,
  2200. "[%010lu] [error] [client %s] ",
  2201. (unsigned long)timestamp,
  2202. src_addr);
  2203. if (conn->request_info.request_method != NULL) {
  2204. fprintf(fi.access.fp,
  2205. "%s %s: ",
  2206. conn->request_info.request_method,
  2207. conn->request_info.request_uri);
  2208. }
  2209. fprintf(fi.access.fp, "%s", buf);
  2210. fputc('\n', fi.access.fp);
  2211. fflush(fi.access.fp);
  2212. funlockfile(fi.access.fp);
  2213. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  2214. * mg_cry here anyway ;-) */
  2215. }
  2216. }
  2217. }
  2218. /* Return fake connection structure. Used for logging, if connection
  2219. * is not applicable at the moment of logging. */
  2220. static struct mg_connection *
  2221. fc(struct mg_context *ctx)
  2222. {
  2223. static struct mg_connection fake_connection;
  2224. fake_connection.ctx = ctx;
  2225. return &fake_connection;
  2226. }
  2227. const char *
  2228. mg_version(void)
  2229. {
  2230. return CIVETWEB_VERSION;
  2231. }
  2232. const struct mg_request_info *
  2233. mg_get_request_info(const struct mg_connection *conn)
  2234. {
  2235. if (!conn) {
  2236. return NULL;
  2237. }
  2238. return &conn->request_info;
  2239. }
  2240. /* Skip the characters until one of the delimiters characters found.
  2241. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  2242. * Advance pointer to buffer to the next word. Return found 0-terminated word.
  2243. * Delimiters can be quoted with quotechar. */
  2244. static char *
  2245. skip_quoted(char **buf,
  2246. const char *delimiters,
  2247. const char *whitespace,
  2248. char quotechar)
  2249. {
  2250. char *p, *begin_word, *end_word, *end_whitespace;
  2251. begin_word = *buf;
  2252. end_word = begin_word + strcspn(begin_word, delimiters);
  2253. /* Check for quotechar */
  2254. if (end_word > begin_word) {
  2255. p = end_word - 1;
  2256. while (*p == quotechar) {
  2257. /* While the delimiter is quoted, look for the next delimiter. */
  2258. /* This happens, e.g., in calls from parse_auth_header,
  2259. * if the user name contains a " character. */
  2260. /* If there is anything beyond end_word, copy it. */
  2261. if (*end_word != '\0') {
  2262. size_t end_off = strcspn(end_word + 1, delimiters);
  2263. memmove(p, end_word, end_off + 1);
  2264. p += end_off; /* p must correspond to end_word - 1 */
  2265. end_word += end_off + 1;
  2266. } else {
  2267. *p = '\0';
  2268. break;
  2269. }
  2270. }
  2271. for (p++; p < end_word; p++) {
  2272. *p = '\0';
  2273. }
  2274. }
  2275. if (*end_word == '\0') {
  2276. *buf = end_word;
  2277. } else {
  2278. #if defined(__GNUC__) || defined(__MINGW32__)
  2279. /* Disable spurious conversion warning for GCC */
  2280. #pragma GCC diagnostic push
  2281. #pragma GCC diagnostic ignored "-Wsign-conversion"
  2282. #endif
  2283. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  2284. #if defined(__GNUC__) || defined(__MINGW32__)
  2285. #pragma GCC diagnostic pop
  2286. #endif
  2287. for (p = end_word; p < end_whitespace; p++) {
  2288. *p = '\0';
  2289. }
  2290. *buf = end_whitespace;
  2291. }
  2292. return begin_word;
  2293. }
  2294. /* Simplified version of skip_quoted without quote char
  2295. * and whitespace == delimiters */
  2296. static char *
  2297. skip(char **buf, const char *delimiters)
  2298. {
  2299. return skip_quoted(buf, delimiters, delimiters, 0);
  2300. }
  2301. /* Return HTTP header value, or NULL if not found. */
  2302. static const char *
  2303. get_header(const struct mg_request_info *ri, const char *name)
  2304. {
  2305. int i;
  2306. if (ri) {
  2307. for (i = 0; i < ri->num_headers; i++) {
  2308. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  2309. return ri->http_headers[i].value;
  2310. }
  2311. }
  2312. }
  2313. return NULL;
  2314. }
  2315. const char *
  2316. mg_get_header(const struct mg_connection *conn, const char *name)
  2317. {
  2318. if (!conn) {
  2319. return NULL;
  2320. }
  2321. return get_header(&conn->request_info, name);
  2322. }
  2323. /* A helper function for traversing a comma separated list of values.
  2324. * It returns a list pointer shifted to the next value, or NULL if the end
  2325. * of the list found.
  2326. * Value is stored in val vector. If value has form "x=y", then eq_val
  2327. * vector is initialized to point to the "y" part, and val vector length
  2328. * is adjusted to point only to "x". */
  2329. static const char *
  2330. next_option(const char *list, struct vec *val, struct vec *eq_val)
  2331. {
  2332. int end;
  2333. reparse:
  2334. if (val == NULL || list == NULL || *list == '\0') {
  2335. /* End of the list */
  2336. list = NULL;
  2337. } else {
  2338. /* Skip over leading LWS */
  2339. while (*list == ' ' || *list == '\t')
  2340. list++;
  2341. val->ptr = list;
  2342. if ((list = strchr(val->ptr, ',')) != NULL) {
  2343. /* Comma found. Store length and shift the list ptr */
  2344. val->len = ((size_t)(list - val->ptr));
  2345. list++;
  2346. } else {
  2347. /* This value is the last one */
  2348. list = val->ptr + strlen(val->ptr);
  2349. val->len = ((size_t)(list - val->ptr));
  2350. }
  2351. /* Adjust length for trailing LWS */
  2352. end = (int)val->len - 1;
  2353. while (end >= 0 && (val->ptr[end] == ' ' || val->ptr[end] == '\t'))
  2354. end--;
  2355. val->len = (size_t)(end + 1);
  2356. if (val->len == 0) {
  2357. /* Ignore any empty entries. */
  2358. goto reparse;
  2359. }
  2360. if (eq_val != NULL) {
  2361. /* Value has form "x=y", adjust pointers and lengths
  2362. * so that val points to "x", and eq_val points to "y". */
  2363. eq_val->len = 0;
  2364. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  2365. if (eq_val->ptr != NULL) {
  2366. eq_val->ptr++; /* Skip over '=' character */
  2367. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  2368. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  2369. }
  2370. }
  2371. }
  2372. return list;
  2373. }
  2374. /* A helper function for checking if a comma separated list of values contains
  2375. * the given option (case insensitvely).
  2376. * 'header' can be NULL, in which case false is returned. */
  2377. static int
  2378. header_has_option(const char *header, const char *option)
  2379. {
  2380. struct vec opt_vec;
  2381. struct vec eq_vec;
  2382. assert(option != NULL);
  2383. assert(option[0] != '\0');
  2384. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  2385. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  2386. return 1;
  2387. }
  2388. return 0;
  2389. }
  2390. /* Perform case-insensitive match of string against pattern */
  2391. static int
  2392. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  2393. {
  2394. const char *or_str;
  2395. size_t i;
  2396. int j, len, res;
  2397. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  2398. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  2399. return (res > 0) ? res : match_prefix(or_str + 1,
  2400. (size_t)((pattern + pattern_len)
  2401. - (or_str + 1)),
  2402. str);
  2403. }
  2404. for (i = 0, j = 0; i < pattern_len; i++, j++) {
  2405. if (pattern[i] == '?' && str[j] != '\0') {
  2406. continue;
  2407. } else if (pattern[i] == '$') {
  2408. return (str[j] == '\0') ? j : -1;
  2409. } else if (pattern[i] == '*') {
  2410. i++;
  2411. if (pattern[i] == '*') {
  2412. i++;
  2413. len = (int)strlen(str + j);
  2414. } else {
  2415. len = (int)strcspn(str + j, "/");
  2416. }
  2417. if (i == pattern_len) {
  2418. return j + len;
  2419. }
  2420. do {
  2421. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  2422. } while (res == -1 && len-- > 0);
  2423. return (res == -1) ? -1 : j + res + len;
  2424. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  2425. return -1;
  2426. }
  2427. }
  2428. return j;
  2429. }
  2430. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  2431. * This function must tolerate situations when connection info is not
  2432. * set up, for example if request parsing failed. */
  2433. static int
  2434. should_keep_alive(const struct mg_connection *conn)
  2435. {
  2436. if (conn != NULL) {
  2437. const char *http_version = conn->request_info.http_version;
  2438. const char *header = mg_get_header(conn, "Connection");
  2439. if (conn->must_close || conn->status_code == 401
  2440. || mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0
  2441. || (header != NULL && !header_has_option(header, "keep-alive"))
  2442. || (header == NULL && http_version
  2443. && 0 != strcmp(http_version, "1.1"))) {
  2444. return 0;
  2445. }
  2446. return 1;
  2447. }
  2448. return 0;
  2449. }
  2450. static int
  2451. should_decode_url(const struct mg_connection *conn)
  2452. {
  2453. if (!conn || !conn->ctx) {
  2454. return 0;
  2455. }
  2456. return (mg_strcasecmp(conn->ctx->config[DECODE_URL], "yes") == 0);
  2457. }
  2458. static const char *
  2459. suggest_connection_header(const struct mg_connection *conn)
  2460. {
  2461. return should_keep_alive(conn) ? "keep-alive" : "close";
  2462. }
  2463. static int
  2464. send_no_cache_header(struct mg_connection *conn)
  2465. {
  2466. /* Send all current and obsolete cache opt-out directives. */
  2467. return mg_printf(conn,
  2468. "Cache-Control: no-cache, no-store, "
  2469. "must-revalidate, private, max-age=0\r\n"
  2470. "Pragma: no-cache\r\n"
  2471. "Expires: 0\r\n");
  2472. }
  2473. static int
  2474. send_static_cache_header(struct mg_connection *conn)
  2475. {
  2476. #if !defined(NO_CACHING)
  2477. /* Read the server config to check how long a file may be cached.
  2478. * The configuration is in seconds. */
  2479. int max_age = atoi(conn->ctx->config[STATIC_FILE_MAX_AGE]);
  2480. if (max_age <= 0) {
  2481. /* 0 means "do not cache". All values <0 are reserved
  2482. * and may be used differently in the future. */
  2483. /* If a file should not be cached, do not only send
  2484. * max-age=0, but also pragmas and Expires headers. */
  2485. return send_no_cache_header(conn);
  2486. }
  2487. /* Use "Cache-Control: max-age" instead of "Expires" header.
  2488. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  2489. /* See also https://www.mnot.net/cache_docs/ */
  2490. /* According to RFC 2616, Section 14.21, caching times should not exceed
  2491. * one year. A year with 365 days corresponds to 31536000 seconds, a leap
  2492. * year to 31622400 seconds. For the moment, we just send whatever has
  2493. * been configured, still the behavior for >1 year should be considered
  2494. * as undefined. */
  2495. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  2496. #else /* NO_CACHING */
  2497. return send_no_cache_header(conn);
  2498. #endif /* !NO_CACHING */
  2499. }
  2500. static void handle_file_based_request(struct mg_connection *conn,
  2501. const char *path,
  2502. struct mg_file *filep);
  2503. const char *
  2504. mg_get_response_code_text(struct mg_connection *conn, int response_code)
  2505. {
  2506. /* See IANA HTTP status code assignment:
  2507. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  2508. */
  2509. switch (response_code) {
  2510. /* RFC2616 Section 10.1 - Informational 1xx */
  2511. case 100:
  2512. return "Continue"; /* RFC2616 Section 10.1.1 */
  2513. case 101:
  2514. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  2515. case 102:
  2516. return "Processing"; /* RFC2518 Section 10.1 */
  2517. /* RFC2616 Section 10.2 - Successful 2xx */
  2518. case 200:
  2519. return "OK"; /* RFC2616 Section 10.2.1 */
  2520. case 201:
  2521. return "Created"; /* RFC2616 Section 10.2.2 */
  2522. case 202:
  2523. return "Accepted"; /* RFC2616 Section 10.2.3 */
  2524. case 203:
  2525. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  2526. case 204:
  2527. return "No Content"; /* RFC2616 Section 10.2.5 */
  2528. case 205:
  2529. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  2530. case 206:
  2531. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  2532. case 207:
  2533. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1 */
  2534. case 208:
  2535. return "Already Reported"; /* RFC5842 Section 7.1 */
  2536. case 226:
  2537. return "IM used"; /* RFC3229 Section 10.4.1 */
  2538. /* RFC2616 Section 10.3 - Redirection 3xx */
  2539. case 300:
  2540. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  2541. case 301:
  2542. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  2543. case 302:
  2544. return "Found"; /* RFC2616 Section 10.3.3 */
  2545. case 303:
  2546. return "See Other"; /* RFC2616 Section 10.3.4 */
  2547. case 304:
  2548. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  2549. case 305:
  2550. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  2551. case 307:
  2552. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  2553. case 308:
  2554. return "Permanent Redirect"; /* RFC7238 Section 3 */
  2555. /* RFC2616 Section 10.4 - Client Error 4xx */
  2556. case 400:
  2557. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  2558. case 401:
  2559. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  2560. case 402:
  2561. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  2562. case 403:
  2563. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  2564. case 404:
  2565. return "Not Found"; /* RFC2616 Section 10.4.5 */
  2566. case 405:
  2567. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  2568. case 406:
  2569. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  2570. case 407:
  2571. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  2572. case 408:
  2573. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  2574. case 409:
  2575. return "Conflict"; /* RFC2616 Section 10.4.10 */
  2576. case 410:
  2577. return "Gone"; /* RFC2616 Section 10.4.11 */
  2578. case 411:
  2579. return "Length Required"; /* RFC2616 Section 10.4.12 */
  2580. case 412:
  2581. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  2582. case 413:
  2583. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  2584. case 414:
  2585. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  2586. case 415:
  2587. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  2588. case 416:
  2589. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17 */
  2590. case 417:
  2591. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  2592. case 421:
  2593. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  2594. case 422:
  2595. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  2596. * Section 11.2 */
  2597. case 423:
  2598. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  2599. case 424:
  2600. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  2601. * Section 11.4 */
  2602. case 426:
  2603. return "Upgrade Required"; /* RFC 2817 Section 4 */
  2604. case 428:
  2605. return "Precondition Required"; /* RFC 6585, Section 3 */
  2606. case 429:
  2607. return "Too Many Requests"; /* RFC 6585, Section 4 */
  2608. case 431:
  2609. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  2610. case 451:
  2611. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  2612. * Section 3 */
  2613. /* RFC2616 Section 10.5 - Server Error 5xx */
  2614. case 500:
  2615. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  2616. case 501:
  2617. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  2618. case 502:
  2619. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  2620. case 503:
  2621. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  2622. case 504:
  2623. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  2624. case 505:
  2625. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  2626. case 506:
  2627. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  2628. case 507:
  2629. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  2630. * Section 11.5 */
  2631. case 508:
  2632. return "Loop Detected"; /* RFC5842 Section 7.1 */
  2633. case 510:
  2634. return "Not Extended"; /* RFC 2774, Section 7 */
  2635. case 511:
  2636. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  2637. /* Other status codes, not shown in the IANA HTTP status code assignment.
  2638. * E.g., "de facto" standards due to common use, ... */
  2639. case 418:
  2640. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  2641. case 419:
  2642. return "Authentication Timeout"; /* common use */
  2643. case 420:
  2644. return "Enhance Your Calm"; /* common use */
  2645. case 440:
  2646. return "Login Timeout"; /* common use */
  2647. case 509:
  2648. return "Bandwidth Limit Exceeded"; /* common use */
  2649. default:
  2650. /* This error code is unknown. This should not happen. */
  2651. if (conn) {
  2652. mg_cry(conn, "Unknown HTTP response code: %u", response_code);
  2653. }
  2654. /* Return at least a category according to RFC 2616 Section 10. */
  2655. if (response_code >= 100 && response_code < 200) {
  2656. /* Unknown informational status code */
  2657. return "Information";
  2658. }
  2659. if (response_code >= 200 && response_code < 300) {
  2660. /* Unknown success code */
  2661. return "Success";
  2662. }
  2663. if (response_code >= 300 && response_code < 400) {
  2664. /* Unknown redirection code */
  2665. return "Redirection";
  2666. }
  2667. if (response_code >= 400 && response_code < 500) {
  2668. /* Unknown request error code */
  2669. return "Client Error";
  2670. }
  2671. if (response_code >= 500 && response_code < 600) {
  2672. /* Unknown server error code */
  2673. return "Server Error";
  2674. }
  2675. /* Response code not even within reasonable range */
  2676. return "";
  2677. }
  2678. }
  2679. static void send_http_error(struct mg_connection *,
  2680. int,
  2681. PRINTF_FORMAT_STRING(const char *fmt),
  2682. ...) PRINTF_ARGS(3, 4);
  2683. static void
  2684. send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  2685. {
  2686. char buf[MG_BUF_LEN];
  2687. va_list ap;
  2688. int len, i, page_handler_found, scope, truncated, has_body;
  2689. char date[64];
  2690. time_t curtime = time(NULL);
  2691. const char *error_handler = NULL;
  2692. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  2693. const char *error_page_file_ext, *tstr;
  2694. const char *status_text = mg_get_response_code_text(conn, status);
  2695. if (conn == NULL) {
  2696. return;
  2697. }
  2698. conn->status_code = status;
  2699. if (conn->in_error_handler || conn->ctx->callbacks.http_error == NULL
  2700. || conn->ctx->callbacks.http_error(conn, status)) {
  2701. if (!conn->in_error_handler) {
  2702. /* Send user defined error pages, if defined */
  2703. error_handler = conn->ctx->config[ERROR_PAGES];
  2704. error_page_file_ext = conn->ctx->config[INDEX_FILES];
  2705. page_handler_found = 0;
  2706. if (error_handler != NULL) {
  2707. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  2708. switch (scope) {
  2709. case 1: /* Handler for specific error, e.g. 404 error */
  2710. mg_snprintf(conn,
  2711. &truncated,
  2712. buf,
  2713. sizeof(buf) - 32,
  2714. "%serror%03u.",
  2715. error_handler,
  2716. status);
  2717. break;
  2718. case 2: /* Handler for error group, e.g., 5xx error handler
  2719. * for all server errors (500-599) */
  2720. mg_snprintf(conn,
  2721. &truncated,
  2722. buf,
  2723. sizeof(buf) - 32,
  2724. "%serror%01uxx.",
  2725. error_handler,
  2726. status / 100);
  2727. break;
  2728. default: /* Handler for all errors */
  2729. mg_snprintf(conn,
  2730. &truncated,
  2731. buf,
  2732. sizeof(buf) - 32,
  2733. "%serror.",
  2734. error_handler);
  2735. break;
  2736. }
  2737. /* String truncation in buf may only occur if error_handler
  2738. * is too long. This string is from the config, not from a
  2739. * client. */
  2740. (void)truncated;
  2741. len = (int)strlen(buf);
  2742. tstr = strchr(error_page_file_ext, '.');
  2743. while (tstr) {
  2744. for (i = 1; i < 32 && tstr[i] != 0 && tstr[i] != ',';
  2745. i++)
  2746. buf[len + i - 1] = tstr[i];
  2747. buf[len + i - 1] = 0;
  2748. if (mg_stat(conn, buf, &error_page_file.stat)) {
  2749. page_handler_found = 1;
  2750. break;
  2751. }
  2752. tstr = strchr(tstr + i, '.');
  2753. }
  2754. }
  2755. }
  2756. if (page_handler_found) {
  2757. conn->in_error_handler = 1;
  2758. handle_file_based_request(conn, buf, &error_page_file);
  2759. conn->in_error_handler = 0;
  2760. return;
  2761. }
  2762. }
  2763. /* No custom error page. Send default error page. */
  2764. gmt_time_string(date, sizeof(date), &curtime);
  2765. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  2766. has_body = (status > 199 && status != 204 && status != 304);
  2767. conn->must_close = 1;
  2768. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  2769. send_no_cache_header(conn);
  2770. if (has_body) {
  2771. mg_printf(conn,
  2772. "%s",
  2773. "Content-Type: text/plain; charset=utf-8\r\n");
  2774. }
  2775. mg_printf(conn,
  2776. "Date: %s\r\n"
  2777. "Connection: close\r\n\r\n",
  2778. date);
  2779. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  2780. if (has_body) {
  2781. mg_printf(conn, "Error %d: %s\n", status, status_text);
  2782. if (fmt != NULL) {
  2783. va_start(ap, fmt);
  2784. mg_vsnprintf(conn, NULL, buf, sizeof(buf), fmt, ap);
  2785. va_end(ap);
  2786. mg_write(conn, buf, strlen(buf));
  2787. DEBUG_TRACE("Error %i - [%s]", status, buf);
  2788. }
  2789. } else {
  2790. /* No body allowed. Close the connection. */
  2791. DEBUG_TRACE("Error %i", status);
  2792. }
  2793. }
  2794. }
  2795. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  2796. /* Create substitutes for POSIX functions in Win32. */
  2797. #if defined(__MINGW32__)
  2798. /* Show no warning in case system functions are not used. */
  2799. #pragma GCC diagnostic push
  2800. #pragma GCC diagnostic ignored "-Wunused-function"
  2801. #endif
  2802. static int
  2803. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  2804. {
  2805. (void)unused;
  2806. *mutex = CreateMutex(NULL, FALSE, NULL);
  2807. return (*mutex == NULL) ? -1 : 0;
  2808. }
  2809. static int
  2810. pthread_mutex_destroy(pthread_mutex_t *mutex)
  2811. {
  2812. return (CloseHandle(*mutex) == 0) ? -1 : 0;
  2813. }
  2814. static int
  2815. pthread_mutex_lock(pthread_mutex_t *mutex)
  2816. {
  2817. return (WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0) ? 0 : -1;
  2818. }
  2819. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  2820. static int
  2821. pthread_mutex_trylock(pthread_mutex_t *mutex)
  2822. {
  2823. switch (WaitForSingleObject(*mutex, 0)) {
  2824. case WAIT_OBJECT_0:
  2825. return 0;
  2826. case WAIT_TIMEOUT:
  2827. return -2; /* EBUSY */
  2828. }
  2829. return -1;
  2830. }
  2831. #endif
  2832. static int
  2833. pthread_mutex_unlock(pthread_mutex_t *mutex)
  2834. {
  2835. return (ReleaseMutex(*mutex) == 0) ? -1 : 0;
  2836. }
  2837. static int
  2838. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  2839. {
  2840. (void)unused;
  2841. InitializeCriticalSection(&cv->threadIdSec);
  2842. cv->waiting_thread = NULL;
  2843. return 0;
  2844. }
  2845. static int
  2846. pthread_cond_timedwait(pthread_cond_t *cv,
  2847. pthread_mutex_t *mutex,
  2848. const struct timespec *abstime)
  2849. {
  2850. struct mg_workerTLS **ptls,
  2851. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2852. int ok;
  2853. struct timespec tsnow;
  2854. int64_t nsnow, nswaitabs, nswaitrel;
  2855. DWORD mswaitrel;
  2856. EnterCriticalSection(&cv->threadIdSec);
  2857. /* Add this thread to cv's waiting list */
  2858. ptls = &cv->waiting_thread;
  2859. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  2860. ;
  2861. tls->next_waiting_thread = NULL;
  2862. *ptls = tls;
  2863. LeaveCriticalSection(&cv->threadIdSec);
  2864. if (abstime) {
  2865. clock_gettime(CLOCK_REALTIME, &tsnow);
  2866. nsnow = (((int64_t)tsnow.tv_sec) * 1000000000) + tsnow.tv_nsec;
  2867. nswaitabs =
  2868. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  2869. nswaitrel = nswaitabs - nsnow;
  2870. if (nswaitrel < 0) {
  2871. nswaitrel = 0;
  2872. }
  2873. mswaitrel = (DWORD)(nswaitrel / 1000000);
  2874. } else {
  2875. mswaitrel = INFINITE;
  2876. }
  2877. pthread_mutex_unlock(mutex);
  2878. ok = (WAIT_OBJECT_0
  2879. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  2880. if (!ok) {
  2881. ok = 1;
  2882. EnterCriticalSection(&cv->threadIdSec);
  2883. ptls = &cv->waiting_thread;
  2884. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  2885. if (*ptls == tls) {
  2886. *ptls = tls->next_waiting_thread;
  2887. ok = 0;
  2888. break;
  2889. }
  2890. }
  2891. LeaveCriticalSection(&cv->threadIdSec);
  2892. if (ok) {
  2893. WaitForSingleObject(tls->pthread_cond_helper_mutex, INFINITE);
  2894. }
  2895. }
  2896. /* This thread has been removed from cv's waiting list */
  2897. pthread_mutex_lock(mutex);
  2898. return ok ? 0 : -1;
  2899. }
  2900. static int
  2901. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  2902. {
  2903. return pthread_cond_timedwait(cv, mutex, NULL);
  2904. }
  2905. static int
  2906. pthread_cond_signal(pthread_cond_t *cv)
  2907. {
  2908. HANDLE wkup = NULL;
  2909. BOOL ok = FALSE;
  2910. EnterCriticalSection(&cv->threadIdSec);
  2911. if (cv->waiting_thread) {
  2912. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  2913. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  2914. ok = SetEvent(wkup);
  2915. assert(ok);
  2916. }
  2917. LeaveCriticalSection(&cv->threadIdSec);
  2918. return ok ? 0 : 1;
  2919. }
  2920. static int
  2921. pthread_cond_broadcast(pthread_cond_t *cv)
  2922. {
  2923. EnterCriticalSection(&cv->threadIdSec);
  2924. while (cv->waiting_thread) {
  2925. pthread_cond_signal(cv);
  2926. }
  2927. LeaveCriticalSection(&cv->threadIdSec);
  2928. return 0;
  2929. }
  2930. static int
  2931. pthread_cond_destroy(pthread_cond_t *cv)
  2932. {
  2933. EnterCriticalSection(&cv->threadIdSec);
  2934. assert(cv->waiting_thread == NULL);
  2935. LeaveCriticalSection(&cv->threadIdSec);
  2936. DeleteCriticalSection(&cv->threadIdSec);
  2937. return 0;
  2938. }
  2939. #ifdef ALTERNATIVE_QUEUE
  2940. static void *
  2941. event_create(void)
  2942. {
  2943. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  2944. }
  2945. static int
  2946. event_wait(void *eventhdl)
  2947. {
  2948. int res = WaitForSingleObject((HANDLE)eventhdl, INFINITE);
  2949. return (res == WAIT_OBJECT_0);
  2950. }
  2951. static int
  2952. event_signal(void *eventhdl)
  2953. {
  2954. return (int)SetEvent((HANDLE)eventhdl);
  2955. }
  2956. static void
  2957. event_destroy(void *eventhdl)
  2958. {
  2959. CloseHandle((HANDLE)eventhdl);
  2960. }
  2961. #endif
  2962. #if defined(__MINGW32__)
  2963. /* Enable unused function warning again */
  2964. #pragma GCC diagnostic pop
  2965. #endif
  2966. /* For Windows, change all slashes to backslashes in path names. */
  2967. static void
  2968. change_slashes_to_backslashes(char *path)
  2969. {
  2970. int i;
  2971. for (i = 0; path[i] != '\0'; i++) {
  2972. if (path[i] == '/') {
  2973. path[i] = '\\';
  2974. }
  2975. /* remove double backslash (check i > 0 to preserve UNC paths,
  2976. * like \\server\file.txt) */
  2977. if ((path[i] == '\\') && (i > 0)) {
  2978. while (path[i + 1] == '\\' || path[i + 1] == '/') {
  2979. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  2980. }
  2981. }
  2982. }
  2983. }
  2984. static int
  2985. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  2986. {
  2987. int diff;
  2988. do {
  2989. diff = tolower(*s1) - tolower(*s2);
  2990. s1++;
  2991. s2++;
  2992. } while (diff == 0 && s1[-1] != '\0');
  2993. return diff;
  2994. }
  2995. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  2996. * wbuf and wbuf_len is a target buffer and its length. */
  2997. static void
  2998. path_to_unicode(const struct mg_connection *conn,
  2999. const char *path,
  3000. wchar_t *wbuf,
  3001. size_t wbuf_len)
  3002. {
  3003. char buf[PATH_MAX], buf2[PATH_MAX];
  3004. wchar_t wbuf2[MAX_PATH + 1];
  3005. DWORD long_len, err;
  3006. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  3007. mg_strlcpy(buf, path, sizeof(buf));
  3008. change_slashes_to_backslashes(buf);
  3009. /* Convert to Unicode and back. If doubly-converted string does not
  3010. * match the original, something is fishy, reject. */
  3011. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  3012. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  3013. WideCharToMultiByte(
  3014. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  3015. if (strcmp(buf, buf2) != 0) {
  3016. wbuf[0] = L'\0';
  3017. }
  3018. /* Windows file systems are not case sensitive, but you can still use
  3019. * uppercase and lowercase letters (on all modern file systems).
  3020. * The server can check if the URI uses the same upper/lowercase
  3021. * letters an the file system, effectively making Windows servers
  3022. * case sensitive (like Linux servers are). It is still not possible
  3023. * to use two files with the same name in different cases on Windows
  3024. * (like /a and /A) - this would be possible in Linux.
  3025. * As a default, Windows is not case sensitive, but the case sensitive
  3026. * file name check can be activated by an additional configuration. */
  3027. if (conn) {
  3028. if (conn->ctx->config[CASE_SENSITIVE_FILES]
  3029. && !mg_strcasecmp(conn->ctx->config[CASE_SENSITIVE_FILES], "yes")) {
  3030. /* Use case sensitive compare function */
  3031. fcompare = wcscmp;
  3032. }
  3033. }
  3034. (void)conn; /* conn is currently unused */
  3035. #if !defined(_WIN32_WCE)
  3036. /* Only accept a full file path, not a Windows short (8.3) path. */
  3037. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  3038. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  3039. if (long_len == 0) {
  3040. err = GetLastError();
  3041. if (err == ERROR_FILE_NOT_FOUND) {
  3042. /* File does not exist. This is not always a problem here. */
  3043. return;
  3044. }
  3045. }
  3046. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  3047. /* Short name is used. */
  3048. wbuf[0] = L'\0';
  3049. }
  3050. #else
  3051. (void)long_len;
  3052. (void)wbuf2;
  3053. (void)err;
  3054. if (strchr(path, '~')) {
  3055. wbuf[0] = L'\0';
  3056. }
  3057. #endif
  3058. }
  3059. /* Windows happily opens files with some garbage at the end of file name.
  3060. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  3061. * "a.cgi", despite one would expect an error back.
  3062. * This function returns non-0 if path ends with some garbage. */
  3063. static int
  3064. path_cannot_disclose_cgi(const char *path)
  3065. {
  3066. static const char *allowed_last_characters = "_-";
  3067. int last = path[strlen(path) - 1];
  3068. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  3069. }
  3070. static int
  3071. mg_stat(const struct mg_connection *conn,
  3072. const char *path,
  3073. struct mg_file_stat *filep)
  3074. {
  3075. wchar_t wbuf[PATH_MAX];
  3076. WIN32_FILE_ATTRIBUTE_DATA info;
  3077. time_t creation_time;
  3078. if (!filep) {
  3079. return 0;
  3080. }
  3081. memset(filep, 0, sizeof(*filep));
  3082. if (conn && is_file_in_memory(conn, path)) {
  3083. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  3084. * memset */
  3085. filep->last_modified = time(NULL); /* xxxxxxxx */
  3086. /* last_modified = now ... assumes the file may change during runtime,
  3087. * so every mg_fopen call may return different data */
  3088. /* last_modified = conn->ctx.start_time;
  3089. * May be used it the data does not change during runtime. This allows
  3090. * browser caching. Since we do not know, we have to assume the file
  3091. * in memory may change. */
  3092. return 1;
  3093. }
  3094. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3095. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  3096. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  3097. filep->last_modified =
  3098. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  3099. info.ftLastWriteTime.dwHighDateTime);
  3100. /* On Windows, the file creation time can be higher than the
  3101. * modification time, e.g. when a file is copied.
  3102. * Since the Last-Modified timestamp is used for caching
  3103. * it should be based on the most recent timestamp. */
  3104. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  3105. info.ftCreationTime.dwHighDateTime);
  3106. if (creation_time > filep->last_modified) {
  3107. filep->last_modified = creation_time;
  3108. }
  3109. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  3110. /* If file name is fishy, reset the file structure and return
  3111. * error.
  3112. * Note it is important to reset, not just return the error, cause
  3113. * functions like is_file_opened() check the struct. */
  3114. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  3115. memset(filep, 0, sizeof(*filep));
  3116. return 0;
  3117. }
  3118. return 1;
  3119. }
  3120. return 0;
  3121. }
  3122. static int
  3123. mg_remove(const struct mg_connection *conn, const char *path)
  3124. {
  3125. wchar_t wbuf[PATH_MAX];
  3126. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3127. return DeleteFileW(wbuf) ? 0 : -1;
  3128. }
  3129. static int
  3130. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  3131. {
  3132. wchar_t wbuf[PATH_MAX];
  3133. (void)mode;
  3134. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3135. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  3136. }
  3137. /* Create substitutes for POSIX functions in Win32. */
  3138. #if defined(__MINGW32__)
  3139. /* Show no warning in case system functions are not used. */
  3140. #pragma GCC diagnostic push
  3141. #pragma GCC diagnostic ignored "-Wunused-function"
  3142. #endif
  3143. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  3144. static DIR *
  3145. mg_opendir(const struct mg_connection *conn, const char *name)
  3146. {
  3147. DIR *dir = NULL;
  3148. wchar_t wpath[PATH_MAX];
  3149. DWORD attrs;
  3150. if (name == NULL) {
  3151. SetLastError(ERROR_BAD_ARGUMENTS);
  3152. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  3153. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  3154. } else {
  3155. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  3156. attrs = GetFileAttributesW(wpath);
  3157. if (attrs != 0xFFFFFFFF && ((attrs & FILE_ATTRIBUTE_DIRECTORY)
  3158. == FILE_ATTRIBUTE_DIRECTORY)) {
  3159. (void)wcscat(wpath, L"\\*");
  3160. dir->handle = FindFirstFileW(wpath, &dir->info);
  3161. dir->result.d_name[0] = '\0';
  3162. } else {
  3163. mg_free(dir);
  3164. dir = NULL;
  3165. }
  3166. }
  3167. return dir;
  3168. }
  3169. static int
  3170. mg_closedir(DIR *dir)
  3171. {
  3172. int result = 0;
  3173. if (dir != NULL) {
  3174. if (dir->handle != INVALID_HANDLE_VALUE)
  3175. result = FindClose(dir->handle) ? 0 : -1;
  3176. mg_free(dir);
  3177. } else {
  3178. result = -1;
  3179. SetLastError(ERROR_BAD_ARGUMENTS);
  3180. }
  3181. return result;
  3182. }
  3183. static struct dirent *
  3184. mg_readdir(DIR *dir)
  3185. {
  3186. struct dirent *result = 0;
  3187. if (dir) {
  3188. if (dir->handle != INVALID_HANDLE_VALUE) {
  3189. result = &dir->result;
  3190. (void)WideCharToMultiByte(CP_UTF8,
  3191. 0,
  3192. dir->info.cFileName,
  3193. -1,
  3194. result->d_name,
  3195. sizeof(result->d_name),
  3196. NULL,
  3197. NULL);
  3198. if (!FindNextFileW(dir->handle, &dir->info)) {
  3199. (void)FindClose(dir->handle);
  3200. dir->handle = INVALID_HANDLE_VALUE;
  3201. }
  3202. } else {
  3203. SetLastError(ERROR_FILE_NOT_FOUND);
  3204. }
  3205. } else {
  3206. SetLastError(ERROR_BAD_ARGUMENTS);
  3207. }
  3208. return result;
  3209. }
  3210. #ifndef HAVE_POLL
  3211. static int
  3212. poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  3213. {
  3214. struct timeval tv;
  3215. fd_set set;
  3216. unsigned int i;
  3217. int result;
  3218. SOCKET maxfd = 0;
  3219. memset(&tv, 0, sizeof(tv));
  3220. tv.tv_sec = milliseconds / 1000;
  3221. tv.tv_usec = (milliseconds % 1000) * 1000;
  3222. FD_ZERO(&set);
  3223. for (i = 0; i < n; i++) {
  3224. FD_SET((SOCKET)pfd[i].fd, &set);
  3225. pfd[i].revents = 0;
  3226. if (pfd[i].fd > maxfd) {
  3227. maxfd = pfd[i].fd;
  3228. }
  3229. }
  3230. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  3231. for (i = 0; i < n; i++) {
  3232. if (FD_ISSET(pfd[i].fd, &set)) {
  3233. pfd[i].revents = POLLIN;
  3234. }
  3235. }
  3236. }
  3237. /* We should subtract the time used in select from remaining
  3238. * "milliseconds", in particular if called from mg_poll with a
  3239. * timeout quantum.
  3240. * Unfortunately, the remaining time is not stored in "tv" in all
  3241. * implementations, so the result in "tv" must be considered undefined.
  3242. * See http://man7.org/linux/man-pages/man2/select.2.html */
  3243. return result;
  3244. }
  3245. #endif /* HAVE_POLL */
  3246. #if defined(__MINGW32__)
  3247. /* Enable unused function warning again */
  3248. #pragma GCC diagnostic pop
  3249. #endif
  3250. static void
  3251. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  3252. {
  3253. (void)conn; /* Unused. */
  3254. #if defined(_WIN32_WCE)
  3255. (void)sock;
  3256. #else
  3257. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  3258. #endif
  3259. }
  3260. int
  3261. mg_start_thread(mg_thread_func_t f, void *p)
  3262. {
  3263. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3264. /* Compile-time option to control stack size, e.g. -DUSE_STACK_SIZE=16384
  3265. */
  3266. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  3267. == ((uintptr_t)(-1L)))
  3268. ? -1
  3269. : 0);
  3270. #else
  3271. return (
  3272. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  3273. ? -1
  3274. : 0);
  3275. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3276. }
  3277. /* Start a thread storing the thread context. */
  3278. static int
  3279. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  3280. void *p,
  3281. pthread_t *threadidptr)
  3282. {
  3283. uintptr_t uip;
  3284. HANDLE threadhandle;
  3285. int result = -1;
  3286. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  3287. threadhandle = (HANDLE)uip;
  3288. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  3289. *threadidptr = threadhandle;
  3290. result = 0;
  3291. }
  3292. return result;
  3293. }
  3294. /* Wait for a thread to finish. */
  3295. static int
  3296. mg_join_thread(pthread_t threadid)
  3297. {
  3298. int result;
  3299. DWORD dwevent;
  3300. result = -1;
  3301. dwevent = WaitForSingleObject(threadid, INFINITE);
  3302. if (dwevent == WAIT_FAILED) {
  3303. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  3304. } else {
  3305. if (dwevent == WAIT_OBJECT_0) {
  3306. CloseHandle(threadid);
  3307. result = 0;
  3308. }
  3309. }
  3310. return result;
  3311. }
  3312. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  3313. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  3314. /* Create substitutes for POSIX functions in Win32. */
  3315. #if defined(__MINGW32__)
  3316. /* Show no warning in case system functions are not used. */
  3317. #pragma GCC diagnostic push
  3318. #pragma GCC diagnostic ignored "-Wunused-function"
  3319. #endif
  3320. static HANDLE
  3321. dlopen(const char *dll_name, int flags)
  3322. {
  3323. wchar_t wbuf[PATH_MAX];
  3324. (void)flags;
  3325. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  3326. return LoadLibraryW(wbuf);
  3327. }
  3328. static int
  3329. dlclose(void *handle)
  3330. {
  3331. int result;
  3332. if (FreeLibrary((HMODULE)handle) != 0) {
  3333. result = 0;
  3334. } else {
  3335. result = -1;
  3336. }
  3337. return result;
  3338. }
  3339. #if defined(__MINGW32__)
  3340. /* Enable unused function warning again */
  3341. #pragma GCC diagnostic pop
  3342. #endif
  3343. #endif
  3344. #if !defined(NO_CGI)
  3345. #define SIGKILL (0)
  3346. static int
  3347. kill(pid_t pid, int sig_num)
  3348. {
  3349. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  3350. (void)CloseHandle((HANDLE)pid);
  3351. return 0;
  3352. }
  3353. static void
  3354. trim_trailing_whitespaces(char *s)
  3355. {
  3356. char *e = s + strlen(s) - 1;
  3357. while (e > s && isspace(*(unsigned char *)e)) {
  3358. *e-- = '\0';
  3359. }
  3360. }
  3361. static pid_t
  3362. spawn_process(struct mg_connection *conn,
  3363. const char *prog,
  3364. char *envblk,
  3365. char *envp[],
  3366. int fdin[2],
  3367. int fdout[2],
  3368. int fderr[2],
  3369. const char *dir)
  3370. {
  3371. HANDLE me;
  3372. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  3373. cmdline[PATH_MAX], buf[PATH_MAX];
  3374. int truncated;
  3375. struct mg_file file = STRUCT_FILE_INITIALIZER;
  3376. STARTUPINFOA si;
  3377. PROCESS_INFORMATION pi = {0};
  3378. (void)envp;
  3379. memset(&si, 0, sizeof(si));
  3380. si.cb = sizeof(si);
  3381. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  3382. si.wShowWindow = SW_HIDE;
  3383. me = GetCurrentProcess();
  3384. DuplicateHandle(me,
  3385. (HANDLE)_get_osfhandle(fdin[0]),
  3386. me,
  3387. &si.hStdInput,
  3388. 0,
  3389. TRUE,
  3390. DUPLICATE_SAME_ACCESS);
  3391. DuplicateHandle(me,
  3392. (HANDLE)_get_osfhandle(fdout[1]),
  3393. me,
  3394. &si.hStdOutput,
  3395. 0,
  3396. TRUE,
  3397. DUPLICATE_SAME_ACCESS);
  3398. DuplicateHandle(me,
  3399. (HANDLE)_get_osfhandle(fderr[1]),
  3400. me,
  3401. &si.hStdError,
  3402. 0,
  3403. TRUE,
  3404. DUPLICATE_SAME_ACCESS);
  3405. /* Mark handles that should not be inherited. See
  3406. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  3407. */
  3408. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  3409. HANDLE_FLAG_INHERIT,
  3410. 0);
  3411. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  3412. HANDLE_FLAG_INHERIT,
  3413. 0);
  3414. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  3415. HANDLE_FLAG_INHERIT,
  3416. 0);
  3417. /* If CGI file is a script, try to read the interpreter line */
  3418. interp = conn->ctx->config[CGI_INTERPRETER];
  3419. if (interp == NULL) {
  3420. buf[0] = buf[1] = '\0';
  3421. /* Read the first line of the script into the buffer */
  3422. mg_snprintf(
  3423. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  3424. if (truncated) {
  3425. pi.hProcess = (pid_t)-1;
  3426. goto spawn_cleanup;
  3427. }
  3428. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  3429. p = (char *)file.access.membuf;
  3430. mg_fgets(buf, sizeof(buf), &file, &p);
  3431. (void)mg_fclose(&file.access); /* ignore error on read only file */
  3432. buf[sizeof(buf) - 1] = '\0';
  3433. }
  3434. if (buf[0] == '#' && buf[1] == '!') {
  3435. trim_trailing_whitespaces(buf + 2);
  3436. } else {
  3437. buf[2] = '\0';
  3438. }
  3439. interp = buf + 2;
  3440. }
  3441. if (interp[0] != '\0') {
  3442. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  3443. interp = full_interp;
  3444. }
  3445. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  3446. if (interp[0] != '\0') {
  3447. mg_snprintf(conn,
  3448. &truncated,
  3449. cmdline,
  3450. sizeof(cmdline),
  3451. "\"%s\" \"%s\\%s\"",
  3452. interp,
  3453. full_dir,
  3454. prog);
  3455. } else {
  3456. mg_snprintf(conn,
  3457. &truncated,
  3458. cmdline,
  3459. sizeof(cmdline),
  3460. "\"%s\\%s\"",
  3461. full_dir,
  3462. prog);
  3463. }
  3464. if (truncated) {
  3465. pi.hProcess = (pid_t)-1;
  3466. goto spawn_cleanup;
  3467. }
  3468. DEBUG_TRACE("Running [%s]", cmdline);
  3469. if (CreateProcessA(NULL,
  3470. cmdline,
  3471. NULL,
  3472. NULL,
  3473. TRUE,
  3474. CREATE_NEW_PROCESS_GROUP,
  3475. envblk,
  3476. NULL,
  3477. &si,
  3478. &pi) == 0) {
  3479. mg_cry(
  3480. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  3481. pi.hProcess = (pid_t)-1;
  3482. /* goto spawn_cleanup; */
  3483. }
  3484. spawn_cleanup:
  3485. (void)CloseHandle(si.hStdOutput);
  3486. (void)CloseHandle(si.hStdError);
  3487. (void)CloseHandle(si.hStdInput);
  3488. if (pi.hThread != NULL) {
  3489. (void)CloseHandle(pi.hThread);
  3490. }
  3491. return (pid_t)pi.hProcess;
  3492. }
  3493. #endif /* !NO_CGI */
  3494. static int
  3495. set_blocking_mode(SOCKET sock, int blocking)
  3496. {
  3497. unsigned long non_blocking = !blocking;
  3498. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  3499. }
  3500. #else
  3501. static int
  3502. mg_stat(const struct mg_connection *conn,
  3503. const char *path,
  3504. struct mg_file_stat *filep)
  3505. {
  3506. struct stat st;
  3507. if (!filep) {
  3508. return 0;
  3509. }
  3510. memset(filep, 0, sizeof(*filep));
  3511. if (conn && is_file_in_memory(conn, path)) {
  3512. return 1;
  3513. }
  3514. if (0 == stat(path, &st)) {
  3515. filep->size = (uint64_t)(st.st_size);
  3516. filep->last_modified = st.st_mtime;
  3517. filep->is_directory = S_ISDIR(st.st_mode);
  3518. return 1;
  3519. }
  3520. return 0;
  3521. }
  3522. static void
  3523. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  3524. {
  3525. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  3526. if (conn) {
  3527. mg_cry(conn,
  3528. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  3529. __func__,
  3530. strerror(ERRNO));
  3531. }
  3532. }
  3533. }
  3534. int
  3535. mg_start_thread(mg_thread_func_t func, void *param)
  3536. {
  3537. pthread_t thread_id;
  3538. pthread_attr_t attr;
  3539. int result;
  3540. (void)pthread_attr_init(&attr);
  3541. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  3542. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3543. /* Compile-time option to control stack size,
  3544. * e.g. -DUSE_STACK_SIZE=16384 */
  3545. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3546. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3547. result = pthread_create(&thread_id, &attr, func, param);
  3548. pthread_attr_destroy(&attr);
  3549. return result;
  3550. }
  3551. /* Start a thread storing the thread context. */
  3552. static int
  3553. mg_start_thread_with_id(mg_thread_func_t func,
  3554. void *param,
  3555. pthread_t *threadidptr)
  3556. {
  3557. pthread_t thread_id;
  3558. pthread_attr_t attr;
  3559. int result;
  3560. (void)pthread_attr_init(&attr);
  3561. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3562. /* Compile-time option to control stack size,
  3563. * e.g. -DUSE_STACK_SIZE=16384 */
  3564. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3565. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  3566. result = pthread_create(&thread_id, &attr, func, param);
  3567. pthread_attr_destroy(&attr);
  3568. if ((result == 0) && (threadidptr != NULL)) {
  3569. *threadidptr = thread_id;
  3570. }
  3571. return result;
  3572. }
  3573. /* Wait for a thread to finish. */
  3574. static int
  3575. mg_join_thread(pthread_t threadid)
  3576. {
  3577. int result;
  3578. result = pthread_join(threadid, NULL);
  3579. return result;
  3580. }
  3581. #ifndef NO_CGI
  3582. static pid_t
  3583. spawn_process(struct mg_connection *conn,
  3584. const char *prog,
  3585. char *envblk,
  3586. char *envp[],
  3587. int fdin[2],
  3588. int fdout[2],
  3589. int fderr[2],
  3590. const char *dir)
  3591. {
  3592. pid_t pid;
  3593. const char *interp;
  3594. (void)envblk;
  3595. if (conn == NULL) {
  3596. return 0;
  3597. }
  3598. if ((pid = fork()) == -1) {
  3599. /* Parent */
  3600. send_http_error(conn,
  3601. 500,
  3602. "Error: Creating CGI process\nfork(): %s",
  3603. strerror(ERRNO));
  3604. } else if (pid == 0) {
  3605. /* Child */
  3606. if (chdir(dir) != 0) {
  3607. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  3608. } else if (dup2(fdin[0], 0) == -1) {
  3609. mg_cry(conn,
  3610. "%s: dup2(%d, 0): %s",
  3611. __func__,
  3612. fdin[0],
  3613. strerror(ERRNO));
  3614. } else if (dup2(fdout[1], 1) == -1) {
  3615. mg_cry(conn,
  3616. "%s: dup2(%d, 1): %s",
  3617. __func__,
  3618. fdout[1],
  3619. strerror(ERRNO));
  3620. } else if (dup2(fderr[1], 2) == -1) {
  3621. mg_cry(conn,
  3622. "%s: dup2(%d, 2): %s",
  3623. __func__,
  3624. fderr[1],
  3625. strerror(ERRNO));
  3626. } else {
  3627. /* Keep stderr and stdout in two different pipes.
  3628. * Stdout will be sent back to the client,
  3629. * stderr should go into a server error log. */
  3630. (void)close(fdin[0]);
  3631. (void)close(fdout[1]);
  3632. (void)close(fderr[1]);
  3633. /* Close write end fdin and read end fdout and fderr */
  3634. (void)close(fdin[1]);
  3635. (void)close(fdout[0]);
  3636. (void)close(fderr[0]);
  3637. /* After exec, all signal handlers are restored to their default
  3638. * values, with one exception of SIGCHLD. According to
  3639. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler will
  3640. * leave unchanged after exec if it was set to be ignored. Restore
  3641. * it to default action. */
  3642. signal(SIGCHLD, SIG_DFL);
  3643. interp = conn->ctx->config[CGI_INTERPRETER];
  3644. if (interp == NULL) {
  3645. (void)execle(prog, prog, NULL, envp);
  3646. mg_cry(conn,
  3647. "%s: execle(%s): %s",
  3648. __func__,
  3649. prog,
  3650. strerror(ERRNO));
  3651. } else {
  3652. (void)execle(interp, interp, prog, NULL, envp);
  3653. mg_cry(conn,
  3654. "%s: execle(%s %s): %s",
  3655. __func__,
  3656. interp,
  3657. prog,
  3658. strerror(ERRNO));
  3659. }
  3660. }
  3661. exit(EXIT_FAILURE);
  3662. }
  3663. return pid;
  3664. }
  3665. #endif /* !NO_CGI */
  3666. static int
  3667. set_blocking_mode(SOCKET sock, int blocking)
  3668. {
  3669. int flags;
  3670. flags = fcntl(sock, F_GETFL, 0);
  3671. if (blocking) {
  3672. (void)fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  3673. } else {
  3674. (void)fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK)));
  3675. }
  3676. return 0;
  3677. }
  3678. #endif /* _WIN32 */
  3679. /* End of initial operating system specific define block. */
  3680. /* Get a random number (independent of C rand function) */
  3681. static uint64_t
  3682. get_random(void)
  3683. {
  3684. static uint64_t lfsr = 0; /* Linear feedback shift register */
  3685. static uint64_t lcg = 0; /* Linear congruential generator */
  3686. struct timespec now;
  3687. memset(&now, 0, sizeof(now));
  3688. clock_gettime(CLOCK_MONOTONIC, &now);
  3689. if (lfsr == 0) {
  3690. /* lfsr will be only 0 if has not been initialized,
  3691. * so this code is called only once. */
  3692. lfsr = (((uint64_t)now.tv_sec) << 21) ^ ((uint64_t)now.tv_nsec)
  3693. ^ ((uint64_t)(ptrdiff_t)&now) ^ (((uint64_t)time(NULL)) << 33);
  3694. lcg = (((uint64_t)now.tv_sec) << 25) + (uint64_t)now.tv_nsec
  3695. + (uint64_t)(ptrdiff_t)&now;
  3696. } else {
  3697. /* Get the next step of both random number generators. */
  3698. lfsr = (lfsr >> 1)
  3699. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  3700. << 63);
  3701. lcg = lcg * 6364136223846793005 + 1442695040888963407;
  3702. }
  3703. /* Combining two pseudo-random number generators and a high resolution part
  3704. * of the current server time will make it hard (impossible?) to guess the
  3705. * next number. */
  3706. return (lfsr ^ lcg ^ (uint64_t)now.tv_nsec);
  3707. }
  3708. static int
  3709. mg_poll(struct pollfd *pfd,
  3710. unsigned int n,
  3711. int milliseconds,
  3712. volatile int *stop_server)
  3713. {
  3714. int ms_now, result;
  3715. /* Call poll, but only for a maximum time of a few seconds.
  3716. * This will allow to stop the server after some seconds, instead
  3717. * of having to wait for a long socket timeout. */
  3718. ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  3719. do {
  3720. if (*stop_server) {
  3721. /* Shut down signal */
  3722. return -2;
  3723. }
  3724. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  3725. ms_now = milliseconds;
  3726. }
  3727. result = poll(pfd, n, ms_now);
  3728. if (result != 0) {
  3729. /* Poll returned either success (1) or error (-1).
  3730. * Forward both to the caller. */
  3731. return result;
  3732. }
  3733. /* Poll returned timeout (0). */
  3734. if (milliseconds > 0) {
  3735. milliseconds -= ms_now;
  3736. }
  3737. } while (milliseconds != 0);
  3738. return result;
  3739. }
  3740. /* Write data to the IO channel - opened file descriptor, socket or SSL
  3741. * descriptor. Return number of bytes written. */
  3742. static int
  3743. push(struct mg_context *ctx,
  3744. FILE *fp,
  3745. SOCKET sock,
  3746. SSL *ssl,
  3747. const char *buf,
  3748. int len,
  3749. double timeout)
  3750. {
  3751. struct timespec start, now;
  3752. int n, err;
  3753. #ifdef _WIN32
  3754. typedef int len_t;
  3755. #else
  3756. typedef size_t len_t;
  3757. #endif
  3758. if (timeout > 0) {
  3759. memset(&start, 0, sizeof(start));
  3760. memset(&now, 0, sizeof(now));
  3761. clock_gettime(CLOCK_MONOTONIC, &start);
  3762. }
  3763. if (ctx == NULL) {
  3764. return -1;
  3765. }
  3766. #ifdef NO_SSL
  3767. if (ssl) {
  3768. return -1;
  3769. }
  3770. #endif
  3771. do {
  3772. #ifndef NO_SSL
  3773. if (ssl != NULL) {
  3774. n = SSL_write(ssl, buf, len);
  3775. if (n <= 0) {
  3776. err = SSL_get_error(ssl, n);
  3777. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  3778. err = ERRNO;
  3779. } else if ((err == SSL_ERROR_WANT_READ)
  3780. || (err == SSL_ERROR_WANT_WRITE)) {
  3781. n = 0;
  3782. } else {
  3783. DEBUG_TRACE("SSL_write() failed, error %d", err);
  3784. return -1;
  3785. }
  3786. } else {
  3787. err = 0;
  3788. }
  3789. } else
  3790. #endif
  3791. if (fp != NULL) {
  3792. n = (int)fwrite(buf, 1, (size_t)len, fp);
  3793. if (ferror(fp)) {
  3794. n = -1;
  3795. err = ERRNO;
  3796. } else {
  3797. err = 0;
  3798. }
  3799. } else {
  3800. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  3801. err = (n < 0) ? ERRNO : 0;
  3802. if (n <= 0) {
  3803. /* shutdown of the socket at client side */
  3804. return -1;
  3805. }
  3806. #if defined(TEMPORARY_INSTRUMENTATION)
  3807. {
  3808. FILE *f = fopen("r:\\all.txt", "ab");
  3809. fprintf(f, "\r\n%010u SEND:\r\n", GetTickCount());
  3810. fwrite(buf, 1, n, f);
  3811. fclose(f);
  3812. }
  3813. #endif
  3814. }
  3815. if (ctx->stop_flag) {
  3816. return -1;
  3817. }
  3818. if ((n > 0) || (n == 0 && len == 0)) {
  3819. /* some data has been read, or no data was requested */
  3820. return n;
  3821. }
  3822. if (n < 0) {
  3823. /* socket error - check errno */
  3824. DEBUG_TRACE("send() failed, error %d", err);
  3825. /* TODO: error handling depending on the error code.
  3826. * These codes are different between Windows and Linux.
  3827. */
  3828. return -1;
  3829. }
  3830. /* Only in case n=0 (timeout), repeat calling the write function */
  3831. if (timeout > 0) {
  3832. clock_gettime(CLOCK_MONOTONIC, &now);
  3833. }
  3834. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  3835. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  3836. used */
  3837. return -1;
  3838. }
  3839. static int64_t
  3840. push_all(struct mg_context *ctx,
  3841. FILE *fp,
  3842. SOCKET sock,
  3843. SSL *ssl,
  3844. const char *buf,
  3845. int64_t len)
  3846. {
  3847. double timeout = -1.0;
  3848. int64_t n, nwritten = 0;
  3849. if (ctx == NULL) {
  3850. return -1;
  3851. }
  3852. if (ctx->config[REQUEST_TIMEOUT]) {
  3853. timeout = atoi(ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  3854. }
  3855. while (len > 0 && ctx->stop_flag == 0) {
  3856. n = push(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  3857. if (n < 0) {
  3858. if (nwritten == 0) {
  3859. nwritten = n; /* Propagate the error */
  3860. }
  3861. break;
  3862. } else if (n == 0) {
  3863. break; /* No more data to write */
  3864. } else {
  3865. nwritten += n;
  3866. len -= n;
  3867. }
  3868. }
  3869. return nwritten;
  3870. }
  3871. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  3872. * Return negative value on error, or number of bytes read on success. */
  3873. static int
  3874. pull(FILE *fp, struct mg_connection *conn, char *buf, int len, double timeout)
  3875. {
  3876. int nread, err = 0;
  3877. #ifdef _WIN32
  3878. typedef int len_t;
  3879. #else
  3880. typedef size_t len_t;
  3881. #endif
  3882. if (fp != NULL) {
  3883. #if !defined(_WIN32_WCE)
  3884. /* Use read() instead of fread(), because if we're reading from the
  3885. * CGI pipe, fread() may block until IO buffer is filled up. We
  3886. * cannot afford to block and must pass all read bytes immediately
  3887. * to the client. */
  3888. nread = (int)read(fileno(fp), buf, (size_t)len);
  3889. #else
  3890. /* WinCE does not support CGI pipes */
  3891. nread = (int)fread(buf, 1, (size_t)len, fp);
  3892. #endif
  3893. err = (nread < 0) ? ERRNO : 0;
  3894. #ifndef NO_SSL
  3895. } else if (conn->ssl != NULL) {
  3896. struct pollfd pfd[1];
  3897. int pollres;
  3898. pfd[0].fd = conn->client.sock;
  3899. pfd[0].events = POLLIN;
  3900. pollres =
  3901. mg_poll(pfd, 1, (int)(timeout * 1000.0), &(conn->ctx->stop_flag));
  3902. if (conn->ctx->stop_flag) {
  3903. return -1;
  3904. }
  3905. if (pollres > 0) {
  3906. nread = SSL_read(conn->ssl, buf, len);
  3907. if (nread <= 0) {
  3908. err = SSL_get_error(conn->ssl, nread);
  3909. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  3910. err = ERRNO;
  3911. } else if ((err == SSL_ERROR_WANT_READ)
  3912. || (err == SSL_ERROR_WANT_WRITE)) {
  3913. nread = 0;
  3914. } else {
  3915. DEBUG_TRACE("SSL_read() failed, error %d", err);
  3916. return -1;
  3917. }
  3918. } else {
  3919. err = 0;
  3920. }
  3921. } else if (pollres < 0) {
  3922. /* Error */
  3923. return -1;
  3924. } else {
  3925. /* pollres = 0 means timeout */
  3926. nread = 0;
  3927. }
  3928. #endif
  3929. } else {
  3930. struct pollfd pfd[1];
  3931. int pollres;
  3932. pfd[0].fd = conn->client.sock;
  3933. pfd[0].events = POLLIN;
  3934. pollres =
  3935. mg_poll(pfd, 1, (int)(timeout * 1000.0), &(conn->ctx->stop_flag));
  3936. if (conn->ctx->stop_flag) {
  3937. return -1;
  3938. }
  3939. if (pollres > 0) {
  3940. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  3941. err = (nread < 0) ? ERRNO : 0;
  3942. if (nread <= 0) {
  3943. /* shutdown of the socket at client side */
  3944. return -1;
  3945. }
  3946. #if defined(TEMPORARY_INSTRUMENTATION)
  3947. {
  3948. FILE *f = fopen("r:\\all.txt", "ab");
  3949. fprintf(f, "\r\n%010u RECV:\r\n", GetTickCount());
  3950. fwrite(buf, 1, nread, f);
  3951. fclose(f);
  3952. }
  3953. #endif
  3954. } else if (pollres < 0) {
  3955. /* error callint poll */
  3956. return -1;
  3957. } else {
  3958. /* pollres = 0 means timeout */
  3959. nread = 0;
  3960. }
  3961. }
  3962. if (conn->ctx->stop_flag) {
  3963. return -1;
  3964. }
  3965. if ((nread > 0) || (nread == 0 && len == 0)) {
  3966. /* some data has been read, or no data was requested */
  3967. return nread;
  3968. }
  3969. if (nread < 0) {
  3970. /* socket error - check errno */
  3971. #ifdef _WIN32
  3972. if (err == WSAEWOULDBLOCK) {
  3973. /* TODO: check if this is still required */
  3974. /* standard case if called from close_socket_gracefully */
  3975. return -1;
  3976. } else if (err == WSAETIMEDOUT) {
  3977. /* TODO: check if this is still required */
  3978. /* timeout is handled by the while loop */
  3979. return 0;
  3980. } else if (err == WSAECONNABORTED) {
  3981. /* See https://www.chilkatsoft.com/p/p_299.asp */
  3982. return -1;
  3983. } else {
  3984. DEBUG_TRACE("recv() failed, error %d", err);
  3985. return -1;
  3986. }
  3987. #else
  3988. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  3989. * if the timeout is reached and if the socket was set to non-
  3990. * blocking in close_socket_gracefully, so we can not distinguish
  3991. * here. We have to wait for the timeout in both cases for now.
  3992. */
  3993. if (err == EAGAIN || err == EWOULDBLOCK || err == EINTR) {
  3994. /* TODO: check if this is still required */
  3995. /* EAGAIN/EWOULDBLOCK:
  3996. * standard case if called from close_socket_gracefully
  3997. * => should return -1 */
  3998. /* or timeout occured
  3999. * => the code must stay in the while loop */
  4000. /* EINTR can be generated on a socket with a timeout set even
  4001. * when SA_RESTART is effective for all relevant signals
  4002. * (see signal(7)).
  4003. * => stay in the while loop */
  4004. } else {
  4005. DEBUG_TRACE("recv() failed, error %d", err);
  4006. return -1;
  4007. }
  4008. #endif
  4009. }
  4010. /* Timeout occured, but no data available. */
  4011. return -1;
  4012. }
  4013. static int
  4014. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  4015. {
  4016. int n, nread = 0;
  4017. double timeout = -1.0;
  4018. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  4019. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  4020. }
  4021. while (len > 0 && conn->ctx->stop_flag == 0) {
  4022. n = pull(fp, conn, buf + nread, len, timeout);
  4023. if (n < 0) {
  4024. if (nread == 0) {
  4025. nread = n; /* Propagate the error */
  4026. }
  4027. break;
  4028. } else if (n == 0) {
  4029. break; /* No more data to read */
  4030. } else {
  4031. conn->consumed_content += n;
  4032. nread += n;
  4033. len -= n;
  4034. }
  4035. }
  4036. return nread;
  4037. }
  4038. static void
  4039. discard_unread_request_data(struct mg_connection *conn)
  4040. {
  4041. char buf[MG_BUF_LEN];
  4042. size_t to_read;
  4043. int nread;
  4044. if (conn == NULL) {
  4045. return;
  4046. }
  4047. to_read = sizeof(buf);
  4048. if (conn->is_chunked) {
  4049. /* Chunked encoding: 1=chunk not read completely, 2=chunk read
  4050. * completely */
  4051. while (conn->is_chunked == 1) {
  4052. nread = mg_read(conn, buf, to_read);
  4053. if (nread <= 0) {
  4054. break;
  4055. }
  4056. }
  4057. } else {
  4058. /* Not chunked: content length is known */
  4059. while (conn->consumed_content < conn->content_len) {
  4060. if (to_read
  4061. > (size_t)(conn->content_len - conn->consumed_content)) {
  4062. to_read = (size_t)(conn->content_len - conn->consumed_content);
  4063. }
  4064. nread = mg_read(conn, buf, to_read);
  4065. if (nread <= 0) {
  4066. break;
  4067. }
  4068. }
  4069. }
  4070. }
  4071. static int
  4072. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  4073. {
  4074. int64_t n, buffered_len, nread;
  4075. int64_t len64 =
  4076. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  4077. * int, we may not read more
  4078. * bytes */
  4079. const char *body;
  4080. if (conn == NULL) {
  4081. return 0;
  4082. }
  4083. /* If Content-Length is not set for a PUT or POST request, read until
  4084. * socket is closed */
  4085. if (conn->consumed_content == 0 && conn->content_len == -1) {
  4086. conn->content_len = INT64_MAX;
  4087. conn->must_close = 1;
  4088. }
  4089. nread = 0;
  4090. if (conn->consumed_content < conn->content_len) {
  4091. /* Adjust number of bytes to read. */
  4092. int64_t left_to_read = conn->content_len - conn->consumed_content;
  4093. if (left_to_read < len64) {
  4094. /* Do not read more than the total content length of the request.
  4095. */
  4096. len64 = left_to_read;
  4097. }
  4098. /* Return buffered data */
  4099. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  4100. - conn->consumed_content;
  4101. if (buffered_len > 0) {
  4102. if (len64 < buffered_len) {
  4103. buffered_len = len64;
  4104. }
  4105. body = conn->buf + conn->request_len + conn->consumed_content;
  4106. memcpy(buf, body, (size_t)buffered_len);
  4107. len64 -= buffered_len;
  4108. conn->consumed_content += buffered_len;
  4109. nread += buffered_len;
  4110. buf = (char *)buf + buffered_len;
  4111. }
  4112. /* We have returned all buffered data. Read new data from the remote
  4113. * socket.
  4114. */
  4115. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  4116. nread += n;
  4117. } else {
  4118. nread = ((nread > 0) ? nread : n);
  4119. }
  4120. }
  4121. return (int)nread;
  4122. }
  4123. static char
  4124. mg_getc(struct mg_connection *conn)
  4125. {
  4126. char c;
  4127. if (conn == NULL) {
  4128. return 0;
  4129. }
  4130. conn->content_len++;
  4131. if (mg_read_inner(conn, &c, 1) <= 0) {
  4132. return (char)0;
  4133. }
  4134. return c;
  4135. }
  4136. int
  4137. mg_read(struct mg_connection *conn, void *buf, size_t len)
  4138. {
  4139. if (len > INT_MAX) {
  4140. len = INT_MAX;
  4141. }
  4142. if (conn == NULL) {
  4143. return 0;
  4144. }
  4145. if (conn->is_chunked) {
  4146. size_t all_read = 0;
  4147. while (len > 0) {
  4148. if (conn->is_chunked == 2) {
  4149. /* No more data left to read */
  4150. return 0;
  4151. }
  4152. if (conn->chunk_remainder) {
  4153. /* copy from the remainder of the last received chunk */
  4154. long read_ret;
  4155. size_t read_now =
  4156. ((conn->chunk_remainder > len) ? (len)
  4157. : (conn->chunk_remainder));
  4158. conn->content_len += (int)read_now;
  4159. read_ret =
  4160. mg_read_inner(conn, (char *)buf + all_read, read_now);
  4161. if (read_ret < 1) {
  4162. /* read error */
  4163. return -1;
  4164. }
  4165. all_read += (size_t)read_ret;
  4166. conn->chunk_remainder -= (size_t)read_ret;
  4167. len -= (size_t)read_ret;
  4168. if (conn->chunk_remainder == 0) {
  4169. /* Add data bytes in the current chunk have been read,
  4170. * so we are expecting \r\n now. */
  4171. char x1 = mg_getc(conn);
  4172. char x2 = mg_getc(conn);
  4173. if ((x1 != '\r') || (x2 != '\n')) {
  4174. /* Protocol violation */
  4175. return -1;
  4176. }
  4177. }
  4178. } else {
  4179. /* fetch a new chunk */
  4180. int i = 0;
  4181. char lenbuf[64];
  4182. char *end = 0;
  4183. unsigned long chunkSize = 0;
  4184. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  4185. lenbuf[i] = mg_getc(conn);
  4186. if (i > 0 && lenbuf[i] == '\r' && lenbuf[i - 1] != '\r') {
  4187. continue;
  4188. }
  4189. if (i > 1 && lenbuf[i] == '\n' && lenbuf[i - 1] == '\r') {
  4190. lenbuf[i + 1] = 0;
  4191. chunkSize = strtoul(lenbuf, &end, 16);
  4192. if (chunkSize == 0) {
  4193. /* regular end of content */
  4194. conn->is_chunked = 2;
  4195. }
  4196. break;
  4197. }
  4198. if (!isxdigit(lenbuf[i])) {
  4199. /* illegal character for chunk length */
  4200. return -1;
  4201. }
  4202. }
  4203. if ((end == NULL) || (*end != '\r')) {
  4204. /* chunksize not set correctly */
  4205. return -1;
  4206. }
  4207. if (chunkSize == 0) {
  4208. break;
  4209. }
  4210. conn->chunk_remainder = chunkSize;
  4211. }
  4212. }
  4213. return (int)all_read;
  4214. }
  4215. return mg_read_inner(conn, buf, len);
  4216. }
  4217. int
  4218. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  4219. {
  4220. time_t now;
  4221. int64_t n, total, allowed;
  4222. if (conn == NULL) {
  4223. return 0;
  4224. }
  4225. if (conn->throttle > 0) {
  4226. if ((now = time(NULL)) != conn->last_throttle_time) {
  4227. conn->last_throttle_time = now;
  4228. conn->last_throttle_bytes = 0;
  4229. }
  4230. allowed = conn->throttle - conn->last_throttle_bytes;
  4231. if (allowed > (int64_t)len) {
  4232. allowed = (int64_t)len;
  4233. }
  4234. if ((total = push_all(conn->ctx,
  4235. NULL,
  4236. conn->client.sock,
  4237. conn->ssl,
  4238. (const char *)buf,
  4239. (int64_t)allowed)) == allowed) {
  4240. buf = (const char *)buf + total;
  4241. conn->last_throttle_bytes += total;
  4242. while (total < (int64_t)len && conn->ctx->stop_flag == 0) {
  4243. allowed = (conn->throttle > ((int64_t)len - total))
  4244. ? (int64_t)len - total
  4245. : conn->throttle;
  4246. if ((n = push_all(conn->ctx,
  4247. NULL,
  4248. conn->client.sock,
  4249. conn->ssl,
  4250. (const char *)buf,
  4251. (int64_t)allowed)) != allowed) {
  4252. break;
  4253. }
  4254. sleep(1);
  4255. conn->last_throttle_bytes = allowed;
  4256. conn->last_throttle_time = time(NULL);
  4257. buf = (const char *)buf + n;
  4258. total += n;
  4259. }
  4260. }
  4261. } else {
  4262. total = push_all(conn->ctx,
  4263. NULL,
  4264. conn->client.sock,
  4265. conn->ssl,
  4266. (const char *)buf,
  4267. (int64_t)len);
  4268. }
  4269. return (int)total;
  4270. }
  4271. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  4272. static int
  4273. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  4274. {
  4275. va_list ap_copy;
  4276. size_t size = MG_BUF_LEN / 4;
  4277. int len = -1;
  4278. *buf = NULL;
  4279. while (len < 0) {
  4280. if (*buf) {
  4281. mg_free(*buf);
  4282. }
  4283. size *= 4;
  4284. *buf = (char *)mg_malloc(size);
  4285. if (!*buf) {
  4286. break;
  4287. }
  4288. va_copy(ap_copy, ap);
  4289. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  4290. va_end(ap_copy);
  4291. (*buf)[size - 1] = 0;
  4292. }
  4293. return len;
  4294. }
  4295. /* Print message to buffer. If buffer is large enough to hold the message,
  4296. * return buffer. If buffer is to small, allocate large enough buffer on heap,
  4297. * and return allocated buffer. */
  4298. static int
  4299. alloc_vprintf(char **out_buf,
  4300. char *prealloc_buf,
  4301. size_t prealloc_size,
  4302. const char *fmt,
  4303. va_list ap)
  4304. {
  4305. va_list ap_copy;
  4306. int len;
  4307. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  4308. * buffer is too small. Also, older versions of msvcrt.dll do not have
  4309. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  4310. * Therefore, we make two passes: on first pass, get required message
  4311. * length.
  4312. * On second pass, actually print the message. */
  4313. va_copy(ap_copy, ap);
  4314. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  4315. va_end(ap_copy);
  4316. if (len < 0) {
  4317. /* C runtime is not standard compliant, vsnprintf() returned -1.
  4318. * Switch to alternative code path that uses incremental allocations.
  4319. */
  4320. va_copy(ap_copy, ap);
  4321. len = alloc_vprintf2(out_buf, fmt, ap);
  4322. va_end(ap_copy);
  4323. } else if ((size_t)(len) >= prealloc_size) {
  4324. /* The pre-allocated buffer not large enough. */
  4325. /* Allocate a new buffer. */
  4326. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  4327. if (!*out_buf) {
  4328. /* Allocation failed. Return -1 as "out of memory" error. */
  4329. return -1;
  4330. }
  4331. /* Buffer allocation successful. Store the string there. */
  4332. va_copy(ap_copy, ap);
  4333. IGNORE_UNUSED_RESULT(
  4334. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  4335. va_end(ap_copy);
  4336. } else {
  4337. /* The pre-allocated buffer is large enough.
  4338. * Use it to store the string and return the address. */
  4339. va_copy(ap_copy, ap);
  4340. IGNORE_UNUSED_RESULT(
  4341. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  4342. va_end(ap_copy);
  4343. *out_buf = prealloc_buf;
  4344. }
  4345. return len;
  4346. }
  4347. static int
  4348. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  4349. {
  4350. char mem[MG_BUF_LEN];
  4351. char *buf = NULL;
  4352. int len;
  4353. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  4354. len = mg_write(conn, buf, (size_t)len);
  4355. }
  4356. if (buf != mem && buf != NULL) {
  4357. mg_free(buf);
  4358. }
  4359. return len;
  4360. }
  4361. int
  4362. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  4363. {
  4364. va_list ap;
  4365. int result;
  4366. va_start(ap, fmt);
  4367. result = mg_vprintf(conn, fmt, ap);
  4368. va_end(ap);
  4369. return result;
  4370. }
  4371. int
  4372. mg_url_decode(const char *src,
  4373. int src_len,
  4374. char *dst,
  4375. int dst_len,
  4376. int is_form_url_encoded)
  4377. {
  4378. int i, j, a, b;
  4379. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  4380. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  4381. if (i < src_len - 2 && src[i] == '%'
  4382. && isxdigit(*(const unsigned char *)(src + i + 1))
  4383. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  4384. a = tolower(*(const unsigned char *)(src + i + 1));
  4385. b = tolower(*(const unsigned char *)(src + i + 2));
  4386. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  4387. i += 2;
  4388. } else if (is_form_url_encoded && src[i] == '+') {
  4389. dst[j] = ' ';
  4390. } else {
  4391. dst[j] = src[i];
  4392. }
  4393. }
  4394. dst[j] = '\0'; /* Null-terminate the destination */
  4395. return (i >= src_len) ? j : -1;
  4396. }
  4397. int
  4398. mg_get_var(const char *data,
  4399. size_t data_len,
  4400. const char *name,
  4401. char *dst,
  4402. size_t dst_len)
  4403. {
  4404. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  4405. }
  4406. int
  4407. mg_get_var2(const char *data,
  4408. size_t data_len,
  4409. const char *name,
  4410. char *dst,
  4411. size_t dst_len,
  4412. size_t occurrence)
  4413. {
  4414. const char *p, *e, *s;
  4415. size_t name_len;
  4416. int len;
  4417. if (dst == NULL || dst_len == 0) {
  4418. len = -2;
  4419. } else if (data == NULL || name == NULL || data_len == 0) {
  4420. len = -1;
  4421. dst[0] = '\0';
  4422. } else {
  4423. name_len = strlen(name);
  4424. e = data + data_len;
  4425. len = -1;
  4426. dst[0] = '\0';
  4427. /* data is "var1=val1&var2=val2...". Find variable first */
  4428. for (p = data; p + name_len < e; p++) {
  4429. if ((p == data || p[-1] == '&') && p[name_len] == '='
  4430. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  4431. /* Point p to variable value */
  4432. p += name_len + 1;
  4433. /* Point s to the end of the value */
  4434. s = (const char *)memchr(p, '&', (size_t)(e - p));
  4435. if (s == NULL) {
  4436. s = e;
  4437. }
  4438. /* assert(s >= p); */
  4439. if (s < p) {
  4440. return -3;
  4441. }
  4442. /* Decode variable into destination buffer */
  4443. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  4444. /* Redirect error code from -1 to -2 (destination buffer too
  4445. * small). */
  4446. if (len == -1) {
  4447. len = -2;
  4448. }
  4449. break;
  4450. }
  4451. }
  4452. }
  4453. return len;
  4454. }
  4455. /* HCP24: some changes to compare hole var_name */
  4456. int
  4457. mg_get_cookie(const char *cookie_header,
  4458. const char *var_name,
  4459. char *dst,
  4460. size_t dst_size)
  4461. {
  4462. const char *s, *p, *end;
  4463. int name_len, len = -1;
  4464. if (dst == NULL || dst_size == 0) {
  4465. return -2;
  4466. }
  4467. dst[0] = '\0';
  4468. if (var_name == NULL || (s = cookie_header) == NULL) {
  4469. return -1;
  4470. }
  4471. name_len = (int)strlen(var_name);
  4472. end = s + strlen(s);
  4473. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  4474. if (s[name_len] == '=') {
  4475. /* HCP24: now check is it a substring or a full cookie name */
  4476. if ((s == cookie_header) || (s[-1] == ' ')) {
  4477. s += name_len + 1;
  4478. if ((p = strchr(s, ' ')) == NULL) {
  4479. p = end;
  4480. }
  4481. if (p[-1] == ';') {
  4482. p--;
  4483. }
  4484. if (*s == '"' && p[-1] == '"' && p > s + 1) {
  4485. s++;
  4486. p--;
  4487. }
  4488. if ((size_t)(p - s) < dst_size) {
  4489. len = (int)(p - s);
  4490. mg_strlcpy(dst, s, (size_t)len + 1);
  4491. } else {
  4492. len = -3;
  4493. }
  4494. break;
  4495. }
  4496. }
  4497. }
  4498. return len;
  4499. }
  4500. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  4501. static void
  4502. base64_encode(const unsigned char *src, int src_len, char *dst)
  4503. {
  4504. static const char *b64 =
  4505. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  4506. int i, j, a, b, c;
  4507. for (i = j = 0; i < src_len; i += 3) {
  4508. a = src[i];
  4509. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  4510. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  4511. dst[j++] = b64[a >> 2];
  4512. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  4513. if (i + 1 < src_len) {
  4514. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  4515. }
  4516. if (i + 2 < src_len) {
  4517. dst[j++] = b64[c & 63];
  4518. }
  4519. }
  4520. while (j % 4 != 0) {
  4521. dst[j++] = '=';
  4522. }
  4523. dst[j++] = '\0';
  4524. }
  4525. #endif
  4526. #if defined(USE_LUA)
  4527. static unsigned char
  4528. b64reverse(char letter)
  4529. {
  4530. if (letter >= 'A' && letter <= 'Z') {
  4531. return letter - 'A';
  4532. }
  4533. if (letter >= 'a' && letter <= 'z') {
  4534. return letter - 'a' + 26;
  4535. }
  4536. if (letter >= '0' && letter <= '9') {
  4537. return letter - '0' + 52;
  4538. }
  4539. if (letter == '+') {
  4540. return 62;
  4541. }
  4542. if (letter == '/') {
  4543. return 63;
  4544. }
  4545. if (letter == '=') {
  4546. return 255; /* normal end */
  4547. }
  4548. return 254; /* error */
  4549. }
  4550. static int
  4551. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  4552. {
  4553. int i;
  4554. unsigned char a, b, c, d;
  4555. *dst_len = 0;
  4556. for (i = 0; i < src_len; i += 4) {
  4557. a = b64reverse(src[i]);
  4558. if (a >= 254) {
  4559. return i;
  4560. }
  4561. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  4562. if (b >= 254) {
  4563. return i + 1;
  4564. }
  4565. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  4566. if (c == 254) {
  4567. return i + 2;
  4568. }
  4569. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  4570. if (d == 254) {
  4571. return i + 3;
  4572. }
  4573. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  4574. if (c != 255) {
  4575. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  4576. if (d != 255) {
  4577. dst[(*dst_len)++] = (c << 6) + d;
  4578. }
  4579. }
  4580. }
  4581. return -1;
  4582. }
  4583. #endif
  4584. static int
  4585. is_put_or_delete_method(const struct mg_connection *conn)
  4586. {
  4587. if (conn) {
  4588. const char *s = conn->request_info.request_method;
  4589. return s != NULL && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  4590. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  4591. }
  4592. return 0;
  4593. }
  4594. static void
  4595. interpret_uri(struct mg_connection *conn, /* in: request (must be valid) */
  4596. char *filename, /* out: filename */
  4597. size_t filename_buf_len, /* in: size of filename buffer */
  4598. struct mg_file_stat *filestat, /* out: file structure */
  4599. int *is_found, /* out: file found (directly) */
  4600. int *is_script_resource, /* out: handled by a script? */
  4601. int *is_websocket_request, /* out: websocket connetion? */
  4602. int *is_put_or_delete_request /* out: put/delete a file? */
  4603. )
  4604. {
  4605. /* TODO (high): Restructure this function */
  4606. #if !defined(NO_FILES)
  4607. const char *uri = conn->request_info.local_uri;
  4608. const char *root = conn->ctx->config[DOCUMENT_ROOT];
  4609. const char *rewrite;
  4610. struct vec a, b;
  4611. int match_len;
  4612. char gz_path[PATH_MAX];
  4613. char const *accept_encoding;
  4614. int truncated;
  4615. #if !defined(NO_CGI) || defined(USE_LUA)
  4616. char *p;
  4617. #endif
  4618. #else
  4619. (void)filename_buf_len; /* unused if NO_FILES is defined */
  4620. #endif
  4621. memset(filestat, 0, sizeof(*filestat));
  4622. *filename = 0;
  4623. *is_found = 0;
  4624. *is_script_resource = 0;
  4625. *is_put_or_delete_request = is_put_or_delete_method(conn);
  4626. #if defined(USE_WEBSOCKET)
  4627. *is_websocket_request = is_websocket_protocol(conn);
  4628. #if !defined(NO_FILES)
  4629. if (*is_websocket_request && conn->ctx->config[WEBSOCKET_ROOT]) {
  4630. root = conn->ctx->config[WEBSOCKET_ROOT];
  4631. }
  4632. #endif /* !NO_FILES */
  4633. #else /* USE_WEBSOCKET */
  4634. *is_websocket_request = 0;
  4635. #endif /* USE_WEBSOCKET */
  4636. #if !defined(NO_FILES)
  4637. /* Note that root == NULL is a regular use case here. This occurs,
  4638. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  4639. * config is not required. */
  4640. if (root == NULL) {
  4641. /* all file related outputs have already been set to 0, just return
  4642. */
  4643. return;
  4644. }
  4645. /* Using buf_len - 1 because memmove() for PATH_INFO may shift part
  4646. * of the path one byte on the right.
  4647. * If document_root is NULL, leave the file empty. */
  4648. mg_snprintf(
  4649. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  4650. if (truncated) {
  4651. goto interpret_cleanup;
  4652. }
  4653. rewrite = conn->ctx->config[REWRITE];
  4654. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  4655. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  4656. mg_snprintf(conn,
  4657. &truncated,
  4658. filename,
  4659. filename_buf_len - 1,
  4660. "%.*s%s",
  4661. (int)b.len,
  4662. b.ptr,
  4663. uri + match_len);
  4664. break;
  4665. }
  4666. }
  4667. if (truncated) {
  4668. goto interpret_cleanup;
  4669. }
  4670. /* Local file path and name, corresponding to requested URI
  4671. * is now stored in "filename" variable. */
  4672. if (mg_stat(conn, filename, filestat)) {
  4673. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  4674. /* File exists. Check if it is a script type. */
  4675. if (0
  4676. #if !defined(NO_CGI)
  4677. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  4678. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4679. filename) > 0
  4680. #endif
  4681. #if defined(USE_LUA)
  4682. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  4683. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  4684. filename) > 0
  4685. #endif
  4686. #if defined(USE_DUKTAPE)
  4687. || match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  4688. strlen(
  4689. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  4690. filename) > 0
  4691. #endif
  4692. ) {
  4693. /* The request addresses a CGI script or a Lua script. The URI
  4694. * corresponds to the script itself (like /path/script.cgi),
  4695. * and there is no additional resource path
  4696. * (like /path/script.cgi/something).
  4697. * Requests that modify (replace or delete) a resource, like
  4698. * PUT and DELETE requests, should replace/delete the script
  4699. * file.
  4700. * Requests that read or write from/to a resource, like GET and
  4701. * POST requests, should call the script and return the
  4702. * generated response. */
  4703. *is_script_resource = !*is_put_or_delete_request;
  4704. }
  4705. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  4706. *is_found = 1;
  4707. return;
  4708. }
  4709. /* If we can't find the actual file, look for the file
  4710. * with the same name but a .gz extension. If we find it,
  4711. * use that and set the gzipped flag in the file struct
  4712. * to indicate that the response need to have the content-
  4713. * encoding: gzip header.
  4714. * We can only do this if the browser declares support. */
  4715. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  4716. if (strstr(accept_encoding, "gzip") != NULL) {
  4717. mg_snprintf(
  4718. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  4719. if (truncated) {
  4720. goto interpret_cleanup;
  4721. }
  4722. if (mg_stat(conn, gz_path, filestat)) {
  4723. if (filestat) {
  4724. filestat->is_gzipped = 1;
  4725. *is_found = 1;
  4726. }
  4727. /* Currently gz files can not be scripts. */
  4728. return;
  4729. }
  4730. }
  4731. }
  4732. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  4733. /* Support PATH_INFO for CGI scripts. */
  4734. for (p = filename + strlen(filename); p > filename + 1; p--) {
  4735. if (*p == '/') {
  4736. *p = '\0';
  4737. if ((0
  4738. #if !defined(NO_CGI)
  4739. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  4740. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4741. filename) > 0
  4742. #endif
  4743. #if defined(USE_LUA)
  4744. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  4745. strlen(
  4746. conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  4747. filename) > 0
  4748. #endif
  4749. #if defined(USE_DUKTAPE)
  4750. || match_prefix(
  4751. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  4752. strlen(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  4753. filename) > 0
  4754. #endif
  4755. ) && mg_stat(conn, filename, filestat)) {
  4756. /* Shift PATH_INFO block one character right, e.g.
  4757. * "/x.cgi/foo/bar\x00" => "/x.cgi\x00/foo/bar\x00"
  4758. * conn->path_info is pointing to the local variable "path"
  4759. * declared in handle_request(), so PATH_INFO is not valid
  4760. * after handle_request returns. */
  4761. conn->path_info = p + 1;
  4762. memmove(p + 2, p + 1, strlen(p + 1) + 1); /* +1 is for
  4763. * trailing \0 */
  4764. p[1] = '/';
  4765. *is_script_resource = 1;
  4766. break;
  4767. } else {
  4768. *p = '/';
  4769. }
  4770. }
  4771. }
  4772. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  4773. #endif /* !defined(NO_FILES) */
  4774. return;
  4775. #if !defined(NO_FILES)
  4776. /* Reset all outputs */
  4777. interpret_cleanup:
  4778. memset(filestat, 0, sizeof(*filestat));
  4779. *filename = 0;
  4780. *is_found = 0;
  4781. *is_script_resource = 0;
  4782. *is_websocket_request = 0;
  4783. *is_put_or_delete_request = 0;
  4784. #endif /* !defined(NO_FILES) */
  4785. }
  4786. /* Check whether full request is buffered. Return:
  4787. * -1 if request is malformed
  4788. * 0 if request is not yet fully buffered
  4789. * >0 actual request length, including last \r\n\r\n */
  4790. static int
  4791. get_request_len(const char *buf, int buflen)
  4792. {
  4793. const char *s, *e;
  4794. int len = 0;
  4795. for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
  4796. /* Control characters are not allowed but >=128 is. */
  4797. if (!isprint(*(const unsigned char *)s) && *s != '\r' && *s != '\n'
  4798. && *(const unsigned char *)s < 128) {
  4799. len = -1;
  4800. break; /* [i_a] abort scan as soon as one malformed character is
  4801. * found; */
  4802. /* don't let subsequent \r\n\r\n win us over anyhow */
  4803. } else if (s[0] == '\n' && s[1] == '\n') {
  4804. len = (int)(s - buf) + 2;
  4805. } else if (s[0] == '\n' && &s[1] < e && s[1] == '\r' && s[2] == '\n') {
  4806. len = (int)(s - buf) + 3;
  4807. }
  4808. return len;
  4809. }
  4810. #if !defined(NO_CACHING)
  4811. /* Convert month to the month number. Return -1 on error, or month number */
  4812. static int
  4813. get_month_index(const char *s)
  4814. {
  4815. size_t i;
  4816. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  4817. if (!strcmp(s, month_names[i])) {
  4818. return (int)i;
  4819. }
  4820. }
  4821. return -1;
  4822. }
  4823. /* Parse UTC date-time string, and return the corresponding time_t value. */
  4824. static time_t
  4825. parse_date_string(const char *datetime)
  4826. {
  4827. char month_str[32] = {0};
  4828. int second, minute, hour, day, month, year;
  4829. time_t result = (time_t)0;
  4830. struct tm tm;
  4831. if ((sscanf(datetime,
  4832. "%d/%3s/%d %d:%d:%d",
  4833. &day,
  4834. month_str,
  4835. &year,
  4836. &hour,
  4837. &minute,
  4838. &second) == 6) || (sscanf(datetime,
  4839. "%d %3s %d %d:%d:%d",
  4840. &day,
  4841. month_str,
  4842. &year,
  4843. &hour,
  4844. &minute,
  4845. &second) == 6)
  4846. || (sscanf(datetime,
  4847. "%*3s, %d %3s %d %d:%d:%d",
  4848. &day,
  4849. month_str,
  4850. &year,
  4851. &hour,
  4852. &minute,
  4853. &second) == 6) || (sscanf(datetime,
  4854. "%d-%3s-%d %d:%d:%d",
  4855. &day,
  4856. month_str,
  4857. &year,
  4858. &hour,
  4859. &minute,
  4860. &second) == 6)) {
  4861. month = get_month_index(month_str);
  4862. if ((month >= 0) && (year >= 1970)) {
  4863. memset(&tm, 0, sizeof(tm));
  4864. tm.tm_year = year - 1900;
  4865. tm.tm_mon = month;
  4866. tm.tm_mday = day;
  4867. tm.tm_hour = hour;
  4868. tm.tm_min = minute;
  4869. tm.tm_sec = second;
  4870. result = timegm(&tm);
  4871. }
  4872. }
  4873. return result;
  4874. }
  4875. #endif /* !NO_CACHING */
  4876. /* Protect against directory disclosure attack by removing '..',
  4877. * excessive '/' and '\' characters */
  4878. static void
  4879. remove_double_dots_and_double_slashes(char *s)
  4880. {
  4881. char *p = s;
  4882. while ((s[0] == '.') && (s[1] == '.')) {
  4883. s++;
  4884. }
  4885. while (*s != '\0') {
  4886. *p++ = *s++;
  4887. if (s[-1] == '/' || s[-1] == '\\') {
  4888. /* Skip all following slashes, backslashes and double-dots */
  4889. while (s[0] != '\0') {
  4890. if (s[0] == '/' || s[0] == '\\') {
  4891. s++;
  4892. } else if (s[0] == '.' && s[1] == '.') {
  4893. s += 2;
  4894. } else {
  4895. break;
  4896. }
  4897. }
  4898. }
  4899. }
  4900. *p = '\0';
  4901. }
  4902. static const struct {
  4903. const char *extension;
  4904. size_t ext_len;
  4905. const char *mime_type;
  4906. } builtin_mime_types[] = {
  4907. /* IANA registered MIME types (http://www.iana.org/assignments/media-types)
  4908. * application types */
  4909. {".doc", 4, "application/msword"},
  4910. {".eps", 4, "application/postscript"},
  4911. {".exe", 4, "application/octet-stream"},
  4912. {".js", 3, "application/javascript"},
  4913. {".json", 5, "application/json"},
  4914. {".pdf", 4, "application/pdf"},
  4915. {".ps", 3, "application/postscript"},
  4916. {".rtf", 4, "application/rtf"},
  4917. {".xhtml", 6, "application/xhtml+xml"},
  4918. {".xsl", 4, "application/xml"},
  4919. {".xslt", 5, "application/xml"},
  4920. /* fonts */
  4921. {".ttf", 4, "application/font-sfnt"},
  4922. {".cff", 4, "application/font-sfnt"},
  4923. {".otf", 4, "application/font-sfnt"},
  4924. {".aat", 4, "application/font-sfnt"},
  4925. {".sil", 4, "application/font-sfnt"},
  4926. {".pfr", 4, "application/font-tdpfr"},
  4927. {".woff", 5, "application/font-woff"},
  4928. /* audio */
  4929. {".mp3", 4, "audio/mpeg"},
  4930. {".oga", 4, "audio/ogg"},
  4931. {".ogg", 4, "audio/ogg"},
  4932. /* image */
  4933. {".gif", 4, "image/gif"},
  4934. {".ief", 4, "image/ief"},
  4935. {".jpeg", 5, "image/jpeg"},
  4936. {".jpg", 4, "image/jpeg"},
  4937. {".jpm", 4, "image/jpm"},
  4938. {".jpx", 4, "image/jpx"},
  4939. {".png", 4, "image/png"},
  4940. {".svg", 4, "image/svg+xml"},
  4941. {".tif", 4, "image/tiff"},
  4942. {".tiff", 5, "image/tiff"},
  4943. /* model */
  4944. {".wrl", 4, "model/vrml"},
  4945. /* text */
  4946. {".css", 4, "text/css"},
  4947. {".csv", 4, "text/csv"},
  4948. {".htm", 4, "text/html"},
  4949. {".html", 5, "text/html"},
  4950. {".sgm", 4, "text/sgml"},
  4951. {".shtm", 5, "text/html"},
  4952. {".shtml", 6, "text/html"},
  4953. {".txt", 4, "text/plain"},
  4954. {".xml", 4, "text/xml"},
  4955. /* video */
  4956. {".mov", 4, "video/quicktime"},
  4957. {".mp4", 4, "video/mp4"},
  4958. {".mpeg", 5, "video/mpeg"},
  4959. {".mpg", 4, "video/mpeg"},
  4960. {".ogv", 4, "video/ogg"},
  4961. {".qt", 3, "video/quicktime"},
  4962. /* not registered types
  4963. * (http://reference.sitepoint.com/html/mime-types-full,
  4964. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  4965. {".arj", 4, "application/x-arj-compressed"},
  4966. {".gz", 3, "application/x-gunzip"},
  4967. {".rar", 4, "application/x-arj-compressed"},
  4968. {".swf", 4, "application/x-shockwave-flash"},
  4969. {".tar", 4, "application/x-tar"},
  4970. {".tgz", 4, "application/x-tar-gz"},
  4971. {".torrent", 8, "application/x-bittorrent"},
  4972. {".ppt", 4, "application/x-mspowerpoint"},
  4973. {".xls", 4, "application/x-msexcel"},
  4974. {".zip", 4, "application/x-zip-compressed"},
  4975. {".aac",
  4976. 4,
  4977. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  4978. {".aif", 4, "audio/x-aif"},
  4979. {".m3u", 4, "audio/x-mpegurl"},
  4980. {".mid", 4, "audio/x-midi"},
  4981. {".ra", 3, "audio/x-pn-realaudio"},
  4982. {".ram", 4, "audio/x-pn-realaudio"},
  4983. {".wav", 4, "audio/x-wav"},
  4984. {".bmp", 4, "image/bmp"},
  4985. {".ico", 4, "image/x-icon"},
  4986. {".pct", 4, "image/x-pct"},
  4987. {".pict", 5, "image/pict"},
  4988. {".rgb", 4, "image/x-rgb"},
  4989. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  4990. {".asf", 4, "video/x-ms-asf"},
  4991. {".avi", 4, "video/x-msvideo"},
  4992. {".m4v", 4, "video/x-m4v"},
  4993. {NULL, 0, NULL}};
  4994. const char *
  4995. mg_get_builtin_mime_type(const char *path)
  4996. {
  4997. const char *ext;
  4998. size_t i, path_len;
  4999. path_len = strlen(path);
  5000. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  5001. ext = path + (path_len - builtin_mime_types[i].ext_len);
  5002. if (path_len > builtin_mime_types[i].ext_len
  5003. && mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {
  5004. return builtin_mime_types[i].mime_type;
  5005. }
  5006. }
  5007. return "text/plain";
  5008. }
  5009. /* Look at the "path" extension and figure what mime type it has.
  5010. * Store mime type in the vector. */
  5011. static void
  5012. get_mime_type(struct mg_context *ctx, const char *path, struct vec *vec)
  5013. {
  5014. struct vec ext_vec, mime_vec;
  5015. const char *list, *ext;
  5016. size_t path_len;
  5017. path_len = strlen(path);
  5018. if (ctx == NULL || vec == NULL) {
  5019. return;
  5020. }
  5021. /* Scan user-defined mime types first, in case user wants to
  5022. * override default mime types. */
  5023. list = ctx->config[EXTRA_MIME_TYPES];
  5024. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  5025. /* ext now points to the path suffix */
  5026. ext = path + path_len - ext_vec.len;
  5027. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  5028. *vec = mime_vec;
  5029. return;
  5030. }
  5031. }
  5032. vec->ptr = mg_get_builtin_mime_type(path);
  5033. vec->len = strlen(vec->ptr);
  5034. }
  5035. /* Stringify binary data. Output buffer must be twice as big as input,
  5036. * because each byte takes 2 bytes in string representation */
  5037. static void
  5038. bin2str(char *to, const unsigned char *p, size_t len)
  5039. {
  5040. static const char *hex = "0123456789abcdef";
  5041. for (; len--; p++) {
  5042. *to++ = hex[p[0] >> 4];
  5043. *to++ = hex[p[0] & 0x0f];
  5044. }
  5045. *to = '\0';
  5046. }
  5047. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes. */
  5048. char *
  5049. mg_md5(char buf[33], ...)
  5050. {
  5051. md5_byte_t hash[16];
  5052. const char *p;
  5053. va_list ap;
  5054. md5_state_t ctx;
  5055. md5_init(&ctx);
  5056. va_start(ap, buf);
  5057. while ((p = va_arg(ap, const char *)) != NULL) {
  5058. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  5059. }
  5060. va_end(ap);
  5061. md5_finish(&ctx, hash);
  5062. bin2str(buf, hash, sizeof(hash));
  5063. return buf;
  5064. }
  5065. /* Check the user's password, return 1 if OK */
  5066. static int
  5067. check_password(const char *method,
  5068. const char *ha1,
  5069. const char *uri,
  5070. const char *nonce,
  5071. const char *nc,
  5072. const char *cnonce,
  5073. const char *qop,
  5074. const char *response)
  5075. {
  5076. char ha2[32 + 1], expected_response[32 + 1];
  5077. /* Some of the parameters may be NULL */
  5078. if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL
  5079. || qop == NULL
  5080. || response == NULL) {
  5081. return 0;
  5082. }
  5083. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  5084. if (strlen(response) != 32) {
  5085. return 0;
  5086. }
  5087. mg_md5(ha2, method, ":", uri, NULL);
  5088. mg_md5(expected_response,
  5089. ha1,
  5090. ":",
  5091. nonce,
  5092. ":",
  5093. nc,
  5094. ":",
  5095. cnonce,
  5096. ":",
  5097. qop,
  5098. ":",
  5099. ha2,
  5100. NULL);
  5101. return mg_strcasecmp(response, expected_response) == 0;
  5102. }
  5103. /* Use the global passwords file, if specified by auth_gpass option,
  5104. * or search for .htpasswd in the requested directory. */
  5105. static void
  5106. open_auth_file(struct mg_connection *conn,
  5107. const char *path,
  5108. struct mg_file *filep)
  5109. {
  5110. if (conn != NULL && conn->ctx != NULL) {
  5111. char name[PATH_MAX];
  5112. const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
  5113. int truncated;
  5114. if (gpass != NULL) {
  5115. /* Use global passwords file */
  5116. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  5117. #ifdef DEBUG
  5118. /* Use mg_cry here, since gpass has been configured. */
  5119. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  5120. #endif
  5121. }
  5122. /* Important: using local struct mg_file to test path for
  5123. * is_directory
  5124. * flag. If filep is used, mg_stat() makes it appear as if auth file
  5125. * was opened. TODO: mg_stat must not make anything appear to be
  5126. * opened */
  5127. } else if (mg_stat(conn, path, &filep->stat)
  5128. && filep->stat.is_directory) {
  5129. mg_snprintf(conn,
  5130. &truncated,
  5131. name,
  5132. sizeof(name),
  5133. "%s/%s",
  5134. path,
  5135. PASSWORDS_FILE_NAME);
  5136. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  5137. #ifdef DEBUG
  5138. /* Don't use mg_cry here, but only a trace, since this is
  5139. * a typical case. It will occur for every directory
  5140. * without a password file. */
  5141. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  5142. #endif
  5143. }
  5144. } else {
  5145. /* Try to find .htpasswd in requested directory. */
  5146. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  5147. if (e[0] == '/') {
  5148. break;
  5149. }
  5150. }
  5151. mg_snprintf(conn,
  5152. &truncated,
  5153. name,
  5154. sizeof(name),
  5155. "%.*s/%s",
  5156. (int)(e - p),
  5157. p,
  5158. PASSWORDS_FILE_NAME);
  5159. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  5160. #ifdef DEBUG
  5161. /* Don't use mg_cry here, but only a trace, since this is
  5162. * a typical case. It will occur for every directory
  5163. * without a password file. */
  5164. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  5165. #endif
  5166. }
  5167. }
  5168. }
  5169. }
  5170. /* Parsed Authorization header */
  5171. struct ah {
  5172. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  5173. };
  5174. /* Return 1 on success. Always initializes the ah structure. */
  5175. static int
  5176. parse_auth_header(struct mg_connection *conn,
  5177. char *buf,
  5178. size_t buf_size,
  5179. struct ah *ah)
  5180. {
  5181. char *name, *value, *s;
  5182. const char *auth_header;
  5183. uint64_t nonce;
  5184. if (!ah || !conn) {
  5185. return 0;
  5186. }
  5187. (void)memset(ah, 0, sizeof(*ah));
  5188. if ((auth_header = mg_get_header(conn, "Authorization")) == NULL
  5189. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  5190. return 0;
  5191. }
  5192. /* Make modifiable copy of the auth header */
  5193. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  5194. s = buf;
  5195. /* Parse authorization header */
  5196. for (;;) {
  5197. /* Gobble initial spaces */
  5198. while (isspace(*(unsigned char *)s)) {
  5199. s++;
  5200. }
  5201. name = skip_quoted(&s, "=", " ", 0);
  5202. /* Value is either quote-delimited, or ends at first comma or space. */
  5203. if (s[0] == '\"') {
  5204. s++;
  5205. value = skip_quoted(&s, "\"", " ", '\\');
  5206. if (s[0] == ',') {
  5207. s++;
  5208. }
  5209. } else {
  5210. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  5211. * spaces */
  5212. }
  5213. if (*name == '\0') {
  5214. break;
  5215. }
  5216. if (!strcmp(name, "username")) {
  5217. ah->user = value;
  5218. } else if (!strcmp(name, "cnonce")) {
  5219. ah->cnonce = value;
  5220. } else if (!strcmp(name, "response")) {
  5221. ah->response = value;
  5222. } else if (!strcmp(name, "uri")) {
  5223. ah->uri = value;
  5224. } else if (!strcmp(name, "qop")) {
  5225. ah->qop = value;
  5226. } else if (!strcmp(name, "nc")) {
  5227. ah->nc = value;
  5228. } else if (!strcmp(name, "nonce")) {
  5229. ah->nonce = value;
  5230. }
  5231. }
  5232. #ifndef NO_NONCE_CHECK
  5233. /* Read the nonce from the response. */
  5234. if (ah->nonce == NULL) {
  5235. return 0;
  5236. }
  5237. s = NULL;
  5238. nonce = strtoull(ah->nonce, &s, 10);
  5239. if ((s == NULL) || (*s != 0)) {
  5240. return 0;
  5241. }
  5242. /* Convert the nonce from the client to a number. */
  5243. nonce ^= conn->ctx->auth_nonce_mask;
  5244. /* The converted number corresponds to the time the nounce has been
  5245. * created. This should not be earlier than the server start. */
  5246. /* Server side nonce check is valuable in all situations but one:
  5247. * if the server restarts frequently, but the client should not see
  5248. * that, so the server should accept nonces from previous starts. */
  5249. /* However, the reasonable default is to not accept a nonce from a
  5250. * previous start, so if anyone changed the access rights between
  5251. * two restarts, a new login is required. */
  5252. if (nonce < (uint64_t)conn->ctx->start_time) {
  5253. /* nonce is from a previous start of the server and no longer valid
  5254. * (replay attack?) */
  5255. return 0;
  5256. }
  5257. /* Check if the nonce is too high, so it has not (yet) been used by the
  5258. * server. */
  5259. if (nonce >= ((uint64_t)conn->ctx->start_time + conn->ctx->nonce_count)) {
  5260. return 0;
  5261. }
  5262. #else
  5263. (void)nonce;
  5264. #endif
  5265. /* CGI needs it as REMOTE_USER */
  5266. if (ah->user != NULL) {
  5267. conn->request_info.remote_user = mg_strdup(ah->user);
  5268. } else {
  5269. return 0;
  5270. }
  5271. return 1;
  5272. }
  5273. static const char *
  5274. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  5275. {
  5276. const char *eof;
  5277. size_t len;
  5278. const char *memend;
  5279. if (!filep) {
  5280. return NULL;
  5281. }
  5282. if (filep->access.membuf != NULL && *p != NULL) {
  5283. memend = (const char *)&filep->access.membuf[filep->stat.size];
  5284. /* Search for \n from p till the end of stream */
  5285. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  5286. if (eof != NULL) {
  5287. eof += 1; /* Include \n */
  5288. } else {
  5289. eof = memend; /* Copy remaining data */
  5290. }
  5291. len =
  5292. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  5293. memcpy(buf, *p, len);
  5294. buf[len] = '\0';
  5295. *p += len;
  5296. return len ? eof : NULL;
  5297. } else if (filep->access.fp != NULL) {
  5298. return fgets(buf, (int)size, filep->access.fp);
  5299. } else {
  5300. return NULL;
  5301. }
  5302. }
  5303. /* Define the initial recursion depth for procesesing htpasswd files that
  5304. * include other htpasswd
  5305. * (or even the same) files. It is not difficult to provide a file or files
  5306. * s.t. they force civetweb
  5307. * to infinitely recurse and then crash.
  5308. */
  5309. #define INITIAL_DEPTH 9
  5310. #if INITIAL_DEPTH <= 0
  5311. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  5312. #endif
  5313. struct read_auth_file_struct {
  5314. struct mg_connection *conn;
  5315. struct ah ah;
  5316. char *domain;
  5317. char buf[256 + 256 + 40];
  5318. char *f_user;
  5319. char *f_domain;
  5320. char *f_ha1;
  5321. };
  5322. static int
  5323. read_auth_file(struct mg_file *filep,
  5324. struct read_auth_file_struct *workdata,
  5325. int depth)
  5326. {
  5327. char *p;
  5328. int is_authorized = 0;
  5329. struct mg_file fp;
  5330. size_t l;
  5331. if (!filep || !workdata || 0 == depth) {
  5332. return 0;
  5333. }
  5334. /* Loop over passwords file */
  5335. p = (char *)filep->access.membuf;
  5336. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  5337. l = strlen(workdata->buf);
  5338. while (l > 0) {
  5339. if (isspace(workdata->buf[l - 1])
  5340. || iscntrl(workdata->buf[l - 1])) {
  5341. l--;
  5342. workdata->buf[l] = 0;
  5343. } else
  5344. break;
  5345. }
  5346. if (l < 1) {
  5347. continue;
  5348. }
  5349. workdata->f_user = workdata->buf;
  5350. if (workdata->f_user[0] == ':') {
  5351. /* user names may not contain a ':' and may not be empty,
  5352. * so lines starting with ':' may be used for a special purpose */
  5353. if (workdata->f_user[1] == '#') {
  5354. /* :# is a comment */
  5355. continue;
  5356. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  5357. if (mg_fopen(workdata->conn,
  5358. workdata->f_user + 9,
  5359. MG_FOPEN_MODE_READ,
  5360. &fp)) {
  5361. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  5362. (void)mg_fclose(
  5363. &fp.access); /* ignore error on read only file */
  5364. /* No need to continue processing files once we have a
  5365. * match, since nothing will reset it back
  5366. * to 0.
  5367. */
  5368. if (is_authorized) {
  5369. return is_authorized;
  5370. }
  5371. } else {
  5372. mg_cry(workdata->conn,
  5373. "%s: cannot open authorization file: %s",
  5374. __func__,
  5375. workdata->buf);
  5376. }
  5377. continue;
  5378. }
  5379. /* everything is invalid for the moment (might change in the
  5380. * future) */
  5381. mg_cry(workdata->conn,
  5382. "%s: syntax error in authorization file: %s",
  5383. __func__,
  5384. workdata->buf);
  5385. continue;
  5386. }
  5387. workdata->f_domain = strchr(workdata->f_user, ':');
  5388. if (workdata->f_domain == NULL) {
  5389. mg_cry(workdata->conn,
  5390. "%s: syntax error in authorization file: %s",
  5391. __func__,
  5392. workdata->buf);
  5393. continue;
  5394. }
  5395. *(workdata->f_domain) = 0;
  5396. (workdata->f_domain)++;
  5397. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  5398. if (workdata->f_ha1 == NULL) {
  5399. mg_cry(workdata->conn,
  5400. "%s: syntax error in authorization file: %s",
  5401. __func__,
  5402. workdata->buf);
  5403. continue;
  5404. }
  5405. *(workdata->f_ha1) = 0;
  5406. (workdata->f_ha1)++;
  5407. if (!strcmp(workdata->ah.user, workdata->f_user)
  5408. && !strcmp(workdata->domain, workdata->f_domain)) {
  5409. return check_password(workdata->conn->request_info.request_method,
  5410. workdata->f_ha1,
  5411. workdata->ah.uri,
  5412. workdata->ah.nonce,
  5413. workdata->ah.nc,
  5414. workdata->ah.cnonce,
  5415. workdata->ah.qop,
  5416. workdata->ah.response);
  5417. }
  5418. }
  5419. return is_authorized;
  5420. }
  5421. /* Authorize against the opened passwords file. Return 1 if authorized. */
  5422. static int
  5423. authorize(struct mg_connection *conn, struct mg_file *filep)
  5424. {
  5425. struct read_auth_file_struct workdata;
  5426. char buf[MG_BUF_LEN];
  5427. if (!conn || !conn->ctx) {
  5428. return 0;
  5429. }
  5430. memset(&workdata, 0, sizeof(workdata));
  5431. workdata.conn = conn;
  5432. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  5433. return 0;
  5434. }
  5435. workdata.domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  5436. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  5437. }
  5438. /* Return 1 if request is authorised, 0 otherwise. */
  5439. static int
  5440. check_authorization(struct mg_connection *conn, const char *path)
  5441. {
  5442. char fname[PATH_MAX];
  5443. struct vec uri_vec, filename_vec;
  5444. const char *list;
  5445. struct mg_file file = STRUCT_FILE_INITIALIZER;
  5446. int authorized = 1, truncated;
  5447. if (!conn || !conn->ctx) {
  5448. return 0;
  5449. }
  5450. list = conn->ctx->config[PROTECT_URI];
  5451. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  5452. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  5453. mg_snprintf(conn,
  5454. &truncated,
  5455. fname,
  5456. sizeof(fname),
  5457. "%.*s",
  5458. (int)filename_vec.len,
  5459. filename_vec.ptr);
  5460. if (truncated
  5461. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  5462. mg_cry(conn,
  5463. "%s: cannot open %s: %s",
  5464. __func__,
  5465. fname,
  5466. strerror(errno));
  5467. }
  5468. break;
  5469. }
  5470. }
  5471. if (!is_file_opened(&file.access)) {
  5472. open_auth_file(conn, path, &file);
  5473. }
  5474. if (is_file_opened(&file.access)) {
  5475. authorized = authorize(conn, &file);
  5476. (void)mg_fclose(&file.access); /* ignore error on read only file */
  5477. }
  5478. return authorized;
  5479. }
  5480. static void
  5481. send_authorization_request(struct mg_connection *conn)
  5482. {
  5483. char date[64];
  5484. time_t curtime = time(NULL);
  5485. if (conn && conn->ctx) {
  5486. uint64_t nonce = (uint64_t)(conn->ctx->start_time);
  5487. (void)pthread_mutex_lock(&conn->ctx->nonce_mutex);
  5488. nonce += conn->ctx->nonce_count;
  5489. ++conn->ctx->nonce_count;
  5490. (void)pthread_mutex_unlock(&conn->ctx->nonce_mutex);
  5491. nonce ^= conn->ctx->auth_nonce_mask;
  5492. conn->status_code = 401;
  5493. conn->must_close = 1;
  5494. gmt_time_string(date, sizeof(date), &curtime);
  5495. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  5496. send_no_cache_header(conn);
  5497. mg_printf(conn,
  5498. "Date: %s\r\n"
  5499. "Connection: %s\r\n"
  5500. "Content-Length: 0\r\n"
  5501. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  5502. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  5503. date,
  5504. suggest_connection_header(conn),
  5505. conn->ctx->config[AUTHENTICATION_DOMAIN],
  5506. nonce);
  5507. }
  5508. }
  5509. #if !defined(NO_FILES)
  5510. static int
  5511. is_authorized_for_put(struct mg_connection *conn)
  5512. {
  5513. if (conn) {
  5514. struct mg_file file = STRUCT_FILE_INITIALIZER;
  5515. const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
  5516. int ret = 0;
  5517. if (passfile != NULL
  5518. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  5519. ret = authorize(conn, &file);
  5520. (void)mg_fclose(&file.access); /* ignore error on read only file */
  5521. }
  5522. return ret;
  5523. }
  5524. return 0;
  5525. }
  5526. #endif
  5527. int
  5528. mg_modify_passwords_file(const char *fname,
  5529. const char *domain,
  5530. const char *user,
  5531. const char *pass)
  5532. {
  5533. int found, i;
  5534. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  5535. FILE *fp, *fp2;
  5536. found = 0;
  5537. fp = fp2 = NULL;
  5538. /* Regard empty password as no password - remove user record. */
  5539. if (pass != NULL && pass[0] == '\0') {
  5540. pass = NULL;
  5541. }
  5542. /* Other arguments must not be empty */
  5543. if (fname == NULL || domain == NULL || user == NULL) {
  5544. return 0;
  5545. }
  5546. /* Using the given file format, user name and domain must not contain ':'
  5547. */
  5548. if (strchr(user, ':') != NULL) {
  5549. return 0;
  5550. }
  5551. if (strchr(domain, ':') != NULL) {
  5552. return 0;
  5553. }
  5554. /* Do not allow control characters like newline in user name and domain.
  5555. * Do not allow excessively long names either. */
  5556. for (i = 0; i < 255 && user[i] != 0; i++) {
  5557. if (iscntrl(user[i])) {
  5558. return 0;
  5559. }
  5560. }
  5561. if (user[i]) {
  5562. return 0;
  5563. }
  5564. for (i = 0; i < 255 && domain[i] != 0; i++) {
  5565. if (iscntrl(domain[i])) {
  5566. return 0;
  5567. }
  5568. }
  5569. if (domain[i]) {
  5570. return 0;
  5571. }
  5572. /* The maximum length of the path to the password file is limited */
  5573. if ((strlen(fname) + 4) >= PATH_MAX) {
  5574. return 0;
  5575. }
  5576. /* Create a temporary file name. Length has been checked before. */
  5577. strcpy(tmp, fname);
  5578. strcat(tmp, ".tmp");
  5579. /* Create the file if does not exist */
  5580. /* Use of fopen here is OK, since fname is only ASCII */
  5581. if ((fp = fopen(fname, "a+")) != NULL) {
  5582. (void)fclose(fp);
  5583. }
  5584. /* Open the given file and temporary file */
  5585. if ((fp = fopen(fname, "r")) == NULL) {
  5586. return 0;
  5587. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  5588. fclose(fp);
  5589. return 0;
  5590. }
  5591. /* Copy the stuff to temporary file */
  5592. while (fgets(line, sizeof(line), fp) != NULL) {
  5593. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  5594. continue;
  5595. }
  5596. u[255] = 0;
  5597. d[255] = 0;
  5598. if (!strcmp(u, user) && !strcmp(d, domain)) {
  5599. found++;
  5600. if (pass != NULL) {
  5601. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  5602. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  5603. }
  5604. } else {
  5605. fprintf(fp2, "%s", line);
  5606. }
  5607. }
  5608. /* If new user, just add it */
  5609. if (!found && pass != NULL) {
  5610. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  5611. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  5612. }
  5613. /* Close files */
  5614. fclose(fp);
  5615. fclose(fp2);
  5616. /* Put the temp file in place of real file */
  5617. IGNORE_UNUSED_RESULT(remove(fname));
  5618. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  5619. return 1;
  5620. }
  5621. static int
  5622. is_valid_port(unsigned long port)
  5623. {
  5624. return port < 0xffff;
  5625. }
  5626. static int
  5627. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  5628. {
  5629. struct addrinfo hints, *res, *ressave;
  5630. int func_ret = 0;
  5631. int gai_ret;
  5632. memset(&hints, 0, sizeof(struct addrinfo));
  5633. hints.ai_family = af;
  5634. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  5635. if (gai_ret != 0) {
  5636. /* gai_strerror could be used to convert gai_ret to a string */
  5637. /* POSIX return values: see
  5638. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  5639. */
  5640. /* Windows return values: see
  5641. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  5642. */
  5643. return 0;
  5644. }
  5645. ressave = res;
  5646. while (res) {
  5647. if (dstlen >= res->ai_addrlen) {
  5648. memcpy(dst, res->ai_addr, res->ai_addrlen);
  5649. func_ret = 1;
  5650. }
  5651. res = res->ai_next;
  5652. }
  5653. freeaddrinfo(ressave);
  5654. return func_ret;
  5655. }
  5656. static int
  5657. connect_socket(struct mg_context *ctx /* may be NULL */,
  5658. const char *host,
  5659. int port,
  5660. int use_ssl,
  5661. char *ebuf,
  5662. size_t ebuf_len,
  5663. SOCKET *sock /* output: socket, must not be NULL */,
  5664. union usa *sa /* output: socket address, must not be NULL */
  5665. )
  5666. {
  5667. int ip_ver = 0;
  5668. *sock = INVALID_SOCKET;
  5669. memset(sa, 0, sizeof(*sa));
  5670. if (ebuf_len > 0) {
  5671. *ebuf = 0;
  5672. }
  5673. if (host == NULL) {
  5674. mg_snprintf(NULL,
  5675. NULL, /* No truncation check for ebuf */
  5676. ebuf,
  5677. ebuf_len,
  5678. "%s",
  5679. "NULL host");
  5680. return 0;
  5681. }
  5682. if (port < 0 || !is_valid_port((unsigned)port)) {
  5683. mg_snprintf(NULL,
  5684. NULL, /* No truncation check for ebuf */
  5685. ebuf,
  5686. ebuf_len,
  5687. "%s",
  5688. "invalid port");
  5689. return 0;
  5690. }
  5691. #if !defined(NO_SSL)
  5692. if (use_ssl && (SSLv23_client_method == NULL)) {
  5693. mg_snprintf(NULL,
  5694. NULL, /* No truncation check for ebuf */
  5695. ebuf,
  5696. ebuf_len,
  5697. "%s",
  5698. "SSL is not initialized");
  5699. return 0;
  5700. }
  5701. #else
  5702. (void)use_ssl;
  5703. #endif
  5704. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  5705. sa->sin.sin_port = htons((uint16_t)port);
  5706. ip_ver = 4;
  5707. #ifdef USE_IPV6
  5708. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  5709. sa->sin6.sin6_port = htons((uint16_t)port);
  5710. ip_ver = 6;
  5711. } else if (host[0] == '[') {
  5712. /* While getaddrinfo on Windows will work with [::1],
  5713. * getaddrinfo on Linux only works with ::1 (without []). */
  5714. size_t l = strlen(host + 1);
  5715. char *h = (l > 1) ? mg_strdup(host + 1) : NULL;
  5716. if (h) {
  5717. h[l - 1] = 0;
  5718. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  5719. sa->sin6.sin6_port = htons((uint16_t)port);
  5720. ip_ver = 6;
  5721. }
  5722. mg_free(h);
  5723. }
  5724. #endif
  5725. }
  5726. if (ip_ver == 0) {
  5727. mg_snprintf(NULL,
  5728. NULL, /* No truncation check for ebuf */
  5729. ebuf,
  5730. ebuf_len,
  5731. "%s",
  5732. "host not found");
  5733. return 0;
  5734. }
  5735. if (ip_ver == 4) {
  5736. *sock = socket(PF_INET, SOCK_STREAM, 0);
  5737. }
  5738. #ifdef USE_IPV6
  5739. else if (ip_ver == 6) {
  5740. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  5741. }
  5742. #endif
  5743. if (*sock == INVALID_SOCKET) {
  5744. mg_snprintf(NULL,
  5745. NULL, /* No truncation check for ebuf */
  5746. ebuf,
  5747. ebuf_len,
  5748. "socket(): %s",
  5749. strerror(ERRNO));
  5750. return 0;
  5751. }
  5752. set_close_on_exec(*sock, fc(ctx));
  5753. if ((ip_ver == 4)
  5754. && (connect(*sock, (struct sockaddr *)&sa->sin, sizeof(sa->sin))
  5755. == 0)) {
  5756. /* connected with IPv4 */
  5757. set_blocking_mode(*sock, 0);
  5758. return 1;
  5759. }
  5760. #ifdef USE_IPV6
  5761. if ((ip_ver == 6)
  5762. && (connect(*sock, (struct sockaddr *)&sa->sin6, sizeof(sa->sin6))
  5763. == 0)) {
  5764. /* connected with IPv6 */
  5765. set_blocking_mode(*sock, 0);
  5766. return 1;
  5767. }
  5768. #endif
  5769. /* Not connected */
  5770. mg_snprintf(NULL,
  5771. NULL, /* No truncation check for ebuf */
  5772. ebuf,
  5773. ebuf_len,
  5774. "connect(%s:%d): %s",
  5775. host,
  5776. port,
  5777. strerror(ERRNO));
  5778. closesocket(*sock);
  5779. *sock = INVALID_SOCKET;
  5780. return 0;
  5781. }
  5782. int
  5783. mg_url_encode(const char *src, char *dst, size_t dst_len)
  5784. {
  5785. static const char *dont_escape = "._-$,;~()";
  5786. static const char *hex = "0123456789abcdef";
  5787. char *pos = dst;
  5788. const char *end = dst + dst_len - 1;
  5789. for (; *src != '\0' && pos < end; src++, pos++) {
  5790. if (isalnum(*(const unsigned char *)src)
  5791. || strchr(dont_escape, *(const unsigned char *)src) != NULL) {
  5792. *pos = *src;
  5793. } else if (pos + 2 < end) {
  5794. pos[0] = '%';
  5795. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  5796. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  5797. pos += 2;
  5798. } else {
  5799. break;
  5800. }
  5801. }
  5802. *pos = '\0';
  5803. return (*src == '\0') ? (int)(pos - dst) : -1;
  5804. }
  5805. static void
  5806. print_dir_entry(struct de *de)
  5807. {
  5808. char size[64], mod[64], href[PATH_MAX * 3 /* worst case */];
  5809. struct tm *tm;
  5810. if (de->file.is_directory) {
  5811. mg_snprintf(de->conn,
  5812. NULL, /* Buffer is big enough */
  5813. size,
  5814. sizeof(size),
  5815. "%s",
  5816. "[DIRECTORY]");
  5817. } else {
  5818. /* We use (signed) cast below because MSVC 6 compiler cannot
  5819. * convert unsigned __int64 to double. Sigh. */
  5820. if (de->file.size < 1024) {
  5821. mg_snprintf(de->conn,
  5822. NULL, /* Buffer is big enough */
  5823. size,
  5824. sizeof(size),
  5825. "%d",
  5826. (int)de->file.size);
  5827. } else if (de->file.size < 0x100000) {
  5828. mg_snprintf(de->conn,
  5829. NULL, /* Buffer is big enough */
  5830. size,
  5831. sizeof(size),
  5832. "%.1fk",
  5833. (double)de->file.size / 1024.0);
  5834. } else if (de->file.size < 0x40000000) {
  5835. mg_snprintf(de->conn,
  5836. NULL, /* Buffer is big enough */
  5837. size,
  5838. sizeof(size),
  5839. "%.1fM",
  5840. (double)de->file.size / 1048576);
  5841. } else {
  5842. mg_snprintf(de->conn,
  5843. NULL, /* Buffer is big enough */
  5844. size,
  5845. sizeof(size),
  5846. "%.1fG",
  5847. (double)de->file.size / 1073741824);
  5848. }
  5849. }
  5850. /* Note: mg_snprintf will not cause a buffer overflow above.
  5851. * So, string truncation checks are not required here. */
  5852. tm = localtime(&de->file.last_modified);
  5853. if (tm != NULL) {
  5854. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  5855. } else {
  5856. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  5857. mod[sizeof(mod) - 1] = '\0';
  5858. }
  5859. mg_url_encode(de->file_name, href, sizeof(href));
  5860. de->conn->num_bytes_sent +=
  5861. mg_printf(de->conn,
  5862. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  5863. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  5864. de->conn->request_info.local_uri,
  5865. href,
  5866. de->file.is_directory ? "/" : "",
  5867. de->file_name,
  5868. de->file.is_directory ? "/" : "",
  5869. mod,
  5870. size);
  5871. }
  5872. /* This function is called from send_directory() and used for
  5873. * sorting directory entries by size, or name, or modification time.
  5874. * On windows, __cdecl specification is needed in case if project is built
  5875. * with __stdcall convention. qsort always requires __cdels callback. */
  5876. static int WINCDECL
  5877. compare_dir_entries(const void *p1, const void *p2)
  5878. {
  5879. if (p1 && p2) {
  5880. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  5881. const char *query_string = a->conn->request_info.query_string;
  5882. int cmp_result = 0;
  5883. if (query_string == NULL) {
  5884. query_string = "na";
  5885. }
  5886. if (a->file.is_directory && !b->file.is_directory) {
  5887. return -1; /* Always put directories on top */
  5888. } else if (!a->file.is_directory && b->file.is_directory) {
  5889. return 1; /* Always put directories on top */
  5890. } else if (*query_string == 'n') {
  5891. cmp_result = strcmp(a->file_name, b->file_name);
  5892. } else if (*query_string == 's') {
  5893. cmp_result = (a->file.size == b->file.size)
  5894. ? 0
  5895. : ((a->file.size > b->file.size) ? 1 : -1);
  5896. } else if (*query_string == 'd') {
  5897. cmp_result =
  5898. (a->file.last_modified == b->file.last_modified)
  5899. ? 0
  5900. : ((a->file.last_modified > b->file.last_modified) ? 1
  5901. : -1);
  5902. }
  5903. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  5904. }
  5905. return 0;
  5906. }
  5907. static int
  5908. must_hide_file(struct mg_connection *conn, const char *path)
  5909. {
  5910. if (conn && conn->ctx) {
  5911. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  5912. const char *pattern = conn->ctx->config[HIDE_FILES];
  5913. return match_prefix(pw_pattern, strlen(pw_pattern), path) > 0
  5914. || (pattern != NULL
  5915. && match_prefix(pattern, strlen(pattern), path) > 0);
  5916. }
  5917. return 0;
  5918. }
  5919. static int
  5920. scan_directory(struct mg_connection *conn,
  5921. const char *dir,
  5922. void *data,
  5923. void (*cb)(struct de *, void *))
  5924. {
  5925. char path[PATH_MAX];
  5926. struct dirent *dp;
  5927. DIR *dirp;
  5928. struct de de;
  5929. int truncated;
  5930. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  5931. return 0;
  5932. } else {
  5933. de.conn = conn;
  5934. while ((dp = mg_readdir(dirp)) != NULL) {
  5935. /* Do not show current dir and hidden files */
  5936. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  5937. || must_hide_file(conn, dp->d_name)) {
  5938. continue;
  5939. }
  5940. mg_snprintf(
  5941. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  5942. /* If we don't memset stat structure to zero, mtime will have
  5943. * garbage and strftime() will segfault later on in
  5944. * print_dir_entry(). memset is required only if mg_stat()
  5945. * fails. For more details, see
  5946. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  5947. memset(&de.file, 0, sizeof(de.file));
  5948. if (truncated) {
  5949. /* If the path is not complete, skip processing. */
  5950. continue;
  5951. }
  5952. if (!mg_stat(conn, path, &de.file)) {
  5953. mg_cry(conn,
  5954. "%s: mg_stat(%s) failed: %s",
  5955. __func__,
  5956. path,
  5957. strerror(ERRNO));
  5958. }
  5959. de.file_name = dp->d_name;
  5960. cb(&de, data);
  5961. }
  5962. (void)mg_closedir(dirp);
  5963. }
  5964. return 1;
  5965. }
  5966. #if !defined(NO_FILES)
  5967. static int
  5968. remove_directory(struct mg_connection *conn, const char *dir)
  5969. {
  5970. char path[PATH_MAX];
  5971. struct dirent *dp;
  5972. DIR *dirp;
  5973. struct de de;
  5974. int truncated;
  5975. int ok = 1;
  5976. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  5977. return 0;
  5978. } else {
  5979. de.conn = conn;
  5980. while ((dp = mg_readdir(dirp)) != NULL) {
  5981. /* Do not show current dir (but show hidden files as they will
  5982. * also be removed) */
  5983. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  5984. continue;
  5985. }
  5986. mg_snprintf(
  5987. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  5988. /* If we don't memset stat structure to zero, mtime will have
  5989. * garbage and strftime() will segfault later on in
  5990. * print_dir_entry(). memset is required only if mg_stat()
  5991. * fails. For more details, see
  5992. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  5993. memset(&de.file, 0, sizeof(de.file));
  5994. if (truncated) {
  5995. /* Do not delete anything shorter */
  5996. ok = 0;
  5997. continue;
  5998. }
  5999. if (!mg_stat(conn, path, &de.file)) {
  6000. mg_cry(conn,
  6001. "%s: mg_stat(%s) failed: %s",
  6002. __func__,
  6003. path,
  6004. strerror(ERRNO));
  6005. ok = 0;
  6006. }
  6007. if (de.file.is_directory) {
  6008. if (remove_directory(conn, path) == 0) {
  6009. ok = 0;
  6010. }
  6011. } else {
  6012. /* This will fail file is the file is in memory */
  6013. if (mg_remove(conn, path) == 0) {
  6014. ok = 0;
  6015. }
  6016. }
  6017. }
  6018. (void)mg_closedir(dirp);
  6019. IGNORE_UNUSED_RESULT(rmdir(dir));
  6020. }
  6021. return ok;
  6022. }
  6023. #endif
  6024. struct dir_scan_data {
  6025. struct de *entries;
  6026. unsigned int num_entries;
  6027. unsigned int arr_size;
  6028. };
  6029. /* Behaves like realloc(), but frees original pointer on failure */
  6030. static void *
  6031. realloc2(void *ptr, size_t size)
  6032. {
  6033. void *new_ptr = mg_realloc(ptr, size);
  6034. if (new_ptr == NULL) {
  6035. mg_free(ptr);
  6036. }
  6037. return new_ptr;
  6038. }
  6039. static void
  6040. dir_scan_callback(struct de *de, void *data)
  6041. {
  6042. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  6043. if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {
  6044. dsd->arr_size *= 2;
  6045. dsd->entries =
  6046. (struct de *)realloc2(dsd->entries,
  6047. dsd->arr_size * sizeof(dsd->entries[0]));
  6048. }
  6049. if (dsd->entries == NULL) {
  6050. /* TODO(lsm, low): propagate an error to the caller */
  6051. dsd->num_entries = 0;
  6052. } else {
  6053. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  6054. dsd->entries[dsd->num_entries].file = de->file;
  6055. dsd->entries[dsd->num_entries].conn = de->conn;
  6056. dsd->num_entries++;
  6057. }
  6058. }
  6059. static void
  6060. handle_directory_request(struct mg_connection *conn, const char *dir)
  6061. {
  6062. unsigned int i;
  6063. int sort_direction;
  6064. struct dir_scan_data data = {NULL, 0, 128};
  6065. char date[64];
  6066. time_t curtime = time(NULL);
  6067. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  6068. send_http_error(conn,
  6069. 500,
  6070. "Error: Cannot open directory\nopendir(%s): %s",
  6071. dir,
  6072. strerror(ERRNO));
  6073. return;
  6074. }
  6075. gmt_time_string(date, sizeof(date), &curtime);
  6076. if (!conn) {
  6077. return;
  6078. }
  6079. sort_direction = ((conn->request_info.query_string != NULL)
  6080. && (conn->request_info.query_string[1] == 'd'))
  6081. ? 'a'
  6082. : 'd';
  6083. conn->must_close = 1;
  6084. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  6085. send_static_cache_header(conn);
  6086. mg_printf(conn,
  6087. "Date: %s\r\n"
  6088. "Connection: close\r\n"
  6089. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  6090. date);
  6091. conn->num_bytes_sent +=
  6092. mg_printf(conn,
  6093. "<html><head><title>Index of %s</title>"
  6094. "<style>th {text-align: left;}</style></head>"
  6095. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  6096. "<tr><th><a href=\"?n%c\">Name</a></th>"
  6097. "<th><a href=\"?d%c\">Modified</a></th>"
  6098. "<th><a href=\"?s%c\">Size</a></th></tr>"
  6099. "<tr><td colspan=\"3\"><hr></td></tr>",
  6100. conn->request_info.local_uri,
  6101. conn->request_info.local_uri,
  6102. sort_direction,
  6103. sort_direction,
  6104. sort_direction);
  6105. /* Print first entry - link to a parent directory */
  6106. conn->num_bytes_sent +=
  6107. mg_printf(conn,
  6108. "<tr><td><a href=\"%s%s\">%s</a></td>"
  6109. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  6110. conn->request_info.local_uri,
  6111. "..",
  6112. "Parent directory",
  6113. "-",
  6114. "-");
  6115. /* Sort and print directory entries */
  6116. if (data.entries != NULL) {
  6117. qsort(data.entries,
  6118. (size_t)data.num_entries,
  6119. sizeof(data.entries[0]),
  6120. compare_dir_entries);
  6121. for (i = 0; i < data.num_entries; i++) {
  6122. print_dir_entry(&data.entries[i]);
  6123. mg_free(data.entries[i].file_name);
  6124. }
  6125. mg_free(data.entries);
  6126. }
  6127. conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");
  6128. conn->status_code = 200;
  6129. }
  6130. /* Send len bytes from the opened file to the client. */
  6131. static void
  6132. send_file_data(struct mg_connection *conn,
  6133. struct mg_file *filep,
  6134. int64_t offset,
  6135. int64_t len)
  6136. {
  6137. char buf[MG_BUF_LEN];
  6138. int to_read, num_read, num_written;
  6139. int64_t size;
  6140. if (!filep || !conn) {
  6141. return;
  6142. }
  6143. /* Sanity check the offset */
  6144. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  6145. : (int64_t)(filep->stat.size);
  6146. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  6147. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  6148. /* file stored in memory */
  6149. if (len > size - offset) {
  6150. len = size - offset;
  6151. }
  6152. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  6153. } else if (len > 0 && filep->access.fp != NULL) {
  6154. /* file stored on disk */
  6155. #if defined(__linux__)
  6156. /* sendfile is only available for Linux */
  6157. if ((conn->ssl == 0) && (conn->throttle == 0)
  6158. && (!mg_strcasecmp(conn->ctx->config[ALLOW_SENDFILE_CALL],
  6159. "yes"))) {
  6160. off_t sf_offs = (off_t)offset;
  6161. ssize_t sf_sent;
  6162. int sf_file = fileno(filep->access.fp);
  6163. int loop_cnt = 0;
  6164. do {
  6165. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  6166. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  6167. size_t sf_tosend =
  6168. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  6169. sf_sent =
  6170. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  6171. if (sf_sent > 0) {
  6172. conn->num_bytes_sent += sf_sent;
  6173. len -= sf_sent;
  6174. offset += sf_sent;
  6175. } else if (loop_cnt == 0) {
  6176. /* This file can not be sent using sendfile.
  6177. * This might be the case for pseudo-files in the
  6178. * /sys/ and /proc/ file system.
  6179. * Use the regular user mode copy code instead. */
  6180. break;
  6181. } else if (sf_sent == 0) {
  6182. /* No error, but 0 bytes sent. May be EOF? */
  6183. return;
  6184. }
  6185. loop_cnt++;
  6186. } while ((len > 0) && (sf_sent >= 0));
  6187. if (sf_sent > 0) {
  6188. return; /* OK */
  6189. }
  6190. /* sf_sent<0 means error, thus fall back to the classic way */
  6191. /* This is always the case, if sf_file is not a "normal" file,
  6192. * e.g., for sending data from the output of a CGI process. */
  6193. offset = (int64_t)sf_offs;
  6194. }
  6195. #endif
  6196. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  6197. mg_cry(conn, "%s: fseeko() failed: %s", __func__, strerror(ERRNO));
  6198. send_http_error(
  6199. conn,
  6200. 500,
  6201. "%s",
  6202. "Error: Unable to access file at requested position.");
  6203. } else {
  6204. while (len > 0) {
  6205. /* Calculate how much to read from the file in the buffer */
  6206. to_read = sizeof(buf);
  6207. if ((int64_t)to_read > len) {
  6208. to_read = (int)len;
  6209. }
  6210. /* Read from file, exit the loop on error */
  6211. if ((num_read =
  6212. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  6213. <= 0) {
  6214. break;
  6215. }
  6216. /* Send read bytes to the client, exit the loop on error */
  6217. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  6218. != num_read) {
  6219. break;
  6220. }
  6221. /* Both read and were successful, adjust counters */
  6222. conn->num_bytes_sent += num_written;
  6223. len -= num_written;
  6224. }
  6225. }
  6226. }
  6227. }
  6228. static int
  6229. parse_range_header(const char *header, int64_t *a, int64_t *b)
  6230. {
  6231. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  6232. }
  6233. static void
  6234. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  6235. {
  6236. if (filestat != NULL && buf != NULL) {
  6237. mg_snprintf(NULL,
  6238. NULL, /* All calls to construct_etag use 64 byte buffer */
  6239. buf,
  6240. buf_len,
  6241. "\"%lx.%" INT64_FMT "\"",
  6242. (unsigned long)filestat->last_modified,
  6243. filestat->size);
  6244. }
  6245. }
  6246. static void
  6247. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  6248. {
  6249. if (filep != NULL && filep->fp != NULL) {
  6250. #ifdef _WIN32
  6251. (void)conn; /* Unused. */
  6252. #else
  6253. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  6254. mg_cry(conn,
  6255. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  6256. __func__,
  6257. strerror(ERRNO));
  6258. }
  6259. #endif
  6260. }
  6261. }
  6262. static void
  6263. handle_static_file_request(struct mg_connection *conn,
  6264. const char *path,
  6265. struct mg_file *filep,
  6266. const char *mime_type,
  6267. const char *additional_headers)
  6268. {
  6269. char date[64], lm[64], etag[64];
  6270. char range[128]; /* large enough, so there will be no overflow */
  6271. const char *msg = "OK", *hdr;
  6272. time_t curtime = time(NULL);
  6273. int64_t cl, r1, r2;
  6274. struct vec mime_vec;
  6275. int n, truncated;
  6276. char gz_path[PATH_MAX];
  6277. const char *encoding = "";
  6278. const char *cors1, *cors2, *cors3;
  6279. if (conn == NULL || conn->ctx == NULL || filep == NULL) {
  6280. return;
  6281. }
  6282. if (mime_type == NULL) {
  6283. get_mime_type(conn->ctx, path, &mime_vec);
  6284. } else {
  6285. mime_vec.ptr = mime_type;
  6286. mime_vec.len = strlen(mime_type);
  6287. }
  6288. if (filep->stat.size > INT64_MAX) {
  6289. send_http_error(conn,
  6290. 500,
  6291. "Error: File size is too large to send\n%" INT64_FMT,
  6292. filep->stat.size);
  6293. }
  6294. cl = (int64_t)filep->stat.size;
  6295. conn->status_code = 200;
  6296. range[0] = '\0';
  6297. /* if this file is in fact a pre-gzipped file, rewrite its filename
  6298. * it's important to rewrite the filename after resolving
  6299. * the mime type from it, to preserve the actual file's type */
  6300. if (filep->stat.is_gzipped) {
  6301. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  6302. if (truncated) {
  6303. send_http_error(conn,
  6304. 500,
  6305. "Error: Path of zipped file too long (%s)",
  6306. path);
  6307. return;
  6308. }
  6309. path = gz_path;
  6310. encoding = "Content-Encoding: gzip\r\n";
  6311. }
  6312. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  6313. send_http_error(conn,
  6314. 500,
  6315. "Error: Cannot open file\nfopen(%s): %s",
  6316. path,
  6317. strerror(ERRNO));
  6318. return;
  6319. }
  6320. fclose_on_exec(&filep->access, conn);
  6321. /* If Range: header specified, act accordingly */
  6322. r1 = r2 = 0;
  6323. hdr = mg_get_header(conn, "Range");
  6324. if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 && r1 >= 0
  6325. && r2 >= 0) {
  6326. /* actually, range requests don't play well with a pre-gzipped
  6327. * file (since the range is specified in the uncompressed space) */
  6328. if (filep->stat.is_gzipped) {
  6329. send_http_error(
  6330. conn,
  6331. 501,
  6332. "%s",
  6333. "Error: Range requests in gzipped files are not supported");
  6334. (void)mg_fclose(
  6335. &filep->access); /* ignore error on read only file */
  6336. return;
  6337. }
  6338. conn->status_code = 206;
  6339. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  6340. mg_snprintf(conn,
  6341. NULL, /* range buffer is big enough */
  6342. range,
  6343. sizeof(range),
  6344. "Content-Range: bytes "
  6345. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  6346. r1,
  6347. r1 + cl - 1,
  6348. filep->stat.size);
  6349. msg = "Partial Content";
  6350. }
  6351. hdr = mg_get_header(conn, "Origin");
  6352. if (hdr) {
  6353. /* Cross-origin resource sharing (CORS), see
  6354. * http://www.html5rocks.com/en/tutorials/cors/,
  6355. * http://www.html5rocks.com/static/images/cors_server_flowchart.png -
  6356. * preflight is not supported for files. */
  6357. cors1 = "Access-Control-Allow-Origin: ";
  6358. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  6359. cors3 = "\r\n";
  6360. } else {
  6361. cors1 = cors2 = cors3 = "";
  6362. }
  6363. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
  6364. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  6365. gmt_time_string(date, sizeof(date), &curtime);
  6366. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  6367. construct_etag(etag, sizeof(etag), &filep->stat);
  6368. (void)mg_printf(conn,
  6369. "HTTP/1.1 %d %s\r\n"
  6370. "%s%s%s"
  6371. "Date: %s\r\n",
  6372. conn->status_code,
  6373. msg,
  6374. cors1,
  6375. cors2,
  6376. cors3,
  6377. date);
  6378. send_static_cache_header(conn);
  6379. (void)mg_printf(conn,
  6380. "Last-Modified: %s\r\n"
  6381. "Etag: %s\r\n"
  6382. "Content-Type: %.*s\r\n"
  6383. "Content-Length: %" INT64_FMT "\r\n"
  6384. "Connection: %s\r\n"
  6385. "Accept-Ranges: bytes\r\n"
  6386. "%s%s",
  6387. lm,
  6388. etag,
  6389. (int)mime_vec.len,
  6390. mime_vec.ptr,
  6391. cl,
  6392. suggest_connection_header(conn),
  6393. range,
  6394. encoding);
  6395. /* The previous code must not add any header starting with X- to make
  6396. * sure no one of the additional_headers is included twice */
  6397. if (additional_headers != NULL) {
  6398. (void)mg_printf(conn,
  6399. "%.*s\r\n\r\n",
  6400. (int)strlen(additional_headers),
  6401. additional_headers);
  6402. } else {
  6403. (void)mg_printf(conn, "\r\n");
  6404. }
  6405. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  6406. send_file_data(conn, filep, r1, cl);
  6407. }
  6408. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  6409. }
  6410. #if !defined(NO_CACHING)
  6411. static void
  6412. handle_not_modified_static_file_request(struct mg_connection *conn,
  6413. struct mg_file *filep)
  6414. {
  6415. char date[64], lm[64], etag[64];
  6416. time_t curtime = time(NULL);
  6417. if (conn == NULL || filep == NULL) {
  6418. return;
  6419. }
  6420. conn->status_code = 304;
  6421. gmt_time_string(date, sizeof(date), &curtime);
  6422. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  6423. construct_etag(etag, sizeof(etag), &filep->stat);
  6424. (void)mg_printf(conn,
  6425. "HTTP/1.1 %d %s\r\n"
  6426. "Date: %s\r\n",
  6427. conn->status_code,
  6428. mg_get_response_code_text(conn, conn->status_code),
  6429. date);
  6430. send_static_cache_header(conn);
  6431. (void)mg_printf(conn,
  6432. "Last-Modified: %s\r\n"
  6433. "Etag: %s\r\n"
  6434. "Connection: %s\r\n"
  6435. "\r\n",
  6436. lm,
  6437. etag,
  6438. suggest_connection_header(conn));
  6439. }
  6440. #endif
  6441. void
  6442. mg_send_file(struct mg_connection *conn, const char *path)
  6443. {
  6444. mg_send_mime_file(conn, path, NULL);
  6445. }
  6446. void
  6447. mg_send_mime_file(struct mg_connection *conn,
  6448. const char *path,
  6449. const char *mime_type)
  6450. {
  6451. mg_send_mime_file2(conn, path, mime_type, NULL);
  6452. }
  6453. void
  6454. mg_send_mime_file2(struct mg_connection *conn,
  6455. const char *path,
  6456. const char *mime_type,
  6457. const char *additional_headers)
  6458. {
  6459. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6460. if (mg_stat(conn, path, &file.stat)) {
  6461. if (file.stat.is_directory) {
  6462. if (!conn) {
  6463. return;
  6464. }
  6465. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  6466. "yes")) {
  6467. handle_directory_request(conn, path);
  6468. } else {
  6469. send_http_error(conn,
  6470. 403,
  6471. "%s",
  6472. "Error: Directory listing denied");
  6473. }
  6474. } else {
  6475. handle_static_file_request(
  6476. conn, path, &file, mime_type, additional_headers);
  6477. }
  6478. } else {
  6479. send_http_error(conn, 404, "%s", "Error: File not found");
  6480. }
  6481. }
  6482. /* For a given PUT path, create all intermediate subdirectories.
  6483. * Return 0 if the path itself is a directory.
  6484. * Return 1 if the path leads to a file.
  6485. * Return -1 for if the path is too long.
  6486. * Return -2 if path can not be created.
  6487. */
  6488. static int
  6489. put_dir(struct mg_connection *conn, const char *path)
  6490. {
  6491. char buf[PATH_MAX];
  6492. const char *s, *p;
  6493. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6494. size_t len;
  6495. int res = 1;
  6496. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  6497. len = (size_t)(p - path);
  6498. if (len >= sizeof(buf)) {
  6499. /* path too long */
  6500. res = -1;
  6501. break;
  6502. }
  6503. memcpy(buf, path, len);
  6504. buf[len] = '\0';
  6505. /* Try to create intermediate directory */
  6506. DEBUG_TRACE("mkdir(%s)", buf);
  6507. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  6508. /* path does not exixt and can not be created */
  6509. res = -2;
  6510. break;
  6511. }
  6512. /* Is path itself a directory? */
  6513. if (p[1] == '\0') {
  6514. res = 0;
  6515. }
  6516. }
  6517. return res;
  6518. }
  6519. static void
  6520. remove_bad_file(const struct mg_connection *conn, const char *path)
  6521. {
  6522. int r = mg_remove(conn, path);
  6523. if (r != 0) {
  6524. mg_cry(conn, "%s: Cannot remove invalid file %s", __func__, path);
  6525. }
  6526. }
  6527. long long
  6528. mg_store_body(struct mg_connection *conn, const char *path)
  6529. {
  6530. char buf[MG_BUF_LEN];
  6531. long long len = 0;
  6532. int ret, n;
  6533. struct mg_file fi;
  6534. if (conn->consumed_content != 0) {
  6535. mg_cry(conn, "%s: Contents already consumed", __func__);
  6536. return -11;
  6537. }
  6538. ret = put_dir(conn, path);
  6539. if (ret < 0) {
  6540. /* -1 for path too long,
  6541. * -2 for path can not be created. */
  6542. return ret;
  6543. }
  6544. if (ret != 1) {
  6545. /* Return 0 means, path itself is a directory. */
  6546. return 0;
  6547. }
  6548. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  6549. return -12;
  6550. }
  6551. ret = mg_read(conn, buf, sizeof(buf));
  6552. while (ret > 0) {
  6553. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  6554. if (n != ret) {
  6555. (void)mg_fclose(
  6556. &fi.access); /* File is bad and will be removed anyway. */
  6557. remove_bad_file(conn, path);
  6558. return -13;
  6559. }
  6560. ret = mg_read(conn, buf, sizeof(buf));
  6561. }
  6562. /* File is open for writing. If fclose fails, there was probably an
  6563. * error flushing the buffer to disk, so the file on disk might be
  6564. * broken. Delete it and return an error to the caller. */
  6565. if (mg_fclose(&fi.access) != 0) {
  6566. remove_bad_file(conn, path);
  6567. return -14;
  6568. }
  6569. return len;
  6570. }
  6571. /* Parse HTTP headers from the given buffer, advance buf pointer
  6572. * to the point where parsing stopped.
  6573. * All parameters must be valid pointers (not NULL).
  6574. * Return <0 on error. */
  6575. static int
  6576. parse_http_headers(char **buf, struct mg_request_info *ri)
  6577. {
  6578. int i;
  6579. ri->num_headers = 0;
  6580. for (i = 0; i < (int)ARRAY_SIZE(ri->http_headers); i++) {
  6581. char *dp = *buf;
  6582. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  6583. dp++;
  6584. }
  6585. if (dp == *buf) {
  6586. /* End of headers reached. */
  6587. break;
  6588. }
  6589. if (*dp != ':') {
  6590. /* This is not a valid field. */
  6591. return -1;
  6592. }
  6593. /* End of header key (*dp == ':') */
  6594. /* Truncate here and set the key name */
  6595. *dp = 0;
  6596. ri->http_headers[i].name = *buf;
  6597. do {
  6598. dp++;
  6599. } while (*dp == ' ');
  6600. /* The rest of the line is the value */
  6601. ri->http_headers[i].value = dp;
  6602. *buf = dp + strcspn(dp, "\r\n");
  6603. if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) {
  6604. *buf = NULL;
  6605. }
  6606. ri->num_headers = i + 1;
  6607. if (*buf) {
  6608. (*buf)[0] = 0;
  6609. (*buf)[1] = 0;
  6610. *buf += 2;
  6611. } else {
  6612. *buf = dp;
  6613. break;
  6614. }
  6615. if ((*buf)[0] == '\r') {
  6616. /* This is the end of the header */
  6617. break;
  6618. }
  6619. }
  6620. return ri->num_headers;
  6621. }
  6622. static int
  6623. is_valid_http_method(const char *method)
  6624. {
  6625. return !strcmp(method, "GET") /* HTTP (RFC 2616) */
  6626. || !strcmp(method, "POST") /* HTTP (RFC 2616) */
  6627. || !strcmp(method, "HEAD") /* HTTP (RFC 2616) */
  6628. || !strcmp(method, "PUT") /* HTTP (RFC 2616) */
  6629. || !strcmp(method, "DELETE") /* HTTP (RFC 2616) */
  6630. || !strcmp(method, "OPTIONS") /* HTTP (RFC 2616) */
  6631. /* TRACE method (RFC 2616) is not supported for security reasons */
  6632. || !strcmp(method, "CONNECT") /* HTTP (RFC 2616) */
  6633. || !strcmp(method, "PROPFIND") /* WEBDAV (RFC 2518) */
  6634. || !strcmp(method, "MKCOL") /* WEBDAV (RFC 2518) */
  6635. /* Unsupported WEBDAV Methods: */
  6636. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  6637. /* + 11 methods from RFC 3253 */
  6638. /* ORDERPATCH (RFC 3648) */
  6639. /* ACL (RFC 3744) */
  6640. /* SEARCH (RFC 5323) */
  6641. /* + MicroSoft extensions
  6642. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  6643. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  6644. || !strcmp(method, "PATCH"); /* PATCH method (RFC 5789) */
  6645. }
  6646. /* Parse HTTP request, fill in mg_request_info structure.
  6647. * This function modifies the buffer by NUL-terminating
  6648. * HTTP request components, header names and header values.
  6649. * Parameters:
  6650. * buf (in/out): pointer to the HTTP header to parse and split
  6651. * len (in): length of HTTP header buffer
  6652. * re (out): parsed header as mg_request_info
  6653. * buf and ri must be valid pointers (not NULL), len>0.
  6654. * Returns <0 on error. */
  6655. static int
  6656. parse_http_message(char *buf, int len, struct mg_request_info *ri)
  6657. {
  6658. int is_request, request_length;
  6659. char *start_line;
  6660. request_length = get_request_len(buf, len);
  6661. if (request_length > 0) {
  6662. /* Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_addr,
  6663. * remote_port */
  6664. ri->remote_user = ri->request_method = ri->request_uri =
  6665. ri->http_version = NULL;
  6666. ri->num_headers = 0;
  6667. buf[request_length - 1] = '\0';
  6668. /* RFC says that all initial whitespaces should be ingored */
  6669. while (*buf != '\0' && isspace(*(unsigned char *)buf)) {
  6670. buf++;
  6671. }
  6672. start_line = skip(&buf, "\r\n");
  6673. ri->request_method = skip(&start_line, " ");
  6674. ri->request_uri = skip(&start_line, " ");
  6675. ri->http_version = start_line;
  6676. /* HTTP message could be either HTTP request:
  6677. * "GET / HTTP/1.0 ..."
  6678. * or a HTTP response:
  6679. * "HTTP/1.0 200 OK ..."
  6680. * otherwise it is invalid.
  6681. */
  6682. is_request = is_valid_http_method(ri->request_method);
  6683. if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0)
  6684. || (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
  6685. /* Not a valid request or response: invalid */
  6686. return -1;
  6687. }
  6688. if (is_request) {
  6689. ri->http_version += 5;
  6690. }
  6691. if (parse_http_headers(&buf, ri) < 0) {
  6692. /* Error while parsing headers */
  6693. return -1;
  6694. }
  6695. }
  6696. return request_length;
  6697. }
  6698. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  6699. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  6700. * buffer (which marks the end of HTTP request). Buffer buf may already
  6701. * have some data. The length of the data is stored in nread.
  6702. * Upon every read operation, increase nread by the number of bytes read. */
  6703. static int
  6704. read_request(FILE *fp,
  6705. struct mg_connection *conn,
  6706. char *buf,
  6707. int bufsiz,
  6708. int *nread)
  6709. {
  6710. int request_len, n = 0;
  6711. struct timespec last_action_time;
  6712. double request_timeout;
  6713. if (!conn) {
  6714. return 0;
  6715. }
  6716. memset(&last_action_time, 0, sizeof(last_action_time));
  6717. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  6718. /* value of request_timeout is in seconds, config in milliseconds */
  6719. request_timeout = atof(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  6720. } else {
  6721. request_timeout = -1.0;
  6722. }
  6723. if (conn->handled_requests > 0) {
  6724. if (conn->ctx->config[KEEP_ALIVE_TIMEOUT]) {
  6725. request_timeout =
  6726. atof(conn->ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  6727. }
  6728. }
  6729. request_len = get_request_len(buf, *nread);
  6730. /* first time reading from this connection */
  6731. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  6732. while (request_len == 0) {
  6733. /* Full request not yet received */
  6734. if (conn->ctx->stop_flag != 0) {
  6735. /* Server is to be stopped. */
  6736. return -1;
  6737. }
  6738. if (*nread >= bufsiz) {
  6739. /* Request too long */
  6740. return -2;
  6741. }
  6742. n = pull(fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  6743. if (n < 0) {
  6744. /* Receive error */
  6745. return -1;
  6746. }
  6747. *nread += n;
  6748. request_len = get_request_len(buf, *nread);
  6749. if ((request_len == 0) && (request_timeout >= 0)) {
  6750. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  6751. > request_timeout) {
  6752. /* Timeout */
  6753. return -1;
  6754. }
  6755. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  6756. }
  6757. }
  6758. return request_len;
  6759. }
  6760. #if !defined(NO_FILES)
  6761. /* For given directory path, substitute it to valid index file.
  6762. * Return 1 if index file has been found, 0 if not found.
  6763. * If the file is found, it's stats is returned in stp. */
  6764. static int
  6765. substitute_index_file(struct mg_connection *conn,
  6766. char *path,
  6767. size_t path_len,
  6768. struct mg_file *filep)
  6769. {
  6770. if (conn && conn->ctx) {
  6771. const char *list = conn->ctx->config[INDEX_FILES];
  6772. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6773. struct vec filename_vec;
  6774. size_t n = strlen(path);
  6775. int found = 0;
  6776. /* The 'path' given to us points to the directory. Remove all trailing
  6777. * directory separator characters from the end of the path, and
  6778. * then append single directory separator character. */
  6779. while (n > 0 && path[n - 1] == '/') {
  6780. n--;
  6781. }
  6782. path[n] = '/';
  6783. /* Traverse index files list. For each entry, append it to the given
  6784. * path and see if the file exists. If it exists, break the loop */
  6785. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6786. /* Ignore too long entries that may overflow path buffer */
  6787. if (filename_vec.len > path_len - (n + 2)) {
  6788. continue;
  6789. }
  6790. /* Prepare full path to the index file */
  6791. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6792. /* Does it exist? */
  6793. if (mg_stat(conn, path, &file.stat)) {
  6794. /* Yes it does, break the loop */
  6795. *filep = file;
  6796. found = 1;
  6797. break;
  6798. }
  6799. }
  6800. /* If no index file exists, restore directory path */
  6801. if (!found) {
  6802. path[n] = '\0';
  6803. }
  6804. return found;
  6805. }
  6806. return 0;
  6807. }
  6808. #endif
  6809. #if !defined(NO_CACHING)
  6810. /* Return True if we should reply 304 Not Modified. */
  6811. static int
  6812. is_not_modified(const struct mg_connection *conn,
  6813. const struct mg_file_stat *filestat)
  6814. {
  6815. char etag[64];
  6816. const char *ims = mg_get_header(conn, "If-Modified-Since");
  6817. const char *inm = mg_get_header(conn, "If-None-Match");
  6818. construct_etag(etag, sizeof(etag), filestat);
  6819. return (inm != NULL && !mg_strcasecmp(etag, inm))
  6820. || ((ims != NULL)
  6821. && (filestat->last_modified <= parse_date_string(ims)));
  6822. }
  6823. #endif /* !NO_CACHING */
  6824. #if !defined(NO_CGI) || !defined(NO_FILES)
  6825. static int
  6826. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  6827. {
  6828. const char *expect, *body;
  6829. char buf[MG_BUF_LEN];
  6830. int to_read, nread, success = 0;
  6831. int64_t buffered_len;
  6832. double timeout = -1.0;
  6833. if (!conn) {
  6834. return 0;
  6835. }
  6836. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  6837. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  6838. }
  6839. expect = mg_get_header(conn, "Expect");
  6840. /* assert(fp != NULL); */
  6841. if (!fp) {
  6842. send_http_error(conn, 500, "%s", "Error: NULL File");
  6843. return 0;
  6844. }
  6845. if (conn->content_len == -1 && !conn->is_chunked) {
  6846. /* Content length is not specified by the client. */
  6847. send_http_error(conn,
  6848. 411,
  6849. "%s",
  6850. "Error: Client did not specify content length");
  6851. } else if ((expect != NULL)
  6852. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  6853. /* Client sent an "Expect: xyz" header and xyz is not 100-continue. */
  6854. send_http_error(conn,
  6855. 417,
  6856. "Error: Can not fulfill expectation %s",
  6857. expect);
  6858. } else {
  6859. if (expect != NULL) {
  6860. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  6861. conn->status_code = 100;
  6862. } else {
  6863. conn->status_code = 200;
  6864. }
  6865. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  6866. - conn->consumed_content;
  6867. /* assert(buffered_len >= 0); */
  6868. /* assert(conn->consumed_content == 0); */
  6869. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  6870. send_http_error(conn, 500, "%s", "Error: Size mismatch");
  6871. return 0;
  6872. }
  6873. if (buffered_len > 0) {
  6874. if ((int64_t)buffered_len > conn->content_len) {
  6875. buffered_len = (int)conn->content_len;
  6876. }
  6877. body = conn->buf + conn->request_len + conn->consumed_content;
  6878. push_all(conn->ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  6879. conn->consumed_content += buffered_len;
  6880. }
  6881. nread = 0;
  6882. while (conn->consumed_content < conn->content_len) {
  6883. to_read = sizeof(buf);
  6884. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  6885. to_read = (int)(conn->content_len - conn->consumed_content);
  6886. }
  6887. nread = pull(NULL, conn, buf, to_read, timeout);
  6888. if (nread <= 0
  6889. || push_all(conn->ctx, fp, sock, ssl, buf, nread) != nread) {
  6890. break;
  6891. }
  6892. conn->consumed_content += nread;
  6893. }
  6894. if (conn->consumed_content == conn->content_len) {
  6895. success = (nread >= 0);
  6896. }
  6897. /* Each error code path in this function must send an error */
  6898. if (!success) {
  6899. /* NOTE: Maybe some data has already been sent. */
  6900. /* TODO (low): If some data has been sent, a correct error
  6901. * reply can no longer be sent, so just close the connection */
  6902. send_http_error(conn, 500, "%s", "");
  6903. }
  6904. }
  6905. return success;
  6906. }
  6907. #endif
  6908. #if !defined(NO_CGI)
  6909. /* This structure helps to create an environment for the spawned CGI program.
  6910. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  6911. * last element must be NULL.
  6912. * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  6913. * strings must reside in a contiguous buffer. The end of the buffer is
  6914. * marked by two '\0' characters.
  6915. * We satisfy both worlds: we create an envp array (which is vars), all
  6916. * entries are actually pointers inside buf. */
  6917. struct cgi_environment {
  6918. struct mg_connection *conn;
  6919. /* Data block */
  6920. char *buf; /* Environment buffer */
  6921. size_t buflen; /* Space available in buf */
  6922. size_t bufused; /* Space taken in buf */
  6923. /* Index block */
  6924. char **var; /* char **envp */
  6925. size_t varlen; /* Number of variables available in var */
  6926. size_t varused; /* Number of variables stored in var */
  6927. };
  6928. static void addenv(struct cgi_environment *env,
  6929. PRINTF_FORMAT_STRING(const char *fmt),
  6930. ...) PRINTF_ARGS(2, 3);
  6931. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  6932. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  6933. static void
  6934. addenv(struct cgi_environment *env, const char *fmt, ...)
  6935. {
  6936. size_t n, space;
  6937. int truncated = 0;
  6938. char *added;
  6939. va_list ap;
  6940. /* Calculate how much space is left in the buffer */
  6941. space = (env->buflen - env->bufused);
  6942. /* Calculate an estimate for the required space */
  6943. n = strlen(fmt) + 2 + 128;
  6944. do {
  6945. if (space <= n) {
  6946. /* Allocate new buffer */
  6947. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  6948. added = (char *)mg_realloc(env->buf, n);
  6949. if (!added) {
  6950. /* Out of memory */
  6951. mg_cry(env->conn,
  6952. "%s: Cannot allocate memory for CGI variable [%s]",
  6953. __func__,
  6954. fmt);
  6955. return;
  6956. }
  6957. env->buf = added;
  6958. env->buflen = n;
  6959. space = (env->buflen - env->bufused);
  6960. }
  6961. /* Make a pointer to the free space int the buffer */
  6962. added = env->buf + env->bufused;
  6963. /* Copy VARIABLE=VALUE\0 string into the free space */
  6964. va_start(ap, fmt);
  6965. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  6966. va_end(ap);
  6967. /* Do not add truncated strings to the environment */
  6968. if (truncated) {
  6969. /* Reallocate the buffer */
  6970. space = 0;
  6971. n = 1;
  6972. }
  6973. } while (truncated);
  6974. /* Calculate number of bytes added to the environment */
  6975. n = strlen(added) + 1;
  6976. env->bufused += n;
  6977. /* Now update the variable index */
  6978. space = (env->varlen - env->varused);
  6979. if (space < 2) {
  6980. mg_cry(env->conn,
  6981. "%s: Cannot register CGI variable [%s]",
  6982. __func__,
  6983. fmt);
  6984. return;
  6985. }
  6986. /* Append a pointer to the added string into the envp array */
  6987. env->var[env->varused] = added;
  6988. env->varused++;
  6989. }
  6990. static void
  6991. prepare_cgi_environment(struct mg_connection *conn,
  6992. const char *prog,
  6993. struct cgi_environment *env)
  6994. {
  6995. const char *s;
  6996. struct vec var_vec;
  6997. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  6998. int i, truncated, uri_len;
  6999. if (conn == NULL || prog == NULL || env == NULL) {
  7000. return;
  7001. }
  7002. env->conn = conn;
  7003. env->buflen = CGI_ENVIRONMENT_SIZE;
  7004. env->bufused = 0;
  7005. env->buf = (char *)mg_malloc(env->buflen);
  7006. env->varlen = MAX_CGI_ENVIR_VARS;
  7007. env->varused = 0;
  7008. env->var = (char **)mg_malloc(env->buflen * sizeof(char *));
  7009. addenv(env, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  7010. addenv(env, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  7011. addenv(env, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  7012. addenv(env, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  7013. /* Prepare the environment block */
  7014. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  7015. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  7016. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  7017. #if defined(USE_IPV6)
  7018. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  7019. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  7020. } else
  7021. #endif
  7022. {
  7023. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  7024. }
  7025. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  7026. addenv(env, "REMOTE_ADDR=%s", src_addr);
  7027. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  7028. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  7029. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  7030. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  7031. /* SCRIPT_NAME */
  7032. uri_len = (int)strlen(conn->request_info.local_uri);
  7033. if (conn->path_info == NULL) {
  7034. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  7035. /* URI: /path_to_script/script.cgi */
  7036. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  7037. } else {
  7038. /* URI: /path_to_script/ ... using index.cgi */
  7039. char *index_file = strrchr(prog, '/');
  7040. if (index_file) {
  7041. addenv(env,
  7042. "SCRIPT_NAME=%s%s",
  7043. conn->request_info.local_uri,
  7044. index_file + 1);
  7045. }
  7046. }
  7047. } else {
  7048. /* URI: /path_to_script/script.cgi/path_info */
  7049. addenv(env,
  7050. "SCRIPT_NAME=%.*s",
  7051. uri_len - (int)strlen(conn->path_info),
  7052. conn->request_info.local_uri);
  7053. }
  7054. addenv(env, "SCRIPT_FILENAME=%s", prog);
  7055. if (conn->path_info == NULL) {
  7056. addenv(env, "PATH_TRANSLATED=%s", conn->ctx->config[DOCUMENT_ROOT]);
  7057. } else {
  7058. addenv(env,
  7059. "PATH_TRANSLATED=%s%s",
  7060. conn->ctx->config[DOCUMENT_ROOT],
  7061. conn->path_info);
  7062. }
  7063. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  7064. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  7065. addenv(env, "CONTENT_TYPE=%s", s);
  7066. }
  7067. if (conn->request_info.query_string != NULL) {
  7068. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  7069. }
  7070. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  7071. addenv(env, "CONTENT_LENGTH=%s", s);
  7072. }
  7073. if ((s = getenv("PATH")) != NULL) {
  7074. addenv(env, "PATH=%s", s);
  7075. }
  7076. if (conn->path_info != NULL) {
  7077. addenv(env, "PATH_INFO=%s", conn->path_info);
  7078. }
  7079. if (conn->status_code > 0) {
  7080. /* CGI error handler should show the status code */
  7081. addenv(env, "STATUS=%d", conn->status_code);
  7082. }
  7083. #if defined(_WIN32)
  7084. if ((s = getenv("COMSPEC")) != NULL) {
  7085. addenv(env, "COMSPEC=%s", s);
  7086. }
  7087. if ((s = getenv("SYSTEMROOT")) != NULL) {
  7088. addenv(env, "SYSTEMROOT=%s", s);
  7089. }
  7090. if ((s = getenv("SystemDrive")) != NULL) {
  7091. addenv(env, "SystemDrive=%s", s);
  7092. }
  7093. if ((s = getenv("ProgramFiles")) != NULL) {
  7094. addenv(env, "ProgramFiles=%s", s);
  7095. }
  7096. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  7097. addenv(env, "ProgramFiles(x86)=%s", s);
  7098. }
  7099. #else
  7100. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  7101. addenv(env, "LD_LIBRARY_PATH=%s", s);
  7102. }
  7103. #endif /* _WIN32 */
  7104. if ((s = getenv("PERLLIB")) != NULL) {
  7105. addenv(env, "PERLLIB=%s", s);
  7106. }
  7107. if (conn->request_info.remote_user != NULL) {
  7108. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  7109. addenv(env, "%s", "AUTH_TYPE=Digest");
  7110. }
  7111. /* Add all headers as HTTP_* variables */
  7112. for (i = 0; i < conn->request_info.num_headers; i++) {
  7113. (void)mg_snprintf(conn,
  7114. &truncated,
  7115. http_var_name,
  7116. sizeof(http_var_name),
  7117. "HTTP_%s",
  7118. conn->request_info.http_headers[i].name);
  7119. if (truncated) {
  7120. mg_cry(conn,
  7121. "%s: HTTP header variable too long [%s]",
  7122. __func__,
  7123. conn->request_info.http_headers[i].name);
  7124. continue;
  7125. }
  7126. /* Convert variable name into uppercase, and change - to _ */
  7127. for (p = http_var_name; *p != '\0'; p++) {
  7128. if (*p == '-') {
  7129. *p = '_';
  7130. }
  7131. *p = (char)toupper(*(unsigned char *)p);
  7132. }
  7133. addenv(env,
  7134. "%s=%s",
  7135. http_var_name,
  7136. conn->request_info.http_headers[i].value);
  7137. }
  7138. /* Add user-specified variables */
  7139. s = conn->ctx->config[CGI_ENVIRONMENT];
  7140. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  7141. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  7142. }
  7143. env->var[env->varused] = NULL;
  7144. env->buf[env->bufused] = '\0';
  7145. }
  7146. static void
  7147. handle_cgi_request(struct mg_connection *conn, const char *prog)
  7148. {
  7149. char *buf;
  7150. size_t buflen;
  7151. int headers_len, data_len, i, truncated;
  7152. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  7153. const char *status, *status_text, *connection_state;
  7154. char *pbuf, dir[PATH_MAX], *p;
  7155. struct mg_request_info ri;
  7156. struct cgi_environment blk;
  7157. FILE *in = NULL, *out = NULL, *err = NULL;
  7158. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  7159. pid_t pid = (pid_t)-1;
  7160. if (conn == NULL) {
  7161. return;
  7162. }
  7163. buf = NULL;
  7164. buflen = 16384;
  7165. prepare_cgi_environment(conn, prog, &blk);
  7166. /* CGI must be executed in its own directory. 'dir' must point to the
  7167. * directory containing executable program, 'p' must point to the
  7168. * executable program name relative to 'dir'. */
  7169. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  7170. if (truncated) {
  7171. mg_cry(conn, "Error: CGI program \"%s\": Path too long", prog);
  7172. send_http_error(conn, 500, "Error: %s", "CGI path too long");
  7173. goto done;
  7174. }
  7175. if ((p = strrchr(dir, '/')) != NULL) {
  7176. *p++ = '\0';
  7177. } else {
  7178. dir[0] = '.', dir[1] = '\0';
  7179. p = (char *)prog;
  7180. }
  7181. if (pipe(fdin) != 0 || pipe(fdout) != 0 || pipe(fderr) != 0) {
  7182. status = strerror(ERRNO);
  7183. mg_cry(conn,
  7184. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  7185. prog,
  7186. status);
  7187. send_http_error(conn, 500, "Error: Cannot create CGI pipe: %s", status);
  7188. goto done;
  7189. }
  7190. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  7191. if (pid == (pid_t)-1) {
  7192. status = strerror(ERRNO);
  7193. mg_cry(conn,
  7194. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  7195. prog,
  7196. status);
  7197. send_http_error(conn,
  7198. 500,
  7199. "Error: Cannot spawn CGI process [%s]: %s",
  7200. prog,
  7201. status);
  7202. goto done;
  7203. }
  7204. /* Make sure child closes all pipe descriptors. It must dup them to 0,1 */
  7205. set_close_on_exec((SOCKET)fdin[0], conn); /* stdin read */
  7206. set_close_on_exec((SOCKET)fdout[1], conn); /* stdout write */
  7207. set_close_on_exec((SOCKET)fderr[1], conn); /* stderr write */
  7208. set_close_on_exec((SOCKET)fdin[1], conn); /* stdin write */
  7209. set_close_on_exec((SOCKET)fdout[0], conn); /* stdout read */
  7210. set_close_on_exec((SOCKET)fderr[0], conn); /* stderr read */
  7211. /* Parent closes only one side of the pipes.
  7212. * If we don't mark them as closed, close() attempt before
  7213. * return from this function throws an exception on Windows.
  7214. * Windows does not like when closed descriptor is closed again. */
  7215. (void)close(fdin[0]);
  7216. (void)close(fdout[1]);
  7217. (void)close(fderr[1]);
  7218. fdin[0] = fdout[1] = fderr[1] = -1;
  7219. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  7220. status = strerror(ERRNO);
  7221. mg_cry(conn,
  7222. "Error: CGI program \"%s\": Can not open stdin: %s",
  7223. prog,
  7224. status);
  7225. send_http_error(conn,
  7226. 500,
  7227. "Error: CGI can not open fdin\nfopen: %s",
  7228. status);
  7229. goto done;
  7230. }
  7231. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  7232. status = strerror(ERRNO);
  7233. mg_cry(conn,
  7234. "Error: CGI program \"%s\": Can not open stdout: %s",
  7235. prog,
  7236. status);
  7237. send_http_error(conn,
  7238. 500,
  7239. "Error: CGI can not open fdout\nfopen: %s",
  7240. status);
  7241. goto done;
  7242. }
  7243. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  7244. status = strerror(ERRNO);
  7245. mg_cry(conn,
  7246. "Error: CGI program \"%s\": Can not open stderr: %s",
  7247. prog,
  7248. status);
  7249. send_http_error(conn,
  7250. 500,
  7251. "Error: CGI can not open fdout\nfopen: %s",
  7252. status);
  7253. goto done;
  7254. }
  7255. setbuf(in, NULL);
  7256. setbuf(out, NULL);
  7257. setbuf(err, NULL);
  7258. fout.access.fp = out;
  7259. if ((conn->request_info.content_length > 0) || conn->is_chunked) {
  7260. /* This is a POST/PUT request, or another request with body data. */
  7261. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  7262. /* Error sending the body data */
  7263. mg_cry(conn,
  7264. "Error: CGI program \"%s\": Forward body data failed",
  7265. prog);
  7266. goto done;
  7267. }
  7268. }
  7269. /* Close so child gets an EOF. */
  7270. fclose(in);
  7271. in = NULL;
  7272. fdin[1] = -1;
  7273. /* Now read CGI reply into a buffer. We need to set correct
  7274. * status code, thus we need to see all HTTP headers first.
  7275. * Do not send anything back to client, until we buffer in all
  7276. * HTTP headers. */
  7277. data_len = 0;
  7278. buf = (char *)mg_malloc(buflen);
  7279. if (buf == NULL) {
  7280. send_http_error(conn,
  7281. 500,
  7282. "Error: Not enough memory for CGI buffer (%u bytes)",
  7283. (unsigned int)buflen);
  7284. mg_cry(conn,
  7285. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  7286. "bytes)",
  7287. prog,
  7288. (unsigned int)buflen);
  7289. goto done;
  7290. }
  7291. headers_len = read_request(out, conn, buf, (int)buflen, &data_len);
  7292. if (headers_len <= 0) {
  7293. /* Could not parse the CGI response. Check if some error message on
  7294. * stderr. */
  7295. i = pull_all(err, conn, buf, (int)buflen);
  7296. if (i > 0) {
  7297. mg_cry(conn,
  7298. "Error: CGI program \"%s\" sent error "
  7299. "message: [%.*s]",
  7300. prog,
  7301. i,
  7302. buf);
  7303. send_http_error(conn,
  7304. 500,
  7305. "Error: CGI program \"%s\" sent error "
  7306. "message: [%.*s]",
  7307. prog,
  7308. i,
  7309. buf);
  7310. } else {
  7311. mg_cry(conn,
  7312. "Error: CGI program sent malformed or too big "
  7313. "(>%u bytes) HTTP headers: [%.*s]",
  7314. (unsigned)buflen,
  7315. data_len,
  7316. buf);
  7317. send_http_error(conn,
  7318. 500,
  7319. "Error: CGI program sent malformed or too big "
  7320. "(>%u bytes) HTTP headers: [%.*s]",
  7321. (unsigned)buflen,
  7322. data_len,
  7323. buf);
  7324. }
  7325. goto done;
  7326. }
  7327. pbuf = buf;
  7328. buf[headers_len - 1] = '\0';
  7329. parse_http_headers(&pbuf, &ri);
  7330. /* Make up and send the status line */
  7331. status_text = "OK";
  7332. if ((status = get_header(&ri, "Status")) != NULL) {
  7333. conn->status_code = atoi(status);
  7334. status_text = status;
  7335. while (isdigit(*(const unsigned char *)status_text)
  7336. || *status_text == ' ') {
  7337. status_text++;
  7338. }
  7339. } else if (get_header(&ri, "Location") != NULL) {
  7340. conn->status_code = 302;
  7341. } else {
  7342. conn->status_code = 200;
  7343. }
  7344. connection_state = get_header(&ri, "Connection");
  7345. if (!header_has_option(connection_state, "keep-alive")) {
  7346. conn->must_close = 1;
  7347. }
  7348. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  7349. /* Send headers */
  7350. for (i = 0; i < ri.num_headers; i++) {
  7351. mg_printf(conn,
  7352. "%s: %s\r\n",
  7353. ri.http_headers[i].name,
  7354. ri.http_headers[i].value);
  7355. }
  7356. mg_write(conn, "\r\n", 2);
  7357. /* Send chunk of data that may have been read after the headers */
  7358. conn->num_bytes_sent +=
  7359. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  7360. /* Read the rest of CGI output and send to the client */
  7361. send_file_data(conn, &fout, 0, INT64_MAX);
  7362. done:
  7363. mg_free(blk.var);
  7364. mg_free(blk.buf);
  7365. if (pid != (pid_t)-1) {
  7366. kill(pid, SIGKILL);
  7367. #if !defined(_WIN32)
  7368. {
  7369. int st;
  7370. while (waitpid(pid, &st, 0) != -1)
  7371. ; /* clean zombies */
  7372. }
  7373. #endif
  7374. }
  7375. if (fdin[0] != -1) {
  7376. close(fdin[0]);
  7377. }
  7378. if (fdout[1] != -1) {
  7379. close(fdout[1]);
  7380. }
  7381. if (in != NULL) {
  7382. fclose(in);
  7383. } else if (fdin[1] != -1) {
  7384. close(fdin[1]);
  7385. }
  7386. if (out != NULL) {
  7387. fclose(out);
  7388. } else if (fdout[0] != -1) {
  7389. close(fdout[0]);
  7390. }
  7391. if (err != NULL) {
  7392. fclose(err);
  7393. } else if (fderr[0] != -1) {
  7394. close(fderr[0]);
  7395. }
  7396. if (buf != NULL) {
  7397. mg_free(buf);
  7398. }
  7399. }
  7400. #endif /* !NO_CGI */
  7401. #if !defined(NO_FILES)
  7402. static void
  7403. mkcol(struct mg_connection *conn, const char *path)
  7404. {
  7405. int rc, body_len;
  7406. struct de de;
  7407. char date[64];
  7408. time_t curtime = time(NULL);
  7409. if (conn == NULL) {
  7410. return;
  7411. }
  7412. /* TODO (mid): Check the send_http_error situations in this function */
  7413. memset(&de.file, 0, sizeof(de.file));
  7414. if (!mg_stat(conn, path, &de.file)) {
  7415. mg_cry(conn,
  7416. "%s: mg_stat(%s) failed: %s",
  7417. __func__,
  7418. path,
  7419. strerror(ERRNO));
  7420. }
  7421. if (de.file.last_modified) {
  7422. /* TODO (high): This check does not seem to make any sense ! */
  7423. send_http_error(
  7424. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7425. return;
  7426. }
  7427. body_len = conn->data_len - conn->request_len;
  7428. if (body_len > 0) {
  7429. send_http_error(
  7430. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7431. return;
  7432. }
  7433. rc = mg_mkdir(conn, path, 0755);
  7434. if (rc == 0) {
  7435. conn->status_code = 201;
  7436. gmt_time_string(date, sizeof(date), &curtime);
  7437. mg_printf(conn,
  7438. "HTTP/1.1 %d Created\r\n"
  7439. "Date: %s\r\n",
  7440. conn->status_code,
  7441. date);
  7442. send_static_cache_header(conn);
  7443. mg_printf(conn,
  7444. "Content-Length: 0\r\n"
  7445. "Connection: %s\r\n\r\n",
  7446. suggest_connection_header(conn));
  7447. } else if (rc == -1) {
  7448. if (errno == EEXIST) {
  7449. send_http_error(
  7450. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7451. } else if (errno == EACCES) {
  7452. send_http_error(
  7453. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7454. } else if (errno == ENOENT) {
  7455. send_http_error(
  7456. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7457. } else {
  7458. send_http_error(conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  7459. }
  7460. }
  7461. }
  7462. static void
  7463. put_file(struct mg_connection *conn, const char *path)
  7464. {
  7465. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7466. const char *range;
  7467. int64_t r1, r2;
  7468. int rc;
  7469. char date[64];
  7470. time_t curtime = time(NULL);
  7471. if (conn == NULL) {
  7472. return;
  7473. }
  7474. if (mg_stat(conn, path, &file.stat)) {
  7475. /* File already exists */
  7476. conn->status_code = 200;
  7477. if (file.stat.is_directory) {
  7478. /* This is an already existing directory,
  7479. * so there is nothing to do for the server. */
  7480. rc = 0;
  7481. } else {
  7482. /* File exists and is not a directory. */
  7483. /* Can it be replaced? */
  7484. if (file.access.membuf != NULL) {
  7485. /* This is an "in-memory" file, that can not be replaced */
  7486. send_http_error(
  7487. conn,
  7488. 405,
  7489. "Error: Put not possible\nReplacing %s is not supported",
  7490. path);
  7491. return;
  7492. }
  7493. /* Check if the server may write this file */
  7494. if (access(path, W_OK) == 0) {
  7495. /* Access granted */
  7496. conn->status_code = 200;
  7497. rc = 1;
  7498. } else {
  7499. send_http_error(
  7500. conn,
  7501. 403,
  7502. "Error: Put not possible\nReplacing %s is not allowed",
  7503. path);
  7504. return;
  7505. }
  7506. }
  7507. } else {
  7508. /* File should be created */
  7509. conn->status_code = 201;
  7510. rc = put_dir(conn, path);
  7511. }
  7512. if (rc == 0) {
  7513. /* put_dir returns 0 if path is a directory */
  7514. gmt_time_string(date, sizeof(date), &curtime);
  7515. mg_printf(conn,
  7516. "HTTP/1.1 %d %s\r\n",
  7517. conn->status_code,
  7518. mg_get_response_code_text(NULL, conn->status_code));
  7519. send_no_cache_header(conn);
  7520. mg_printf(conn,
  7521. "Date: %s\r\n"
  7522. "Content-Length: 0\r\n"
  7523. "Connection: %s\r\n\r\n",
  7524. date,
  7525. suggest_connection_header(conn));
  7526. /* Request to create a directory has been fulfilled successfully.
  7527. * No need to put a file. */
  7528. return;
  7529. }
  7530. if (rc == -1) {
  7531. /* put_dir returns -1 if the path is too long */
  7532. send_http_error(conn,
  7533. 414,
  7534. "Error: Path too long\nput_dir(%s): %s",
  7535. path,
  7536. strerror(ERRNO));
  7537. return;
  7538. }
  7539. if (rc == -2) {
  7540. /* put_dir returns -2 if the directory can not be created */
  7541. send_http_error(conn,
  7542. 500,
  7543. "Error: Can not create directory\nput_dir(%s): %s",
  7544. path,
  7545. strerror(ERRNO));
  7546. return;
  7547. }
  7548. /* A file should be created or overwritten. */
  7549. /* TODO: Test if write or write+read is required. */
  7550. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  7551. || file.access.fp == NULL) {
  7552. (void)mg_fclose(&file.access);
  7553. send_http_error(conn,
  7554. 500,
  7555. "Error: Can not create file\nfopen(%s): %s",
  7556. path,
  7557. strerror(ERRNO));
  7558. return;
  7559. }
  7560. fclose_on_exec(&file.access, conn);
  7561. range = mg_get_header(conn, "Content-Range");
  7562. r1 = r2 = 0;
  7563. if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
  7564. conn->status_code = 206; /* Partial content */
  7565. fseeko(file.access.fp, r1, SEEK_SET);
  7566. }
  7567. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  7568. /* forward_body_data failed.
  7569. * The error code has already been sent to the client,
  7570. * and conn->status_code is already set. */
  7571. (void)mg_fclose(&file.access);
  7572. return;
  7573. }
  7574. if (mg_fclose(&file.access) != 0) {
  7575. /* fclose failed. This might have different reasons, but a likely
  7576. * one is "no space on disk", http 507. */
  7577. conn->status_code = 507;
  7578. }
  7579. gmt_time_string(date, sizeof(date), &curtime);
  7580. mg_printf(conn,
  7581. "HTTP/1.1 %d %s\r\n",
  7582. conn->status_code,
  7583. mg_get_response_code_text(NULL, conn->status_code));
  7584. send_no_cache_header(conn);
  7585. mg_printf(conn,
  7586. "Date: %s\r\n"
  7587. "Content-Length: 0\r\n"
  7588. "Connection: %s\r\n\r\n",
  7589. date,
  7590. suggest_connection_header(conn));
  7591. }
  7592. static void
  7593. delete_file(struct mg_connection *conn, const char *path)
  7594. {
  7595. struct de de;
  7596. memset(&de.file, 0, sizeof(de.file));
  7597. if (!mg_stat(conn, path, &de.file)) {
  7598. /* mg_stat returns 0 if the file does not exist */
  7599. send_http_error(conn,
  7600. 404,
  7601. "Error: Cannot delete file\nFile %s not found",
  7602. path);
  7603. return;
  7604. }
  7605. #if 0 /* Ignore if a file in memory is inside a folder */
  7606. if (de.access.membuf != NULL) {
  7607. /* the file is cached in memory */
  7608. send_http_error(
  7609. conn,
  7610. 405,
  7611. "Error: Delete not possible\nDeleting %s is not supported",
  7612. path);
  7613. return;
  7614. }
  7615. #endif
  7616. if (de.file.is_directory) {
  7617. if (remove_directory(conn, path)) {
  7618. /* Delete is successful: Return 204 without content. */
  7619. send_http_error(conn, 204, "%s", "");
  7620. } else {
  7621. /* Delete is not successful: Return 500 (Server error). */
  7622. send_http_error(conn, 500, "Error: Could not delete %s", path);
  7623. }
  7624. return;
  7625. }
  7626. /* This is an existing file (not a directory).
  7627. * Check if write permission is granted. */
  7628. if (access(path, W_OK) != 0) {
  7629. /* File is read only */
  7630. send_http_error(
  7631. conn,
  7632. 403,
  7633. "Error: Delete not possible\nDeleting %s is not allowed",
  7634. path);
  7635. return;
  7636. }
  7637. /* Try to delete it. */
  7638. if (mg_remove(conn, path) == 0) {
  7639. /* Delete was successful: Return 204 without content. */
  7640. send_http_error(conn, 204, "%s", "");
  7641. } else {
  7642. /* Delete not successful (file locked). */
  7643. send_http_error(conn,
  7644. 423,
  7645. "Error: Cannot delete file\nremove(%s): %s",
  7646. path,
  7647. strerror(ERRNO));
  7648. }
  7649. }
  7650. #endif /* !NO_FILES */
  7651. static void
  7652. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  7653. static void
  7654. do_ssi_include(struct mg_connection *conn,
  7655. const char *ssi,
  7656. char *tag,
  7657. int include_level)
  7658. {
  7659. char file_name[MG_BUF_LEN], path[512], *p;
  7660. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7661. size_t len;
  7662. int truncated = 0;
  7663. if (conn == NULL) {
  7664. return;
  7665. }
  7666. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  7667. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  7668. * always < MG_BUF_LEN. */
  7669. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  7670. /* File name is relative to the webserver root */
  7671. file_name[511] = 0;
  7672. (void)mg_snprintf(conn,
  7673. &truncated,
  7674. path,
  7675. sizeof(path),
  7676. "%s/%s",
  7677. conn->ctx->config[DOCUMENT_ROOT],
  7678. file_name);
  7679. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  7680. /* File name is relative to the webserver working directory
  7681. * or it is absolute system path */
  7682. file_name[511] = 0;
  7683. (void)
  7684. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  7685. } else if (sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1
  7686. || sscanf(tag, " \"%511[^\"]\"", file_name) == 1) {
  7687. /* File name is relative to the currect document */
  7688. file_name[511] = 0;
  7689. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  7690. if (!truncated) {
  7691. if ((p = strrchr(path, '/')) != NULL) {
  7692. p[1] = '\0';
  7693. }
  7694. len = strlen(path);
  7695. (void)mg_snprintf(conn,
  7696. &truncated,
  7697. path + len,
  7698. sizeof(path) - len,
  7699. "%s",
  7700. file_name);
  7701. }
  7702. } else {
  7703. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  7704. return;
  7705. }
  7706. if (truncated) {
  7707. mg_cry(conn, "SSI #include path length overflow: [%s]", tag);
  7708. return;
  7709. }
  7710. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  7711. mg_cry(conn,
  7712. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  7713. tag,
  7714. path,
  7715. strerror(ERRNO));
  7716. } else {
  7717. fclose_on_exec(&file.access, conn);
  7718. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  7719. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  7720. path) > 0) {
  7721. send_ssi_file(conn, path, &file, include_level + 1);
  7722. } else {
  7723. send_file_data(conn, &file, 0, INT64_MAX);
  7724. }
  7725. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  7726. }
  7727. }
  7728. #if !defined(NO_POPEN)
  7729. static void
  7730. do_ssi_exec(struct mg_connection *conn, char *tag)
  7731. {
  7732. char cmd[1024] = "";
  7733. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7734. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  7735. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  7736. } else {
  7737. cmd[1023] = 0;
  7738. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  7739. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  7740. } else {
  7741. send_file_data(conn, &file, 0, INT64_MAX);
  7742. pclose(file.access.fp);
  7743. }
  7744. }
  7745. }
  7746. #endif /* !NO_POPEN */
  7747. static int
  7748. mg_fgetc(struct mg_file *filep, int offset)
  7749. {
  7750. if (filep == NULL) {
  7751. return EOF;
  7752. }
  7753. if (filep->access.membuf != NULL && offset >= 0
  7754. && ((unsigned int)(offset)) < filep->stat.size) {
  7755. return ((const unsigned char *)filep->access.membuf)[offset];
  7756. } else if (filep->access.fp != NULL) {
  7757. return fgetc(filep->access.fp);
  7758. } else {
  7759. return EOF;
  7760. }
  7761. }
  7762. static void
  7763. send_ssi_file(struct mg_connection *conn,
  7764. const char *path,
  7765. struct mg_file *filep,
  7766. int include_level)
  7767. {
  7768. char buf[MG_BUF_LEN];
  7769. int ch, offset, len, in_ssi_tag;
  7770. if (include_level > 10) {
  7771. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  7772. return;
  7773. }
  7774. in_ssi_tag = len = offset = 0;
  7775. while ((ch = mg_fgetc(filep, offset)) != EOF) {
  7776. if (in_ssi_tag && ch == '>') {
  7777. in_ssi_tag = 0;
  7778. buf[len++] = (char)ch;
  7779. buf[len] = '\0';
  7780. /* assert(len <= (int) sizeof(buf)); */
  7781. if (len > (int)sizeof(buf)) {
  7782. break;
  7783. }
  7784. if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
  7785. /* Not an SSI tag, pass it */
  7786. (void)mg_write(conn, buf, (size_t)len);
  7787. } else {
  7788. if (!memcmp(buf + 5, "include", 7)) {
  7789. do_ssi_include(conn, path, buf + 12, include_level);
  7790. #if !defined(NO_POPEN)
  7791. } else if (!memcmp(buf + 5, "exec", 4)) {
  7792. do_ssi_exec(conn, buf + 9);
  7793. #endif /* !NO_POPEN */
  7794. } else {
  7795. mg_cry(conn,
  7796. "%s: unknown SSI "
  7797. "command: \"%s\"",
  7798. path,
  7799. buf);
  7800. }
  7801. }
  7802. len = 0;
  7803. } else if (in_ssi_tag) {
  7804. if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
  7805. /* Not an SSI tag */
  7806. in_ssi_tag = 0;
  7807. } else if (len == (int)sizeof(buf) - 2) {
  7808. mg_cry(conn, "%s: SSI tag is too large", path);
  7809. len = 0;
  7810. }
  7811. buf[len++] = (char)(ch & 0xff);
  7812. } else if (ch == '<') {
  7813. in_ssi_tag = 1;
  7814. if (len > 0) {
  7815. mg_write(conn, buf, (size_t)len);
  7816. }
  7817. len = 0;
  7818. buf[len++] = (char)(ch & 0xff);
  7819. } else {
  7820. buf[len++] = (char)(ch & 0xff);
  7821. if (len == (int)sizeof(buf)) {
  7822. mg_write(conn, buf, (size_t)len);
  7823. len = 0;
  7824. }
  7825. }
  7826. }
  7827. /* Send the rest of buffered data */
  7828. if (len > 0) {
  7829. mg_write(conn, buf, (size_t)len);
  7830. }
  7831. }
  7832. static void
  7833. handle_ssi_file_request(struct mg_connection *conn,
  7834. const char *path,
  7835. struct mg_file *filep)
  7836. {
  7837. char date[64];
  7838. time_t curtime = time(NULL);
  7839. const char *cors1, *cors2, *cors3;
  7840. if (conn == NULL || path == NULL || filep == NULL) {
  7841. return;
  7842. }
  7843. if (mg_get_header(conn, "Origin")) {
  7844. /* Cross-origin resource sharing (CORS). */
  7845. cors1 = "Access-Control-Allow-Origin: ";
  7846. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  7847. cors3 = "\r\n";
  7848. } else {
  7849. cors1 = cors2 = cors3 = "";
  7850. }
  7851. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  7852. /* File exists (precondition for calling this function),
  7853. * but can not be opened by the server. */
  7854. send_http_error(conn,
  7855. 500,
  7856. "Error: Cannot read file\nfopen(%s): %s",
  7857. path,
  7858. strerror(ERRNO));
  7859. } else {
  7860. conn->must_close = 1;
  7861. gmt_time_string(date, sizeof(date), &curtime);
  7862. fclose_on_exec(&filep->access, conn);
  7863. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  7864. send_no_cache_header(conn);
  7865. mg_printf(conn,
  7866. "%s%s%s"
  7867. "Date: %s\r\n"
  7868. "Content-Type: text/html\r\n"
  7869. "Connection: %s\r\n\r\n",
  7870. cors1,
  7871. cors2,
  7872. cors3,
  7873. date,
  7874. suggest_connection_header(conn));
  7875. send_ssi_file(conn, path, filep, 0);
  7876. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  7877. }
  7878. }
  7879. #if !defined(NO_FILES)
  7880. static void
  7881. send_options(struct mg_connection *conn)
  7882. {
  7883. char date[64];
  7884. time_t curtime = time(NULL);
  7885. if (!conn) {
  7886. return;
  7887. }
  7888. conn->status_code = 200;
  7889. conn->must_close = 1;
  7890. gmt_time_string(date, sizeof(date), &curtime);
  7891. mg_printf(conn,
  7892. "HTTP/1.1 200 OK\r\n"
  7893. "Date: %s\r\n"
  7894. /* TODO: "Cache-Control" (?) */
  7895. "Connection: %s\r\n"
  7896. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  7897. "PROPFIND, MKCOL\r\n"
  7898. "DAV: 1\r\n\r\n",
  7899. date,
  7900. suggest_connection_header(conn));
  7901. }
  7902. /* Writes PROPFIND properties for a collection element */
  7903. static void
  7904. print_props(struct mg_connection *conn,
  7905. const char *uri,
  7906. struct mg_file_stat *filep)
  7907. {
  7908. char mtime[64];
  7909. if (conn == NULL || uri == NULL || filep == NULL) {
  7910. return;
  7911. }
  7912. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  7913. conn->num_bytes_sent +=
  7914. mg_printf(conn,
  7915. "<d:response>"
  7916. "<d:href>%s</d:href>"
  7917. "<d:propstat>"
  7918. "<d:prop>"
  7919. "<d:resourcetype>%s</d:resourcetype>"
  7920. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  7921. "<d:getlastmodified>%s</d:getlastmodified>"
  7922. "</d:prop>"
  7923. "<d:status>HTTP/1.1 200 OK</d:status>"
  7924. "</d:propstat>"
  7925. "</d:response>\n",
  7926. uri,
  7927. filep->is_directory ? "<d:collection/>" : "",
  7928. filep->size,
  7929. mtime);
  7930. }
  7931. static void
  7932. print_dav_dir_entry(struct de *de, void *data)
  7933. {
  7934. char href[PATH_MAX];
  7935. char href_encoded[PATH_MAX * 3 /* worst case */];
  7936. int truncated;
  7937. struct mg_connection *conn = (struct mg_connection *)data;
  7938. if (!de || !conn) {
  7939. return;
  7940. }
  7941. mg_snprintf(conn,
  7942. &truncated,
  7943. href,
  7944. sizeof(href),
  7945. "%s%s",
  7946. conn->request_info.local_uri,
  7947. de->file_name);
  7948. if (!truncated) {
  7949. mg_url_encode(href, href_encoded, PATH_MAX * 3);
  7950. print_props(conn, href_encoded, &de->file);
  7951. }
  7952. }
  7953. static void
  7954. handle_propfind(struct mg_connection *conn,
  7955. const char *path,
  7956. struct mg_file_stat *filep)
  7957. {
  7958. const char *depth = mg_get_header(conn, "Depth");
  7959. char date[64];
  7960. time_t curtime = time(NULL);
  7961. gmt_time_string(date, sizeof(date), &curtime);
  7962. if (!conn || !path || !filep || !conn->ctx) {
  7963. return;
  7964. }
  7965. conn->must_close = 1;
  7966. conn->status_code = 207;
  7967. mg_printf(conn,
  7968. "HTTP/1.1 207 Multi-Status\r\n"
  7969. "Date: %s\r\n",
  7970. date);
  7971. send_static_cache_header(conn);
  7972. mg_printf(conn,
  7973. "Connection: %s\r\n"
  7974. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  7975. suggest_connection_header(conn));
  7976. conn->num_bytes_sent +=
  7977. mg_printf(conn,
  7978. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  7979. "<d:multistatus xmlns:d='DAV:'>\n");
  7980. /* Print properties for the requested resource itself */
  7981. print_props(conn, conn->request_info.local_uri, filep);
  7982. /* If it is a directory, print directory entries too if Depth is not 0 */
  7983. if (filep && filep->is_directory
  7984. && !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")
  7985. && (depth == NULL || strcmp(depth, "0") != 0)) {
  7986. scan_directory(conn, path, conn, &print_dav_dir_entry);
  7987. }
  7988. conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");
  7989. }
  7990. #endif
  7991. void
  7992. mg_lock_connection(struct mg_connection *conn)
  7993. {
  7994. if (conn) {
  7995. (void)pthread_mutex_lock(&conn->mutex);
  7996. }
  7997. }
  7998. void
  7999. mg_unlock_connection(struct mg_connection *conn)
  8000. {
  8001. if (conn) {
  8002. (void)pthread_mutex_unlock(&conn->mutex);
  8003. }
  8004. }
  8005. void
  8006. mg_lock_context(struct mg_context *ctx)
  8007. {
  8008. if (ctx) {
  8009. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  8010. }
  8011. }
  8012. void
  8013. mg_unlock_context(struct mg_context *ctx)
  8014. {
  8015. if (ctx) {
  8016. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  8017. }
  8018. }
  8019. #if defined(USE_TIMERS)
  8020. #include "timer.inl"
  8021. #endif /* USE_TIMERS */
  8022. #ifdef USE_LUA
  8023. #include "mod_lua.inl"
  8024. #endif /* USE_LUA */
  8025. #ifdef USE_DUKTAPE
  8026. #include "mod_duktape.inl"
  8027. #endif /* USE_DUKTAPE */
  8028. #if defined(USE_WEBSOCKET)
  8029. #define SHA_API static
  8030. #include "sha1.inl"
  8031. static int
  8032. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  8033. {
  8034. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  8035. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  8036. SHA1_CTX sha_ctx;
  8037. int truncated;
  8038. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  8039. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  8040. if (truncated) {
  8041. conn->must_close = 1;
  8042. return 0;
  8043. }
  8044. SHA1_Init(&sha_ctx);
  8045. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  8046. SHA1_Final(&sha_ctx, (unsigned char *)sha);
  8047. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  8048. mg_printf(conn,
  8049. "HTTP/1.1 101 Switching Protocols\r\n"
  8050. "Upgrade: websocket\r\n"
  8051. "Connection: Upgrade\r\n"
  8052. "Sec-WebSocket-Accept: %s\r\n",
  8053. b64_sha);
  8054. if (conn->request_info.acceptedWebSocketSubprotocol) {
  8055. mg_printf(conn,
  8056. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  8057. conn->request_info.acceptedWebSocketSubprotocol);
  8058. } else {
  8059. mg_printf(conn, "%s", "\r\n");
  8060. }
  8061. return 1;
  8062. }
  8063. static void
  8064. read_websocket(struct mg_connection *conn,
  8065. mg_websocket_data_handler ws_data_handler,
  8066. void *callback_data)
  8067. {
  8068. /* Pointer to the beginning of the portion of the incoming websocket
  8069. * message queue.
  8070. * The original websocket upgrade request is never removed, so the queue
  8071. * begins after it. */
  8072. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  8073. int n, error, exit_by_callback;
  8074. /* body_len is the length of the entire queue in bytes
  8075. * len is the length of the current message
  8076. * data_len is the length of the current message's data payload
  8077. * header_len is the length of the current message's header */
  8078. size_t i, len, mask_len = 0, data_len = 0, header_len, body_len;
  8079. /* "The masking key is a 32-bit value chosen at random by the client."
  8080. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  8081. */
  8082. unsigned char mask[4];
  8083. /* data points to the place where the message is stored when passed to
  8084. * the
  8085. * websocket_data callback. This is either mem on the stack, or a
  8086. * dynamically allocated buffer if it is too large. */
  8087. unsigned char mem[4096];
  8088. unsigned char *data = mem;
  8089. unsigned char mop; /* mask flag and opcode */
  8090. double timeout = -1.0;
  8091. if (conn->ctx->config[WEBSOCKET_TIMEOUT]) {
  8092. timeout = atoi(conn->ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  8093. }
  8094. if ((timeout <= 0.0) && (conn->ctx->config[REQUEST_TIMEOUT])) {
  8095. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  8096. }
  8097. mg_set_thread_name("wsock");
  8098. /* Loop continuously, reading messages from the socket, invoking the
  8099. * callback, and waiting repeatedly until an error occurs. */
  8100. while (!conn->ctx->stop_flag) {
  8101. header_len = 0;
  8102. assert(conn->data_len >= conn->request_len);
  8103. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  8104. len = buf[1] & 127;
  8105. mask_len = (buf[1] & 128) ? 4 : 0;
  8106. if ((len < 126) && (body_len >= mask_len)) {
  8107. data_len = len;
  8108. header_len = 2 + mask_len;
  8109. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  8110. header_len = 4 + mask_len;
  8111. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  8112. } else if (body_len >= (10 + mask_len)) {
  8113. header_len = 10 + mask_len;
  8114. data_len = (((uint64_t)ntohl(*(uint32_t *)(void *)&buf[2]))
  8115. << 32) + ntohl(*(uint32_t *)(void *)&buf[6]);
  8116. }
  8117. }
  8118. if (header_len > 0 && body_len >= header_len) {
  8119. /* Allocate space to hold websocket payload */
  8120. data = mem;
  8121. if (data_len > sizeof(mem)) {
  8122. data = (unsigned char *)mg_malloc(data_len);
  8123. if (data == NULL) {
  8124. /* Allocation failed, exit the loop and then close the
  8125. * connection */
  8126. mg_cry(conn, "websocket out of memory; closing connection");
  8127. break;
  8128. }
  8129. }
  8130. /* Copy the mask before we shift the queue and destroy it */
  8131. if (mask_len > 0) {
  8132. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  8133. } else {
  8134. memset(mask, 0, sizeof(mask));
  8135. }
  8136. /* Read frame payload from the first message in the queue into
  8137. * data and advance the queue by moving the memory in place. */
  8138. assert(body_len >= header_len);
  8139. if (data_len + header_len > body_len) {
  8140. mop = buf[0]; /* current mask and opcode */
  8141. /* Overflow case */
  8142. len = body_len - header_len;
  8143. memcpy(data, buf + header_len, len);
  8144. error = 0;
  8145. while (len < data_len) {
  8146. n = pull(NULL,
  8147. conn,
  8148. (char *)(data + len),
  8149. (int)(data_len - len),
  8150. timeout);
  8151. if (n <= 0) {
  8152. error = 1;
  8153. break;
  8154. }
  8155. len += (size_t)n;
  8156. }
  8157. if (error) {
  8158. mg_cry(conn, "Websocket pull failed; closing connection");
  8159. break;
  8160. }
  8161. conn->data_len = conn->request_len;
  8162. } else {
  8163. mop = buf[0]; /* current mask and opcode, overwritten by
  8164. * memmove() */
  8165. /* Length of the message being read at the front of the
  8166. * queue */
  8167. len = data_len + header_len;
  8168. /* Copy the data payload into the data pointer for the
  8169. * callback */
  8170. memcpy(data, buf + header_len, data_len);
  8171. /* Move the queue forward len bytes */
  8172. memmove(buf, buf + len, body_len - len);
  8173. /* Mark the queue as advanced */
  8174. conn->data_len -= (int)len;
  8175. }
  8176. /* Apply mask if necessary */
  8177. if (mask_len > 0) {
  8178. for (i = 0; i < data_len; ++i) {
  8179. data[i] ^= mask[i & 3];
  8180. }
  8181. }
  8182. /* Exit the loop if callback signals to exit (server side),
  8183. * or "connection close" opcode received (client side). */
  8184. exit_by_callback = 0;
  8185. if ((ws_data_handler != NULL)
  8186. && !ws_data_handler(
  8187. conn, mop, (char *)data, data_len, callback_data)) {
  8188. exit_by_callback = 1;
  8189. }
  8190. if (data != mem) {
  8191. mg_free(data);
  8192. }
  8193. if (exit_by_callback
  8194. || ((mop & 0xf) == WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  8195. /* Opcode == 8, connection close */
  8196. break;
  8197. }
  8198. /* Not breaking the loop, process next websocket frame. */
  8199. } else {
  8200. /* Read from the socket into the next available location in the
  8201. * message queue. */
  8202. if ((n = pull(NULL,
  8203. conn,
  8204. conn->buf + conn->data_len,
  8205. conn->buf_size - conn->data_len,
  8206. timeout)) <= 0) {
  8207. /* Error, no bytes read */
  8208. break;
  8209. }
  8210. conn->data_len += n;
  8211. }
  8212. }
  8213. mg_set_thread_name("worker");
  8214. }
  8215. static int
  8216. mg_websocket_write_exec(struct mg_connection *conn,
  8217. int opcode,
  8218. const char *data,
  8219. size_t dataLen,
  8220. uint32_t masking_key)
  8221. {
  8222. unsigned char header[14];
  8223. size_t headerLen = 1;
  8224. int retval = -1;
  8225. #if defined(__GNUC__) || defined(__MINGW32__)
  8226. /* Disable spurious conversion warning for GCC */
  8227. #pragma GCC diagnostic push
  8228. #pragma GCC diagnostic ignored "-Wconversion"
  8229. #endif
  8230. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  8231. #if defined(__GNUC__) || defined(__MINGW32__)
  8232. #pragma GCC diagnostic pop
  8233. #endif
  8234. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  8235. if (dataLen < 126) {
  8236. /* inline 7-bit length field */
  8237. header[1] = (unsigned char)dataLen;
  8238. headerLen = 2;
  8239. } else if (dataLen <= 0xFFFF) {
  8240. /* 16-bit length field */
  8241. uint16_t len = htons((uint16_t)dataLen);
  8242. header[1] = 126;
  8243. memcpy(header + 2, &len, 2);
  8244. headerLen = 4;
  8245. } else {
  8246. /* 64-bit length field */
  8247. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  8248. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  8249. header[1] = 127;
  8250. memcpy(header + 2, &len1, 4);
  8251. memcpy(header + 6, &len2, 4);
  8252. headerLen = 10;
  8253. }
  8254. if (masking_key) {
  8255. /* add mask */
  8256. header[1] |= 0x80;
  8257. memcpy(header + headerLen, &masking_key, 4);
  8258. headerLen += 4;
  8259. }
  8260. /* Note that POSIX/Winsock's send() is threadsafe
  8261. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  8262. * but mongoose's mg_printf/mg_write is not (because of the loop in
  8263. * push(), although that is only a problem if the packet is large or
  8264. * outgoing buffer is full). */
  8265. (void)mg_lock_connection(conn);
  8266. retval = mg_write(conn, header, headerLen);
  8267. if (dataLen > 0) {
  8268. retval = mg_write(conn, data, dataLen);
  8269. }
  8270. mg_unlock_connection(conn);
  8271. return retval;
  8272. }
  8273. int
  8274. mg_websocket_write(struct mg_connection *conn,
  8275. int opcode,
  8276. const char *data,
  8277. size_t dataLen)
  8278. {
  8279. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  8280. }
  8281. static void
  8282. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  8283. {
  8284. size_t i = 0;
  8285. i = 0;
  8286. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  8287. /* Convert in 32 bit words, if data is 4 byte aligned */
  8288. while (i < (in_len - 3)) {
  8289. *(uint32_t *)(void *)(out + i) =
  8290. *(uint32_t *)(void *)(in + i) ^ masking_key;
  8291. i += 4;
  8292. }
  8293. }
  8294. if (i != in_len) {
  8295. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  8296. while (i < in_len) {
  8297. *(uint8_t *)(void *)(out + i) =
  8298. *(uint8_t *)(void *)(in + i)
  8299. ^ *(((uint8_t *)&masking_key) + (i % 4));
  8300. i++;
  8301. }
  8302. }
  8303. }
  8304. int
  8305. mg_websocket_client_write(struct mg_connection *conn,
  8306. int opcode,
  8307. const char *data,
  8308. size_t dataLen)
  8309. {
  8310. int retval = -1;
  8311. char *masked_data = (char *)mg_malloc(((dataLen + 7) / 4) * 4);
  8312. uint32_t masking_key = (uint32_t)get_random();
  8313. if (masked_data == NULL) {
  8314. /* Return -1 in an error case */
  8315. mg_cry(conn,
  8316. "Cannot allocate buffer for masked websocket response: "
  8317. "Out of memory");
  8318. return -1;
  8319. }
  8320. mask_data(data, dataLen, masking_key, masked_data);
  8321. retval = mg_websocket_write_exec(
  8322. conn, opcode, masked_data, dataLen, masking_key);
  8323. mg_free(masked_data);
  8324. return retval;
  8325. }
  8326. static void
  8327. handle_websocket_request(struct mg_connection *conn,
  8328. const char *path,
  8329. int is_callback_resource,
  8330. struct mg_websocket_subprotocols *subprotocols,
  8331. mg_websocket_connect_handler ws_connect_handler,
  8332. mg_websocket_ready_handler ws_ready_handler,
  8333. mg_websocket_data_handler ws_data_handler,
  8334. mg_websocket_close_handler ws_close_handler,
  8335. void *cbData)
  8336. {
  8337. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  8338. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  8339. int lua_websock = 0;
  8340. #if !defined(USE_LUA)
  8341. (void)path;
  8342. #endif
  8343. /* Step 1: Check websocket protocol version. */
  8344. /* Step 1.1: Check Sec-WebSocket-Key. */
  8345. if (!websock_key) {
  8346. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  8347. * requires a Sec-WebSocket-Key header.
  8348. */
  8349. /* It could be the hixie draft version
  8350. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  8351. */
  8352. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  8353. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  8354. char key3[8];
  8355. if ((key1 != NULL) && (key2 != NULL)) {
  8356. /* This version uses 8 byte body data in a GET request */
  8357. conn->content_len = 8;
  8358. if (8 == mg_read(conn, key3, 8)) {
  8359. /* This is the hixie version */
  8360. send_http_error(conn,
  8361. 426,
  8362. "%s",
  8363. "Protocol upgrade to RFC 6455 required");
  8364. return;
  8365. }
  8366. }
  8367. /* This is an unknown version */
  8368. send_http_error(conn, 400, "%s", "Malformed websocket request");
  8369. return;
  8370. }
  8371. /* Step 1.2: Check websocket protocol version. */
  8372. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  8373. if (version == NULL || strcmp(version, "13") != 0) {
  8374. /* Reject wrong versions */
  8375. send_http_error(conn, 426, "%s", "Protocol upgrade required");
  8376. return;
  8377. }
  8378. /* Step 1.3: Could check for "Host", but we do not really nead this
  8379. * value for anything, so just ignore it. */
  8380. /* Step 2: If a callback is responsible, call it. */
  8381. if (is_callback_resource) {
  8382. /* Step 2.1 check and select subprotocol */
  8383. const char *protocol = mg_get_header(conn, "Sec-WebSocket-Protocol");
  8384. if (protocol && subprotocols) {
  8385. int idx;
  8386. unsigned long len;
  8387. const char *sep, *curSubProtocol,
  8388. *acceptedWebSocketSubprotocol = NULL;
  8389. /* look for matching subprotocol */
  8390. do {
  8391. sep = strchr(protocol, ',');
  8392. curSubProtocol = protocol;
  8393. len = sep ? (unsigned long)(sep - protocol)
  8394. : (unsigned long)strlen(protocol);
  8395. while (sep && isspace(*++sep))
  8396. ; // ignore leading whitespaces
  8397. protocol = sep;
  8398. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  8399. if ((strlen(subprotocols->subprotocols[idx]) == len)
  8400. && (strncmp(curSubProtocol,
  8401. subprotocols->subprotocols[idx],
  8402. len) == 0)) {
  8403. acceptedWebSocketSubprotocol =
  8404. subprotocols->subprotocols[idx];
  8405. break;
  8406. }
  8407. }
  8408. } while (sep && !acceptedWebSocketSubprotocol);
  8409. conn->request_info.acceptedWebSocketSubprotocol =
  8410. acceptedWebSocketSubprotocol;
  8411. } else if (protocol) {
  8412. /* keep legacy behavior */
  8413. /* The protocol is a comma seperated list of names. */
  8414. /* The server must only return one value from this list. */
  8415. /* First check if it is a list or just a single value. */
  8416. const char *sep = strrchr(protocol, ',');
  8417. if (sep == NULL) {
  8418. /* Just a single protocol -> accept it. */
  8419. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  8420. } else {
  8421. /* Multiple protocols -> accept the last one. */
  8422. /* This is just a quick fix if the client offers multiple
  8423. * protocols. The handler should have a list of accepted
  8424. * protocols on his own
  8425. * and use it to select one protocol among those the client has
  8426. * offered.
  8427. */
  8428. while (isspace(*++sep))
  8429. ; // ignore leading whitespaces
  8430. conn->request_info.acceptedWebSocketSubprotocol = sep;
  8431. }
  8432. }
  8433. if (ws_connect_handler != NULL
  8434. && ws_connect_handler(conn, cbData) != 0) {
  8435. /* C callback has returned non-zero, do not proceed with
  8436. * handshake.
  8437. */
  8438. /* Note that C callbacks are no longer called when Lua is
  8439. * responsible, so C can no longer filter callbacks for Lua. */
  8440. return;
  8441. }
  8442. }
  8443. #if defined(USE_LUA)
  8444. /* Step 3: No callback. Check if Lua is responsible. */
  8445. else {
  8446. /* Step 3.1: Check if Lua is responsible. */
  8447. if (conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  8448. lua_websock =
  8449. match_prefix(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  8450. strlen(
  8451. conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  8452. path);
  8453. }
  8454. if (lua_websock) {
  8455. /* Step 3.2: Lua is responsible: call it. */
  8456. conn->lua_websocket_state = lua_websocket_new(path, conn);
  8457. if (!conn->lua_websocket_state) {
  8458. /* Lua rejected the new client */
  8459. return;
  8460. }
  8461. }
  8462. }
  8463. #endif
  8464. /* Step 4: Check if there is a responsible websocket handler. */
  8465. if (!is_callback_resource && !lua_websock) {
  8466. /* There is no callback, and Lua is not responsible either. */
  8467. /* Reply with a 404 Not Found or with nothing at all?
  8468. * TODO (mid): check the websocket standards, how to reply to
  8469. * requests to invalid websocket addresses. */
  8470. send_http_error(conn, 404, "%s", "Not found");
  8471. return;
  8472. }
  8473. /* Step 5: The websocket connection has been accepted */
  8474. if (!send_websocket_handshake(conn, websock_key)) {
  8475. send_http_error(conn, 500, "%s", "Websocket handshake failed");
  8476. return;
  8477. }
  8478. /* Step 6: Call the ready handler */
  8479. if (is_callback_resource) {
  8480. if (ws_ready_handler != NULL) {
  8481. ws_ready_handler(conn, cbData);
  8482. }
  8483. #if defined(USE_LUA)
  8484. } else if (lua_websock) {
  8485. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  8486. /* the ready handler returned false */
  8487. return;
  8488. }
  8489. #endif
  8490. }
  8491. /* Step 7: Enter the read loop */
  8492. if (is_callback_resource) {
  8493. read_websocket(conn, ws_data_handler, cbData);
  8494. #if defined(USE_LUA)
  8495. } else if (lua_websock) {
  8496. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  8497. #endif
  8498. }
  8499. /* Step 8: Call the close handler */
  8500. if (ws_close_handler) {
  8501. ws_close_handler(conn, cbData);
  8502. }
  8503. }
  8504. static int
  8505. is_websocket_protocol(const struct mg_connection *conn)
  8506. {
  8507. const char *upgrade, *connection;
  8508. /* A websocket protocoll has the following HTTP headers:
  8509. *
  8510. * Connection: Upgrade
  8511. * Upgrade: Websocket
  8512. */
  8513. upgrade = mg_get_header(conn, "Upgrade");
  8514. if (upgrade == NULL) {
  8515. return 0; /* fail early, don't waste time checking other header
  8516. * fields
  8517. */
  8518. }
  8519. if (!mg_strcasestr(upgrade, "websocket")) {
  8520. return 0;
  8521. }
  8522. connection = mg_get_header(conn, "Connection");
  8523. if (connection == NULL) {
  8524. return 0;
  8525. }
  8526. if (!mg_strcasestr(connection, "upgrade")) {
  8527. return 0;
  8528. }
  8529. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  8530. * "Sec-WebSocket-Version" are also required.
  8531. * Don't check them here, since even an unsupported websocket protocol
  8532. * request still IS a websocket request (in contrast to a standard HTTP
  8533. * request). It will fail later in handle_websocket_request.
  8534. */
  8535. return 1;
  8536. }
  8537. #endif /* !USE_WEBSOCKET */
  8538. static int
  8539. isbyte(int n)
  8540. {
  8541. return n >= 0 && n <= 255;
  8542. }
  8543. static int
  8544. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  8545. {
  8546. int n, a, b, c, d, slash = 32, len = 0;
  8547. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5
  8548. || sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) && isbyte(a)
  8549. && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0
  8550. && slash < 33) {
  8551. len = n;
  8552. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  8553. | (uint32_t)d;
  8554. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  8555. }
  8556. return len;
  8557. }
  8558. static int
  8559. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  8560. {
  8561. int throttle = 0;
  8562. struct vec vec, val;
  8563. uint32_t net, mask;
  8564. char mult;
  8565. double v;
  8566. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  8567. mult = ',';
  8568. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  8569. || (v < 0) || ((lowercase(&mult) != 'k')
  8570. && (lowercase(&mult) != 'm') && (mult != ','))) {
  8571. continue;
  8572. }
  8573. v *= (lowercase(&mult) == 'k')
  8574. ? 1024
  8575. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  8576. if (vec.len == 1 && vec.ptr[0] == '*') {
  8577. throttle = (int)v;
  8578. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  8579. if ((remote_ip & mask) == net) {
  8580. throttle = (int)v;
  8581. }
  8582. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  8583. throttle = (int)v;
  8584. }
  8585. }
  8586. return throttle;
  8587. }
  8588. static uint32_t
  8589. get_remote_ip(const struct mg_connection *conn)
  8590. {
  8591. if (!conn) {
  8592. return 0;
  8593. }
  8594. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  8595. }
  8596. /* The mg_upload function is superseeded by mg_handle_form_request. */
  8597. #include "handle_form.inl"
  8598. #if defined(MG_LEGACY_INTERFACE)
  8599. /* Implement the deprecated mg_upload function by calling the new
  8600. * mg_handle_form_request function. While mg_upload could only handle
  8601. * HTML forms sent as POST request in multipart/form-data format
  8602. * containing only file input elements, mg_handle_form_request can
  8603. * handle all form input elements and all standard request methods. */
  8604. struct mg_upload_user_data {
  8605. struct mg_connection *conn;
  8606. const char *destination_dir;
  8607. int num_uploaded_files;
  8608. };
  8609. /* Helper function for deprecated mg_upload. */
  8610. static int
  8611. mg_upload_field_found(const char *key,
  8612. const char *filename,
  8613. char *path,
  8614. size_t pathlen,
  8615. void *user_data)
  8616. {
  8617. int truncated = 0;
  8618. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  8619. (void)key;
  8620. if (!filename) {
  8621. mg_cry(fud->conn, "%s: No filename set", __func__);
  8622. return FORM_FIELD_STORAGE_ABORT;
  8623. }
  8624. mg_snprintf(fud->conn,
  8625. &truncated,
  8626. path,
  8627. pathlen - 1,
  8628. "%s/%s",
  8629. fud->destination_dir,
  8630. filename);
  8631. if (!truncated) {
  8632. mg_cry(fud->conn, "%s: File path too long", __func__);
  8633. return FORM_FIELD_STORAGE_ABORT;
  8634. }
  8635. return FORM_FIELD_STORAGE_STORE;
  8636. }
  8637. /* Helper function for deprecated mg_upload. */
  8638. static int
  8639. mg_upload_field_get(const char *key,
  8640. const char *value,
  8641. size_t value_size,
  8642. void *user_data)
  8643. {
  8644. /* Function should never be called */
  8645. (void)key;
  8646. (void)value;
  8647. (void)value_size;
  8648. (void)user_data;
  8649. return 0;
  8650. }
  8651. /* Helper function for deprecated mg_upload. */
  8652. static int
  8653. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  8654. {
  8655. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  8656. (void)file_size;
  8657. fud->num_uploaded_files++;
  8658. fud->conn->ctx->callbacks.upload(fud->conn, path);
  8659. return 0;
  8660. }
  8661. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  8662. int
  8663. mg_upload(struct mg_connection *conn, const char *destination_dir)
  8664. {
  8665. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  8666. struct mg_form_data_handler fdh = {mg_upload_field_found,
  8667. mg_upload_field_get,
  8668. mg_upload_field_stored,
  8669. 0};
  8670. int ret;
  8671. fdh.user_data = (void *)&fud;
  8672. ret = mg_handle_form_request(conn, &fdh);
  8673. if (ret < 0) {
  8674. mg_cry(conn, "%s: Error while parsing the request", __func__);
  8675. }
  8676. return fud.num_uploaded_files;
  8677. }
  8678. #endif
  8679. static int
  8680. get_first_ssl_listener_index(const struct mg_context *ctx)
  8681. {
  8682. unsigned int i;
  8683. int idx = -1;
  8684. if (ctx) {
  8685. for (i = 0; idx == -1 && i < ctx->num_listening_sockets; i++) {
  8686. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  8687. }
  8688. }
  8689. return idx;
  8690. }
  8691. static void
  8692. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  8693. {
  8694. char host[1025];
  8695. const char *host_header;
  8696. size_t hostlen;
  8697. host_header = mg_get_header(conn, "Host");
  8698. hostlen = sizeof(host);
  8699. if (host_header != NULL) {
  8700. char *pos;
  8701. mg_strlcpy(host, host_header, hostlen);
  8702. host[hostlen - 1] = '\0';
  8703. pos = strchr(host, ':');
  8704. if (pos != NULL) {
  8705. *pos = '\0';
  8706. }
  8707. } else {
  8708. /* Cannot get host from the Host: header.
  8709. * Fallback to our IP address. */
  8710. if (conn) {
  8711. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  8712. }
  8713. }
  8714. /* Send host, port, uri and (if it exists) ?query_string */
  8715. if (conn) {
  8716. mg_printf(conn,
  8717. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  8718. host,
  8719. #if defined(USE_IPV6)
  8720. (conn->ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  8721. == AF_INET6)
  8722. ? (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  8723. .lsa.sin6.sin6_port)
  8724. :
  8725. #endif
  8726. (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  8727. .lsa.sin.sin_port),
  8728. conn->request_info.local_uri,
  8729. (conn->request_info.query_string == NULL) ? "" : "?",
  8730. (conn->request_info.query_string == NULL)
  8731. ? ""
  8732. : conn->request_info.query_string);
  8733. }
  8734. }
  8735. static void
  8736. mg_set_handler_type(struct mg_context *ctx,
  8737. const char *uri,
  8738. int handler_type,
  8739. int is_delete_request,
  8740. mg_request_handler handler,
  8741. struct mg_websocket_subprotocols *subprotocols,
  8742. mg_websocket_connect_handler connect_handler,
  8743. mg_websocket_ready_handler ready_handler,
  8744. mg_websocket_data_handler data_handler,
  8745. mg_websocket_close_handler close_handler,
  8746. mg_authorization_handler auth_handler,
  8747. void *cbdata)
  8748. {
  8749. struct mg_handler_info *tmp_rh, **lastref;
  8750. size_t urilen = strlen(uri);
  8751. if (handler_type == WEBSOCKET_HANDLER) {
  8752. /* assert(handler == NULL); */
  8753. /* assert(is_delete_request || connect_handler!=NULL ||
  8754. * ready_handler!=NULL || data_handler!=NULL ||
  8755. * close_handler!=NULL);
  8756. */
  8757. /* assert(auth_handler == NULL); */
  8758. if (handler != NULL) {
  8759. return;
  8760. }
  8761. if (!is_delete_request && connect_handler == NULL
  8762. && ready_handler == NULL
  8763. && data_handler == NULL
  8764. && close_handler == NULL) {
  8765. return;
  8766. }
  8767. if (auth_handler != NULL) {
  8768. return;
  8769. }
  8770. } else if (handler_type == REQUEST_HANDLER) {
  8771. /* assert(connect_handler==NULL && ready_handler==NULL &&
  8772. * data_handler==NULL && close_handler==NULL); */
  8773. /* assert(is_delete_request || (handler!=NULL));
  8774. */
  8775. /* assert(auth_handler == NULL); */
  8776. if (connect_handler != NULL || ready_handler != NULL
  8777. || data_handler != NULL
  8778. || close_handler != NULL) {
  8779. return;
  8780. }
  8781. if (!is_delete_request && (handler == NULL)) {
  8782. return;
  8783. }
  8784. if (auth_handler != NULL) {
  8785. return;
  8786. }
  8787. } else { /* AUTH_HANDLER */
  8788. /* assert(handler == NULL); */
  8789. /* assert(connect_handler==NULL && ready_handler==NULL &&
  8790. * data_handler==NULL && close_handler==NULL); */
  8791. /* assert(auth_handler != NULL); */
  8792. if (handler != NULL) {
  8793. return;
  8794. }
  8795. if (connect_handler != NULL || ready_handler != NULL
  8796. || data_handler != NULL
  8797. || close_handler != NULL) {
  8798. return;
  8799. }
  8800. if (!is_delete_request && (auth_handler == NULL)) {
  8801. return;
  8802. }
  8803. }
  8804. if (!ctx) {
  8805. return;
  8806. }
  8807. mg_lock_context(ctx);
  8808. /* first try to find an existing handler */
  8809. lastref = &(ctx->handlers);
  8810. for (tmp_rh = ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  8811. if (tmp_rh->handler_type == handler_type) {
  8812. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  8813. if (!is_delete_request) {
  8814. /* update existing handler */
  8815. if (handler_type == REQUEST_HANDLER) {
  8816. tmp_rh->handler = handler;
  8817. } else if (handler_type == WEBSOCKET_HANDLER) {
  8818. tmp_rh->subprotocols = subprotocols;
  8819. tmp_rh->connect_handler = connect_handler;
  8820. tmp_rh->ready_handler = ready_handler;
  8821. tmp_rh->data_handler = data_handler;
  8822. tmp_rh->close_handler = close_handler;
  8823. } else { /* AUTH_HANDLER */
  8824. tmp_rh->auth_handler = auth_handler;
  8825. }
  8826. tmp_rh->cbdata = cbdata;
  8827. } else {
  8828. /* remove existing handler */
  8829. *lastref = tmp_rh->next;
  8830. mg_free(tmp_rh->uri);
  8831. mg_free(tmp_rh);
  8832. }
  8833. mg_unlock_context(ctx);
  8834. return;
  8835. }
  8836. }
  8837. lastref = &(tmp_rh->next);
  8838. }
  8839. if (is_delete_request) {
  8840. /* no handler to set, this was a remove request to a non-existing
  8841. * handler */
  8842. mg_unlock_context(ctx);
  8843. return;
  8844. }
  8845. tmp_rh =
  8846. (struct mg_handler_info *)mg_calloc(sizeof(struct mg_handler_info), 1);
  8847. if (tmp_rh == NULL) {
  8848. mg_unlock_context(ctx);
  8849. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  8850. return;
  8851. }
  8852. tmp_rh->uri = mg_strdup(uri);
  8853. if (!tmp_rh->uri) {
  8854. mg_unlock_context(ctx);
  8855. mg_free(tmp_rh);
  8856. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  8857. return;
  8858. }
  8859. tmp_rh->uri_len = urilen;
  8860. if (handler_type == REQUEST_HANDLER) {
  8861. tmp_rh->handler = handler;
  8862. } else if (handler_type == WEBSOCKET_HANDLER) {
  8863. tmp_rh->subprotocols = subprotocols;
  8864. tmp_rh->connect_handler = connect_handler;
  8865. tmp_rh->ready_handler = ready_handler;
  8866. tmp_rh->data_handler = data_handler;
  8867. tmp_rh->close_handler = close_handler;
  8868. } else { /* AUTH_HANDLER */
  8869. tmp_rh->auth_handler = auth_handler;
  8870. }
  8871. tmp_rh->cbdata = cbdata;
  8872. tmp_rh->handler_type = handler_type;
  8873. tmp_rh->next = NULL;
  8874. *lastref = tmp_rh;
  8875. mg_unlock_context(ctx);
  8876. }
  8877. void
  8878. mg_set_request_handler(struct mg_context *ctx,
  8879. const char *uri,
  8880. mg_request_handler handler,
  8881. void *cbdata)
  8882. {
  8883. mg_set_handler_type(ctx,
  8884. uri,
  8885. REQUEST_HANDLER,
  8886. handler == NULL,
  8887. handler,
  8888. NULL,
  8889. NULL,
  8890. NULL,
  8891. NULL,
  8892. NULL,
  8893. NULL,
  8894. cbdata);
  8895. }
  8896. void
  8897. mg_set_websocket_handler(struct mg_context *ctx,
  8898. const char *uri,
  8899. mg_websocket_connect_handler connect_handler,
  8900. mg_websocket_ready_handler ready_handler,
  8901. mg_websocket_data_handler data_handler,
  8902. mg_websocket_close_handler close_handler,
  8903. void *cbdata)
  8904. {
  8905. mg_set_websocket_handler_with_subprotocols(ctx,
  8906. uri,
  8907. NULL,
  8908. connect_handler,
  8909. ready_handler,
  8910. data_handler,
  8911. close_handler,
  8912. cbdata);
  8913. }
  8914. void
  8915. mg_set_websocket_handler_with_subprotocols(
  8916. struct mg_context *ctx,
  8917. const char *uri,
  8918. struct mg_websocket_subprotocols *subprotocols,
  8919. mg_websocket_connect_handler connect_handler,
  8920. mg_websocket_ready_handler ready_handler,
  8921. mg_websocket_data_handler data_handler,
  8922. mg_websocket_close_handler close_handler,
  8923. void *cbdata)
  8924. {
  8925. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  8926. && (data_handler == NULL)
  8927. && (close_handler == NULL);
  8928. mg_set_handler_type(ctx,
  8929. uri,
  8930. WEBSOCKET_HANDLER,
  8931. is_delete_request,
  8932. NULL,
  8933. subprotocols,
  8934. connect_handler,
  8935. ready_handler,
  8936. data_handler,
  8937. close_handler,
  8938. NULL,
  8939. cbdata);
  8940. }
  8941. void
  8942. mg_set_auth_handler(struct mg_context *ctx,
  8943. const char *uri,
  8944. mg_request_handler handler,
  8945. void *cbdata)
  8946. {
  8947. mg_set_handler_type(ctx,
  8948. uri,
  8949. AUTH_HANDLER,
  8950. handler == NULL,
  8951. NULL,
  8952. NULL,
  8953. NULL,
  8954. NULL,
  8955. NULL,
  8956. NULL,
  8957. handler,
  8958. cbdata);
  8959. }
  8960. static int
  8961. get_request_handler(struct mg_connection *conn,
  8962. int handler_type,
  8963. mg_request_handler *handler,
  8964. struct mg_websocket_subprotocols **subprotocols,
  8965. mg_websocket_connect_handler *connect_handler,
  8966. mg_websocket_ready_handler *ready_handler,
  8967. mg_websocket_data_handler *data_handler,
  8968. mg_websocket_close_handler *close_handler,
  8969. mg_authorization_handler *auth_handler,
  8970. void **cbdata)
  8971. {
  8972. const struct mg_request_info *request_info = mg_get_request_info(conn);
  8973. if (request_info) {
  8974. const char *uri = request_info->local_uri;
  8975. size_t urilen = strlen(uri);
  8976. struct mg_handler_info *tmp_rh;
  8977. if (!conn || !conn->ctx) {
  8978. return 0;
  8979. }
  8980. mg_lock_context(conn->ctx);
  8981. /* first try for an exact match */
  8982. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8983. tmp_rh = tmp_rh->next) {
  8984. if (tmp_rh->handler_type == handler_type) {
  8985. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  8986. if (handler_type == WEBSOCKET_HANDLER) {
  8987. *subprotocols = tmp_rh->subprotocols;
  8988. *connect_handler = tmp_rh->connect_handler;
  8989. *ready_handler = tmp_rh->ready_handler;
  8990. *data_handler = tmp_rh->data_handler;
  8991. *close_handler = tmp_rh->close_handler;
  8992. } else if (handler_type == REQUEST_HANDLER) {
  8993. *handler = tmp_rh->handler;
  8994. } else { /* AUTH_HANDLER */
  8995. *auth_handler = tmp_rh->auth_handler;
  8996. }
  8997. *cbdata = tmp_rh->cbdata;
  8998. mg_unlock_context(conn->ctx);
  8999. return 1;
  9000. }
  9001. }
  9002. }
  9003. /* next try for a partial match, we will accept uri/something */
  9004. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  9005. tmp_rh = tmp_rh->next) {
  9006. if (tmp_rh->handler_type == handler_type) {
  9007. if (tmp_rh->uri_len < urilen && uri[tmp_rh->uri_len] == '/'
  9008. && memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0) {
  9009. if (handler_type == WEBSOCKET_HANDLER) {
  9010. *subprotocols = tmp_rh->subprotocols;
  9011. *connect_handler = tmp_rh->connect_handler;
  9012. *ready_handler = tmp_rh->ready_handler;
  9013. *data_handler = tmp_rh->data_handler;
  9014. *close_handler = tmp_rh->close_handler;
  9015. } else if (handler_type == REQUEST_HANDLER) {
  9016. *handler = tmp_rh->handler;
  9017. } else { /* AUTH_HANDLER */
  9018. *auth_handler = tmp_rh->auth_handler;
  9019. }
  9020. *cbdata = tmp_rh->cbdata;
  9021. mg_unlock_context(conn->ctx);
  9022. return 1;
  9023. }
  9024. }
  9025. }
  9026. /* finally try for pattern match */
  9027. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  9028. tmp_rh = tmp_rh->next) {
  9029. if (tmp_rh->handler_type == handler_type) {
  9030. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  9031. if (handler_type == WEBSOCKET_HANDLER) {
  9032. *subprotocols = tmp_rh->subprotocols;
  9033. *connect_handler = tmp_rh->connect_handler;
  9034. *ready_handler = tmp_rh->ready_handler;
  9035. *data_handler = tmp_rh->data_handler;
  9036. *close_handler = tmp_rh->close_handler;
  9037. } else if (handler_type == REQUEST_HANDLER) {
  9038. *handler = tmp_rh->handler;
  9039. } else { /* AUTH_HANDLER */
  9040. *auth_handler = tmp_rh->auth_handler;
  9041. }
  9042. *cbdata = tmp_rh->cbdata;
  9043. mg_unlock_context(conn->ctx);
  9044. return 1;
  9045. }
  9046. }
  9047. }
  9048. mg_unlock_context(conn->ctx);
  9049. }
  9050. return 0; /* none found */
  9051. }
  9052. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  9053. static int
  9054. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  9055. void *cbdata)
  9056. {
  9057. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9058. if (pcallbacks->websocket_connect) {
  9059. return pcallbacks->websocket_connect(conn);
  9060. }
  9061. /* No handler set - assume "OK" */
  9062. return 0;
  9063. }
  9064. static void
  9065. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  9066. {
  9067. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9068. if (pcallbacks->websocket_ready) {
  9069. pcallbacks->websocket_ready(conn);
  9070. }
  9071. }
  9072. static int
  9073. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  9074. int bits,
  9075. char *data,
  9076. size_t len,
  9077. void *cbdata)
  9078. {
  9079. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9080. if (pcallbacks->websocket_data) {
  9081. return pcallbacks->websocket_data(conn, bits, data, len);
  9082. }
  9083. /* No handler set - assume "OK" */
  9084. return 1;
  9085. }
  9086. #endif
  9087. /* This is the heart of the Civetweb's logic.
  9088. * This function is called when the request is read, parsed and validated,
  9089. * and Civetweb must decide what action to take: serve a file, or
  9090. * a directory, or call embedded function, etcetera. */
  9091. static void
  9092. handle_request(struct mg_connection *conn)
  9093. {
  9094. if (conn) {
  9095. struct mg_request_info *ri = &conn->request_info;
  9096. char path[PATH_MAX];
  9097. int uri_len, ssl_index;
  9098. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  9099. is_put_or_delete_request = 0, is_callback_resource = 0;
  9100. int i;
  9101. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9102. mg_request_handler callback_handler = NULL;
  9103. struct mg_websocket_subprotocols *subprotocols;
  9104. mg_websocket_connect_handler ws_connect_handler = NULL;
  9105. mg_websocket_ready_handler ws_ready_handler = NULL;
  9106. mg_websocket_data_handler ws_data_handler = NULL;
  9107. mg_websocket_close_handler ws_close_handler = NULL;
  9108. void *callback_data = NULL;
  9109. mg_authorization_handler auth_handler = NULL;
  9110. void *auth_callback_data = NULL;
  9111. #if !defined(NO_FILES)
  9112. time_t curtime = time(NULL);
  9113. char date[64];
  9114. #endif
  9115. path[0] = 0;
  9116. if (!ri) {
  9117. return;
  9118. }
  9119. /* 1. get the request url */
  9120. /* 1.1. split into url and query string */
  9121. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  9122. != NULL) {
  9123. *((char *)conn->request_info.query_string++) = '\0';
  9124. }
  9125. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  9126. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  9127. ssl_index = get_first_ssl_listener_index(conn->ctx);
  9128. if (ssl_index >= 0) {
  9129. redirect_to_https_port(conn, ssl_index);
  9130. } else {
  9131. /* A http to https forward port has been specified,
  9132. * but no https port to forward to. */
  9133. send_http_error(conn,
  9134. 503,
  9135. "%s",
  9136. "Error: SSL forward not configured properly");
  9137. mg_cry(conn, "Can not redirect to SSL, no SSL port available");
  9138. }
  9139. return;
  9140. }
  9141. uri_len = (int)strlen(ri->local_uri);
  9142. /* 1.3. decode url (if config says so) */
  9143. if (should_decode_url(conn)) {
  9144. mg_url_decode(
  9145. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  9146. }
  9147. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  9148. * not possible */
  9149. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  9150. /* step 1. completed, the url is known now */
  9151. uri_len = (int)strlen(ri->local_uri);
  9152. DEBUG_TRACE("URL: %s", ri->local_uri);
  9153. /* 3. if this ip has limited speed, set it for this connection */
  9154. conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
  9155. get_remote_ip(conn),
  9156. ri->local_uri);
  9157. /* 4. call a "handle everything" callback, if registered */
  9158. if (conn->ctx->callbacks.begin_request != NULL) {
  9159. /* Note that since V1.7 the "begin_request" function is called
  9160. * before an authorization check. If an authorization check is
  9161. * required, use a request_handler instead. */
  9162. i = conn->ctx->callbacks.begin_request(conn);
  9163. if (i > 0) {
  9164. /* callback already processed the request. Store the
  9165. return value as a status code for the access log. */
  9166. conn->status_code = i;
  9167. discard_unread_request_data(conn);
  9168. return;
  9169. } else if (i == 0) {
  9170. /* civetweb should process the request */
  9171. } else {
  9172. /* unspecified - may change with the next version */
  9173. return;
  9174. }
  9175. }
  9176. /* request not yet handled by a handler or redirect, so the request
  9177. * is processed here */
  9178. /* 5. interpret the url to find out how the request must be handled
  9179. */
  9180. /* 5.1. first test, if the request targets the regular http(s)://
  9181. * protocol namespace or the websocket ws(s):// protocol namespace.
  9182. */
  9183. is_websocket_request = is_websocket_protocol(conn);
  9184. /* 5.2. check if the request will be handled by a callback */
  9185. if (get_request_handler(conn,
  9186. is_websocket_request ? WEBSOCKET_HANDLER
  9187. : REQUEST_HANDLER,
  9188. &callback_handler,
  9189. &subprotocols,
  9190. &ws_connect_handler,
  9191. &ws_ready_handler,
  9192. &ws_data_handler,
  9193. &ws_close_handler,
  9194. NULL,
  9195. &callback_data)) {
  9196. /* 5.2.1. A callback will handle this request. All requests
  9197. * handled
  9198. * by a callback have to be considered as requests to a script
  9199. * resource. */
  9200. is_callback_resource = 1;
  9201. is_script_resource = 1;
  9202. is_put_or_delete_request = is_put_or_delete_method(conn);
  9203. } else {
  9204. no_callback_resource:
  9205. /* 5.2.2. No callback is responsible for this request. The URI
  9206. * addresses a file based resource (static content or Lua/cgi
  9207. * scripts in the file system). */
  9208. is_callback_resource = 0;
  9209. interpret_uri(conn,
  9210. path,
  9211. sizeof(path),
  9212. &file.stat,
  9213. &is_found,
  9214. &is_script_resource,
  9215. &is_websocket_request,
  9216. &is_put_or_delete_request);
  9217. }
  9218. /* 6. authorization check */
  9219. /* 6.1. a custom authorization handler is installed */
  9220. if (get_request_handler(conn,
  9221. AUTH_HANDLER,
  9222. NULL,
  9223. NULL,
  9224. NULL,
  9225. NULL,
  9226. NULL,
  9227. NULL,
  9228. &auth_handler,
  9229. &auth_callback_data)) {
  9230. if (!auth_handler(conn, auth_callback_data)) {
  9231. return;
  9232. }
  9233. } else if (is_put_or_delete_request && !is_script_resource
  9234. && !is_callback_resource) {
  9235. /* 6.2. this request is a PUT/DELETE to a real file */
  9236. /* 6.2.1. thus, the server must have real files */
  9237. #if defined(NO_FILES)
  9238. if (1) {
  9239. #else
  9240. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  9241. #endif
  9242. /* This server does not have any real files, thus the
  9243. * PUT/DELETE methods are not valid. */
  9244. send_http_error(conn,
  9245. 405,
  9246. "%s method not allowed",
  9247. conn->request_info.request_method);
  9248. return;
  9249. }
  9250. #if !defined(NO_FILES)
  9251. /* 6.2.2. Check if put authorization for static files is
  9252. * available.
  9253. */
  9254. if (!is_authorized_for_put(conn)) {
  9255. send_authorization_request(conn);
  9256. return;
  9257. }
  9258. #endif
  9259. } else {
  9260. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  9261. * or it is a PUT or DELETE request to a resource that does not
  9262. * correspond to a file. Check authorization. */
  9263. if (!check_authorization(conn, path)) {
  9264. send_authorization_request(conn);
  9265. return;
  9266. }
  9267. }
  9268. /* request is authorized or does not need authorization */
  9269. /* 7. check if there are request handlers for this uri */
  9270. if (is_callback_resource) {
  9271. if (!is_websocket_request) {
  9272. i = callback_handler(conn, callback_data);
  9273. if (i > 0) {
  9274. /* Do nothing, callback has served the request. Store
  9275. * the
  9276. * return value as status code for the log and discard
  9277. * all
  9278. * data from the client not used by the callback. */
  9279. conn->status_code = i;
  9280. discard_unread_request_data(conn);
  9281. } else {
  9282. /* TODO (high): what if the handler did NOT handle the
  9283. * request */
  9284. /* The last version did handle this as a file request,
  9285. * but
  9286. * since a file request is not always a script resource,
  9287. * the authorization check might be different */
  9288. interpret_uri(conn,
  9289. path,
  9290. sizeof(path),
  9291. &file.stat,
  9292. &is_found,
  9293. &is_script_resource,
  9294. &is_websocket_request,
  9295. &is_put_or_delete_request);
  9296. callback_handler = NULL;
  9297. /* TODO (very low): goto is deprecated but for the
  9298. * moment,
  9299. * a goto is simpler than some curious loop. */
  9300. /* The situation "callback does not handle the request"
  9301. * needs to be reconsidered anyway. */
  9302. goto no_callback_resource;
  9303. }
  9304. } else {
  9305. #if defined(USE_WEBSOCKET)
  9306. handle_websocket_request(conn,
  9307. path,
  9308. is_callback_resource,
  9309. subprotocols,
  9310. ws_connect_handler,
  9311. ws_ready_handler,
  9312. ws_data_handler,
  9313. ws_close_handler,
  9314. callback_data);
  9315. #endif
  9316. }
  9317. return;
  9318. }
  9319. /* 8. handle websocket requests */
  9320. #if defined(USE_WEBSOCKET)
  9321. if (is_websocket_request) {
  9322. if (is_script_resource) {
  9323. /* Websocket Lua script */
  9324. handle_websocket_request(conn,
  9325. path,
  9326. 0 /* Lua Script */,
  9327. NULL,
  9328. NULL,
  9329. NULL,
  9330. NULL,
  9331. NULL,
  9332. &conn->ctx->callbacks);
  9333. } else {
  9334. #if defined(MG_LEGACY_INTERFACE)
  9335. handle_websocket_request(
  9336. conn,
  9337. path,
  9338. !is_script_resource /* could be deprecated global callback */,
  9339. NULL,
  9340. deprecated_websocket_connect_wrapper,
  9341. deprecated_websocket_ready_wrapper,
  9342. deprecated_websocket_data_wrapper,
  9343. NULL,
  9344. &conn->ctx->callbacks);
  9345. #else
  9346. send_http_error(conn, 404, "%s", "Not found");
  9347. #endif
  9348. }
  9349. return;
  9350. } else
  9351. #endif
  9352. #if defined(NO_FILES)
  9353. /* 9a. In case the server uses only callbacks, this uri is
  9354. * unknown.
  9355. * Then, all request handling ends here. */
  9356. send_http_error(conn, 404, "%s", "Not Found");
  9357. #else
  9358. /* 9b. This request is either for a static file or resource handled
  9359. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  9360. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  9361. send_http_error(conn, 404, "%s", "Not Found");
  9362. return;
  9363. }
  9364. /* 10. File is handled by a script. */
  9365. if (is_script_resource) {
  9366. handle_file_based_request(conn, path, &file);
  9367. return;
  9368. }
  9369. /* 11. Handle put/delete/mkcol requests */
  9370. if (is_put_or_delete_request) {
  9371. /* 11.1. PUT method */
  9372. if (!strcmp(ri->request_method, "PUT")) {
  9373. put_file(conn, path);
  9374. return;
  9375. }
  9376. /* 11.2. DELETE method */
  9377. if (!strcmp(ri->request_method, "DELETE")) {
  9378. delete_file(conn, path);
  9379. return;
  9380. }
  9381. /* 11.3. MKCOL method */
  9382. if (!strcmp(ri->request_method, "MKCOL")) {
  9383. mkcol(conn, path);
  9384. return;
  9385. }
  9386. /* 11.4. PATCH method
  9387. * This method is not supported for static resources,
  9388. * only for scripts (Lua, CGI) and callbacks. */
  9389. send_http_error(conn,
  9390. 405,
  9391. "%s method not allowed",
  9392. conn->request_info.request_method);
  9393. return;
  9394. }
  9395. /* 11. File does not exist, or it was configured that it should be
  9396. * hidden */
  9397. if (!is_found || (must_hide_file(conn, path))) {
  9398. send_http_error(conn, 404, "%s", "Not found");
  9399. return;
  9400. }
  9401. /* 12. Directory uris should end with a slash */
  9402. if (file.stat.is_directory && (uri_len > 0)
  9403. && (ri->local_uri[uri_len - 1] != '/')) {
  9404. gmt_time_string(date, sizeof(date), &curtime);
  9405. mg_printf(conn,
  9406. "HTTP/1.1 301 Moved Permanently\r\n"
  9407. "Location: %s/\r\n"
  9408. "Date: %s\r\n"
  9409. /* "Cache-Control: private\r\n" (= default) */
  9410. "Content-Length: 0\r\n"
  9411. "Connection: %s\r\n\r\n",
  9412. ri->request_uri,
  9413. date,
  9414. suggest_connection_header(conn));
  9415. return;
  9416. }
  9417. /* 13. Handle other methods than GET/HEAD */
  9418. /* 13.1. Handle PROPFIND */
  9419. if (!strcmp(ri->request_method, "PROPFIND")) {
  9420. handle_propfind(conn, path, &file.stat);
  9421. return;
  9422. }
  9423. /* 13.2. Handle OPTIONS for files */
  9424. if (!strcmp(ri->request_method, "OPTIONS")) {
  9425. /* This standard handler is only used for real files.
  9426. * Scripts should support the OPTIONS method themselves, to allow a
  9427. * maximum flexibility.
  9428. * Lua and CGI scripts may fully support CORS this way (including
  9429. * preflights). */
  9430. send_options(conn);
  9431. return;
  9432. }
  9433. /* 13.3. everything but GET and HEAD (e.g. POST) */
  9434. if (0 != strcmp(ri->request_method, "GET")
  9435. && 0 != strcmp(ri->request_method, "HEAD")) {
  9436. send_http_error(conn,
  9437. 405,
  9438. "%s method not allowed",
  9439. conn->request_info.request_method);
  9440. return;
  9441. }
  9442. /* 14. directories */
  9443. if (file.stat.is_directory) {
  9444. if (substitute_index_file(conn, path, sizeof(path), &file)) {
  9445. /* 14.1. use a substitute file */
  9446. /* TODO (high): substitute index may be a script resource.
  9447. * define what should be possible in this case. */
  9448. } else {
  9449. /* 14.2. no substitute file */
  9450. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  9451. "yes")) {
  9452. handle_directory_request(conn, path);
  9453. } else {
  9454. send_http_error(conn,
  9455. 403,
  9456. "%s",
  9457. "Error: Directory listing denied");
  9458. }
  9459. return;
  9460. }
  9461. }
  9462. handle_file_based_request(conn, path, &file);
  9463. #endif /* !defined(NO_FILES) */
  9464. #if 0
  9465. /* Perform redirect and auth checks before calling begin_request()
  9466. * handler.
  9467. * Otherwise, begin_request() would need to perform auth checks and
  9468. * redirects. */
  9469. #endif
  9470. }
  9471. return;
  9472. }
  9473. static void
  9474. handle_file_based_request(struct mg_connection *conn,
  9475. const char *path,
  9476. struct mg_file *file)
  9477. {
  9478. if (!conn || !conn->ctx) {
  9479. return;
  9480. }
  9481. if (0) {
  9482. #ifdef USE_LUA
  9483. } else if (match_prefix(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  9484. strlen(
  9485. conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  9486. path) > 0) {
  9487. /* Lua server page: an SSI like page containing mostly plain html
  9488. * code
  9489. * plus some tags with server generated contents. */
  9490. handle_lsp_request(conn, path, file, NULL);
  9491. } else if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  9492. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  9493. path) > 0) {
  9494. /* Lua in-server module script: a CGI like script used to generate
  9495. * the
  9496. * entire reply. */
  9497. mg_exec_lua_script(conn, path, NULL);
  9498. #endif
  9499. #if defined(USE_DUKTAPE)
  9500. } else if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  9501. strlen(
  9502. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  9503. path) > 0) {
  9504. /* Call duktape to generate the page */
  9505. mg_exec_duktape_script(conn, path);
  9506. #endif
  9507. #if !defined(NO_CGI)
  9508. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  9509. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  9510. path) > 0) {
  9511. /* CGI scripts may support all HTTP methods */
  9512. handle_cgi_request(conn, path);
  9513. #endif /* !NO_CGI */
  9514. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  9515. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  9516. path) > 0) {
  9517. handle_ssi_file_request(conn, path, file);
  9518. #if !defined(NO_CACHING)
  9519. } else if ((!conn->in_error_handler)
  9520. && is_not_modified(conn, &file->stat)) {
  9521. /* Send 304 "Not Modified" - this must not send any body data */
  9522. handle_not_modified_static_file_request(conn, file);
  9523. #endif /* !NO_CACHING */
  9524. } else {
  9525. handle_static_file_request(conn, path, file, NULL, NULL);
  9526. }
  9527. }
  9528. static void
  9529. close_all_listening_sockets(struct mg_context *ctx)
  9530. {
  9531. unsigned int i;
  9532. if (!ctx) {
  9533. return;
  9534. }
  9535. for (i = 0; i < ctx->num_listening_sockets; i++) {
  9536. closesocket(ctx->listening_sockets[i].sock);
  9537. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  9538. }
  9539. mg_free(ctx->listening_sockets);
  9540. ctx->listening_sockets = NULL;
  9541. mg_free(ctx->listening_socket_fds);
  9542. ctx->listening_socket_fds = NULL;
  9543. }
  9544. /* Valid listening port specification is: [ip_address:]port[s]
  9545. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  9546. * Examples for IPv6: [::]:80, [::1]:80,
  9547. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  9548. * see https://tools.ietf.org/html/rfc3513#section-2.2
  9549. * In order to bind to both, IPv4 and IPv6, you can either add
  9550. * both ports using 8080,[::]:8080, or the short form +8080.
  9551. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  9552. * one only accepting IPv4 the other only IPv6. +8080 creates
  9553. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  9554. * environment, they might work differently, or might not work
  9555. * at all - it must be tested what options work best in the
  9556. * relevant network environment.
  9557. */
  9558. static int
  9559. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  9560. {
  9561. unsigned int a, b, c, d, port;
  9562. int ch, len;
  9563. #if defined(USE_IPV6)
  9564. char buf[100] = {0};
  9565. #endif
  9566. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  9567. * Also, all-zeroes in the socket address means binding to all addresses
  9568. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  9569. memset(so, 0, sizeof(*so));
  9570. so->lsa.sin.sin_family = AF_INET;
  9571. *ip_version = 0;
  9572. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  9573. == 5) {
  9574. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  9575. so->lsa.sin.sin_addr.s_addr =
  9576. htonl((a << 24) | (b << 16) | (c << 8) | d);
  9577. so->lsa.sin.sin_port = htons((uint16_t)port);
  9578. *ip_version = 4;
  9579. #if defined(USE_IPV6)
  9580. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  9581. && mg_inet_pton(
  9582. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  9583. /* IPv6 address, examples: see above */
  9584. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  9585. */
  9586. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  9587. *ip_version = 6;
  9588. #endif
  9589. } else if ((vec->ptr[0] == '+')
  9590. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  9591. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  9592. /* Add 1 to len for the + character we skipped before */
  9593. len++;
  9594. #if defined(USE_IPV6)
  9595. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  9596. so->lsa.sin6.sin6_family = AF_INET6;
  9597. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  9598. *ip_version = 4 + 6;
  9599. #else
  9600. /* Bind to IPv4 only, since IPv6 is not built in. */
  9601. so->lsa.sin.sin_port = htons((uint16_t)port);
  9602. *ip_version = 4;
  9603. #endif
  9604. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  9605. /* If only port is specified, bind to IPv4, INADDR_ANY */
  9606. so->lsa.sin.sin_port = htons((uint16_t)port);
  9607. *ip_version = 4;
  9608. } else {
  9609. /* Parsing failure. Make port invalid. */
  9610. port = 0;
  9611. len = 0;
  9612. }
  9613. /* sscanf and the option splitting code ensure the following condition
  9614. */
  9615. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  9616. *ip_version = 0;
  9617. return 0;
  9618. }
  9619. ch = vec->ptr[len]; /* Next character after the port number */
  9620. so->is_ssl = (ch == 's');
  9621. so->ssl_redir = (ch == 'r');
  9622. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  9623. if (is_valid_port(port)
  9624. && (ch == '\0' || ch == 's' || ch == 'r' || ch == ',')) {
  9625. return 1;
  9626. }
  9627. /* Reset ip_version to 0 of there is an error */
  9628. *ip_version = 0;
  9629. return 0;
  9630. }
  9631. static int
  9632. set_ports_option(struct mg_context *ctx)
  9633. {
  9634. const char *list;
  9635. int on = 1;
  9636. #if defined(USE_IPV6)
  9637. int off = 0;
  9638. #endif
  9639. struct vec vec;
  9640. struct socket so, *ptr;
  9641. struct pollfd *pfd;
  9642. union usa usa;
  9643. socklen_t len;
  9644. int ip_version;
  9645. int portsTotal = 0;
  9646. int portsOk = 0;
  9647. if (!ctx) {
  9648. return 0;
  9649. }
  9650. memset(&so, 0, sizeof(so));
  9651. memset(&usa, 0, sizeof(usa));
  9652. len = sizeof(usa);
  9653. list = ctx->config[LISTENING_PORTS];
  9654. while ((list = next_option(list, &vec, NULL)) != NULL) {
  9655. portsTotal++;
  9656. if (!parse_port_string(&vec, &so, &ip_version)) {
  9657. mg_cry(fc(ctx),
  9658. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  9659. (int)vec.len,
  9660. vec.ptr,
  9661. portsTotal,
  9662. "[IP_ADDRESS:]PORT[s|r]");
  9663. continue;
  9664. }
  9665. #if !defined(NO_SSL)
  9666. if (so.is_ssl && ctx->ssl_ctx == NULL) {
  9667. mg_cry(fc(ctx),
  9668. "Cannot add SSL socket (entry %i). Is -ssl_certificate "
  9669. "option set?",
  9670. portsTotal);
  9671. continue;
  9672. }
  9673. #endif
  9674. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  9675. == INVALID_SOCKET) {
  9676. mg_cry(fc(ctx), "cannot create socket (entry %i)", portsTotal);
  9677. continue;
  9678. }
  9679. #ifdef _WIN32
  9680. /* Windows SO_REUSEADDR lets many procs binds to a
  9681. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  9682. * if someone already has the socket -- DTL */
  9683. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  9684. * Windows might need a few seconds before
  9685. * the same port can be used again in the
  9686. * same process, so a short Sleep may be
  9687. * required between mg_stop and mg_start.
  9688. */
  9689. if (setsockopt(so.sock,
  9690. SOL_SOCKET,
  9691. SO_EXCLUSIVEADDRUSE,
  9692. (SOCK_OPT_TYPE)&on,
  9693. sizeof(on)) != 0) {
  9694. /* Set reuse option, but don't abort on errors. */
  9695. mg_cry(fc(ctx),
  9696. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  9697. portsTotal);
  9698. }
  9699. #else
  9700. if (setsockopt(so.sock,
  9701. SOL_SOCKET,
  9702. SO_REUSEADDR,
  9703. (SOCK_OPT_TYPE)&on,
  9704. sizeof(on)) != 0) {
  9705. /* Set reuse option, but don't abort on errors. */
  9706. mg_cry(fc(ctx),
  9707. "cannot set socket option SO_REUSEADDR (entry %i)",
  9708. portsTotal);
  9709. }
  9710. #endif
  9711. if (ip_version > 4) {
  9712. #if defined(USE_IPV6)
  9713. if (ip_version == 6) {
  9714. if (so.lsa.sa.sa_family == AF_INET6
  9715. && setsockopt(so.sock,
  9716. IPPROTO_IPV6,
  9717. IPV6_V6ONLY,
  9718. (void *)&off,
  9719. sizeof(off)) != 0) {
  9720. /* Set IPv6 only option, but don't abort on errors. */
  9721. mg_cry(fc(ctx),
  9722. "cannot set socket option IPV6_V6ONLY (entry %i)",
  9723. portsTotal);
  9724. }
  9725. }
  9726. #else
  9727. mg_cry(fc(ctx), "IPv6 not available");
  9728. closesocket(so.sock);
  9729. so.sock = INVALID_SOCKET;
  9730. continue;
  9731. #endif
  9732. }
  9733. if (so.lsa.sa.sa_family == AF_INET) {
  9734. len = sizeof(so.lsa.sin);
  9735. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  9736. mg_cry(fc(ctx),
  9737. "cannot bind to %.*s: %d (%s)",
  9738. (int)vec.len,
  9739. vec.ptr,
  9740. (int)ERRNO,
  9741. strerror(errno));
  9742. closesocket(so.sock);
  9743. so.sock = INVALID_SOCKET;
  9744. continue;
  9745. }
  9746. }
  9747. #if defined(USE_IPV6)
  9748. else if (so.lsa.sa.sa_family == AF_INET6) {
  9749. len = sizeof(so.lsa.sin6);
  9750. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  9751. mg_cry(fc(ctx),
  9752. "cannot bind to IPv6 %.*s: %d (%s)",
  9753. (int)vec.len,
  9754. vec.ptr,
  9755. (int)ERRNO,
  9756. strerror(errno));
  9757. closesocket(so.sock);
  9758. so.sock = INVALID_SOCKET;
  9759. continue;
  9760. }
  9761. }
  9762. #endif
  9763. else {
  9764. mg_cry(fc(ctx),
  9765. "cannot bind: address family not supported (entry %i)",
  9766. portsTotal);
  9767. continue;
  9768. }
  9769. if (listen(so.sock, SOMAXCONN) != 0) {
  9770. mg_cry(fc(ctx),
  9771. "cannot listen to %.*s: %d (%s)",
  9772. (int)vec.len,
  9773. vec.ptr,
  9774. (int)ERRNO,
  9775. strerror(errno));
  9776. closesocket(so.sock);
  9777. so.sock = INVALID_SOCKET;
  9778. continue;
  9779. }
  9780. if (getsockname(so.sock, &(usa.sa), &len) != 0
  9781. || usa.sa.sa_family != so.lsa.sa.sa_family) {
  9782. int err = (int)ERRNO;
  9783. mg_cry(fc(ctx),
  9784. "call to getsockname failed %.*s: %d (%s)",
  9785. (int)vec.len,
  9786. vec.ptr,
  9787. err,
  9788. strerror(errno));
  9789. closesocket(so.sock);
  9790. so.sock = INVALID_SOCKET;
  9791. continue;
  9792. }
  9793. /* Update lsa port in case of random free ports */
  9794. #if defined(USE_IPV6)
  9795. if (so.lsa.sa.sa_family == AF_INET6) {
  9796. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  9797. } else
  9798. #endif
  9799. {
  9800. so.lsa.sin.sin_port = usa.sin.sin_port;
  9801. }
  9802. if ((ptr = (struct socket *)
  9803. mg_realloc(ctx->listening_sockets,
  9804. (ctx->num_listening_sockets + 1)
  9805. * sizeof(ctx->listening_sockets[0]))) == NULL) {
  9806. mg_cry(fc(ctx), "%s", "Out of memory");
  9807. closesocket(so.sock);
  9808. so.sock = INVALID_SOCKET;
  9809. continue;
  9810. }
  9811. if ((pfd = (struct pollfd *)mg_realloc(
  9812. ctx->listening_socket_fds,
  9813. (ctx->num_listening_sockets + 1)
  9814. * sizeof(ctx->listening_socket_fds[0]))) == NULL) {
  9815. mg_cry(fc(ctx), "%s", "Out of memory");
  9816. closesocket(so.sock);
  9817. so.sock = INVALID_SOCKET;
  9818. mg_free(ptr);
  9819. continue;
  9820. }
  9821. set_close_on_exec(so.sock, fc(ctx));
  9822. ctx->listening_sockets = ptr;
  9823. ctx->listening_sockets[ctx->num_listening_sockets] = so;
  9824. ctx->listening_socket_fds = pfd;
  9825. ctx->num_listening_sockets++;
  9826. portsOk++;
  9827. }
  9828. if (portsOk != portsTotal) {
  9829. close_all_listening_sockets(ctx);
  9830. portsOk = 0;
  9831. }
  9832. return portsOk;
  9833. }
  9834. static const char *
  9835. header_val(const struct mg_connection *conn, const char *header)
  9836. {
  9837. const char *header_value;
  9838. if ((header_value = mg_get_header(conn, header)) == NULL) {
  9839. return "-";
  9840. } else {
  9841. return header_value;
  9842. }
  9843. }
  9844. static void
  9845. log_access(const struct mg_connection *conn)
  9846. {
  9847. const struct mg_request_info *ri;
  9848. struct mg_file fi;
  9849. char date[64], src_addr[IP_ADDR_STR_LEN];
  9850. struct tm *tm;
  9851. const char *referer;
  9852. const char *user_agent;
  9853. char buf[4096];
  9854. if (!conn || !conn->ctx) {
  9855. return;
  9856. }
  9857. if (conn->ctx->config[ACCESS_LOG_FILE] != NULL) {
  9858. if (mg_fopen(conn,
  9859. conn->ctx->config[ACCESS_LOG_FILE],
  9860. MG_FOPEN_MODE_APPEND,
  9861. &fi) == 0) {
  9862. fi.access.fp = NULL;
  9863. }
  9864. } else {
  9865. fi.access.fp = NULL;
  9866. }
  9867. /* Log is written to a file and/or a callback. If both are not set,
  9868. * executing the rest of the function is pointless. */
  9869. if ((fi.access.fp == NULL) && (conn->ctx->callbacks.log_access == NULL)) {
  9870. return;
  9871. }
  9872. tm = localtime(&conn->conn_birth_time);
  9873. if (tm != NULL) {
  9874. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  9875. } else {
  9876. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  9877. date[sizeof(date) - 1] = '\0';
  9878. }
  9879. ri = &conn->request_info;
  9880. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9881. referer = header_val(conn, "Referer");
  9882. user_agent = header_val(conn, "User-Agent");
  9883. mg_snprintf(conn,
  9884. NULL, /* Ignore truncation in access log */
  9885. buf,
  9886. sizeof(buf),
  9887. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  9888. src_addr,
  9889. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  9890. date,
  9891. ri->request_method ? ri->request_method : "-",
  9892. ri->request_uri ? ri->request_uri : "-",
  9893. ri->query_string ? "?" : "",
  9894. ri->query_string ? ri->query_string : "",
  9895. ri->http_version,
  9896. conn->status_code,
  9897. conn->num_bytes_sent,
  9898. referer,
  9899. user_agent);
  9900. if (conn->ctx->callbacks.log_access) {
  9901. conn->ctx->callbacks.log_access(conn, buf);
  9902. }
  9903. if (fi.access.fp) {
  9904. int ok = 1;
  9905. flockfile(fi.access.fp);
  9906. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  9907. ok = 0;
  9908. }
  9909. if (fflush(fi.access.fp) != 0) {
  9910. ok = 0;
  9911. }
  9912. funlockfile(fi.access.fp);
  9913. if (mg_fclose(&fi.access) != 0) {
  9914. ok = 0;
  9915. }
  9916. if (!ok) {
  9917. mg_cry(conn,
  9918. "Error writing log file %s",
  9919. conn->ctx->config[ACCESS_LOG_FILE]);
  9920. }
  9921. }
  9922. }
  9923. /* Verify given socket address against the ACL.
  9924. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  9925. */
  9926. static int
  9927. check_acl(struct mg_context *ctx, uint32_t remote_ip)
  9928. {
  9929. int allowed, flag;
  9930. uint32_t net, mask;
  9931. struct vec vec;
  9932. if (ctx) {
  9933. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  9934. /* If any ACL is set, deny by default */
  9935. allowed = (list == NULL) ? '+' : '-';
  9936. while ((list = next_option(list, &vec, NULL)) != NULL) {
  9937. flag = vec.ptr[0];
  9938. if ((flag != '+' && flag != '-')
  9939. || parse_net(&vec.ptr[1], &net, &mask) == 0) {
  9940. mg_cry(fc(ctx),
  9941. "%s: subnet must be [+|-]x.x.x.x[/x]",
  9942. __func__);
  9943. return -1;
  9944. }
  9945. if (net == (remote_ip & mask)) {
  9946. allowed = flag;
  9947. }
  9948. }
  9949. return allowed == '+';
  9950. }
  9951. return -1;
  9952. }
  9953. #if !defined(_WIN32)
  9954. static int
  9955. set_uid_option(struct mg_context *ctx)
  9956. {
  9957. struct passwd *pw;
  9958. if (ctx) {
  9959. const char *uid = ctx->config[RUN_AS_USER];
  9960. int success = 0;
  9961. if (uid == NULL) {
  9962. success = 1;
  9963. } else {
  9964. if ((pw = getpwnam(uid)) == NULL) {
  9965. mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  9966. } else if (setgid(pw->pw_gid) == -1) {
  9967. mg_cry(fc(ctx),
  9968. "%s: setgid(%s): %s",
  9969. __func__,
  9970. uid,
  9971. strerror(errno));
  9972. } else if (setgroups(0, NULL)) {
  9973. mg_cry(fc(ctx),
  9974. "%s: setgroups(): %s",
  9975. __func__,
  9976. strerror(errno));
  9977. } else if (setuid(pw->pw_uid) == -1) {
  9978. mg_cry(fc(ctx),
  9979. "%s: setuid(%s): %s",
  9980. __func__,
  9981. uid,
  9982. strerror(errno));
  9983. } else {
  9984. success = 1;
  9985. }
  9986. }
  9987. return success;
  9988. }
  9989. return 0;
  9990. }
  9991. #endif /* !_WIN32 */
  9992. static void
  9993. tls_dtor(void *key)
  9994. {
  9995. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  9996. /* key == pthread_getspecific(sTlsKey); */
  9997. if (tls) {
  9998. if (tls->is_master == 2) {
  9999. tls->is_master = -3; /* Mark memory as dead */
  10000. mg_free(tls);
  10001. }
  10002. }
  10003. pthread_setspecific(sTlsKey, NULL);
  10004. }
  10005. #if !defined(NO_SSL)
  10006. static int ssl_use_pem_file(struct mg_context *ctx, const char *pem);
  10007. static const char *ssl_error(void);
  10008. static int
  10009. refresh_trust(struct mg_connection *conn)
  10010. {
  10011. static int reload_lock = 0;
  10012. static long int data_check = 0;
  10013. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  10014. struct stat cert_buf;
  10015. long int t;
  10016. char *pem;
  10017. int should_verify_peer;
  10018. if ((pem = conn->ctx->config[SSL_CERTIFICATE]) == NULL) {
  10019. /* If peem is NULL and conn->ctx->callbacks.init_ssl is not,
  10020. * refresh_trust still can not work. */
  10021. return 0;
  10022. }
  10023. t = data_check;
  10024. if (stat(pem, &cert_buf) != -1) {
  10025. t = (long int)cert_buf.st_mtime;
  10026. }
  10027. if (data_check != t) {
  10028. data_check = t;
  10029. should_verify_peer =
  10030. (conn->ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  10031. && (mg_strcasecmp(conn->ctx->config[SSL_DO_VERIFY_PEER], "yes")
  10032. == 0);
  10033. if (should_verify_peer) {
  10034. char *ca_path = conn->ctx->config[SSL_CA_PATH];
  10035. char *ca_file = conn->ctx->config[SSL_CA_FILE];
  10036. if (SSL_CTX_load_verify_locations(conn->ctx->ssl_ctx,
  10037. ca_file,
  10038. ca_path) != 1) {
  10039. mg_cry(fc(conn->ctx),
  10040. "SSL_CTX_load_verify_locations error: %s "
  10041. "ssl_verify_peer requires setting "
  10042. "either ssl_ca_path or ssl_ca_file. Is any of them "
  10043. "present in "
  10044. "the .conf file?",
  10045. ssl_error());
  10046. return 0;
  10047. }
  10048. }
  10049. if (1 == mg_atomic_inc(p_reload_lock)) {
  10050. if (ssl_use_pem_file(conn->ctx, pem) == 0) {
  10051. return 0;
  10052. }
  10053. *p_reload_lock = 0;
  10054. }
  10055. }
  10056. /* lock while cert is reloading */
  10057. while (*p_reload_lock) {
  10058. sleep(1);
  10059. }
  10060. return 1;
  10061. }
  10062. static pthread_mutex_t *ssl_mutexes;
  10063. static int
  10064. sslize(struct mg_connection *conn,
  10065. SSL_CTX *s,
  10066. int (*func)(SSL *),
  10067. volatile int *stop_server)
  10068. {
  10069. int ret, err;
  10070. int short_trust;
  10071. unsigned i;
  10072. if (!conn) {
  10073. return 0;
  10074. }
  10075. short_trust =
  10076. (conn->ctx->config[SSL_SHORT_TRUST] != NULL)
  10077. && (mg_strcasecmp(conn->ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  10078. if (short_trust) {
  10079. int trust_ret = refresh_trust(conn);
  10080. if (!trust_ret) {
  10081. return trust_ret;
  10082. }
  10083. }
  10084. conn->ssl = SSL_new(s);
  10085. if (conn->ssl == NULL) {
  10086. return 0;
  10087. }
  10088. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  10089. if (ret != 1) {
  10090. err = SSL_get_error(conn->ssl, ret);
  10091. (void)err; /* TODO: set some error message */
  10092. SSL_free(conn->ssl);
  10093. conn->ssl = NULL;
  10094. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  10095. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  10096. ERR_remove_state(0);
  10097. return 0;
  10098. }
  10099. /* SSL functions may fail and require to be called again:
  10100. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  10101. * Here "func" could be SSL_connect or SSL_accept. */
  10102. for (i = 16; i <= 1024; i *= 2) {
  10103. ret = func(conn->ssl);
  10104. if (ret != 1) {
  10105. err = SSL_get_error(conn->ssl, ret);
  10106. if ((err == SSL_ERROR_WANT_CONNECT)
  10107. || (err == SSL_ERROR_WANT_ACCEPT)
  10108. || (err == SSL_ERROR_WANT_READ)
  10109. || (err == SSL_ERROR_WANT_WRITE)) {
  10110. /* Need to retry the function call "later".
  10111. * See https://linux.die.net/man/3/ssl_get_error
  10112. * This is typical for non-blocking sockets. */
  10113. if (*stop_server) {
  10114. /* Don't wait if the server is going to be stopped. */
  10115. break;
  10116. }
  10117. mg_sleep(i);
  10118. } else if (err == SSL_ERROR_SYSCALL) {
  10119. /* This is an IO error. Look at errno. */
  10120. err = errno;
  10121. /* TODO: set some error message */
  10122. break;
  10123. } else {
  10124. /* This is an SSL specific error */
  10125. /* TODO: set some error message */
  10126. break;
  10127. }
  10128. } else {
  10129. /* success */
  10130. break;
  10131. }
  10132. }
  10133. if (ret != 1) {
  10134. SSL_free(conn->ssl);
  10135. conn->ssl = NULL;
  10136. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  10137. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  10138. ERR_remove_state(0);
  10139. return 0;
  10140. }
  10141. return 1;
  10142. }
  10143. /* Return OpenSSL error message (from CRYPTO lib) */
  10144. static const char *
  10145. ssl_error(void)
  10146. {
  10147. unsigned long err;
  10148. err = ERR_get_error();
  10149. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  10150. }
  10151. static int
  10152. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  10153. {
  10154. int i;
  10155. const char hexdigit[] = "0123456789abcdef";
  10156. if (memlen <= 0 || buflen <= 0) {
  10157. return 0;
  10158. }
  10159. if (buflen < (3 * memlen)) {
  10160. return 0;
  10161. }
  10162. for (i = 0; i < memlen; i++) {
  10163. if (i > 0) {
  10164. buf[3 * i - 1] = ' ';
  10165. }
  10166. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  10167. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  10168. }
  10169. buf[3 * memlen - 1] = 0;
  10170. return 1;
  10171. }
  10172. static void
  10173. ssl_get_client_cert_info(struct mg_connection *conn)
  10174. {
  10175. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  10176. if (cert) {
  10177. char str_subject[1024];
  10178. char str_issuer[1024];
  10179. char str_serial[1024];
  10180. char str_finger[1024];
  10181. unsigned char buf[256];
  10182. int len;
  10183. unsigned int ulen;
  10184. /* Handle to algorithm used for fingerprint */
  10185. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  10186. /* Get Subject and issuer */
  10187. X509_NAME *subj = X509_get_subject_name(cert);
  10188. X509_NAME *iss = X509_get_issuer_name(cert);
  10189. /* Get serial number */
  10190. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  10191. /* Translate subject and issuer to a string */
  10192. (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
  10193. (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
  10194. /* Translate serial number to a hex string */
  10195. len = i2c_ASN1_INTEGER(serial, NULL);
  10196. if ((len > 0) && ((unsigned)len < (unsigned)sizeof(buf))) {
  10197. unsigned char *pbuf = buf;
  10198. int len2 = i2c_ASN1_INTEGER(serial, &pbuf);
  10199. if (!hexdump2string(
  10200. buf, len2, str_serial, (int)sizeof(str_serial))) {
  10201. *str_serial = 0;
  10202. }
  10203. } else {
  10204. *str_serial = 0;
  10205. }
  10206. /* Calculate SHA1 fingerprint and store as a hex string */
  10207. ulen = 0;
  10208. ASN1_digest((int (*)())i2d_X509, digest, (char *)cert, buf, &ulen);
  10209. if (!hexdump2string(
  10210. buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
  10211. *str_finger = 0;
  10212. }
  10213. conn->request_info.client_cert =
  10214. (struct client_cert *)mg_malloc(sizeof(struct client_cert));
  10215. if (conn->request_info.client_cert) {
  10216. conn->request_info.client_cert->subject = mg_strdup(str_subject);
  10217. conn->request_info.client_cert->issuer = mg_strdup(str_issuer);
  10218. conn->request_info.client_cert->serial = mg_strdup(str_serial);
  10219. conn->request_info.client_cert->finger = mg_strdup(str_finger);
  10220. } else {
  10221. /* TODO: write some OOM message */
  10222. }
  10223. X509_free(cert);
  10224. }
  10225. }
  10226. static void
  10227. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  10228. {
  10229. (void)line;
  10230. (void)file;
  10231. if (mode & 1) {
  10232. /* 1 is CRYPTO_LOCK */
  10233. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  10234. } else {
  10235. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  10236. }
  10237. }
  10238. #if !defined(NO_SSL_DL)
  10239. static void *
  10240. load_dll(struct mg_context *ctx, const char *dll_name, struct ssl_func *sw)
  10241. {
  10242. union {
  10243. void *p;
  10244. void (*fp)(void);
  10245. } u;
  10246. void *dll_handle;
  10247. struct ssl_func *fp;
  10248. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  10249. mg_cry(fc(ctx), "%s: cannot load %s", __func__, dll_name);
  10250. return NULL;
  10251. }
  10252. for (fp = sw; fp->name != NULL; fp++) {
  10253. #ifdef _WIN32
  10254. /* GetProcAddress() returns pointer to function */
  10255. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  10256. #else
  10257. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  10258. * pointers to function pointers. We need to use a union to make a
  10259. * cast. */
  10260. u.p = dlsym(dll_handle, fp->name);
  10261. #endif /* _WIN32 */
  10262. if (u.fp == NULL) {
  10263. mg_cry(fc(ctx),
  10264. "%s: %s: cannot find %s",
  10265. __func__,
  10266. dll_name,
  10267. fp->name);
  10268. dlclose(dll_handle);
  10269. return NULL;
  10270. } else {
  10271. fp->ptr = u.fp;
  10272. }
  10273. }
  10274. return dll_handle;
  10275. }
  10276. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  10277. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  10278. #endif /* NO_SSL_DL */
  10279. #if defined(SSL_ALREADY_INITIALIZED)
  10280. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  10281. #else
  10282. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  10283. #endif
  10284. static int
  10285. initialize_ssl(struct mg_context *ctx)
  10286. {
  10287. int i;
  10288. size_t size;
  10289. #if !defined(NO_SSL_DL)
  10290. if (!cryptolib_dll_handle) {
  10291. cryptolib_dll_handle = load_dll(ctx, CRYPTO_LIB, crypto_sw);
  10292. if (!cryptolib_dll_handle) {
  10293. return 0;
  10294. }
  10295. }
  10296. #endif /* NO_SSL_DL */
  10297. if (mg_atomic_inc(&cryptolib_users) > 1) {
  10298. return 1;
  10299. }
  10300. /* Initialize locking callbacks, needed for thread safety.
  10301. * http://www.openssl.org/support/faq.html#PROG1
  10302. */
  10303. i = CRYPTO_num_locks();
  10304. if (i < 0) {
  10305. i = 0;
  10306. }
  10307. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  10308. if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  10309. mg_cry(fc(ctx),
  10310. "%s: cannot allocate mutexes: %s",
  10311. __func__,
  10312. ssl_error());
  10313. return 0;
  10314. }
  10315. for (i = 0; i < CRYPTO_num_locks(); i++) {
  10316. pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr);
  10317. }
  10318. CRYPTO_set_locking_callback(&ssl_locking_callback);
  10319. CRYPTO_set_id_callback(&mg_current_thread_id);
  10320. return 1;
  10321. }
  10322. static int
  10323. ssl_use_pem_file(struct mg_context *ctx, const char *pem)
  10324. {
  10325. if (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0) {
  10326. mg_cry(fc(ctx),
  10327. "%s: cannot open certificate file %s: %s",
  10328. __func__,
  10329. pem,
  10330. ssl_error());
  10331. return 0;
  10332. }
  10333. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  10334. if (SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0) {
  10335. mg_cry(fc(ctx),
  10336. "%s: cannot open private key file %s: %s",
  10337. __func__,
  10338. pem,
  10339. ssl_error());
  10340. return 0;
  10341. }
  10342. if (SSL_CTX_check_private_key(ctx->ssl_ctx) == 0) {
  10343. mg_cry(fc(ctx),
  10344. "%s: certificate and private key do not match: %s",
  10345. __func__,
  10346. pem);
  10347. return 0;
  10348. }
  10349. if (SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem) == 0) {
  10350. mg_cry(fc(ctx),
  10351. "%s: cannot use certificate chain file %s: %s",
  10352. __func__,
  10353. pem,
  10354. ssl_error());
  10355. return 0;
  10356. }
  10357. return 1;
  10358. }
  10359. static long
  10360. ssl_get_protocol(int version_id)
  10361. {
  10362. long ret = SSL_OP_ALL;
  10363. if (version_id > 0)
  10364. ret |= SSL_OP_NO_SSLv2;
  10365. if (version_id > 1)
  10366. ret |= SSL_OP_NO_SSLv3;
  10367. if (version_id > 2)
  10368. ret |= SSL_OP_NO_TLSv1;
  10369. if (version_id > 3)
  10370. ret |= SSL_OP_NO_TLSv1_1;
  10371. return ret;
  10372. }
  10373. /* Dynamically load SSL library. Set up ctx->ssl_ctx pointer. */
  10374. static int
  10375. set_ssl_option(struct mg_context *ctx)
  10376. {
  10377. const char *pem;
  10378. int callback_ret;
  10379. int should_verify_peer;
  10380. const char *ca_path;
  10381. const char *ca_file;
  10382. int use_default_verify_paths;
  10383. int verify_depth;
  10384. time_t now_rt = time(NULL);
  10385. struct timespec now_mt;
  10386. md5_byte_t ssl_context_id[16];
  10387. md5_state_t md5state;
  10388. int protocol_ver;
  10389. /* If PEM file is not specified and the init_ssl callback
  10390. * is not specified, skip SSL initialization. */
  10391. if (!ctx) {
  10392. return 0;
  10393. }
  10394. if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL
  10395. && ctx->callbacks.init_ssl == NULL) {
  10396. return 1;
  10397. }
  10398. if (!initialize_ssl(ctx)) {
  10399. return 0;
  10400. }
  10401. #if !defined(NO_SSL_DL)
  10402. if (!ssllib_dll_handle) {
  10403. ssllib_dll_handle = load_dll(ctx, SSL_LIB, ssl_sw);
  10404. if (!ssllib_dll_handle) {
  10405. return 0;
  10406. }
  10407. }
  10408. #endif /* NO_SSL_DL */
  10409. /* Initialize SSL library */
  10410. SSL_library_init();
  10411. SSL_load_error_strings();
  10412. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  10413. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  10414. return 0;
  10415. }
  10416. SSL_CTX_clear_options(ctx->ssl_ctx,
  10417. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  10418. | SSL_OP_NO_TLSv1_1);
  10419. protocol_ver = atoi(ctx->config[SSL_PROTOCOL_VERSION]);
  10420. SSL_CTX_set_options(ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  10421. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  10422. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  10423. SSL_CTX_set_ecdh_auto(ctx->ssl_ctx, 1);
  10424. /* If a callback has been specified, call it. */
  10425. callback_ret =
  10426. (ctx->callbacks.init_ssl == NULL)
  10427. ? 0
  10428. : (ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data));
  10429. /* If callback returns 0, civetweb sets up the SSL certificate.
  10430. * If it returns 1, civetweb assumes the calback already did this.
  10431. * If it returns -1, initializing ssl fails. */
  10432. if (callback_ret < 0) {
  10433. mg_cry(fc(ctx), "SSL callback returned error: %i", callback_ret);
  10434. return 0;
  10435. }
  10436. if (callback_ret > 0) {
  10437. if (pem != NULL) {
  10438. (void)SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
  10439. }
  10440. return 1;
  10441. }
  10442. /* Use some UID as session context ID. */
  10443. md5_init(&md5state);
  10444. md5_append(&md5state, (const md5_byte_t *)&now_rt, sizeof(now_rt));
  10445. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  10446. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  10447. md5_append(&md5state,
  10448. (const md5_byte_t *)ctx->config[LISTENING_PORTS],
  10449. strlen(ctx->config[LISTENING_PORTS]));
  10450. md5_append(&md5state, (const md5_byte_t *)ctx, sizeof(*ctx));
  10451. md5_finish(&md5state, ssl_context_id);
  10452. SSL_CTX_set_session_id_context(ctx->ssl_ctx,
  10453. (const unsigned char *)&ssl_context_id,
  10454. sizeof(ssl_context_id));
  10455. if (pem != NULL) {
  10456. if (!ssl_use_pem_file(ctx, pem)) {
  10457. return 0;
  10458. }
  10459. }
  10460. should_verify_peer =
  10461. (ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  10462. && (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0);
  10463. use_default_verify_paths =
  10464. (ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  10465. && (mg_strcasecmp(ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes") == 0);
  10466. if (should_verify_peer) {
  10467. ca_path = ctx->config[SSL_CA_PATH];
  10468. ca_file = ctx->config[SSL_CA_FILE];
  10469. if (SSL_CTX_load_verify_locations(ctx->ssl_ctx, ca_file, ca_path)
  10470. != 1) {
  10471. mg_cry(fc(ctx),
  10472. "SSL_CTX_load_verify_locations error: %s "
  10473. "ssl_verify_peer requires setting "
  10474. "either ssl_ca_path or ssl_ca_file. Is any of them "
  10475. "present in "
  10476. "the .conf file?",
  10477. ssl_error());
  10478. return 0;
  10479. }
  10480. SSL_CTX_set_verify(ctx->ssl_ctx,
  10481. SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  10482. NULL);
  10483. if (use_default_verify_paths
  10484. && SSL_CTX_set_default_verify_paths(ctx->ssl_ctx) != 1) {
  10485. mg_cry(fc(ctx),
  10486. "SSL_CTX_set_default_verify_paths error: %s",
  10487. ssl_error());
  10488. return 0;
  10489. }
  10490. if (ctx->config[SSL_VERIFY_DEPTH]) {
  10491. verify_depth = atoi(ctx->config[SSL_VERIFY_DEPTH]);
  10492. SSL_CTX_set_verify_depth(ctx->ssl_ctx, verify_depth);
  10493. }
  10494. }
  10495. if (ctx->config[SSL_CIPHER_LIST] != NULL) {
  10496. if (SSL_CTX_set_cipher_list(ctx->ssl_ctx, ctx->config[SSL_CIPHER_LIST])
  10497. != 1) {
  10498. mg_cry(fc(ctx), "SSL_CTX_set_cipher_list error: %s", ssl_error());
  10499. }
  10500. }
  10501. return 1;
  10502. }
  10503. static void
  10504. uninitialize_ssl(struct mg_context *ctx)
  10505. {
  10506. int i;
  10507. (void)ctx;
  10508. if (mg_atomic_dec(&cryptolib_users) == 0) {
  10509. /* Shutdown according to
  10510. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  10511. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  10512. */
  10513. CRYPTO_set_locking_callback(NULL);
  10514. CRYPTO_set_id_callback(NULL);
  10515. ENGINE_cleanup();
  10516. CONF_modules_unload(1);
  10517. ERR_free_strings();
  10518. EVP_cleanup();
  10519. CRYPTO_cleanup_all_ex_data();
  10520. ERR_remove_state(0);
  10521. for (i = 0; i < CRYPTO_num_locks(); i++) {
  10522. pthread_mutex_destroy(&ssl_mutexes[i]);
  10523. }
  10524. mg_free(ssl_mutexes);
  10525. ssl_mutexes = NULL;
  10526. }
  10527. }
  10528. #endif /* !NO_SSL */
  10529. static int
  10530. set_gpass_option(struct mg_context *ctx)
  10531. {
  10532. if (ctx) {
  10533. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10534. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  10535. if (path != NULL && !mg_stat(fc(ctx), path, &file.stat)) {
  10536. mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  10537. return 0;
  10538. }
  10539. return 1;
  10540. }
  10541. return 0;
  10542. }
  10543. static int
  10544. set_acl_option(struct mg_context *ctx)
  10545. {
  10546. return check_acl(ctx, (uint32_t)0x7f000001UL) != -1;
  10547. }
  10548. static void
  10549. reset_per_request_attributes(struct mg_connection *conn)
  10550. {
  10551. if (!conn) {
  10552. return;
  10553. }
  10554. conn->path_info = NULL;
  10555. conn->num_bytes_sent = conn->consumed_content = 0;
  10556. conn->status_code = -1;
  10557. conn->is_chunked = 0;
  10558. conn->must_close = conn->request_len = conn->throttle = 0;
  10559. conn->request_info.content_length = -1;
  10560. conn->request_info.remote_user = NULL;
  10561. conn->request_info.request_method = NULL;
  10562. conn->request_info.request_uri = NULL;
  10563. conn->request_info.local_uri = NULL;
  10564. conn->request_info.uri = NULL; /* TODO: cleanup uri,
  10565. * local_uri and request_uri */
  10566. conn->request_info.http_version = NULL;
  10567. conn->request_info.num_headers = 0;
  10568. conn->data_len = 0;
  10569. conn->chunk_remainder = 0;
  10570. }
  10571. #if 0
  10572. /* Note: set_sock_timeout is not required for non-blocking sockets.
  10573. * Leave this function here (commented out) for reference until
  10574. * CivetWeb 1.9 is tested, and the tests confirme this function is
  10575. * no longer required.
  10576. */
  10577. static int
  10578. set_sock_timeout(SOCKET sock, int milliseconds)
  10579. {
  10580. int r0 = 0, r1, r2;
  10581. #ifdef _WIN32
  10582. /* Windows specific */
  10583. DWORD tv = (DWORD)milliseconds;
  10584. #else
  10585. /* Linux, ... (not Windows) */
  10586. struct timeval tv;
  10587. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  10588. * max. time waiting for the acknowledged of TCP data before the connection
  10589. * will be forcefully closed and ETIMEDOUT is returned to the application.
  10590. * If this option is not set, the default timeout of 20-30 minutes is used.
  10591. */
  10592. /* #define TCP_USER_TIMEOUT (18) */
  10593. #if defined(TCP_USER_TIMEOUT)
  10594. unsigned int uto = (unsigned int)milliseconds;
  10595. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  10596. #endif
  10597. memset(&tv, 0, sizeof(tv));
  10598. tv.tv_sec = milliseconds / 1000;
  10599. tv.tv_usec = (milliseconds * 1000) % 1000000;
  10600. #endif /* _WIN32 */
  10601. r1 = setsockopt(
  10602. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  10603. r2 = setsockopt(
  10604. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  10605. return r0 || r1 || r2;
  10606. }
  10607. #endif
  10608. static int
  10609. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  10610. {
  10611. if (setsockopt(sock,
  10612. IPPROTO_TCP,
  10613. TCP_NODELAY,
  10614. (SOCK_OPT_TYPE)&nodelay_on,
  10615. sizeof(nodelay_on)) != 0) {
  10616. /* Error */
  10617. return 1;
  10618. }
  10619. /* OK */
  10620. return 0;
  10621. }
  10622. static void
  10623. close_socket_gracefully(struct mg_connection *conn)
  10624. {
  10625. #if defined(_WIN32)
  10626. char buf[MG_BUF_LEN];
  10627. int n;
  10628. #endif
  10629. struct linger linger;
  10630. int error_code = 0;
  10631. int linger_timeout = -2;
  10632. socklen_t opt_len = sizeof(error_code);
  10633. if (!conn) {
  10634. return;
  10635. }
  10636. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  10637. * "Note that enabling a nonzero timeout on a nonblocking socket
  10638. * is not recommended.", so set it to blocking now */
  10639. set_blocking_mode(conn->client.sock, 1);
  10640. /* Send FIN to the client */
  10641. shutdown(conn->client.sock, SHUTDOWN_WR);
  10642. #if defined(_WIN32)
  10643. /* Read and discard pending incoming data. If we do not do that and
  10644. * close
  10645. * the socket, the data in the send buffer may be discarded. This
  10646. * behaviour is seen on Windows, when client keeps sending data
  10647. * when server decides to close the connection; then when client
  10648. * does recv() it gets no data back. */
  10649. do {
  10650. n = pull(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  10651. } while (n > 0);
  10652. #endif
  10653. if (conn->ctx->config[LINGER_TIMEOUT]) {
  10654. linger_timeout = atoi(conn->ctx->config[LINGER_TIMEOUT]);
  10655. }
  10656. /* Set linger option according to configuration */
  10657. if (linger_timeout >= 0) {
  10658. /* Set linger option to avoid socket hanging out after close. This
  10659. * prevent ephemeral port exhaust problem under high QPS. */
  10660. linger.l_onoff = 1;
  10661. #if defined(_MSC_VER)
  10662. #pragma warning(push)
  10663. #pragma warning(disable : 4244)
  10664. #endif
  10665. linger.l_linger = (linger_timeout + 999) / 1000;
  10666. #if defined(_MSC_VER)
  10667. #pragma warning(pop)
  10668. #endif
  10669. } else {
  10670. linger.l_onoff = 0;
  10671. linger.l_linger = 0;
  10672. }
  10673. if (linger_timeout < -1) {
  10674. /* Default: don't configure any linger */
  10675. } else if (getsockopt(conn->client.sock,
  10676. SOL_SOCKET,
  10677. SO_ERROR,
  10678. (char *)&error_code,
  10679. &opt_len) != 0) {
  10680. /* Cannot determine if socket is already closed. This should
  10681. * not occur and never did in a test. Log an error message
  10682. * and continue. */
  10683. mg_cry(conn,
  10684. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  10685. __func__,
  10686. strerror(ERRNO));
  10687. } else if (error_code == ECONNRESET) {
  10688. /* Socket already closed by client/peer, close socket without linger */
  10689. } else {
  10690. /* Set linger timeout */
  10691. if (setsockopt(conn->client.sock,
  10692. SOL_SOCKET,
  10693. SO_LINGER,
  10694. (char *)&linger,
  10695. sizeof(linger)) != 0) {
  10696. mg_cry(conn,
  10697. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  10698. __func__,
  10699. linger.l_onoff,
  10700. linger.l_linger,
  10701. strerror(ERRNO));
  10702. }
  10703. }
  10704. /* Now we know that our FIN is ACK-ed, safe to close */
  10705. closesocket(conn->client.sock);
  10706. conn->client.sock = INVALID_SOCKET;
  10707. }
  10708. static void
  10709. close_connection(struct mg_connection *conn)
  10710. {
  10711. if (!conn || !conn->ctx) {
  10712. return;
  10713. }
  10714. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  10715. if (conn->lua_websocket_state) {
  10716. lua_websocket_close(conn, conn->lua_websocket_state);
  10717. conn->lua_websocket_state = NULL;
  10718. }
  10719. #endif
  10720. /* call the connection_close callback if assigned */
  10721. if ((conn->ctx->callbacks.connection_close != NULL)
  10722. && (conn->ctx->context_type == 1)) {
  10723. conn->ctx->callbacks.connection_close(conn);
  10724. }
  10725. mg_lock_connection(conn);
  10726. conn->must_close = 1;
  10727. #ifndef NO_SSL
  10728. if (conn->ssl != NULL) {
  10729. /* Run SSL_shutdown twice to ensure completly close SSL connection
  10730. */
  10731. SSL_shutdown(conn->ssl);
  10732. SSL_free(conn->ssl);
  10733. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  10734. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  10735. ERR_remove_state(0);
  10736. conn->ssl = NULL;
  10737. }
  10738. #endif
  10739. if (conn->client.sock != INVALID_SOCKET) {
  10740. close_socket_gracefully(conn);
  10741. conn->client.sock = INVALID_SOCKET;
  10742. }
  10743. mg_unlock_connection(conn);
  10744. }
  10745. void
  10746. mg_close_connection(struct mg_connection *conn)
  10747. {
  10748. struct mg_context *client_ctx = NULL;
  10749. if (conn == NULL) {
  10750. return;
  10751. }
  10752. #if defined(USE_WEBSOCKET)
  10753. if (conn->ctx->context_type == 2) {
  10754. unsigned int i;
  10755. /* ws/wss client */
  10756. client_ctx = conn->ctx;
  10757. /* client context: loops must end */
  10758. conn->ctx->stop_flag = 1;
  10759. /* We need to get the client thread out of the select/recv call here. */
  10760. /* Since we use a sleep quantum of some seconds to check for recv
  10761. * timeouts, we will just wait a few seconds in mg_join_thread. */
  10762. /* join worker thread */
  10763. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  10764. if (client_ctx->workerthreadids[i] != 0) {
  10765. mg_join_thread(client_ctx->workerthreadids[i]);
  10766. }
  10767. }
  10768. }
  10769. #else
  10770. (void)client_ctx;
  10771. #endif
  10772. close_connection(conn);
  10773. #ifndef NO_SSL
  10774. if (conn->client_ssl_ctx != NULL) {
  10775. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  10776. }
  10777. #endif
  10778. if (client_ctx != NULL) {
  10779. /* free context */
  10780. mg_free(client_ctx->workerthreadids);
  10781. mg_free(client_ctx);
  10782. (void)pthread_mutex_destroy(&conn->mutex);
  10783. mg_free(conn);
  10784. }
  10785. }
  10786. static struct mg_connection *
  10787. mg_connect_client_impl(const struct mg_client_options *client_options,
  10788. int use_ssl,
  10789. char *ebuf,
  10790. size_t ebuf_len)
  10791. {
  10792. static struct mg_context fake_ctx;
  10793. struct mg_connection *conn = NULL;
  10794. SOCKET sock;
  10795. union usa sa;
  10796. if (!connect_socket(&fake_ctx,
  10797. client_options->host,
  10798. client_options->port,
  10799. use_ssl,
  10800. ebuf,
  10801. ebuf_len,
  10802. &sock,
  10803. &sa)) {
  10804. ;
  10805. } else if ((conn = (struct mg_connection *)
  10806. mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) {
  10807. mg_snprintf(NULL,
  10808. NULL, /* No truncation check for ebuf */
  10809. ebuf,
  10810. ebuf_len,
  10811. "calloc(): %s",
  10812. strerror(ERRNO));
  10813. closesocket(sock);
  10814. #ifndef NO_SSL
  10815. } else if (use_ssl
  10816. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  10817. == NULL) {
  10818. mg_snprintf(NULL,
  10819. NULL, /* No truncation check for ebuf */
  10820. ebuf,
  10821. ebuf_len,
  10822. "SSL_CTX_new error");
  10823. closesocket(sock);
  10824. mg_free(conn);
  10825. conn = NULL;
  10826. #endif /* NO_SSL */
  10827. } else {
  10828. #ifdef USE_IPV6
  10829. socklen_t len = (sa.sa.sa_family == AF_INET)
  10830. ? sizeof(conn->client.rsa.sin)
  10831. : sizeof(conn->client.rsa.sin6);
  10832. struct sockaddr *psa =
  10833. (sa.sa.sa_family == AF_INET)
  10834. ? (struct sockaddr *)&(conn->client.rsa.sin)
  10835. : (struct sockaddr *)&(conn->client.rsa.sin6);
  10836. #else
  10837. socklen_t len = sizeof(conn->client.rsa.sin);
  10838. struct sockaddr *psa = (struct sockaddr *)&(conn->client.rsa.sin);
  10839. #endif
  10840. conn->buf_size = MAX_REQUEST_SIZE;
  10841. conn->buf = (char *)(conn + 1);
  10842. conn->ctx = &fake_ctx;
  10843. conn->client.sock = sock;
  10844. conn->client.lsa = sa;
  10845. if (getsockname(sock, psa, &len) != 0) {
  10846. mg_cry(conn,
  10847. "%s: getsockname() failed: %s",
  10848. __func__,
  10849. strerror(ERRNO));
  10850. }
  10851. conn->client.is_ssl = use_ssl ? 1 : 0;
  10852. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  10853. #ifndef NO_SSL
  10854. if (use_ssl) {
  10855. fake_ctx.ssl_ctx = conn->client_ssl_ctx;
  10856. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  10857. * SSL_CTX_set_verify call is needed to switch off server
  10858. * certificate checking, which is off by default in OpenSSL and
  10859. * on in yaSSL. */
  10860. /* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  10861. * SSL_VERIFY_PEER, verify_ssl_server); */
  10862. if (client_options->client_cert) {
  10863. if (!ssl_use_pem_file(&fake_ctx, client_options->client_cert)) {
  10864. mg_snprintf(NULL,
  10865. NULL, /* No truncation check for ebuf */
  10866. ebuf,
  10867. ebuf_len,
  10868. "Can not use SSL client certificate");
  10869. SSL_CTX_free(conn->client_ssl_ctx);
  10870. closesocket(sock);
  10871. mg_free(conn);
  10872. conn = NULL;
  10873. }
  10874. }
  10875. if (client_options->server_cert) {
  10876. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  10877. client_options->server_cert,
  10878. NULL);
  10879. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  10880. } else {
  10881. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  10882. }
  10883. if (!sslize(conn,
  10884. conn->client_ssl_ctx,
  10885. SSL_connect,
  10886. &(conn->ctx->stop_flag))) {
  10887. mg_snprintf(NULL,
  10888. NULL, /* No truncation check for ebuf */
  10889. ebuf,
  10890. ebuf_len,
  10891. "SSL connection error");
  10892. SSL_CTX_free(conn->client_ssl_ctx);
  10893. closesocket(sock);
  10894. mg_free(conn);
  10895. conn = NULL;
  10896. }
  10897. }
  10898. #endif
  10899. }
  10900. if (conn) {
  10901. set_blocking_mode(sock, 0);
  10902. }
  10903. return conn;
  10904. }
  10905. CIVETWEB_API struct mg_connection *
  10906. mg_connect_client_secure(const struct mg_client_options *client_options,
  10907. char *error_buffer,
  10908. size_t error_buffer_size)
  10909. {
  10910. return mg_connect_client_impl(client_options,
  10911. 1,
  10912. error_buffer,
  10913. error_buffer_size);
  10914. }
  10915. struct mg_connection *
  10916. mg_connect_client(const char *host,
  10917. int port,
  10918. int use_ssl,
  10919. char *error_buffer,
  10920. size_t error_buffer_size)
  10921. {
  10922. struct mg_client_options opts;
  10923. memset(&opts, 0, sizeof(opts));
  10924. opts.host = host;
  10925. opts.port = port;
  10926. return mg_connect_client_impl(&opts,
  10927. use_ssl,
  10928. error_buffer,
  10929. error_buffer_size);
  10930. }
  10931. static const struct {
  10932. const char *proto;
  10933. size_t proto_len;
  10934. unsigned default_port;
  10935. } abs_uri_protocols[] = {{"http://", 7, 80},
  10936. {"https://", 8, 443},
  10937. {"ws://", 5, 80},
  10938. {"wss://", 6, 443},
  10939. {NULL, 0, 0}};
  10940. /* Check if the uri is valid.
  10941. * return 0 for invalid uri,
  10942. * return 1 for *,
  10943. * return 2 for relative uri,
  10944. * return 3 for absolute uri without port,
  10945. * return 4 for absolute uri with port */
  10946. static int
  10947. get_uri_type(const char *uri)
  10948. {
  10949. int i;
  10950. char *hostend, *portbegin, *portend;
  10951. unsigned long port;
  10952. /* According to the HTTP standard
  10953. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  10954. * URI can be an asterisk (*) or should start with slash (relative uri),
  10955. * or it should start with the protocol (absolute uri). */
  10956. if (uri[0] == '*' && uri[1] == '\0') {
  10957. /* asterisk */
  10958. return 1;
  10959. }
  10960. /* Valid URIs according to RFC 3986
  10961. * (https://www.ietf.org/rfc/rfc3986.txt)
  10962. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  10963. * and unreserved characters A-Z a-z 0-9 and -._~
  10964. * and % encoded symbols.
  10965. */
  10966. for (i = 0; uri[i] != 0; i++) {
  10967. if (uri[i] < 33) {
  10968. /* control characters and spaces are invalid */
  10969. return 0;
  10970. }
  10971. if (uri[i] > 126) {
  10972. /* non-ascii characters must be % encoded */
  10973. return 0;
  10974. } else {
  10975. switch (uri[i]) {
  10976. case '"': /* 34 */
  10977. case '<': /* 60 */
  10978. case '>': /* 62 */
  10979. case '\\': /* 92 */
  10980. case '^': /* 94 */
  10981. case '`': /* 96 */
  10982. case '{': /* 123 */
  10983. case '|': /* 124 */
  10984. case '}': /* 125 */
  10985. return 0;
  10986. default:
  10987. /* character is ok */
  10988. break;
  10989. }
  10990. }
  10991. }
  10992. /* A relative uri starts with a / character */
  10993. if (uri[0] == '/') {
  10994. /* relative uri */
  10995. return 2;
  10996. }
  10997. /* It could be an absolute uri: */
  10998. /* This function only checks if the uri is valid, not if it is
  10999. * addressing the current server. So civetweb can also be used
  11000. * as a proxy server. */
  11001. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  11002. if (mg_strncasecmp(uri,
  11003. abs_uri_protocols[i].proto,
  11004. abs_uri_protocols[i].proto_len) == 0) {
  11005. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  11006. if (!hostend) {
  11007. return 0;
  11008. }
  11009. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  11010. if (!portbegin) {
  11011. return 3;
  11012. }
  11013. port = strtoul(portbegin + 1, &portend, 10);
  11014. if ((portend != hostend) || !port || !is_valid_port(port)) {
  11015. return 0;
  11016. }
  11017. return 4;
  11018. }
  11019. }
  11020. return 0;
  11021. }
  11022. /* Return NULL or the relative uri at the current server */
  11023. static const char *
  11024. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  11025. {
  11026. const char *server_domain;
  11027. size_t server_domain_len;
  11028. size_t request_domain_len = 0;
  11029. unsigned long port = 0;
  11030. int i;
  11031. const char *hostbegin = NULL;
  11032. const char *hostend = NULL;
  11033. const char *portbegin;
  11034. char *portend;
  11035. /* DNS is case insensitive, so use case insensitive string compare here
  11036. */
  11037. server_domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  11038. if (!server_domain) {
  11039. return 0;
  11040. }
  11041. server_domain_len = strlen(server_domain);
  11042. if (!server_domain_len) {
  11043. return 0;
  11044. }
  11045. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  11046. if (mg_strncasecmp(uri,
  11047. abs_uri_protocols[i].proto,
  11048. abs_uri_protocols[i].proto_len) == 0) {
  11049. hostbegin = uri + abs_uri_protocols[i].proto_len;
  11050. hostend = strchr(hostbegin, '/');
  11051. if (!hostend) {
  11052. return 0;
  11053. }
  11054. portbegin = strchr(hostbegin, ':');
  11055. if ((!portbegin) || (portbegin > hostend)) {
  11056. port = abs_uri_protocols[i].default_port;
  11057. request_domain_len = (size_t)(hostend - hostbegin);
  11058. } else {
  11059. port = strtoul(portbegin + 1, &portend, 10);
  11060. if ((portend != hostend) || !port || !is_valid_port(port)) {
  11061. return 0;
  11062. }
  11063. request_domain_len = (size_t)(portbegin - hostbegin);
  11064. }
  11065. /* protocol found, port set */
  11066. break;
  11067. }
  11068. }
  11069. if (!port) {
  11070. /* port remains 0 if the protocol is not found */
  11071. return 0;
  11072. }
  11073. /* Check if the request is directed to a different server. */
  11074. /* First check if the port is the same (IPv4 and IPv6). */
  11075. #if defined(USE_IPV6)
  11076. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  11077. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  11078. /* Request is directed to a different port */
  11079. return 0;
  11080. }
  11081. } else
  11082. #endif
  11083. {
  11084. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  11085. /* Request is directed to a different port */
  11086. return 0;
  11087. }
  11088. }
  11089. /* Finally check if the server corresponds to the authentication
  11090. * domain of the server (the server domain).
  11091. * Allow full matches (like http://mydomain.com/path/file.ext), and
  11092. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  11093. * but do not allow substrings (like http://notmydomain.com/path/file.ext
  11094. * or http://mydomain.com.fake/path/file.ext).
  11095. */
  11096. if ((request_domain_len == server_domain_len)
  11097. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  11098. /* Request is directed to this server - full name match. */
  11099. } else {
  11100. if (request_domain_len < (server_domain_len + 2)) {
  11101. /* Request is directed to another server: The server name is longer
  11102. * than
  11103. * the request name. Drop this case here to avoid overflows in the
  11104. * following checks. */
  11105. return 0;
  11106. }
  11107. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  11108. /* Request is directed to another server: It could be a substring
  11109. * like notmyserver.com */
  11110. return 0;
  11111. }
  11112. if (0 != memcmp(server_domain,
  11113. hostbegin + request_domain_len - server_domain_len,
  11114. server_domain_len)) {
  11115. /* Request is directed to another server:
  11116. * The server name is different. */
  11117. return 0;
  11118. }
  11119. }
  11120. return hostend;
  11121. }
  11122. static int
  11123. getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  11124. {
  11125. const char *cl;
  11126. if (ebuf_len > 0) {
  11127. ebuf[0] = '\0';
  11128. }
  11129. *err = 0;
  11130. reset_per_request_attributes(conn);
  11131. if (!conn) {
  11132. mg_snprintf(conn,
  11133. NULL, /* No truncation check for ebuf */
  11134. ebuf,
  11135. ebuf_len,
  11136. "%s",
  11137. "Internal error");
  11138. *err = 500;
  11139. return 0;
  11140. }
  11141. /* Set the time the request was received. This value should be used for
  11142. * timeouts. */
  11143. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  11144. conn->request_len =
  11145. read_request(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  11146. /* assert(conn->request_len < 0 || conn->data_len >= conn->request_len);
  11147. */
  11148. if (conn->request_len >= 0 && conn->data_len < conn->request_len) {
  11149. mg_snprintf(conn,
  11150. NULL, /* No truncation check for ebuf */
  11151. ebuf,
  11152. ebuf_len,
  11153. "%s",
  11154. "Invalid request size");
  11155. *err = 500;
  11156. return 0;
  11157. }
  11158. if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
  11159. mg_snprintf(conn,
  11160. NULL, /* No truncation check for ebuf */
  11161. ebuf,
  11162. ebuf_len,
  11163. "%s",
  11164. "Request Too Large");
  11165. *err = 413;
  11166. return 0;
  11167. } else if (conn->request_len <= 0) {
  11168. if (conn->data_len > 0) {
  11169. mg_snprintf(conn,
  11170. NULL, /* No truncation check for ebuf */
  11171. ebuf,
  11172. ebuf_len,
  11173. "%s",
  11174. "Client sent malformed request");
  11175. *err = 400;
  11176. } else {
  11177. /* Server did not recv anything -> just close the connection */
  11178. conn->must_close = 1;
  11179. mg_snprintf(conn,
  11180. NULL, /* No truncation check for ebuf */
  11181. ebuf,
  11182. ebuf_len,
  11183. "%s",
  11184. "Client did not send a request");
  11185. *err = 0;
  11186. }
  11187. return 0;
  11188. } else if (parse_http_message(conn->buf,
  11189. conn->buf_size,
  11190. &conn->request_info) <= 0) {
  11191. mg_snprintf(conn,
  11192. NULL, /* No truncation check for ebuf */
  11193. ebuf,
  11194. ebuf_len,
  11195. "%s",
  11196. "Bad Request");
  11197. *err = 400;
  11198. return 0;
  11199. } else {
  11200. /* Message is a valid request or response */
  11201. if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) {
  11202. /* Request/response has content length set */
  11203. char *endptr = NULL;
  11204. conn->content_len = strtoll(cl, &endptr, 10);
  11205. if (endptr == cl) {
  11206. mg_snprintf(conn,
  11207. NULL, /* No truncation check for ebuf */
  11208. ebuf,
  11209. ebuf_len,
  11210. "%s",
  11211. "Bad Request");
  11212. *err = 411;
  11213. return 0;
  11214. }
  11215. /* Publish the content length back to the request info. */
  11216. conn->request_info.content_length = conn->content_len;
  11217. } else if ((cl = get_header(&conn->request_info, "Transfer-Encoding"))
  11218. != NULL
  11219. && !mg_strcasecmp(cl, "chunked")) {
  11220. conn->is_chunked = 1;
  11221. } else if (!mg_strcasecmp(conn->request_info.request_method, "POST")
  11222. || !mg_strcasecmp(conn->request_info.request_method,
  11223. "PUT")) {
  11224. /* POST or PUT request without content length set */
  11225. conn->content_len = -1;
  11226. } else if (!mg_strncasecmp(conn->request_info.request_method,
  11227. "HTTP/",
  11228. 5)) {
  11229. /* Response without content length set */
  11230. conn->content_len = -1;
  11231. } else {
  11232. /* Other request */
  11233. conn->content_len = 0;
  11234. }
  11235. }
  11236. return 1;
  11237. }
  11238. int
  11239. mg_get_response(struct mg_connection *conn,
  11240. char *ebuf,
  11241. size_t ebuf_len,
  11242. int timeout)
  11243. {
  11244. if (conn) {
  11245. /* Implementation of API function for HTTP clients */
  11246. int err, ret;
  11247. struct mg_context *octx = conn->ctx;
  11248. struct mg_context rctx = *(conn->ctx);
  11249. char txt[32]; /* will not overflow */
  11250. if (timeout >= 0) {
  11251. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  11252. rctx.config[REQUEST_TIMEOUT] = txt;
  11253. /* Not required for non-blocking sockets.
  11254. set_sock_timeout(conn->client.sock, timeout);
  11255. */
  11256. } else {
  11257. rctx.config[REQUEST_TIMEOUT] = NULL;
  11258. }
  11259. conn->ctx = &rctx;
  11260. ret = getreq(conn, ebuf, ebuf_len, &err);
  11261. conn->ctx = octx;
  11262. /* TODO: 1) uri is deprecated;
  11263. * 2) here, ri.uri is the http response code */
  11264. conn->request_info.uri = conn->request_info.request_uri;
  11265. /* TODO (mid): Define proper return values - maybe return length?
  11266. * For the first test use <0 for error and >0 for OK */
  11267. return (ret == 0) ? -1 : +1;
  11268. }
  11269. return -1;
  11270. }
  11271. struct mg_connection *
  11272. mg_download(const char *host,
  11273. int port,
  11274. int use_ssl,
  11275. char *ebuf,
  11276. size_t ebuf_len,
  11277. const char *fmt,
  11278. ...)
  11279. {
  11280. struct mg_connection *conn;
  11281. va_list ap;
  11282. int i;
  11283. int reqerr;
  11284. va_start(ap, fmt);
  11285. ebuf[0] = '\0';
  11286. /* open a connection */
  11287. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  11288. if (conn != NULL) {
  11289. i = mg_vprintf(conn, fmt, ap);
  11290. if (i <= 0) {
  11291. mg_snprintf(conn,
  11292. NULL, /* No truncation check for ebuf */
  11293. ebuf,
  11294. ebuf_len,
  11295. "%s",
  11296. "Error sending request");
  11297. } else {
  11298. getreq(conn, ebuf, ebuf_len, &reqerr);
  11299. /* TODO: 1) uri is deprecated;
  11300. * 2) here, ri.uri is the http response code */
  11301. conn->request_info.uri = conn->request_info.request_uri;
  11302. }
  11303. }
  11304. /* if an error occured, close the connection */
  11305. if (ebuf[0] != '\0' && conn != NULL) {
  11306. mg_close_connection(conn);
  11307. conn = NULL;
  11308. }
  11309. va_end(ap);
  11310. return conn;
  11311. }
  11312. struct websocket_client_thread_data {
  11313. struct mg_connection *conn;
  11314. mg_websocket_data_handler data_handler;
  11315. mg_websocket_close_handler close_handler;
  11316. void *callback_data;
  11317. };
  11318. #if defined(USE_WEBSOCKET)
  11319. #ifdef _WIN32
  11320. static unsigned __stdcall websocket_client_thread(void *data)
  11321. #else
  11322. static void *
  11323. websocket_client_thread(void *data)
  11324. #endif
  11325. {
  11326. struct websocket_client_thread_data *cdata =
  11327. (struct websocket_client_thread_data *)data;
  11328. mg_set_thread_name("ws-clnt");
  11329. if (cdata->conn->ctx) {
  11330. if (cdata->conn->ctx->callbacks.init_thread) {
  11331. /* 3 indicates a websocket client thread */
  11332. /* TODO: check if conn->ctx can be set */
  11333. cdata->conn->ctx->callbacks.init_thread(cdata->conn->ctx, 3);
  11334. }
  11335. }
  11336. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  11337. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  11338. if (cdata->close_handler != NULL) {
  11339. cdata->close_handler(cdata->conn, cdata->callback_data);
  11340. }
  11341. /* The websocket_client context has only this thread. If it runs out,
  11342. set the stop_flag to 2 (= "stopped"). */
  11343. cdata->conn->ctx->stop_flag = 2;
  11344. mg_free((void *)cdata);
  11345. #ifdef _WIN32
  11346. return 0;
  11347. #else
  11348. return NULL;
  11349. #endif
  11350. }
  11351. #endif
  11352. struct mg_connection *
  11353. mg_connect_websocket_client(const char *host,
  11354. int port,
  11355. int use_ssl,
  11356. char *error_buffer,
  11357. size_t error_buffer_size,
  11358. const char *path,
  11359. const char *origin,
  11360. mg_websocket_data_handler data_func,
  11361. mg_websocket_close_handler close_func,
  11362. void *user_data)
  11363. {
  11364. struct mg_connection *conn = NULL;
  11365. #if defined(USE_WEBSOCKET)
  11366. struct mg_context *newctx = NULL;
  11367. struct websocket_client_thread_data *thread_data;
  11368. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  11369. static const char *handshake_req;
  11370. if (origin != NULL) {
  11371. handshake_req = "GET %s HTTP/1.1\r\n"
  11372. "Host: %s\r\n"
  11373. "Upgrade: websocket\r\n"
  11374. "Connection: Upgrade\r\n"
  11375. "Sec-WebSocket-Key: %s\r\n"
  11376. "Sec-WebSocket-Version: 13\r\n"
  11377. "Origin: %s\r\n"
  11378. "\r\n";
  11379. } else {
  11380. handshake_req = "GET %s HTTP/1.1\r\n"
  11381. "Host: %s\r\n"
  11382. "Upgrade: websocket\r\n"
  11383. "Connection: Upgrade\r\n"
  11384. "Sec-WebSocket-Key: %s\r\n"
  11385. "Sec-WebSocket-Version: 13\r\n"
  11386. "\r\n";
  11387. }
  11388. /* Establish the client connection and request upgrade */
  11389. conn = mg_download(host,
  11390. port,
  11391. use_ssl,
  11392. error_buffer,
  11393. error_buffer_size,
  11394. handshake_req,
  11395. path,
  11396. host,
  11397. magic,
  11398. origin);
  11399. /* Connection object will be null if something goes wrong */
  11400. if (conn == NULL || (strcmp(conn->request_info.request_uri, "101") != 0)) {
  11401. if (!*error_buffer) {
  11402. /* if there is a connection, but it did not return 101,
  11403. * error_buffer is not yet set */
  11404. mg_snprintf(conn,
  11405. NULL, /* No truncation check for ebuf */
  11406. error_buffer,
  11407. error_buffer_size,
  11408. "Unexpected server reply");
  11409. }
  11410. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  11411. if (conn != NULL) {
  11412. mg_free(conn);
  11413. conn = NULL;
  11414. }
  11415. return conn;
  11416. }
  11417. /* For client connections, mg_context is fake. Since we need to set a
  11418. * callback function, we need to create a copy and modify it. */
  11419. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  11420. memcpy(newctx, conn->ctx, sizeof(struct mg_context));
  11421. newctx->user_data = user_data;
  11422. newctx->context_type = 2; /* ws/wss client context type */
  11423. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  11424. newctx->workerthreadids =
  11425. (pthread_t *)mg_calloc(newctx->cfg_worker_threads, sizeof(pthread_t));
  11426. conn->ctx = newctx;
  11427. thread_data = (struct websocket_client_thread_data *)
  11428. mg_calloc(sizeof(struct websocket_client_thread_data), 1);
  11429. thread_data->conn = conn;
  11430. thread_data->data_handler = data_func;
  11431. thread_data->close_handler = close_func;
  11432. thread_data->callback_data = NULL;
  11433. /* Start a thread to read the websocket client connection
  11434. * This thread will automatically stop when mg_disconnect is
  11435. * called on the client connection */
  11436. if (mg_start_thread_with_id(websocket_client_thread,
  11437. (void *)thread_data,
  11438. newctx->workerthreadids) != 0) {
  11439. mg_free((void *)thread_data);
  11440. mg_free((void *)newctx->workerthreadids);
  11441. mg_free((void *)newctx);
  11442. mg_free((void *)conn);
  11443. conn = NULL;
  11444. DEBUG_TRACE("%s",
  11445. "Websocket client connect thread could not be started\r\n");
  11446. }
  11447. #else
  11448. /* Appease "unused parameter" warnings */
  11449. (void)host;
  11450. (void)port;
  11451. (void)use_ssl;
  11452. (void)error_buffer;
  11453. (void)error_buffer_size;
  11454. (void)path;
  11455. (void)origin;
  11456. (void)user_data;
  11457. (void)data_func;
  11458. (void)close_func;
  11459. #endif
  11460. return conn;
  11461. }
  11462. static void
  11463. process_new_connection(struct mg_connection *conn)
  11464. {
  11465. if (conn && conn->ctx) {
  11466. struct mg_request_info *ri = &conn->request_info;
  11467. int keep_alive_enabled, keep_alive, discard_len;
  11468. char ebuf[100];
  11469. const char *hostend;
  11470. int reqerr, uri_type;
  11471. keep_alive_enabled =
  11472. !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  11473. /* Important: on new connection, reset the receiving buffer. Credit
  11474. * goes to crule42. */
  11475. conn->data_len = 0;
  11476. conn->handled_requests = 0;
  11477. do {
  11478. DEBUG_TRACE("calling getreq (%i times for this connection)",
  11479. conn->handled_requests + 1);
  11480. if (!getreq(conn, ebuf, sizeof(ebuf), &reqerr)) {
  11481. /* The request sent by the client could not be understood by
  11482. * the server, or it was incomplete or a timeout. Send an
  11483. * error message and close the connection. */
  11484. if (reqerr > 0) {
  11485. /*assert(ebuf[0] != '\0');*/
  11486. send_http_error(conn, reqerr, "%s", ebuf);
  11487. }
  11488. } else if (strcmp(ri->http_version, "1.0")
  11489. && strcmp(ri->http_version, "1.1")) {
  11490. mg_snprintf(conn,
  11491. NULL, /* No truncation check for ebuf */
  11492. ebuf,
  11493. sizeof(ebuf),
  11494. "Bad HTTP version: [%s]",
  11495. ri->http_version);
  11496. send_http_error(conn, 505, "%s", ebuf);
  11497. }
  11498. if (ebuf[0] == '\0') {
  11499. uri_type = get_uri_type(conn->request_info.request_uri);
  11500. switch (uri_type) {
  11501. case 1:
  11502. /* Asterisk */
  11503. conn->request_info.local_uri = NULL;
  11504. break;
  11505. case 2:
  11506. /* relative uri */
  11507. conn->request_info.local_uri =
  11508. conn->request_info.request_uri;
  11509. break;
  11510. case 3:
  11511. case 4:
  11512. /* absolute uri (with/without port) */
  11513. hostend = get_rel_url_at_current_server(
  11514. conn->request_info.request_uri, conn);
  11515. if (hostend) {
  11516. conn->request_info.local_uri = hostend;
  11517. } else {
  11518. conn->request_info.local_uri = NULL;
  11519. }
  11520. break;
  11521. default:
  11522. mg_snprintf(conn,
  11523. NULL, /* No truncation check for ebuf */
  11524. ebuf,
  11525. sizeof(ebuf),
  11526. "Invalid URI");
  11527. send_http_error(conn, 400, "%s", ebuf);
  11528. conn->request_info.local_uri = NULL;
  11529. break;
  11530. }
  11531. /* TODO: cleanup uri, local_uri and request_uri */
  11532. conn->request_info.uri = conn->request_info.local_uri;
  11533. }
  11534. DEBUG_TRACE("http: %s, error: %s",
  11535. (ri->http_version ? ri->http_version : "none"),
  11536. (ebuf[0] ? ebuf : "none"));
  11537. if (ebuf[0] == '\0') {
  11538. if (conn->request_info.local_uri) {
  11539. /* handle request to local server */
  11540. handle_request(conn);
  11541. DEBUG_TRACE("%s", "handle_request done");
  11542. if (conn->ctx->callbacks.end_request != NULL) {
  11543. conn->ctx->callbacks.end_request(conn,
  11544. conn->status_code);
  11545. DEBUG_TRACE("%s", "end_request callback done");
  11546. }
  11547. log_access(conn);
  11548. } else {
  11549. /* TODO: handle non-local request (PROXY) */
  11550. conn->must_close = 1;
  11551. }
  11552. } else {
  11553. conn->must_close = 1;
  11554. }
  11555. if (ri->remote_user != NULL) {
  11556. mg_free((void *)ri->remote_user);
  11557. /* Important! When having connections with and without auth
  11558. * would cause double free and then crash */
  11559. ri->remote_user = NULL;
  11560. }
  11561. /* NOTE(lsm): order is important here. should_keep_alive() call
  11562. * is
  11563. * using parsed request, which will be invalid after memmove's
  11564. * below.
  11565. * Therefore, memorize should_keep_alive() result now for later
  11566. * use
  11567. * in loop exit condition. */
  11568. keep_alive = (conn->ctx->stop_flag == 0) && keep_alive_enabled
  11569. && (conn->content_len >= 0) && should_keep_alive(conn);
  11570. /* Discard all buffered data for this request */
  11571. discard_len = ((conn->content_len >= 0) && (conn->request_len > 0)
  11572. && ((conn->request_len + conn->content_len)
  11573. < (int64_t)conn->data_len))
  11574. ? (int)(conn->request_len + conn->content_len)
  11575. : conn->data_len;
  11576. /*assert(discard_len >= 0);*/
  11577. if (discard_len < 0) {
  11578. DEBUG_TRACE("internal error: discard_len = %li",
  11579. (long int)discard_len);
  11580. break;
  11581. }
  11582. conn->data_len -= discard_len;
  11583. if (conn->data_len > 0) {
  11584. DEBUG_TRACE("discard_len = %lu", (long unsigned)discard_len);
  11585. memmove(conn->buf,
  11586. conn->buf + discard_len,
  11587. (size_t)conn->data_len);
  11588. }
  11589. /* assert(conn->data_len >= 0); */
  11590. /* assert(conn->data_len <= conn->buf_size); */
  11591. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  11592. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  11593. (long int)conn->data_len,
  11594. (long int)conn->buf_size);
  11595. break;
  11596. }
  11597. conn->handled_requests++;
  11598. } while (keep_alive);
  11599. }
  11600. }
  11601. #if defined(ALTERNATIVE_QUEUE)
  11602. static void
  11603. produce_socket(struct mg_context *ctx, const struct socket *sp)
  11604. {
  11605. unsigned int i;
  11606. for (;;) {
  11607. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  11608. /* find a free worker slot and signal it */
  11609. if (ctx->client_socks[i].in_use == 0) {
  11610. ctx->client_socks[i] = *sp;
  11611. ctx->client_socks[i].in_use = 1;
  11612. event_signal(ctx->client_wait_events[i]);
  11613. return;
  11614. }
  11615. }
  11616. /* queue is full */
  11617. mg_sleep(1);
  11618. }
  11619. }
  11620. static int
  11621. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  11622. {
  11623. DEBUG_TRACE("%s", "going idle");
  11624. ctx->client_socks[thread_index].in_use = 0;
  11625. event_wait(ctx->client_wait_events[thread_index]);
  11626. *sp = ctx->client_socks[thread_index];
  11627. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  11628. return !ctx->stop_flag;
  11629. }
  11630. #else /* ALTERNATIVE_QUEUE */
  11631. /* Worker threads take accepted socket from the queue */
  11632. static int
  11633. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  11634. {
  11635. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  11636. (void)thread_index;
  11637. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11638. DEBUG_TRACE("%s", "going idle");
  11639. /* If the queue is empty, wait. We're idle at this point. */
  11640. while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
  11641. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  11642. }
  11643. /* If we're stopping, sq_head may be equal to sq_tail. */
  11644. if (ctx->sq_head > ctx->sq_tail) {
  11645. /* Copy socket from the queue and increment tail */
  11646. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  11647. ctx->sq_tail++;
  11648. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  11649. /* Wrap pointers if needed */
  11650. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  11651. ctx->sq_tail -= QUEUE_SIZE(ctx);
  11652. ctx->sq_head -= QUEUE_SIZE(ctx);
  11653. }
  11654. }
  11655. (void)pthread_cond_signal(&ctx->sq_empty);
  11656. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11657. return !ctx->stop_flag;
  11658. #undef QUEUE_SIZE
  11659. }
  11660. /* Master thread adds accepted socket to a queue */
  11661. static void
  11662. produce_socket(struct mg_context *ctx, const struct socket *sp)
  11663. {
  11664. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  11665. if (!ctx) {
  11666. return;
  11667. }
  11668. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11669. /* If the queue is full, wait */
  11670. while (ctx->stop_flag == 0
  11671. && ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx)) {
  11672. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  11673. }
  11674. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  11675. /* Copy socket to the queue and increment head */
  11676. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  11677. ctx->sq_head++;
  11678. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  11679. }
  11680. (void)pthread_cond_signal(&ctx->sq_full);
  11681. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11682. #undef QUEUE_SIZE
  11683. }
  11684. #endif /* ALTERNATIVE_QUEUE */
  11685. struct worker_thread_args {
  11686. struct mg_context *ctx;
  11687. int index;
  11688. };
  11689. static void *
  11690. worker_thread_run(struct worker_thread_args *thread_args)
  11691. {
  11692. struct mg_context *ctx = thread_args->ctx;
  11693. struct mg_connection *conn;
  11694. struct mg_workerTLS tls;
  11695. #if defined(MG_LEGACY_INTERFACE)
  11696. uint32_t addr;
  11697. #endif
  11698. mg_set_thread_name("worker");
  11699. tls.is_master = 0;
  11700. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  11701. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11702. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  11703. #endif
  11704. if (ctx->callbacks.init_thread) {
  11705. /* call init_thread for a worker thread (type 1) */
  11706. ctx->callbacks.init_thread(ctx, 1);
  11707. }
  11708. conn =
  11709. (struct mg_connection *)mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE);
  11710. if (conn == NULL) {
  11711. mg_cry(fc(ctx), "%s", "Cannot create new connection struct, OOM");
  11712. } else {
  11713. pthread_setspecific(sTlsKey, &tls);
  11714. conn->buf_size = MAX_REQUEST_SIZE;
  11715. conn->buf = (char *)(conn + 1);
  11716. conn->ctx = ctx;
  11717. conn->thread_index = thread_args->index;
  11718. conn->request_info.user_data = ctx->user_data;
  11719. /* Allocate a mutex for this connection to allow communication both
  11720. * within the request handler and from elsewhere in the application
  11721. */
  11722. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  11723. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  11724. * signal sq_empty condvar to wake up the master waiting in
  11725. * produce_socket() */
  11726. while (consume_socket(ctx, &conn->client, conn->thread_index)) {
  11727. conn->conn_birth_time = time(NULL);
  11728. /* Fill in IP, port info early so even if SSL setup below fails,
  11729. * error handler would have the corresponding info.
  11730. * Thanks to Johannes Winkelmann for the patch.
  11731. */
  11732. #if defined(USE_IPV6)
  11733. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  11734. conn->request_info.remote_port =
  11735. ntohs(conn->client.rsa.sin6.sin6_port);
  11736. } else
  11737. #endif
  11738. {
  11739. conn->request_info.remote_port =
  11740. ntohs(conn->client.rsa.sin.sin_port);
  11741. }
  11742. sockaddr_to_string(conn->request_info.remote_addr,
  11743. sizeof(conn->request_info.remote_addr),
  11744. &conn->client.rsa);
  11745. DEBUG_TRACE("Start processing connection from %s",
  11746. conn->request_info.remote_addr);
  11747. #if defined(MG_LEGACY_INTERFACE)
  11748. /* This legacy interface only works for the IPv4 case */
  11749. addr = ntohl(conn->client.rsa.sin.sin_addr.s_addr);
  11750. memcpy(&conn->request_info.remote_ip, &addr, 4);
  11751. #endif
  11752. conn->request_info.is_ssl = conn->client.is_ssl;
  11753. if (conn->client.is_ssl) {
  11754. #ifndef NO_SSL
  11755. /* HTTPS connection */
  11756. if (sslize(conn,
  11757. conn->ctx->ssl_ctx,
  11758. SSL_accept,
  11759. &(conn->ctx->stop_flag))) {
  11760. /* Get SSL client certificate information (if set) */
  11761. ssl_get_client_cert_info(conn);
  11762. /* process HTTPS connection */
  11763. process_new_connection(conn);
  11764. /* Free client certificate info */
  11765. if (conn->request_info.client_cert) {
  11766. mg_free(
  11767. (void *)(conn->request_info.client_cert->subject));
  11768. mg_free(
  11769. (void *)(conn->request_info.client_cert->issuer));
  11770. mg_free(
  11771. (void *)(conn->request_info.client_cert->serial));
  11772. mg_free(
  11773. (void *)(conn->request_info.client_cert->finger));
  11774. conn->request_info.client_cert->subject = 0;
  11775. conn->request_info.client_cert->issuer = 0;
  11776. conn->request_info.client_cert->serial = 0;
  11777. conn->request_info.client_cert->finger = 0;
  11778. mg_free(conn->request_info.client_cert);
  11779. conn->request_info.client_cert = 0;
  11780. }
  11781. }
  11782. #endif
  11783. } else {
  11784. /* process HTTP connection */
  11785. process_new_connection(conn);
  11786. }
  11787. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  11788. conn->request_info.remote_addr,
  11789. difftime(time(NULL), conn->conn_birth_time));
  11790. close_connection(conn);
  11791. DEBUG_TRACE("%s", "Connection closed");
  11792. }
  11793. }
  11794. pthread_setspecific(sTlsKey, NULL);
  11795. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11796. CloseHandle(tls.pthread_cond_helper_mutex);
  11797. #endif
  11798. pthread_mutex_destroy(&conn->mutex);
  11799. mg_free(conn);
  11800. DEBUG_TRACE("%s", "exiting");
  11801. return NULL;
  11802. }
  11803. /* Threads have different return types on Windows and Unix. */
  11804. #ifdef _WIN32
  11805. static unsigned __stdcall worker_thread(void *thread_func_param)
  11806. {
  11807. struct worker_thread_args *pwta =
  11808. (struct worker_thread_args *)thread_func_param;
  11809. worker_thread_run(pwta);
  11810. mg_free(thread_func_param);
  11811. return 0;
  11812. }
  11813. #else
  11814. static void *
  11815. worker_thread(void *thread_func_param)
  11816. {
  11817. struct worker_thread_args *pwta =
  11818. (struct worker_thread_args *)thread_func_param;
  11819. worker_thread_run(pwta);
  11820. mg_free(thread_func_param);
  11821. return NULL;
  11822. }
  11823. #endif /* _WIN32 */
  11824. static void
  11825. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  11826. {
  11827. struct socket so;
  11828. char src_addr[IP_ADDR_STR_LEN];
  11829. socklen_t len = sizeof(so.rsa);
  11830. int on = 1;
  11831. int timeout;
  11832. if (!listener) {
  11833. return;
  11834. }
  11835. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  11836. == INVALID_SOCKET) {
  11837. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  11838. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  11839. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  11840. closesocket(so.sock);
  11841. so.sock = INVALID_SOCKET;
  11842. } else {
  11843. /* Put so socket structure into the queue */
  11844. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  11845. set_close_on_exec(so.sock, fc(ctx));
  11846. so.is_ssl = listener->is_ssl;
  11847. so.ssl_redir = listener->ssl_redir;
  11848. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  11849. mg_cry(fc(ctx),
  11850. "%s: getsockname() failed: %s",
  11851. __func__,
  11852. strerror(ERRNO));
  11853. }
  11854. /* Set TCP keep-alive. This is needed because if HTTP-level
  11855. * keep-alive
  11856. * is enabled, and client resets the connection, server won't get
  11857. * TCP FIN or RST and will keep the connection open forever. With
  11858. * TCP keep-alive, next keep-alive handshake will figure out that
  11859. * the client is down and will close the server end.
  11860. * Thanks to Igor Klopov who suggested the patch. */
  11861. if (setsockopt(so.sock,
  11862. SOL_SOCKET,
  11863. SO_KEEPALIVE,
  11864. (SOCK_OPT_TYPE)&on,
  11865. sizeof(on)) != 0) {
  11866. mg_cry(fc(ctx),
  11867. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  11868. __func__,
  11869. strerror(ERRNO));
  11870. }
  11871. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  11872. * to effectively fill up the underlying IP packet payload and
  11873. * reduce the overhead of sending lots of small buffers. However
  11874. * this hurts the server's throughput (ie. operations per second)
  11875. * when HTTP 1.1 persistent connections are used and the responses
  11876. * are relatively small (eg. less than 1400 bytes).
  11877. */
  11878. if ((ctx != NULL) && (ctx->config[CONFIG_TCP_NODELAY] != NULL)
  11879. && (!strcmp(ctx->config[CONFIG_TCP_NODELAY], "1"))) {
  11880. if (set_tcp_nodelay(so.sock, 1) != 0) {
  11881. mg_cry(fc(ctx),
  11882. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  11883. __func__,
  11884. strerror(ERRNO));
  11885. }
  11886. }
  11887. if (ctx && ctx->config[REQUEST_TIMEOUT]) {
  11888. timeout = atoi(ctx->config[REQUEST_TIMEOUT]);
  11889. } else {
  11890. timeout = -1;
  11891. }
  11892. /* TODO: if non blocking sockets are used, timeouts are implemented
  11893. * differently */
  11894. // if (timeout > 0) {
  11895. // set_sock_timeout(so.sock, timeout);
  11896. //}
  11897. (void)timeout;
  11898. set_blocking_mode(so.sock, 0);
  11899. produce_socket(ctx, &so);
  11900. }
  11901. }
  11902. static void
  11903. master_thread_run(void *thread_func_param)
  11904. {
  11905. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  11906. struct mg_workerTLS tls;
  11907. struct pollfd *pfd;
  11908. unsigned int i;
  11909. unsigned int workerthreadcount;
  11910. if (!ctx) {
  11911. return;
  11912. }
  11913. mg_set_thread_name("master");
  11914. /* Increase priority of the master thread */
  11915. #if defined(_WIN32)
  11916. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  11917. #elif defined(USE_MASTER_THREAD_PRIORITY)
  11918. int min_prio = sched_get_priority_min(SCHED_RR);
  11919. int max_prio = sched_get_priority_max(SCHED_RR);
  11920. if ((min_prio >= 0) && (max_prio >= 0)
  11921. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  11922. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  11923. struct sched_param sched_param = {0};
  11924. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  11925. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  11926. }
  11927. #endif
  11928. /* Initialize thread local storage */
  11929. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11930. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  11931. #endif
  11932. tls.is_master = 1;
  11933. pthread_setspecific(sTlsKey, &tls);
  11934. if (ctx->callbacks.init_thread) {
  11935. /* Callback for the master thread (type 0) */
  11936. ctx->callbacks.init_thread(ctx, 0);
  11937. }
  11938. /* Server starts *now* */
  11939. ctx->start_time = time(NULL);
  11940. /* Start the server */
  11941. pfd = ctx->listening_socket_fds;
  11942. while (ctx->stop_flag == 0) {
  11943. for (i = 0; i < ctx->num_listening_sockets; i++) {
  11944. pfd[i].fd = ctx->listening_sockets[i].sock;
  11945. pfd[i].events = POLLIN;
  11946. }
  11947. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  11948. for (i = 0; i < ctx->num_listening_sockets; i++) {
  11949. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  11950. * successful poll, and POLLIN is defined as
  11951. * (POLLRDNORM | POLLRDBAND)
  11952. * Therefore, we're checking pfd[i].revents & POLLIN, not
  11953. * pfd[i].revents == POLLIN. */
  11954. if (ctx->stop_flag == 0 && (pfd[i].revents & POLLIN)) {
  11955. accept_new_connection(&ctx->listening_sockets[i], ctx);
  11956. }
  11957. }
  11958. }
  11959. }
  11960. /* Here stop_flag is 1 - Initiate shutdown. */
  11961. DEBUG_TRACE("%s", "stopping workers");
  11962. /* Stop signal received: somebody called mg_stop. Quit. */
  11963. close_all_listening_sockets(ctx);
  11964. /* Wakeup workers that are waiting for connections to handle. */
  11965. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11966. #if defined(ALTERNATIVE_QUEUE)
  11967. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  11968. event_signal(ctx->client_wait_events[i]);
  11969. /* Since we know all sockets, we can shutdown the connections. */
  11970. if (ctx->client_socks[i].in_use) {
  11971. shutdown(ctx->client_socks[i].sock, SHUTDOWN_BOTH);
  11972. }
  11973. }
  11974. #else
  11975. pthread_cond_broadcast(&ctx->sq_full);
  11976. #endif
  11977. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11978. /* Join all worker threads to avoid leaking threads. */
  11979. workerthreadcount = ctx->cfg_worker_threads;
  11980. for (i = 0; i < workerthreadcount; i++) {
  11981. if (ctx->workerthreadids[i] != 0) {
  11982. mg_join_thread(ctx->workerthreadids[i]);
  11983. }
  11984. }
  11985. #if !defined(NO_SSL)
  11986. if (ctx->ssl_ctx != NULL) {
  11987. uninitialize_ssl(ctx);
  11988. }
  11989. #endif
  11990. DEBUG_TRACE("%s", "exiting");
  11991. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11992. CloseHandle(tls.pthread_cond_helper_mutex);
  11993. #endif
  11994. pthread_setspecific(sTlsKey, NULL);
  11995. /* Signal mg_stop() that we're done.
  11996. * WARNING: This must be the very last thing this
  11997. * thread does, as ctx becomes invalid after this line. */
  11998. ctx->stop_flag = 2;
  11999. }
  12000. /* Threads have different return types on Windows and Unix. */
  12001. #ifdef _WIN32
  12002. static unsigned __stdcall master_thread(void *thread_func_param)
  12003. {
  12004. master_thread_run(thread_func_param);
  12005. return 0;
  12006. }
  12007. #else
  12008. static void *
  12009. master_thread(void *thread_func_param)
  12010. {
  12011. master_thread_run(thread_func_param);
  12012. return NULL;
  12013. }
  12014. #endif /* _WIN32 */
  12015. static void
  12016. free_context(struct mg_context *ctx)
  12017. {
  12018. int i;
  12019. struct mg_handler_info *tmp_rh;
  12020. if (ctx == NULL) {
  12021. return;
  12022. }
  12023. if (ctx->callbacks.exit_context) {
  12024. ctx->callbacks.exit_context(ctx);
  12025. }
  12026. /* All threads exited, no sync is needed. Destroy thread mutex and
  12027. * condvars
  12028. */
  12029. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  12030. #if defined(ALTERNATIVE_QUEUE)
  12031. mg_free(ctx->client_socks);
  12032. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  12033. event_destroy(ctx->client_wait_events[i]);
  12034. }
  12035. mg_free(ctx->client_wait_events);
  12036. #else
  12037. (void)pthread_cond_destroy(&ctx->sq_empty);
  12038. (void)pthread_cond_destroy(&ctx->sq_full);
  12039. #endif
  12040. /* Destroy other context global data structures mutex */
  12041. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  12042. #if defined(USE_TIMERS)
  12043. timers_exit(ctx);
  12044. #endif
  12045. /* Deallocate config parameters */
  12046. for (i = 0; i < NUM_OPTIONS; i++) {
  12047. if (ctx->config[i] != NULL) {
  12048. #if defined(_MSC_VER)
  12049. #pragma warning(suppress : 6001)
  12050. #endif
  12051. mg_free(ctx->config[i]);
  12052. }
  12053. }
  12054. /* Deallocate request handlers */
  12055. while (ctx->handlers) {
  12056. tmp_rh = ctx->handlers;
  12057. ctx->handlers = tmp_rh->next;
  12058. mg_free(tmp_rh->uri);
  12059. mg_free(tmp_rh);
  12060. }
  12061. #ifndef NO_SSL
  12062. /* Deallocate SSL context */
  12063. if (ctx->ssl_ctx != NULL) {
  12064. SSL_CTX_free(ctx->ssl_ctx);
  12065. }
  12066. #endif /* !NO_SSL */
  12067. /* Deallocate worker thread ID array */
  12068. if (ctx->workerthreadids != NULL) {
  12069. mg_free(ctx->workerthreadids);
  12070. }
  12071. /* Deallocate the tls variable */
  12072. if (mg_atomic_dec(&sTlsInit) == 0) {
  12073. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12074. DeleteCriticalSection(&global_log_file_lock);
  12075. #endif /* _WIN32 && !__SYMBIAN32__ */
  12076. #if !defined(_WIN32)
  12077. pthread_mutexattr_destroy(&pthread_mutex_attr);
  12078. #endif
  12079. pthread_key_delete(sTlsKey);
  12080. #if defined(USE_LUA)
  12081. lua_exit_optional_libraries();
  12082. #endif
  12083. }
  12084. /* deallocate system name string */
  12085. mg_free(ctx->systemName);
  12086. /* Deallocate context itself */
  12087. mg_free(ctx);
  12088. }
  12089. void
  12090. mg_stop(struct mg_context *ctx)
  12091. {
  12092. pthread_t mt;
  12093. if (!ctx) {
  12094. return;
  12095. }
  12096. /* We don't use a lock here. Calling mg_stop with the same ctx from
  12097. * two threads is not allowed. */
  12098. mt = ctx->masterthreadid;
  12099. if (mt == 0) {
  12100. return;
  12101. }
  12102. ctx->masterthreadid = 0;
  12103. /* Set stop flag, so all threads know they have to exit. */
  12104. ctx->stop_flag = 1;
  12105. /* Wait until everything has stopped. */
  12106. while (ctx->stop_flag != 2) {
  12107. (void)mg_sleep(10);
  12108. }
  12109. mg_join_thread(mt);
  12110. free_context(ctx);
  12111. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12112. (void)WSACleanup();
  12113. #endif /* _WIN32 && !__SYMBIAN32__ */
  12114. }
  12115. static void
  12116. get_system_name(char **sysName)
  12117. {
  12118. #if defined(_WIN32)
  12119. #if !defined(__SYMBIAN32__)
  12120. #if defined(_WIN32_WCE)
  12121. *sysName = mg_strdup("WinCE");
  12122. #else
  12123. char name[128];
  12124. DWORD dwVersion = 0;
  12125. DWORD dwMajorVersion = 0;
  12126. DWORD dwMinorVersion = 0;
  12127. DWORD dwBuild = 0;
  12128. #ifdef _MSC_VER
  12129. #pragma warning(push)
  12130. /* GetVersion was declared deprecated */
  12131. #pragma warning(disable : 4996)
  12132. #endif
  12133. dwVersion = GetVersion();
  12134. #ifdef _MSC_VER
  12135. #pragma warning(pop)
  12136. #endif
  12137. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  12138. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  12139. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  12140. (void)dwBuild;
  12141. sprintf(name,
  12142. "Windows %u.%u",
  12143. (unsigned)dwMajorVersion,
  12144. (unsigned)dwMinorVersion);
  12145. *sysName = mg_strdup(name);
  12146. #endif
  12147. #else
  12148. *sysName = mg_strdup("Symbian");
  12149. #endif
  12150. #else
  12151. struct utsname name;
  12152. memset(&name, 0, sizeof(name));
  12153. uname(&name);
  12154. *sysName = mg_strdup(name.sysname);
  12155. #endif
  12156. }
  12157. struct mg_context *
  12158. mg_start(const struct mg_callbacks *callbacks,
  12159. void *user_data,
  12160. const char **options)
  12161. {
  12162. struct mg_context *ctx;
  12163. const char *name, *value, *default_value;
  12164. int idx, ok, workerthreadcount;
  12165. unsigned int i;
  12166. void (*exit_callback)(const struct mg_context *ctx) = 0;
  12167. struct mg_workerTLS tls;
  12168. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12169. WSADATA data;
  12170. WSAStartup(MAKEWORD(2, 2), &data);
  12171. #endif /* _WIN32 && !__SYMBIAN32__ */
  12172. /* Allocate context and initialize reasonable general case defaults. */
  12173. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  12174. return NULL;
  12175. }
  12176. /* Random number generator will initialize at the first call */
  12177. ctx->auth_nonce_mask =
  12178. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  12179. if (mg_atomic_inc(&sTlsInit) == 1) {
  12180. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12181. InitializeCriticalSection(&global_log_file_lock);
  12182. #endif /* _WIN32 && !__SYMBIAN32__ */
  12183. #if !defined(_WIN32)
  12184. pthread_mutexattr_init(&pthread_mutex_attr);
  12185. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  12186. #endif
  12187. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  12188. /* Fatal error - abort start. However, this situation should
  12189. * never
  12190. * occur in practice. */
  12191. mg_atomic_dec(&sTlsInit);
  12192. mg_cry(fc(ctx), "Cannot initialize thread local storage");
  12193. mg_free(ctx);
  12194. return NULL;
  12195. }
  12196. #if defined(USE_LUA)
  12197. lua_init_optional_libraries();
  12198. #endif
  12199. } else {
  12200. /* TODO (low): istead of sleeping, check if sTlsKey is already
  12201. * initialized. */
  12202. mg_sleep(1);
  12203. }
  12204. tls.is_master = -1;
  12205. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  12206. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12207. tls.pthread_cond_helper_mutex = NULL;
  12208. #endif
  12209. pthread_setspecific(sTlsKey, &tls);
  12210. /* Dummy use this function - in some #ifdef combinations it's used,
  12211. * while it's not used in others, but GCC seems to stupid to understand
  12212. * #pragma GCC diagnostic ignored "-Wunused-function"
  12213. * in cases the function is unused, and it also complains on
  12214. * __attribute((unused))__ in cases it is used.
  12215. * So dummy use it, to have our peace. */
  12216. (void)mg_current_thread_id();
  12217. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr);
  12218. #if !defined(ALTERNATIVE_QUEUE)
  12219. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  12220. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  12221. #endif
  12222. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr);
  12223. if (!ok) {
  12224. /* Fatal error - abort start. However, this situation should never
  12225. * occur in practice. */
  12226. mg_cry(fc(ctx), "Cannot initialize thread synchronization objects");
  12227. mg_free(ctx);
  12228. pthread_setspecific(sTlsKey, NULL);
  12229. return NULL;
  12230. }
  12231. if (callbacks) {
  12232. ctx->callbacks = *callbacks;
  12233. exit_callback = callbacks->exit_context;
  12234. ctx->callbacks.exit_context = 0;
  12235. }
  12236. ctx->user_data = user_data;
  12237. ctx->handlers = NULL;
  12238. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  12239. ctx->shared_lua_websockets = 0;
  12240. #endif
  12241. while (options && (name = *options++) != NULL) {
  12242. if ((idx = get_option_index(name)) == -1) {
  12243. mg_cry(fc(ctx), "Invalid option: %s", name);
  12244. free_context(ctx);
  12245. pthread_setspecific(sTlsKey, NULL);
  12246. return NULL;
  12247. } else if ((value = *options++) == NULL) {
  12248. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  12249. free_context(ctx);
  12250. pthread_setspecific(sTlsKey, NULL);
  12251. return NULL;
  12252. }
  12253. if (ctx->config[idx] != NULL) {
  12254. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  12255. mg_free(ctx->config[idx]);
  12256. }
  12257. ctx->config[idx] = mg_strdup(value);
  12258. DEBUG_TRACE("[%s] -> [%s]", name, value);
  12259. }
  12260. /* Set default value if needed */
  12261. for (i = 0; config_options[i].name != NULL; i++) {
  12262. default_value = config_options[i].default_value;
  12263. if (ctx->config[i] == NULL && default_value != NULL) {
  12264. ctx->config[i] = mg_strdup(default_value);
  12265. }
  12266. }
  12267. workerthreadcount = atoi(ctx->config[NUM_THREADS]);
  12268. if (workerthreadcount > MAX_WORKER_THREADS) {
  12269. mg_cry(fc(ctx), "Too many worker threads");
  12270. free_context(ctx);
  12271. pthread_setspecific(sTlsKey, NULL);
  12272. return NULL;
  12273. }
  12274. if (workerthreadcount <= 0) {
  12275. mg_cry(fc(ctx), "Invalid number of worker threads");
  12276. free_context(ctx);
  12277. pthread_setspecific(sTlsKey, NULL);
  12278. return NULL;
  12279. }
  12280. #if defined(NO_FILES)
  12281. if (ctx->config[DOCUMENT_ROOT] != NULL) {
  12282. mg_cry(fc(ctx), "%s", "Document root must not be set");
  12283. free_context(ctx);
  12284. pthread_setspecific(sTlsKey, NULL);
  12285. return NULL;
  12286. }
  12287. #endif
  12288. get_system_name(&ctx->systemName);
  12289. /* NOTE(lsm): order is important here. SSL certificates must
  12290. * be initialized before listening ports. UID must be set last. */
  12291. if (!set_gpass_option(ctx) ||
  12292. #if !defined(NO_SSL)
  12293. !set_ssl_option(ctx) ||
  12294. #endif
  12295. !set_ports_option(ctx) ||
  12296. #if !defined(_WIN32)
  12297. !set_uid_option(ctx) ||
  12298. #endif
  12299. !set_acl_option(ctx)) {
  12300. free_context(ctx);
  12301. pthread_setspecific(sTlsKey, NULL);
  12302. return NULL;
  12303. }
  12304. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  12305. /* Ignore SIGPIPE signal, so if browser cancels the request, it
  12306. * won't kill the whole process. */
  12307. (void)signal(SIGPIPE, SIG_IGN);
  12308. #endif /* !_WIN32 && !__SYMBIAN32__ */
  12309. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  12310. ctx->workerthreadids =
  12311. (pthread_t *)mg_calloc(ctx->cfg_worker_threads, sizeof(pthread_t));
  12312. if (ctx->workerthreadids == NULL) {
  12313. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  12314. free_context(ctx);
  12315. pthread_setspecific(sTlsKey, NULL);
  12316. return NULL;
  12317. }
  12318. #if defined(ALTERNATIVE_QUEUE)
  12319. ctx->client_wait_events =
  12320. mg_calloc(sizeof(ctx->client_wait_events[0]), ctx->cfg_worker_threads);
  12321. if (ctx->client_wait_events == NULL) {
  12322. mg_cry(fc(ctx), "Not enough memory for worker event array");
  12323. mg_free(ctx->workerthreadids);
  12324. free_context(ctx);
  12325. pthread_setspecific(sTlsKey, NULL);
  12326. return NULL;
  12327. }
  12328. ctx->client_socks =
  12329. mg_calloc(sizeof(ctx->client_socks[0]), ctx->cfg_worker_threads);
  12330. if (ctx->client_wait_events == NULL) {
  12331. mg_cry(fc(ctx), "Not enough memory for worker socket array");
  12332. mg_free(ctx->client_socks);
  12333. mg_free(ctx->workerthreadids);
  12334. free_context(ctx);
  12335. pthread_setspecific(sTlsKey, NULL);
  12336. return NULL;
  12337. }
  12338. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  12339. ctx->client_wait_events[i] = event_create();
  12340. if (ctx->client_wait_events[i] == 0) {
  12341. mg_cry(fc(ctx), "Error creating worker event %i", i);
  12342. /* TODO: clean all and exit */
  12343. }
  12344. }
  12345. #endif
  12346. #if defined(USE_TIMERS)
  12347. if (timers_init(ctx) != 0) {
  12348. mg_cry(fc(ctx), "Error creating timers");
  12349. free_context(ctx);
  12350. pthread_setspecific(sTlsKey, NULL);
  12351. return NULL;
  12352. }
  12353. #endif
  12354. /* Context has been created - init user libraries */
  12355. if (ctx->callbacks.init_context) {
  12356. ctx->callbacks.init_context(ctx);
  12357. }
  12358. ctx->callbacks.exit_context = exit_callback;
  12359. ctx->context_type = 1; /* server context */
  12360. /* Start master (listening) thread */
  12361. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  12362. /* Start worker threads */
  12363. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  12364. struct worker_thread_args *wta =
  12365. mg_malloc(sizeof(struct worker_thread_args));
  12366. if (wta) {
  12367. wta->ctx = ctx;
  12368. wta->index = (int)i;
  12369. }
  12370. if ((wta == NULL)
  12371. || (mg_start_thread_with_id(worker_thread,
  12372. wta,
  12373. &ctx->workerthreadids[i]) != 0)) {
  12374. /* thread was not created */
  12375. if (wta != NULL) {
  12376. mg_free(wta);
  12377. }
  12378. if (i > 0) {
  12379. mg_cry(fc(ctx),
  12380. "Cannot start worker thread %i: error %ld",
  12381. i + 1,
  12382. (long)ERRNO);
  12383. } else {
  12384. mg_cry(fc(ctx),
  12385. "Cannot create threads: error %ld",
  12386. (long)ERRNO);
  12387. free_context(ctx);
  12388. pthread_setspecific(sTlsKey, NULL);
  12389. return NULL;
  12390. }
  12391. break;
  12392. }
  12393. }
  12394. pthread_setspecific(sTlsKey, NULL);
  12395. return ctx;
  12396. }
  12397. /* Feature check API function */
  12398. unsigned
  12399. mg_check_feature(unsigned feature)
  12400. {
  12401. static const unsigned feature_set = 0
  12402. /* Set bits for available features according to API documentation.
  12403. * This bit mask is created at compile time, according to the active
  12404. * preprocessor defines. It is a single const value at runtime. */
  12405. #if !defined(NO_FILES)
  12406. | 0x0001u
  12407. #endif
  12408. #if !defined(NO_SSL)
  12409. | 0x0002u
  12410. #endif
  12411. #if !defined(NO_CGI)
  12412. | 0x0004u
  12413. #endif
  12414. #if defined(USE_IPV6)
  12415. | 0x0008u
  12416. #endif
  12417. #if defined(USE_WEBSOCKET)
  12418. | 0x0010u
  12419. #endif
  12420. #if defined(USE_LUA)
  12421. | 0x0020u
  12422. #endif
  12423. #if defined(USE_DUKTAPE)
  12424. | 0x0040u
  12425. #endif
  12426. #if !defined(NO_CACHING)
  12427. | 0x0080u
  12428. #endif
  12429. /* Set some extra bits not defined in the API documentation.
  12430. * These bits may change without further notice. */
  12431. #if defined(MG_LEGACY_INTERFACE)
  12432. | 0x8000u
  12433. #endif
  12434. #if defined(MEMORY_DEBUGGING)
  12435. | 0x0100u
  12436. #endif
  12437. #if defined(USE_TIMERS)
  12438. | 0x0200u
  12439. #endif
  12440. #if !defined(NO_NONCE_CHECK)
  12441. | 0x0400u
  12442. #endif
  12443. #if !defined(NO_POPEN)
  12444. | 0x0800u
  12445. #endif
  12446. ;
  12447. return (feature & feature_set);
  12448. }