civetweb.c 377 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478
  1. /* Copyright (c) 2013-2016 the Civetweb developers
  2. * Copyright (c) 2004-2013 Sergey Lyubka
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. * THE SOFTWARE.
  21. */
  22. #if defined(_WIN32)
  23. #if !defined(_CRT_SECURE_NO_WARNINGS)
  24. #define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */
  25. #endif
  26. #ifndef _WIN32_WINNT /* defined for tdm-gcc so we can use getnameinfo */
  27. #define _WIN32_WINNT 0x0501
  28. #endif
  29. #else
  30. #if defined(__GNUC__) && !defined(_GNU_SOURCE)
  31. #define _GNU_SOURCE /* for setgroups() */
  32. #endif
  33. #if defined(__linux__) && !defined(_XOPEN_SOURCE)
  34. #define _XOPEN_SOURCE 600 /* For flockfile() on Linux */
  35. #endif
  36. #ifndef _LARGEFILE_SOURCE
  37. #define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
  38. #endif
  39. #ifndef _FILE_OFFSET_BITS
  40. #define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
  41. #endif
  42. #ifndef __STDC_FORMAT_MACROS
  43. #define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
  44. #endif
  45. #ifndef __STDC_LIMIT_MACROS
  46. #define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
  47. #endif
  48. #ifdef __sun
  49. #define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */
  50. #define __inline inline /* not recognized on older compiler versions */
  51. #endif
  52. #endif
  53. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  54. #define USE_TIMERS
  55. #endif
  56. #if defined(_MSC_VER)
  57. /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
  58. #pragma warning(disable : 4306)
  59. /* conditional expression is constant: introduced by FD_SET(..) */
  60. #pragma warning(disable : 4127)
  61. /* non-constant aggregate initializer: issued due to missing C99 support */
  62. #pragma warning(disable : 4204)
  63. /* padding added after data member */
  64. #pragma warning(disable : 4820)
  65. /* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
  66. #pragma warning(disable : 4668)
  67. /* no function prototype given: converting '()' to '(void)' */
  68. #pragma warning(disable : 4255)
  69. /* function has been selected for automatic inline expansion */
  70. #pragma warning(disable : 4711)
  71. #endif
  72. /* This code uses static_assert to check some conditions.
  73. * Unfortunately some compilers still do not support it, so we have a
  74. * replacement function here. */
  75. #if defined(_MSC_VER) && (_MSC_VER >= 1600)
  76. #define mg_static_assert static_assert
  77. #elif defined(__cplusplus) && (__cplusplus >= 201103L)
  78. #define mg_static_assert static_assert
  79. #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)
  80. #define mg_static_assert _Static_assert
  81. #else
  82. char static_assert_replacement[1];
  83. #define mg_static_assert(cond, txt) \
  84. extern char static_assert_replacement[(cond) ? 1 : -1]
  85. #endif
  86. mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
  87. "int data type size check");
  88. mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
  89. "pointer data type size check");
  90. mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
  91. /* DTL -- including winsock2.h works better if lean and mean */
  92. #ifndef WIN32_LEAN_AND_MEAN
  93. #define WIN32_LEAN_AND_MEAN
  94. #endif
  95. #if defined(__SYMBIAN32__)
  96. #define NO_SSL /* SSL is not supported */
  97. #define NO_CGI /* CGI is not supported */
  98. #define PATH_MAX FILENAME_MAX
  99. #endif /* __SYMBIAN32__ */
  100. /* Include the header file here, so the CivetWeb interface is defined for the
  101. * entire implementation, including the following forward definitions. */
  102. #include "civetweb.h"
  103. #ifndef IGNORE_UNUSED_RESULT
  104. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  105. #endif
  106. #ifndef _WIN32_WCE /* Some ANSI #includes are not available on Windows CE */
  107. #include <sys/types.h>
  108. #include <sys/stat.h>
  109. #include <errno.h>
  110. #include <signal.h>
  111. #include <fcntl.h>
  112. #endif /* !_WIN32_WCE */
  113. #ifdef __clang__
  114. /* When using -Weverything, clang does not accept it's own headers
  115. * in a release build configuration. Disable what is too much in
  116. * -Weverything. */
  117. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  118. #endif
  119. #ifdef __MACH__ /* Apple OSX section */
  120. #ifdef __clang__
  121. /* Avoid warnings for Xopen 7.00 and higher */
  122. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  123. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  124. #endif
  125. #define CLOCK_MONOTONIC (1)
  126. #define CLOCK_REALTIME (2)
  127. #include <sys/errno.h>
  128. #include <sys/time.h>
  129. #include <mach/clock.h>
  130. #include <mach/mach.h>
  131. #include <mach/mach_time.h>
  132. #include <assert.h>
  133. /* clock_gettime is not implemented on OSX prior to 10.12 */
  134. int _civet_clock_gettime(int clk_id, struct timespec *t);
  135. int
  136. _civet_clock_gettime(int clk_id, struct timespec *t)
  137. {
  138. memset(t, 0, sizeof(*t));
  139. if (clk_id == CLOCK_REALTIME) {
  140. struct timeval now;
  141. int rv = gettimeofday(&now, NULL);
  142. if (rv) {
  143. return rv;
  144. }
  145. t->tv_sec = now.tv_sec;
  146. t->tv_nsec = now.tv_usec * 1000;
  147. return 0;
  148. } else if (clk_id == CLOCK_MONOTONIC) {
  149. static uint64_t clock_start_time = 0;
  150. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  151. uint64_t now = mach_absolute_time();
  152. if (clock_start_time == 0) {
  153. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  154. #if defined(DEBUG)
  155. assert(mach_status == KERN_SUCCESS);
  156. #else
  157. /* appease "unused variable" warning for release builds */
  158. (void)mach_status;
  159. #endif
  160. clock_start_time = now;
  161. }
  162. now = (uint64_t)((double)(now - clock_start_time)
  163. * (double)timebase_ifo.numer
  164. / (double)timebase_ifo.denom);
  165. t->tv_sec = now / 1000000000;
  166. t->tv_nsec = now % 1000000000;
  167. return 0;
  168. }
  169. return -1; /* EINVAL - Clock ID is unknown */
  170. }
  171. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  172. #ifdef __CLOCK_AVAILABILITY
  173. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  174. * declared
  175. * but it may be NULL at runtime. So we need to check before using it. */
  176. int _civet_safe_clock_gettime(int clk_id, struct timespec *t);
  177. int
  178. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  179. {
  180. if (clock_gettime) {
  181. return clock_gettime(clk_id, t);
  182. }
  183. return _civet_clock_gettime(clk_id, t);
  184. }
  185. #define clock_gettime _civet_safe_clock_gettime
  186. #else
  187. #define clock_gettime _civet_clock_gettime
  188. #endif
  189. #endif
  190. #include <time.h>
  191. #include <stdlib.h>
  192. #include <stdarg.h>
  193. #include <assert.h>
  194. #include <string.h>
  195. #include <ctype.h>
  196. #include <limits.h>
  197. #include <stddef.h>
  198. #include <stdio.h>
  199. #include <stdint.h>
  200. #ifndef INT64_MAX
  201. #define INT64_MAX (9223372036854775807)
  202. #endif
  203. #ifndef MAX_WORKER_THREADS
  204. #define MAX_WORKER_THREADS (1024 * 64)
  205. #endif
  206. #ifndef SOCKET_TIMEOUT_QUANTUM /* in ms */
  207. #define SOCKET_TIMEOUT_QUANTUM (2000)
  208. #endif
  209. #define SHUTDOWN_RD (0)
  210. #define SHUTDOWN_WR (1)
  211. #define SHUTDOWN_BOTH (2)
  212. mg_static_assert(MAX_WORKER_THREADS >= 1,
  213. "worker threads must be a positive number");
  214. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  215. "size_t data type size check");
  216. #if defined(_WIN32) \
  217. && !defined(__SYMBIAN32__) /* WINDOWS / UNIX include block */
  218. #include <windows.h>
  219. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  220. #include <ws2tcpip.h>
  221. typedef const char *SOCK_OPT_TYPE;
  222. #if !defined(PATH_MAX)
  223. #define PATH_MAX (MAX_PATH)
  224. #endif
  225. #if !defined(PATH_MAX)
  226. #define PATH_MAX (4096)
  227. #endif
  228. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  229. #ifndef _IN_PORT_T
  230. #ifndef in_port_t
  231. #define in_port_t u_short
  232. #endif
  233. #endif
  234. #ifndef _WIN32_WCE
  235. #include <process.h>
  236. #include <direct.h>
  237. #include <io.h>
  238. #else /* _WIN32_WCE */
  239. #define NO_CGI /* WinCE has no pipes */
  240. #define NO_POPEN /* WinCE has no popen */
  241. typedef long off_t;
  242. #define errno ((int)(GetLastError()))
  243. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  244. #endif /* _WIN32_WCE */
  245. #define MAKEUQUAD(lo, hi) \
  246. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  247. #define RATE_DIFF (10000000) /* 100 nsecs */
  248. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  249. #define SYS2UNIX_TIME(lo, hi) \
  250. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  251. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  252. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  253. * Also use _strtoui64 on modern M$ compilers */
  254. #if defined(_MSC_VER)
  255. #if (_MSC_VER < 1300)
  256. #define STRX(x) #x
  257. #define STR(x) STRX(x)
  258. #define __func__ __FILE__ ":" STR(__LINE__)
  259. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  260. #define strtoll(x, y, z) (_atoi64(x))
  261. #else
  262. #define __func__ __FUNCTION__
  263. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  264. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  265. #endif
  266. #endif /* _MSC_VER */
  267. #define ERRNO ((int)(GetLastError()))
  268. #define NO_SOCKLEN_T
  269. #if defined(_WIN64) || defined(__MINGW64__)
  270. #define SSL_LIB "ssleay64.dll"
  271. #define CRYPTO_LIB "libeay64.dll"
  272. #else
  273. #define SSL_LIB "ssleay32.dll"
  274. #define CRYPTO_LIB "libeay32.dll"
  275. #endif
  276. #define O_NONBLOCK (0)
  277. #ifndef W_OK
  278. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  279. #endif
  280. #if !defined(EWOULDBLOCK)
  281. #define EWOULDBLOCK WSAEWOULDBLOCK
  282. #endif /* !EWOULDBLOCK */
  283. #define _POSIX_
  284. #define INT64_FMT "I64d"
  285. #define UINT64_FMT "I64u"
  286. #define WINCDECL __cdecl
  287. #define vsnprintf_impl _vsnprintf
  288. #define access _access
  289. #define mg_sleep(x) (Sleep(x))
  290. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  291. #ifndef popen
  292. #define popen(x, y) (_popen(x, y))
  293. #endif
  294. #ifndef pclose
  295. #define pclose(x) (_pclose(x))
  296. #endif
  297. #define close(x) (_close(x))
  298. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  299. #define RTLD_LAZY (0)
  300. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  301. #define fdopen(x, y) (_fdopen((x), (y)))
  302. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  303. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  304. #define flockfile(x) (EnterCriticalSection(&global_log_file_lock))
  305. #define funlockfile(x) (LeaveCriticalSection(&global_log_file_lock))
  306. #define sleep(x) (Sleep((x)*1000))
  307. #define rmdir(x) (_rmdir(x))
  308. #define timegm(x) (_mkgmtime(x))
  309. #if !defined(fileno)
  310. #define fileno(x) (_fileno(x))
  311. #endif /* !fileno MINGW #defines fileno */
  312. typedef HANDLE pthread_mutex_t;
  313. typedef DWORD pthread_key_t;
  314. typedef HANDLE pthread_t;
  315. typedef struct {
  316. CRITICAL_SECTION threadIdSec;
  317. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  318. } pthread_cond_t;
  319. #ifndef __clockid_t_defined
  320. typedef DWORD clockid_t;
  321. #endif
  322. #ifndef CLOCK_MONOTONIC
  323. #define CLOCK_MONOTONIC (1)
  324. #endif
  325. #ifndef CLOCK_REALTIME
  326. #define CLOCK_REALTIME (2)
  327. #endif
  328. #ifndef WIN_PTHREADS_TIME_H
  329. static int
  330. clock_gettime(clockid_t clk_id, struct timespec *tp)
  331. {
  332. FILETIME ft;
  333. ULARGE_INTEGER li;
  334. BOOL ok = FALSE;
  335. double d;
  336. static double perfcnt_per_sec = 0.0;
  337. if (tp) {
  338. memset(tp, 0, sizeof(*tp));
  339. if (clk_id == CLOCK_REALTIME) {
  340. GetSystemTimeAsFileTime(&ft);
  341. li.LowPart = ft.dwLowDateTime;
  342. li.HighPart = ft.dwHighDateTime;
  343. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  344. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  345. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  346. ok = TRUE;
  347. } else if (clk_id == CLOCK_MONOTONIC) {
  348. if (perfcnt_per_sec == 0.0) {
  349. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  350. perfcnt_per_sec = 1.0 / li.QuadPart;
  351. }
  352. if (perfcnt_per_sec != 0.0) {
  353. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  354. d = li.QuadPart * perfcnt_per_sec;
  355. tp->tv_sec = (time_t)d;
  356. d -= tp->tv_sec;
  357. tp->tv_nsec = (long)(d * 1.0E9);
  358. ok = TRUE;
  359. }
  360. }
  361. }
  362. return ok ? 0 : -1;
  363. }
  364. #endif
  365. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  366. #define _TIMESPEC_DEFINED
  367. #endif
  368. #ifndef _TIMESPEC_DEFINED
  369. struct timespec {
  370. time_t tv_sec; /* seconds */
  371. long tv_nsec; /* nanoseconds */
  372. };
  373. #endif
  374. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  375. static int pthread_mutex_lock(pthread_mutex_t *);
  376. static int pthread_mutex_unlock(pthread_mutex_t *);
  377. static void path_to_unicode(const struct mg_connection *conn,
  378. const char *path,
  379. wchar_t *wbuf,
  380. size_t wbuf_len);
  381. /* All file operations need to be rewritten to solve #246. */
  382. #include "file_ops.inl"
  383. struct mg_file;
  384. static const char *
  385. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p);
  386. /* POSIX dirent interface */
  387. struct dirent {
  388. char d_name[PATH_MAX];
  389. };
  390. typedef struct DIR {
  391. HANDLE handle;
  392. WIN32_FIND_DATAW info;
  393. struct dirent result;
  394. } DIR;
  395. #if defined(_WIN32) && !defined(POLLIN)
  396. #ifndef HAVE_POLL
  397. struct pollfd {
  398. SOCKET fd;
  399. short events;
  400. short revents;
  401. };
  402. #define POLLIN (0x0300)
  403. #endif
  404. #endif
  405. /* Mark required libraries */
  406. #if defined(_MSC_VER)
  407. #pragma comment(lib, "Ws2_32.lib")
  408. #endif
  409. #else /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  410. WINDOWS / UNIX include block */
  411. #include <sys/wait.h>
  412. #include <sys/socket.h>
  413. #include <sys/poll.h>
  414. #include <netinet/in.h>
  415. #include <arpa/inet.h>
  416. #include <sys/time.h>
  417. #include <sys/utsname.h>
  418. #include <stdint.h>
  419. #include <inttypes.h>
  420. #include <netdb.h>
  421. #include <netinet/tcp.h>
  422. typedef const void *SOCK_OPT_TYPE;
  423. #if defined(ANDROID)
  424. typedef unsigned short int in_port_t;
  425. #endif
  426. #include <pwd.h>
  427. #include <unistd.h>
  428. #include <grp.h>
  429. #include <dirent.h>
  430. #define vsnprintf_impl vsnprintf
  431. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  432. #include <dlfcn.h>
  433. #endif
  434. #include <pthread.h>
  435. #if defined(__MACH__)
  436. #define SSL_LIB "libssl.dylib"
  437. #define CRYPTO_LIB "libcrypto.dylib"
  438. #else
  439. #if !defined(SSL_LIB)
  440. #define SSL_LIB "libssl.so"
  441. #endif
  442. #if !defined(CRYPTO_LIB)
  443. #define CRYPTO_LIB "libcrypto.so"
  444. #endif
  445. #endif
  446. #ifndef O_BINARY
  447. #define O_BINARY (0)
  448. #endif /* O_BINARY */
  449. #define closesocket(a) (close(a))
  450. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  451. #define mg_remove(conn, x) (remove(x))
  452. #define mg_sleep(x) (usleep((x)*1000))
  453. #define mg_opendir(conn, x) (opendir(x))
  454. #define mg_closedir(x) (closedir(x))
  455. #define mg_readdir(x) (readdir(x))
  456. #define ERRNO (errno)
  457. #define INVALID_SOCKET (-1)
  458. #define INT64_FMT PRId64
  459. #define UINT64_FMT PRIu64
  460. typedef int SOCKET;
  461. #define WINCDECL
  462. #if defined(__hpux)
  463. /* HPUX 11 does not have monotonic, fall back to realtime */
  464. #ifndef CLOCK_MONOTONIC
  465. #define CLOCK_MONOTONIC CLOCK_REALTIME
  466. #endif
  467. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  468. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  469. * the prototypes use int* rather than socklen_t* which matches the
  470. * actual library expectation. When called with the wrong size arg
  471. * accept() returns a zero client inet addr and check_acl() always
  472. * fails. Since socklen_t is widely used below, just force replace
  473. * their typedef with int. - DTL
  474. */
  475. #define socklen_t int
  476. #endif /* hpux */
  477. #endif /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  478. WINDOWS / UNIX include block */
  479. /* va_copy should always be a macro, C99 and C++11 - DTL */
  480. #ifndef va_copy
  481. #define va_copy(x, y) ((x) = (y))
  482. #endif
  483. #ifdef _WIN32
  484. /* Create substitutes for POSIX functions in Win32. */
  485. #if defined(__MINGW32__)
  486. /* Show no warning in case system functions are not used. */
  487. #pragma GCC diagnostic push
  488. #pragma GCC diagnostic ignored "-Wunused-function"
  489. #endif
  490. static CRITICAL_SECTION global_log_file_lock;
  491. static DWORD
  492. pthread_self(void)
  493. {
  494. return GetCurrentThreadId();
  495. }
  496. static int
  497. pthread_key_create(
  498. pthread_key_t *key,
  499. void (*_ignored)(void *) /* destructor not supported for Windows */
  500. )
  501. {
  502. (void)_ignored;
  503. if ((key != 0)) {
  504. *key = TlsAlloc();
  505. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  506. }
  507. return -2;
  508. }
  509. static int
  510. pthread_key_delete(pthread_key_t key)
  511. {
  512. return TlsFree(key) ? 0 : 1;
  513. }
  514. static int
  515. pthread_setspecific(pthread_key_t key, void *value)
  516. {
  517. return TlsSetValue(key, value) ? 0 : 1;
  518. }
  519. static void *
  520. pthread_getspecific(pthread_key_t key)
  521. {
  522. return TlsGetValue(key);
  523. }
  524. #if defined(__MINGW32__)
  525. /* Enable unused function warning again */
  526. #pragma GCC diagnostic pop
  527. #endif
  528. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  529. #else
  530. static pthread_mutexattr_t pthread_mutex_attr;
  531. #endif /* _WIN32 */
  532. #define PASSWORDS_FILE_NAME ".htpasswd"
  533. #define CGI_ENVIRONMENT_SIZE (4096)
  534. #define MAX_CGI_ENVIR_VARS (256)
  535. #define MG_BUF_LEN (8192)
  536. #ifndef MAX_REQUEST_SIZE
  537. #define MAX_REQUEST_SIZE (16384)
  538. #endif
  539. mg_static_assert(MAX_REQUEST_SIZE >= 256,
  540. "request size length must be a positive number");
  541. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  542. #if defined(_WIN32_WCE)
  543. /* Create substitutes for POSIX functions in Win32. */
  544. #if defined(__MINGW32__)
  545. /* Show no warning in case system functions are not used. */
  546. #pragma GCC diagnostic push
  547. #pragma GCC diagnostic ignored "-Wunused-function"
  548. #endif
  549. static time_t
  550. time(time_t *ptime)
  551. {
  552. time_t t;
  553. SYSTEMTIME st;
  554. FILETIME ft;
  555. GetSystemTime(&st);
  556. SystemTimeToFileTime(&st, &ft);
  557. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  558. if (ptime != NULL) {
  559. *ptime = t;
  560. }
  561. return t;
  562. }
  563. static struct tm *
  564. localtime_s(const time_t *ptime, struct tm *ptm)
  565. {
  566. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  567. FILETIME ft, lft;
  568. SYSTEMTIME st;
  569. TIME_ZONE_INFORMATION tzinfo;
  570. if (ptm == NULL) {
  571. return NULL;
  572. }
  573. *(int64_t *)&ft = t;
  574. FileTimeToLocalFileTime(&ft, &lft);
  575. FileTimeToSystemTime(&lft, &st);
  576. ptm->tm_year = st.wYear - 1900;
  577. ptm->tm_mon = st.wMonth - 1;
  578. ptm->tm_wday = st.wDayOfWeek;
  579. ptm->tm_mday = st.wDay;
  580. ptm->tm_hour = st.wHour;
  581. ptm->tm_min = st.wMinute;
  582. ptm->tm_sec = st.wSecond;
  583. ptm->tm_yday = 0; /* hope nobody uses this */
  584. ptm->tm_isdst =
  585. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  586. return ptm;
  587. }
  588. static struct tm *
  589. gmtime_s(const time_t *ptime, struct tm *ptm)
  590. {
  591. /* FIXME(lsm): fix this. */
  592. return localtime_s(ptime, ptm);
  593. }
  594. static int mg_atomic_inc(volatile int *addr);
  595. static struct tm tm_array[MAX_WORKER_THREADS];
  596. static int tm_index = 0;
  597. static struct tm *
  598. localtime(const time_t *ptime)
  599. {
  600. int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0]));
  601. return localtime_s(ptime, tm_array + i);
  602. }
  603. static struct tm *
  604. gmtime(const time_t *ptime)
  605. {
  606. int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  607. return gmtime_s(ptime, tm_array + i);
  608. }
  609. static size_t
  610. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  611. {
  612. /* TODO */ //(void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  613. // for WinCE");
  614. return 0;
  615. }
  616. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  617. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  618. #define remove(f) mg_remove(NULL, f)
  619. static int
  620. rename(const char *a, const char *b)
  621. {
  622. wchar_t wa[PATH_MAX];
  623. wchar_t wb[PATH_MAX];
  624. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  625. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  626. return MoveFileW(wa, wb) ? 0 : -1;
  627. }
  628. struct stat {
  629. int64_t st_size;
  630. time_t st_mtime;
  631. };
  632. static int
  633. stat(const char *name, struct stat *st)
  634. {
  635. wchar_t wbuf[PATH_MAX];
  636. WIN32_FILE_ATTRIBUTE_DATA attr;
  637. time_t creation_time, write_time;
  638. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  639. memset(&attr, 0, sizeof(attr));
  640. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  641. st->st_size =
  642. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  643. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  644. attr.ftLastWriteTime.dwHighDateTime);
  645. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  646. attr.ftCreationTime.dwHighDateTime);
  647. if (creation_time > write_time) {
  648. st->st_mtime = creation_time;
  649. } else {
  650. st->st_mtime = write_time;
  651. }
  652. return 0;
  653. }
  654. #define access(x, a) 1 /* not required anyway */
  655. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  656. #define EEXIST 1 /* TODO: See Windows error codes */
  657. #define EACCES 2 /* TODO: See Windows error codes */
  658. #define ENOENT 3 /* TODO: See Windows Error codes */
  659. #if defined(__MINGW32__)
  660. /* Enable unused function warning again */
  661. #pragma GCC diagnostic pop
  662. #endif
  663. #endif /* defined(_WIN32_WCE) */
  664. #if !defined(DEBUG_TRACE)
  665. #if defined(DEBUG)
  666. static void DEBUG_TRACE_FUNC(const char *func,
  667. unsigned line,
  668. PRINTF_FORMAT_STRING(const char *fmt),
  669. ...) PRINTF_ARGS(3, 4);
  670. static void
  671. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  672. {
  673. va_list args;
  674. struct timespec tsnow;
  675. uint64_t nsnow;
  676. static uint64_t nslast;
  677. clock_gettime(CLOCK_REALTIME, &tsnow);
  678. nsnow = (((int64_t)tsnow.tv_sec) * 1000000000) + tsnow.tv_nsec;
  679. flockfile(stdout);
  680. printf("*** %lu.%09lu %12" INT64_FMT " %p %s:%u: ",
  681. (unsigned long)tsnow.tv_sec,
  682. (unsigned long)tsnow.tv_nsec,
  683. nsnow - nslast,
  684. (void *)pthread_self(),
  685. func,
  686. line);
  687. va_start(args, fmt);
  688. vprintf(fmt, args);
  689. va_end(args);
  690. putchar('\n');
  691. fflush(stdout);
  692. funlockfile(stdout);
  693. nslast = nsnow;
  694. }
  695. #define DEBUG_TRACE(fmt, ...) \
  696. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  697. #else
  698. #define DEBUG_TRACE(fmt, ...) \
  699. do { \
  700. } while (0)
  701. #endif /* DEBUG */
  702. #endif /* DEBUG_TRACE */
  703. #if defined(MEMORY_DEBUGGING)
  704. unsigned long mg_memory_debug_blockCount = 0;
  705. unsigned long mg_memory_debug_totalMemUsed = 0;
  706. static void *
  707. mg_malloc_ex(size_t size, const char *file, unsigned line)
  708. {
  709. void *data = malloc(size + sizeof(size_t));
  710. void *memory = 0;
  711. char mallocStr[256];
  712. if (data) {
  713. *(size_t *)data = size;
  714. mg_memory_debug_totalMemUsed += size;
  715. mg_memory_debug_blockCount++;
  716. memory = (void *)(((char *)data) + sizeof(size_t));
  717. }
  718. sprintf(mallocStr,
  719. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  720. memory,
  721. (unsigned long)size,
  722. mg_memory_debug_totalMemUsed,
  723. mg_memory_debug_blockCount,
  724. file,
  725. line);
  726. #if defined(_WIN32)
  727. OutputDebugStringA(mallocStr);
  728. #else
  729. DEBUG_TRACE("%s", mallocStr);
  730. #endif
  731. return memory;
  732. }
  733. static void *
  734. mg_calloc_ex(size_t count, size_t size, const char *file, unsigned line)
  735. {
  736. void *data = mg_malloc_ex(size * count, file, line);
  737. if (data) {
  738. memset(data, 0, size * count);
  739. }
  740. return data;
  741. }
  742. static void
  743. mg_free_ex(void *memory, const char *file, unsigned line)
  744. {
  745. char mallocStr[256];
  746. void *data = (void *)(((char *)memory) - sizeof(size_t));
  747. size_t size;
  748. if (memory) {
  749. size = *(size_t *)data;
  750. mg_memory_debug_totalMemUsed -= size;
  751. mg_memory_debug_blockCount--;
  752. sprintf(mallocStr,
  753. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  754. memory,
  755. (unsigned long)size,
  756. mg_memory_debug_totalMemUsed,
  757. mg_memory_debug_blockCount,
  758. file,
  759. line);
  760. #if defined(_WIN32)
  761. OutputDebugStringA(mallocStr);
  762. #else
  763. DEBUG_TRACE("%s", mallocStr);
  764. #endif
  765. free(data);
  766. }
  767. }
  768. static void *
  769. mg_realloc_ex(void *memory, size_t newsize, const char *file, unsigned line)
  770. {
  771. char mallocStr[256];
  772. void *data;
  773. void *_realloc;
  774. size_t oldsize;
  775. if (newsize) {
  776. if (memory) {
  777. data = (void *)(((char *)memory) - sizeof(size_t));
  778. oldsize = *(size_t *)data;
  779. _realloc = realloc(data, newsize + sizeof(size_t));
  780. if (_realloc) {
  781. data = _realloc;
  782. mg_memory_debug_totalMemUsed -= oldsize;
  783. sprintf(mallocStr,
  784. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  785. memory,
  786. (unsigned long)oldsize,
  787. mg_memory_debug_totalMemUsed,
  788. mg_memory_debug_blockCount,
  789. file,
  790. line);
  791. #if defined(_WIN32)
  792. OutputDebugStringA(mallocStr);
  793. #else
  794. DEBUG_TRACE("%s", mallocStr);
  795. #endif
  796. mg_memory_debug_totalMemUsed += newsize;
  797. sprintf(mallocStr,
  798. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  799. memory,
  800. (unsigned long)newsize,
  801. mg_memory_debug_totalMemUsed,
  802. mg_memory_debug_blockCount,
  803. file,
  804. line);
  805. #if defined(_WIN32)
  806. OutputDebugStringA(mallocStr);
  807. #else
  808. DEBUG_TRACE("%s", mallocStr);
  809. #endif
  810. *(size_t *)data = newsize;
  811. data = (void *)(((char *)data) + sizeof(size_t));
  812. } else {
  813. #if defined(_WIN32)
  814. OutputDebugStringA("MEM: realloc failed\n");
  815. #else
  816. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  817. #endif
  818. return _realloc;
  819. }
  820. } else {
  821. data = mg_malloc_ex(newsize, file, line);
  822. }
  823. } else {
  824. data = 0;
  825. mg_free_ex(memory, file, line);
  826. }
  827. return data;
  828. }
  829. #define mg_malloc(a) mg_malloc_ex(a, __FILE__, __LINE__)
  830. #define mg_calloc(a, b) mg_calloc_ex(a, b, __FILE__, __LINE__)
  831. #define mg_realloc(a, b) mg_realloc_ex(a, b, __FILE__, __LINE__)
  832. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  833. #else
  834. static __inline void *
  835. mg_malloc(size_t a)
  836. {
  837. return malloc(a);
  838. }
  839. static __inline void *
  840. mg_calloc(size_t a, size_t b)
  841. {
  842. return calloc(a, b);
  843. }
  844. static __inline void *
  845. mg_realloc(void *a, size_t b)
  846. {
  847. return realloc(a, b);
  848. }
  849. static __inline void
  850. mg_free(void *a)
  851. {
  852. free(a);
  853. }
  854. #endif
  855. static void mg_vsnprintf(const struct mg_connection *conn,
  856. int *truncated,
  857. char *buf,
  858. size_t buflen,
  859. const char *fmt,
  860. va_list ap);
  861. static void mg_snprintf(const struct mg_connection *conn,
  862. int *truncated,
  863. char *buf,
  864. size_t buflen,
  865. PRINTF_FORMAT_STRING(const char *fmt),
  866. ...) PRINTF_ARGS(5, 6);
  867. /* This following lines are just meant as a reminder to use the mg-functions
  868. * for memory management */
  869. #ifdef malloc
  870. #undef malloc
  871. #endif
  872. #ifdef calloc
  873. #undef calloc
  874. #endif
  875. #ifdef realloc
  876. #undef realloc
  877. #endif
  878. #ifdef free
  879. #undef free
  880. #endif
  881. #ifdef snprintf
  882. #undef snprintf
  883. #endif
  884. #ifdef vsnprintf
  885. #undef vsnprintf
  886. #endif
  887. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  888. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  889. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  890. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  891. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  892. #ifdef _WIN32 /* vsnprintf must not be used in any system, * \ \ \ \
  893. * but this define only works well for Windows. */
  894. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  895. #endif
  896. #define MD5_STATIC static
  897. #include "md5.inl"
  898. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  899. #ifdef NO_SOCKLEN_T
  900. typedef int socklen_t;
  901. #endif /* NO_SOCKLEN_T */
  902. #define _DARWIN_UNLIMITED_SELECT
  903. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  904. #if !defined(MSG_NOSIGNAL)
  905. #define MSG_NOSIGNAL (0)
  906. #endif
  907. #if !defined(SOMAXCONN)
  908. #define SOMAXCONN (100)
  909. #endif
  910. /* Size of the accepted socket queue */
  911. #if !defined(MGSQLEN)
  912. #define MGSQLEN (20)
  913. #endif
  914. #if defined(NO_SSL)
  915. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  916. typedef struct SSL_CTX SSL_CTX;
  917. #else
  918. #if defined(NO_SSL_DL)
  919. #include <openssl/ssl.h>
  920. #include <openssl/err.h>
  921. #include <openssl/crypto.h>
  922. #include <openssl/x509.h>
  923. #include <openssl/pem.h>
  924. #include <openssl/engine.h>
  925. #include <openssl/conf.h>
  926. #include <openssl/dh.h>
  927. #else
  928. /* SSL loaded dynamically from DLL.
  929. * I put the prototypes here to be independent from OpenSSL source
  930. * installation. */
  931. typedef struct ssl_st SSL;
  932. typedef struct ssl_method_st SSL_METHOD;
  933. typedef struct ssl_ctx_st SSL_CTX;
  934. typedef struct x509_store_ctx_st X509_STORE_CTX;
  935. typedef struct x509_name X509_NAME;
  936. typedef struct asn1_integer ASN1_INTEGER;
  937. typedef struct evp_md EVP_MD;
  938. typedef struct x509 X509;
  939. #define SSL_CTRL_OPTIONS (32)
  940. #define SSL_CTRL_CLEAR_OPTIONS (77)
  941. #define SSL_CTRL_SET_ECDH_AUTO (94)
  942. #define SSL_VERIFY_NONE (0)
  943. #define SSL_VERIFY_PEER (1)
  944. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  945. #define SSL_VERIFY_CLIENT_ONCE (4)
  946. #define SSL_OP_ALL ((long)(0x80000BFFUL))
  947. #define SSL_OP_NO_SSLv2 (0x01000000L)
  948. #define SSL_OP_NO_SSLv3 (0x02000000L)
  949. #define SSL_OP_NO_TLSv1 (0x04000000L)
  950. #define SSL_OP_NO_TLSv1_2 (0x08000000L)
  951. #define SSL_OP_NO_TLSv1_1 (0x10000000L)
  952. #define SSL_OP_SINGLE_DH_USE (0x00100000L)
  953. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000L)
  954. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000L)
  955. #define SSL_ERROR_NONE (0)
  956. #define SSL_ERROR_SSL (1)
  957. #define SSL_ERROR_WANT_READ (2)
  958. #define SSL_ERROR_WANT_WRITE (3)
  959. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  960. #define SSL_ERROR_SYSCALL (5) /* see errno */
  961. #define SSL_ERROR_ZERO_RETURN (6)
  962. #define SSL_ERROR_WANT_CONNECT (7)
  963. #define SSL_ERROR_WANT_ACCEPT (8)
  964. struct ssl_func {
  965. const char *name; /* SSL function name */
  966. void (*ptr)(void); /* Function pointer */
  967. };
  968. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  969. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  970. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  971. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  972. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  973. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  974. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  975. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  976. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  977. #define SSLv23_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  978. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  979. #define SSL_CTX_use_PrivateKey_file \
  980. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  981. #define SSL_CTX_use_certificate_file \
  982. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  983. #define SSL_CTX_set_default_passwd_cb \
  984. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  985. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  986. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  987. #define SSL_CTX_use_certificate_chain_file \
  988. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  989. #define SSLv23_client_method (*(SSL_METHOD * (*)(void))ssl_sw[17].ptr)
  990. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  991. #define SSL_CTX_set_verify \
  992. (*(void (*)(SSL_CTX *, \
  993. int, \
  994. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19].ptr)
  995. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  996. #define SSL_CTX_load_verify_locations \
  997. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  998. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  999. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  1000. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[24].ptr)
  1001. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  1002. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[26].ptr)
  1003. #define SSL_CIPHER_get_name \
  1004. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  1005. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  1006. #define SSL_CTX_set_session_id_context \
  1007. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  1008. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  1009. #define SSL_CTX_set_cipher_list \
  1010. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  1011. #define SSL_CTX_set_options(ctx, op) \
  1012. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  1013. #define SSL_CTX_clear_options(ctx, op) \
  1014. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1015. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1016. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1017. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1018. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1019. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  1020. #define CRYPTO_set_locking_callback \
  1021. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  1022. #define CRYPTO_set_id_callback \
  1023. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  1024. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  1025. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  1026. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  1027. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  1028. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  1029. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  1030. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  1031. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  1032. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  1033. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[12].ptr)
  1034. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[13].ptr)
  1035. #define X509_NAME_oneline \
  1036. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  1037. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[15].ptr)
  1038. #define i2c_ASN1_INTEGER \
  1039. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  1040. #define EVP_get_digestbyname \
  1041. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1042. #define ASN1_digest \
  1043. (*(int (*)(int (*)(), \
  1044. const EVP_MD *, \
  1045. char *, \
  1046. unsigned char *, \
  1047. unsigned int *))crypto_sw[18].ptr)
  1048. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1049. /* set_ssl_option() function updates this array.
  1050. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1051. * of respective functions. The macros above (like SSL_connect()) are really
  1052. * just calling these functions indirectly via the pointer. */
  1053. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1054. {"SSL_accept", NULL},
  1055. {"SSL_connect", NULL},
  1056. {"SSL_read", NULL},
  1057. {"SSL_write", NULL},
  1058. {"SSL_get_error", NULL},
  1059. {"SSL_set_fd", NULL},
  1060. {"SSL_new", NULL},
  1061. {"SSL_CTX_new", NULL},
  1062. {"SSLv23_server_method", NULL},
  1063. {"SSL_library_init", NULL},
  1064. {"SSL_CTX_use_PrivateKey_file", NULL},
  1065. {"SSL_CTX_use_certificate_file", NULL},
  1066. {"SSL_CTX_set_default_passwd_cb", NULL},
  1067. {"SSL_CTX_free", NULL},
  1068. {"SSL_load_error_strings", NULL},
  1069. {"SSL_CTX_use_certificate_chain_file", NULL},
  1070. {"SSLv23_client_method", NULL},
  1071. {"SSL_pending", NULL},
  1072. {"SSL_CTX_set_verify", NULL},
  1073. {"SSL_shutdown", NULL},
  1074. {"SSL_CTX_load_verify_locations", NULL},
  1075. {"SSL_CTX_set_default_verify_paths", NULL},
  1076. {"SSL_CTX_set_verify_depth", NULL},
  1077. {"SSL_get_peer_certificate", NULL},
  1078. {"SSL_get_version", NULL},
  1079. {"SSL_get_current_cipher", NULL},
  1080. {"SSL_CIPHER_get_name", NULL},
  1081. {"SSL_CTX_check_private_key", NULL},
  1082. {"SSL_CTX_set_session_id_context", NULL},
  1083. {"SSL_CTX_ctrl", NULL},
  1084. {"SSL_CTX_set_cipher_list", NULL},
  1085. {NULL, NULL}};
  1086. /* Similar array as ssl_sw. These functions could be located in different
  1087. * lib. */
  1088. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  1089. {"CRYPTO_set_locking_callback", NULL},
  1090. {"CRYPTO_set_id_callback", NULL},
  1091. {"ERR_get_error", NULL},
  1092. {"ERR_error_string", NULL},
  1093. {"ERR_remove_state", NULL},
  1094. {"ERR_free_strings", NULL},
  1095. {"ENGINE_cleanup", NULL},
  1096. {"CONF_modules_unload", NULL},
  1097. {"CRYPTO_cleanup_all_ex_data", NULL},
  1098. {"EVP_cleanup", NULL},
  1099. {"X509_free", NULL},
  1100. {"X509_get_subject_name", NULL},
  1101. {"X509_get_issuer_name", NULL},
  1102. {"X509_NAME_oneline", NULL},
  1103. {"X509_get_serialNumber", NULL},
  1104. {"i2c_ASN1_INTEGER", NULL},
  1105. {"EVP_get_digestbyname", NULL},
  1106. {"ASN1_digest", NULL},
  1107. {"i2d_X509", NULL},
  1108. {NULL, NULL}};
  1109. #endif /* NO_SSL_DL */
  1110. #endif /* NO_SSL */
  1111. #if !defined(NO_CACHING)
  1112. static const char *month_names[] = {"Jan",
  1113. "Feb",
  1114. "Mar",
  1115. "Apr",
  1116. "May",
  1117. "Jun",
  1118. "Jul",
  1119. "Aug",
  1120. "Sep",
  1121. "Oct",
  1122. "Nov",
  1123. "Dec"};
  1124. #endif /* !NO_CACHING */
  1125. /* Unified socket address. For IPv6 support, add IPv6 address structure in the
  1126. * union u. */
  1127. union usa {
  1128. struct sockaddr sa;
  1129. struct sockaddr_in sin;
  1130. #if defined(USE_IPV6)
  1131. struct sockaddr_in6 sin6;
  1132. #endif
  1133. };
  1134. /* Describes a string (chunk of memory). */
  1135. struct vec {
  1136. const char *ptr;
  1137. size_t len;
  1138. };
  1139. struct mg_file_stat {
  1140. /* File properties filled by mg_stat: */
  1141. uint64_t size;
  1142. time_t last_modified;
  1143. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1144. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1145. * case we need a "Content-Eencoding: gzip" header */
  1146. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1147. };
  1148. struct mg_file_access {
  1149. /* File properties filled by mg_fopen: */
  1150. FILE *fp;
  1151. const char *membuf;
  1152. };
  1153. struct mg_file {
  1154. struct mg_file_stat stat;
  1155. struct mg_file_access access;
  1156. };
  1157. #define STRUCT_FILE_INITIALIZER \
  1158. { \
  1159. { \
  1160. (uint64_t)0, (time_t)0, 0, 0, 0 \
  1161. } \
  1162. , \
  1163. { \
  1164. (FILE *) NULL, (const char *)NULL \
  1165. } \
  1166. }
  1167. /* Describes listening socket, or socket which was accept()-ed by the master
  1168. * thread and queued for future handling by the worker thread. */
  1169. struct socket {
  1170. SOCKET sock; /* Listening socket */
  1171. union usa lsa; /* Local socket address */
  1172. union usa rsa; /* Remote socket address */
  1173. unsigned char is_ssl; /* Is port SSL-ed */
  1174. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1175. * port */
  1176. unsigned char in_use; /* Is valid */
  1177. };
  1178. /* NOTE(lsm): this enum shoulds be in sync with the config_options below. */
  1179. enum {
  1180. CGI_EXTENSIONS,
  1181. CGI_ENVIRONMENT,
  1182. PUT_DELETE_PASSWORDS_FILE,
  1183. CGI_INTERPRETER,
  1184. PROTECT_URI,
  1185. AUTHENTICATION_DOMAIN,
  1186. SSI_EXTENSIONS,
  1187. THROTTLE,
  1188. ACCESS_LOG_FILE,
  1189. ENABLE_DIRECTORY_LISTING,
  1190. ERROR_LOG_FILE,
  1191. GLOBAL_PASSWORDS_FILE,
  1192. INDEX_FILES,
  1193. ENABLE_KEEP_ALIVE,
  1194. ACCESS_CONTROL_LIST,
  1195. EXTRA_MIME_TYPES,
  1196. LISTENING_PORTS,
  1197. DOCUMENT_ROOT,
  1198. SSL_CERTIFICATE,
  1199. NUM_THREADS,
  1200. RUN_AS_USER,
  1201. REWRITE,
  1202. HIDE_FILES,
  1203. REQUEST_TIMEOUT,
  1204. SSL_DO_VERIFY_PEER,
  1205. SSL_CA_PATH,
  1206. SSL_CA_FILE,
  1207. SSL_VERIFY_DEPTH,
  1208. SSL_DEFAULT_VERIFY_PATHS,
  1209. SSL_CIPHER_LIST,
  1210. SSL_PROTOCOL_VERSION,
  1211. SSL_SHORT_TRUST,
  1212. #if defined(USE_WEBSOCKET)
  1213. WEBSOCKET_TIMEOUT,
  1214. #endif
  1215. DECODE_URL,
  1216. #if defined(USE_LUA)
  1217. LUA_PRELOAD_FILE,
  1218. LUA_SCRIPT_EXTENSIONS,
  1219. LUA_SERVER_PAGE_EXTENSIONS,
  1220. #endif
  1221. #if defined(USE_DUKTAPE)
  1222. DUKTAPE_SCRIPT_EXTENSIONS,
  1223. #endif
  1224. #if defined(USE_WEBSOCKET)
  1225. WEBSOCKET_ROOT,
  1226. #endif
  1227. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1228. LUA_WEBSOCKET_EXTENSIONS,
  1229. #endif
  1230. ACCESS_CONTROL_ALLOW_ORIGIN,
  1231. ERROR_PAGES,
  1232. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1233. * socket option typedef TCP_NODELAY. */
  1234. #if !defined(NO_CACHING)
  1235. STATIC_FILE_MAX_AGE,
  1236. #endif
  1237. #if defined(__linux__)
  1238. ALLOW_SENDFILE_CALL,
  1239. #endif
  1240. #if defined(_WIN32)
  1241. CASE_SENSITIVE_FILES,
  1242. #endif
  1243. NUM_OPTIONS
  1244. };
  1245. /* Config option name, config types, default value */
  1246. static struct mg_option config_options[] = {
  1247. {"cgi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1248. {"cgi_environment", CONFIG_TYPE_STRING, NULL},
  1249. {"put_delete_auth_file", CONFIG_TYPE_FILE, NULL},
  1250. {"cgi_interpreter", CONFIG_TYPE_FILE, NULL},
  1251. {"protect_uri", CONFIG_TYPE_STRING, NULL},
  1252. {"authentication_domain", CONFIG_TYPE_STRING, "mydomain.com"},
  1253. {"ssi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1254. {"throttle", CONFIG_TYPE_STRING, NULL},
  1255. {"access_log_file", CONFIG_TYPE_FILE, NULL},
  1256. {"enable_directory_listing", CONFIG_TYPE_BOOLEAN, "yes"},
  1257. {"error_log_file", CONFIG_TYPE_FILE, NULL},
  1258. {"global_auth_file", CONFIG_TYPE_FILE, NULL},
  1259. {"index_files",
  1260. CONFIG_TYPE_STRING,
  1261. #ifdef USE_LUA
  1262. "index.xhtml,index.html,index.htm,index.lp,index.lsp,index.lua,index.cgi,"
  1263. "index.shtml,index.php"},
  1264. #else
  1265. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1266. #endif
  1267. {"enable_keep_alive", CONFIG_TYPE_BOOLEAN, "no"},
  1268. {"access_control_list", CONFIG_TYPE_STRING, NULL},
  1269. {"extra_mime_types", CONFIG_TYPE_STRING, NULL},
  1270. {"listening_ports", CONFIG_TYPE_STRING, "8080"},
  1271. {"document_root", CONFIG_TYPE_DIRECTORY, NULL},
  1272. {"ssl_certificate", CONFIG_TYPE_FILE, NULL},
  1273. {"num_threads", CONFIG_TYPE_NUMBER, "50"},
  1274. {"run_as_user", CONFIG_TYPE_STRING, NULL},
  1275. {"url_rewrite_patterns", CONFIG_TYPE_STRING, NULL},
  1276. {"hide_files_patterns", CONFIG_TYPE_EXT_PATTERN, NULL},
  1277. {"request_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1278. {"ssl_verify_peer", CONFIG_TYPE_BOOLEAN, "no"},
  1279. {"ssl_ca_path", CONFIG_TYPE_DIRECTORY, NULL},
  1280. {"ssl_ca_file", CONFIG_TYPE_FILE, NULL},
  1281. {"ssl_verify_depth", CONFIG_TYPE_NUMBER, "9"},
  1282. {"ssl_default_verify_paths", CONFIG_TYPE_BOOLEAN, "yes"},
  1283. {"ssl_cipher_list", CONFIG_TYPE_STRING, NULL},
  1284. {"ssl_protocol_version", CONFIG_TYPE_NUMBER, "0"},
  1285. {"ssl_short_trust", CONFIG_TYPE_BOOLEAN, "no"},
  1286. #if defined(USE_WEBSOCKET)
  1287. {"websocket_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1288. #endif
  1289. {"decode_url", CONFIG_TYPE_BOOLEAN, "yes"},
  1290. #if defined(USE_LUA)
  1291. {"lua_preload_file", CONFIG_TYPE_FILE, NULL},
  1292. {"lua_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1293. {"lua_server_page_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1294. #endif
  1295. #if defined(USE_DUKTAPE)
  1296. /* The support for duktape is still in alpha version state.
  1297. * The name of this config option might change. */
  1298. {"duktape_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1299. #endif
  1300. #if defined(USE_WEBSOCKET)
  1301. {"websocket_root", CONFIG_TYPE_DIRECTORY, NULL},
  1302. #endif
  1303. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1304. {"lua_websocket_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1305. #endif
  1306. {"access_control_allow_origin", CONFIG_TYPE_STRING, "*"},
  1307. {"error_pages", CONFIG_TYPE_DIRECTORY, NULL},
  1308. {"tcp_nodelay", CONFIG_TYPE_NUMBER, "0"},
  1309. #if !defined(NO_CACHING)
  1310. {"static_file_max_age", CONFIG_TYPE_NUMBER, "3600"},
  1311. #endif
  1312. #if defined(__linux__)
  1313. {"allow_sendfile_call", CONFIG_TYPE_BOOLEAN, "yes"},
  1314. #endif
  1315. #if defined(_WIN32)
  1316. {"case_sensitive", CONFIG_TYPE_BOOLEAN, "no"},
  1317. #endif
  1318. {NULL, CONFIG_TYPE_UNKNOWN, NULL}};
  1319. /* Check if the config_options and the corresponding enum have compatible
  1320. * sizes. */
  1321. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1322. == (NUM_OPTIONS + 1),
  1323. "config_options and enum not sync");
  1324. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1325. struct mg_handler_info {
  1326. /* Name/Pattern of the URI. */
  1327. char *uri;
  1328. size_t uri_len;
  1329. /* handler type */
  1330. int handler_type;
  1331. /* Handler for http/https or authorization requests. */
  1332. mg_request_handler handler;
  1333. /* Handler for ws/wss (websocket) requests. */
  1334. mg_websocket_connect_handler connect_handler;
  1335. mg_websocket_ready_handler ready_handler;
  1336. mg_websocket_data_handler data_handler;
  1337. mg_websocket_close_handler close_handler;
  1338. /* accepted subprotocols for ws/wss requests. */
  1339. struct mg_websocket_subprotocols *subprotocols;
  1340. /* Handler for authorization requests */
  1341. mg_authorization_handler auth_handler;
  1342. /* User supplied argument for the handler function. */
  1343. void *cbdata;
  1344. /* next handler in a linked list */
  1345. struct mg_handler_info *next;
  1346. };
  1347. struct mg_context {
  1348. volatile int stop_flag; /* Should we stop event loop */
  1349. SSL_CTX *ssl_ctx; /* SSL context */
  1350. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1351. struct mg_callbacks callbacks; /* User-defined callback function */
  1352. void *user_data; /* User-defined data */
  1353. int context_type; /* 1 = server context,
  1354. * 2 = ws/wss client context,
  1355. */
  1356. struct socket *listening_sockets;
  1357. struct pollfd *listening_socket_fds;
  1358. unsigned int num_listening_sockets;
  1359. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  1360. #ifdef ALTERNATIVE_QUEUE
  1361. struct socket *client_socks;
  1362. void **client_wait_events;
  1363. #else
  1364. struct socket queue[MGSQLEN]; /* Accepted sockets */
  1365. volatile int sq_head; /* Head of the socket queue */
  1366. volatile int sq_tail; /* Tail of the socket queue */
  1367. pthread_cond_t sq_full; /* Signaled when socket is produced */
  1368. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  1369. #endif
  1370. pthread_t masterthreadid; /* The master thread ID */
  1371. unsigned int
  1372. cfg_worker_threads; /* The number of configured worker threads. */
  1373. pthread_t *workerthreadids; /* The worker thread IDs */
  1374. time_t start_time; /* Server start time, used for authentication */
  1375. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1376. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  1377. unsigned long nonce_count; /* Used nonces, used for authentication */
  1378. char *systemName; /* What operating system is running */
  1379. /* linked list of uri handlers */
  1380. struct mg_handler_info *handlers;
  1381. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1382. /* linked list of shared lua websockets */
  1383. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1384. #endif
  1385. #ifdef USE_TIMERS
  1386. struct ttimers *timers;
  1387. #endif
  1388. };
  1389. struct mg_connection {
  1390. struct mg_request_info request_info;
  1391. struct mg_context *ctx;
  1392. SSL *ssl; /* SSL descriptor */
  1393. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  1394. struct socket client; /* Connected client */
  1395. time_t conn_birth_time; /* Time (wall clock) when connection was
  1396. * established */
  1397. struct timespec req_time; /* Time (since system start) when the request
  1398. * was received */
  1399. int64_t num_bytes_sent; /* Total bytes sent to client */
  1400. int64_t content_len; /* Content-Length header value */
  1401. int64_t consumed_content; /* How many bytes of content have been read */
  1402. int is_chunked; /* Transfer-Encoding is chunked: 0=no, 1=yes:
  1403. * data available, 2: all data read */
  1404. size_t chunk_remainder; /* Unread data from the last chunk */
  1405. char *buf; /* Buffer for received data */
  1406. char *path_info; /* PATH_INFO part of the URL */
  1407. int must_close; /* 1 if connection must be closed */
  1408. int in_error_handler; /* 1 if in handler for user defined error
  1409. * pages */
  1410. int internal_error; /* 1 if an error occured while processing the
  1411. * request */
  1412. int buf_size; /* Buffer size */
  1413. int request_len; /* Size of the request + headers in a buffer */
  1414. int data_len; /* Total size of data in a buffer */
  1415. int status_code; /* HTTP reply status code, e.g. 200 */
  1416. int throttle; /* Throttling, bytes/sec. <= 0 means no
  1417. * throttle */
  1418. time_t last_throttle_time; /* Last time throttled data was sent */
  1419. int64_t last_throttle_bytes; /* Bytes sent this second */
  1420. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  1421. * atomic transmissions for websockets */
  1422. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1423. void *lua_websocket_state; /* Lua_State for a websocket connection */
  1424. #endif
  1425. int thread_index; /* Thread index within ctx */
  1426. };
  1427. static pthread_key_t sTlsKey; /* Thread local storage index */
  1428. static int sTlsInit = 0;
  1429. static int thread_idx_max = 0;
  1430. struct mg_workerTLS {
  1431. int is_master;
  1432. unsigned long thread_idx;
  1433. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1434. HANDLE pthread_cond_helper_mutex;
  1435. struct mg_workerTLS *next_waiting_thread;
  1436. #endif
  1437. };
  1438. /* Directory entry */
  1439. struct de {
  1440. struct mg_connection *conn;
  1441. char *file_name;
  1442. struct mg_file_stat file;
  1443. };
  1444. #if defined(USE_WEBSOCKET)
  1445. static int is_websocket_protocol(const struct mg_connection *conn);
  1446. #else
  1447. #define is_websocket_protocol(conn) (0)
  1448. #endif
  1449. static int
  1450. mg_atomic_inc(volatile int *addr)
  1451. {
  1452. int ret;
  1453. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1454. /* Depending on the SDK, this function uses either
  1455. * (volatile unsigned int *) or (volatile LONG *),
  1456. * so whatever you use, the other SDK is likely to raise a warning. */
  1457. ret = InterlockedIncrement((volatile long *)addr);
  1458. #elif defined(__GNUC__) \
  1459. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  1460. ret = __sync_add_and_fetch(addr, 1);
  1461. #else
  1462. ret = (++(*addr));
  1463. #endif
  1464. return ret;
  1465. }
  1466. static int
  1467. mg_atomic_dec(volatile int *addr)
  1468. {
  1469. int ret;
  1470. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1471. /* Depending on the SDK, this function uses either
  1472. * (volatile unsigned int *) or (volatile LONG *),
  1473. * so whatever you use, the other SDK is likely to raise a warning. */
  1474. ret = InterlockedDecrement((volatile long *)addr);
  1475. #elif defined(__GNUC__) \
  1476. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  1477. ret = __sync_sub_and_fetch(addr, 1);
  1478. #else
  1479. ret = (--(*addr));
  1480. #endif
  1481. return ret;
  1482. }
  1483. #if !defined(NO_THREAD_NAME)
  1484. #if defined(_WIN32) && defined(_MSC_VER)
  1485. /* Set the thread name for debugging purposes in Visual Studio
  1486. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  1487. */
  1488. #pragma pack(push, 8)
  1489. typedef struct tagTHREADNAME_INFO {
  1490. DWORD dwType; /* Must be 0x1000. */
  1491. LPCSTR szName; /* Pointer to name (in user addr space). */
  1492. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  1493. DWORD dwFlags; /* Reserved for future use, must be zero. */
  1494. } THREADNAME_INFO;
  1495. #pragma pack(pop)
  1496. #elif defined(__linux__)
  1497. #include <sys/prctl.h>
  1498. #include <sys/sendfile.h>
  1499. #include <sys/eventfd.h>
  1500. #if defined(ALTERNATIVE_QUEUE)
  1501. static void *
  1502. event_create(void)
  1503. {
  1504. int ret = eventfd(0, EFD_CLOEXEC);
  1505. if (ret == -1) {
  1506. /* Linux uses -1 on error, Windows NULL. */
  1507. /* However, Linux does not return 0 on success either. */
  1508. return 0;
  1509. }
  1510. return (void *)ret;
  1511. }
  1512. static int
  1513. event_wait(void *eventhdl)
  1514. {
  1515. uint64_t u;
  1516. int s = (int)read((int)eventhdl, &u, sizeof(u));
  1517. if (s != sizeof(uint64_t)) {
  1518. /* error */
  1519. return 0;
  1520. }
  1521. (void)u; /* the value is not required */
  1522. return 1;
  1523. }
  1524. static int
  1525. event_signal(void *eventhdl)
  1526. {
  1527. uint64_t u = 1;
  1528. int s = (int)write((int)eventhdl, &u, sizeof(u));
  1529. if (s != sizeof(uint64_t)) {
  1530. /* error */
  1531. return 0;
  1532. }
  1533. return 1;
  1534. }
  1535. static void
  1536. event_destroy(void *eventhdl)
  1537. {
  1538. close((int)eventhdl);
  1539. }
  1540. #endif
  1541. #endif
  1542. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  1543. struct posix_event {
  1544. pthread_mutex_t mutex;
  1545. pthread_cond_t cond;
  1546. };
  1547. static void *
  1548. event_create(void)
  1549. {
  1550. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  1551. if (ret == 0) {
  1552. /* out of memory */
  1553. return 0;
  1554. }
  1555. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  1556. /* pthread mutex not available */
  1557. mg_free(ret);
  1558. return 0;
  1559. }
  1560. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  1561. /* pthread cond not available */
  1562. pthread_mutex_destroy(&(ret->mutex));
  1563. mg_free(ret);
  1564. return 0;
  1565. }
  1566. return (void *)ret;
  1567. }
  1568. static int
  1569. event_wait(void *eventhdl)
  1570. {
  1571. struct posix_event *ev = (struct posix_event *)eventhdl;
  1572. pthread_mutex_lock(&(ev->mutex));
  1573. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  1574. pthread_mutex_unlock(&(ev->mutex));
  1575. return 1;
  1576. }
  1577. static int
  1578. event_signal(void *eventhdl)
  1579. {
  1580. struct posix_event *ev = (struct posix_event *)eventhdl;
  1581. pthread_mutex_lock(&(ev->mutex));
  1582. pthread_cond_signal(&(ev->cond));
  1583. pthread_mutex_unlock(&(ev->mutex));
  1584. return 1;
  1585. }
  1586. static void
  1587. event_destroy(void *eventhdl)
  1588. {
  1589. struct posix_event *ev = (struct posix_event *)eventhdl;
  1590. pthread_cond_destroy(&(ev->cond));
  1591. pthread_mutex_destroy(&(ev->mutex));
  1592. mg_free(ev);
  1593. }
  1594. #endif
  1595. static void
  1596. mg_set_thread_name(const char *name)
  1597. {
  1598. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  1599. mg_snprintf(
  1600. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  1601. #if defined(_WIN32)
  1602. #if defined(_MSC_VER)
  1603. /* Windows and Visual Studio Compiler */
  1604. __try
  1605. {
  1606. THREADNAME_INFO info;
  1607. info.dwType = 0x1000;
  1608. info.szName = threadName;
  1609. info.dwThreadID = ~0U;
  1610. info.dwFlags = 0;
  1611. RaiseException(0x406D1388,
  1612. 0,
  1613. sizeof(info) / sizeof(ULONG_PTR),
  1614. (ULONG_PTR *)&info);
  1615. }
  1616. __except(EXCEPTION_EXECUTE_HANDLER)
  1617. {
  1618. }
  1619. #elif defined(__MINGW32__)
  1620. /* No option known to set thread name for MinGW */
  1621. #endif
  1622. #elif defined(__GLIBC__) \
  1623. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  1624. /* pthread_setname_np first appeared in glibc in version 2.12*/
  1625. (void)pthread_setname_np(pthread_self(), threadName);
  1626. #elif defined(__linux__)
  1627. /* on linux we can use the old prctl function */
  1628. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  1629. #endif
  1630. }
  1631. #else /* !defined(NO_THREAD_NAME) */
  1632. void
  1633. mg_set_thread_name(const char *threadName)
  1634. {
  1635. }
  1636. #endif
  1637. #if defined(MG_LEGACY_INTERFACE)
  1638. const char **
  1639. mg_get_valid_option_names(void)
  1640. {
  1641. /* This function is deprecated. Use mg_get_valid_options instead. */
  1642. static const char *
  1643. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  1644. int i;
  1645. for (i = 0; config_options[i].name != NULL; i++) {
  1646. data[i * 2] = config_options[i].name;
  1647. data[i * 2 + 1] = config_options[i].default_value;
  1648. }
  1649. return data;
  1650. }
  1651. #endif
  1652. const struct mg_option *
  1653. mg_get_valid_options(void)
  1654. {
  1655. return config_options;
  1656. }
  1657. /* If a file is in memory, set all "stat" members and the membuf pointer of
  1658. * output filep and return 1, otherwise return 0 and don't modify anything. */
  1659. static int
  1660. open_file_in_memory(const struct mg_connection *conn,
  1661. const char *path,
  1662. struct mg_file *filep)
  1663. {
  1664. size_t size = 0;
  1665. const char *buf = NULL;
  1666. if (!conn) {
  1667. return 0;
  1668. }
  1669. if (conn->ctx->callbacks.open_file) {
  1670. buf = conn->ctx->callbacks.open_file(conn, path, &size);
  1671. if (buf != NULL) {
  1672. if (filep == NULL) {
  1673. /* This is a file in memory, but we cannot store the properties
  1674. * now.
  1675. * Called from "is_file_in_memory" function. */
  1676. return 1;
  1677. }
  1678. /* NOTE: override filep->size only on success. Otherwise, it might
  1679. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  1680. filep->access.membuf = buf;
  1681. filep->access.fp = NULL;
  1682. /* Size was set by the callback */
  1683. filep->stat.size = size;
  1684. /* Assume the data may change during runtime by setting
  1685. * last_modified = now */
  1686. filep->stat.last_modified = time(NULL);
  1687. filep->stat.is_directory = 0;
  1688. filep->stat.is_gzipped = 0;
  1689. }
  1690. }
  1691. return (buf != NULL);
  1692. }
  1693. static int
  1694. is_file_in_memory(const struct mg_connection *conn, const char *path)
  1695. {
  1696. return open_file_in_memory(conn, path, NULL);
  1697. }
  1698. static int
  1699. is_file_opened(const struct mg_file_access *fileacc)
  1700. {
  1701. if (!fileacc) {
  1702. return 0;
  1703. }
  1704. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  1705. }
  1706. static int mg_stat(const struct mg_connection *conn,
  1707. const char *path,
  1708. struct mg_file_stat *filep);
  1709. #define MG_FOPEN_MODE_READ (1)
  1710. #define MG_FOPEN_MODE_WRITE (2)
  1711. #define MG_FOPEN_MODE_APPEND (4)
  1712. /* mg_fopen will open a file either in memory or on the disk.
  1713. * The input parameter path is a string in UTF-8 encoding.
  1714. * The input parameter mode is MG_FOPEN_MODE_*
  1715. * Either fp or membuf will be set in the output struct file.
  1716. * The function returns 1 on success, 0 on error. */
  1717. static int
  1718. mg_fopen(const struct mg_connection *conn,
  1719. const char *path,
  1720. int mode,
  1721. struct mg_file *filep)
  1722. {
  1723. int found;
  1724. if (!filep) {
  1725. return 0;
  1726. }
  1727. filep->access.fp = NULL;
  1728. filep->access.membuf = NULL;
  1729. if (!is_file_in_memory(conn, path)) {
  1730. /* filep is initialized in mg_stat: all fields with memset to,
  1731. * some fields like size and modification date with values */
  1732. found = mg_stat(conn, path, &(filep->stat));
  1733. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  1734. /* file does not exist and will not be created */
  1735. return 0;
  1736. }
  1737. #ifdef _WIN32
  1738. {
  1739. wchar_t wbuf[PATH_MAX];
  1740. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  1741. switch (mode) {
  1742. case MG_FOPEN_MODE_READ:
  1743. filep->access.fp = _wfopen(wbuf, L"rb");
  1744. break;
  1745. case MG_FOPEN_MODE_WRITE:
  1746. filep->access.fp = _wfopen(wbuf, L"wb");
  1747. break;
  1748. case MG_FOPEN_MODE_APPEND:
  1749. filep->access.fp = _wfopen(wbuf, L"ab");
  1750. break;
  1751. }
  1752. }
  1753. #else
  1754. /* Linux et al already use unicode. No need to convert. */
  1755. switch (mode) {
  1756. case MG_FOPEN_MODE_READ:
  1757. filep->access.fp = fopen(path, "r");
  1758. break;
  1759. case MG_FOPEN_MODE_WRITE:
  1760. filep->access.fp = fopen(path, "w");
  1761. break;
  1762. case MG_FOPEN_MODE_APPEND:
  1763. filep->access.fp = fopen(path, "a");
  1764. break;
  1765. }
  1766. #endif
  1767. if (!found) {
  1768. /* File did not exist before fopen was called.
  1769. * Maybe it has been created now. Get stat info
  1770. * like creation time now. */
  1771. found = mg_stat(conn, path, &(filep->stat));
  1772. (void)found;
  1773. }
  1774. /* file is on disk */
  1775. return (filep->access.fp != NULL);
  1776. } else {
  1777. if (open_file_in_memory(conn, path, filep)) {
  1778. /* file is in memory */
  1779. return (filep->access.membuf != NULL);
  1780. }
  1781. }
  1782. /* Open failed */
  1783. return 0;
  1784. }
  1785. /* return 0 on success, just like fclose */
  1786. static int
  1787. mg_fclose(struct mg_file_access *fileacc)
  1788. {
  1789. int ret = -1;
  1790. if (fileacc != NULL) {
  1791. if (fileacc->fp != NULL) {
  1792. ret = fclose(fileacc->fp);
  1793. } else if (fileacc->membuf != NULL) {
  1794. ret = 0;
  1795. }
  1796. /* reset all members of fileacc */
  1797. memset(fileacc, 0, sizeof(*fileacc));
  1798. }
  1799. return ret;
  1800. }
  1801. static void
  1802. mg_strlcpy(register char *dst, register const char *src, size_t n)
  1803. {
  1804. for (; *src != '\0' && n > 1; n--) {
  1805. *dst++ = *src++;
  1806. }
  1807. *dst = '\0';
  1808. }
  1809. static int
  1810. lowercase(const char *s)
  1811. {
  1812. return tolower(*(const unsigned char *)s);
  1813. }
  1814. int
  1815. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  1816. {
  1817. int diff = 0;
  1818. if (len > 0) {
  1819. do {
  1820. diff = lowercase(s1++) - lowercase(s2++);
  1821. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  1822. }
  1823. return diff;
  1824. }
  1825. int
  1826. mg_strcasecmp(const char *s1, const char *s2)
  1827. {
  1828. int diff;
  1829. do {
  1830. diff = lowercase(s1++) - lowercase(s2++);
  1831. } while (diff == 0 && s1[-1] != '\0');
  1832. return diff;
  1833. }
  1834. static char *
  1835. mg_strndup(const char *ptr, size_t len)
  1836. {
  1837. char *p;
  1838. if ((p = (char *)mg_malloc(len + 1)) != NULL) {
  1839. mg_strlcpy(p, ptr, len + 1);
  1840. }
  1841. return p;
  1842. }
  1843. static char *
  1844. mg_strdup(const char *str)
  1845. {
  1846. return mg_strndup(str, strlen(str));
  1847. }
  1848. static const char *
  1849. mg_strcasestr(const char *big_str, const char *small_str)
  1850. {
  1851. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  1852. if (big_len >= small_len) {
  1853. for (i = 0; i <= (big_len - small_len); i++) {
  1854. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  1855. return big_str + i;
  1856. }
  1857. }
  1858. }
  1859. return NULL;
  1860. }
  1861. /* Return null terminated string of given maximum length.
  1862. * Report errors if length is exceeded. */
  1863. static void
  1864. mg_vsnprintf(const struct mg_connection *conn,
  1865. int *truncated,
  1866. char *buf,
  1867. size_t buflen,
  1868. const char *fmt,
  1869. va_list ap)
  1870. {
  1871. int n, ok;
  1872. if (buflen == 0) {
  1873. return;
  1874. }
  1875. #ifdef __clang__
  1876. #pragma clang diagnostic push
  1877. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  1878. /* Using fmt as a non-literal is intended here, since it is mostly called
  1879. * indirectly by mg_snprintf */
  1880. #endif
  1881. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  1882. ok = (n >= 0) && ((size_t)n < buflen);
  1883. #ifdef __clang__
  1884. #pragma clang diagnostic pop
  1885. #endif
  1886. if (ok) {
  1887. if (truncated) {
  1888. *truncated = 0;
  1889. }
  1890. } else {
  1891. if (truncated) {
  1892. *truncated = 1;
  1893. }
  1894. mg_cry(conn,
  1895. "truncating vsnprintf buffer: [%.*s]",
  1896. (int)((buflen > 200) ? 200 : (buflen - 1)),
  1897. buf);
  1898. n = (int)buflen - 1;
  1899. }
  1900. buf[n] = '\0';
  1901. }
  1902. static void
  1903. mg_snprintf(const struct mg_connection *conn,
  1904. int *truncated,
  1905. char *buf,
  1906. size_t buflen,
  1907. const char *fmt,
  1908. ...)
  1909. {
  1910. va_list ap;
  1911. va_start(ap, fmt);
  1912. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  1913. va_end(ap);
  1914. }
  1915. static int
  1916. get_option_index(const char *name)
  1917. {
  1918. int i;
  1919. for (i = 0; config_options[i].name != NULL; i++) {
  1920. if (strcmp(config_options[i].name, name) == 0) {
  1921. return i;
  1922. }
  1923. }
  1924. return -1;
  1925. }
  1926. const char *
  1927. mg_get_option(const struct mg_context *ctx, const char *name)
  1928. {
  1929. int i;
  1930. if ((i = get_option_index(name)) == -1) {
  1931. return NULL;
  1932. } else if (!ctx || ctx->config[i] == NULL) {
  1933. return "";
  1934. } else {
  1935. return ctx->config[i];
  1936. }
  1937. }
  1938. struct mg_context *
  1939. mg_get_context(const struct mg_connection *conn)
  1940. {
  1941. return (conn == NULL) ? (struct mg_context *)NULL : (conn->ctx);
  1942. }
  1943. void *
  1944. mg_get_user_data(const struct mg_context *ctx)
  1945. {
  1946. return (ctx == NULL) ? NULL : ctx->user_data;
  1947. }
  1948. void
  1949. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  1950. {
  1951. if (conn != NULL) {
  1952. conn->request_info.conn_data = data;
  1953. }
  1954. }
  1955. void *
  1956. mg_get_user_connection_data(const struct mg_connection *conn)
  1957. {
  1958. if (conn != NULL) {
  1959. return conn->request_info.conn_data;
  1960. }
  1961. return NULL;
  1962. }
  1963. size_t
  1964. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  1965. {
  1966. size_t i;
  1967. if (!ctx) {
  1968. return 0;
  1969. }
  1970. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  1971. ssl[i] = ctx->listening_sockets[i].is_ssl;
  1972. ports[i] =
  1973. #if defined(USE_IPV6)
  1974. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  1975. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  1976. :
  1977. #endif
  1978. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  1979. }
  1980. return i;
  1981. }
  1982. int
  1983. mg_get_server_ports(const struct mg_context *ctx,
  1984. int size,
  1985. struct mg_server_ports *ports)
  1986. {
  1987. int i, cnt = 0;
  1988. if (size <= 0) {
  1989. return -1;
  1990. }
  1991. memset(ports, 0, sizeof(*ports) * (size_t)size);
  1992. if (!ctx) {
  1993. return -1;
  1994. }
  1995. if (!ctx->listening_sockets) {
  1996. return -1;
  1997. }
  1998. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  1999. ports[cnt].port =
  2000. #if defined(USE_IPV6)
  2001. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2002. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2003. :
  2004. #endif
  2005. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2006. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  2007. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  2008. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  2009. /* IPv4 */
  2010. ports[cnt].protocol = 1;
  2011. cnt++;
  2012. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  2013. /* IPv6 */
  2014. ports[cnt].protocol = 3;
  2015. cnt++;
  2016. }
  2017. }
  2018. return cnt;
  2019. }
  2020. static void
  2021. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  2022. {
  2023. buf[0] = '\0';
  2024. if (!usa) {
  2025. return;
  2026. }
  2027. if (usa->sa.sa_family == AF_INET) {
  2028. getnameinfo(&usa->sa,
  2029. sizeof(usa->sin),
  2030. buf,
  2031. (unsigned)len,
  2032. NULL,
  2033. 0,
  2034. NI_NUMERICHOST);
  2035. }
  2036. #if defined(USE_IPV6)
  2037. else if (usa->sa.sa_family == AF_INET6) {
  2038. getnameinfo(&usa->sa,
  2039. sizeof(usa->sin6),
  2040. buf,
  2041. (unsigned)len,
  2042. NULL,
  2043. 0,
  2044. NI_NUMERICHOST);
  2045. }
  2046. #endif
  2047. }
  2048. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  2049. * included in all responses other than 100, 101, 5xx. */
  2050. static void
  2051. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  2052. {
  2053. struct tm *tm;
  2054. tm = ((t != NULL) ? gmtime(t) : NULL);
  2055. if (tm != NULL) {
  2056. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  2057. } else {
  2058. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  2059. buf[buf_len - 1] = '\0';
  2060. }
  2061. }
  2062. /* difftime for struct timespec. Return value is in seconds. */
  2063. static double
  2064. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  2065. {
  2066. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  2067. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  2068. }
  2069. /* Print error message to the opened error log stream. */
  2070. void
  2071. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  2072. {
  2073. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  2074. va_list ap;
  2075. struct mg_file fi;
  2076. time_t timestamp;
  2077. va_start(ap, fmt);
  2078. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  2079. va_end(ap);
  2080. buf[sizeof(buf) - 1] = 0;
  2081. if (!conn) {
  2082. puts(buf);
  2083. return;
  2084. }
  2085. /* Do not lock when getting the callback value, here and below.
  2086. * I suppose this is fine, since function cannot disappear in the
  2087. * same way string option can. */
  2088. if ((conn->ctx->callbacks.log_message == NULL)
  2089. || (conn->ctx->callbacks.log_message(conn, buf) == 0)) {
  2090. if (conn->ctx->config[ERROR_LOG_FILE] != NULL) {
  2091. if (mg_fopen(conn,
  2092. conn->ctx->config[ERROR_LOG_FILE],
  2093. MG_FOPEN_MODE_APPEND,
  2094. &fi) == 0) {
  2095. fi.access.fp = NULL;
  2096. }
  2097. } else {
  2098. fi.access.fp = NULL;
  2099. }
  2100. if (fi.access.fp != NULL) {
  2101. flockfile(fi.access.fp);
  2102. timestamp = time(NULL);
  2103. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  2104. fprintf(fi.access.fp,
  2105. "[%010lu] [error] [client %s] ",
  2106. (unsigned long)timestamp,
  2107. src_addr);
  2108. if (conn->request_info.request_method != NULL) {
  2109. fprintf(fi.access.fp,
  2110. "%s %s: ",
  2111. conn->request_info.request_method,
  2112. conn->request_info.request_uri);
  2113. }
  2114. fprintf(fi.access.fp, "%s", buf);
  2115. fputc('\n', fi.access.fp);
  2116. fflush(fi.access.fp);
  2117. funlockfile(fi.access.fp);
  2118. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  2119. * mg_cry here anyway ;-) */
  2120. }
  2121. }
  2122. }
  2123. /* Return fake connection structure. Used for logging, if connection
  2124. * is not applicable at the moment of logging. */
  2125. static struct mg_connection *
  2126. fc(struct mg_context *ctx)
  2127. {
  2128. static struct mg_connection fake_connection;
  2129. fake_connection.ctx = ctx;
  2130. return &fake_connection;
  2131. }
  2132. const char *
  2133. mg_version(void)
  2134. {
  2135. return CIVETWEB_VERSION;
  2136. }
  2137. const struct mg_request_info *
  2138. mg_get_request_info(const struct mg_connection *conn)
  2139. {
  2140. if (!conn) {
  2141. return NULL;
  2142. }
  2143. return &conn->request_info;
  2144. }
  2145. /* Skip the characters until one of the delimiters characters found.
  2146. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  2147. * Advance pointer to buffer to the next word. Return found 0-terminated word.
  2148. * Delimiters can be quoted with quotechar. */
  2149. static char *
  2150. skip_quoted(char **buf,
  2151. const char *delimiters,
  2152. const char *whitespace,
  2153. char quotechar)
  2154. {
  2155. char *p, *begin_word, *end_word, *end_whitespace;
  2156. begin_word = *buf;
  2157. end_word = begin_word + strcspn(begin_word, delimiters);
  2158. /* Check for quotechar */
  2159. if (end_word > begin_word) {
  2160. p = end_word - 1;
  2161. while (*p == quotechar) {
  2162. /* While the delimiter is quoted, look for the next delimiter. */
  2163. /* This happens, e.g., in calls from parse_auth_header,
  2164. * if the user name contains a " character. */
  2165. /* If there is anything beyond end_word, copy it. */
  2166. if (*end_word != '\0') {
  2167. size_t end_off = strcspn(end_word + 1, delimiters);
  2168. memmove(p, end_word, end_off + 1);
  2169. p += end_off; /* p must correspond to end_word - 1 */
  2170. end_word += end_off + 1;
  2171. } else {
  2172. *p = '\0';
  2173. break;
  2174. }
  2175. }
  2176. for (p++; p < end_word; p++) {
  2177. *p = '\0';
  2178. }
  2179. }
  2180. if (*end_word == '\0') {
  2181. *buf = end_word;
  2182. } else {
  2183. #if defined(__GNUC__) || defined(__MINGW32__)
  2184. /* Disable spurious conversion warning for GCC */
  2185. #pragma GCC diagnostic push
  2186. #pragma GCC diagnostic ignored "-Wsign-conversion"
  2187. #endif
  2188. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  2189. #if defined(__GNUC__) || defined(__MINGW32__)
  2190. #pragma GCC diagnostic pop
  2191. #endif
  2192. for (p = end_word; p < end_whitespace; p++) {
  2193. *p = '\0';
  2194. }
  2195. *buf = end_whitespace;
  2196. }
  2197. return begin_word;
  2198. }
  2199. /* Simplified version of skip_quoted without quote char
  2200. * and whitespace == delimiters */
  2201. static char *
  2202. skip(char **buf, const char *delimiters)
  2203. {
  2204. return skip_quoted(buf, delimiters, delimiters, 0);
  2205. }
  2206. /* Return HTTP header value, or NULL if not found. */
  2207. static const char *
  2208. get_header(const struct mg_request_info *ri, const char *name)
  2209. {
  2210. int i;
  2211. if (ri) {
  2212. for (i = 0; i < ri->num_headers; i++) {
  2213. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  2214. return ri->http_headers[i].value;
  2215. }
  2216. }
  2217. }
  2218. return NULL;
  2219. }
  2220. const char *
  2221. mg_get_header(const struct mg_connection *conn, const char *name)
  2222. {
  2223. if (!conn) {
  2224. return NULL;
  2225. }
  2226. return get_header(&conn->request_info, name);
  2227. }
  2228. /* A helper function for traversing a comma separated list of values.
  2229. * It returns a list pointer shifted to the next value, or NULL if the end
  2230. * of the list found.
  2231. * Value is stored in val vector. If value has form "x=y", then eq_val
  2232. * vector is initialized to point to the "y" part, and val vector length
  2233. * is adjusted to point only to "x". */
  2234. static const char *
  2235. next_option(const char *list, struct vec *val, struct vec *eq_val)
  2236. {
  2237. int end;
  2238. reparse:
  2239. if (val == NULL || list == NULL || *list == '\0') {
  2240. /* End of the list */
  2241. list = NULL;
  2242. } else {
  2243. /* Skip over leading LWS */
  2244. while (*list == ' ' || *list == '\t')
  2245. list++;
  2246. val->ptr = list;
  2247. if ((list = strchr(val->ptr, ',')) != NULL) {
  2248. /* Comma found. Store length and shift the list ptr */
  2249. val->len = ((size_t)(list - val->ptr));
  2250. list++;
  2251. } else {
  2252. /* This value is the last one */
  2253. list = val->ptr + strlen(val->ptr);
  2254. val->len = ((size_t)(list - val->ptr));
  2255. }
  2256. /* Adjust length for trailing LWS */
  2257. end = (int)val->len - 1;
  2258. while (end >= 0 && (val->ptr[end] == ' ' || val->ptr[end] == '\t'))
  2259. end--;
  2260. val->len = (size_t)(end + 1);
  2261. if (val->len == 0) {
  2262. /* Ignore any empty entries. */
  2263. goto reparse;
  2264. }
  2265. if (eq_val != NULL) {
  2266. /* Value has form "x=y", adjust pointers and lengths
  2267. * so that val points to "x", and eq_val points to "y". */
  2268. eq_val->len = 0;
  2269. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  2270. if (eq_val->ptr != NULL) {
  2271. eq_val->ptr++; /* Skip over '=' character */
  2272. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  2273. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  2274. }
  2275. }
  2276. }
  2277. return list;
  2278. }
  2279. /* A helper function for checking if a comma separated list of values contains
  2280. * the given option (case insensitvely).
  2281. * 'header' can be NULL, in which case false is returned. */
  2282. static int
  2283. header_has_option(const char *header, const char *option)
  2284. {
  2285. struct vec opt_vec;
  2286. struct vec eq_vec;
  2287. assert(option != NULL);
  2288. assert(option[0] != '\0');
  2289. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  2290. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  2291. return 1;
  2292. }
  2293. return 0;
  2294. }
  2295. /* Perform case-insensitive match of string against pattern */
  2296. static int
  2297. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  2298. {
  2299. const char *or_str;
  2300. size_t i;
  2301. int j, len, res;
  2302. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  2303. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  2304. return (res > 0) ? res : match_prefix(or_str + 1,
  2305. (size_t)((pattern + pattern_len)
  2306. - (or_str + 1)),
  2307. str);
  2308. }
  2309. for (i = 0, j = 0; i < pattern_len; i++, j++) {
  2310. if (pattern[i] == '?' && str[j] != '\0') {
  2311. continue;
  2312. } else if (pattern[i] == '$') {
  2313. return (str[j] == '\0') ? j : -1;
  2314. } else if (pattern[i] == '*') {
  2315. i++;
  2316. if (pattern[i] == '*') {
  2317. i++;
  2318. len = (int)strlen(str + j);
  2319. } else {
  2320. len = (int)strcspn(str + j, "/");
  2321. }
  2322. if (i == pattern_len) {
  2323. return j + len;
  2324. }
  2325. do {
  2326. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  2327. } while (res == -1 && len-- > 0);
  2328. return (res == -1) ? -1 : j + res + len;
  2329. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  2330. return -1;
  2331. }
  2332. }
  2333. return j;
  2334. }
  2335. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  2336. * This function must tolerate situations when connection info is not
  2337. * set up, for example if request parsing failed. */
  2338. static int
  2339. should_keep_alive(const struct mg_connection *conn)
  2340. {
  2341. if (conn != NULL) {
  2342. const char *http_version = conn->request_info.http_version;
  2343. const char *header = mg_get_header(conn, "Connection");
  2344. if (conn->must_close || conn->internal_error || conn->status_code == 401
  2345. || mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0
  2346. || (header != NULL && !header_has_option(header, "keep-alive"))
  2347. || (header == NULL && http_version
  2348. && 0 != strcmp(http_version, "1.1"))) {
  2349. return 0;
  2350. }
  2351. return 1;
  2352. }
  2353. return 0;
  2354. }
  2355. static int
  2356. should_decode_url(const struct mg_connection *conn)
  2357. {
  2358. if (!conn || !conn->ctx) {
  2359. return 0;
  2360. }
  2361. return (mg_strcasecmp(conn->ctx->config[DECODE_URL], "yes") == 0);
  2362. }
  2363. static const char *
  2364. suggest_connection_header(const struct mg_connection *conn)
  2365. {
  2366. return should_keep_alive(conn) ? "keep-alive" : "close";
  2367. }
  2368. static int
  2369. send_no_cache_header(struct mg_connection *conn)
  2370. {
  2371. /* Send all current and obsolete cache opt-out directives. */
  2372. return mg_printf(conn,
  2373. "Cache-Control: no-cache, no-store, "
  2374. "must-revalidate, private, max-age=0\r\n"
  2375. "Pragma: no-cache\r\n"
  2376. "Expires: 0\r\n");
  2377. }
  2378. static int
  2379. send_static_cache_header(struct mg_connection *conn)
  2380. {
  2381. #if !defined(NO_CACHING)
  2382. /* Read the server config to check how long a file may be cached.
  2383. * The configuration is in seconds. */
  2384. int max_age = atoi(conn->ctx->config[STATIC_FILE_MAX_AGE]);
  2385. if (max_age <= 0) {
  2386. /* 0 means "do not cache". All values <0 are reserved
  2387. * and may be used differently in the future. */
  2388. /* If a file should not be cached, do not only send
  2389. * max-age=0, but also pragmas and Expires headers. */
  2390. return send_no_cache_header(conn);
  2391. }
  2392. /* Use "Cache-Control: max-age" instead of "Expires" header.
  2393. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  2394. /* See also https://www.mnot.net/cache_docs/ */
  2395. /* According to RFC 2616, Section 14.21, caching times should not exceed
  2396. * one year. A year with 365 days corresponds to 31536000 seconds, a leap
  2397. * year to 31622400 seconds. For the moment, we just send whatever has
  2398. * been configured, still the behavior for >1 year should be considered
  2399. * as undefined. */
  2400. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  2401. #else /* NO_CACHING */
  2402. return send_no_cache_header(conn);
  2403. #endif /* !NO_CACHING */
  2404. }
  2405. static void handle_file_based_request(struct mg_connection *conn,
  2406. const char *path,
  2407. struct mg_file *filep);
  2408. const char *
  2409. mg_get_response_code_text(struct mg_connection *conn, int response_code)
  2410. {
  2411. /* See IANA HTTP status code assignment:
  2412. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  2413. */
  2414. switch (response_code) {
  2415. /* RFC2616 Section 10.1 - Informational 1xx */
  2416. case 100:
  2417. return "Continue"; /* RFC2616 Section 10.1.1 */
  2418. case 101:
  2419. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  2420. case 102:
  2421. return "Processing"; /* RFC2518 Section 10.1 */
  2422. /* RFC2616 Section 10.2 - Successful 2xx */
  2423. case 200:
  2424. return "OK"; /* RFC2616 Section 10.2.1 */
  2425. case 201:
  2426. return "Created"; /* RFC2616 Section 10.2.2 */
  2427. case 202:
  2428. return "Accepted"; /* RFC2616 Section 10.2.3 */
  2429. case 203:
  2430. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  2431. case 204:
  2432. return "No Content"; /* RFC2616 Section 10.2.5 */
  2433. case 205:
  2434. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  2435. case 206:
  2436. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  2437. case 207:
  2438. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1 */
  2439. case 208:
  2440. return "Already Reported"; /* RFC5842 Section 7.1 */
  2441. case 226:
  2442. return "IM used"; /* RFC3229 Section 10.4.1 */
  2443. /* RFC2616 Section 10.3 - Redirection 3xx */
  2444. case 300:
  2445. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  2446. case 301:
  2447. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  2448. case 302:
  2449. return "Found"; /* RFC2616 Section 10.3.3 */
  2450. case 303:
  2451. return "See Other"; /* RFC2616 Section 10.3.4 */
  2452. case 304:
  2453. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  2454. case 305:
  2455. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  2456. case 307:
  2457. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  2458. case 308:
  2459. return "Permanent Redirect"; /* RFC7238 Section 3 */
  2460. /* RFC2616 Section 10.4 - Client Error 4xx */
  2461. case 400:
  2462. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  2463. case 401:
  2464. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  2465. case 402:
  2466. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  2467. case 403:
  2468. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  2469. case 404:
  2470. return "Not Found"; /* RFC2616 Section 10.4.5 */
  2471. case 405:
  2472. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  2473. case 406:
  2474. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  2475. case 407:
  2476. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  2477. case 408:
  2478. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  2479. case 409:
  2480. return "Conflict"; /* RFC2616 Section 10.4.10 */
  2481. case 410:
  2482. return "Gone"; /* RFC2616 Section 10.4.11 */
  2483. case 411:
  2484. return "Length Required"; /* RFC2616 Section 10.4.12 */
  2485. case 412:
  2486. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  2487. case 413:
  2488. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  2489. case 414:
  2490. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  2491. case 415:
  2492. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  2493. case 416:
  2494. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17 */
  2495. case 417:
  2496. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  2497. case 421:
  2498. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  2499. case 422:
  2500. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  2501. * Section 11.2 */
  2502. case 423:
  2503. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  2504. case 424:
  2505. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  2506. * Section 11.4 */
  2507. case 426:
  2508. return "Upgrade Required"; /* RFC 2817 Section 4 */
  2509. case 428:
  2510. return "Precondition Required"; /* RFC 6585, Section 3 */
  2511. case 429:
  2512. return "Too Many Requests"; /* RFC 6585, Section 4 */
  2513. case 431:
  2514. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  2515. case 451:
  2516. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  2517. * Section 3 */
  2518. /* RFC2616 Section 10.5 - Server Error 5xx */
  2519. case 500:
  2520. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  2521. case 501:
  2522. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  2523. case 502:
  2524. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  2525. case 503:
  2526. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  2527. case 504:
  2528. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  2529. case 505:
  2530. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  2531. case 506:
  2532. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  2533. case 507:
  2534. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  2535. * Section 11.5 */
  2536. case 508:
  2537. return "Loop Detected"; /* RFC5842 Section 7.1 */
  2538. case 510:
  2539. return "Not Extended"; /* RFC 2774, Section 7 */
  2540. case 511:
  2541. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  2542. /* Other status codes, not shown in the IANA HTTP status code assignment.
  2543. * E.g., "de facto" standards due to common use, ... */
  2544. case 418:
  2545. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  2546. case 419:
  2547. return "Authentication Timeout"; /* common use */
  2548. case 420:
  2549. return "Enhance Your Calm"; /* common use */
  2550. case 440:
  2551. return "Login Timeout"; /* common use */
  2552. case 509:
  2553. return "Bandwidth Limit Exceeded"; /* common use */
  2554. default:
  2555. /* This error code is unknown. This should not happen. */
  2556. if (conn) {
  2557. mg_cry(conn, "Unknown HTTP response code: %u", response_code);
  2558. }
  2559. /* Return at least a category according to RFC 2616 Section 10. */
  2560. if (response_code >= 100 && response_code < 200) {
  2561. /* Unknown informational status code */
  2562. return "Information";
  2563. }
  2564. if (response_code >= 200 && response_code < 300) {
  2565. /* Unknown success code */
  2566. return "Success";
  2567. }
  2568. if (response_code >= 300 && response_code < 400) {
  2569. /* Unknown redirection code */
  2570. return "Redirection";
  2571. }
  2572. if (response_code >= 400 && response_code < 500) {
  2573. /* Unknown request error code */
  2574. return "Client Error";
  2575. }
  2576. if (response_code >= 500 && response_code < 600) {
  2577. /* Unknown server error code */
  2578. return "Server Error";
  2579. }
  2580. /* Response code not even within reasonable range */
  2581. return "";
  2582. }
  2583. }
  2584. static void send_http_error(struct mg_connection *,
  2585. int,
  2586. PRINTF_FORMAT_STRING(const char *fmt),
  2587. ...) PRINTF_ARGS(3, 4);
  2588. static void
  2589. send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  2590. {
  2591. char buf[MG_BUF_LEN];
  2592. va_list ap;
  2593. int len, i, page_handler_found, scope, truncated, has_body;
  2594. char date[64];
  2595. time_t curtime = time(NULL);
  2596. const char *error_handler = NULL;
  2597. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  2598. const char *error_page_file_ext, *tstr;
  2599. const char *status_text = mg_get_response_code_text(conn, status);
  2600. if (conn == NULL) {
  2601. return;
  2602. }
  2603. conn->status_code = status;
  2604. if (conn->in_error_handler || conn->ctx->callbacks.http_error == NULL
  2605. || conn->ctx->callbacks.http_error(conn, status)) {
  2606. if (!conn->in_error_handler) {
  2607. /* Send user defined error pages, if defined */
  2608. error_handler = conn->ctx->config[ERROR_PAGES];
  2609. error_page_file_ext = conn->ctx->config[INDEX_FILES];
  2610. page_handler_found = 0;
  2611. if (error_handler != NULL) {
  2612. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  2613. switch (scope) {
  2614. case 1: /* Handler for specific error, e.g. 404 error */
  2615. mg_snprintf(conn,
  2616. &truncated,
  2617. buf,
  2618. sizeof(buf) - 32,
  2619. "%serror%03u.",
  2620. error_handler,
  2621. status);
  2622. break;
  2623. case 2: /* Handler for error group, e.g., 5xx error handler
  2624. * for all server errors (500-599) */
  2625. mg_snprintf(conn,
  2626. &truncated,
  2627. buf,
  2628. sizeof(buf) - 32,
  2629. "%serror%01uxx.",
  2630. error_handler,
  2631. status / 100);
  2632. break;
  2633. default: /* Handler for all errors */
  2634. mg_snprintf(conn,
  2635. &truncated,
  2636. buf,
  2637. sizeof(buf) - 32,
  2638. "%serror.",
  2639. error_handler);
  2640. break;
  2641. }
  2642. /* String truncation in buf may only occur if error_handler
  2643. * is too long. This string is from the config, not from a
  2644. * client. */
  2645. (void)truncated;
  2646. len = (int)strlen(buf);
  2647. tstr = strchr(error_page_file_ext, '.');
  2648. while (tstr) {
  2649. for (i = 1; i < 32 && tstr[i] != 0 && tstr[i] != ',';
  2650. i++)
  2651. buf[len + i - 1] = tstr[i];
  2652. buf[len + i - 1] = 0;
  2653. if (mg_stat(conn, buf, &error_page_file.stat)) {
  2654. page_handler_found = 1;
  2655. break;
  2656. }
  2657. tstr = strchr(tstr + i, '.');
  2658. }
  2659. }
  2660. }
  2661. if (page_handler_found) {
  2662. conn->in_error_handler = 1;
  2663. handle_file_based_request(conn, buf, &error_page_file);
  2664. conn->in_error_handler = 0;
  2665. return;
  2666. }
  2667. }
  2668. /* No custom error page. Send default error page. */
  2669. gmt_time_string(date, sizeof(date), &curtime);
  2670. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  2671. has_body = (status > 199 && status != 204 && status != 304);
  2672. conn->must_close = 1;
  2673. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  2674. send_no_cache_header(conn);
  2675. if (has_body) {
  2676. mg_printf(conn,
  2677. "%s",
  2678. "Content-Type: text/plain; charset=utf-8\r\n");
  2679. }
  2680. mg_printf(conn,
  2681. "Date: %s\r\n"
  2682. "Connection: close\r\n\r\n",
  2683. date);
  2684. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  2685. if (has_body) {
  2686. mg_printf(conn, "Error %d: %s\n", status, status_text);
  2687. if (fmt != NULL) {
  2688. va_start(ap, fmt);
  2689. mg_vsnprintf(conn, NULL, buf, sizeof(buf), fmt, ap);
  2690. va_end(ap);
  2691. mg_write(conn, buf, strlen(buf));
  2692. DEBUG_TRACE("Error %i - [%s]", status, buf);
  2693. }
  2694. } else {
  2695. /* No body allowed. Close the connection. */
  2696. DEBUG_TRACE("Error %i", status);
  2697. }
  2698. }
  2699. }
  2700. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  2701. /* Create substitutes for POSIX functions in Win32. */
  2702. #if defined(__MINGW32__)
  2703. /* Show no warning in case system functions are not used. */
  2704. #pragma GCC diagnostic push
  2705. #pragma GCC diagnostic ignored "-Wunused-function"
  2706. #endif
  2707. static int
  2708. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  2709. {
  2710. (void)unused;
  2711. *mutex = CreateMutex(NULL, FALSE, NULL);
  2712. return (*mutex == NULL) ? -1 : 0;
  2713. }
  2714. static int
  2715. pthread_mutex_destroy(pthread_mutex_t *mutex)
  2716. {
  2717. return (CloseHandle(*mutex) == 0) ? -1 : 0;
  2718. }
  2719. static int
  2720. pthread_mutex_lock(pthread_mutex_t *mutex)
  2721. {
  2722. return (WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0) ? 0 : -1;
  2723. }
  2724. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  2725. static int
  2726. pthread_mutex_trylock(pthread_mutex_t *mutex)
  2727. {
  2728. switch (WaitForSingleObject(*mutex, 0)) {
  2729. case WAIT_OBJECT_0:
  2730. return 0;
  2731. case WAIT_TIMEOUT:
  2732. return -2; /* EBUSY */
  2733. }
  2734. return -1;
  2735. }
  2736. #endif
  2737. static int
  2738. pthread_mutex_unlock(pthread_mutex_t *mutex)
  2739. {
  2740. return (ReleaseMutex(*mutex) == 0) ? -1 : 0;
  2741. }
  2742. static int
  2743. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  2744. {
  2745. (void)unused;
  2746. InitializeCriticalSection(&cv->threadIdSec);
  2747. cv->waiting_thread = NULL;
  2748. return 0;
  2749. }
  2750. static int
  2751. pthread_cond_timedwait(pthread_cond_t *cv,
  2752. pthread_mutex_t *mutex,
  2753. const struct timespec *abstime)
  2754. {
  2755. struct mg_workerTLS **ptls,
  2756. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2757. int ok;
  2758. struct timespec tsnow;
  2759. int64_t nsnow, nswaitabs, nswaitrel;
  2760. DWORD mswaitrel;
  2761. EnterCriticalSection(&cv->threadIdSec);
  2762. /* Add this thread to cv's waiting list */
  2763. ptls = &cv->waiting_thread;
  2764. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  2765. ;
  2766. tls->next_waiting_thread = NULL;
  2767. *ptls = tls;
  2768. LeaveCriticalSection(&cv->threadIdSec);
  2769. if (abstime) {
  2770. clock_gettime(CLOCK_REALTIME, &tsnow);
  2771. nsnow = (((int64_t)tsnow.tv_sec) * 1000000000) + tsnow.tv_nsec;
  2772. nswaitabs =
  2773. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  2774. nswaitrel = nswaitabs - nsnow;
  2775. if (nswaitrel < 0) {
  2776. nswaitrel = 0;
  2777. }
  2778. mswaitrel = (DWORD)(nswaitrel / 1000000);
  2779. } else {
  2780. mswaitrel = INFINITE;
  2781. }
  2782. pthread_mutex_unlock(mutex);
  2783. ok = (WAIT_OBJECT_0
  2784. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  2785. if (!ok) {
  2786. ok = 1;
  2787. EnterCriticalSection(&cv->threadIdSec);
  2788. ptls = &cv->waiting_thread;
  2789. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  2790. if (*ptls == tls) {
  2791. *ptls = tls->next_waiting_thread;
  2792. ok = 0;
  2793. break;
  2794. }
  2795. }
  2796. LeaveCriticalSection(&cv->threadIdSec);
  2797. if (ok) {
  2798. WaitForSingleObject(tls->pthread_cond_helper_mutex, INFINITE);
  2799. }
  2800. }
  2801. /* This thread has been removed from cv's waiting list */
  2802. pthread_mutex_lock(mutex);
  2803. return ok ? 0 : -1;
  2804. }
  2805. static int
  2806. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  2807. {
  2808. return pthread_cond_timedwait(cv, mutex, NULL);
  2809. }
  2810. static int
  2811. pthread_cond_signal(pthread_cond_t *cv)
  2812. {
  2813. HANDLE wkup = NULL;
  2814. BOOL ok = FALSE;
  2815. EnterCriticalSection(&cv->threadIdSec);
  2816. if (cv->waiting_thread) {
  2817. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  2818. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  2819. ok = SetEvent(wkup);
  2820. assert(ok);
  2821. }
  2822. LeaveCriticalSection(&cv->threadIdSec);
  2823. return ok ? 0 : 1;
  2824. }
  2825. static int
  2826. pthread_cond_broadcast(pthread_cond_t *cv)
  2827. {
  2828. EnterCriticalSection(&cv->threadIdSec);
  2829. while (cv->waiting_thread) {
  2830. pthread_cond_signal(cv);
  2831. }
  2832. LeaveCriticalSection(&cv->threadIdSec);
  2833. return 0;
  2834. }
  2835. static int
  2836. pthread_cond_destroy(pthread_cond_t *cv)
  2837. {
  2838. EnterCriticalSection(&cv->threadIdSec);
  2839. assert(cv->waiting_thread == NULL);
  2840. LeaveCriticalSection(&cv->threadIdSec);
  2841. DeleteCriticalSection(&cv->threadIdSec);
  2842. return 0;
  2843. }
  2844. #ifdef ALTERNATIVE_QUEUE
  2845. static void *
  2846. event_create(void)
  2847. {
  2848. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  2849. }
  2850. static int
  2851. event_wait(void *eventhdl)
  2852. {
  2853. int res = WaitForSingleObject((HANDLE)eventhdl, INFINITE);
  2854. return (res == WAIT_OBJECT_0);
  2855. }
  2856. static int
  2857. event_signal(void *eventhdl)
  2858. {
  2859. return (int)SetEvent((HANDLE)eventhdl);
  2860. }
  2861. static void
  2862. event_destroy(void *eventhdl)
  2863. {
  2864. CloseHandle((HANDLE)eventhdl);
  2865. }
  2866. #endif
  2867. #if defined(__MINGW32__)
  2868. /* Enable unused function warning again */
  2869. #pragma GCC diagnostic pop
  2870. #endif
  2871. /* For Windows, change all slashes to backslashes in path names. */
  2872. static void
  2873. change_slashes_to_backslashes(char *path)
  2874. {
  2875. int i;
  2876. for (i = 0; path[i] != '\0'; i++) {
  2877. if (path[i] == '/') {
  2878. path[i] = '\\';
  2879. }
  2880. /* remove double backslash (check i > 0 to preserve UNC paths,
  2881. * like \\server\file.txt) */
  2882. if ((path[i] == '\\') && (i > 0)) {
  2883. while (path[i + 1] == '\\' || path[i + 1] == '/') {
  2884. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  2885. }
  2886. }
  2887. }
  2888. }
  2889. static int
  2890. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  2891. {
  2892. int diff;
  2893. do {
  2894. diff = tolower(*s1) - tolower(*s2);
  2895. s1++;
  2896. s2++;
  2897. } while (diff == 0 && s1[-1] != '\0');
  2898. return diff;
  2899. }
  2900. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  2901. * wbuf and wbuf_len is a target buffer and its length. */
  2902. static void
  2903. path_to_unicode(const struct mg_connection *conn,
  2904. const char *path,
  2905. wchar_t *wbuf,
  2906. size_t wbuf_len)
  2907. {
  2908. char buf[PATH_MAX], buf2[PATH_MAX];
  2909. wchar_t wbuf2[MAX_PATH + 1];
  2910. DWORD long_len, err;
  2911. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  2912. mg_strlcpy(buf, path, sizeof(buf));
  2913. change_slashes_to_backslashes(buf);
  2914. /* Convert to Unicode and back. If doubly-converted string does not
  2915. * match the original, something is fishy, reject. */
  2916. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  2917. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  2918. WideCharToMultiByte(
  2919. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  2920. if (strcmp(buf, buf2) != 0) {
  2921. wbuf[0] = L'\0';
  2922. }
  2923. /* Windows file systems are not case sensitive, but you can still use
  2924. * uppercase and lowercase letters (on all modern file systems).
  2925. * The server can check if the URI uses the same upper/lowercase
  2926. * letters an the file system, effectively making Windows servers
  2927. * case sensitive (like Linux servers are). It is still not possible
  2928. * to use two files with the same name in different cases on Windows
  2929. * (like /a and /A) - this would be possible in Linux.
  2930. * As a default, Windows is not case sensitive, but the case sensitive
  2931. * file name check can be activated by an additional configuration. */
  2932. if (conn) {
  2933. if (conn->ctx->config[CASE_SENSITIVE_FILES]
  2934. && !mg_strcasecmp(conn->ctx->config[CASE_SENSITIVE_FILES], "yes")) {
  2935. /* Use case sensitive compare function */
  2936. fcompare = wcscmp;
  2937. }
  2938. }
  2939. (void)conn; /* conn is currently unused */
  2940. #if !defined(_WIN32_WCE)
  2941. /* Only accept a full file path, not a Windows short (8.3) path. */
  2942. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  2943. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  2944. if (long_len == 0) {
  2945. err = GetLastError();
  2946. if (err == ERROR_FILE_NOT_FOUND) {
  2947. /* File does not exist. This is not always a problem here. */
  2948. return;
  2949. }
  2950. }
  2951. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  2952. /* Short name is used. */
  2953. wbuf[0] = L'\0';
  2954. }
  2955. #else
  2956. (void)long_len;
  2957. (void)wbuf2;
  2958. (void)err;
  2959. if (strchr(path, '~')) {
  2960. wbuf[0] = L'\0';
  2961. }
  2962. #endif
  2963. }
  2964. /* Windows happily opens files with some garbage at the end of file name.
  2965. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  2966. * "a.cgi", despite one would expect an error back.
  2967. * This function returns non-0 if path ends with some garbage. */
  2968. static int
  2969. path_cannot_disclose_cgi(const char *path)
  2970. {
  2971. static const char *allowed_last_characters = "_-";
  2972. int last = path[strlen(path) - 1];
  2973. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  2974. }
  2975. static int
  2976. mg_stat(const struct mg_connection *conn,
  2977. const char *path,
  2978. struct mg_file_stat *filep)
  2979. {
  2980. wchar_t wbuf[PATH_MAX];
  2981. WIN32_FILE_ATTRIBUTE_DATA info;
  2982. time_t creation_time;
  2983. if (!filep) {
  2984. return 0;
  2985. }
  2986. memset(filep, 0, sizeof(*filep));
  2987. if (conn && is_file_in_memory(conn, path)) {
  2988. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  2989. * memset */
  2990. filep->last_modified = time(NULL); /* xxxxxxxx */
  2991. /* last_modified = now ... assumes the file may change during runtime,
  2992. * so every mg_fopen call may return different data */
  2993. /* last_modified = conn->ctx.start_time;
  2994. * May be used it the data does not change during runtime. This allows
  2995. * browser caching. Since we do not know, we have to assume the file
  2996. * in memory may change. */
  2997. return 1;
  2998. }
  2999. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3000. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  3001. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  3002. filep->last_modified =
  3003. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  3004. info.ftLastWriteTime.dwHighDateTime);
  3005. /* On Windows, the file creation time can be higher than the
  3006. * modification time, e.g. when a file is copied.
  3007. * Since the Last-Modified timestamp is used for caching
  3008. * it should be based on the most recent timestamp. */
  3009. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  3010. info.ftCreationTime.dwHighDateTime);
  3011. if (creation_time > filep->last_modified) {
  3012. filep->last_modified = creation_time;
  3013. }
  3014. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  3015. /* If file name is fishy, reset the file structure and return
  3016. * error.
  3017. * Note it is important to reset, not just return the error, cause
  3018. * functions like is_file_opened() check the struct. */
  3019. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  3020. memset(filep, 0, sizeof(*filep));
  3021. return 0;
  3022. }
  3023. return 1;
  3024. }
  3025. return 0;
  3026. }
  3027. static int
  3028. mg_remove(const struct mg_connection *conn, const char *path)
  3029. {
  3030. wchar_t wbuf[PATH_MAX];
  3031. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3032. return DeleteFileW(wbuf) ? 0 : -1;
  3033. }
  3034. static int
  3035. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  3036. {
  3037. wchar_t wbuf[PATH_MAX];
  3038. (void)mode;
  3039. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3040. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  3041. }
  3042. /* Create substitutes for POSIX functions in Win32. */
  3043. #if defined(__MINGW32__)
  3044. /* Show no warning in case system functions are not used. */
  3045. #pragma GCC diagnostic push
  3046. #pragma GCC diagnostic ignored "-Wunused-function"
  3047. #endif
  3048. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  3049. static DIR *
  3050. mg_opendir(const struct mg_connection *conn, const char *name)
  3051. {
  3052. DIR *dir = NULL;
  3053. wchar_t wpath[PATH_MAX];
  3054. DWORD attrs;
  3055. if (name == NULL) {
  3056. SetLastError(ERROR_BAD_ARGUMENTS);
  3057. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  3058. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  3059. } else {
  3060. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  3061. attrs = GetFileAttributesW(wpath);
  3062. if (attrs != 0xFFFFFFFF && ((attrs & FILE_ATTRIBUTE_DIRECTORY)
  3063. == FILE_ATTRIBUTE_DIRECTORY)) {
  3064. (void)wcscat(wpath, L"\\*");
  3065. dir->handle = FindFirstFileW(wpath, &dir->info);
  3066. dir->result.d_name[0] = '\0';
  3067. } else {
  3068. mg_free(dir);
  3069. dir = NULL;
  3070. }
  3071. }
  3072. return dir;
  3073. }
  3074. static int
  3075. mg_closedir(DIR *dir)
  3076. {
  3077. int result = 0;
  3078. if (dir != NULL) {
  3079. if (dir->handle != INVALID_HANDLE_VALUE)
  3080. result = FindClose(dir->handle) ? 0 : -1;
  3081. mg_free(dir);
  3082. } else {
  3083. result = -1;
  3084. SetLastError(ERROR_BAD_ARGUMENTS);
  3085. }
  3086. return result;
  3087. }
  3088. static struct dirent *
  3089. mg_readdir(DIR *dir)
  3090. {
  3091. struct dirent *result = 0;
  3092. if (dir) {
  3093. if (dir->handle != INVALID_HANDLE_VALUE) {
  3094. result = &dir->result;
  3095. (void)WideCharToMultiByte(CP_UTF8,
  3096. 0,
  3097. dir->info.cFileName,
  3098. -1,
  3099. result->d_name,
  3100. sizeof(result->d_name),
  3101. NULL,
  3102. NULL);
  3103. if (!FindNextFileW(dir->handle, &dir->info)) {
  3104. (void)FindClose(dir->handle);
  3105. dir->handle = INVALID_HANDLE_VALUE;
  3106. }
  3107. } else {
  3108. SetLastError(ERROR_FILE_NOT_FOUND);
  3109. }
  3110. } else {
  3111. SetLastError(ERROR_BAD_ARGUMENTS);
  3112. }
  3113. return result;
  3114. }
  3115. #ifndef HAVE_POLL
  3116. static int
  3117. poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  3118. {
  3119. struct timeval tv;
  3120. fd_set set;
  3121. unsigned int i;
  3122. int result;
  3123. SOCKET maxfd = 0;
  3124. memset(&tv, 0, sizeof(tv));
  3125. tv.tv_sec = milliseconds / 1000;
  3126. tv.tv_usec = (milliseconds % 1000) * 1000;
  3127. FD_ZERO(&set);
  3128. for (i = 0; i < n; i++) {
  3129. FD_SET((SOCKET)pfd[i].fd, &set);
  3130. pfd[i].revents = 0;
  3131. if (pfd[i].fd > maxfd) {
  3132. maxfd = pfd[i].fd;
  3133. }
  3134. }
  3135. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  3136. for (i = 0; i < n; i++) {
  3137. if (FD_ISSET(pfd[i].fd, &set)) {
  3138. pfd[i].revents = POLLIN;
  3139. }
  3140. }
  3141. }
  3142. /* We should subtract the time used in select from remaining
  3143. * "milliseconds", in particular if called from mg_poll with a
  3144. * timeout quantum.
  3145. * Unfortunately, the remaining time is not stored in "tv" in all
  3146. * implementations, so the result in "tv" must be considered undefined.
  3147. * See http://man7.org/linux/man-pages/man2/select.2.html */
  3148. return result;
  3149. }
  3150. #endif /* HAVE_POLL */
  3151. #if defined(__MINGW32__)
  3152. /* Enable unused function warning again */
  3153. #pragma GCC diagnostic pop
  3154. #endif
  3155. static void
  3156. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  3157. {
  3158. (void)conn; /* Unused. */
  3159. #if defined(_WIN32_WCE)
  3160. (void)sock;
  3161. #else
  3162. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  3163. #endif
  3164. }
  3165. int
  3166. mg_start_thread(mg_thread_func_t f, void *p)
  3167. {
  3168. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3169. /* Compile-time option to control stack size, e.g. -DUSE_STACK_SIZE=16384
  3170. */
  3171. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  3172. == ((uintptr_t)(-1L)))
  3173. ? -1
  3174. : 0);
  3175. #else
  3176. return (
  3177. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  3178. ? -1
  3179. : 0);
  3180. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3181. }
  3182. /* Start a thread storing the thread context. */
  3183. static int
  3184. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  3185. void *p,
  3186. pthread_t *threadidptr)
  3187. {
  3188. uintptr_t uip;
  3189. HANDLE threadhandle;
  3190. int result = -1;
  3191. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  3192. threadhandle = (HANDLE)uip;
  3193. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  3194. *threadidptr = threadhandle;
  3195. result = 0;
  3196. }
  3197. return result;
  3198. }
  3199. /* Wait for a thread to finish. */
  3200. static int
  3201. mg_join_thread(pthread_t threadid)
  3202. {
  3203. int result;
  3204. DWORD dwevent;
  3205. result = -1;
  3206. dwevent = WaitForSingleObject(threadid, INFINITE);
  3207. if (dwevent == WAIT_FAILED) {
  3208. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  3209. } else {
  3210. if (dwevent == WAIT_OBJECT_0) {
  3211. CloseHandle(threadid);
  3212. result = 0;
  3213. }
  3214. }
  3215. return result;
  3216. }
  3217. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  3218. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  3219. /* Create substitutes for POSIX functions in Win32. */
  3220. #if defined(__MINGW32__)
  3221. /* Show no warning in case system functions are not used. */
  3222. #pragma GCC diagnostic push
  3223. #pragma GCC diagnostic ignored "-Wunused-function"
  3224. #endif
  3225. static HANDLE
  3226. dlopen(const char *dll_name, int flags)
  3227. {
  3228. wchar_t wbuf[PATH_MAX];
  3229. (void)flags;
  3230. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  3231. return LoadLibraryW(wbuf);
  3232. }
  3233. static int
  3234. dlclose(void *handle)
  3235. {
  3236. int result;
  3237. if (FreeLibrary((HMODULE)handle) != 0) {
  3238. result = 0;
  3239. } else {
  3240. result = -1;
  3241. }
  3242. return result;
  3243. }
  3244. #if defined(__MINGW32__)
  3245. /* Enable unused function warning again */
  3246. #pragma GCC diagnostic pop
  3247. #endif
  3248. #endif
  3249. #if !defined(NO_CGI)
  3250. #define SIGKILL (0)
  3251. static int
  3252. kill(pid_t pid, int sig_num)
  3253. {
  3254. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  3255. (void)CloseHandle((HANDLE)pid);
  3256. return 0;
  3257. }
  3258. static void
  3259. trim_trailing_whitespaces(char *s)
  3260. {
  3261. char *e = s + strlen(s) - 1;
  3262. while (e > s && isspace(*(unsigned char *)e)) {
  3263. *e-- = '\0';
  3264. }
  3265. }
  3266. static pid_t
  3267. spawn_process(struct mg_connection *conn,
  3268. const char *prog,
  3269. char *envblk,
  3270. char *envp[],
  3271. int fdin[2],
  3272. int fdout[2],
  3273. int fderr[2],
  3274. const char *dir)
  3275. {
  3276. HANDLE me;
  3277. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  3278. cmdline[PATH_MAX], buf[PATH_MAX];
  3279. int truncated;
  3280. struct mg_file file = STRUCT_FILE_INITIALIZER;
  3281. STARTUPINFOA si;
  3282. PROCESS_INFORMATION pi = {0};
  3283. (void)envp;
  3284. memset(&si, 0, sizeof(si));
  3285. si.cb = sizeof(si);
  3286. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  3287. si.wShowWindow = SW_HIDE;
  3288. me = GetCurrentProcess();
  3289. DuplicateHandle(me,
  3290. (HANDLE)_get_osfhandle(fdin[0]),
  3291. me,
  3292. &si.hStdInput,
  3293. 0,
  3294. TRUE,
  3295. DUPLICATE_SAME_ACCESS);
  3296. DuplicateHandle(me,
  3297. (HANDLE)_get_osfhandle(fdout[1]),
  3298. me,
  3299. &si.hStdOutput,
  3300. 0,
  3301. TRUE,
  3302. DUPLICATE_SAME_ACCESS);
  3303. DuplicateHandle(me,
  3304. (HANDLE)_get_osfhandle(fderr[1]),
  3305. me,
  3306. &si.hStdError,
  3307. 0,
  3308. TRUE,
  3309. DUPLICATE_SAME_ACCESS);
  3310. /* Mark handles that should not be inherited. See
  3311. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  3312. */
  3313. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  3314. HANDLE_FLAG_INHERIT,
  3315. 0);
  3316. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  3317. HANDLE_FLAG_INHERIT,
  3318. 0);
  3319. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  3320. HANDLE_FLAG_INHERIT,
  3321. 0);
  3322. /* If CGI file is a script, try to read the interpreter line */
  3323. interp = conn->ctx->config[CGI_INTERPRETER];
  3324. if (interp == NULL) {
  3325. buf[0] = buf[1] = '\0';
  3326. /* Read the first line of the script into the buffer */
  3327. mg_snprintf(
  3328. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  3329. if (truncated) {
  3330. pi.hProcess = (pid_t)-1;
  3331. goto spawn_cleanup;
  3332. }
  3333. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  3334. p = (char *)file.access.membuf;
  3335. mg_fgets(buf, sizeof(buf), &file, &p);
  3336. (void)mg_fclose(&file.access); /* ignore error on read only file */
  3337. buf[sizeof(buf) - 1] = '\0';
  3338. }
  3339. if (buf[0] == '#' && buf[1] == '!') {
  3340. trim_trailing_whitespaces(buf + 2);
  3341. } else {
  3342. buf[2] = '\0';
  3343. }
  3344. interp = buf + 2;
  3345. }
  3346. if (interp[0] != '\0') {
  3347. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  3348. interp = full_interp;
  3349. }
  3350. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  3351. if (interp[0] != '\0') {
  3352. mg_snprintf(conn,
  3353. &truncated,
  3354. cmdline,
  3355. sizeof(cmdline),
  3356. "\"%s\" \"%s\\%s\"",
  3357. interp,
  3358. full_dir,
  3359. prog);
  3360. } else {
  3361. mg_snprintf(conn,
  3362. &truncated,
  3363. cmdline,
  3364. sizeof(cmdline),
  3365. "\"%s\\%s\"",
  3366. full_dir,
  3367. prog);
  3368. }
  3369. if (truncated) {
  3370. pi.hProcess = (pid_t)-1;
  3371. goto spawn_cleanup;
  3372. }
  3373. DEBUG_TRACE("Running [%s]", cmdline);
  3374. if (CreateProcessA(NULL,
  3375. cmdline,
  3376. NULL,
  3377. NULL,
  3378. TRUE,
  3379. CREATE_NEW_PROCESS_GROUP,
  3380. envblk,
  3381. NULL,
  3382. &si,
  3383. &pi) == 0) {
  3384. mg_cry(
  3385. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  3386. pi.hProcess = (pid_t)-1;
  3387. /* goto spawn_cleanup; */
  3388. }
  3389. spawn_cleanup:
  3390. (void)CloseHandle(si.hStdOutput);
  3391. (void)CloseHandle(si.hStdError);
  3392. (void)CloseHandle(si.hStdInput);
  3393. if (pi.hThread != NULL) {
  3394. (void)CloseHandle(pi.hThread);
  3395. }
  3396. return (pid_t)pi.hProcess;
  3397. }
  3398. #endif /* !NO_CGI */
  3399. static int
  3400. set_non_blocking_mode(SOCKET sock)
  3401. {
  3402. unsigned long on = 1;
  3403. return ioctlsocket(sock, (long)FIONBIO, &on);
  3404. }
  3405. #else
  3406. static int
  3407. mg_stat(const struct mg_connection *conn,
  3408. const char *path,
  3409. struct mg_file_stat *filep)
  3410. {
  3411. struct stat st;
  3412. if (!filep) {
  3413. return 0;
  3414. }
  3415. memset(filep, 0, sizeof(*filep));
  3416. if (conn && is_file_in_memory(conn, path)) {
  3417. return 1;
  3418. }
  3419. if (0 == stat(path, &st)) {
  3420. filep->size = (uint64_t)(st.st_size);
  3421. filep->last_modified = st.st_mtime;
  3422. filep->is_directory = S_ISDIR(st.st_mode);
  3423. return 1;
  3424. }
  3425. return 0;
  3426. }
  3427. static void
  3428. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  3429. {
  3430. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  3431. if (conn) {
  3432. mg_cry(conn,
  3433. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  3434. __func__,
  3435. strerror(ERRNO));
  3436. }
  3437. }
  3438. }
  3439. int
  3440. mg_start_thread(mg_thread_func_t func, void *param)
  3441. {
  3442. pthread_t thread_id;
  3443. pthread_attr_t attr;
  3444. int result;
  3445. (void)pthread_attr_init(&attr);
  3446. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  3447. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3448. /* Compile-time option to control stack size,
  3449. * e.g. -DUSE_STACK_SIZE=16384 */
  3450. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3451. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3452. result = pthread_create(&thread_id, &attr, func, param);
  3453. pthread_attr_destroy(&attr);
  3454. return result;
  3455. }
  3456. /* Start a thread storing the thread context. */
  3457. static int
  3458. mg_start_thread_with_id(mg_thread_func_t func,
  3459. void *param,
  3460. pthread_t *threadidptr)
  3461. {
  3462. pthread_t thread_id;
  3463. pthread_attr_t attr;
  3464. int result;
  3465. (void)pthread_attr_init(&attr);
  3466. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3467. /* Compile-time option to control stack size,
  3468. * e.g. -DUSE_STACK_SIZE=16384 */
  3469. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3470. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  3471. result = pthread_create(&thread_id, &attr, func, param);
  3472. pthread_attr_destroy(&attr);
  3473. if ((result == 0) && (threadidptr != NULL)) {
  3474. *threadidptr = thread_id;
  3475. }
  3476. return result;
  3477. }
  3478. /* Wait for a thread to finish. */
  3479. static int
  3480. mg_join_thread(pthread_t threadid)
  3481. {
  3482. int result;
  3483. result = pthread_join(threadid, NULL);
  3484. return result;
  3485. }
  3486. #ifndef NO_CGI
  3487. static pid_t
  3488. spawn_process(struct mg_connection *conn,
  3489. const char *prog,
  3490. char *envblk,
  3491. char *envp[],
  3492. int fdin[2],
  3493. int fdout[2],
  3494. int fderr[2],
  3495. const char *dir)
  3496. {
  3497. pid_t pid;
  3498. const char *interp;
  3499. (void)envblk;
  3500. if (conn == NULL) {
  3501. return 0;
  3502. }
  3503. if ((pid = fork()) == -1) {
  3504. /* Parent */
  3505. send_http_error(conn,
  3506. 500,
  3507. "Error: Creating CGI process\nfork(): %s",
  3508. strerror(ERRNO));
  3509. } else if (pid == 0) {
  3510. /* Child */
  3511. if (chdir(dir) != 0) {
  3512. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  3513. } else if (dup2(fdin[0], 0) == -1) {
  3514. mg_cry(conn,
  3515. "%s: dup2(%d, 0): %s",
  3516. __func__,
  3517. fdin[0],
  3518. strerror(ERRNO));
  3519. } else if (dup2(fdout[1], 1) == -1) {
  3520. mg_cry(conn,
  3521. "%s: dup2(%d, 1): %s",
  3522. __func__,
  3523. fdout[1],
  3524. strerror(ERRNO));
  3525. } else if (dup2(fderr[1], 2) == -1) {
  3526. mg_cry(conn,
  3527. "%s: dup2(%d, 2): %s",
  3528. __func__,
  3529. fderr[1],
  3530. strerror(ERRNO));
  3531. } else {
  3532. /* Keep stderr and stdout in two different pipes.
  3533. * Stdout will be sent back to the client,
  3534. * stderr should go into a server error log. */
  3535. (void)close(fdin[0]);
  3536. (void)close(fdout[1]);
  3537. (void)close(fderr[1]);
  3538. /* Close write end fdin and read end fdout and fderr */
  3539. (void)close(fdin[1]);
  3540. (void)close(fdout[0]);
  3541. (void)close(fderr[0]);
  3542. /* After exec, all signal handlers are restored to their default
  3543. * values, with one exception of SIGCHLD. According to
  3544. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler will
  3545. * leave unchanged after exec if it was set to be ignored. Restore
  3546. * it to default action. */
  3547. signal(SIGCHLD, SIG_DFL);
  3548. interp = conn->ctx->config[CGI_INTERPRETER];
  3549. if (interp == NULL) {
  3550. (void)execle(prog, prog, NULL, envp);
  3551. mg_cry(conn,
  3552. "%s: execle(%s): %s",
  3553. __func__,
  3554. prog,
  3555. strerror(ERRNO));
  3556. } else {
  3557. (void)execle(interp, interp, prog, NULL, envp);
  3558. mg_cry(conn,
  3559. "%s: execle(%s %s): %s",
  3560. __func__,
  3561. interp,
  3562. prog,
  3563. strerror(ERRNO));
  3564. }
  3565. }
  3566. exit(EXIT_FAILURE);
  3567. }
  3568. return pid;
  3569. }
  3570. #endif /* !NO_CGI */
  3571. static int
  3572. set_non_blocking_mode(SOCKET sock)
  3573. {
  3574. int flags;
  3575. flags = fcntl(sock, F_GETFL, 0);
  3576. (void)fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  3577. return 0;
  3578. }
  3579. #endif /* _WIN32 */
  3580. /* End of initial operating system specific define block. */
  3581. /* Get a random number (independent of C rand function) */
  3582. static uint64_t
  3583. get_random(void)
  3584. {
  3585. static uint64_t lfsr = 0; /* Linear feedback shift register */
  3586. static uint64_t lcg = 0; /* Linear congruential generator */
  3587. struct timespec now;
  3588. memset(&now, 0, sizeof(now));
  3589. clock_gettime(CLOCK_MONOTONIC, &now);
  3590. if (lfsr == 0) {
  3591. /* lfsr will be only 0 if has not been initialized,
  3592. * so this code is called only once. */
  3593. lfsr = (((uint64_t)now.tv_sec) << 21) ^ ((uint64_t)now.tv_nsec)
  3594. ^ ((uint64_t)(ptrdiff_t)&now) ^ (((uint64_t)time(NULL)) << 33);
  3595. lcg = (((uint64_t)now.tv_sec) << 25) + (uint64_t)now.tv_nsec
  3596. + (uint64_t)(ptrdiff_t)&now;
  3597. } else {
  3598. /* Get the next step of both random number generators. */
  3599. lfsr = (lfsr >> 1)
  3600. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  3601. << 63);
  3602. lcg = lcg * 6364136223846793005 + 1442695040888963407;
  3603. }
  3604. /* Combining two pseudo-random number generators and a high resolution part
  3605. * of the current server time will make it hard (impossible?) to guess the
  3606. * next number. */
  3607. return (lfsr ^ lcg ^ (uint64_t)now.tv_nsec);
  3608. }
  3609. static int
  3610. mg_poll(struct pollfd *pfd,
  3611. unsigned int n,
  3612. int milliseconds,
  3613. volatile int *stop_server)
  3614. {
  3615. int ms_now, result;
  3616. /* Call poll, but only for a maximum time of a few seconds.
  3617. * This will allow to stop the server after some seconds, instead
  3618. * of having to wait for a long socket timeout. */
  3619. ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  3620. do {
  3621. if (*stop_server) {
  3622. /* Shut down signal */
  3623. return -2;
  3624. }
  3625. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  3626. ms_now = milliseconds;
  3627. }
  3628. result = poll(pfd, n, ms_now);
  3629. if (result != 0) {
  3630. /* Poll returned either success (1) or error (-1).
  3631. * Forward both to the caller. */
  3632. return result;
  3633. }
  3634. /* Poll returned timeout (0). */
  3635. if (milliseconds > 0) {
  3636. milliseconds -= ms_now;
  3637. }
  3638. } while (milliseconds != 0);
  3639. return result;
  3640. }
  3641. /* Write data to the IO channel - opened file descriptor, socket or SSL
  3642. * descriptor. Return number of bytes written. */
  3643. static int
  3644. push(struct mg_context *ctx,
  3645. FILE *fp,
  3646. SOCKET sock,
  3647. SSL *ssl,
  3648. const char *buf,
  3649. int len,
  3650. double timeout)
  3651. {
  3652. struct timespec start, now;
  3653. int n, err;
  3654. #ifdef _WIN32
  3655. typedef int len_t;
  3656. #else
  3657. typedef size_t len_t;
  3658. #endif
  3659. if (timeout > 0) {
  3660. memset(&start, 0, sizeof(start));
  3661. memset(&now, 0, sizeof(now));
  3662. clock_gettime(CLOCK_MONOTONIC, &start);
  3663. }
  3664. if (ctx == NULL) {
  3665. return -1;
  3666. }
  3667. #ifdef NO_SSL
  3668. if (ssl) {
  3669. return -1;
  3670. }
  3671. #endif
  3672. do {
  3673. #ifndef NO_SSL
  3674. if (ssl != NULL) {
  3675. n = SSL_write(ssl, buf, len);
  3676. if (n <= 0) {
  3677. err = SSL_get_error(ssl, n);
  3678. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  3679. err = ERRNO;
  3680. } else if ((err == SSL_ERROR_WANT_READ)
  3681. || (err == SSL_ERROR_WANT_WRITE)) {
  3682. n = 0;
  3683. } else {
  3684. DEBUG_TRACE("SSL_write() failed, error %d", err);
  3685. return -1;
  3686. }
  3687. } else {
  3688. err = 0;
  3689. }
  3690. } else
  3691. #endif
  3692. if (fp != NULL) {
  3693. n = (int)fwrite(buf, 1, (size_t)len, fp);
  3694. if (ferror(fp)) {
  3695. n = -1;
  3696. err = ERRNO;
  3697. } else {
  3698. err = 0;
  3699. }
  3700. } else {
  3701. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  3702. err = (n < 0) ? ERRNO : 0;
  3703. if (n <= 0) {
  3704. /* shutdown of the socket at client side */
  3705. return -1;
  3706. }
  3707. #if defined(TEMPORARY_INSTRUMENTATION)
  3708. {
  3709. FILE *f = fopen("r:\\all.txt", "ab");
  3710. fprintf(f, "\r\n%010u SEND:\r\n", GetTickCount());
  3711. fwrite(buf, 1, n, f);
  3712. fclose(f);
  3713. }
  3714. #endif
  3715. }
  3716. if (ctx->stop_flag) {
  3717. return -1;
  3718. }
  3719. if ((n > 0) || (n == 0 && len == 0)) {
  3720. /* some data has been read, or no data was requested */
  3721. return n;
  3722. }
  3723. if (n < 0) {
  3724. /* socket error - check errno */
  3725. DEBUG_TRACE("send() failed, error %d", err);
  3726. /* TODO: error handling depending on the error code.
  3727. * These codes are different between Windows and Linux.
  3728. */
  3729. return -1;
  3730. }
  3731. /* This code is not reached in the moment.
  3732. * ==> Fix the TODOs above first. */
  3733. if (timeout > 0) {
  3734. clock_gettime(CLOCK_MONOTONIC, &now);
  3735. }
  3736. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  3737. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  3738. used */
  3739. return -1;
  3740. }
  3741. static int64_t
  3742. push_all(struct mg_context *ctx,
  3743. FILE *fp,
  3744. SOCKET sock,
  3745. SSL *ssl,
  3746. const char *buf,
  3747. int64_t len)
  3748. {
  3749. double timeout = -1.0;
  3750. int64_t n, nwritten = 0;
  3751. if (ctx == NULL) {
  3752. return -1;
  3753. }
  3754. if (ctx->config[REQUEST_TIMEOUT]) {
  3755. timeout = atoi(ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  3756. }
  3757. while (len > 0 && ctx->stop_flag == 0) {
  3758. n = push(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  3759. if (n < 0) {
  3760. if (nwritten == 0) {
  3761. nwritten = n; /* Propagate the error */
  3762. }
  3763. break;
  3764. } else if (n == 0) {
  3765. break; /* No more data to write */
  3766. } else {
  3767. nwritten += n;
  3768. len -= n;
  3769. }
  3770. }
  3771. return nwritten;
  3772. }
  3773. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  3774. * Return negative value on error, or number of bytes read on success. */
  3775. static int
  3776. pull(FILE *fp, struct mg_connection *conn, char *buf, int len, double timeout)
  3777. {
  3778. int nread, err = 0;
  3779. #ifdef _WIN32
  3780. typedef int len_t;
  3781. #else
  3782. typedef size_t len_t;
  3783. #endif
  3784. if (fp != NULL) {
  3785. #if !defined(_WIN32_WCE)
  3786. /* Use read() instead of fread(), because if we're reading from the
  3787. * CGI pipe, fread() may block until IO buffer is filled up. We
  3788. * cannot afford to block and must pass all read bytes immediately
  3789. * to the client. */
  3790. nread = (int)read(fileno(fp), buf, (size_t)len);
  3791. #else
  3792. /* WinCE does not support CGI pipes */
  3793. nread = (int)fread(buf, 1, (size_t)len, fp);
  3794. #endif
  3795. err = (nread < 0) ? ERRNO : 0;
  3796. #ifndef NO_SSL
  3797. } else if (conn->ssl != NULL) {
  3798. struct pollfd pfd[1];
  3799. int pollres;
  3800. pfd[0].fd = conn->client.sock;
  3801. pfd[0].events = POLLIN;
  3802. pollres =
  3803. mg_poll(pfd, 1, (int)(timeout * 1000.0), &(conn->ctx->stop_flag));
  3804. if (conn->ctx->stop_flag) {
  3805. return -1;
  3806. }
  3807. if (pollres > 0) {
  3808. nread = SSL_read(conn->ssl, buf, len);
  3809. if (nread <= 0) {
  3810. err = SSL_get_error(conn->ssl, nread);
  3811. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  3812. err = ERRNO;
  3813. } else if ((err == SSL_ERROR_WANT_READ)
  3814. || (err == SSL_ERROR_WANT_WRITE)) {
  3815. nread = 0;
  3816. } else {
  3817. DEBUG_TRACE("SSL_read() failed, error %d", err);
  3818. return -1;
  3819. }
  3820. } else {
  3821. err = 0;
  3822. }
  3823. } else if (pollres < 0) {
  3824. /* Error */
  3825. return -1;
  3826. } else {
  3827. /* pollres = 0 means timeout */
  3828. nread = 0;
  3829. }
  3830. #endif
  3831. } else {
  3832. struct pollfd pfd[1];
  3833. int pollres;
  3834. pfd[0].fd = conn->client.sock;
  3835. pfd[0].events = POLLIN;
  3836. pollres =
  3837. mg_poll(pfd, 1, (int)(timeout * 1000.0), &(conn->ctx->stop_flag));
  3838. if (conn->ctx->stop_flag) {
  3839. return -1;
  3840. }
  3841. if (pollres > 0) {
  3842. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  3843. err = (nread < 0) ? ERRNO : 0;
  3844. if (nread <= 0) {
  3845. /* shutdown of the socket at client side */
  3846. return -1;
  3847. }
  3848. #if defined(TEMPORARY_INSTRUMENTATION)
  3849. {
  3850. FILE *f = fopen("r:\\all.txt", "ab");
  3851. fprintf(f, "\r\n%010u RECV:\r\n", GetTickCount());
  3852. fwrite(buf, 1, nread, f);
  3853. fclose(f);
  3854. }
  3855. #endif
  3856. } else if (pollres < 0) {
  3857. /* error callint poll */
  3858. return -1;
  3859. } else {
  3860. /* pollres = 0 means timeout */
  3861. nread = 0;
  3862. }
  3863. }
  3864. if (conn->ctx->stop_flag) {
  3865. return -1;
  3866. }
  3867. if ((nread > 0) || (nread == 0 && len == 0)) {
  3868. /* some data has been read, or no data was requested */
  3869. return nread;
  3870. }
  3871. if (nread < 0) {
  3872. /* socket error - check errno */
  3873. #ifdef _WIN32
  3874. if (err == WSAEWOULDBLOCK) {
  3875. /* TODO: check if this is still required */
  3876. /* standard case if called from close_socket_gracefully */
  3877. return -1;
  3878. } else if (err == WSAETIMEDOUT) {
  3879. /* TODO: check if this is still required */
  3880. /* timeout is handled by the while loop */
  3881. return 0;
  3882. } else if (err == WSAECONNABORTED) {
  3883. /* See https://www.chilkatsoft.com/p/p_299.asp */
  3884. return -1;
  3885. } else {
  3886. DEBUG_TRACE("recv() failed, error %d", err);
  3887. return -1;
  3888. }
  3889. #else
  3890. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  3891. * if the timeout is reached and if the socket was set to non-
  3892. * blocking in close_socket_gracefully, so we can not distinguish
  3893. * here. We have to wait for the timeout in both cases for now.
  3894. */
  3895. if (err == EAGAIN || err == EWOULDBLOCK || err == EINTR) {
  3896. /* TODO: check if this is still required */
  3897. /* EAGAIN/EWOULDBLOCK:
  3898. * standard case if called from close_socket_gracefully
  3899. * => should return -1 */
  3900. /* or timeout occured
  3901. * => the code must stay in the while loop */
  3902. /* EINTR can be generated on a socket with a timeout set even
  3903. * when SA_RESTART is effective for all relevant signals
  3904. * (see signal(7)).
  3905. * => stay in the while loop */
  3906. } else {
  3907. DEBUG_TRACE("recv() failed, error %d", err);
  3908. return -1;
  3909. }
  3910. #endif
  3911. }
  3912. /* Timeout occured, but no data available. */
  3913. return -1;
  3914. }
  3915. static int
  3916. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  3917. {
  3918. int n, nread = 0;
  3919. double timeout = -1.0;
  3920. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  3921. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  3922. }
  3923. while (len > 0 && conn->ctx->stop_flag == 0) {
  3924. n = pull(fp, conn, buf + nread, len, timeout);
  3925. if (n < 0) {
  3926. if (nread == 0) {
  3927. nread = n; /* Propagate the error */
  3928. }
  3929. break;
  3930. } else if (n == 0) {
  3931. break; /* No more data to read */
  3932. } else {
  3933. conn->consumed_content += n;
  3934. nread += n;
  3935. len -= n;
  3936. }
  3937. }
  3938. return nread;
  3939. }
  3940. static void
  3941. discard_unread_request_data(struct mg_connection *conn)
  3942. {
  3943. char buf[MG_BUF_LEN];
  3944. size_t to_read;
  3945. int nread;
  3946. if (conn == NULL) {
  3947. return;
  3948. }
  3949. to_read = sizeof(buf);
  3950. if (conn->is_chunked) {
  3951. /* Chunked encoding: 1=chunk not read completely, 2=chunk read
  3952. * completely */
  3953. while (conn->is_chunked == 1) {
  3954. nread = mg_read(conn, buf, to_read);
  3955. if (nread <= 0) {
  3956. break;
  3957. }
  3958. }
  3959. } else {
  3960. /* Not chunked: content length is known */
  3961. while (conn->consumed_content < conn->content_len) {
  3962. if (to_read
  3963. > (size_t)(conn->content_len - conn->consumed_content)) {
  3964. to_read = (size_t)(conn->content_len - conn->consumed_content);
  3965. }
  3966. nread = mg_read(conn, buf, to_read);
  3967. if (nread <= 0) {
  3968. break;
  3969. }
  3970. }
  3971. }
  3972. }
  3973. static int
  3974. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  3975. {
  3976. int64_t n, buffered_len, nread;
  3977. int64_t len64 =
  3978. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  3979. * int, we may not read more
  3980. * bytes */
  3981. const char *body;
  3982. if (conn == NULL) {
  3983. return 0;
  3984. }
  3985. /* If Content-Length is not set for a PUT or POST request, read until
  3986. * socket is closed */
  3987. if (conn->consumed_content == 0 && conn->content_len == -1) {
  3988. conn->content_len = INT64_MAX;
  3989. conn->must_close = 1;
  3990. }
  3991. nread = 0;
  3992. if (conn->consumed_content < conn->content_len) {
  3993. /* Adjust number of bytes to read. */
  3994. int64_t left_to_read = conn->content_len - conn->consumed_content;
  3995. if (left_to_read < len64) {
  3996. /* Do not read more than the total content length of the request.
  3997. */
  3998. len64 = left_to_read;
  3999. }
  4000. /* Return buffered data */
  4001. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  4002. - conn->consumed_content;
  4003. if (buffered_len > 0) {
  4004. if (len64 < buffered_len) {
  4005. buffered_len = len64;
  4006. }
  4007. body = conn->buf + conn->request_len + conn->consumed_content;
  4008. memcpy(buf, body, (size_t)buffered_len);
  4009. len64 -= buffered_len;
  4010. conn->consumed_content += buffered_len;
  4011. nread += buffered_len;
  4012. buf = (char *)buf + buffered_len;
  4013. }
  4014. /* We have returned all buffered data. Read new data from the remote
  4015. * socket.
  4016. */
  4017. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  4018. nread += n;
  4019. } else {
  4020. nread = ((nread > 0) ? nread : n);
  4021. }
  4022. }
  4023. return (int)nread;
  4024. }
  4025. static char
  4026. mg_getc(struct mg_connection *conn)
  4027. {
  4028. char c;
  4029. if (conn == NULL) {
  4030. return 0;
  4031. }
  4032. conn->content_len++;
  4033. if (mg_read_inner(conn, &c, 1) <= 0) {
  4034. return (char)0;
  4035. }
  4036. return c;
  4037. }
  4038. int
  4039. mg_read(struct mg_connection *conn, void *buf, size_t len)
  4040. {
  4041. if (len > INT_MAX) {
  4042. len = INT_MAX;
  4043. }
  4044. if (conn == NULL) {
  4045. return 0;
  4046. }
  4047. if (conn->is_chunked) {
  4048. size_t all_read = 0;
  4049. while (len > 0) {
  4050. if (conn->is_chunked == 2) {
  4051. /* No more data left to read */
  4052. return 0;
  4053. }
  4054. if (conn->chunk_remainder) {
  4055. /* copy from the remainder of the last received chunk */
  4056. long read_ret;
  4057. size_t read_now =
  4058. ((conn->chunk_remainder > len) ? (len)
  4059. : (conn->chunk_remainder));
  4060. conn->content_len += (int)read_now;
  4061. read_ret =
  4062. mg_read_inner(conn, (char *)buf + all_read, read_now);
  4063. if (read_ret < 1) {
  4064. /* read error */
  4065. return -1;
  4066. }
  4067. all_read += (size_t)read_ret;
  4068. conn->chunk_remainder -= (size_t)read_ret;
  4069. len -= (size_t)read_ret;
  4070. if (conn->chunk_remainder == 0) {
  4071. /* Add data bytes in the current chunk have been read,
  4072. * so we are expecting \r\n now. */
  4073. char x1 = mg_getc(conn);
  4074. char x2 = mg_getc(conn);
  4075. if ((x1 != '\r') || (x2 != '\n')) {
  4076. /* Protocol violation */
  4077. return -1;
  4078. }
  4079. }
  4080. } else {
  4081. /* fetch a new chunk */
  4082. int i = 0;
  4083. char lenbuf[64];
  4084. char *end = 0;
  4085. unsigned long chunkSize = 0;
  4086. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  4087. lenbuf[i] = mg_getc(conn);
  4088. if (i > 0 && lenbuf[i] == '\r' && lenbuf[i - 1] != '\r') {
  4089. continue;
  4090. }
  4091. if (i > 1 && lenbuf[i] == '\n' && lenbuf[i - 1] == '\r') {
  4092. lenbuf[i + 1] = 0;
  4093. chunkSize = strtoul(lenbuf, &end, 16);
  4094. if (chunkSize == 0) {
  4095. /* regular end of content */
  4096. conn->is_chunked = 2;
  4097. }
  4098. break;
  4099. }
  4100. if (!isxdigit(lenbuf[i])) {
  4101. /* illegal character for chunk length */
  4102. return -1;
  4103. }
  4104. }
  4105. if ((end == NULL) || (*end != '\r')) {
  4106. /* chunksize not set correctly */
  4107. return -1;
  4108. }
  4109. if (chunkSize == 0) {
  4110. break;
  4111. }
  4112. conn->chunk_remainder = chunkSize;
  4113. }
  4114. }
  4115. return (int)all_read;
  4116. }
  4117. return mg_read_inner(conn, buf, len);
  4118. }
  4119. int
  4120. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  4121. {
  4122. time_t now;
  4123. int64_t n, total, allowed;
  4124. if (conn == NULL) {
  4125. return 0;
  4126. }
  4127. if (conn->throttle > 0) {
  4128. if ((now = time(NULL)) != conn->last_throttle_time) {
  4129. conn->last_throttle_time = now;
  4130. conn->last_throttle_bytes = 0;
  4131. }
  4132. allowed = conn->throttle - conn->last_throttle_bytes;
  4133. if (allowed > (int64_t)len) {
  4134. allowed = (int64_t)len;
  4135. }
  4136. if ((total = push_all(conn->ctx,
  4137. NULL,
  4138. conn->client.sock,
  4139. conn->ssl,
  4140. (const char *)buf,
  4141. (int64_t)allowed)) == allowed) {
  4142. buf = (const char *)buf + total;
  4143. conn->last_throttle_bytes += total;
  4144. while (total < (int64_t)len && conn->ctx->stop_flag == 0) {
  4145. allowed = (conn->throttle > ((int64_t)len - total))
  4146. ? (int64_t)len - total
  4147. : conn->throttle;
  4148. if ((n = push_all(conn->ctx,
  4149. NULL,
  4150. conn->client.sock,
  4151. conn->ssl,
  4152. (const char *)buf,
  4153. (int64_t)allowed)) != allowed) {
  4154. break;
  4155. }
  4156. sleep(1);
  4157. conn->last_throttle_bytes = allowed;
  4158. conn->last_throttle_time = time(NULL);
  4159. buf = (const char *)buf + n;
  4160. total += n;
  4161. }
  4162. }
  4163. } else {
  4164. total = push_all(conn->ctx,
  4165. NULL,
  4166. conn->client.sock,
  4167. conn->ssl,
  4168. (const char *)buf,
  4169. (int64_t)len);
  4170. }
  4171. return (int)total;
  4172. }
  4173. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  4174. static int
  4175. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  4176. {
  4177. va_list ap_copy;
  4178. size_t size = MG_BUF_LEN / 4;
  4179. int len = -1;
  4180. *buf = NULL;
  4181. while (len < 0) {
  4182. if (*buf) {
  4183. mg_free(*buf);
  4184. }
  4185. size *= 4;
  4186. *buf = (char *)mg_malloc(size);
  4187. if (!*buf) {
  4188. break;
  4189. }
  4190. va_copy(ap_copy, ap);
  4191. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  4192. va_end(ap_copy);
  4193. (*buf)[size - 1] = 0;
  4194. }
  4195. return len;
  4196. }
  4197. /* Print message to buffer. If buffer is large enough to hold the message,
  4198. * return buffer. If buffer is to small, allocate large enough buffer on heap,
  4199. * and return allocated buffer. */
  4200. static int
  4201. alloc_vprintf(char **out_buf,
  4202. char *prealloc_buf,
  4203. size_t prealloc_size,
  4204. const char *fmt,
  4205. va_list ap)
  4206. {
  4207. va_list ap_copy;
  4208. int len;
  4209. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  4210. * buffer is too small. Also, older versions of msvcrt.dll do not have
  4211. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  4212. * Therefore, we make two passes: on first pass, get required message
  4213. * length.
  4214. * On second pass, actually print the message. */
  4215. va_copy(ap_copy, ap);
  4216. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  4217. va_end(ap_copy);
  4218. if (len < 0) {
  4219. /* C runtime is not standard compliant, vsnprintf() returned -1.
  4220. * Switch to alternative code path that uses incremental allocations.
  4221. */
  4222. va_copy(ap_copy, ap);
  4223. len = alloc_vprintf2(out_buf, fmt, ap);
  4224. va_end(ap_copy);
  4225. } else if ((size_t)(len) >= prealloc_size) {
  4226. /* The pre-allocated buffer not large enough. */
  4227. /* Allocate a new buffer. */
  4228. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  4229. if (!*out_buf) {
  4230. /* Allocation failed. Return -1 as "out of memory" error. */
  4231. return -1;
  4232. }
  4233. /* Buffer allocation successful. Store the string there. */
  4234. va_copy(ap_copy, ap);
  4235. IGNORE_UNUSED_RESULT(
  4236. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  4237. va_end(ap_copy);
  4238. } else {
  4239. /* The pre-allocated buffer is large enough.
  4240. * Use it to store the string and return the address. */
  4241. va_copy(ap_copy, ap);
  4242. IGNORE_UNUSED_RESULT(
  4243. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  4244. va_end(ap_copy);
  4245. *out_buf = prealloc_buf;
  4246. }
  4247. return len;
  4248. }
  4249. static int
  4250. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  4251. {
  4252. char mem[MG_BUF_LEN];
  4253. char *buf = NULL;
  4254. int len;
  4255. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  4256. len = mg_write(conn, buf, (size_t)len);
  4257. }
  4258. if (buf != mem && buf != NULL) {
  4259. mg_free(buf);
  4260. }
  4261. return len;
  4262. }
  4263. int
  4264. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  4265. {
  4266. va_list ap;
  4267. int result;
  4268. va_start(ap, fmt);
  4269. result = mg_vprintf(conn, fmt, ap);
  4270. va_end(ap);
  4271. return result;
  4272. }
  4273. int
  4274. mg_url_decode(const char *src,
  4275. int src_len,
  4276. char *dst,
  4277. int dst_len,
  4278. int is_form_url_encoded)
  4279. {
  4280. int i, j, a, b;
  4281. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  4282. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  4283. if (i < src_len - 2 && src[i] == '%'
  4284. && isxdigit(*(const unsigned char *)(src + i + 1))
  4285. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  4286. a = tolower(*(const unsigned char *)(src + i + 1));
  4287. b = tolower(*(const unsigned char *)(src + i + 2));
  4288. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  4289. i += 2;
  4290. } else if (is_form_url_encoded && src[i] == '+') {
  4291. dst[j] = ' ';
  4292. } else {
  4293. dst[j] = src[i];
  4294. }
  4295. }
  4296. dst[j] = '\0'; /* Null-terminate the destination */
  4297. return (i >= src_len) ? j : -1;
  4298. }
  4299. int
  4300. mg_get_var(const char *data,
  4301. size_t data_len,
  4302. const char *name,
  4303. char *dst,
  4304. size_t dst_len)
  4305. {
  4306. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  4307. }
  4308. int
  4309. mg_get_var2(const char *data,
  4310. size_t data_len,
  4311. const char *name,
  4312. char *dst,
  4313. size_t dst_len,
  4314. size_t occurrence)
  4315. {
  4316. const char *p, *e, *s;
  4317. size_t name_len;
  4318. int len;
  4319. if (dst == NULL || dst_len == 0) {
  4320. len = -2;
  4321. } else if (data == NULL || name == NULL || data_len == 0) {
  4322. len = -1;
  4323. dst[0] = '\0';
  4324. } else {
  4325. name_len = strlen(name);
  4326. e = data + data_len;
  4327. len = -1;
  4328. dst[0] = '\0';
  4329. /* data is "var1=val1&var2=val2...". Find variable first */
  4330. for (p = data; p + name_len < e; p++) {
  4331. if ((p == data || p[-1] == '&') && p[name_len] == '='
  4332. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  4333. /* Point p to variable value */
  4334. p += name_len + 1;
  4335. /* Point s to the end of the value */
  4336. s = (const char *)memchr(p, '&', (size_t)(e - p));
  4337. if (s == NULL) {
  4338. s = e;
  4339. }
  4340. /* assert(s >= p); */
  4341. if (s < p) {
  4342. return -3;
  4343. }
  4344. /* Decode variable into destination buffer */
  4345. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  4346. /* Redirect error code from -1 to -2 (destination buffer too
  4347. * small). */
  4348. if (len == -1) {
  4349. len = -2;
  4350. }
  4351. break;
  4352. }
  4353. }
  4354. }
  4355. return len;
  4356. }
  4357. /* HCP24: some changes to compare hole var_name */
  4358. int
  4359. mg_get_cookie(const char *cookie_header,
  4360. const char *var_name,
  4361. char *dst,
  4362. size_t dst_size)
  4363. {
  4364. const char *s, *p, *end;
  4365. int name_len, len = -1;
  4366. if (dst == NULL || dst_size == 0) {
  4367. return -2;
  4368. }
  4369. dst[0] = '\0';
  4370. if (var_name == NULL || (s = cookie_header) == NULL) {
  4371. return -1;
  4372. }
  4373. name_len = (int)strlen(var_name);
  4374. end = s + strlen(s);
  4375. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  4376. if (s[name_len] == '=') {
  4377. /* HCP24: now check is it a substring or a full cookie name */
  4378. if ((s == cookie_header) || (s[-1] == ' ')) {
  4379. s += name_len + 1;
  4380. if ((p = strchr(s, ' ')) == NULL) {
  4381. p = end;
  4382. }
  4383. if (p[-1] == ';') {
  4384. p--;
  4385. }
  4386. if (*s == '"' && p[-1] == '"' && p > s + 1) {
  4387. s++;
  4388. p--;
  4389. }
  4390. if ((size_t)(p - s) < dst_size) {
  4391. len = (int)(p - s);
  4392. mg_strlcpy(dst, s, (size_t)len + 1);
  4393. } else {
  4394. len = -3;
  4395. }
  4396. break;
  4397. }
  4398. }
  4399. }
  4400. return len;
  4401. }
  4402. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  4403. static void
  4404. base64_encode(const unsigned char *src, int src_len, char *dst)
  4405. {
  4406. static const char *b64 =
  4407. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  4408. int i, j, a, b, c;
  4409. for (i = j = 0; i < src_len; i += 3) {
  4410. a = src[i];
  4411. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  4412. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  4413. dst[j++] = b64[a >> 2];
  4414. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  4415. if (i + 1 < src_len) {
  4416. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  4417. }
  4418. if (i + 2 < src_len) {
  4419. dst[j++] = b64[c & 63];
  4420. }
  4421. }
  4422. while (j % 4 != 0) {
  4423. dst[j++] = '=';
  4424. }
  4425. dst[j++] = '\0';
  4426. }
  4427. #endif
  4428. #if defined(USE_LUA)
  4429. static unsigned char
  4430. b64reverse(char letter)
  4431. {
  4432. if (letter >= 'A' && letter <= 'Z') {
  4433. return letter - 'A';
  4434. }
  4435. if (letter >= 'a' && letter <= 'z') {
  4436. return letter - 'a' + 26;
  4437. }
  4438. if (letter >= '0' && letter <= '9') {
  4439. return letter - '0' + 52;
  4440. }
  4441. if (letter == '+') {
  4442. return 62;
  4443. }
  4444. if (letter == '/') {
  4445. return 63;
  4446. }
  4447. if (letter == '=') {
  4448. return 255; /* normal end */
  4449. }
  4450. return 254; /* error */
  4451. }
  4452. static int
  4453. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  4454. {
  4455. int i;
  4456. unsigned char a, b, c, d;
  4457. *dst_len = 0;
  4458. for (i = 0; i < src_len; i += 4) {
  4459. a = b64reverse(src[i]);
  4460. if (a >= 254) {
  4461. return i;
  4462. }
  4463. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  4464. if (b >= 254) {
  4465. return i + 1;
  4466. }
  4467. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  4468. if (c == 254) {
  4469. return i + 2;
  4470. }
  4471. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  4472. if (d == 254) {
  4473. return i + 3;
  4474. }
  4475. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  4476. if (c != 255) {
  4477. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  4478. if (d != 255) {
  4479. dst[(*dst_len)++] = (c << 6) + d;
  4480. }
  4481. }
  4482. }
  4483. return -1;
  4484. }
  4485. #endif
  4486. static int
  4487. is_put_or_delete_method(const struct mg_connection *conn)
  4488. {
  4489. if (conn) {
  4490. const char *s = conn->request_info.request_method;
  4491. return s != NULL && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  4492. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  4493. }
  4494. return 0;
  4495. }
  4496. static void
  4497. interpret_uri(struct mg_connection *conn, /* in: request (must be valid) */
  4498. char *filename, /* out: filename */
  4499. size_t filename_buf_len, /* in: size of filename buffer */
  4500. struct mg_file_stat *filestat, /* out: file structure */
  4501. int *is_found, /* out: file found (directly) */
  4502. int *is_script_resource, /* out: handled by a script? */
  4503. int *is_websocket_request, /* out: websocket connetion? */
  4504. int *is_put_or_delete_request /* out: put/delete a file? */
  4505. )
  4506. {
  4507. /* TODO (high): Restructure this function */
  4508. #if !defined(NO_FILES)
  4509. const char *uri = conn->request_info.local_uri;
  4510. const char *root = conn->ctx->config[DOCUMENT_ROOT];
  4511. const char *rewrite;
  4512. struct vec a, b;
  4513. int match_len;
  4514. char gz_path[PATH_MAX];
  4515. char const *accept_encoding;
  4516. int truncated;
  4517. #if !defined(NO_CGI) || defined(USE_LUA)
  4518. char *p;
  4519. #endif
  4520. #else
  4521. (void)filename_buf_len; /* unused if NO_FILES is defined */
  4522. #endif
  4523. memset(filestat, 0, sizeof(*filestat));
  4524. *filename = 0;
  4525. *is_found = 0;
  4526. *is_script_resource = 0;
  4527. *is_put_or_delete_request = is_put_or_delete_method(conn);
  4528. #if defined(USE_WEBSOCKET)
  4529. *is_websocket_request = is_websocket_protocol(conn);
  4530. #if !defined(NO_FILES)
  4531. if (*is_websocket_request && conn->ctx->config[WEBSOCKET_ROOT]) {
  4532. root = conn->ctx->config[WEBSOCKET_ROOT];
  4533. }
  4534. #endif /* !NO_FILES */
  4535. #else /* USE_WEBSOCKET */
  4536. *is_websocket_request = 0;
  4537. #endif /* USE_WEBSOCKET */
  4538. #if !defined(NO_FILES)
  4539. /* Note that root == NULL is a regular use case here. This occurs,
  4540. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  4541. * config is not required. */
  4542. if (root == NULL) {
  4543. /* all file related outputs have already been set to 0, just return
  4544. */
  4545. return;
  4546. }
  4547. /* Using buf_len - 1 because memmove() for PATH_INFO may shift part
  4548. * of the path one byte on the right.
  4549. * If document_root is NULL, leave the file empty. */
  4550. mg_snprintf(
  4551. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  4552. if (truncated) {
  4553. goto interpret_cleanup;
  4554. }
  4555. rewrite = conn->ctx->config[REWRITE];
  4556. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  4557. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  4558. mg_snprintf(conn,
  4559. &truncated,
  4560. filename,
  4561. filename_buf_len - 1,
  4562. "%.*s%s",
  4563. (int)b.len,
  4564. b.ptr,
  4565. uri + match_len);
  4566. break;
  4567. }
  4568. }
  4569. if (truncated) {
  4570. goto interpret_cleanup;
  4571. }
  4572. /* Local file path and name, corresponding to requested URI
  4573. * is now stored in "filename" variable. */
  4574. if (mg_stat(conn, filename, filestat)) {
  4575. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  4576. /* File exists. Check if it is a script type. */
  4577. if (0
  4578. #if !defined(NO_CGI)
  4579. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  4580. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4581. filename) > 0
  4582. #endif
  4583. #if defined(USE_LUA)
  4584. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  4585. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  4586. filename) > 0
  4587. #endif
  4588. #if defined(USE_DUKTAPE)
  4589. || match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  4590. strlen(
  4591. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  4592. filename) > 0
  4593. #endif
  4594. ) {
  4595. /* The request addresses a CGI script or a Lua script. The URI
  4596. * corresponds to the script itself (like /path/script.cgi),
  4597. * and there is no additional resource path
  4598. * (like /path/script.cgi/something).
  4599. * Requests that modify (replace or delete) a resource, like
  4600. * PUT and DELETE requests, should replace/delete the script
  4601. * file.
  4602. * Requests that read or write from/to a resource, like GET and
  4603. * POST requests, should call the script and return the
  4604. * generated response. */
  4605. *is_script_resource = !*is_put_or_delete_request;
  4606. }
  4607. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  4608. *is_found = 1;
  4609. return;
  4610. }
  4611. /* If we can't find the actual file, look for the file
  4612. * with the same name but a .gz extension. If we find it,
  4613. * use that and set the gzipped flag in the file struct
  4614. * to indicate that the response need to have the content-
  4615. * encoding: gzip header.
  4616. * We can only do this if the browser declares support. */
  4617. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  4618. if (strstr(accept_encoding, "gzip") != NULL) {
  4619. mg_snprintf(
  4620. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  4621. if (truncated) {
  4622. goto interpret_cleanup;
  4623. }
  4624. if (mg_stat(conn, gz_path, filestat)) {
  4625. if (filestat) {
  4626. filestat->is_gzipped = 1;
  4627. *is_found = 1;
  4628. }
  4629. /* Currently gz files can not be scripts. */
  4630. return;
  4631. }
  4632. }
  4633. }
  4634. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  4635. /* Support PATH_INFO for CGI scripts. */
  4636. for (p = filename + strlen(filename); p > filename + 1; p--) {
  4637. if (*p == '/') {
  4638. *p = '\0';
  4639. if ((0
  4640. #if !defined(NO_CGI)
  4641. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  4642. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4643. filename) > 0
  4644. #endif
  4645. #if defined(USE_LUA)
  4646. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  4647. strlen(
  4648. conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  4649. filename) > 0
  4650. #endif
  4651. #if defined(USE_DUKTAPE)
  4652. || match_prefix(
  4653. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  4654. strlen(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  4655. filename) > 0
  4656. #endif
  4657. ) && mg_stat(conn, filename, filestat)) {
  4658. /* Shift PATH_INFO block one character right, e.g.
  4659. * "/x.cgi/foo/bar\x00" => "/x.cgi\x00/foo/bar\x00"
  4660. * conn->path_info is pointing to the local variable "path"
  4661. * declared in handle_request(), so PATH_INFO is not valid
  4662. * after handle_request returns. */
  4663. conn->path_info = p + 1;
  4664. memmove(p + 2, p + 1, strlen(p + 1) + 1); /* +1 is for
  4665. * trailing \0 */
  4666. p[1] = '/';
  4667. *is_script_resource = 1;
  4668. break;
  4669. } else {
  4670. *p = '/';
  4671. }
  4672. }
  4673. }
  4674. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  4675. #endif /* !defined(NO_FILES) */
  4676. return;
  4677. #if !defined(NO_FILES)
  4678. /* Reset all outputs */
  4679. interpret_cleanup:
  4680. memset(filestat, 0, sizeof(*filestat));
  4681. *filename = 0;
  4682. *is_found = 0;
  4683. *is_script_resource = 0;
  4684. *is_websocket_request = 0;
  4685. *is_put_or_delete_request = 0;
  4686. #endif /* !defined(NO_FILES) */
  4687. }
  4688. /* Check whether full request is buffered. Return:
  4689. * -1 if request is malformed
  4690. * 0 if request is not yet fully buffered
  4691. * >0 actual request length, including last \r\n\r\n */
  4692. static int
  4693. get_request_len(const char *buf, int buflen)
  4694. {
  4695. const char *s, *e;
  4696. int len = 0;
  4697. for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
  4698. /* Control characters are not allowed but >=128 is. */
  4699. if (!isprint(*(const unsigned char *)s) && *s != '\r' && *s != '\n'
  4700. && *(const unsigned char *)s < 128) {
  4701. len = -1;
  4702. break; /* [i_a] abort scan as soon as one malformed character is
  4703. * found; */
  4704. /* don't let subsequent \r\n\r\n win us over anyhow */
  4705. } else if (s[0] == '\n' && s[1] == '\n') {
  4706. len = (int)(s - buf) + 2;
  4707. } else if (s[0] == '\n' && &s[1] < e && s[1] == '\r' && s[2] == '\n') {
  4708. len = (int)(s - buf) + 3;
  4709. }
  4710. return len;
  4711. }
  4712. #if !defined(NO_CACHING)
  4713. /* Convert month to the month number. Return -1 on error, or month number */
  4714. static int
  4715. get_month_index(const char *s)
  4716. {
  4717. size_t i;
  4718. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  4719. if (!strcmp(s, month_names[i])) {
  4720. return (int)i;
  4721. }
  4722. }
  4723. return -1;
  4724. }
  4725. /* Parse UTC date-time string, and return the corresponding time_t value. */
  4726. static time_t
  4727. parse_date_string(const char *datetime)
  4728. {
  4729. char month_str[32] = {0};
  4730. int second, minute, hour, day, month, year;
  4731. time_t result = (time_t)0;
  4732. struct tm tm;
  4733. if ((sscanf(datetime,
  4734. "%d/%3s/%d %d:%d:%d",
  4735. &day,
  4736. month_str,
  4737. &year,
  4738. &hour,
  4739. &minute,
  4740. &second) == 6) || (sscanf(datetime,
  4741. "%d %3s %d %d:%d:%d",
  4742. &day,
  4743. month_str,
  4744. &year,
  4745. &hour,
  4746. &minute,
  4747. &second) == 6)
  4748. || (sscanf(datetime,
  4749. "%*3s, %d %3s %d %d:%d:%d",
  4750. &day,
  4751. month_str,
  4752. &year,
  4753. &hour,
  4754. &minute,
  4755. &second) == 6) || (sscanf(datetime,
  4756. "%d-%3s-%d %d:%d:%d",
  4757. &day,
  4758. month_str,
  4759. &year,
  4760. &hour,
  4761. &minute,
  4762. &second) == 6)) {
  4763. month = get_month_index(month_str);
  4764. if ((month >= 0) && (year >= 1970)) {
  4765. memset(&tm, 0, sizeof(tm));
  4766. tm.tm_year = year - 1900;
  4767. tm.tm_mon = month;
  4768. tm.tm_mday = day;
  4769. tm.tm_hour = hour;
  4770. tm.tm_min = minute;
  4771. tm.tm_sec = second;
  4772. result = timegm(&tm);
  4773. }
  4774. }
  4775. return result;
  4776. }
  4777. #endif /* !NO_CACHING */
  4778. /* Protect against directory disclosure attack by removing '..',
  4779. * excessive '/' and '\' characters */
  4780. static void
  4781. remove_double_dots_and_double_slashes(char *s)
  4782. {
  4783. char *p = s;
  4784. while ((s[0] == '.') && (s[1] == '.')) {
  4785. s++;
  4786. }
  4787. while (*s != '\0') {
  4788. *p++ = *s++;
  4789. if (s[-1] == '/' || s[-1] == '\\') {
  4790. /* Skip all following slashes, backslashes and double-dots */
  4791. while (s[0] != '\0') {
  4792. if (s[0] == '/' || s[0] == '\\') {
  4793. s++;
  4794. } else if (s[0] == '.' && s[1] == '.') {
  4795. s += 2;
  4796. } else {
  4797. break;
  4798. }
  4799. }
  4800. }
  4801. }
  4802. *p = '\0';
  4803. }
  4804. static const struct {
  4805. const char *extension;
  4806. size_t ext_len;
  4807. const char *mime_type;
  4808. } builtin_mime_types[] = {
  4809. /* IANA registered MIME types (http://www.iana.org/assignments/media-types)
  4810. * application types */
  4811. {".doc", 4, "application/msword"},
  4812. {".eps", 4, "application/postscript"},
  4813. {".exe", 4, "application/octet-stream"},
  4814. {".js", 3, "application/javascript"},
  4815. {".json", 5, "application/json"},
  4816. {".pdf", 4, "application/pdf"},
  4817. {".ps", 3, "application/postscript"},
  4818. {".rtf", 4, "application/rtf"},
  4819. {".xhtml", 6, "application/xhtml+xml"},
  4820. {".xsl", 4, "application/xml"},
  4821. {".xslt", 5, "application/xml"},
  4822. /* fonts */
  4823. {".ttf", 4, "application/font-sfnt"},
  4824. {".cff", 4, "application/font-sfnt"},
  4825. {".otf", 4, "application/font-sfnt"},
  4826. {".aat", 4, "application/font-sfnt"},
  4827. {".sil", 4, "application/font-sfnt"},
  4828. {".pfr", 4, "application/font-tdpfr"},
  4829. {".woff", 5, "application/font-woff"},
  4830. /* audio */
  4831. {".mp3", 4, "audio/mpeg"},
  4832. {".oga", 4, "audio/ogg"},
  4833. {".ogg", 4, "audio/ogg"},
  4834. /* image */
  4835. {".gif", 4, "image/gif"},
  4836. {".ief", 4, "image/ief"},
  4837. {".jpeg", 5, "image/jpeg"},
  4838. {".jpg", 4, "image/jpeg"},
  4839. {".jpm", 4, "image/jpm"},
  4840. {".jpx", 4, "image/jpx"},
  4841. {".png", 4, "image/png"},
  4842. {".svg", 4, "image/svg+xml"},
  4843. {".tif", 4, "image/tiff"},
  4844. {".tiff", 5, "image/tiff"},
  4845. /* model */
  4846. {".wrl", 4, "model/vrml"},
  4847. /* text */
  4848. {".css", 4, "text/css"},
  4849. {".csv", 4, "text/csv"},
  4850. {".htm", 4, "text/html"},
  4851. {".html", 5, "text/html"},
  4852. {".sgm", 4, "text/sgml"},
  4853. {".shtm", 5, "text/html"},
  4854. {".shtml", 6, "text/html"},
  4855. {".txt", 4, "text/plain"},
  4856. {".xml", 4, "text/xml"},
  4857. /* video */
  4858. {".mov", 4, "video/quicktime"},
  4859. {".mp4", 4, "video/mp4"},
  4860. {".mpeg", 5, "video/mpeg"},
  4861. {".mpg", 4, "video/mpeg"},
  4862. {".ogv", 4, "video/ogg"},
  4863. {".qt", 3, "video/quicktime"},
  4864. /* not registered types
  4865. * (http://reference.sitepoint.com/html/mime-types-full,
  4866. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  4867. {".arj", 4, "application/x-arj-compressed"},
  4868. {".gz", 3, "application/x-gunzip"},
  4869. {".rar", 4, "application/x-arj-compressed"},
  4870. {".swf", 4, "application/x-shockwave-flash"},
  4871. {".tar", 4, "application/x-tar"},
  4872. {".tgz", 4, "application/x-tar-gz"},
  4873. {".torrent", 8, "application/x-bittorrent"},
  4874. {".ppt", 4, "application/x-mspowerpoint"},
  4875. {".xls", 4, "application/x-msexcel"},
  4876. {".zip", 4, "application/x-zip-compressed"},
  4877. {".aac",
  4878. 4,
  4879. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  4880. {".aif", 4, "audio/x-aif"},
  4881. {".m3u", 4, "audio/x-mpegurl"},
  4882. {".mid", 4, "audio/x-midi"},
  4883. {".ra", 3, "audio/x-pn-realaudio"},
  4884. {".ram", 4, "audio/x-pn-realaudio"},
  4885. {".wav", 4, "audio/x-wav"},
  4886. {".bmp", 4, "image/bmp"},
  4887. {".ico", 4, "image/x-icon"},
  4888. {".pct", 4, "image/x-pct"},
  4889. {".pict", 5, "image/pict"},
  4890. {".rgb", 4, "image/x-rgb"},
  4891. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  4892. {".asf", 4, "video/x-ms-asf"},
  4893. {".avi", 4, "video/x-msvideo"},
  4894. {".m4v", 4, "video/x-m4v"},
  4895. {NULL, 0, NULL}};
  4896. const char *
  4897. mg_get_builtin_mime_type(const char *path)
  4898. {
  4899. const char *ext;
  4900. size_t i, path_len;
  4901. path_len = strlen(path);
  4902. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  4903. ext = path + (path_len - builtin_mime_types[i].ext_len);
  4904. if (path_len > builtin_mime_types[i].ext_len
  4905. && mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {
  4906. return builtin_mime_types[i].mime_type;
  4907. }
  4908. }
  4909. return "text/plain";
  4910. }
  4911. /* Look at the "path" extension and figure what mime type it has.
  4912. * Store mime type in the vector. */
  4913. static void
  4914. get_mime_type(struct mg_context *ctx, const char *path, struct vec *vec)
  4915. {
  4916. struct vec ext_vec, mime_vec;
  4917. const char *list, *ext;
  4918. size_t path_len;
  4919. path_len = strlen(path);
  4920. if (ctx == NULL || vec == NULL) {
  4921. return;
  4922. }
  4923. /* Scan user-defined mime types first, in case user wants to
  4924. * override default mime types. */
  4925. list = ctx->config[EXTRA_MIME_TYPES];
  4926. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  4927. /* ext now points to the path suffix */
  4928. ext = path + path_len - ext_vec.len;
  4929. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  4930. *vec = mime_vec;
  4931. return;
  4932. }
  4933. }
  4934. vec->ptr = mg_get_builtin_mime_type(path);
  4935. vec->len = strlen(vec->ptr);
  4936. }
  4937. /* Stringify binary data. Output buffer must be twice as big as input,
  4938. * because each byte takes 2 bytes in string representation */
  4939. static void
  4940. bin2str(char *to, const unsigned char *p, size_t len)
  4941. {
  4942. static const char *hex = "0123456789abcdef";
  4943. for (; len--; p++) {
  4944. *to++ = hex[p[0] >> 4];
  4945. *to++ = hex[p[0] & 0x0f];
  4946. }
  4947. *to = '\0';
  4948. }
  4949. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes. */
  4950. char *
  4951. mg_md5(char buf[33], ...)
  4952. {
  4953. md5_byte_t hash[16];
  4954. const char *p;
  4955. va_list ap;
  4956. md5_state_t ctx;
  4957. md5_init(&ctx);
  4958. va_start(ap, buf);
  4959. while ((p = va_arg(ap, const char *)) != NULL) {
  4960. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  4961. }
  4962. va_end(ap);
  4963. md5_finish(&ctx, hash);
  4964. bin2str(buf, hash, sizeof(hash));
  4965. return buf;
  4966. }
  4967. /* Check the user's password, return 1 if OK */
  4968. static int
  4969. check_password(const char *method,
  4970. const char *ha1,
  4971. const char *uri,
  4972. const char *nonce,
  4973. const char *nc,
  4974. const char *cnonce,
  4975. const char *qop,
  4976. const char *response)
  4977. {
  4978. char ha2[32 + 1], expected_response[32 + 1];
  4979. /* Some of the parameters may be NULL */
  4980. if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL
  4981. || qop == NULL
  4982. || response == NULL) {
  4983. return 0;
  4984. }
  4985. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  4986. if (strlen(response) != 32) {
  4987. return 0;
  4988. }
  4989. mg_md5(ha2, method, ":", uri, NULL);
  4990. mg_md5(expected_response,
  4991. ha1,
  4992. ":",
  4993. nonce,
  4994. ":",
  4995. nc,
  4996. ":",
  4997. cnonce,
  4998. ":",
  4999. qop,
  5000. ":",
  5001. ha2,
  5002. NULL);
  5003. return mg_strcasecmp(response, expected_response) == 0;
  5004. }
  5005. /* Use the global passwords file, if specified by auth_gpass option,
  5006. * or search for .htpasswd in the requested directory. */
  5007. static void
  5008. open_auth_file(struct mg_connection *conn,
  5009. const char *path,
  5010. struct mg_file *filep)
  5011. {
  5012. if (conn != NULL && conn->ctx != NULL) {
  5013. char name[PATH_MAX];
  5014. const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
  5015. int truncated;
  5016. if (gpass != NULL) {
  5017. /* Use global passwords file */
  5018. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  5019. #ifdef DEBUG
  5020. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  5021. #endif
  5022. }
  5023. /* Important: using local struct mg_file to test path for
  5024. * is_directory
  5025. * flag. If filep is used, mg_stat() makes it appear as if auth file
  5026. * was opened. TODO: mg_stat must not make anything appear to be
  5027. * opened */
  5028. } else if (mg_stat(conn, path, &filep->stat)
  5029. && filep->stat.is_directory) {
  5030. mg_snprintf(conn,
  5031. &truncated,
  5032. name,
  5033. sizeof(name),
  5034. "%s/%s",
  5035. path,
  5036. PASSWORDS_FILE_NAME);
  5037. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  5038. #ifdef DEBUG
  5039. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  5040. #endif
  5041. }
  5042. } else {
  5043. /* Try to find .htpasswd in requested directory. */
  5044. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  5045. if (e[0] == '/') {
  5046. break;
  5047. }
  5048. }
  5049. mg_snprintf(conn,
  5050. &truncated,
  5051. name,
  5052. sizeof(name),
  5053. "%.*s/%s",
  5054. (int)(e - p),
  5055. p,
  5056. PASSWORDS_FILE_NAME);
  5057. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  5058. #ifdef DEBUG
  5059. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  5060. #endif
  5061. }
  5062. }
  5063. }
  5064. }
  5065. /* Parsed Authorization header */
  5066. struct ah {
  5067. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  5068. };
  5069. /* Return 1 on success. Always initializes the ah structure. */
  5070. static int
  5071. parse_auth_header(struct mg_connection *conn,
  5072. char *buf,
  5073. size_t buf_size,
  5074. struct ah *ah)
  5075. {
  5076. char *name, *value, *s;
  5077. const char *auth_header;
  5078. uint64_t nonce;
  5079. if (!ah || !conn) {
  5080. return 0;
  5081. }
  5082. (void)memset(ah, 0, sizeof(*ah));
  5083. if ((auth_header = mg_get_header(conn, "Authorization")) == NULL
  5084. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  5085. return 0;
  5086. }
  5087. /* Make modifiable copy of the auth header */
  5088. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  5089. s = buf;
  5090. /* Parse authorization header */
  5091. for (;;) {
  5092. /* Gobble initial spaces */
  5093. while (isspace(*(unsigned char *)s)) {
  5094. s++;
  5095. }
  5096. name = skip_quoted(&s, "=", " ", 0);
  5097. /* Value is either quote-delimited, or ends at first comma or space. */
  5098. if (s[0] == '\"') {
  5099. s++;
  5100. value = skip_quoted(&s, "\"", " ", '\\');
  5101. if (s[0] == ',') {
  5102. s++;
  5103. }
  5104. } else {
  5105. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  5106. * spaces */
  5107. }
  5108. if (*name == '\0') {
  5109. break;
  5110. }
  5111. if (!strcmp(name, "username")) {
  5112. ah->user = value;
  5113. } else if (!strcmp(name, "cnonce")) {
  5114. ah->cnonce = value;
  5115. } else if (!strcmp(name, "response")) {
  5116. ah->response = value;
  5117. } else if (!strcmp(name, "uri")) {
  5118. ah->uri = value;
  5119. } else if (!strcmp(name, "qop")) {
  5120. ah->qop = value;
  5121. } else if (!strcmp(name, "nc")) {
  5122. ah->nc = value;
  5123. } else if (!strcmp(name, "nonce")) {
  5124. ah->nonce = value;
  5125. }
  5126. }
  5127. #ifndef NO_NONCE_CHECK
  5128. /* Read the nonce from the response. */
  5129. if (ah->nonce == NULL) {
  5130. return 0;
  5131. }
  5132. s = NULL;
  5133. nonce = strtoull(ah->nonce, &s, 10);
  5134. if ((s == NULL) || (*s != 0)) {
  5135. return 0;
  5136. }
  5137. /* Convert the nonce from the client to a number. */
  5138. nonce ^= conn->ctx->auth_nonce_mask;
  5139. /* The converted number corresponds to the time the nounce has been
  5140. * created. This should not be earlier than the server start. */
  5141. /* Server side nonce check is valuable in all situations but one:
  5142. * if the server restarts frequently, but the client should not see
  5143. * that, so the server should accept nonces from previous starts. */
  5144. /* However, the reasonable default is to not accept a nonce from a
  5145. * previous start, so if anyone changed the access rights between
  5146. * two restarts, a new login is required. */
  5147. if (nonce < (uint64_t)conn->ctx->start_time) {
  5148. /* nonce is from a previous start of the server and no longer valid
  5149. * (replay attack?) */
  5150. return 0;
  5151. }
  5152. /* Check if the nonce is too high, so it has not (yet) been used by the
  5153. * server. */
  5154. if (nonce >= ((uint64_t)conn->ctx->start_time + conn->ctx->nonce_count)) {
  5155. return 0;
  5156. }
  5157. #else
  5158. (void)nonce;
  5159. #endif
  5160. /* CGI needs it as REMOTE_USER */
  5161. if (ah->user != NULL) {
  5162. conn->request_info.remote_user = mg_strdup(ah->user);
  5163. } else {
  5164. return 0;
  5165. }
  5166. return 1;
  5167. }
  5168. static const char *
  5169. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  5170. {
  5171. const char *eof;
  5172. size_t len;
  5173. const char *memend;
  5174. if (!filep) {
  5175. return NULL;
  5176. }
  5177. if (filep->access.membuf != NULL && *p != NULL) {
  5178. memend = (const char *)&filep->access.membuf[filep->stat.size];
  5179. /* Search for \n from p till the end of stream */
  5180. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  5181. if (eof != NULL) {
  5182. eof += 1; /* Include \n */
  5183. } else {
  5184. eof = memend; /* Copy remaining data */
  5185. }
  5186. len =
  5187. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  5188. memcpy(buf, *p, len);
  5189. buf[len] = '\0';
  5190. *p += len;
  5191. return len ? eof : NULL;
  5192. } else if (filep->access.fp != NULL) {
  5193. return fgets(buf, (int)size, filep->access.fp);
  5194. } else {
  5195. return NULL;
  5196. }
  5197. }
  5198. struct read_auth_file_struct {
  5199. struct mg_connection *conn;
  5200. struct ah ah;
  5201. char *domain;
  5202. char buf[256 + 256 + 40];
  5203. char *f_user;
  5204. char *f_domain;
  5205. char *f_ha1;
  5206. };
  5207. static int
  5208. read_auth_file(struct mg_file *filep, struct read_auth_file_struct *workdata)
  5209. {
  5210. char *p;
  5211. int is_authorized = 0;
  5212. struct mg_file fp;
  5213. size_t l;
  5214. if (!filep || !workdata) {
  5215. return 0;
  5216. }
  5217. /* Loop over passwords file */
  5218. p = (char *)filep->access.membuf;
  5219. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  5220. l = strlen(workdata->buf);
  5221. while (l > 0) {
  5222. if (isspace(workdata->buf[l - 1])
  5223. || iscntrl(workdata->buf[l - 1])) {
  5224. l--;
  5225. workdata->buf[l] = 0;
  5226. } else
  5227. break;
  5228. }
  5229. if (l < 1) {
  5230. continue;
  5231. }
  5232. workdata->f_user = workdata->buf;
  5233. if (workdata->f_user[0] == ':') {
  5234. /* user names may not contain a ':' and may not be empty,
  5235. * so lines starting with ':' may be used for a special purpose */
  5236. if (workdata->f_user[1] == '#') {
  5237. /* :# is a comment */
  5238. continue;
  5239. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  5240. if (mg_fopen(workdata->conn,
  5241. workdata->f_user + 9,
  5242. MG_FOPEN_MODE_READ,
  5243. &fp)) {
  5244. is_authorized = read_auth_file(&fp, workdata);
  5245. (void)mg_fclose(
  5246. &fp.access); /* ignore error on read only file */
  5247. } else {
  5248. mg_cry(workdata->conn,
  5249. "%s: cannot open authorization file: %s",
  5250. __func__,
  5251. workdata->buf);
  5252. }
  5253. continue;
  5254. }
  5255. /* everything is invalid for the moment (might change in the
  5256. * future) */
  5257. mg_cry(workdata->conn,
  5258. "%s: syntax error in authorization file: %s",
  5259. __func__,
  5260. workdata->buf);
  5261. continue;
  5262. }
  5263. workdata->f_domain = strchr(workdata->f_user, ':');
  5264. if (workdata->f_domain == NULL) {
  5265. mg_cry(workdata->conn,
  5266. "%s: syntax error in authorization file: %s",
  5267. __func__,
  5268. workdata->buf);
  5269. continue;
  5270. }
  5271. *(workdata->f_domain) = 0;
  5272. (workdata->f_domain)++;
  5273. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  5274. if (workdata->f_ha1 == NULL) {
  5275. mg_cry(workdata->conn,
  5276. "%s: syntax error in authorization file: %s",
  5277. __func__,
  5278. workdata->buf);
  5279. continue;
  5280. }
  5281. *(workdata->f_ha1) = 0;
  5282. (workdata->f_ha1)++;
  5283. if (!strcmp(workdata->ah.user, workdata->f_user)
  5284. && !strcmp(workdata->domain, workdata->f_domain)) {
  5285. return check_password(workdata->conn->request_info.request_method,
  5286. workdata->f_ha1,
  5287. workdata->ah.uri,
  5288. workdata->ah.nonce,
  5289. workdata->ah.nc,
  5290. workdata->ah.cnonce,
  5291. workdata->ah.qop,
  5292. workdata->ah.response);
  5293. }
  5294. }
  5295. return is_authorized;
  5296. }
  5297. /* Authorize against the opened passwords file. Return 1 if authorized. */
  5298. static int
  5299. authorize(struct mg_connection *conn, struct mg_file *filep)
  5300. {
  5301. struct read_auth_file_struct workdata;
  5302. char buf[MG_BUF_LEN];
  5303. if (!conn || !conn->ctx) {
  5304. return 0;
  5305. }
  5306. memset(&workdata, 0, sizeof(workdata));
  5307. workdata.conn = conn;
  5308. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  5309. return 0;
  5310. }
  5311. workdata.domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  5312. return read_auth_file(filep, &workdata);
  5313. }
  5314. /* Return 1 if request is authorised, 0 otherwise. */
  5315. static int
  5316. check_authorization(struct mg_connection *conn, const char *path)
  5317. {
  5318. char fname[PATH_MAX];
  5319. struct vec uri_vec, filename_vec;
  5320. const char *list;
  5321. struct mg_file file = STRUCT_FILE_INITIALIZER;
  5322. int authorized = 1, truncated;
  5323. if (!conn || !conn->ctx) {
  5324. return 0;
  5325. }
  5326. list = conn->ctx->config[PROTECT_URI];
  5327. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  5328. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  5329. mg_snprintf(conn,
  5330. &truncated,
  5331. fname,
  5332. sizeof(fname),
  5333. "%.*s",
  5334. (int)filename_vec.len,
  5335. filename_vec.ptr);
  5336. if (truncated
  5337. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  5338. mg_cry(conn,
  5339. "%s: cannot open %s: %s",
  5340. __func__,
  5341. fname,
  5342. strerror(errno));
  5343. }
  5344. break;
  5345. }
  5346. }
  5347. if (!is_file_opened(&file.access)) {
  5348. open_auth_file(conn, path, &file);
  5349. }
  5350. if (is_file_opened(&file.access)) {
  5351. authorized = authorize(conn, &file);
  5352. (void)mg_fclose(&file.access); /* ignore error on read only file */
  5353. }
  5354. return authorized;
  5355. }
  5356. static void
  5357. send_authorization_request(struct mg_connection *conn)
  5358. {
  5359. char date[64];
  5360. time_t curtime = time(NULL);
  5361. if (conn && conn->ctx) {
  5362. uint64_t nonce = (uint64_t)(conn->ctx->start_time);
  5363. (void)pthread_mutex_lock(&conn->ctx->nonce_mutex);
  5364. nonce += conn->ctx->nonce_count;
  5365. ++conn->ctx->nonce_count;
  5366. (void)pthread_mutex_unlock(&conn->ctx->nonce_mutex);
  5367. nonce ^= conn->ctx->auth_nonce_mask;
  5368. conn->status_code = 401;
  5369. conn->must_close = 1;
  5370. gmt_time_string(date, sizeof(date), &curtime);
  5371. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  5372. send_no_cache_header(conn);
  5373. mg_printf(conn,
  5374. "Date: %s\r\n"
  5375. "Connection: %s\r\n"
  5376. "Content-Length: 0\r\n"
  5377. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  5378. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  5379. date,
  5380. suggest_connection_header(conn),
  5381. conn->ctx->config[AUTHENTICATION_DOMAIN],
  5382. nonce);
  5383. }
  5384. }
  5385. #if !defined(NO_FILES)
  5386. static int
  5387. is_authorized_for_put(struct mg_connection *conn)
  5388. {
  5389. if (conn) {
  5390. struct mg_file file = STRUCT_FILE_INITIALIZER;
  5391. const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
  5392. int ret = 0;
  5393. if (passfile != NULL
  5394. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  5395. ret = authorize(conn, &file);
  5396. (void)mg_fclose(&file.access); /* ignore error on read only file */
  5397. }
  5398. return ret;
  5399. }
  5400. return 0;
  5401. }
  5402. #endif
  5403. int
  5404. mg_modify_passwords_file(const char *fname,
  5405. const char *domain,
  5406. const char *user,
  5407. const char *pass)
  5408. {
  5409. int found, i;
  5410. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  5411. FILE *fp, *fp2;
  5412. found = 0;
  5413. fp = fp2 = NULL;
  5414. /* Regard empty password as no password - remove user record. */
  5415. if (pass != NULL && pass[0] == '\0') {
  5416. pass = NULL;
  5417. }
  5418. /* Other arguments must not be empty */
  5419. if (fname == NULL || domain == NULL || user == NULL) {
  5420. return 0;
  5421. }
  5422. /* Using the given file format, user name and domain must not contain ':'
  5423. */
  5424. if (strchr(user, ':') != NULL) {
  5425. return 0;
  5426. }
  5427. if (strchr(domain, ':') != NULL) {
  5428. return 0;
  5429. }
  5430. /* Do not allow control characters like newline in user name and domain.
  5431. * Do not allow excessively long names either. */
  5432. for (i = 0; i < 255 && user[i] != 0; i++) {
  5433. if (iscntrl(user[i])) {
  5434. return 0;
  5435. }
  5436. }
  5437. if (user[i]) {
  5438. return 0;
  5439. }
  5440. for (i = 0; i < 255 && domain[i] != 0; i++) {
  5441. if (iscntrl(domain[i])) {
  5442. return 0;
  5443. }
  5444. }
  5445. if (domain[i]) {
  5446. return 0;
  5447. }
  5448. /* The maximum length of the path to the password file is limited */
  5449. if ((strlen(fname) + 4) >= PATH_MAX) {
  5450. return 0;
  5451. }
  5452. /* Create a temporary file name. Length has been checked before. */
  5453. strcpy(tmp, fname);
  5454. strcat(tmp, ".tmp");
  5455. /* Create the file if does not exist */
  5456. /* Use of fopen here is OK, since fname is only ASCII */
  5457. if ((fp = fopen(fname, "a+")) != NULL) {
  5458. (void)fclose(fp);
  5459. }
  5460. /* Open the given file and temporary file */
  5461. if ((fp = fopen(fname, "r")) == NULL) {
  5462. return 0;
  5463. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  5464. fclose(fp);
  5465. return 0;
  5466. }
  5467. /* Copy the stuff to temporary file */
  5468. while (fgets(line, sizeof(line), fp) != NULL) {
  5469. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  5470. continue;
  5471. }
  5472. u[255] = 0;
  5473. d[255] = 0;
  5474. if (!strcmp(u, user) && !strcmp(d, domain)) {
  5475. found++;
  5476. if (pass != NULL) {
  5477. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  5478. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  5479. }
  5480. } else {
  5481. fprintf(fp2, "%s", line);
  5482. }
  5483. }
  5484. /* If new user, just add it */
  5485. if (!found && pass != NULL) {
  5486. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  5487. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  5488. }
  5489. /* Close files */
  5490. fclose(fp);
  5491. fclose(fp2);
  5492. /* Put the temp file in place of real file */
  5493. IGNORE_UNUSED_RESULT(remove(fname));
  5494. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  5495. return 1;
  5496. }
  5497. static int
  5498. is_valid_port(unsigned long port)
  5499. {
  5500. return port < 0xffff;
  5501. }
  5502. static int
  5503. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  5504. {
  5505. struct addrinfo hints, *res, *ressave;
  5506. int func_ret = 0;
  5507. int gai_ret;
  5508. memset(&hints, 0, sizeof(struct addrinfo));
  5509. hints.ai_family = af;
  5510. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  5511. if (gai_ret != 0) {
  5512. /* gai_strerror could be used to convert gai_ret to a string */
  5513. /* POSIX return values: see
  5514. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  5515. */
  5516. /* Windows return values: see
  5517. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  5518. */
  5519. return 0;
  5520. }
  5521. ressave = res;
  5522. while (res) {
  5523. if (dstlen >= res->ai_addrlen) {
  5524. memcpy(dst, res->ai_addr, res->ai_addrlen);
  5525. func_ret = 1;
  5526. }
  5527. res = res->ai_next;
  5528. }
  5529. freeaddrinfo(ressave);
  5530. return func_ret;
  5531. }
  5532. static int
  5533. connect_socket(struct mg_context *ctx /* may be NULL */,
  5534. const char *host,
  5535. int port,
  5536. int use_ssl,
  5537. char *ebuf,
  5538. size_t ebuf_len,
  5539. SOCKET *sock /* output: socket, must not be NULL */,
  5540. union usa *sa /* output: socket address, must not be NULL */
  5541. )
  5542. {
  5543. int ip_ver = 0;
  5544. *sock = INVALID_SOCKET;
  5545. memset(sa, 0, sizeof(*sa));
  5546. if (ebuf_len > 0) {
  5547. *ebuf = 0;
  5548. }
  5549. if (host == NULL) {
  5550. mg_snprintf(NULL,
  5551. NULL, /* No truncation check for ebuf */
  5552. ebuf,
  5553. ebuf_len,
  5554. "%s",
  5555. "NULL host");
  5556. return 0;
  5557. }
  5558. if (port < 0 || !is_valid_port((unsigned)port)) {
  5559. mg_snprintf(NULL,
  5560. NULL, /* No truncation check for ebuf */
  5561. ebuf,
  5562. ebuf_len,
  5563. "%s",
  5564. "invalid port");
  5565. return 0;
  5566. }
  5567. #if !defined(NO_SSL)
  5568. if (use_ssl && (SSLv23_client_method == NULL)) {
  5569. mg_snprintf(NULL,
  5570. NULL, /* No truncation check for ebuf */
  5571. ebuf,
  5572. ebuf_len,
  5573. "%s",
  5574. "SSL is not initialized");
  5575. return 0;
  5576. }
  5577. #else
  5578. (void)use_ssl;
  5579. #endif
  5580. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  5581. sa->sin.sin_port = htons((uint16_t)port);
  5582. ip_ver = 4;
  5583. #ifdef USE_IPV6
  5584. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  5585. sa->sin6.sin6_port = htons((uint16_t)port);
  5586. ip_ver = 6;
  5587. } else if (host[0] == '[') {
  5588. /* While getaddrinfo on Windows will work with [::1],
  5589. * getaddrinfo on Linux only works with ::1 (without []). */
  5590. size_t l = strlen(host + 1);
  5591. char *h = (l > 1) ? mg_strdup(host + 1) : NULL;
  5592. if (h) {
  5593. h[l - 1] = 0;
  5594. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  5595. sa->sin6.sin6_port = htons((uint16_t)port);
  5596. ip_ver = 6;
  5597. }
  5598. mg_free(h);
  5599. }
  5600. #endif
  5601. }
  5602. if (ip_ver == 0) {
  5603. mg_snprintf(NULL,
  5604. NULL, /* No truncation check for ebuf */
  5605. ebuf,
  5606. ebuf_len,
  5607. "%s",
  5608. "host not found");
  5609. return 0;
  5610. }
  5611. if (ip_ver == 4) {
  5612. *sock = socket(PF_INET, SOCK_STREAM, 0);
  5613. }
  5614. #ifdef USE_IPV6
  5615. else if (ip_ver == 6) {
  5616. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  5617. }
  5618. #endif
  5619. if (*sock == INVALID_SOCKET) {
  5620. mg_snprintf(NULL,
  5621. NULL, /* No truncation check for ebuf */
  5622. ebuf,
  5623. ebuf_len,
  5624. "socket(): %s",
  5625. strerror(ERRNO));
  5626. return 0;
  5627. }
  5628. set_close_on_exec(*sock, fc(ctx));
  5629. if ((ip_ver == 4)
  5630. && (connect(*sock, (struct sockaddr *)&sa->sin, sizeof(sa->sin))
  5631. == 0)) {
  5632. /* connected with IPv4 */
  5633. set_non_blocking_mode(*sock);
  5634. return 1;
  5635. }
  5636. #ifdef USE_IPV6
  5637. if ((ip_ver == 6)
  5638. && (connect(*sock, (struct sockaddr *)&sa->sin6, sizeof(sa->sin6))
  5639. == 0)) {
  5640. /* connected with IPv6 */
  5641. set_non_blocking_mode(*sock);
  5642. return 1;
  5643. }
  5644. #endif
  5645. /* Not connected */
  5646. mg_snprintf(NULL,
  5647. NULL, /* No truncation check for ebuf */
  5648. ebuf,
  5649. ebuf_len,
  5650. "connect(%s:%d): %s",
  5651. host,
  5652. port,
  5653. strerror(ERRNO));
  5654. closesocket(*sock);
  5655. *sock = INVALID_SOCKET;
  5656. return 0;
  5657. }
  5658. int
  5659. mg_url_encode(const char *src, char *dst, size_t dst_len)
  5660. {
  5661. static const char *dont_escape = "._-$,;~()";
  5662. static const char *hex = "0123456789abcdef";
  5663. char *pos = dst;
  5664. const char *end = dst + dst_len - 1;
  5665. for (; *src != '\0' && pos < end; src++, pos++) {
  5666. if (isalnum(*(const unsigned char *)src)
  5667. || strchr(dont_escape, *(const unsigned char *)src) != NULL) {
  5668. *pos = *src;
  5669. } else if (pos + 2 < end) {
  5670. pos[0] = '%';
  5671. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  5672. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  5673. pos += 2;
  5674. } else {
  5675. break;
  5676. }
  5677. }
  5678. *pos = '\0';
  5679. return (*src == '\0') ? (int)(pos - dst) : -1;
  5680. }
  5681. static void
  5682. print_dir_entry(struct de *de)
  5683. {
  5684. char size[64], mod[64], href[PATH_MAX * 3 /* worst case */];
  5685. struct tm *tm;
  5686. if (de->file.is_directory) {
  5687. mg_snprintf(de->conn,
  5688. NULL, /* Buffer is big enough */
  5689. size,
  5690. sizeof(size),
  5691. "%s",
  5692. "[DIRECTORY]");
  5693. } else {
  5694. /* We use (signed) cast below because MSVC 6 compiler cannot
  5695. * convert unsigned __int64 to double. Sigh. */
  5696. if (de->file.size < 1024) {
  5697. mg_snprintf(de->conn,
  5698. NULL, /* Buffer is big enough */
  5699. size,
  5700. sizeof(size),
  5701. "%d",
  5702. (int)de->file.size);
  5703. } else if (de->file.size < 0x100000) {
  5704. mg_snprintf(de->conn,
  5705. NULL, /* Buffer is big enough */
  5706. size,
  5707. sizeof(size),
  5708. "%.1fk",
  5709. (double)de->file.size / 1024.0);
  5710. } else if (de->file.size < 0x40000000) {
  5711. mg_snprintf(de->conn,
  5712. NULL, /* Buffer is big enough */
  5713. size,
  5714. sizeof(size),
  5715. "%.1fM",
  5716. (double)de->file.size / 1048576);
  5717. } else {
  5718. mg_snprintf(de->conn,
  5719. NULL, /* Buffer is big enough */
  5720. size,
  5721. sizeof(size),
  5722. "%.1fG",
  5723. (double)de->file.size / 1073741824);
  5724. }
  5725. }
  5726. /* Note: mg_snprintf will not cause a buffer overflow above.
  5727. * So, string truncation checks are not required here. */
  5728. tm = localtime(&de->file.last_modified);
  5729. if (tm != NULL) {
  5730. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  5731. } else {
  5732. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  5733. mod[sizeof(mod) - 1] = '\0';
  5734. }
  5735. mg_url_encode(de->file_name, href, sizeof(href));
  5736. de->conn->num_bytes_sent +=
  5737. mg_printf(de->conn,
  5738. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  5739. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  5740. de->conn->request_info.local_uri,
  5741. href,
  5742. de->file.is_directory ? "/" : "",
  5743. de->file_name,
  5744. de->file.is_directory ? "/" : "",
  5745. mod,
  5746. size);
  5747. }
  5748. /* This function is called from send_directory() and used for
  5749. * sorting directory entries by size, or name, or modification time.
  5750. * On windows, __cdecl specification is needed in case if project is built
  5751. * with __stdcall convention. qsort always requires __cdels callback. */
  5752. static int WINCDECL
  5753. compare_dir_entries(const void *p1, const void *p2)
  5754. {
  5755. if (p1 && p2) {
  5756. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  5757. const char *query_string = a->conn->request_info.query_string;
  5758. int cmp_result = 0;
  5759. if (query_string == NULL) {
  5760. query_string = "na";
  5761. }
  5762. if (a->file.is_directory && !b->file.is_directory) {
  5763. return -1; /* Always put directories on top */
  5764. } else if (!a->file.is_directory && b->file.is_directory) {
  5765. return 1; /* Always put directories on top */
  5766. } else if (*query_string == 'n') {
  5767. cmp_result = strcmp(a->file_name, b->file_name);
  5768. } else if (*query_string == 's') {
  5769. cmp_result = (a->file.size == b->file.size)
  5770. ? 0
  5771. : ((a->file.size > b->file.size) ? 1 : -1);
  5772. } else if (*query_string == 'd') {
  5773. cmp_result =
  5774. (a->file.last_modified == b->file.last_modified)
  5775. ? 0
  5776. : ((a->file.last_modified > b->file.last_modified) ? 1
  5777. : -1);
  5778. }
  5779. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  5780. }
  5781. return 0;
  5782. }
  5783. static int
  5784. must_hide_file(struct mg_connection *conn, const char *path)
  5785. {
  5786. if (conn && conn->ctx) {
  5787. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  5788. const char *pattern = conn->ctx->config[HIDE_FILES];
  5789. return match_prefix(pw_pattern, strlen(pw_pattern), path) > 0
  5790. || (pattern != NULL
  5791. && match_prefix(pattern, strlen(pattern), path) > 0);
  5792. }
  5793. return 0;
  5794. }
  5795. static int
  5796. scan_directory(struct mg_connection *conn,
  5797. const char *dir,
  5798. void *data,
  5799. void (*cb)(struct de *, void *))
  5800. {
  5801. char path[PATH_MAX];
  5802. struct dirent *dp;
  5803. DIR *dirp;
  5804. struct de de;
  5805. int truncated;
  5806. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  5807. return 0;
  5808. } else {
  5809. de.conn = conn;
  5810. while ((dp = mg_readdir(dirp)) != NULL) {
  5811. /* Do not show current dir and hidden files */
  5812. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  5813. || must_hide_file(conn, dp->d_name)) {
  5814. continue;
  5815. }
  5816. mg_snprintf(
  5817. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  5818. /* If we don't memset stat structure to zero, mtime will have
  5819. * garbage and strftime() will segfault later on in
  5820. * print_dir_entry(). memset is required only if mg_stat()
  5821. * fails. For more details, see
  5822. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  5823. memset(&de.file, 0, sizeof(de.file));
  5824. if (truncated) {
  5825. /* If the path is not complete, skip processing. */
  5826. continue;
  5827. }
  5828. if (!mg_stat(conn, path, &de.file)) {
  5829. mg_cry(conn,
  5830. "%s: mg_stat(%s) failed: %s",
  5831. __func__,
  5832. path,
  5833. strerror(ERRNO));
  5834. }
  5835. de.file_name = dp->d_name;
  5836. cb(&de, data);
  5837. }
  5838. (void)mg_closedir(dirp);
  5839. }
  5840. return 1;
  5841. }
  5842. #if !defined(NO_FILES)
  5843. static int
  5844. remove_directory(struct mg_connection *conn, const char *dir)
  5845. {
  5846. char path[PATH_MAX];
  5847. struct dirent *dp;
  5848. DIR *dirp;
  5849. struct de de;
  5850. int truncated;
  5851. int ok = 1;
  5852. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  5853. return 0;
  5854. } else {
  5855. de.conn = conn;
  5856. while ((dp = mg_readdir(dirp)) != NULL) {
  5857. /* Do not show current dir (but show hidden files as they will
  5858. * also be removed) */
  5859. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  5860. continue;
  5861. }
  5862. mg_snprintf(
  5863. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  5864. /* If we don't memset stat structure to zero, mtime will have
  5865. * garbage and strftime() will segfault later on in
  5866. * print_dir_entry(). memset is required only if mg_stat()
  5867. * fails. For more details, see
  5868. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  5869. memset(&de.file, 0, sizeof(de.file));
  5870. if (truncated) {
  5871. /* Do not delete anything shorter */
  5872. ok = 0;
  5873. continue;
  5874. }
  5875. if (!mg_stat(conn, path, &de.file)) {
  5876. mg_cry(conn,
  5877. "%s: mg_stat(%s) failed: %s",
  5878. __func__,
  5879. path,
  5880. strerror(ERRNO));
  5881. ok = 0;
  5882. }
  5883. if (de.file.is_directory) {
  5884. if (remove_directory(conn, path) == 0) {
  5885. ok = 0;
  5886. }
  5887. } else {
  5888. /* This will fail file is the file is in memory */
  5889. if (mg_remove(conn, path) == 0) {
  5890. ok = 0;
  5891. }
  5892. }
  5893. }
  5894. (void)mg_closedir(dirp);
  5895. IGNORE_UNUSED_RESULT(rmdir(dir));
  5896. }
  5897. return ok;
  5898. }
  5899. #endif
  5900. struct dir_scan_data {
  5901. struct de *entries;
  5902. unsigned int num_entries;
  5903. unsigned int arr_size;
  5904. };
  5905. /* Behaves like realloc(), but frees original pointer on failure */
  5906. static void *
  5907. realloc2(void *ptr, size_t size)
  5908. {
  5909. void *new_ptr = mg_realloc(ptr, size);
  5910. if (new_ptr == NULL) {
  5911. mg_free(ptr);
  5912. }
  5913. return new_ptr;
  5914. }
  5915. static void
  5916. dir_scan_callback(struct de *de, void *data)
  5917. {
  5918. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  5919. if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {
  5920. dsd->arr_size *= 2;
  5921. dsd->entries =
  5922. (struct de *)realloc2(dsd->entries,
  5923. dsd->arr_size * sizeof(dsd->entries[0]));
  5924. }
  5925. if (dsd->entries == NULL) {
  5926. /* TODO(lsm, low): propagate an error to the caller */
  5927. dsd->num_entries = 0;
  5928. } else {
  5929. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  5930. dsd->entries[dsd->num_entries].file = de->file;
  5931. dsd->entries[dsd->num_entries].conn = de->conn;
  5932. dsd->num_entries++;
  5933. }
  5934. }
  5935. static void
  5936. handle_directory_request(struct mg_connection *conn, const char *dir)
  5937. {
  5938. unsigned int i;
  5939. int sort_direction;
  5940. struct dir_scan_data data = {NULL, 0, 128};
  5941. char date[64];
  5942. time_t curtime = time(NULL);
  5943. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  5944. send_http_error(conn,
  5945. 500,
  5946. "Error: Cannot open directory\nopendir(%s): %s",
  5947. dir,
  5948. strerror(ERRNO));
  5949. return;
  5950. }
  5951. gmt_time_string(date, sizeof(date), &curtime);
  5952. if (!conn) {
  5953. return;
  5954. }
  5955. sort_direction = ((conn->request_info.query_string != NULL)
  5956. && (conn->request_info.query_string[1] == 'd'))
  5957. ? 'a'
  5958. : 'd';
  5959. conn->must_close = 1;
  5960. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  5961. send_static_cache_header(conn);
  5962. mg_printf(conn,
  5963. "Date: %s\r\n"
  5964. "Connection: close\r\n"
  5965. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  5966. date);
  5967. conn->num_bytes_sent +=
  5968. mg_printf(conn,
  5969. "<html><head><title>Index of %s</title>"
  5970. "<style>th {text-align: left;}</style></head>"
  5971. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  5972. "<tr><th><a href=\"?n%c\">Name</a></th>"
  5973. "<th><a href=\"?d%c\">Modified</a></th>"
  5974. "<th><a href=\"?s%c\">Size</a></th></tr>"
  5975. "<tr><td colspan=\"3\"><hr></td></tr>",
  5976. conn->request_info.local_uri,
  5977. conn->request_info.local_uri,
  5978. sort_direction,
  5979. sort_direction,
  5980. sort_direction);
  5981. /* Print first entry - link to a parent directory */
  5982. conn->num_bytes_sent +=
  5983. mg_printf(conn,
  5984. "<tr><td><a href=\"%s%s\">%s</a></td>"
  5985. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  5986. conn->request_info.local_uri,
  5987. "..",
  5988. "Parent directory",
  5989. "-",
  5990. "-");
  5991. /* Sort and print directory entries */
  5992. if (data.entries != NULL) {
  5993. qsort(data.entries,
  5994. (size_t)data.num_entries,
  5995. sizeof(data.entries[0]),
  5996. compare_dir_entries);
  5997. for (i = 0; i < data.num_entries; i++) {
  5998. print_dir_entry(&data.entries[i]);
  5999. mg_free(data.entries[i].file_name);
  6000. }
  6001. mg_free(data.entries);
  6002. }
  6003. conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");
  6004. conn->status_code = 200;
  6005. }
  6006. /* Send len bytes from the opened file to the client. */
  6007. static void
  6008. send_file_data(struct mg_connection *conn,
  6009. struct mg_file *filep,
  6010. int64_t offset,
  6011. int64_t len)
  6012. {
  6013. char buf[MG_BUF_LEN];
  6014. int to_read, num_read, num_written;
  6015. int64_t size;
  6016. if (!filep || !conn) {
  6017. return;
  6018. }
  6019. /* Sanity check the offset */
  6020. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  6021. : (int64_t)(filep->stat.size);
  6022. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  6023. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  6024. /* file stored in memory */
  6025. if (len > size - offset) {
  6026. len = size - offset;
  6027. }
  6028. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  6029. } else if (len > 0 && filep->access.fp != NULL) {
  6030. /* file stored on disk */
  6031. #if defined(__linux__)
  6032. /* sendfile is only available for Linux */
  6033. if ((conn->ssl == 0) && (conn->throttle == 0)
  6034. && (!mg_strcasecmp(conn->ctx->config[ALLOW_SENDFILE_CALL],
  6035. "yes"))) {
  6036. off_t sf_offs = (off_t)offset;
  6037. ssize_t sf_sent;
  6038. int sf_file = fileno(filep->access.fp);
  6039. int loop_cnt = 0;
  6040. do {
  6041. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  6042. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  6043. size_t sf_tosend =
  6044. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  6045. sf_sent =
  6046. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  6047. if (sf_sent > 0) {
  6048. conn->num_bytes_sent += sf_sent;
  6049. len -= sf_sent;
  6050. offset += sf_sent;
  6051. } else if (loop_cnt == 0) {
  6052. /* This file can not be sent using sendfile.
  6053. * This might be the case for pseudo-files in the
  6054. * /sys/ and /proc/ file system.
  6055. * Use the regular user mode copy code instead. */
  6056. break;
  6057. } else if (sf_sent == 0) {
  6058. /* No error, but 0 bytes sent. May be EOF? */
  6059. return;
  6060. }
  6061. loop_cnt++;
  6062. } while ((len > 0) && (sf_sent >= 0));
  6063. if (sf_sent > 0) {
  6064. return; /* OK */
  6065. }
  6066. /* sf_sent<0 means error, thus fall back to the classic way */
  6067. /* This is always the case, if sf_file is not a "normal" file,
  6068. * e.g., for sending data from the output of a CGI process. */
  6069. offset = (int64_t)sf_offs;
  6070. }
  6071. #endif
  6072. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  6073. mg_cry(conn, "%s: fseeko() failed: %s", __func__, strerror(ERRNO));
  6074. send_http_error(
  6075. conn,
  6076. 500,
  6077. "%s",
  6078. "Error: Unable to access file at requested position.");
  6079. } else {
  6080. while (len > 0) {
  6081. /* Calculate how much to read from the file in the buffer */
  6082. to_read = sizeof(buf);
  6083. if ((int64_t)to_read > len) {
  6084. to_read = (int)len;
  6085. }
  6086. /* Read from file, exit the loop on error */
  6087. if ((num_read =
  6088. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  6089. <= 0) {
  6090. break;
  6091. }
  6092. /* Send read bytes to the client, exit the loop on error */
  6093. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  6094. != num_read) {
  6095. break;
  6096. }
  6097. /* Both read and were successful, adjust counters */
  6098. conn->num_bytes_sent += num_written;
  6099. len -= num_written;
  6100. }
  6101. }
  6102. }
  6103. }
  6104. static int
  6105. parse_range_header(const char *header, int64_t *a, int64_t *b)
  6106. {
  6107. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  6108. }
  6109. static void
  6110. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  6111. {
  6112. if (filestat != NULL && buf != NULL) {
  6113. mg_snprintf(NULL,
  6114. NULL, /* All calls to construct_etag use 64 byte buffer */
  6115. buf,
  6116. buf_len,
  6117. "\"%lx.%" INT64_FMT "\"",
  6118. (unsigned long)filestat->last_modified,
  6119. filestat->size);
  6120. }
  6121. }
  6122. static void
  6123. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  6124. {
  6125. if (filep != NULL && filep->fp != NULL) {
  6126. #ifdef _WIN32
  6127. (void)conn; /* Unused. */
  6128. #else
  6129. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  6130. mg_cry(conn,
  6131. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  6132. __func__,
  6133. strerror(ERRNO));
  6134. }
  6135. #endif
  6136. }
  6137. }
  6138. static void
  6139. handle_static_file_request(struct mg_connection *conn,
  6140. const char *path,
  6141. struct mg_file *filep,
  6142. const char *mime_type,
  6143. const char *additional_headers)
  6144. {
  6145. char date[64], lm[64], etag[64];
  6146. char range[128]; /* large enough, so there will be no overflow */
  6147. const char *msg = "OK", *hdr;
  6148. time_t curtime = time(NULL);
  6149. int64_t cl, r1, r2;
  6150. struct vec mime_vec;
  6151. int n, truncated;
  6152. char gz_path[PATH_MAX];
  6153. const char *encoding = "";
  6154. const char *cors1, *cors2, *cors3;
  6155. if (conn == NULL || conn->ctx == NULL || filep == NULL) {
  6156. return;
  6157. }
  6158. if (mime_type == NULL) {
  6159. get_mime_type(conn->ctx, path, &mime_vec);
  6160. } else {
  6161. mime_vec.ptr = mime_type;
  6162. mime_vec.len = strlen(mime_type);
  6163. }
  6164. if (filep->stat.size > INT64_MAX) {
  6165. send_http_error(conn,
  6166. 500,
  6167. "Error: File size is too large to send\n%" INT64_FMT,
  6168. filep->stat.size);
  6169. }
  6170. cl = (int64_t)filep->stat.size;
  6171. conn->status_code = 200;
  6172. range[0] = '\0';
  6173. /* if this file is in fact a pre-gzipped file, rewrite its filename
  6174. * it's important to rewrite the filename after resolving
  6175. * the mime type from it, to preserve the actual file's type */
  6176. if (filep->stat.is_gzipped) {
  6177. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  6178. if (truncated) {
  6179. send_http_error(conn,
  6180. 500,
  6181. "Error: Path of zipped file too long (%s)",
  6182. path);
  6183. return;
  6184. }
  6185. path = gz_path;
  6186. encoding = "Content-Encoding: gzip\r\n";
  6187. }
  6188. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  6189. send_http_error(conn,
  6190. 500,
  6191. "Error: Cannot open file\nfopen(%s): %s",
  6192. path,
  6193. strerror(ERRNO));
  6194. return;
  6195. }
  6196. fclose_on_exec(&filep->access, conn);
  6197. /* If Range: header specified, act accordingly */
  6198. r1 = r2 = 0;
  6199. hdr = mg_get_header(conn, "Range");
  6200. if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 && r1 >= 0
  6201. && r2 >= 0) {
  6202. /* actually, range requests don't play well with a pre-gzipped
  6203. * file (since the range is specified in the uncompressed space) */
  6204. if (filep->stat.is_gzipped) {
  6205. send_http_error(
  6206. conn,
  6207. 501,
  6208. "%s",
  6209. "Error: Range requests in gzipped files are not supported");
  6210. (void)mg_fclose(
  6211. &filep->access); /* ignore error on read only file */
  6212. return;
  6213. }
  6214. conn->status_code = 206;
  6215. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  6216. mg_snprintf(conn,
  6217. NULL, /* range buffer is big enough */
  6218. range,
  6219. sizeof(range),
  6220. "Content-Range: bytes "
  6221. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  6222. r1,
  6223. r1 + cl - 1,
  6224. filep->stat.size);
  6225. msg = "Partial Content";
  6226. }
  6227. hdr = mg_get_header(conn, "Origin");
  6228. if (hdr) {
  6229. /* Cross-origin resource sharing (CORS), see
  6230. * http://www.html5rocks.com/en/tutorials/cors/,
  6231. * http://www.html5rocks.com/static/images/cors_server_flowchart.png -
  6232. * preflight is not supported for files. */
  6233. cors1 = "Access-Control-Allow-Origin: ";
  6234. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  6235. cors3 = "\r\n";
  6236. } else {
  6237. cors1 = cors2 = cors3 = "";
  6238. }
  6239. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
  6240. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  6241. gmt_time_string(date, sizeof(date), &curtime);
  6242. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  6243. construct_etag(etag, sizeof(etag), &filep->stat);
  6244. (void)mg_printf(conn,
  6245. "HTTP/1.1 %d %s\r\n"
  6246. "%s%s%s"
  6247. "Date: %s\r\n",
  6248. conn->status_code,
  6249. msg,
  6250. cors1,
  6251. cors2,
  6252. cors3,
  6253. date);
  6254. send_static_cache_header(conn);
  6255. (void)mg_printf(conn,
  6256. "Last-Modified: %s\r\n"
  6257. "Etag: %s\r\n"
  6258. "Content-Type: %.*s\r\n"
  6259. "Content-Length: %" INT64_FMT "\r\n"
  6260. "Connection: %s\r\n"
  6261. "Accept-Ranges: bytes\r\n"
  6262. "%s%s",
  6263. lm,
  6264. etag,
  6265. (int)mime_vec.len,
  6266. mime_vec.ptr,
  6267. cl,
  6268. suggest_connection_header(conn),
  6269. range,
  6270. encoding);
  6271. /* The previous code must not add any header starting with X- to make
  6272. * sure no one of the additional_headers is included twice */
  6273. if (additional_headers != NULL) {
  6274. (void)mg_printf(conn,
  6275. "%.*s\r\n\r\n",
  6276. (int)strlen(additional_headers),
  6277. additional_headers);
  6278. } else {
  6279. (void)mg_printf(conn, "\r\n");
  6280. }
  6281. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  6282. send_file_data(conn, filep, r1, cl);
  6283. }
  6284. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  6285. }
  6286. #if !defined(NO_CACHING)
  6287. static void
  6288. handle_not_modified_static_file_request(struct mg_connection *conn,
  6289. struct mg_file *filep)
  6290. {
  6291. char date[64], lm[64], etag[64];
  6292. time_t curtime = time(NULL);
  6293. if (conn == NULL || filep == NULL) {
  6294. return;
  6295. }
  6296. conn->status_code = 304;
  6297. gmt_time_string(date, sizeof(date), &curtime);
  6298. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  6299. construct_etag(etag, sizeof(etag), &filep->stat);
  6300. (void)mg_printf(conn,
  6301. "HTTP/1.1 %d %s\r\n"
  6302. "Date: %s\r\n",
  6303. conn->status_code,
  6304. mg_get_response_code_text(conn, conn->status_code),
  6305. date);
  6306. send_static_cache_header(conn);
  6307. (void)mg_printf(conn,
  6308. "Last-Modified: %s\r\n"
  6309. "Etag: %s\r\n"
  6310. "Connection: %s\r\n"
  6311. "\r\n",
  6312. lm,
  6313. etag,
  6314. suggest_connection_header(conn));
  6315. }
  6316. #endif
  6317. void
  6318. mg_send_file(struct mg_connection *conn, const char *path)
  6319. {
  6320. mg_send_mime_file(conn, path, NULL);
  6321. }
  6322. void
  6323. mg_send_mime_file(struct mg_connection *conn,
  6324. const char *path,
  6325. const char *mime_type)
  6326. {
  6327. mg_send_mime_file2(conn, path, mime_type, NULL);
  6328. }
  6329. void
  6330. mg_send_mime_file2(struct mg_connection *conn,
  6331. const char *path,
  6332. const char *mime_type,
  6333. const char *additional_headers)
  6334. {
  6335. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6336. if (mg_stat(conn, path, &file.stat)) {
  6337. if (file.stat.is_directory) {
  6338. if (!conn) {
  6339. return;
  6340. }
  6341. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  6342. "yes")) {
  6343. handle_directory_request(conn, path);
  6344. } else {
  6345. send_http_error(conn,
  6346. 403,
  6347. "%s",
  6348. "Error: Directory listing denied");
  6349. }
  6350. } else {
  6351. handle_static_file_request(
  6352. conn, path, &file, mime_type, additional_headers);
  6353. }
  6354. } else {
  6355. send_http_error(conn, 404, "%s", "Error: File not found");
  6356. }
  6357. }
  6358. /* For a given PUT path, create all intermediate subdirectories.
  6359. * Return 0 if the path itself is a directory.
  6360. * Return 1 if the path leads to a file.
  6361. * Return -1 for if the path is too long.
  6362. * Return -2 if path can not be created.
  6363. */
  6364. static int
  6365. put_dir(struct mg_connection *conn, const char *path)
  6366. {
  6367. char buf[PATH_MAX];
  6368. const char *s, *p;
  6369. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6370. size_t len;
  6371. int res = 1;
  6372. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  6373. len = (size_t)(p - path);
  6374. if (len >= sizeof(buf)) {
  6375. /* path too long */
  6376. res = -1;
  6377. break;
  6378. }
  6379. memcpy(buf, path, len);
  6380. buf[len] = '\0';
  6381. /* Try to create intermediate directory */
  6382. DEBUG_TRACE("mkdir(%s)", buf);
  6383. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  6384. /* path does not exixt and can not be created */
  6385. res = -2;
  6386. break;
  6387. }
  6388. /* Is path itself a directory? */
  6389. if (p[1] == '\0') {
  6390. res = 0;
  6391. }
  6392. }
  6393. return res;
  6394. }
  6395. static void
  6396. remove_bad_file(const struct mg_connection *conn, const char *path)
  6397. {
  6398. int r = mg_remove(conn, path);
  6399. if (r != 0) {
  6400. mg_cry(conn, "%s: Cannot remove invalid file %s", __func__, path);
  6401. }
  6402. }
  6403. long long
  6404. mg_store_body(struct mg_connection *conn, const char *path)
  6405. {
  6406. char buf[MG_BUF_LEN];
  6407. long long len = 0;
  6408. int ret, n;
  6409. struct mg_file fi;
  6410. if (conn->consumed_content != 0) {
  6411. mg_cry(conn, "%s: Contents already consumed", __func__);
  6412. return -11;
  6413. }
  6414. ret = put_dir(conn, path);
  6415. if (ret < 0) {
  6416. /* -1 for path too long,
  6417. * -2 for path can not be created. */
  6418. return ret;
  6419. }
  6420. if (ret != 1) {
  6421. /* Return 0 means, path itself is a directory. */
  6422. return 0;
  6423. }
  6424. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  6425. return -12;
  6426. }
  6427. ret = mg_read(conn, buf, sizeof(buf));
  6428. while (ret > 0) {
  6429. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  6430. if (n != ret) {
  6431. (void)mg_fclose(
  6432. &fi.access); /* File is bad and will be removed anyway. */
  6433. remove_bad_file(conn, path);
  6434. return -13;
  6435. }
  6436. ret = mg_read(conn, buf, sizeof(buf));
  6437. }
  6438. /* File is open for writing. If fclose fails, there was probably an
  6439. * error flushing the buffer to disk, so the file on disk might be
  6440. * broken. Delete it and return an error to the caller. */
  6441. if (mg_fclose(&fi.access) != 0) {
  6442. remove_bad_file(conn, path);
  6443. return -14;
  6444. }
  6445. return len;
  6446. }
  6447. /* Parse HTTP headers from the given buffer, advance buf pointer
  6448. * to the point where parsing stopped.
  6449. * All parameters must be valid pointers (not NULL).
  6450. * Return <0 on error. */
  6451. static int
  6452. parse_http_headers(char **buf, struct mg_request_info *ri)
  6453. {
  6454. int i;
  6455. ri->num_headers = 0;
  6456. for (i = 0; i < (int)ARRAY_SIZE(ri->http_headers); i++) {
  6457. char *dp = *buf;
  6458. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  6459. dp++;
  6460. }
  6461. if (dp == *buf) {
  6462. /* End of headers reached. */
  6463. break;
  6464. }
  6465. if (*dp != ':') {
  6466. /* This is not a valid field. */
  6467. return -1;
  6468. }
  6469. /* End of header key (*dp == ':') */
  6470. /* Truncate here and set the key name */
  6471. *dp = 0;
  6472. ri->http_headers[i].name = *buf;
  6473. do {
  6474. dp++;
  6475. } while (*dp == ' ');
  6476. /* The rest of the line is the value */
  6477. ri->http_headers[i].value = dp;
  6478. *buf = dp + strcspn(dp, "\r\n");
  6479. if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) {
  6480. *buf = NULL;
  6481. }
  6482. ri->num_headers = i + 1;
  6483. if (*buf) {
  6484. (*buf)[0] = 0;
  6485. (*buf)[1] = 0;
  6486. *buf += 2;
  6487. } else {
  6488. *buf = dp;
  6489. break;
  6490. }
  6491. if ((*buf)[0] == '\r') {
  6492. /* This is the end of the header */
  6493. break;
  6494. }
  6495. }
  6496. return ri->num_headers;
  6497. }
  6498. static int
  6499. is_valid_http_method(const char *method)
  6500. {
  6501. return !strcmp(method, "GET") /* HTTP (RFC 2616) */
  6502. || !strcmp(method, "POST") /* HTTP (RFC 2616) */
  6503. || !strcmp(method, "HEAD") /* HTTP (RFC 2616) */
  6504. || !strcmp(method, "PUT") /* HTTP (RFC 2616) */
  6505. || !strcmp(method, "DELETE") /* HTTP (RFC 2616) */
  6506. || !strcmp(method, "OPTIONS") /* HTTP (RFC 2616) */
  6507. /* TRACE method (RFC 2616) is not supported for security reasons */
  6508. || !strcmp(method, "CONNECT") /* HTTP (RFC 2616) */
  6509. || !strcmp(method, "PROPFIND") /* WEBDAV (RFC 2518) */
  6510. || !strcmp(method, "MKCOL") /* WEBDAV (RFC 2518) */
  6511. /* Unsupported WEBDAV Methods: */
  6512. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  6513. /* + 11 methods from RFC 3253 */
  6514. /* ORDERPATCH (RFC 3648) */
  6515. /* ACL (RFC 3744) */
  6516. /* SEARCH (RFC 5323) */
  6517. /* + MicroSoft extensions
  6518. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  6519. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  6520. || !strcmp(method, "PATCH"); /* PATCH method (RFC 5789) */
  6521. }
  6522. /* Parse HTTP request, fill in mg_request_info structure.
  6523. * This function modifies the buffer by NUL-terminating
  6524. * HTTP request components, header names and header values.
  6525. * Parameters:
  6526. * buf (in/out): pointer to the HTTP header to parse and split
  6527. * len (in): length of HTTP header buffer
  6528. * re (out): parsed header as mg_request_info
  6529. * buf and ri must be valid pointers (not NULL), len>0.
  6530. * Returns <0 on error. */
  6531. static int
  6532. parse_http_message(char *buf, int len, struct mg_request_info *ri)
  6533. {
  6534. int is_request, request_length;
  6535. char *start_line;
  6536. request_length = get_request_len(buf, len);
  6537. if (request_length > 0) {
  6538. /* Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_addr,
  6539. * remote_port */
  6540. ri->remote_user = ri->request_method = ri->request_uri =
  6541. ri->http_version = NULL;
  6542. ri->num_headers = 0;
  6543. buf[request_length - 1] = '\0';
  6544. /* RFC says that all initial whitespaces should be ingored */
  6545. while (*buf != '\0' && isspace(*(unsigned char *)buf)) {
  6546. buf++;
  6547. }
  6548. start_line = skip(&buf, "\r\n");
  6549. ri->request_method = skip(&start_line, " ");
  6550. ri->request_uri = skip(&start_line, " ");
  6551. ri->http_version = start_line;
  6552. /* HTTP message could be either HTTP request:
  6553. * "GET / HTTP/1.0 ..."
  6554. * or a HTTP response:
  6555. * "HTTP/1.0 200 OK ..."
  6556. * otherwise it is invalid.
  6557. */
  6558. is_request = is_valid_http_method(ri->request_method);
  6559. if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0)
  6560. || (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
  6561. /* Not a valid request or response: invalid */
  6562. return -1;
  6563. }
  6564. if (is_request) {
  6565. ri->http_version += 5;
  6566. }
  6567. if (parse_http_headers(&buf, ri) < 0) {
  6568. /* Error while parsing headers */
  6569. return -1;
  6570. }
  6571. }
  6572. return request_length;
  6573. }
  6574. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  6575. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  6576. * buffer (which marks the end of HTTP request). Buffer buf may already
  6577. * have some data. The length of the data is stored in nread.
  6578. * Upon every read operation, increase nread by the number of bytes read. */
  6579. static int
  6580. read_request(FILE *fp,
  6581. struct mg_connection *conn,
  6582. char *buf,
  6583. int bufsiz,
  6584. int *nread)
  6585. {
  6586. int request_len, n = 0;
  6587. struct timespec last_action_time;
  6588. double request_timeout;
  6589. if (!conn) {
  6590. return 0;
  6591. }
  6592. memset(&last_action_time, 0, sizeof(last_action_time));
  6593. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  6594. /* value of request_timeout is in seconds, config in milliseconds */
  6595. request_timeout = atof(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  6596. } else {
  6597. request_timeout = -1.0;
  6598. }
  6599. request_len = get_request_len(buf, *nread);
  6600. /* first time reading from this connection */
  6601. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  6602. while (request_len == 0) {
  6603. /* Full request not yet received */
  6604. if (conn->ctx->stop_flag != 0) {
  6605. /* Server is to be stopped. */
  6606. return -1;
  6607. }
  6608. if (*nread >= bufsiz) {
  6609. /* Request too long */
  6610. return -2;
  6611. }
  6612. n = pull(fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  6613. if (n < 0) {
  6614. /* Receive error */
  6615. return -1;
  6616. }
  6617. *nread += n;
  6618. request_len = get_request_len(buf, *nread);
  6619. if ((request_len == 0) && (request_timeout >= 0)) {
  6620. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  6621. > request_timeout) {
  6622. /* Timeout */
  6623. return -1;
  6624. }
  6625. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  6626. }
  6627. }
  6628. return request_len;
  6629. }
  6630. #if !defined(NO_FILES)
  6631. /* For given directory path, substitute it to valid index file.
  6632. * Return 1 if index file has been found, 0 if not found.
  6633. * If the file is found, it's stats is returned in stp. */
  6634. static int
  6635. substitute_index_file(struct mg_connection *conn,
  6636. char *path,
  6637. size_t path_len,
  6638. struct mg_file *filep)
  6639. {
  6640. if (conn && conn->ctx) {
  6641. const char *list = conn->ctx->config[INDEX_FILES];
  6642. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6643. struct vec filename_vec;
  6644. size_t n = strlen(path);
  6645. int found = 0;
  6646. /* The 'path' given to us points to the directory. Remove all trailing
  6647. * directory separator characters from the end of the path, and
  6648. * then append single directory separator character. */
  6649. while (n > 0 && path[n - 1] == '/') {
  6650. n--;
  6651. }
  6652. path[n] = '/';
  6653. /* Traverse index files list. For each entry, append it to the given
  6654. * path and see if the file exists. If it exists, break the loop */
  6655. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6656. /* Ignore too long entries that may overflow path buffer */
  6657. if (filename_vec.len > path_len - (n + 2)) {
  6658. continue;
  6659. }
  6660. /* Prepare full path to the index file */
  6661. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6662. /* Does it exist? */
  6663. if (mg_stat(conn, path, &file.stat)) {
  6664. /* Yes it does, break the loop */
  6665. *filep = file;
  6666. found = 1;
  6667. break;
  6668. }
  6669. }
  6670. /* If no index file exists, restore directory path */
  6671. if (!found) {
  6672. path[n] = '\0';
  6673. }
  6674. return found;
  6675. }
  6676. return 0;
  6677. }
  6678. #endif
  6679. #if !defined(NO_CACHING)
  6680. /* Return True if we should reply 304 Not Modified. */
  6681. static int
  6682. is_not_modified(const struct mg_connection *conn,
  6683. const struct mg_file_stat *filestat)
  6684. {
  6685. char etag[64];
  6686. const char *ims = mg_get_header(conn, "If-Modified-Since");
  6687. const char *inm = mg_get_header(conn, "If-None-Match");
  6688. construct_etag(etag, sizeof(etag), filestat);
  6689. return (inm != NULL && !mg_strcasecmp(etag, inm))
  6690. || ((ims != NULL)
  6691. && (filestat->last_modified <= parse_date_string(ims)));
  6692. }
  6693. #endif /* !NO_CACHING */
  6694. #if !defined(NO_CGI) || !defined(NO_FILES)
  6695. static int
  6696. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  6697. {
  6698. const char *expect, *body;
  6699. char buf[MG_BUF_LEN];
  6700. int to_read, nread, success = 0;
  6701. int64_t buffered_len;
  6702. double timeout = -1.0;
  6703. if (!conn) {
  6704. return 0;
  6705. }
  6706. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  6707. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  6708. }
  6709. expect = mg_get_header(conn, "Expect");
  6710. /* assert(fp != NULL); */
  6711. if (!fp) {
  6712. send_http_error(conn, 500, "%s", "Error: NULL File");
  6713. return 0;
  6714. }
  6715. if (conn->content_len == -1 && !conn->is_chunked) {
  6716. /* Content length is not specified by the client. */
  6717. send_http_error(conn,
  6718. 411,
  6719. "%s",
  6720. "Error: Client did not specify content length");
  6721. } else if ((expect != NULL)
  6722. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  6723. /* Client sent an "Expect: xyz" header and xyz is not 100-continue. */
  6724. send_http_error(conn,
  6725. 417,
  6726. "Error: Can not fulfill expectation %s",
  6727. expect);
  6728. } else {
  6729. if (expect != NULL) {
  6730. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  6731. conn->status_code = 100;
  6732. } else {
  6733. conn->status_code = 200;
  6734. }
  6735. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  6736. - conn->consumed_content;
  6737. /* assert(buffered_len >= 0); */
  6738. /* assert(conn->consumed_content == 0); */
  6739. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  6740. send_http_error(conn, 500, "%s", "Error: Size mismatch");
  6741. return 0;
  6742. }
  6743. if (buffered_len > 0) {
  6744. if ((int64_t)buffered_len > conn->content_len) {
  6745. buffered_len = (int)conn->content_len;
  6746. }
  6747. body = conn->buf + conn->request_len + conn->consumed_content;
  6748. push_all(conn->ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  6749. conn->consumed_content += buffered_len;
  6750. }
  6751. nread = 0;
  6752. while (conn->consumed_content < conn->content_len) {
  6753. to_read = sizeof(buf);
  6754. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  6755. to_read = (int)(conn->content_len - conn->consumed_content);
  6756. }
  6757. nread = pull(NULL, conn, buf, to_read, timeout);
  6758. if (nread <= 0
  6759. || push_all(conn->ctx, fp, sock, ssl, buf, nread) != nread) {
  6760. break;
  6761. }
  6762. conn->consumed_content += nread;
  6763. }
  6764. if (conn->consumed_content == conn->content_len) {
  6765. success = (nread >= 0);
  6766. }
  6767. /* Each error code path in this function must send an error */
  6768. if (!success) {
  6769. /* NOTE: Maybe some data has already been sent. */
  6770. /* TODO (low): If some data has been sent, a correct error
  6771. * reply can no longer be sent, so just close the connection */
  6772. send_http_error(conn, 500, "%s", "");
  6773. }
  6774. }
  6775. return success;
  6776. }
  6777. #endif
  6778. #if !defined(NO_CGI)
  6779. /* This structure helps to create an environment for the spawned CGI program.
  6780. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  6781. * last element must be NULL.
  6782. * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  6783. * strings must reside in a contiguous buffer. The end of the buffer is
  6784. * marked by two '\0' characters.
  6785. * We satisfy both worlds: we create an envp array (which is vars), all
  6786. * entries are actually pointers inside buf. */
  6787. struct cgi_environment {
  6788. struct mg_connection *conn;
  6789. /* Data block */
  6790. char *buf; /* Environment buffer */
  6791. size_t buflen; /* Space available in buf */
  6792. size_t bufused; /* Space taken in buf */
  6793. /* Index block */
  6794. char **var; /* char **envp */
  6795. size_t varlen; /* Number of variables available in var */
  6796. size_t varused; /* Number of variables stored in var */
  6797. };
  6798. static void addenv(struct cgi_environment *env,
  6799. PRINTF_FORMAT_STRING(const char *fmt),
  6800. ...) PRINTF_ARGS(2, 3);
  6801. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  6802. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  6803. static void
  6804. addenv(struct cgi_environment *env, const char *fmt, ...)
  6805. {
  6806. size_t n, space;
  6807. int truncated = 0;
  6808. char *added;
  6809. va_list ap;
  6810. /* Calculate how much space is left in the buffer */
  6811. space = (env->buflen - env->bufused);
  6812. /* Calculate an estimate for the required space */
  6813. n = strlen(fmt) + 2 + 128;
  6814. do {
  6815. if (space <= n) {
  6816. /* Allocate new buffer */
  6817. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  6818. added = (char *)mg_realloc(env->buf, n);
  6819. if (!added) {
  6820. /* Out of memory */
  6821. mg_cry(env->conn,
  6822. "%s: Cannot allocate memory for CGI variable [%s]",
  6823. __func__,
  6824. fmt);
  6825. return;
  6826. }
  6827. env->buf = added;
  6828. env->buflen = n;
  6829. space = (env->buflen - env->bufused);
  6830. }
  6831. /* Make a pointer to the free space int the buffer */
  6832. added = env->buf + env->bufused;
  6833. /* Copy VARIABLE=VALUE\0 string into the free space */
  6834. va_start(ap, fmt);
  6835. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  6836. va_end(ap);
  6837. /* Do not add truncated strings to the environment */
  6838. if (truncated) {
  6839. /* Reallocate the buffer */
  6840. space = 0;
  6841. n = 1;
  6842. }
  6843. } while (truncated);
  6844. /* Calculate number of bytes added to the environment */
  6845. n = strlen(added) + 1;
  6846. env->bufused += n;
  6847. /* Now update the variable index */
  6848. space = (env->varlen - env->varused);
  6849. if (space < 2) {
  6850. mg_cry(env->conn,
  6851. "%s: Cannot register CGI variable [%s]",
  6852. __func__,
  6853. fmt);
  6854. return;
  6855. }
  6856. /* Append a pointer to the added string into the envp array */
  6857. env->var[env->varused] = added;
  6858. env->varused++;
  6859. }
  6860. static void
  6861. prepare_cgi_environment(struct mg_connection *conn,
  6862. const char *prog,
  6863. struct cgi_environment *env)
  6864. {
  6865. const char *s;
  6866. struct vec var_vec;
  6867. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  6868. int i, truncated;
  6869. if (conn == NULL || prog == NULL || env == NULL) {
  6870. return;
  6871. }
  6872. env->conn = conn;
  6873. env->buflen = CGI_ENVIRONMENT_SIZE;
  6874. env->bufused = 0;
  6875. env->buf = (char *)mg_malloc(env->buflen);
  6876. env->varlen = MAX_CGI_ENVIR_VARS;
  6877. env->varused = 0;
  6878. env->var = (char **)mg_malloc(env->buflen * sizeof(char *));
  6879. addenv(env, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  6880. addenv(env, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6881. addenv(env, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6882. addenv(env, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  6883. /* Prepare the environment block */
  6884. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  6885. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  6886. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  6887. #if defined(USE_IPV6)
  6888. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  6889. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  6890. } else
  6891. #endif
  6892. {
  6893. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  6894. }
  6895. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  6896. addenv(env, "REMOTE_ADDR=%s", src_addr);
  6897. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  6898. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  6899. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  6900. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  6901. /* SCRIPT_NAME */
  6902. addenv(env,
  6903. "SCRIPT_NAME=%.*s",
  6904. (int)strlen(conn->request_info.local_uri)
  6905. - ((conn->path_info == NULL) ? 0 : (int)strlen(conn->path_info)),
  6906. conn->request_info.local_uri);
  6907. addenv(env, "SCRIPT_FILENAME=%s", prog);
  6908. if (conn->path_info == NULL) {
  6909. addenv(env, "PATH_TRANSLATED=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6910. } else {
  6911. addenv(env,
  6912. "PATH_TRANSLATED=%s%s",
  6913. conn->ctx->config[DOCUMENT_ROOT],
  6914. conn->path_info);
  6915. }
  6916. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  6917. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  6918. addenv(env, "CONTENT_TYPE=%s", s);
  6919. }
  6920. if (conn->request_info.query_string != NULL) {
  6921. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  6922. }
  6923. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  6924. addenv(env, "CONTENT_LENGTH=%s", s);
  6925. }
  6926. if ((s = getenv("PATH")) != NULL) {
  6927. addenv(env, "PATH=%s", s);
  6928. }
  6929. if (conn->path_info != NULL) {
  6930. addenv(env, "PATH_INFO=%s", conn->path_info);
  6931. }
  6932. if (conn->status_code > 0) {
  6933. /* CGI error handler should show the status code */
  6934. addenv(env, "STATUS=%d", conn->status_code);
  6935. }
  6936. #if defined(_WIN32)
  6937. if ((s = getenv("COMSPEC")) != NULL) {
  6938. addenv(env, "COMSPEC=%s", s);
  6939. }
  6940. if ((s = getenv("SYSTEMROOT")) != NULL) {
  6941. addenv(env, "SYSTEMROOT=%s", s);
  6942. }
  6943. if ((s = getenv("SystemDrive")) != NULL) {
  6944. addenv(env, "SystemDrive=%s", s);
  6945. }
  6946. if ((s = getenv("ProgramFiles")) != NULL) {
  6947. addenv(env, "ProgramFiles=%s", s);
  6948. }
  6949. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  6950. addenv(env, "ProgramFiles(x86)=%s", s);
  6951. }
  6952. #else
  6953. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  6954. addenv(env, "LD_LIBRARY_PATH=%s", s);
  6955. }
  6956. #endif /* _WIN32 */
  6957. if ((s = getenv("PERLLIB")) != NULL) {
  6958. addenv(env, "PERLLIB=%s", s);
  6959. }
  6960. if (conn->request_info.remote_user != NULL) {
  6961. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  6962. addenv(env, "%s", "AUTH_TYPE=Digest");
  6963. }
  6964. /* Add all headers as HTTP_* variables */
  6965. for (i = 0; i < conn->request_info.num_headers; i++) {
  6966. (void)mg_snprintf(conn,
  6967. &truncated,
  6968. http_var_name,
  6969. sizeof(http_var_name),
  6970. "HTTP_%s",
  6971. conn->request_info.http_headers[i].name);
  6972. if (truncated) {
  6973. mg_cry(conn,
  6974. "%s: HTTP header variable too long [%s]",
  6975. __func__,
  6976. conn->request_info.http_headers[i].name);
  6977. continue;
  6978. }
  6979. /* Convert variable name into uppercase, and change - to _ */
  6980. for (p = http_var_name; *p != '\0'; p++) {
  6981. if (*p == '-') {
  6982. *p = '_';
  6983. }
  6984. *p = (char)toupper(*(unsigned char *)p);
  6985. }
  6986. addenv(env,
  6987. "%s=%s",
  6988. http_var_name,
  6989. conn->request_info.http_headers[i].value);
  6990. }
  6991. /* Add user-specified variables */
  6992. s = conn->ctx->config[CGI_ENVIRONMENT];
  6993. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  6994. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  6995. }
  6996. env->var[env->varused] = NULL;
  6997. env->buf[env->bufused] = '\0';
  6998. }
  6999. static void
  7000. handle_cgi_request(struct mg_connection *conn, const char *prog)
  7001. {
  7002. char *buf;
  7003. size_t buflen;
  7004. int headers_len, data_len, i, truncated;
  7005. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  7006. const char *status, *status_text, *connection_state;
  7007. char *pbuf, dir[PATH_MAX], *p;
  7008. struct mg_request_info ri;
  7009. struct cgi_environment blk;
  7010. FILE *in = NULL, *out = NULL, *err = NULL;
  7011. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  7012. pid_t pid = (pid_t)-1;
  7013. if (conn == NULL) {
  7014. return;
  7015. }
  7016. buf = NULL;
  7017. buflen = 16384;
  7018. prepare_cgi_environment(conn, prog, &blk);
  7019. /* CGI must be executed in its own directory. 'dir' must point to the
  7020. * directory containing executable program, 'p' must point to the
  7021. * executable program name relative to 'dir'. */
  7022. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  7023. if (truncated) {
  7024. mg_cry(conn, "Error: CGI program \"%s\": Path too long", prog);
  7025. send_http_error(conn, 500, "Error: %s", "CGI path too long");
  7026. goto done;
  7027. }
  7028. if ((p = strrchr(dir, '/')) != NULL) {
  7029. *p++ = '\0';
  7030. } else {
  7031. dir[0] = '.', dir[1] = '\0';
  7032. p = (char *)prog;
  7033. }
  7034. if (pipe(fdin) != 0 || pipe(fdout) != 0 || pipe(fderr) != 0) {
  7035. status = strerror(ERRNO);
  7036. mg_cry(conn,
  7037. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  7038. prog,
  7039. status);
  7040. send_http_error(conn, 500, "Error: Cannot create CGI pipe: %s", status);
  7041. goto done;
  7042. }
  7043. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  7044. if (pid == (pid_t)-1) {
  7045. status = strerror(ERRNO);
  7046. mg_cry(conn,
  7047. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  7048. prog,
  7049. status);
  7050. send_http_error(conn,
  7051. 500,
  7052. "Error: Cannot spawn CGI process [%s]: %s",
  7053. prog,
  7054. status);
  7055. goto done;
  7056. }
  7057. /* Make sure child closes all pipe descriptors. It must dup them to 0,1 */
  7058. set_close_on_exec((SOCKET)fdin[0], conn); /* stdin read */
  7059. set_close_on_exec((SOCKET)fdout[1], conn); /* stdout write */
  7060. set_close_on_exec((SOCKET)fderr[1], conn); /* stderr write */
  7061. set_close_on_exec((SOCKET)fdin[1], conn); /* stdin write */
  7062. set_close_on_exec((SOCKET)fdout[0], conn); /* stdout read */
  7063. set_close_on_exec((SOCKET)fderr[0], conn); /* stderr read */
  7064. /* Parent closes only one side of the pipes.
  7065. * If we don't mark them as closed, close() attempt before
  7066. * return from this function throws an exception on Windows.
  7067. * Windows does not like when closed descriptor is closed again. */
  7068. (void)close(fdin[0]);
  7069. (void)close(fdout[1]);
  7070. (void)close(fderr[1]);
  7071. fdin[0] = fdout[1] = fderr[1] = -1;
  7072. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  7073. status = strerror(ERRNO);
  7074. mg_cry(conn,
  7075. "Error: CGI program \"%s\": Can not open stdin: %s",
  7076. prog,
  7077. status);
  7078. send_http_error(conn,
  7079. 500,
  7080. "Error: CGI can not open fdin\nfopen: %s",
  7081. status);
  7082. goto done;
  7083. }
  7084. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  7085. status = strerror(ERRNO);
  7086. mg_cry(conn,
  7087. "Error: CGI program \"%s\": Can not open stdout: %s",
  7088. prog,
  7089. status);
  7090. send_http_error(conn,
  7091. 500,
  7092. "Error: CGI can not open fdout\nfopen: %s",
  7093. status);
  7094. goto done;
  7095. }
  7096. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  7097. status = strerror(ERRNO);
  7098. mg_cry(conn,
  7099. "Error: CGI program \"%s\": Can not open stderr: %s",
  7100. prog,
  7101. status);
  7102. send_http_error(conn,
  7103. 500,
  7104. "Error: CGI can not open fdout\nfopen: %s",
  7105. status);
  7106. goto done;
  7107. }
  7108. setbuf(in, NULL);
  7109. setbuf(out, NULL);
  7110. setbuf(err, NULL);
  7111. fout.access.fp = out;
  7112. if ((conn->request_info.content_length > 0) || conn->is_chunked) {
  7113. /* This is a POST/PUT request, or another request with body data. */
  7114. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  7115. /* Error sending the body data */
  7116. mg_cry(conn,
  7117. "Error: CGI program \"%s\": Forward body data failed",
  7118. prog);
  7119. goto done;
  7120. }
  7121. }
  7122. /* Close so child gets an EOF. */
  7123. fclose(in);
  7124. in = NULL;
  7125. fdin[1] = -1;
  7126. /* Now read CGI reply into a buffer. We need to set correct
  7127. * status code, thus we need to see all HTTP headers first.
  7128. * Do not send anything back to client, until we buffer in all
  7129. * HTTP headers. */
  7130. data_len = 0;
  7131. buf = (char *)mg_malloc(buflen);
  7132. if (buf == NULL) {
  7133. send_http_error(conn,
  7134. 500,
  7135. "Error: Not enough memory for CGI buffer (%u bytes)",
  7136. (unsigned int)buflen);
  7137. mg_cry(conn,
  7138. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  7139. "bytes)",
  7140. prog,
  7141. (unsigned int)buflen);
  7142. goto done;
  7143. }
  7144. headers_len = read_request(out, conn, buf, (int)buflen, &data_len);
  7145. if (headers_len <= 0) {
  7146. /* Could not parse the CGI response. Check if some error message on
  7147. * stderr. */
  7148. i = pull_all(err, conn, buf, (int)buflen);
  7149. if (i > 0) {
  7150. mg_cry(conn,
  7151. "Error: CGI program \"%s\" sent error "
  7152. "message: [%.*s]",
  7153. prog,
  7154. i,
  7155. buf);
  7156. send_http_error(conn,
  7157. 500,
  7158. "Error: CGI program \"%s\" sent error "
  7159. "message: [%.*s]",
  7160. prog,
  7161. i,
  7162. buf);
  7163. } else {
  7164. mg_cry(conn,
  7165. "Error: CGI program sent malformed or too big "
  7166. "(>%u bytes) HTTP headers: [%.*s]",
  7167. (unsigned)buflen,
  7168. data_len,
  7169. buf);
  7170. send_http_error(conn,
  7171. 500,
  7172. "Error: CGI program sent malformed or too big "
  7173. "(>%u bytes) HTTP headers: [%.*s]",
  7174. (unsigned)buflen,
  7175. data_len,
  7176. buf);
  7177. }
  7178. goto done;
  7179. }
  7180. pbuf = buf;
  7181. buf[headers_len - 1] = '\0';
  7182. parse_http_headers(&pbuf, &ri);
  7183. /* Make up and send the status line */
  7184. status_text = "OK";
  7185. if ((status = get_header(&ri, "Status")) != NULL) {
  7186. conn->status_code = atoi(status);
  7187. status_text = status;
  7188. while (isdigit(*(const unsigned char *)status_text)
  7189. || *status_text == ' ') {
  7190. status_text++;
  7191. }
  7192. } else if (get_header(&ri, "Location") != NULL) {
  7193. conn->status_code = 302;
  7194. } else {
  7195. conn->status_code = 200;
  7196. }
  7197. connection_state = get_header(&ri, "Connection");
  7198. if (!header_has_option(connection_state, "keep-alive")) {
  7199. conn->must_close = 1;
  7200. }
  7201. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  7202. /* Send headers */
  7203. for (i = 0; i < ri.num_headers; i++) {
  7204. mg_printf(conn,
  7205. "%s: %s\r\n",
  7206. ri.http_headers[i].name,
  7207. ri.http_headers[i].value);
  7208. }
  7209. mg_write(conn, "\r\n", 2);
  7210. /* Send chunk of data that may have been read after the headers */
  7211. conn->num_bytes_sent +=
  7212. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  7213. /* Read the rest of CGI output and send to the client */
  7214. send_file_data(conn, &fout, 0, INT64_MAX);
  7215. done:
  7216. mg_free(blk.var);
  7217. mg_free(blk.buf);
  7218. if (pid != (pid_t)-1) {
  7219. kill(pid, SIGKILL);
  7220. #if !defined(_WIN32)
  7221. {
  7222. int st;
  7223. while (waitpid(pid, &st, 0) != -1)
  7224. ; /* clean zombies */
  7225. }
  7226. #endif
  7227. }
  7228. if (fdin[0] != -1) {
  7229. close(fdin[0]);
  7230. }
  7231. if (fdout[1] != -1) {
  7232. close(fdout[1]);
  7233. }
  7234. if (in != NULL) {
  7235. fclose(in);
  7236. } else if (fdin[1] != -1) {
  7237. close(fdin[1]);
  7238. }
  7239. if (out != NULL) {
  7240. fclose(out);
  7241. } else if (fdout[0] != -1) {
  7242. close(fdout[0]);
  7243. }
  7244. if (err != NULL) {
  7245. fclose(err);
  7246. } else if (fderr[0] != -1) {
  7247. close(fderr[0]);
  7248. }
  7249. if (buf != NULL) {
  7250. mg_free(buf);
  7251. }
  7252. }
  7253. #endif /* !NO_CGI */
  7254. #if !defined(NO_FILES)
  7255. static void
  7256. mkcol(struct mg_connection *conn, const char *path)
  7257. {
  7258. int rc, body_len;
  7259. struct de de;
  7260. char date[64];
  7261. time_t curtime = time(NULL);
  7262. if (conn == NULL) {
  7263. return;
  7264. }
  7265. /* TODO (mid): Check the send_http_error situations in this function */
  7266. memset(&de.file, 0, sizeof(de.file));
  7267. if (!mg_stat(conn, path, &de.file)) {
  7268. mg_cry(conn,
  7269. "%s: mg_stat(%s) failed: %s",
  7270. __func__,
  7271. path,
  7272. strerror(ERRNO));
  7273. }
  7274. if (de.file.last_modified) {
  7275. /* TODO (high): This check does not seem to make any sense ! */
  7276. send_http_error(
  7277. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7278. return;
  7279. }
  7280. body_len = conn->data_len - conn->request_len;
  7281. if (body_len > 0) {
  7282. send_http_error(
  7283. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7284. return;
  7285. }
  7286. rc = mg_mkdir(conn, path, 0755);
  7287. if (rc == 0) {
  7288. conn->status_code = 201;
  7289. gmt_time_string(date, sizeof(date), &curtime);
  7290. mg_printf(conn,
  7291. "HTTP/1.1 %d Created\r\n"
  7292. "Date: %s\r\n",
  7293. conn->status_code,
  7294. date);
  7295. send_static_cache_header(conn);
  7296. mg_printf(conn,
  7297. "Content-Length: 0\r\n"
  7298. "Connection: %s\r\n\r\n",
  7299. suggest_connection_header(conn));
  7300. } else if (rc == -1) {
  7301. if (errno == EEXIST) {
  7302. send_http_error(
  7303. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7304. } else if (errno == EACCES) {
  7305. send_http_error(
  7306. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7307. } else if (errno == ENOENT) {
  7308. send_http_error(
  7309. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7310. } else {
  7311. send_http_error(conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  7312. }
  7313. }
  7314. }
  7315. static void
  7316. put_file(struct mg_connection *conn, const char *path)
  7317. {
  7318. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7319. const char *range;
  7320. int64_t r1, r2;
  7321. int rc;
  7322. char date[64];
  7323. time_t curtime = time(NULL);
  7324. if (conn == NULL) {
  7325. return;
  7326. }
  7327. if (mg_stat(conn, path, &file.stat)) {
  7328. /* File already exists */
  7329. conn->status_code = 200;
  7330. if (file.stat.is_directory) {
  7331. /* This is an already existing directory,
  7332. * so there is nothing to do for the server. */
  7333. rc = 0;
  7334. } else {
  7335. /* File exists and is not a directory. */
  7336. /* Can it be replaced? */
  7337. if (file.access.membuf != NULL) {
  7338. /* This is an "in-memory" file, that can not be replaced */
  7339. send_http_error(
  7340. conn,
  7341. 405,
  7342. "Error: Put not possible\nReplacing %s is not supported",
  7343. path);
  7344. return;
  7345. }
  7346. /* Check if the server may write this file */
  7347. if (access(path, W_OK) == 0) {
  7348. /* Access granted */
  7349. conn->status_code = 200;
  7350. rc = 1;
  7351. } else {
  7352. send_http_error(
  7353. conn,
  7354. 403,
  7355. "Error: Put not possible\nReplacing %s is not allowed",
  7356. path);
  7357. return;
  7358. }
  7359. }
  7360. } else {
  7361. /* File should be created */
  7362. conn->status_code = 201;
  7363. rc = put_dir(conn, path);
  7364. }
  7365. if (rc == 0) {
  7366. /* put_dir returns 0 if path is a directory */
  7367. gmt_time_string(date, sizeof(date), &curtime);
  7368. mg_printf(conn,
  7369. "HTTP/1.1 %d %s\r\n",
  7370. conn->status_code,
  7371. mg_get_response_code_text(NULL, conn->status_code));
  7372. send_no_cache_header(conn);
  7373. mg_printf(conn,
  7374. "Date: %s\r\n"
  7375. "Content-Length: 0\r\n"
  7376. "Connection: %s\r\n\r\n",
  7377. date,
  7378. suggest_connection_header(conn));
  7379. /* Request to create a directory has been fulfilled successfully.
  7380. * No need to put a file. */
  7381. return;
  7382. }
  7383. if (rc == -1) {
  7384. /* put_dir returns -1 if the path is too long */
  7385. send_http_error(conn,
  7386. 414,
  7387. "Error: Path too long\nput_dir(%s): %s",
  7388. path,
  7389. strerror(ERRNO));
  7390. return;
  7391. }
  7392. if (rc == -2) {
  7393. /* put_dir returns -2 if the directory can not be created */
  7394. send_http_error(conn,
  7395. 500,
  7396. "Error: Can not create directory\nput_dir(%s): %s",
  7397. path,
  7398. strerror(ERRNO));
  7399. return;
  7400. }
  7401. /* A file should be created or overwritten. */
  7402. /* TODO: Test if write or write+read is required. */
  7403. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  7404. || file.access.fp == NULL) {
  7405. (void)mg_fclose(&file.access);
  7406. send_http_error(conn,
  7407. 500,
  7408. "Error: Can not create file\nfopen(%s): %s",
  7409. path,
  7410. strerror(ERRNO));
  7411. return;
  7412. }
  7413. fclose_on_exec(&file.access, conn);
  7414. range = mg_get_header(conn, "Content-Range");
  7415. r1 = r2 = 0;
  7416. if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
  7417. conn->status_code = 206; /* Partial content */
  7418. fseeko(file.access.fp, r1, SEEK_SET);
  7419. }
  7420. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  7421. /* forward_body_data failed.
  7422. * The error code has already been sent to the client,
  7423. * and conn->status_code is already set. */
  7424. (void)mg_fclose(&file.access);
  7425. return;
  7426. }
  7427. if (mg_fclose(&file.access) != 0) {
  7428. /* fclose failed. This might have different reasons, but a likely
  7429. * one is "no space on disk", http 507. */
  7430. conn->status_code = 507;
  7431. }
  7432. gmt_time_string(date, sizeof(date), &curtime);
  7433. mg_printf(conn,
  7434. "HTTP/1.1 %d %s\r\n",
  7435. conn->status_code,
  7436. mg_get_response_code_text(NULL, conn->status_code));
  7437. send_no_cache_header(conn);
  7438. mg_printf(conn,
  7439. "Date: %s\r\n"
  7440. "Content-Length: 0\r\n"
  7441. "Connection: %s\r\n\r\n",
  7442. date,
  7443. suggest_connection_header(conn));
  7444. }
  7445. static void
  7446. delete_file(struct mg_connection *conn, const char *path)
  7447. {
  7448. struct de de;
  7449. memset(&de.file, 0, sizeof(de.file));
  7450. if (!mg_stat(conn, path, &de.file)) {
  7451. /* mg_stat returns 0 if the file does not exist */
  7452. send_http_error(conn,
  7453. 404,
  7454. "Error: Cannot delete file\nFile %s not found",
  7455. path);
  7456. return;
  7457. }
  7458. #if 0 /* Ignore if a file in memory is inside a folder */
  7459. if (de.access.membuf != NULL) {
  7460. /* the file is cached in memory */
  7461. send_http_error(
  7462. conn,
  7463. 405,
  7464. "Error: Delete not possible\nDeleting %s is not supported",
  7465. path);
  7466. return;
  7467. }
  7468. #endif
  7469. if (de.file.is_directory) {
  7470. if (remove_directory(conn, path)) {
  7471. /* Delete is successful: Return 204 without content. */
  7472. send_http_error(conn, 204, "%s", "");
  7473. } else {
  7474. /* Delete is not successful: Return 500 (Server error). */
  7475. send_http_error(conn, 500, "Error: Could not delete %s", path);
  7476. }
  7477. return;
  7478. }
  7479. /* This is an existing file (not a directory).
  7480. * Check if write permission is granted. */
  7481. if (access(path, W_OK) != 0) {
  7482. /* File is read only */
  7483. send_http_error(
  7484. conn,
  7485. 403,
  7486. "Error: Delete not possible\nDeleting %s is not allowed",
  7487. path);
  7488. return;
  7489. }
  7490. /* Try to delete it. */
  7491. if (mg_remove(conn, path) == 0) {
  7492. /* Delete was successful: Return 204 without content. */
  7493. send_http_error(conn, 204, "%s", "");
  7494. } else {
  7495. /* Delete not successful (file locked). */
  7496. send_http_error(conn,
  7497. 423,
  7498. "Error: Cannot delete file\nremove(%s): %s",
  7499. path,
  7500. strerror(ERRNO));
  7501. }
  7502. }
  7503. #endif /* !NO_FILES */
  7504. static void
  7505. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  7506. static void
  7507. do_ssi_include(struct mg_connection *conn,
  7508. const char *ssi,
  7509. char *tag,
  7510. int include_level)
  7511. {
  7512. char file_name[MG_BUF_LEN], path[512], *p;
  7513. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7514. size_t len;
  7515. int truncated = 0;
  7516. if (conn == NULL) {
  7517. return;
  7518. }
  7519. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  7520. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  7521. * always < MG_BUF_LEN. */
  7522. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  7523. /* File name is relative to the webserver root */
  7524. file_name[511] = 0;
  7525. (void)mg_snprintf(conn,
  7526. &truncated,
  7527. path,
  7528. sizeof(path),
  7529. "%s/%s",
  7530. conn->ctx->config[DOCUMENT_ROOT],
  7531. file_name);
  7532. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  7533. /* File name is relative to the webserver working directory
  7534. * or it is absolute system path */
  7535. file_name[511] = 0;
  7536. (void)
  7537. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  7538. } else if (sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1
  7539. || sscanf(tag, " \"%511[^\"]\"", file_name) == 1) {
  7540. /* File name is relative to the currect document */
  7541. file_name[511] = 0;
  7542. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  7543. if (!truncated) {
  7544. if ((p = strrchr(path, '/')) != NULL) {
  7545. p[1] = '\0';
  7546. }
  7547. len = strlen(path);
  7548. (void)mg_snprintf(conn,
  7549. &truncated,
  7550. path + len,
  7551. sizeof(path) - len,
  7552. "%s",
  7553. file_name);
  7554. }
  7555. } else {
  7556. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  7557. return;
  7558. }
  7559. if (truncated) {
  7560. mg_cry(conn, "SSI #include path length overflow: [%s]", tag);
  7561. return;
  7562. }
  7563. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  7564. mg_cry(conn,
  7565. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  7566. tag,
  7567. path,
  7568. strerror(ERRNO));
  7569. } else {
  7570. fclose_on_exec(&file.access, conn);
  7571. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  7572. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  7573. path) > 0) {
  7574. send_ssi_file(conn, path, &file, include_level + 1);
  7575. } else {
  7576. send_file_data(conn, &file, 0, INT64_MAX);
  7577. }
  7578. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  7579. }
  7580. }
  7581. #if !defined(NO_POPEN)
  7582. static void
  7583. do_ssi_exec(struct mg_connection *conn, char *tag)
  7584. {
  7585. char cmd[1024] = "";
  7586. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7587. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  7588. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  7589. } else {
  7590. cmd[1023] = 0;
  7591. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  7592. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  7593. } else {
  7594. send_file_data(conn, &file, 0, INT64_MAX);
  7595. pclose(file.access.fp);
  7596. }
  7597. }
  7598. }
  7599. #endif /* !NO_POPEN */
  7600. static int
  7601. mg_fgetc(struct mg_file *filep, int offset)
  7602. {
  7603. if (filep == NULL) {
  7604. return EOF;
  7605. }
  7606. if (filep->access.membuf != NULL && offset >= 0
  7607. && ((unsigned int)(offset)) < filep->stat.size) {
  7608. return ((const unsigned char *)filep->access.membuf)[offset];
  7609. } else if (filep->access.fp != NULL) {
  7610. return fgetc(filep->access.fp);
  7611. } else {
  7612. return EOF;
  7613. }
  7614. }
  7615. static void
  7616. send_ssi_file(struct mg_connection *conn,
  7617. const char *path,
  7618. struct mg_file *filep,
  7619. int include_level)
  7620. {
  7621. char buf[MG_BUF_LEN];
  7622. int ch, offset, len, in_ssi_tag;
  7623. if (include_level > 10) {
  7624. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  7625. return;
  7626. }
  7627. in_ssi_tag = len = offset = 0;
  7628. while ((ch = mg_fgetc(filep, offset)) != EOF) {
  7629. if (in_ssi_tag && ch == '>') {
  7630. in_ssi_tag = 0;
  7631. buf[len++] = (char)ch;
  7632. buf[len] = '\0';
  7633. /* assert(len <= (int) sizeof(buf)); */
  7634. if (len > (int)sizeof(buf)) {
  7635. break;
  7636. }
  7637. if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
  7638. /* Not an SSI tag, pass it */
  7639. (void)mg_write(conn, buf, (size_t)len);
  7640. } else {
  7641. if (!memcmp(buf + 5, "include", 7)) {
  7642. do_ssi_include(conn, path, buf + 12, include_level);
  7643. #if !defined(NO_POPEN)
  7644. } else if (!memcmp(buf + 5, "exec", 4)) {
  7645. do_ssi_exec(conn, buf + 9);
  7646. #endif /* !NO_POPEN */
  7647. } else {
  7648. mg_cry(conn,
  7649. "%s: unknown SSI "
  7650. "command: \"%s\"",
  7651. path,
  7652. buf);
  7653. }
  7654. }
  7655. len = 0;
  7656. } else if (in_ssi_tag) {
  7657. if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
  7658. /* Not an SSI tag */
  7659. in_ssi_tag = 0;
  7660. } else if (len == (int)sizeof(buf) - 2) {
  7661. mg_cry(conn, "%s: SSI tag is too large", path);
  7662. len = 0;
  7663. }
  7664. buf[len++] = (char)(ch & 0xff);
  7665. } else if (ch == '<') {
  7666. in_ssi_tag = 1;
  7667. if (len > 0) {
  7668. mg_write(conn, buf, (size_t)len);
  7669. }
  7670. len = 0;
  7671. buf[len++] = (char)(ch & 0xff);
  7672. } else {
  7673. buf[len++] = (char)(ch & 0xff);
  7674. if (len == (int)sizeof(buf)) {
  7675. mg_write(conn, buf, (size_t)len);
  7676. len = 0;
  7677. }
  7678. }
  7679. }
  7680. /* Send the rest of buffered data */
  7681. if (len > 0) {
  7682. mg_write(conn, buf, (size_t)len);
  7683. }
  7684. }
  7685. static void
  7686. handle_ssi_file_request(struct mg_connection *conn,
  7687. const char *path,
  7688. struct mg_file *filep)
  7689. {
  7690. char date[64];
  7691. time_t curtime = time(NULL);
  7692. const char *cors1, *cors2, *cors3;
  7693. if (conn == NULL || path == NULL || filep == NULL) {
  7694. return;
  7695. }
  7696. if (mg_get_header(conn, "Origin")) {
  7697. /* Cross-origin resource sharing (CORS). */
  7698. cors1 = "Access-Control-Allow-Origin: ";
  7699. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  7700. cors3 = "\r\n";
  7701. } else {
  7702. cors1 = cors2 = cors3 = "";
  7703. }
  7704. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  7705. /* File exists (precondition for calling this function),
  7706. * but can not be opened by the server. */
  7707. send_http_error(conn,
  7708. 500,
  7709. "Error: Cannot read file\nfopen(%s): %s",
  7710. path,
  7711. strerror(ERRNO));
  7712. } else {
  7713. conn->must_close = 1;
  7714. gmt_time_string(date, sizeof(date), &curtime);
  7715. fclose_on_exec(&filep->access, conn);
  7716. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  7717. send_no_cache_header(conn);
  7718. mg_printf(conn,
  7719. "%s%s%s"
  7720. "Date: %s\r\n"
  7721. "Content-Type: text/html\r\n"
  7722. "Connection: %s\r\n\r\n",
  7723. cors1,
  7724. cors2,
  7725. cors3,
  7726. date,
  7727. suggest_connection_header(conn));
  7728. send_ssi_file(conn, path, filep, 0);
  7729. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  7730. }
  7731. }
  7732. #if !defined(NO_FILES)
  7733. static void
  7734. send_options(struct mg_connection *conn)
  7735. {
  7736. char date[64];
  7737. time_t curtime = time(NULL);
  7738. if (!conn) {
  7739. return;
  7740. }
  7741. conn->status_code = 200;
  7742. conn->must_close = 1;
  7743. gmt_time_string(date, sizeof(date), &curtime);
  7744. mg_printf(conn,
  7745. "HTTP/1.1 200 OK\r\n"
  7746. "Date: %s\r\n"
  7747. /* TODO: "Cache-Control" (?) */
  7748. "Connection: %s\r\n"
  7749. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  7750. "PROPFIND, MKCOL\r\n"
  7751. "DAV: 1\r\n\r\n",
  7752. date,
  7753. suggest_connection_header(conn));
  7754. }
  7755. /* Writes PROPFIND properties for a collection element */
  7756. static void
  7757. print_props(struct mg_connection *conn,
  7758. const char *uri,
  7759. struct mg_file_stat *filep)
  7760. {
  7761. char mtime[64];
  7762. if (conn == NULL || uri == NULL || filep == NULL) {
  7763. return;
  7764. }
  7765. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  7766. conn->num_bytes_sent +=
  7767. mg_printf(conn,
  7768. "<d:response>"
  7769. "<d:href>%s</d:href>"
  7770. "<d:propstat>"
  7771. "<d:prop>"
  7772. "<d:resourcetype>%s</d:resourcetype>"
  7773. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  7774. "<d:getlastmodified>%s</d:getlastmodified>"
  7775. "</d:prop>"
  7776. "<d:status>HTTP/1.1 200 OK</d:status>"
  7777. "</d:propstat>"
  7778. "</d:response>\n",
  7779. uri,
  7780. filep->is_directory ? "<d:collection/>" : "",
  7781. filep->size,
  7782. mtime);
  7783. }
  7784. static void
  7785. print_dav_dir_entry(struct de *de, void *data)
  7786. {
  7787. char href[PATH_MAX];
  7788. char href_encoded[PATH_MAX * 3 /* worst case */];
  7789. int truncated;
  7790. struct mg_connection *conn = (struct mg_connection *)data;
  7791. if (!de || !conn) {
  7792. return;
  7793. }
  7794. mg_snprintf(conn,
  7795. &truncated,
  7796. href,
  7797. sizeof(href),
  7798. "%s%s",
  7799. conn->request_info.local_uri,
  7800. de->file_name);
  7801. if (!truncated) {
  7802. mg_url_encode(href, href_encoded, PATH_MAX * 3);
  7803. print_props(conn, href_encoded, &de->file);
  7804. }
  7805. }
  7806. static void
  7807. handle_propfind(struct mg_connection *conn,
  7808. const char *path,
  7809. struct mg_file_stat *filep)
  7810. {
  7811. const char *depth = mg_get_header(conn, "Depth");
  7812. char date[64];
  7813. time_t curtime = time(NULL);
  7814. gmt_time_string(date, sizeof(date), &curtime);
  7815. if (!conn || !path || !filep || !conn->ctx) {
  7816. return;
  7817. }
  7818. conn->must_close = 1;
  7819. conn->status_code = 207;
  7820. mg_printf(conn,
  7821. "HTTP/1.1 207 Multi-Status\r\n"
  7822. "Date: %s\r\n",
  7823. date);
  7824. send_static_cache_header(conn);
  7825. mg_printf(conn,
  7826. "Connection: %s\r\n"
  7827. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  7828. suggest_connection_header(conn));
  7829. conn->num_bytes_sent +=
  7830. mg_printf(conn,
  7831. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  7832. "<d:multistatus xmlns:d='DAV:'>\n");
  7833. /* Print properties for the requested resource itself */
  7834. print_props(conn, conn->request_info.local_uri, filep);
  7835. /* If it is a directory, print directory entries too if Depth is not 0 */
  7836. if (filep && filep->is_directory
  7837. && !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")
  7838. && (depth == NULL || strcmp(depth, "0") != 0)) {
  7839. scan_directory(conn, path, conn, &print_dav_dir_entry);
  7840. }
  7841. conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");
  7842. }
  7843. #endif
  7844. void
  7845. mg_lock_connection(struct mg_connection *conn)
  7846. {
  7847. if (conn) {
  7848. (void)pthread_mutex_lock(&conn->mutex);
  7849. }
  7850. }
  7851. void
  7852. mg_unlock_connection(struct mg_connection *conn)
  7853. {
  7854. if (conn) {
  7855. (void)pthread_mutex_unlock(&conn->mutex);
  7856. }
  7857. }
  7858. void
  7859. mg_lock_context(struct mg_context *ctx)
  7860. {
  7861. if (ctx) {
  7862. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  7863. }
  7864. }
  7865. void
  7866. mg_unlock_context(struct mg_context *ctx)
  7867. {
  7868. if (ctx) {
  7869. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  7870. }
  7871. }
  7872. #if defined(USE_TIMERS)
  7873. #include "timer.inl"
  7874. #endif /* USE_TIMERS */
  7875. #ifdef USE_LUA
  7876. #include "mod_lua.inl"
  7877. #endif /* USE_LUA */
  7878. #ifdef USE_DUKTAPE
  7879. #include "mod_duktape.inl"
  7880. #endif /* USE_DUKTAPE */
  7881. #if defined(USE_WEBSOCKET)
  7882. /* START OF SHA-1 code
  7883. * Copyright(c) By Steve Reid <steve@edmweb.com> */
  7884. #define SHA1HANDSOFF
  7885. /* According to current tests (May 2015), the <solarisfixes.h> is not required.
  7886. *
  7887. * #if defined(__sun)
  7888. * #include "solarisfixes.h"
  7889. * #endif
  7890. */
  7891. static int
  7892. is_big_endian(void)
  7893. {
  7894. static const int n = 1;
  7895. return ((char *)&n)[0] == 0;
  7896. }
  7897. union char64long16 {
  7898. unsigned char c[64];
  7899. uint32_t l[16];
  7900. };
  7901. #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
  7902. static uint32_t
  7903. blk0(union char64long16 *block, int i)
  7904. {
  7905. /* Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN */
  7906. if (!is_big_endian()) {
  7907. block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00)
  7908. | (rol(block->l[i], 8) & 0x00FF00FF);
  7909. }
  7910. return block->l[i];
  7911. }
  7912. #define blk(i) \
  7913. (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] \
  7914. ^ block->l[(i + 2) & 15] ^ block->l[i & 15], \
  7915. 1))
  7916. #define R0(v, w, x, y, z, i) \
  7917. z += ((w & (x ^ y)) ^ y) + blk0(block, i) + 0x5A827999 + rol(v, 5); \
  7918. w = rol(w, 30);
  7919. #define R1(v, w, x, y, z, i) \
  7920. z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \
  7921. w = rol(w, 30);
  7922. #define R2(v, w, x, y, z, i) \
  7923. z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \
  7924. w = rol(w, 30);
  7925. #define R3(v, w, x, y, z, i) \
  7926. z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \
  7927. w = rol(w, 30);
  7928. #define R4(v, w, x, y, z, i) \
  7929. z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \
  7930. w = rol(w, 30);
  7931. typedef struct {
  7932. uint32_t state[5];
  7933. uint32_t count[2];
  7934. unsigned char buffer[64];
  7935. } SHA1_CTX;
  7936. static void
  7937. SHA1Transform(uint32_t state[5], const unsigned char buffer[64])
  7938. {
  7939. uint32_t a, b, c, d, e;
  7940. union char64long16 block[1];
  7941. memcpy(block, buffer, 64);
  7942. a = state[0];
  7943. b = state[1];
  7944. c = state[2];
  7945. d = state[3];
  7946. e = state[4];
  7947. R0(a, b, c, d, e, 0);
  7948. R0(e, a, b, c, d, 1);
  7949. R0(d, e, a, b, c, 2);
  7950. R0(c, d, e, a, b, 3);
  7951. R0(b, c, d, e, a, 4);
  7952. R0(a, b, c, d, e, 5);
  7953. R0(e, a, b, c, d, 6);
  7954. R0(d, e, a, b, c, 7);
  7955. R0(c, d, e, a, b, 8);
  7956. R0(b, c, d, e, a, 9);
  7957. R0(a, b, c, d, e, 10);
  7958. R0(e, a, b, c, d, 11);
  7959. R0(d, e, a, b, c, 12);
  7960. R0(c, d, e, a, b, 13);
  7961. R0(b, c, d, e, a, 14);
  7962. R0(a, b, c, d, e, 15);
  7963. R1(e, a, b, c, d, 16);
  7964. R1(d, e, a, b, c, 17);
  7965. R1(c, d, e, a, b, 18);
  7966. R1(b, c, d, e, a, 19);
  7967. R2(a, b, c, d, e, 20);
  7968. R2(e, a, b, c, d, 21);
  7969. R2(d, e, a, b, c, 22);
  7970. R2(c, d, e, a, b, 23);
  7971. R2(b, c, d, e, a, 24);
  7972. R2(a, b, c, d, e, 25);
  7973. R2(e, a, b, c, d, 26);
  7974. R2(d, e, a, b, c, 27);
  7975. R2(c, d, e, a, b, 28);
  7976. R2(b, c, d, e, a, 29);
  7977. R2(a, b, c, d, e, 30);
  7978. R2(e, a, b, c, d, 31);
  7979. R2(d, e, a, b, c, 32);
  7980. R2(c, d, e, a, b, 33);
  7981. R2(b, c, d, e, a, 34);
  7982. R2(a, b, c, d, e, 35);
  7983. R2(e, a, b, c, d, 36);
  7984. R2(d, e, a, b, c, 37);
  7985. R2(c, d, e, a, b, 38);
  7986. R2(b, c, d, e, a, 39);
  7987. R3(a, b, c, d, e, 40);
  7988. R3(e, a, b, c, d, 41);
  7989. R3(d, e, a, b, c, 42);
  7990. R3(c, d, e, a, b, 43);
  7991. R3(b, c, d, e, a, 44);
  7992. R3(a, b, c, d, e, 45);
  7993. R3(e, a, b, c, d, 46);
  7994. R3(d, e, a, b, c, 47);
  7995. R3(c, d, e, a, b, 48);
  7996. R3(b, c, d, e, a, 49);
  7997. R3(a, b, c, d, e, 50);
  7998. R3(e, a, b, c, d, 51);
  7999. R3(d, e, a, b, c, 52);
  8000. R3(c, d, e, a, b, 53);
  8001. R3(b, c, d, e, a, 54);
  8002. R3(a, b, c, d, e, 55);
  8003. R3(e, a, b, c, d, 56);
  8004. R3(d, e, a, b, c, 57);
  8005. R3(c, d, e, a, b, 58);
  8006. R3(b, c, d, e, a, 59);
  8007. R4(a, b, c, d, e, 60);
  8008. R4(e, a, b, c, d, 61);
  8009. R4(d, e, a, b, c, 62);
  8010. R4(c, d, e, a, b, 63);
  8011. R4(b, c, d, e, a, 64);
  8012. R4(a, b, c, d, e, 65);
  8013. R4(e, a, b, c, d, 66);
  8014. R4(d, e, a, b, c, 67);
  8015. R4(c, d, e, a, b, 68);
  8016. R4(b, c, d, e, a, 69);
  8017. R4(a, b, c, d, e, 70);
  8018. R4(e, a, b, c, d, 71);
  8019. R4(d, e, a, b, c, 72);
  8020. R4(c, d, e, a, b, 73);
  8021. R4(b, c, d, e, a, 74);
  8022. R4(a, b, c, d, e, 75);
  8023. R4(e, a, b, c, d, 76);
  8024. R4(d, e, a, b, c, 77);
  8025. R4(c, d, e, a, b, 78);
  8026. R4(b, c, d, e, a, 79);
  8027. state[0] += a;
  8028. state[1] += b;
  8029. state[2] += c;
  8030. state[3] += d;
  8031. state[4] += e;
  8032. a = b = c = d = e = 0;
  8033. memset(block, '\0', sizeof(block));
  8034. }
  8035. static void
  8036. SHA1Init(SHA1_CTX *context)
  8037. {
  8038. context->state[0] = 0x67452301;
  8039. context->state[1] = 0xEFCDAB89;
  8040. context->state[2] = 0x98BADCFE;
  8041. context->state[3] = 0x10325476;
  8042. context->state[4] = 0xC3D2E1F0;
  8043. context->count[0] = context->count[1] = 0;
  8044. }
  8045. static void
  8046. SHA1Update(SHA1_CTX *context, const unsigned char *data, uint32_t len)
  8047. {
  8048. uint32_t i, j;
  8049. j = context->count[0];
  8050. if ((context->count[0] += len << 3) < j) {
  8051. context->count[1]++;
  8052. }
  8053. context->count[1] += (len >> 29);
  8054. j = (j >> 3) & 63;
  8055. if ((j + len) > 63) {
  8056. memcpy(&context->buffer[j], data, (i = 64 - j));
  8057. SHA1Transform(context->state, context->buffer);
  8058. for (; i + 63 < len; i += 64) {
  8059. SHA1Transform(context->state, &data[i]);
  8060. }
  8061. j = 0;
  8062. } else
  8063. i = 0;
  8064. memcpy(&context->buffer[j], &data[i], len - i);
  8065. }
  8066. static void
  8067. SHA1Final(unsigned char digest[20], SHA1_CTX *context)
  8068. {
  8069. unsigned i;
  8070. unsigned char finalcount[8], c;
  8071. for (i = 0; i < 8; i++) {
  8072. finalcount[i] = (unsigned char)((context->count[(i >= 4) ? 0 : 1]
  8073. >> ((3 - (i & 3)) * 8)) & 255);
  8074. }
  8075. c = 0200;
  8076. SHA1Update(context, &c, 1);
  8077. while ((context->count[0] & 504) != 448) {
  8078. c = 0000;
  8079. SHA1Update(context, &c, 1);
  8080. }
  8081. SHA1Update(context, finalcount, 8);
  8082. for (i = 0; i < 20; i++) {
  8083. digest[i] = (unsigned char)((context->state[i >> 2]
  8084. >> ((3 - (i & 3)) * 8)) & 255);
  8085. }
  8086. memset(context, '\0', sizeof(*context));
  8087. memset(&finalcount, '\0', sizeof(finalcount));
  8088. }
  8089. /* END OF SHA1 CODE */
  8090. static int
  8091. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  8092. {
  8093. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  8094. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  8095. SHA1_CTX sha_ctx;
  8096. int truncated;
  8097. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  8098. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  8099. if (truncated) {
  8100. conn->must_close = 1;
  8101. return 0;
  8102. }
  8103. SHA1Init(&sha_ctx);
  8104. SHA1Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  8105. SHA1Final((unsigned char *)sha, &sha_ctx);
  8106. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  8107. mg_printf(conn,
  8108. "HTTP/1.1 101 Switching Protocols\r\n"
  8109. "Upgrade: websocket\r\n"
  8110. "Connection: Upgrade\r\n"
  8111. "Sec-WebSocket-Accept: %s\r\n",
  8112. b64_sha);
  8113. if (conn->request_info.acceptedWebSocketSubprotocol) {
  8114. mg_printf(conn,
  8115. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  8116. conn->request_info.acceptedWebSocketSubprotocol);
  8117. } else {
  8118. mg_printf(conn, "%s", "\r\n");
  8119. }
  8120. return 1;
  8121. }
  8122. static void
  8123. read_websocket(struct mg_connection *conn,
  8124. mg_websocket_data_handler ws_data_handler,
  8125. void *callback_data)
  8126. {
  8127. /* Pointer to the beginning of the portion of the incoming websocket
  8128. * message queue.
  8129. * The original websocket upgrade request is never removed, so the queue
  8130. * begins after it. */
  8131. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  8132. int n, error, exit_by_callback;
  8133. /* body_len is the length of the entire queue in bytes
  8134. * len is the length of the current message
  8135. * data_len is the length of the current message's data payload
  8136. * header_len is the length of the current message's header */
  8137. size_t i, len, mask_len = 0, data_len = 0, header_len, body_len;
  8138. /* "The masking key is a 32-bit value chosen at random by the client."
  8139. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  8140. */
  8141. unsigned char mask[4];
  8142. /* data points to the place where the message is stored when passed to
  8143. * the
  8144. * websocket_data callback. This is either mem on the stack, or a
  8145. * dynamically allocated buffer if it is too large. */
  8146. unsigned char mem[4096];
  8147. unsigned char *data = mem;
  8148. unsigned char mop; /* mask flag and opcode */
  8149. double timeout = -1.0;
  8150. if (conn->ctx->config[WEBSOCKET_TIMEOUT]) {
  8151. timeout = atoi(conn->ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  8152. }
  8153. if ((timeout <= 0.0) && (conn->ctx->config[REQUEST_TIMEOUT])) {
  8154. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  8155. }
  8156. mg_set_thread_name("wsock");
  8157. /* Loop continuously, reading messages from the socket, invoking the
  8158. * callback, and waiting repeatedly until an error occurs. */
  8159. while (!conn->ctx->stop_flag) {
  8160. header_len = 0;
  8161. assert(conn->data_len >= conn->request_len);
  8162. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  8163. len = buf[1] & 127;
  8164. mask_len = (buf[1] & 128) ? 4 : 0;
  8165. if ((len < 126) && (body_len >= mask_len)) {
  8166. data_len = len;
  8167. header_len = 2 + mask_len;
  8168. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  8169. header_len = 4 + mask_len;
  8170. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  8171. } else if (body_len >= (10 + mask_len)) {
  8172. header_len = 10 + mask_len;
  8173. data_len = (((uint64_t)ntohl(*(uint32_t *)(void *)&buf[2]))
  8174. << 32) + ntohl(*(uint32_t *)(void *)&buf[6]);
  8175. }
  8176. }
  8177. if (header_len > 0 && body_len >= header_len) {
  8178. /* Allocate space to hold websocket payload */
  8179. data = mem;
  8180. if (data_len > sizeof(mem)) {
  8181. data = (unsigned char *)mg_malloc(data_len);
  8182. if (data == NULL) {
  8183. /* Allocation failed, exit the loop and then close the
  8184. * connection */
  8185. mg_cry(conn, "websocket out of memory; closing connection");
  8186. break;
  8187. }
  8188. }
  8189. /* Copy the mask before we shift the queue and destroy it */
  8190. if (mask_len > 0) {
  8191. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  8192. } else {
  8193. memset(mask, 0, sizeof(mask));
  8194. }
  8195. /* Read frame payload from the first message in the queue into
  8196. * data and advance the queue by moving the memory in place. */
  8197. assert(body_len >= header_len);
  8198. if (data_len + header_len > body_len) {
  8199. mop = buf[0]; /* current mask and opcode */
  8200. /* Overflow case */
  8201. len = body_len - header_len;
  8202. memcpy(data, buf + header_len, len);
  8203. error = 0;
  8204. while (len < data_len) {
  8205. n = pull(NULL,
  8206. conn,
  8207. (char *)(data + len),
  8208. (int)(data_len - len),
  8209. timeout);
  8210. if (n <= 0) {
  8211. error = 1;
  8212. break;
  8213. }
  8214. len += (size_t)n;
  8215. }
  8216. if (error) {
  8217. mg_cry(conn, "Websocket pull failed; closing connection");
  8218. break;
  8219. }
  8220. conn->data_len = conn->request_len;
  8221. } else {
  8222. mop = buf[0]; /* current mask and opcode, overwritten by
  8223. * memmove() */
  8224. /* Length of the message being read at the front of the
  8225. * queue */
  8226. len = data_len + header_len;
  8227. /* Copy the data payload into the data pointer for the
  8228. * callback */
  8229. memcpy(data, buf + header_len, data_len);
  8230. /* Move the queue forward len bytes */
  8231. memmove(buf, buf + len, body_len - len);
  8232. /* Mark the queue as advanced */
  8233. conn->data_len -= (int)len;
  8234. }
  8235. /* Apply mask if necessary */
  8236. if (mask_len > 0) {
  8237. for (i = 0; i < data_len; ++i) {
  8238. data[i] ^= mask[i & 3];
  8239. }
  8240. }
  8241. /* Exit the loop if callback signals to exit (server side),
  8242. * or "connection close" opcode received (client side). */
  8243. exit_by_callback = 0;
  8244. if ((ws_data_handler != NULL)
  8245. && !ws_data_handler(
  8246. conn, mop, (char *)data, data_len, callback_data)) {
  8247. exit_by_callback = 1;
  8248. }
  8249. if (data != mem) {
  8250. mg_free(data);
  8251. }
  8252. if (exit_by_callback
  8253. || ((mop & 0xf) == WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  8254. /* Opcode == 8, connection close */
  8255. break;
  8256. }
  8257. /* Not breaking the loop, process next websocket frame. */
  8258. } else {
  8259. /* Read from the socket into the next available location in the
  8260. * message queue. */
  8261. if ((n = pull(NULL,
  8262. conn,
  8263. conn->buf + conn->data_len,
  8264. conn->buf_size - conn->data_len,
  8265. timeout)) <= 0) {
  8266. /* Error, no bytes read */
  8267. break;
  8268. }
  8269. conn->data_len += n;
  8270. }
  8271. }
  8272. mg_set_thread_name("worker");
  8273. }
  8274. static int
  8275. mg_websocket_write_exec(struct mg_connection *conn,
  8276. int opcode,
  8277. const char *data,
  8278. size_t dataLen,
  8279. uint32_t masking_key)
  8280. {
  8281. unsigned char header[14];
  8282. size_t headerLen = 1;
  8283. int retval = -1;
  8284. #if defined(__GNUC__) || defined(__MINGW32__)
  8285. /* Disable spurious conversion warning for GCC */
  8286. #pragma GCC diagnostic push
  8287. #pragma GCC diagnostic ignored "-Wconversion"
  8288. #endif
  8289. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  8290. #if defined(__GNUC__) || defined(__MINGW32__)
  8291. #pragma GCC diagnostic pop
  8292. #endif
  8293. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  8294. if (dataLen < 126) {
  8295. /* inline 7-bit length field */
  8296. header[1] = (unsigned char)dataLen;
  8297. headerLen = 2;
  8298. } else if (dataLen <= 0xFFFF) {
  8299. /* 16-bit length field */
  8300. uint16_t len = htons((uint16_t)dataLen);
  8301. header[1] = 126;
  8302. memcpy(header + 2, &len, 2);
  8303. headerLen = 4;
  8304. } else {
  8305. /* 64-bit length field */
  8306. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  8307. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  8308. header[1] = 127;
  8309. memcpy(header + 2, &len1, 4);
  8310. memcpy(header + 6, &len2, 4);
  8311. headerLen = 10;
  8312. }
  8313. if (masking_key) {
  8314. /* add mask */
  8315. header[1] |= 0x80;
  8316. memcpy(header + headerLen, &masking_key, 4);
  8317. headerLen += 4;
  8318. }
  8319. /* Note that POSIX/Winsock's send() is threadsafe
  8320. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  8321. * but mongoose's mg_printf/mg_write is not (because of the loop in
  8322. * push(), although that is only a problem if the packet is large or
  8323. * outgoing buffer is full). */
  8324. (void)mg_lock_connection(conn);
  8325. retval = mg_write(conn, header, headerLen);
  8326. if (dataLen > 0) {
  8327. retval = mg_write(conn, data, dataLen);
  8328. }
  8329. mg_unlock_connection(conn);
  8330. return retval;
  8331. }
  8332. int
  8333. mg_websocket_write(struct mg_connection *conn,
  8334. int opcode,
  8335. const char *data,
  8336. size_t dataLen)
  8337. {
  8338. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  8339. }
  8340. static void
  8341. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  8342. {
  8343. size_t i = 0;
  8344. i = 0;
  8345. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  8346. /* Convert in 32 bit words, if data is 4 byte aligned */
  8347. while (i < (in_len - 3)) {
  8348. *(uint32_t *)(void *)(out + i) =
  8349. *(uint32_t *)(void *)(in + i) ^ masking_key;
  8350. i += 4;
  8351. }
  8352. }
  8353. if (i != in_len) {
  8354. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  8355. while (i < in_len) {
  8356. *(uint8_t *)(void *)(out + i) =
  8357. *(uint8_t *)(void *)(in + i)
  8358. ^ *(((uint8_t *)&masking_key) + (i % 4));
  8359. i++;
  8360. }
  8361. }
  8362. }
  8363. int
  8364. mg_websocket_client_write(struct mg_connection *conn,
  8365. int opcode,
  8366. const char *data,
  8367. size_t dataLen)
  8368. {
  8369. int retval = -1;
  8370. char *masked_data = (char *)mg_malloc(((dataLen + 7) / 4) * 4);
  8371. uint32_t masking_key = (uint32_t)get_random();
  8372. if (masked_data == NULL) {
  8373. /* Return -1 in an error case */
  8374. mg_cry(conn,
  8375. "Cannot allocate buffer for masked websocket response: "
  8376. "Out of memory");
  8377. return -1;
  8378. }
  8379. mask_data(data, dataLen, masking_key, masked_data);
  8380. retval = mg_websocket_write_exec(
  8381. conn, opcode, masked_data, dataLen, masking_key);
  8382. mg_free(masked_data);
  8383. return retval;
  8384. }
  8385. static void
  8386. handle_websocket_request(struct mg_connection *conn,
  8387. const char *path,
  8388. int is_callback_resource,
  8389. struct mg_websocket_subprotocols *subprotocols,
  8390. mg_websocket_connect_handler ws_connect_handler,
  8391. mg_websocket_ready_handler ws_ready_handler,
  8392. mg_websocket_data_handler ws_data_handler,
  8393. mg_websocket_close_handler ws_close_handler,
  8394. void *cbData)
  8395. {
  8396. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  8397. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  8398. int lua_websock = 0;
  8399. #if !defined(USE_LUA)
  8400. (void)path;
  8401. #endif
  8402. /* Step 1: Check websocket protocol version. */
  8403. /* Step 1.1: Check Sec-WebSocket-Key. */
  8404. if (!websock_key) {
  8405. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  8406. * requires a Sec-WebSocket-Key header.
  8407. */
  8408. /* It could be the hixie draft version
  8409. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  8410. */
  8411. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  8412. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  8413. char key3[8];
  8414. if ((key1 != NULL) && (key2 != NULL)) {
  8415. /* This version uses 8 byte body data in a GET request */
  8416. conn->content_len = 8;
  8417. if (8 == mg_read(conn, key3, 8)) {
  8418. /* This is the hixie version */
  8419. send_http_error(conn,
  8420. 426,
  8421. "%s",
  8422. "Protocol upgrade to RFC 6455 required");
  8423. return;
  8424. }
  8425. }
  8426. /* This is an unknown version */
  8427. send_http_error(conn, 400, "%s", "Malformed websocket request");
  8428. return;
  8429. }
  8430. /* Step 1.2: Check websocket protocol version. */
  8431. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  8432. if (version == NULL || strcmp(version, "13") != 0) {
  8433. /* Reject wrong versions */
  8434. send_http_error(conn, 426, "%s", "Protocol upgrade required");
  8435. return;
  8436. }
  8437. /* Step 1.3: Could check for "Host", but we do not really nead this
  8438. * value for anything, so just ignore it. */
  8439. /* Step 2: If a callback is responsible, call it. */
  8440. if (is_callback_resource) {
  8441. /* Step 2.1 check and select subprotocol */
  8442. const char *protocol = mg_get_header(conn, "Sec-WebSocket-Protocol");
  8443. if (protocol && subprotocols) {
  8444. int idx;
  8445. unsigned long len;
  8446. const char *sep, *curSubProtocol,
  8447. *acceptedWebSocketSubprotocol = NULL;
  8448. /* look for matching subprotocol */
  8449. do {
  8450. sep = strchr(protocol, ',');
  8451. curSubProtocol = protocol;
  8452. len = sep ? (unsigned long)(sep - protocol) : strlen(protocol);
  8453. while(sep && isspace(*++sep)); // ignore leading whitespaces
  8454. protocol = sep;
  8455. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  8456. if ((strlen(subprotocols->subprotocols[idx]) == len)
  8457. && (strncmp(curSubProtocol,
  8458. subprotocols->subprotocols[idx],
  8459. len) == 0)) {
  8460. acceptedWebSocketSubprotocol =
  8461. subprotocols->subprotocols[idx];
  8462. break;
  8463. }
  8464. }
  8465. } while (sep && !acceptedWebSocketSubprotocol);
  8466. conn->request_info.acceptedWebSocketSubprotocol =
  8467. acceptedWebSocketSubprotocol;
  8468. } else if (protocol) {
  8469. /* keep legacy behavior */
  8470. /* The protocol is a comma seperated list of names. */
  8471. /* The server must only return one value from this list. */
  8472. /* First check if it is a list or just a single value. */
  8473. const char *sep = strrchr(protocol, ',');
  8474. if (sep == NULL) {
  8475. /* Just a single protocol -> accept it. */
  8476. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  8477. } else {
  8478. /* Multiple protocols -> accept the last one. */
  8479. /* This is just a quick fix if the client offers multiple
  8480. * protocols. The handler should have a list of accepted
  8481. * protocols on his own
  8482. * and use it to select one protocol among those the client has
  8483. * offered.
  8484. */
  8485. while(isspace(*++sep)); // ignore leading whitespaces
  8486. conn->request_info.acceptedWebSocketSubprotocol = sep;
  8487. }
  8488. }
  8489. if (ws_connect_handler != NULL
  8490. && ws_connect_handler(conn, cbData) != 0) {
  8491. /* C callback has returned non-zero, do not proceed with
  8492. * handshake.
  8493. */
  8494. /* Note that C callbacks are no longer called when Lua is
  8495. * responsible, so C can no longer filter callbacks for Lua. */
  8496. return;
  8497. }
  8498. }
  8499. #if defined(USE_LUA)
  8500. /* Step 3: No callback. Check if Lua is responsible. */
  8501. else {
  8502. /* Step 3.1: Check if Lua is responsible. */
  8503. if (conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  8504. lua_websock =
  8505. match_prefix(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  8506. strlen(
  8507. conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  8508. path);
  8509. }
  8510. if (lua_websock) {
  8511. /* Step 3.2: Lua is responsible: call it. */
  8512. conn->lua_websocket_state = lua_websocket_new(path, conn);
  8513. if (!conn->lua_websocket_state) {
  8514. /* Lua rejected the new client */
  8515. return;
  8516. }
  8517. }
  8518. }
  8519. #endif
  8520. /* Step 4: Check if there is a responsible websocket handler. */
  8521. if (!is_callback_resource && !lua_websock) {
  8522. /* There is no callback, an Lua is not responsible either. */
  8523. /* Reply with a 404 Not Found or with nothing at all?
  8524. * TODO (mid): check the websocket standards, how to reply to
  8525. * requests to invalid websocket addresses. */
  8526. send_http_error(conn, 404, "%s", "Not found");
  8527. return;
  8528. }
  8529. /* Step 5: The websocket connection has been accepted */
  8530. if (!send_websocket_handshake(conn, websock_key)) {
  8531. send_http_error(conn, 500, "%s", "Websocket handshake failed");
  8532. return;
  8533. }
  8534. /* Step 6: Call the ready handler */
  8535. if (is_callback_resource) {
  8536. if (ws_ready_handler != NULL) {
  8537. ws_ready_handler(conn, cbData);
  8538. }
  8539. #if defined(USE_LUA)
  8540. } else if (lua_websock) {
  8541. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  8542. /* the ready handler returned false */
  8543. return;
  8544. }
  8545. #endif
  8546. }
  8547. /* Step 7: Enter the read loop */
  8548. if (is_callback_resource) {
  8549. read_websocket(conn, ws_data_handler, cbData);
  8550. #if defined(USE_LUA)
  8551. } else if (lua_websock) {
  8552. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  8553. #endif
  8554. }
  8555. /* Step 8: Call the close handler */
  8556. if (ws_close_handler) {
  8557. ws_close_handler(conn, cbData);
  8558. }
  8559. }
  8560. static int
  8561. is_websocket_protocol(const struct mg_connection *conn)
  8562. {
  8563. const char *upgrade, *connection;
  8564. /* A websocket protocoll has the following HTTP headers:
  8565. *
  8566. * Connection: Upgrade
  8567. * Upgrade: Websocket
  8568. */
  8569. upgrade = mg_get_header(conn, "Upgrade");
  8570. if (upgrade == NULL) {
  8571. return 0; /* fail early, don't waste time checking other header
  8572. * fields
  8573. */
  8574. }
  8575. if (!mg_strcasestr(upgrade, "websocket")) {
  8576. return 0;
  8577. }
  8578. connection = mg_get_header(conn, "Connection");
  8579. if (connection == NULL) {
  8580. return 0;
  8581. }
  8582. if (!mg_strcasestr(connection, "upgrade")) {
  8583. return 0;
  8584. }
  8585. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  8586. * "Sec-WebSocket-Version" are also required.
  8587. * Don't check them here, since even an unsupported websocket protocol
  8588. * request still IS a websocket request (in contrast to a standard HTTP
  8589. * request). It will fail later in handle_websocket_request.
  8590. */
  8591. return 1;
  8592. }
  8593. #endif /* !USE_WEBSOCKET */
  8594. static int
  8595. isbyte(int n)
  8596. {
  8597. return n >= 0 && n <= 255;
  8598. }
  8599. static int
  8600. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  8601. {
  8602. int n, a, b, c, d, slash = 32, len = 0;
  8603. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5
  8604. || sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) && isbyte(a)
  8605. && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0
  8606. && slash < 33) {
  8607. len = n;
  8608. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  8609. | (uint32_t)d;
  8610. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  8611. }
  8612. return len;
  8613. }
  8614. static int
  8615. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  8616. {
  8617. int throttle = 0;
  8618. struct vec vec, val;
  8619. uint32_t net, mask;
  8620. char mult;
  8621. double v;
  8622. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  8623. mult = ',';
  8624. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  8625. || (v < 0) || ((lowercase(&mult) != 'k')
  8626. && (lowercase(&mult) != 'm') && (mult != ','))) {
  8627. continue;
  8628. }
  8629. v *= (lowercase(&mult) == 'k')
  8630. ? 1024
  8631. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  8632. if (vec.len == 1 && vec.ptr[0] == '*') {
  8633. throttle = (int)v;
  8634. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  8635. if ((remote_ip & mask) == net) {
  8636. throttle = (int)v;
  8637. }
  8638. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  8639. throttle = (int)v;
  8640. }
  8641. }
  8642. return throttle;
  8643. }
  8644. static uint32_t
  8645. get_remote_ip(const struct mg_connection *conn)
  8646. {
  8647. if (!conn) {
  8648. return 0;
  8649. }
  8650. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  8651. }
  8652. /* The mg_upload function is superseeded by mg_handle_form_request. */
  8653. #include "handle_form.inl"
  8654. #if defined(MG_LEGACY_INTERFACE)
  8655. /* Implement the deprecated mg_upload function by calling the new
  8656. * mg_handle_form_request function. While mg_upload could only handle
  8657. * HTML forms sent as POST request in multipart/form-data format
  8658. * containing only file input elements, mg_handle_form_request can
  8659. * handle all form input elements and all standard request methods. */
  8660. struct mg_upload_user_data {
  8661. struct mg_connection *conn;
  8662. const char *destination_dir;
  8663. int num_uploaded_files;
  8664. };
  8665. /* Helper function for deprecated mg_upload. */
  8666. static int
  8667. mg_upload_field_found(const char *key,
  8668. const char *filename,
  8669. char *path,
  8670. size_t pathlen,
  8671. void *user_data)
  8672. {
  8673. int truncated = 0;
  8674. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  8675. (void)key;
  8676. if (!filename) {
  8677. mg_cry(fud->conn, "%s: No filename set", __func__);
  8678. return FORM_FIELD_STORAGE_ABORT;
  8679. }
  8680. mg_snprintf(fud->conn,
  8681. &truncated,
  8682. path,
  8683. pathlen - 1,
  8684. "%s/%s",
  8685. fud->destination_dir,
  8686. filename);
  8687. if (!truncated) {
  8688. mg_cry(fud->conn, "%s: File path too long", __func__);
  8689. return FORM_FIELD_STORAGE_ABORT;
  8690. }
  8691. return FORM_FIELD_STORAGE_STORE;
  8692. }
  8693. /* Helper function for deprecated mg_upload. */
  8694. static int
  8695. mg_upload_field_get(const char *key,
  8696. const char *value,
  8697. size_t value_size,
  8698. void *user_data)
  8699. {
  8700. /* Function should never be called */
  8701. (void)key;
  8702. (void)value;
  8703. (void)value_size;
  8704. (void)user_data;
  8705. return 0;
  8706. }
  8707. /* Helper function for deprecated mg_upload. */
  8708. static int
  8709. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  8710. {
  8711. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  8712. (void)file_size;
  8713. fud->num_uploaded_files++;
  8714. fud->conn->ctx->callbacks.upload(fud->conn, path);
  8715. return 0;
  8716. }
  8717. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  8718. int
  8719. mg_upload(struct mg_connection *conn, const char *destination_dir)
  8720. {
  8721. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  8722. struct mg_form_data_handler fdh = {mg_upload_field_found,
  8723. mg_upload_field_get,
  8724. mg_upload_field_stored,
  8725. 0};
  8726. int ret;
  8727. fdh.user_data = (void *)&fud;
  8728. ret = mg_handle_form_request(conn, &fdh);
  8729. if (ret < 0) {
  8730. mg_cry(conn, "%s: Error while parsing the request", __func__);
  8731. }
  8732. return fud.num_uploaded_files;
  8733. }
  8734. #endif
  8735. static int
  8736. get_first_ssl_listener_index(const struct mg_context *ctx)
  8737. {
  8738. unsigned int i;
  8739. int idx = -1;
  8740. if (ctx) {
  8741. for (i = 0; idx == -1 && i < ctx->num_listening_sockets; i++) {
  8742. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  8743. }
  8744. }
  8745. return idx;
  8746. }
  8747. static void
  8748. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  8749. {
  8750. char host[1025];
  8751. const char *host_header;
  8752. size_t hostlen;
  8753. host_header = mg_get_header(conn, "Host");
  8754. hostlen = sizeof(host);
  8755. if (host_header != NULL) {
  8756. char *pos;
  8757. mg_strlcpy(host, host_header, hostlen);
  8758. host[hostlen - 1] = '\0';
  8759. pos = strchr(host, ':');
  8760. if (pos != NULL) {
  8761. *pos = '\0';
  8762. }
  8763. } else {
  8764. /* Cannot get host from the Host: header.
  8765. * Fallback to our IP address. */
  8766. if (conn) {
  8767. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  8768. }
  8769. }
  8770. /* Send host, port, uri and (if it exists) ?query_string */
  8771. if (conn) {
  8772. mg_printf(conn,
  8773. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  8774. host,
  8775. #if defined(USE_IPV6)
  8776. (conn->ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  8777. == AF_INET6)
  8778. ? (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  8779. .lsa.sin6.sin6_port)
  8780. :
  8781. #endif
  8782. (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  8783. .lsa.sin.sin_port),
  8784. conn->request_info.local_uri,
  8785. (conn->request_info.query_string == NULL) ? "" : "?",
  8786. (conn->request_info.query_string == NULL)
  8787. ? ""
  8788. : conn->request_info.query_string);
  8789. }
  8790. }
  8791. static void
  8792. mg_set_handler_type(struct mg_context *ctx,
  8793. const char *uri,
  8794. int handler_type,
  8795. int is_delete_request,
  8796. mg_request_handler handler,
  8797. struct mg_websocket_subprotocols *subprotocols,
  8798. mg_websocket_connect_handler connect_handler,
  8799. mg_websocket_ready_handler ready_handler,
  8800. mg_websocket_data_handler data_handler,
  8801. mg_websocket_close_handler close_handler,
  8802. mg_authorization_handler auth_handler,
  8803. void *cbdata)
  8804. {
  8805. struct mg_handler_info *tmp_rh, **lastref;
  8806. size_t urilen = strlen(uri);
  8807. if (handler_type == WEBSOCKET_HANDLER) {
  8808. /* assert(handler == NULL); */
  8809. /* assert(is_delete_request || connect_handler!=NULL ||
  8810. * ready_handler!=NULL || data_handler!=NULL ||
  8811. * close_handler!=NULL);
  8812. */
  8813. /* assert(auth_handler == NULL); */
  8814. if (handler != NULL) {
  8815. return;
  8816. }
  8817. if (!is_delete_request && connect_handler == NULL
  8818. && ready_handler == NULL
  8819. && data_handler == NULL
  8820. && close_handler == NULL) {
  8821. return;
  8822. }
  8823. if (auth_handler != NULL) {
  8824. return;
  8825. }
  8826. } else if (handler_type == REQUEST_HANDLER) {
  8827. /* assert(connect_handler==NULL && ready_handler==NULL &&
  8828. * data_handler==NULL && close_handler==NULL); */
  8829. /* assert(is_delete_request || (handler!=NULL));
  8830. */
  8831. /* assert(auth_handler == NULL); */
  8832. if (connect_handler != NULL || ready_handler != NULL
  8833. || data_handler != NULL
  8834. || close_handler != NULL) {
  8835. return;
  8836. }
  8837. if (!is_delete_request && (handler == NULL)) {
  8838. return;
  8839. }
  8840. if (auth_handler != NULL) {
  8841. return;
  8842. }
  8843. } else { /* AUTH_HANDLER */
  8844. /* assert(handler == NULL); */
  8845. /* assert(connect_handler==NULL && ready_handler==NULL &&
  8846. * data_handler==NULL && close_handler==NULL); */
  8847. /* assert(auth_handler != NULL); */
  8848. if (handler != NULL) {
  8849. return;
  8850. }
  8851. if (connect_handler != NULL || ready_handler != NULL
  8852. || data_handler != NULL
  8853. || close_handler != NULL) {
  8854. return;
  8855. }
  8856. if (!is_delete_request && (auth_handler == NULL)) {
  8857. return;
  8858. }
  8859. }
  8860. if (!ctx) {
  8861. return;
  8862. }
  8863. mg_lock_context(ctx);
  8864. /* first try to find an existing handler */
  8865. lastref = &(ctx->handlers);
  8866. for (tmp_rh = ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  8867. if (tmp_rh->handler_type == handler_type) {
  8868. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  8869. if (!is_delete_request) {
  8870. /* update existing handler */
  8871. if (handler_type == REQUEST_HANDLER) {
  8872. tmp_rh->handler = handler;
  8873. } else if (handler_type == WEBSOCKET_HANDLER) {
  8874. tmp_rh->subprotocols = subprotocols;
  8875. tmp_rh->connect_handler = connect_handler;
  8876. tmp_rh->ready_handler = ready_handler;
  8877. tmp_rh->data_handler = data_handler;
  8878. tmp_rh->close_handler = close_handler;
  8879. } else { /* AUTH_HANDLER */
  8880. tmp_rh->auth_handler = auth_handler;
  8881. }
  8882. tmp_rh->cbdata = cbdata;
  8883. } else {
  8884. /* remove existing handler */
  8885. *lastref = tmp_rh->next;
  8886. mg_free(tmp_rh->uri);
  8887. mg_free(tmp_rh);
  8888. }
  8889. mg_unlock_context(ctx);
  8890. return;
  8891. }
  8892. }
  8893. lastref = &(tmp_rh->next);
  8894. }
  8895. if (is_delete_request) {
  8896. /* no handler to set, this was a remove request to a non-existing
  8897. * handler */
  8898. mg_unlock_context(ctx);
  8899. return;
  8900. }
  8901. tmp_rh =
  8902. (struct mg_handler_info *)mg_calloc(sizeof(struct mg_handler_info), 1);
  8903. if (tmp_rh == NULL) {
  8904. mg_unlock_context(ctx);
  8905. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  8906. return;
  8907. }
  8908. tmp_rh->uri = mg_strdup(uri);
  8909. if (!tmp_rh->uri) {
  8910. mg_unlock_context(ctx);
  8911. mg_free(tmp_rh);
  8912. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  8913. return;
  8914. }
  8915. tmp_rh->uri_len = urilen;
  8916. if (handler_type == REQUEST_HANDLER) {
  8917. tmp_rh->handler = handler;
  8918. } else if (handler_type == WEBSOCKET_HANDLER) {
  8919. tmp_rh->subprotocols = subprotocols;
  8920. tmp_rh->connect_handler = connect_handler;
  8921. tmp_rh->ready_handler = ready_handler;
  8922. tmp_rh->data_handler = data_handler;
  8923. tmp_rh->close_handler = close_handler;
  8924. } else { /* AUTH_HANDLER */
  8925. tmp_rh->auth_handler = auth_handler;
  8926. }
  8927. tmp_rh->cbdata = cbdata;
  8928. tmp_rh->handler_type = handler_type;
  8929. tmp_rh->next = NULL;
  8930. *lastref = tmp_rh;
  8931. mg_unlock_context(ctx);
  8932. }
  8933. void
  8934. mg_set_request_handler(struct mg_context *ctx,
  8935. const char *uri,
  8936. mg_request_handler handler,
  8937. void *cbdata)
  8938. {
  8939. mg_set_handler_type(ctx,
  8940. uri,
  8941. REQUEST_HANDLER,
  8942. handler == NULL,
  8943. handler,
  8944. NULL,
  8945. NULL,
  8946. NULL,
  8947. NULL,
  8948. NULL,
  8949. NULL,
  8950. cbdata);
  8951. }
  8952. void
  8953. mg_set_websocket_handler(struct mg_context *ctx,
  8954. const char *uri,
  8955. mg_websocket_connect_handler connect_handler,
  8956. mg_websocket_ready_handler ready_handler,
  8957. mg_websocket_data_handler data_handler,
  8958. mg_websocket_close_handler close_handler,
  8959. void *cbdata)
  8960. {
  8961. mg_set_websocket_handler_with_subprotocols(ctx,
  8962. uri,
  8963. NULL,
  8964. connect_handler,
  8965. ready_handler,
  8966. data_handler,
  8967. close_handler,
  8968. cbdata);
  8969. }
  8970. void
  8971. mg_set_websocket_handler_with_subprotocols(
  8972. struct mg_context *ctx,
  8973. const char *uri,
  8974. struct mg_websocket_subprotocols *subprotocols,
  8975. mg_websocket_connect_handler connect_handler,
  8976. mg_websocket_ready_handler ready_handler,
  8977. mg_websocket_data_handler data_handler,
  8978. mg_websocket_close_handler close_handler,
  8979. void *cbdata)
  8980. {
  8981. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  8982. && (data_handler == NULL)
  8983. && (close_handler == NULL);
  8984. mg_set_handler_type(ctx,
  8985. uri,
  8986. WEBSOCKET_HANDLER,
  8987. is_delete_request,
  8988. NULL,
  8989. subprotocols,
  8990. connect_handler,
  8991. ready_handler,
  8992. data_handler,
  8993. close_handler,
  8994. NULL,
  8995. cbdata);
  8996. }
  8997. void
  8998. mg_set_auth_handler(struct mg_context *ctx,
  8999. const char *uri,
  9000. mg_request_handler handler,
  9001. void *cbdata)
  9002. {
  9003. mg_set_handler_type(ctx,
  9004. uri,
  9005. AUTH_HANDLER,
  9006. handler == NULL,
  9007. NULL,
  9008. NULL,
  9009. NULL,
  9010. NULL,
  9011. NULL,
  9012. NULL,
  9013. handler,
  9014. cbdata);
  9015. }
  9016. static int
  9017. get_request_handler(struct mg_connection *conn,
  9018. int handler_type,
  9019. mg_request_handler *handler,
  9020. struct mg_websocket_subprotocols **subprotocols,
  9021. mg_websocket_connect_handler *connect_handler,
  9022. mg_websocket_ready_handler *ready_handler,
  9023. mg_websocket_data_handler *data_handler,
  9024. mg_websocket_close_handler *close_handler,
  9025. mg_authorization_handler *auth_handler,
  9026. void **cbdata)
  9027. {
  9028. const struct mg_request_info *request_info = mg_get_request_info(conn);
  9029. if (request_info) {
  9030. const char *uri = request_info->local_uri;
  9031. size_t urilen = strlen(uri);
  9032. struct mg_handler_info *tmp_rh;
  9033. if (!conn || !conn->ctx) {
  9034. return 0;
  9035. }
  9036. mg_lock_context(conn->ctx);
  9037. /* first try for an exact match */
  9038. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  9039. tmp_rh = tmp_rh->next) {
  9040. if (tmp_rh->handler_type == handler_type) {
  9041. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  9042. if (handler_type == WEBSOCKET_HANDLER) {
  9043. *subprotocols = tmp_rh->subprotocols;
  9044. *connect_handler = tmp_rh->connect_handler;
  9045. *ready_handler = tmp_rh->ready_handler;
  9046. *data_handler = tmp_rh->data_handler;
  9047. *close_handler = tmp_rh->close_handler;
  9048. } else if (handler_type == REQUEST_HANDLER) {
  9049. *handler = tmp_rh->handler;
  9050. } else { /* AUTH_HANDLER */
  9051. *auth_handler = tmp_rh->auth_handler;
  9052. }
  9053. *cbdata = tmp_rh->cbdata;
  9054. mg_unlock_context(conn->ctx);
  9055. return 1;
  9056. }
  9057. }
  9058. }
  9059. /* next try for a partial match, we will accept uri/something */
  9060. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  9061. tmp_rh = tmp_rh->next) {
  9062. if (tmp_rh->handler_type == handler_type) {
  9063. if (tmp_rh->uri_len < urilen && uri[tmp_rh->uri_len] == '/'
  9064. && memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0) {
  9065. if (handler_type == WEBSOCKET_HANDLER) {
  9066. *subprotocols = tmp_rh->subprotocols;
  9067. *connect_handler = tmp_rh->connect_handler;
  9068. *ready_handler = tmp_rh->ready_handler;
  9069. *data_handler = tmp_rh->data_handler;
  9070. *close_handler = tmp_rh->close_handler;
  9071. } else if (handler_type == REQUEST_HANDLER) {
  9072. *handler = tmp_rh->handler;
  9073. } else { /* AUTH_HANDLER */
  9074. *auth_handler = tmp_rh->auth_handler;
  9075. }
  9076. *cbdata = tmp_rh->cbdata;
  9077. mg_unlock_context(conn->ctx);
  9078. return 1;
  9079. }
  9080. }
  9081. }
  9082. /* finally try for pattern match */
  9083. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  9084. tmp_rh = tmp_rh->next) {
  9085. if (tmp_rh->handler_type == handler_type) {
  9086. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  9087. if (handler_type == WEBSOCKET_HANDLER) {
  9088. *subprotocols = tmp_rh->subprotocols;
  9089. *connect_handler = tmp_rh->connect_handler;
  9090. *ready_handler = tmp_rh->ready_handler;
  9091. *data_handler = tmp_rh->data_handler;
  9092. *close_handler = tmp_rh->close_handler;
  9093. } else if (handler_type == REQUEST_HANDLER) {
  9094. *handler = tmp_rh->handler;
  9095. } else { /* AUTH_HANDLER */
  9096. *auth_handler = tmp_rh->auth_handler;
  9097. }
  9098. *cbdata = tmp_rh->cbdata;
  9099. mg_unlock_context(conn->ctx);
  9100. return 1;
  9101. }
  9102. }
  9103. }
  9104. mg_unlock_context(conn->ctx);
  9105. }
  9106. return 0; /* none found */
  9107. }
  9108. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  9109. static int
  9110. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  9111. void *cbdata)
  9112. {
  9113. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9114. if (pcallbacks->websocket_connect) {
  9115. return pcallbacks->websocket_connect(conn);
  9116. }
  9117. /* No handler set - assume "OK" */
  9118. return 0;
  9119. }
  9120. static void
  9121. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  9122. {
  9123. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9124. if (pcallbacks->websocket_ready) {
  9125. pcallbacks->websocket_ready(conn);
  9126. }
  9127. }
  9128. static int
  9129. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  9130. int bits,
  9131. char *data,
  9132. size_t len,
  9133. void *cbdata)
  9134. {
  9135. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9136. if (pcallbacks->websocket_data) {
  9137. return pcallbacks->websocket_data(conn, bits, data, len);
  9138. }
  9139. /* No handler set - assume "OK" */
  9140. return 1;
  9141. }
  9142. #endif
  9143. /* This is the heart of the Civetweb's logic.
  9144. * This function is called when the request is read, parsed and validated,
  9145. * and Civetweb must decide what action to take: serve a file, or
  9146. * a directory, or call embedded function, etcetera. */
  9147. static void
  9148. handle_request(struct mg_connection *conn)
  9149. {
  9150. if (conn) {
  9151. struct mg_request_info *ri = &conn->request_info;
  9152. char path[PATH_MAX];
  9153. int uri_len, ssl_index;
  9154. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  9155. is_put_or_delete_request = 0, is_callback_resource = 0;
  9156. int i;
  9157. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9158. mg_request_handler callback_handler = NULL;
  9159. struct mg_websocket_subprotocols *subprotocols;
  9160. mg_websocket_connect_handler ws_connect_handler = NULL;
  9161. mg_websocket_ready_handler ws_ready_handler = NULL;
  9162. mg_websocket_data_handler ws_data_handler = NULL;
  9163. mg_websocket_close_handler ws_close_handler = NULL;
  9164. void *callback_data = NULL;
  9165. mg_authorization_handler auth_handler = NULL;
  9166. void *auth_callback_data = NULL;
  9167. #if !defined(NO_FILES)
  9168. time_t curtime = time(NULL);
  9169. char date[64];
  9170. #endif
  9171. path[0] = 0;
  9172. if (!ri) {
  9173. return;
  9174. }
  9175. /* 1. get the request url */
  9176. /* 1.1. split into url and query string */
  9177. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  9178. != NULL) {
  9179. *((char *)conn->request_info.query_string++) = '\0';
  9180. }
  9181. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  9182. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  9183. ssl_index = get_first_ssl_listener_index(conn->ctx);
  9184. if (ssl_index >= 0) {
  9185. redirect_to_https_port(conn, ssl_index);
  9186. } else {
  9187. /* A http to https forward port has been specified,
  9188. * but no https port to forward to. */
  9189. send_http_error(conn,
  9190. 503,
  9191. "%s",
  9192. "Error: SSL forward not configured properly");
  9193. mg_cry(conn, "Can not redirect to SSL, no SSL port available");
  9194. }
  9195. return;
  9196. }
  9197. uri_len = (int)strlen(ri->local_uri);
  9198. /* 1.3. decode url (if config says so) */
  9199. if (should_decode_url(conn)) {
  9200. mg_url_decode(
  9201. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  9202. }
  9203. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  9204. * not possible */
  9205. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  9206. /* step 1. completed, the url is known now */
  9207. uri_len = (int)strlen(ri->local_uri);
  9208. DEBUG_TRACE("URL: %s", ri->local_uri);
  9209. /* 3. if this ip has limited speed, set it for this connection */
  9210. conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
  9211. get_remote_ip(conn),
  9212. ri->local_uri);
  9213. /* 4. call a "handle everything" callback, if registered */
  9214. if (conn->ctx->callbacks.begin_request != NULL) {
  9215. /* Note that since V1.7 the "begin_request" function is called
  9216. * before an authorization check. If an authorization check is
  9217. * required, use a request_handler instead. */
  9218. i = conn->ctx->callbacks.begin_request(conn);
  9219. if (i > 0) {
  9220. /* callback already processed the request. Store the
  9221. return value as a status code for the access log. */
  9222. conn->status_code = i;
  9223. discard_unread_request_data(conn);
  9224. return;
  9225. } else if (i == 0) {
  9226. /* civetweb should process the request */
  9227. } else {
  9228. /* unspecified - may change with the next version */
  9229. return;
  9230. }
  9231. }
  9232. /* request not yet handled by a handler or redirect, so the request
  9233. * is processed here */
  9234. /* 5. interpret the url to find out how the request must be handled
  9235. */
  9236. /* 5.1. first test, if the request targets the regular http(s)://
  9237. * protocol namespace or the websocket ws(s):// protocol namespace.
  9238. */
  9239. is_websocket_request = is_websocket_protocol(conn);
  9240. /* 5.2. check if the request will be handled by a callback */
  9241. if (get_request_handler(conn,
  9242. is_websocket_request ? WEBSOCKET_HANDLER
  9243. : REQUEST_HANDLER,
  9244. &callback_handler,
  9245. &subprotocols,
  9246. &ws_connect_handler,
  9247. &ws_ready_handler,
  9248. &ws_data_handler,
  9249. &ws_close_handler,
  9250. NULL,
  9251. &callback_data)) {
  9252. /* 5.2.1. A callback will handle this request. All requests
  9253. * handled
  9254. * by a callback have to be considered as requests to a script
  9255. * resource. */
  9256. is_callback_resource = 1;
  9257. is_script_resource = 1;
  9258. is_put_or_delete_request = is_put_or_delete_method(conn);
  9259. } else {
  9260. no_callback_resource:
  9261. /* 5.2.2. No callback is responsible for this request. The URI
  9262. * addresses a file based resource (static content or Lua/cgi
  9263. * scripts in the file system). */
  9264. is_callback_resource = 0;
  9265. interpret_uri(conn,
  9266. path,
  9267. sizeof(path),
  9268. &file.stat,
  9269. &is_found,
  9270. &is_script_resource,
  9271. &is_websocket_request,
  9272. &is_put_or_delete_request);
  9273. }
  9274. /* 6. authorization check */
  9275. /* 6.1. a custom authorization handler is installed */
  9276. if (get_request_handler(conn,
  9277. AUTH_HANDLER,
  9278. NULL,
  9279. NULL,
  9280. NULL,
  9281. NULL,
  9282. NULL,
  9283. NULL,
  9284. &auth_handler,
  9285. &auth_callback_data)) {
  9286. if (!auth_handler(conn, auth_callback_data)) {
  9287. return;
  9288. }
  9289. } else if (is_put_or_delete_request && !is_script_resource
  9290. && !is_callback_resource) {
  9291. /* 6.2. this request is a PUT/DELETE to a real file */
  9292. /* 6.2.1. thus, the server must have real files */
  9293. #if defined(NO_FILES)
  9294. if (1) {
  9295. #else
  9296. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  9297. #endif
  9298. /* This server does not have any real files, thus the
  9299. * PUT/DELETE methods are not valid. */
  9300. send_http_error(conn,
  9301. 405,
  9302. "%s method not allowed",
  9303. conn->request_info.request_method);
  9304. return;
  9305. }
  9306. #if !defined(NO_FILES)
  9307. /* 6.2.2. Check if put authorization for static files is
  9308. * available.
  9309. */
  9310. if (!is_authorized_for_put(conn)) {
  9311. send_authorization_request(conn);
  9312. return;
  9313. }
  9314. #endif
  9315. } else {
  9316. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  9317. * or it is a PUT or DELETE request to a resource that does not
  9318. * correspond to a file. Check authorization. */
  9319. if (!check_authorization(conn, path)) {
  9320. send_authorization_request(conn);
  9321. return;
  9322. }
  9323. }
  9324. /* request is authorized or does not need authorization */
  9325. /* 7. check if there are request handlers for this uri */
  9326. if (is_callback_resource) {
  9327. if (!is_websocket_request) {
  9328. i = callback_handler(conn, callback_data);
  9329. if (i > 0) {
  9330. /* Do nothing, callback has served the request. Store
  9331. * the
  9332. * return value as status code for the log and discard
  9333. * all
  9334. * data from the client not used by the callback. */
  9335. conn->status_code = i;
  9336. discard_unread_request_data(conn);
  9337. } else {
  9338. /* TODO (high): what if the handler did NOT handle the
  9339. * request */
  9340. /* The last version did handle this as a file request,
  9341. * but
  9342. * since a file request is not always a script resource,
  9343. * the authorization check might be different */
  9344. interpret_uri(conn,
  9345. path,
  9346. sizeof(path),
  9347. &file.stat,
  9348. &is_found,
  9349. &is_script_resource,
  9350. &is_websocket_request,
  9351. &is_put_or_delete_request);
  9352. callback_handler = NULL;
  9353. /* TODO (very low): goto is deprecated but for the
  9354. * moment,
  9355. * a goto is simpler than some curious loop. */
  9356. /* The situation "callback does not handle the request"
  9357. * needs to be reconsidered anyway. */
  9358. goto no_callback_resource;
  9359. }
  9360. } else {
  9361. #if defined(USE_WEBSOCKET)
  9362. handle_websocket_request(conn,
  9363. path,
  9364. is_callback_resource,
  9365. subprotocols,
  9366. ws_connect_handler,
  9367. ws_ready_handler,
  9368. ws_data_handler,
  9369. ws_close_handler,
  9370. callback_data);
  9371. #endif
  9372. }
  9373. return;
  9374. }
  9375. /* 8. handle websocket requests */
  9376. #if defined(USE_WEBSOCKET)
  9377. if (is_websocket_request) {
  9378. if (is_script_resource) {
  9379. /* Websocket Lua script */
  9380. handle_websocket_request(conn,
  9381. path,
  9382. 0 /* Lua Script */,
  9383. NULL,
  9384. NULL,
  9385. NULL,
  9386. NULL,
  9387. NULL,
  9388. &conn->ctx->callbacks);
  9389. } else {
  9390. #if defined(MG_LEGACY_INTERFACE)
  9391. handle_websocket_request(
  9392. conn,
  9393. path,
  9394. !is_script_resource /* could be deprecated global callback */,
  9395. NULL,
  9396. deprecated_websocket_connect_wrapper,
  9397. deprecated_websocket_ready_wrapper,
  9398. deprecated_websocket_data_wrapper,
  9399. NULL,
  9400. &conn->ctx->callbacks);
  9401. #else
  9402. send_http_error(conn, 404, "%s", "Not found");
  9403. #endif
  9404. }
  9405. return;
  9406. } else
  9407. #endif
  9408. #if defined(NO_FILES)
  9409. /* 9a. In case the server uses only callbacks, this uri is
  9410. * unknown.
  9411. * Then, all request handling ends here. */
  9412. send_http_error(conn, 404, "%s", "Not Found");
  9413. #else
  9414. /* 9b. This request is either for a static file or resource handled
  9415. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  9416. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  9417. send_http_error(conn, 404, "%s", "Not Found");
  9418. return;
  9419. }
  9420. /* 10. File is handled by a script. */
  9421. if (is_script_resource) {
  9422. handle_file_based_request(conn, path, &file);
  9423. return;
  9424. }
  9425. /* 11. Handle put/delete/mkcol requests */
  9426. if (is_put_or_delete_request) {
  9427. /* 11.1. PUT method */
  9428. if (!strcmp(ri->request_method, "PUT")) {
  9429. put_file(conn, path);
  9430. return;
  9431. }
  9432. /* 11.2. DELETE method */
  9433. if (!strcmp(ri->request_method, "DELETE")) {
  9434. delete_file(conn, path);
  9435. return;
  9436. }
  9437. /* 11.3. MKCOL method */
  9438. if (!strcmp(ri->request_method, "MKCOL")) {
  9439. mkcol(conn, path);
  9440. return;
  9441. }
  9442. /* 11.4. PATCH method
  9443. * This method is not supported for static resources,
  9444. * only for scripts (Lua, CGI) and callbacks. */
  9445. send_http_error(conn,
  9446. 405,
  9447. "%s method not allowed",
  9448. conn->request_info.request_method);
  9449. return;
  9450. }
  9451. /* 11. File does not exist, or it was configured that it should be
  9452. * hidden */
  9453. if (!is_found || (must_hide_file(conn, path))) {
  9454. send_http_error(conn, 404, "%s", "Not found");
  9455. return;
  9456. }
  9457. /* 12. Directory uris should end with a slash */
  9458. if (file.stat.is_directory && (uri_len > 0)
  9459. && (ri->local_uri[uri_len - 1] != '/')) {
  9460. gmt_time_string(date, sizeof(date), &curtime);
  9461. mg_printf(conn,
  9462. "HTTP/1.1 301 Moved Permanently\r\n"
  9463. "Location: %s/\r\n"
  9464. "Date: %s\r\n"
  9465. /* "Cache-Control: private\r\n" (= default) */
  9466. "Content-Length: 0\r\n"
  9467. "Connection: %s\r\n\r\n",
  9468. ri->request_uri,
  9469. date,
  9470. suggest_connection_header(conn));
  9471. return;
  9472. }
  9473. /* 13. Handle other methods than GET/HEAD */
  9474. /* 13.1. Handle PROPFIND */
  9475. if (!strcmp(ri->request_method, "PROPFIND")) {
  9476. handle_propfind(conn, path, &file.stat);
  9477. return;
  9478. }
  9479. /* 13.2. Handle OPTIONS for files */
  9480. if (!strcmp(ri->request_method, "OPTIONS")) {
  9481. /* This standard handler is only used for real files.
  9482. * Scripts should support the OPTIONS method themselves, to allow a
  9483. * maximum flexibility.
  9484. * Lua and CGI scripts may fully support CORS this way (including
  9485. * preflights). */
  9486. send_options(conn);
  9487. return;
  9488. }
  9489. /* 13.3. everything but GET and HEAD (e.g. POST) */
  9490. if (0 != strcmp(ri->request_method, "GET")
  9491. && 0 != strcmp(ri->request_method, "HEAD")) {
  9492. send_http_error(conn,
  9493. 405,
  9494. "%s method not allowed",
  9495. conn->request_info.request_method);
  9496. return;
  9497. }
  9498. /* 14. directories */
  9499. if (file.stat.is_directory) {
  9500. if (substitute_index_file(conn, path, sizeof(path), &file)) {
  9501. /* 14.1. use a substitute file */
  9502. /* TODO (high): substitute index may be a script resource.
  9503. * define what should be possible in this case. */
  9504. } else {
  9505. /* 14.2. no substitute file */
  9506. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  9507. "yes")) {
  9508. handle_directory_request(conn, path);
  9509. } else {
  9510. send_http_error(conn,
  9511. 403,
  9512. "%s",
  9513. "Error: Directory listing denied");
  9514. }
  9515. return;
  9516. }
  9517. }
  9518. handle_file_based_request(conn, path, &file);
  9519. #endif /* !defined(NO_FILES) */
  9520. #if 0
  9521. /* Perform redirect and auth checks before calling begin_request()
  9522. * handler.
  9523. * Otherwise, begin_request() would need to perform auth checks and
  9524. * redirects. */
  9525. #endif
  9526. }
  9527. return;
  9528. }
  9529. static void
  9530. handle_file_based_request(struct mg_connection *conn,
  9531. const char *path,
  9532. struct mg_file *file)
  9533. {
  9534. if (!conn || !conn->ctx) {
  9535. return;
  9536. }
  9537. if (0) {
  9538. #ifdef USE_LUA
  9539. } else if (match_prefix(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  9540. strlen(
  9541. conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  9542. path) > 0) {
  9543. /* Lua server page: an SSI like page containing mostly plain html
  9544. * code
  9545. * plus some tags with server generated contents. */
  9546. handle_lsp_request(conn, path, file, NULL);
  9547. } else if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  9548. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  9549. path) > 0) {
  9550. /* Lua in-server module script: a CGI like script used to generate
  9551. * the
  9552. * entire reply. */
  9553. mg_exec_lua_script(conn, path, NULL);
  9554. #endif
  9555. #if defined(USE_DUKTAPE)
  9556. } else if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  9557. strlen(
  9558. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  9559. path) > 0) {
  9560. /* Call duktape to generate the page */
  9561. mg_exec_duktape_script(conn, path);
  9562. #endif
  9563. #if !defined(NO_CGI)
  9564. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  9565. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  9566. path) > 0) {
  9567. /* CGI scripts may support all HTTP methods */
  9568. handle_cgi_request(conn, path);
  9569. #endif /* !NO_CGI */
  9570. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  9571. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  9572. path) > 0) {
  9573. handle_ssi_file_request(conn, path, file);
  9574. #if !defined(NO_CACHING)
  9575. } else if ((!conn->in_error_handler)
  9576. && is_not_modified(conn, &file->stat)) {
  9577. /* Send 304 "Not Modified" - this must not send any body data */
  9578. handle_not_modified_static_file_request(conn, file);
  9579. #endif /* !NO_CACHING */
  9580. } else {
  9581. handle_static_file_request(conn, path, file, NULL, NULL);
  9582. }
  9583. }
  9584. static void
  9585. close_all_listening_sockets(struct mg_context *ctx)
  9586. {
  9587. unsigned int i;
  9588. if (!ctx) {
  9589. return;
  9590. }
  9591. for (i = 0; i < ctx->num_listening_sockets; i++) {
  9592. closesocket(ctx->listening_sockets[i].sock);
  9593. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  9594. }
  9595. mg_free(ctx->listening_sockets);
  9596. ctx->listening_sockets = NULL;
  9597. mg_free(ctx->listening_socket_fds);
  9598. ctx->listening_socket_fds = NULL;
  9599. }
  9600. /* Valid listening port specification is: [ip_address:]port[s]
  9601. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  9602. * Examples for IPv6: [::]:80, [::1]:80,
  9603. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  9604. * see https://tools.ietf.org/html/rfc3513#section-2.2
  9605. * In order to bind to both, IPv4 and IPv6, you can either add
  9606. * both ports using 8080,[::]:8080, or the short form +8080.
  9607. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  9608. * one only accepting IPv4 the other only IPv6. +8080 creates
  9609. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  9610. * environment, they might work differently, or might not work
  9611. * at all - it must be tested what options work best in the
  9612. * relevant network environment.
  9613. */
  9614. static int
  9615. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  9616. {
  9617. unsigned int a, b, c, d, port;
  9618. int ch, len;
  9619. #if defined(USE_IPV6)
  9620. char buf[100] = {0};
  9621. #endif
  9622. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  9623. * Also, all-zeroes in the socket address means binding to all addresses
  9624. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  9625. memset(so, 0, sizeof(*so));
  9626. so->lsa.sin.sin_family = AF_INET;
  9627. *ip_version = 0;
  9628. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  9629. == 5) {
  9630. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  9631. so->lsa.sin.sin_addr.s_addr =
  9632. htonl((a << 24) | (b << 16) | (c << 8) | d);
  9633. so->lsa.sin.sin_port = htons((uint16_t)port);
  9634. *ip_version = 4;
  9635. #if defined(USE_IPV6)
  9636. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  9637. && mg_inet_pton(
  9638. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  9639. /* IPv6 address, examples: see above */
  9640. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  9641. */
  9642. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  9643. *ip_version = 6;
  9644. #endif
  9645. } else if ((vec->ptr[0] == '+')
  9646. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  9647. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  9648. /* Add 1 to len for the + character we skipped before */
  9649. len++;
  9650. #if defined(USE_IPV6)
  9651. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  9652. so->lsa.sin6.sin6_family = AF_INET6;
  9653. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  9654. *ip_version = 4 + 6;
  9655. #else
  9656. /* Bind to IPv4 only, since IPv6 is not built in. */
  9657. so->lsa.sin.sin_port = htons((uint16_t)port);
  9658. *ip_version = 4;
  9659. #endif
  9660. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  9661. /* If only port is specified, bind to IPv4, INADDR_ANY */
  9662. so->lsa.sin.sin_port = htons((uint16_t)port);
  9663. *ip_version = 4;
  9664. } else {
  9665. /* Parsing failure. Make port invalid. */
  9666. port = 0;
  9667. len = 0;
  9668. }
  9669. /* sscanf and the option splitting code ensure the following condition
  9670. */
  9671. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  9672. *ip_version = 0;
  9673. return 0;
  9674. }
  9675. ch = vec->ptr[len]; /* Next character after the port number */
  9676. so->is_ssl = (ch == 's');
  9677. so->ssl_redir = (ch == 'r');
  9678. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  9679. if (is_valid_port(port)
  9680. && (ch == '\0' || ch == 's' || ch == 'r' || ch == ',')) {
  9681. return 1;
  9682. }
  9683. /* Reset ip_version to 0 of there is an error */
  9684. *ip_version = 0;
  9685. return 0;
  9686. }
  9687. static int
  9688. set_ports_option(struct mg_context *ctx)
  9689. {
  9690. const char *list;
  9691. int on = 1;
  9692. #if defined(USE_IPV6)
  9693. int off = 0;
  9694. #endif
  9695. struct vec vec;
  9696. struct socket so, *ptr;
  9697. struct pollfd *pfd;
  9698. union usa usa;
  9699. socklen_t len;
  9700. int ip_version;
  9701. int portsTotal = 0;
  9702. int portsOk = 0;
  9703. if (!ctx) {
  9704. return 0;
  9705. }
  9706. memset(&so, 0, sizeof(so));
  9707. memset(&usa, 0, sizeof(usa));
  9708. len = sizeof(usa);
  9709. list = ctx->config[LISTENING_PORTS];
  9710. while ((list = next_option(list, &vec, NULL)) != NULL) {
  9711. portsTotal++;
  9712. if (!parse_port_string(&vec, &so, &ip_version)) {
  9713. mg_cry(fc(ctx),
  9714. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  9715. (int)vec.len,
  9716. vec.ptr,
  9717. portsTotal,
  9718. "[IP_ADDRESS:]PORT[s|r]");
  9719. continue;
  9720. }
  9721. #if !defined(NO_SSL)
  9722. if (so.is_ssl && ctx->ssl_ctx == NULL) {
  9723. mg_cry(fc(ctx),
  9724. "Cannot add SSL socket (entry %i). Is -ssl_certificate "
  9725. "option set?",
  9726. portsTotal);
  9727. continue;
  9728. }
  9729. #endif
  9730. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  9731. == INVALID_SOCKET) {
  9732. mg_cry(fc(ctx), "cannot create socket (entry %i)", portsTotal);
  9733. continue;
  9734. }
  9735. #ifdef _WIN32
  9736. /* Windows SO_REUSEADDR lets many procs binds to a
  9737. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  9738. * if someone already has the socket -- DTL */
  9739. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  9740. * Windows might need a few seconds before
  9741. * the same port can be used again in the
  9742. * same process, so a short Sleep may be
  9743. * required between mg_stop and mg_start.
  9744. */
  9745. if (setsockopt(so.sock,
  9746. SOL_SOCKET,
  9747. SO_EXCLUSIVEADDRUSE,
  9748. (SOCK_OPT_TYPE)&on,
  9749. sizeof(on)) != 0) {
  9750. /* Set reuse option, but don't abort on errors. */
  9751. mg_cry(fc(ctx),
  9752. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  9753. portsTotal);
  9754. }
  9755. #else
  9756. if (setsockopt(so.sock,
  9757. SOL_SOCKET,
  9758. SO_REUSEADDR,
  9759. (SOCK_OPT_TYPE)&on,
  9760. sizeof(on)) != 0) {
  9761. /* Set reuse option, but don't abort on errors. */
  9762. mg_cry(fc(ctx),
  9763. "cannot set socket option SO_REUSEADDR (entry %i)",
  9764. portsTotal);
  9765. }
  9766. #endif
  9767. if (ip_version > 4) {
  9768. #if defined(USE_IPV6)
  9769. if (ip_version == 6) {
  9770. if (so.lsa.sa.sa_family == AF_INET6
  9771. && setsockopt(so.sock,
  9772. IPPROTO_IPV6,
  9773. IPV6_V6ONLY,
  9774. (void *)&off,
  9775. sizeof(off)) != 0) {
  9776. /* Set IPv6 only option, but don't abort on errors. */
  9777. mg_cry(fc(ctx),
  9778. "cannot set socket option IPV6_V6ONLY (entry %i)",
  9779. portsTotal);
  9780. }
  9781. }
  9782. #else
  9783. mg_cry(fc(ctx), "IPv6 not available");
  9784. closesocket(so.sock);
  9785. so.sock = INVALID_SOCKET;
  9786. continue;
  9787. #endif
  9788. }
  9789. if (so.lsa.sa.sa_family == AF_INET) {
  9790. len = sizeof(so.lsa.sin);
  9791. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  9792. mg_cry(fc(ctx),
  9793. "cannot bind to %.*s: %d (%s)",
  9794. (int)vec.len,
  9795. vec.ptr,
  9796. (int)ERRNO,
  9797. strerror(errno));
  9798. closesocket(so.sock);
  9799. so.sock = INVALID_SOCKET;
  9800. continue;
  9801. }
  9802. }
  9803. #if defined(USE_IPV6)
  9804. else if (so.lsa.sa.sa_family == AF_INET6) {
  9805. len = sizeof(so.lsa.sin6);
  9806. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  9807. mg_cry(fc(ctx),
  9808. "cannot bind to IPv6 %.*s: %d (%s)",
  9809. (int)vec.len,
  9810. vec.ptr,
  9811. (int)ERRNO,
  9812. strerror(errno));
  9813. closesocket(so.sock);
  9814. so.sock = INVALID_SOCKET;
  9815. continue;
  9816. }
  9817. }
  9818. #endif
  9819. else {
  9820. mg_cry(fc(ctx),
  9821. "cannot bind: address family not supported (entry %i)",
  9822. portsTotal);
  9823. continue;
  9824. }
  9825. if (listen(so.sock, SOMAXCONN) != 0) {
  9826. mg_cry(fc(ctx),
  9827. "cannot listen to %.*s: %d (%s)",
  9828. (int)vec.len,
  9829. vec.ptr,
  9830. (int)ERRNO,
  9831. strerror(errno));
  9832. closesocket(so.sock);
  9833. so.sock = INVALID_SOCKET;
  9834. continue;
  9835. }
  9836. if (getsockname(so.sock, &(usa.sa), &len) != 0
  9837. || usa.sa.sa_family != so.lsa.sa.sa_family) {
  9838. int err = (int)ERRNO;
  9839. mg_cry(fc(ctx),
  9840. "call to getsockname failed %.*s: %d (%s)",
  9841. (int)vec.len,
  9842. vec.ptr,
  9843. err,
  9844. strerror(errno));
  9845. closesocket(so.sock);
  9846. so.sock = INVALID_SOCKET;
  9847. continue;
  9848. }
  9849. /* Update lsa port in case of random free ports */
  9850. #if defined(USE_IPV6)
  9851. if (so.lsa.sa.sa_family == AF_INET6) {
  9852. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  9853. } else
  9854. #endif
  9855. {
  9856. so.lsa.sin.sin_port = usa.sin.sin_port;
  9857. }
  9858. if ((ptr = (struct socket *)
  9859. mg_realloc(ctx->listening_sockets,
  9860. (ctx->num_listening_sockets + 1)
  9861. * sizeof(ctx->listening_sockets[0]))) == NULL) {
  9862. mg_cry(fc(ctx), "%s", "Out of memory");
  9863. closesocket(so.sock);
  9864. so.sock = INVALID_SOCKET;
  9865. continue;
  9866. }
  9867. if ((pfd = (struct pollfd *)mg_realloc(
  9868. ctx->listening_socket_fds,
  9869. (ctx->num_listening_sockets + 1)
  9870. * sizeof(ctx->listening_socket_fds[0]))) == NULL) {
  9871. mg_cry(fc(ctx), "%s", "Out of memory");
  9872. closesocket(so.sock);
  9873. so.sock = INVALID_SOCKET;
  9874. mg_free(ptr);
  9875. continue;
  9876. }
  9877. set_close_on_exec(so.sock, fc(ctx));
  9878. ctx->listening_sockets = ptr;
  9879. ctx->listening_sockets[ctx->num_listening_sockets] = so;
  9880. ctx->listening_socket_fds = pfd;
  9881. ctx->num_listening_sockets++;
  9882. portsOk++;
  9883. }
  9884. if (portsOk != portsTotal) {
  9885. close_all_listening_sockets(ctx);
  9886. portsOk = 0;
  9887. }
  9888. return portsOk;
  9889. }
  9890. static const char *
  9891. header_val(const struct mg_connection *conn, const char *header)
  9892. {
  9893. const char *header_value;
  9894. if ((header_value = mg_get_header(conn, header)) == NULL) {
  9895. return "-";
  9896. } else {
  9897. return header_value;
  9898. }
  9899. }
  9900. static void
  9901. log_access(const struct mg_connection *conn)
  9902. {
  9903. const struct mg_request_info *ri;
  9904. struct mg_file fi;
  9905. char date[64], src_addr[IP_ADDR_STR_LEN];
  9906. struct tm *tm;
  9907. const char *referer;
  9908. const char *user_agent;
  9909. char buf[4096];
  9910. if (!conn || !conn->ctx) {
  9911. return;
  9912. }
  9913. if (conn->ctx->config[ACCESS_LOG_FILE] != NULL) {
  9914. if (mg_fopen(conn,
  9915. conn->ctx->config[ACCESS_LOG_FILE],
  9916. MG_FOPEN_MODE_APPEND,
  9917. &fi) == 0) {
  9918. fi.access.fp = NULL;
  9919. }
  9920. } else {
  9921. fi.access.fp = NULL;
  9922. }
  9923. /* Log is written to a file and/or a callback. If both are not set,
  9924. * executing the rest of the function is pointless. */
  9925. if ((fi.access.fp == NULL) && (conn->ctx->callbacks.log_access == NULL)) {
  9926. return;
  9927. }
  9928. tm = localtime(&conn->conn_birth_time);
  9929. if (tm != NULL) {
  9930. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  9931. } else {
  9932. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  9933. date[sizeof(date) - 1] = '\0';
  9934. }
  9935. ri = &conn->request_info;
  9936. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9937. referer = header_val(conn, "Referer");
  9938. user_agent = header_val(conn, "User-Agent");
  9939. mg_snprintf(conn,
  9940. NULL, /* Ignore truncation in access log */
  9941. buf,
  9942. sizeof(buf),
  9943. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  9944. src_addr,
  9945. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  9946. date,
  9947. ri->request_method ? ri->request_method : "-",
  9948. ri->request_uri ? ri->request_uri : "-",
  9949. ri->query_string ? "?" : "",
  9950. ri->query_string ? ri->query_string : "",
  9951. ri->http_version,
  9952. conn->status_code,
  9953. conn->num_bytes_sent,
  9954. referer,
  9955. user_agent);
  9956. if (conn->ctx->callbacks.log_access) {
  9957. conn->ctx->callbacks.log_access(conn, buf);
  9958. }
  9959. if (fi.access.fp) {
  9960. int ok = 1;
  9961. flockfile(fi.access.fp);
  9962. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  9963. ok = 0;
  9964. }
  9965. if (fflush(fi.access.fp) != 0) {
  9966. ok = 0;
  9967. }
  9968. funlockfile(fi.access.fp);
  9969. if (mg_fclose(&fi.access) != 0) {
  9970. ok = 0;
  9971. }
  9972. if (!ok) {
  9973. mg_cry(conn,
  9974. "Error writing log file %s",
  9975. conn->ctx->config[ACCESS_LOG_FILE]);
  9976. }
  9977. }
  9978. }
  9979. /* Verify given socket address against the ACL.
  9980. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  9981. */
  9982. static int
  9983. check_acl(struct mg_context *ctx, uint32_t remote_ip)
  9984. {
  9985. int allowed, flag;
  9986. uint32_t net, mask;
  9987. struct vec vec;
  9988. if (ctx) {
  9989. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  9990. /* If any ACL is set, deny by default */
  9991. allowed = (list == NULL) ? '+' : '-';
  9992. while ((list = next_option(list, &vec, NULL)) != NULL) {
  9993. flag = vec.ptr[0];
  9994. if ((flag != '+' && flag != '-')
  9995. || parse_net(&vec.ptr[1], &net, &mask) == 0) {
  9996. mg_cry(fc(ctx),
  9997. "%s: subnet must be [+|-]x.x.x.x[/x]",
  9998. __func__);
  9999. return -1;
  10000. }
  10001. if (net == (remote_ip & mask)) {
  10002. allowed = flag;
  10003. }
  10004. }
  10005. return allowed == '+';
  10006. }
  10007. return -1;
  10008. }
  10009. #if !defined(_WIN32)
  10010. static int
  10011. set_uid_option(struct mg_context *ctx)
  10012. {
  10013. struct passwd *pw;
  10014. if (ctx) {
  10015. const char *uid = ctx->config[RUN_AS_USER];
  10016. int success = 0;
  10017. if (uid == NULL) {
  10018. success = 1;
  10019. } else {
  10020. if ((pw = getpwnam(uid)) == NULL) {
  10021. mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  10022. } else if (setgid(pw->pw_gid) == -1) {
  10023. mg_cry(fc(ctx),
  10024. "%s: setgid(%s): %s",
  10025. __func__,
  10026. uid,
  10027. strerror(errno));
  10028. } else if (setgroups(0, NULL)) {
  10029. mg_cry(fc(ctx),
  10030. "%s: setgroups(): %s",
  10031. __func__,
  10032. strerror(errno));
  10033. } else if (setuid(pw->pw_uid) == -1) {
  10034. mg_cry(fc(ctx),
  10035. "%s: setuid(%s): %s",
  10036. __func__,
  10037. uid,
  10038. strerror(errno));
  10039. } else {
  10040. success = 1;
  10041. }
  10042. }
  10043. return success;
  10044. }
  10045. return 0;
  10046. }
  10047. #endif /* !_WIN32 */
  10048. static void
  10049. tls_dtor(void *key)
  10050. {
  10051. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  10052. /* key == pthread_getspecific(sTlsKey); */
  10053. if (tls) {
  10054. if (tls->is_master == 2) {
  10055. tls->is_master = -3; /* Mark memory as dead */
  10056. mg_free(tls);
  10057. }
  10058. }
  10059. pthread_setspecific(sTlsKey, NULL);
  10060. }
  10061. #if !defined(NO_SSL)
  10062. /* Must be set if sizeof(pthread_t) > sizeof(unsigned long) */
  10063. static unsigned long
  10064. ssl_id_callback(void)
  10065. {
  10066. #ifdef _WIN32
  10067. return GetCurrentThreadId();
  10068. #else
  10069. #ifdef __clang__
  10070. #pragma clang diagnostic push
  10071. #pragma clang diagnostic ignored "-Wunreachable-code"
  10072. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  10073. * or not, so one of the two conditions will be unreachable by construction.
  10074. * Unfortunately the C standard does not define a way to check this at
  10075. * compile time, since the #if preprocessor conditions can not use the sizeof
  10076. * operator as an argument. */
  10077. #endif
  10078. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  10079. /* This is the problematic case for CRYPTO_set_id_callback:
  10080. * The OS pthread_t can not be cast to unsigned long. */
  10081. struct mg_workerTLS *tls =
  10082. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  10083. if (tls == NULL) {
  10084. /* SSL called from an unknown thread: Create some thread index.
  10085. */
  10086. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  10087. tls->is_master = -2; /* -2 means "3rd party thread" */
  10088. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  10089. pthread_setspecific(sTlsKey, tls);
  10090. }
  10091. return tls->thread_idx;
  10092. } else {
  10093. /* pthread_t may be any data type, so a simple cast to unsigned long
  10094. * can rise a warning/error, depending on the platform.
  10095. * Here memcpy is used as an anything-to-anything cast. */
  10096. unsigned long ret = 0;
  10097. pthread_t t = pthread_self();
  10098. memcpy(&ret, &t, sizeof(pthread_t));
  10099. return ret;
  10100. }
  10101. #ifdef __clang__
  10102. #pragma clang diagnostic pop
  10103. #endif
  10104. #endif
  10105. }
  10106. static int ssl_use_pem_file(struct mg_context *ctx, const char *pem);
  10107. static const char *ssl_error(void);
  10108. static int
  10109. refresh_trust(struct mg_connection *conn)
  10110. {
  10111. static int reload_lock = 0;
  10112. static long int data_check = 0;
  10113. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  10114. struct stat cert_buf;
  10115. long int t;
  10116. char *pem;
  10117. int should_verify_peer;
  10118. if ((pem = conn->ctx->config[SSL_CERTIFICATE]) == NULL) {
  10119. /* If peem is NULL and conn->ctx->callbacks.init_ssl is not,
  10120. * refresh_trust still can not work. */
  10121. return 0;
  10122. }
  10123. t = data_check;
  10124. if (stat(pem, &cert_buf) != -1) {
  10125. t = (long int)cert_buf.st_mtime;
  10126. }
  10127. if (data_check != t) {
  10128. data_check = t;
  10129. should_verify_peer =
  10130. (conn->ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  10131. && (mg_strcasecmp(conn->ctx->config[SSL_DO_VERIFY_PEER], "yes")
  10132. == 0);
  10133. if (should_verify_peer) {
  10134. char *ca_path = conn->ctx->config[SSL_CA_PATH];
  10135. char *ca_file = conn->ctx->config[SSL_CA_FILE];
  10136. if (SSL_CTX_load_verify_locations(conn->ctx->ssl_ctx,
  10137. ca_file,
  10138. ca_path) != 1) {
  10139. mg_cry(fc(conn->ctx),
  10140. "SSL_CTX_load_verify_locations error: %s "
  10141. "ssl_verify_peer requires setting "
  10142. "either ssl_ca_path or ssl_ca_file. Is any of them "
  10143. "present in "
  10144. "the .conf file?",
  10145. ssl_error());
  10146. return 0;
  10147. }
  10148. }
  10149. if (1 == mg_atomic_inc(p_reload_lock)) {
  10150. if (ssl_use_pem_file(conn->ctx, pem) == 0) {
  10151. return 0;
  10152. }
  10153. *p_reload_lock = 0;
  10154. }
  10155. }
  10156. /* lock while cert is reloading */
  10157. while (*p_reload_lock) {
  10158. sleep(1);
  10159. }
  10160. return 1;
  10161. }
  10162. static pthread_mutex_t *ssl_mutexes;
  10163. static int
  10164. sslize(struct mg_connection *conn,
  10165. SSL_CTX *s,
  10166. int (*func)(SSL *),
  10167. volatile int *stop_server)
  10168. {
  10169. int ret, err;
  10170. int short_trust;
  10171. unsigned i;
  10172. if (!conn) {
  10173. return 0;
  10174. }
  10175. short_trust =
  10176. (conn->ctx->config[SSL_SHORT_TRUST] != NULL)
  10177. && (mg_strcasecmp(conn->ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  10178. if (short_trust) {
  10179. int trust_ret = refresh_trust(conn);
  10180. if (!trust_ret) {
  10181. return trust_ret;
  10182. }
  10183. }
  10184. conn->ssl = SSL_new(s);
  10185. if (conn->ssl == NULL) {
  10186. return 0;
  10187. }
  10188. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  10189. if (ret != 1) {
  10190. err = SSL_get_error(conn->ssl, ret);
  10191. (void)err; /* TODO: set some error message */
  10192. SSL_free(conn->ssl);
  10193. conn->ssl = NULL;
  10194. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  10195. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  10196. ERR_remove_state(0);
  10197. return 0;
  10198. }
  10199. /* SSL functions may fail and require to be called again:
  10200. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  10201. * Here "func" could be SSL_connect or SSL_accept. */
  10202. for (i = 16; i <= 1024; i *= 2) {
  10203. ret = func(conn->ssl);
  10204. if (ret != 1) {
  10205. err = SSL_get_error(conn->ssl, ret);
  10206. if ((err == SSL_ERROR_WANT_CONNECT)
  10207. || (err == SSL_ERROR_WANT_ACCEPT)
  10208. || (err == SSL_ERROR_WANT_READ)
  10209. || (err == SSL_ERROR_WANT_WRITE)) {
  10210. /* Need to retry the function call "later".
  10211. * See https://linux.die.net/man/3/ssl_get_error
  10212. * This is typical for non-blocking sockets. */
  10213. if (*stop_server) {
  10214. /* Don't wait if the server is going to be stopped. */
  10215. break;
  10216. }
  10217. mg_sleep(i);
  10218. } else if (err == SSL_ERROR_SYSCALL) {
  10219. /* This is an IO error. Look at errno. */
  10220. err = errno;
  10221. /* TODO: set some error message */
  10222. break;
  10223. } else {
  10224. /* This is an SSL specific error */
  10225. /* TODO: set some error message */
  10226. break;
  10227. }
  10228. } else {
  10229. /* success */
  10230. break;
  10231. }
  10232. }
  10233. if (ret != 1) {
  10234. SSL_free(conn->ssl);
  10235. conn->ssl = NULL;
  10236. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  10237. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  10238. ERR_remove_state(0);
  10239. return 0;
  10240. }
  10241. return 1;
  10242. }
  10243. /* Return OpenSSL error message (from CRYPTO lib) */
  10244. static const char *
  10245. ssl_error(void)
  10246. {
  10247. unsigned long err;
  10248. err = ERR_get_error();
  10249. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  10250. }
  10251. static int
  10252. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  10253. {
  10254. int i;
  10255. const char hexdigit[] = "0123456789abcdef";
  10256. if (memlen <= 0 || buflen <= 0) {
  10257. return 0;
  10258. }
  10259. if (buflen < (3 * memlen)) {
  10260. return 0;
  10261. }
  10262. for (i = 0; i < memlen; i++) {
  10263. if (i > 0) {
  10264. buf[3 * i - 1] = ' ';
  10265. }
  10266. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  10267. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  10268. }
  10269. buf[3 * memlen - 1] = 0;
  10270. return 1;
  10271. }
  10272. static void
  10273. ssl_get_client_cert_info(struct mg_connection *conn)
  10274. {
  10275. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  10276. if (cert) {
  10277. char str_subject[1024];
  10278. char str_issuer[1024];
  10279. char str_serial[1024];
  10280. char str_finger[1024];
  10281. unsigned char buf[256];
  10282. int len;
  10283. unsigned int ulen;
  10284. /* Handle to algorithm used for fingerprint */
  10285. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  10286. /* Get Subject and issuer */
  10287. X509_NAME *subj = X509_get_subject_name(cert);
  10288. X509_NAME *iss = X509_get_issuer_name(cert);
  10289. /* Get serial number */
  10290. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  10291. /* Translate subject and issuer to a string */
  10292. (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
  10293. (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
  10294. /* Translate serial number to a hex string */
  10295. len = i2c_ASN1_INTEGER(serial, NULL);
  10296. if ((len > 0) && ((unsigned)len < (unsigned)sizeof(buf))) {
  10297. unsigned char *pbuf = buf;
  10298. int len2 = i2c_ASN1_INTEGER(serial, &pbuf);
  10299. if (!hexdump2string(
  10300. buf, len2, str_serial, (int)sizeof(str_serial))) {
  10301. *str_serial = 0;
  10302. }
  10303. } else {
  10304. *str_serial = 0;
  10305. }
  10306. /* Calculate SHA1 fingerprint and store as a hex string */
  10307. ulen = 0;
  10308. ASN1_digest((int (*)())i2d_X509, digest, (char *)cert, buf, &ulen);
  10309. if (!hexdump2string(
  10310. buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
  10311. *str_finger = 0;
  10312. }
  10313. conn->request_info.client_cert =
  10314. (struct client_cert *)mg_malloc(sizeof(struct client_cert));
  10315. if (conn->request_info.client_cert) {
  10316. conn->request_info.client_cert->subject = mg_strdup(str_subject);
  10317. conn->request_info.client_cert->issuer = mg_strdup(str_issuer);
  10318. conn->request_info.client_cert->serial = mg_strdup(str_serial);
  10319. conn->request_info.client_cert->finger = mg_strdup(str_finger);
  10320. } else {
  10321. /* TODO: write some OOM message */
  10322. }
  10323. X509_free(cert);
  10324. }
  10325. }
  10326. static void
  10327. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  10328. {
  10329. (void)line;
  10330. (void)file;
  10331. if (mode & 1) {
  10332. /* 1 is CRYPTO_LOCK */
  10333. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  10334. } else {
  10335. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  10336. }
  10337. }
  10338. #if !defined(NO_SSL_DL)
  10339. static void *
  10340. load_dll(struct mg_context *ctx, const char *dll_name, struct ssl_func *sw)
  10341. {
  10342. union {
  10343. void *p;
  10344. void (*fp)(void);
  10345. } u;
  10346. void *dll_handle;
  10347. struct ssl_func *fp;
  10348. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  10349. mg_cry(fc(ctx), "%s: cannot load %s", __func__, dll_name);
  10350. return NULL;
  10351. }
  10352. for (fp = sw; fp->name != NULL; fp++) {
  10353. #ifdef _WIN32
  10354. /* GetProcAddress() returns pointer to function */
  10355. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  10356. #else
  10357. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  10358. * pointers to function pointers. We need to use a union to make a
  10359. * cast. */
  10360. u.p = dlsym(dll_handle, fp->name);
  10361. #endif /* _WIN32 */
  10362. if (u.fp == NULL) {
  10363. mg_cry(fc(ctx),
  10364. "%s: %s: cannot find %s",
  10365. __func__,
  10366. dll_name,
  10367. fp->name);
  10368. dlclose(dll_handle);
  10369. return NULL;
  10370. } else {
  10371. fp->ptr = u.fp;
  10372. }
  10373. }
  10374. return dll_handle;
  10375. }
  10376. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  10377. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  10378. #endif /* NO_SSL_DL */
  10379. #if defined(SSL_ALREADY_INITIALIZED)
  10380. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  10381. #else
  10382. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  10383. #endif
  10384. static int
  10385. initialize_ssl(struct mg_context *ctx)
  10386. {
  10387. int i;
  10388. size_t size;
  10389. #if !defined(NO_SSL_DL)
  10390. if (!cryptolib_dll_handle) {
  10391. cryptolib_dll_handle = load_dll(ctx, CRYPTO_LIB, crypto_sw);
  10392. if (!cryptolib_dll_handle) {
  10393. return 0;
  10394. }
  10395. }
  10396. #endif /* NO_SSL_DL */
  10397. if (mg_atomic_inc(&cryptolib_users) > 1) {
  10398. return 1;
  10399. }
  10400. /* Initialize locking callbacks, needed for thread safety.
  10401. * http://www.openssl.org/support/faq.html#PROG1
  10402. */
  10403. i = CRYPTO_num_locks();
  10404. if (i < 0) {
  10405. i = 0;
  10406. }
  10407. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  10408. if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  10409. mg_cry(fc(ctx),
  10410. "%s: cannot allocate mutexes: %s",
  10411. __func__,
  10412. ssl_error());
  10413. return 0;
  10414. }
  10415. for (i = 0; i < CRYPTO_num_locks(); i++) {
  10416. pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr);
  10417. }
  10418. CRYPTO_set_locking_callback(&ssl_locking_callback);
  10419. CRYPTO_set_id_callback(&ssl_id_callback);
  10420. return 1;
  10421. }
  10422. static int
  10423. ssl_use_pem_file(struct mg_context *ctx, const char *pem)
  10424. {
  10425. if (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0) {
  10426. mg_cry(fc(ctx),
  10427. "%s: cannot open certificate file %s: %s",
  10428. __func__,
  10429. pem,
  10430. ssl_error());
  10431. return 0;
  10432. }
  10433. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  10434. if (SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0) {
  10435. mg_cry(fc(ctx),
  10436. "%s: cannot open private key file %s: %s",
  10437. __func__,
  10438. pem,
  10439. ssl_error());
  10440. return 0;
  10441. }
  10442. if (SSL_CTX_check_private_key(ctx->ssl_ctx) == 0) {
  10443. mg_cry(fc(ctx),
  10444. "%s: certificate and private key do not match: %s",
  10445. __func__,
  10446. pem);
  10447. return 0;
  10448. }
  10449. if (SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem) == 0) {
  10450. mg_cry(fc(ctx),
  10451. "%s: cannot use certificate chain file %s: %s",
  10452. __func__,
  10453. pem,
  10454. ssl_error());
  10455. return 0;
  10456. }
  10457. return 1;
  10458. }
  10459. static long
  10460. ssl_get_protocol(int version_id)
  10461. {
  10462. long ret = SSL_OP_ALL;
  10463. if (version_id > 0)
  10464. ret |= SSL_OP_NO_SSLv2;
  10465. if (version_id > 1)
  10466. ret |= SSL_OP_NO_SSLv3;
  10467. if (version_id > 2)
  10468. ret |= SSL_OP_NO_TLSv1;
  10469. if (version_id > 3)
  10470. ret |= SSL_OP_NO_TLSv1_1;
  10471. return ret;
  10472. }
  10473. /* Dynamically load SSL library. Set up ctx->ssl_ctx pointer. */
  10474. static int
  10475. set_ssl_option(struct mg_context *ctx)
  10476. {
  10477. const char *pem;
  10478. int callback_ret;
  10479. int should_verify_peer;
  10480. const char *ca_path;
  10481. const char *ca_file;
  10482. int use_default_verify_paths;
  10483. int verify_depth;
  10484. time_t now_rt = time(NULL);
  10485. struct timespec now_mt;
  10486. md5_byte_t ssl_context_id[16];
  10487. md5_state_t md5state;
  10488. int protocol_ver;
  10489. /* If PEM file is not specified and the init_ssl callback
  10490. * is not specified, skip SSL initialization. */
  10491. if (!ctx) {
  10492. return 0;
  10493. }
  10494. if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL
  10495. && ctx->callbacks.init_ssl == NULL) {
  10496. return 1;
  10497. }
  10498. if (!initialize_ssl(ctx)) {
  10499. return 0;
  10500. }
  10501. #if !defined(NO_SSL_DL)
  10502. if (!ssllib_dll_handle) {
  10503. ssllib_dll_handle = load_dll(ctx, SSL_LIB, ssl_sw);
  10504. if (!ssllib_dll_handle) {
  10505. return 0;
  10506. }
  10507. }
  10508. #endif /* NO_SSL_DL */
  10509. /* Initialize SSL library */
  10510. SSL_library_init();
  10511. SSL_load_error_strings();
  10512. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  10513. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  10514. return 0;
  10515. }
  10516. SSL_CTX_clear_options(ctx->ssl_ctx,
  10517. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  10518. | SSL_OP_NO_TLSv1_1);
  10519. protocol_ver = atoi(ctx->config[SSL_PROTOCOL_VERSION]);
  10520. SSL_CTX_set_options(ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  10521. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  10522. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  10523. SSL_CTX_set_ecdh_auto(ctx->ssl_ctx, 1);
  10524. /* If a callback has been specified, call it. */
  10525. callback_ret =
  10526. (ctx->callbacks.init_ssl == NULL)
  10527. ? 0
  10528. : (ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data));
  10529. /* If callback returns 0, civetweb sets up the SSL certificate.
  10530. * If it returns 1, civetweb assumes the calback already did this.
  10531. * If it returns -1, initializing ssl fails. */
  10532. if (callback_ret < 0) {
  10533. mg_cry(fc(ctx), "SSL callback returned error: %i", callback_ret);
  10534. return 0;
  10535. }
  10536. if (callback_ret > 0) {
  10537. if (pem != NULL) {
  10538. (void)SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
  10539. }
  10540. return 1;
  10541. }
  10542. /* Use some UID as session context ID. */
  10543. md5_init(&md5state);
  10544. md5_append(&md5state, (const md5_byte_t *)&now_rt, sizeof(now_rt));
  10545. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  10546. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  10547. md5_append(&md5state,
  10548. (const md5_byte_t *)ctx->config[LISTENING_PORTS],
  10549. strlen(ctx->config[LISTENING_PORTS]));
  10550. md5_append(&md5state, (const md5_byte_t *)ctx, sizeof(*ctx));
  10551. md5_finish(&md5state, ssl_context_id);
  10552. SSL_CTX_set_session_id_context(ctx->ssl_ctx,
  10553. (const unsigned char *)&ssl_context_id,
  10554. sizeof(ssl_context_id));
  10555. if (pem != NULL) {
  10556. if (!ssl_use_pem_file(ctx, pem)) {
  10557. return 0;
  10558. }
  10559. }
  10560. should_verify_peer =
  10561. (ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  10562. && (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0);
  10563. use_default_verify_paths =
  10564. (ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  10565. && (mg_strcasecmp(ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes") == 0);
  10566. if (should_verify_peer) {
  10567. ca_path = ctx->config[SSL_CA_PATH];
  10568. ca_file = ctx->config[SSL_CA_FILE];
  10569. if (SSL_CTX_load_verify_locations(ctx->ssl_ctx, ca_file, ca_path)
  10570. != 1) {
  10571. mg_cry(fc(ctx),
  10572. "SSL_CTX_load_verify_locations error: %s "
  10573. "ssl_verify_peer requires setting "
  10574. "either ssl_ca_path or ssl_ca_file. Is any of them "
  10575. "present in "
  10576. "the .conf file?",
  10577. ssl_error());
  10578. return 0;
  10579. }
  10580. SSL_CTX_set_verify(ctx->ssl_ctx,
  10581. SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  10582. NULL);
  10583. if (use_default_verify_paths
  10584. && SSL_CTX_set_default_verify_paths(ctx->ssl_ctx) != 1) {
  10585. mg_cry(fc(ctx),
  10586. "SSL_CTX_set_default_verify_paths error: %s",
  10587. ssl_error());
  10588. return 0;
  10589. }
  10590. if (ctx->config[SSL_VERIFY_DEPTH]) {
  10591. verify_depth = atoi(ctx->config[SSL_VERIFY_DEPTH]);
  10592. SSL_CTX_set_verify_depth(ctx->ssl_ctx, verify_depth);
  10593. }
  10594. }
  10595. if (ctx->config[SSL_CIPHER_LIST] != NULL) {
  10596. if (SSL_CTX_set_cipher_list(ctx->ssl_ctx, ctx->config[SSL_CIPHER_LIST])
  10597. != 1) {
  10598. mg_cry(fc(ctx), "SSL_CTX_set_cipher_list error: %s", ssl_error());
  10599. }
  10600. }
  10601. return 1;
  10602. }
  10603. static void
  10604. uninitialize_ssl(struct mg_context *ctx)
  10605. {
  10606. int i;
  10607. (void)ctx;
  10608. if (mg_atomic_dec(&cryptolib_users) == 0) {
  10609. /* Shutdown according to
  10610. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  10611. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  10612. */
  10613. CRYPTO_set_locking_callback(NULL);
  10614. CRYPTO_set_id_callback(NULL);
  10615. ENGINE_cleanup();
  10616. CONF_modules_unload(1);
  10617. ERR_free_strings();
  10618. EVP_cleanup();
  10619. CRYPTO_cleanup_all_ex_data();
  10620. ERR_remove_state(0);
  10621. for (i = 0; i < CRYPTO_num_locks(); i++) {
  10622. pthread_mutex_destroy(&ssl_mutexes[i]);
  10623. }
  10624. mg_free(ssl_mutexes);
  10625. ssl_mutexes = NULL;
  10626. }
  10627. }
  10628. #endif /* !NO_SSL */
  10629. static int
  10630. set_gpass_option(struct mg_context *ctx)
  10631. {
  10632. if (ctx) {
  10633. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10634. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  10635. if (path != NULL && !mg_stat(fc(ctx), path, &file.stat)) {
  10636. mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  10637. return 0;
  10638. }
  10639. return 1;
  10640. }
  10641. return 0;
  10642. }
  10643. static int
  10644. set_acl_option(struct mg_context *ctx)
  10645. {
  10646. return check_acl(ctx, (uint32_t)0x7f000001UL) != -1;
  10647. }
  10648. static void
  10649. reset_per_request_attributes(struct mg_connection *conn)
  10650. {
  10651. if (!conn) {
  10652. return;
  10653. }
  10654. conn->path_info = NULL;
  10655. conn->num_bytes_sent = conn->consumed_content = 0;
  10656. conn->status_code = -1;
  10657. conn->is_chunked = 0;
  10658. conn->must_close = conn->request_len = conn->throttle = 0;
  10659. conn->request_info.content_length = -1;
  10660. conn->request_info.remote_user = NULL;
  10661. conn->request_info.request_method = NULL;
  10662. conn->request_info.request_uri = NULL;
  10663. conn->request_info.local_uri = NULL;
  10664. conn->request_info.uri = NULL; /* TODO: cleanup uri,
  10665. * local_uri and request_uri */
  10666. conn->request_info.http_version = NULL;
  10667. conn->request_info.num_headers = 0;
  10668. conn->data_len = 0;
  10669. conn->chunk_remainder = 0;
  10670. conn->internal_error = 0;
  10671. }
  10672. static int
  10673. set_sock_timeout(SOCKET sock, int milliseconds)
  10674. {
  10675. int r0 = 0, r1, r2;
  10676. #ifdef _WIN32
  10677. /* Windows specific */
  10678. DWORD tv = (DWORD)milliseconds;
  10679. #else
  10680. /* Linux, ... (not Windows) */
  10681. struct timeval tv;
  10682. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  10683. * max. time waiting for the acknowledged of TCP data before the connection
  10684. * will be forcefully closed and ETIMEDOUT is returned to the application.
  10685. * If this option is not set, the default timeout of 20-30 minutes is used.
  10686. */
  10687. /* #define TCP_USER_TIMEOUT (18) */
  10688. #if defined(TCP_USER_TIMEOUT)
  10689. unsigned int uto = (unsigned int)milliseconds;
  10690. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  10691. #endif
  10692. memset(&tv, 0, sizeof(tv));
  10693. tv.tv_sec = milliseconds / 1000;
  10694. tv.tv_usec = (milliseconds * 1000) % 1000000;
  10695. #endif /* _WIN32 */
  10696. r1 = setsockopt(
  10697. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  10698. r2 = setsockopt(
  10699. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  10700. return r0 || r1 || r2;
  10701. }
  10702. static int
  10703. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  10704. {
  10705. if (setsockopt(sock,
  10706. IPPROTO_TCP,
  10707. TCP_NODELAY,
  10708. (SOCK_OPT_TYPE)&nodelay_on,
  10709. sizeof(nodelay_on)) != 0) {
  10710. /* Error */
  10711. return 1;
  10712. }
  10713. /* OK */
  10714. return 0;
  10715. }
  10716. static void
  10717. close_socket_gracefully(struct mg_connection *conn)
  10718. {
  10719. #if defined(_WIN32)
  10720. char buf[MG_BUF_LEN];
  10721. int n;
  10722. #endif
  10723. struct linger linger;
  10724. int error_code = 0;
  10725. socklen_t opt_len = sizeof(error_code);
  10726. if (!conn) {
  10727. return;
  10728. }
  10729. /* Set linger option to avoid socket hanging out after close. This
  10730. * prevent ephemeral port exhaust problem under high QPS. */
  10731. linger.l_onoff = 1;
  10732. linger.l_linger = 1;
  10733. if (getsockopt(conn->client.sock,
  10734. SOL_SOCKET,
  10735. SO_ERROR,
  10736. (char *)&error_code,
  10737. &opt_len) != 0) {
  10738. /* Cannot determine if socket is already closed. This should
  10739. * not occur and never did in a test. Log an error message
  10740. * and continue. */
  10741. mg_cry(conn,
  10742. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  10743. __func__,
  10744. strerror(ERRNO));
  10745. } else if (error_code == ECONNRESET) {
  10746. /* Socket already closed by client/peer, close socket without linger */
  10747. } else {
  10748. if (setsockopt(conn->client.sock,
  10749. SOL_SOCKET,
  10750. SO_LINGER,
  10751. (char *)&linger,
  10752. sizeof(linger)) != 0) {
  10753. mg_cry(conn,
  10754. "%s: setsockopt(SOL_SOCKET SO_LINGER) failed: %s",
  10755. __func__,
  10756. strerror(ERRNO));
  10757. }
  10758. }
  10759. /* Send FIN to the client */
  10760. shutdown(conn->client.sock, SHUTDOWN_WR);
  10761. set_non_blocking_mode(conn->client.sock);
  10762. #if defined(_WIN32)
  10763. /* Read and discard pending incoming data. If we do not do that and
  10764. * close
  10765. * the socket, the data in the send buffer may be discarded. This
  10766. * behaviour is seen on Windows, when client keeps sending data
  10767. * when server decides to close the connection; then when client
  10768. * does recv() it gets no data back. */
  10769. do {
  10770. n = pull(
  10771. NULL, conn, buf, sizeof(buf), 1E-10 /* TODO: allow 0 as timeout */);
  10772. } while (n > 0);
  10773. #endif
  10774. /* Now we know that our FIN is ACK-ed, safe to close */
  10775. closesocket(conn->client.sock);
  10776. conn->client.sock = INVALID_SOCKET;
  10777. }
  10778. static void
  10779. close_connection(struct mg_connection *conn)
  10780. {
  10781. if (!conn || !conn->ctx) {
  10782. return;
  10783. }
  10784. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  10785. if (conn->lua_websocket_state) {
  10786. lua_websocket_close(conn, conn->lua_websocket_state);
  10787. conn->lua_websocket_state = NULL;
  10788. }
  10789. #endif
  10790. /* call the connection_close callback if assigned */
  10791. if ((conn->ctx->callbacks.connection_close != NULL)
  10792. && (conn->ctx->context_type == 1)) {
  10793. conn->ctx->callbacks.connection_close(conn);
  10794. }
  10795. mg_lock_connection(conn);
  10796. conn->must_close = 1;
  10797. #ifndef NO_SSL
  10798. if (conn->ssl != NULL) {
  10799. /* Run SSL_shutdown twice to ensure completly close SSL connection
  10800. */
  10801. SSL_shutdown(conn->ssl);
  10802. SSL_free(conn->ssl);
  10803. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  10804. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  10805. ERR_remove_state(0);
  10806. conn->ssl = NULL;
  10807. }
  10808. #endif
  10809. if (conn->client.sock != INVALID_SOCKET) {
  10810. close_socket_gracefully(conn);
  10811. conn->client.sock = INVALID_SOCKET;
  10812. }
  10813. mg_unlock_connection(conn);
  10814. }
  10815. void
  10816. mg_close_connection(struct mg_connection *conn)
  10817. {
  10818. struct mg_context *client_ctx = NULL;
  10819. if (conn == NULL) {
  10820. return;
  10821. }
  10822. #if defined(USE_WEBSOCKET)
  10823. if (conn->ctx->context_type == 2) {
  10824. unsigned int i;
  10825. /* ws/wss client */
  10826. client_ctx = conn->ctx;
  10827. /* client context: loops must end */
  10828. conn->ctx->stop_flag = 1;
  10829. /* We need to get the client thread out of the select/recv call here. */
  10830. /* Since we use a sleep quantum of some seconds to check for recv
  10831. * timeouts, we will just wait a few seconds in mg_join_thread. */
  10832. /* join worker thread */
  10833. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  10834. if (client_ctx->workerthreadids[i] != 0) {
  10835. mg_join_thread(client_ctx->workerthreadids[i]);
  10836. }
  10837. }
  10838. }
  10839. #else
  10840. (void)client_ctx;
  10841. #endif
  10842. close_connection(conn);
  10843. #ifndef NO_SSL
  10844. if (conn->client_ssl_ctx != NULL) {
  10845. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  10846. }
  10847. #endif
  10848. if (client_ctx != NULL) {
  10849. /* free context */
  10850. mg_free(client_ctx->workerthreadids);
  10851. mg_free(client_ctx);
  10852. (void)pthread_mutex_destroy(&conn->mutex);
  10853. mg_free(conn);
  10854. }
  10855. }
  10856. static struct mg_connection *
  10857. mg_connect_client_impl(const struct mg_client_options *client_options,
  10858. int use_ssl,
  10859. char *ebuf,
  10860. size_t ebuf_len)
  10861. {
  10862. static struct mg_context fake_ctx;
  10863. struct mg_connection *conn = NULL;
  10864. SOCKET sock;
  10865. union usa sa;
  10866. if (!connect_socket(&fake_ctx,
  10867. client_options->host,
  10868. client_options->port,
  10869. use_ssl,
  10870. ebuf,
  10871. ebuf_len,
  10872. &sock,
  10873. &sa)) {
  10874. ;
  10875. } else if ((conn = (struct mg_connection *)
  10876. mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) {
  10877. mg_snprintf(NULL,
  10878. NULL, /* No truncation check for ebuf */
  10879. ebuf,
  10880. ebuf_len,
  10881. "calloc(): %s",
  10882. strerror(ERRNO));
  10883. closesocket(sock);
  10884. #ifndef NO_SSL
  10885. } else if (use_ssl
  10886. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  10887. == NULL) {
  10888. mg_snprintf(NULL,
  10889. NULL, /* No truncation check for ebuf */
  10890. ebuf,
  10891. ebuf_len,
  10892. "SSL_CTX_new error");
  10893. closesocket(sock);
  10894. mg_free(conn);
  10895. conn = NULL;
  10896. #endif /* NO_SSL */
  10897. } else {
  10898. #ifdef USE_IPV6
  10899. socklen_t len = (sa.sa.sa_family == AF_INET)
  10900. ? sizeof(conn->client.rsa.sin)
  10901. : sizeof(conn->client.rsa.sin6);
  10902. struct sockaddr *psa =
  10903. (sa.sa.sa_family == AF_INET)
  10904. ? (struct sockaddr *)&(conn->client.rsa.sin)
  10905. : (struct sockaddr *)&(conn->client.rsa.sin6);
  10906. #else
  10907. socklen_t len = sizeof(conn->client.rsa.sin);
  10908. struct sockaddr *psa = (struct sockaddr *)&(conn->client.rsa.sin);
  10909. #endif
  10910. conn->buf_size = MAX_REQUEST_SIZE;
  10911. conn->buf = (char *)(conn + 1);
  10912. conn->ctx = &fake_ctx;
  10913. conn->client.sock = sock;
  10914. conn->client.lsa = sa;
  10915. if (getsockname(sock, psa, &len) != 0) {
  10916. mg_cry(conn,
  10917. "%s: getsockname() failed: %s",
  10918. __func__,
  10919. strerror(ERRNO));
  10920. }
  10921. conn->client.is_ssl = use_ssl ? 1 : 0;
  10922. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  10923. #ifndef NO_SSL
  10924. if (use_ssl) {
  10925. fake_ctx.ssl_ctx = conn->client_ssl_ctx;
  10926. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  10927. * SSL_CTX_set_verify call is needed to switch off server
  10928. * certificate checking, which is off by default in OpenSSL and
  10929. * on in yaSSL. */
  10930. /* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  10931. * SSL_VERIFY_PEER, verify_ssl_server); */
  10932. if (client_options->client_cert) {
  10933. if (!ssl_use_pem_file(&fake_ctx, client_options->client_cert)) {
  10934. mg_snprintf(NULL,
  10935. NULL, /* No truncation check for ebuf */
  10936. ebuf,
  10937. ebuf_len,
  10938. "Can not use SSL client certificate");
  10939. SSL_CTX_free(conn->client_ssl_ctx);
  10940. closesocket(sock);
  10941. mg_free(conn);
  10942. conn = NULL;
  10943. }
  10944. }
  10945. if (client_options->server_cert) {
  10946. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  10947. client_options->server_cert,
  10948. NULL);
  10949. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  10950. } else {
  10951. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  10952. }
  10953. if (!sslize(conn,
  10954. conn->client_ssl_ctx,
  10955. SSL_connect,
  10956. &(conn->ctx->stop_flag))) {
  10957. mg_snprintf(NULL,
  10958. NULL, /* No truncation check for ebuf */
  10959. ebuf,
  10960. ebuf_len,
  10961. "SSL connection error");
  10962. SSL_CTX_free(conn->client_ssl_ctx);
  10963. closesocket(sock);
  10964. mg_free(conn);
  10965. conn = NULL;
  10966. }
  10967. }
  10968. #endif
  10969. }
  10970. return conn;
  10971. }
  10972. CIVETWEB_API struct mg_connection *
  10973. mg_connect_client_secure(const struct mg_client_options *client_options,
  10974. char *error_buffer,
  10975. size_t error_buffer_size)
  10976. {
  10977. return mg_connect_client_impl(client_options,
  10978. 1,
  10979. error_buffer,
  10980. error_buffer_size);
  10981. }
  10982. struct mg_connection *
  10983. mg_connect_client(const char *host,
  10984. int port,
  10985. int use_ssl,
  10986. char *error_buffer,
  10987. size_t error_buffer_size)
  10988. {
  10989. struct mg_client_options opts;
  10990. memset(&opts, 0, sizeof(opts));
  10991. opts.host = host;
  10992. opts.port = port;
  10993. return mg_connect_client_impl(&opts,
  10994. use_ssl,
  10995. error_buffer,
  10996. error_buffer_size);
  10997. }
  10998. static const struct {
  10999. const char *proto;
  11000. size_t proto_len;
  11001. unsigned default_port;
  11002. } abs_uri_protocols[] = {{"http://", 7, 80},
  11003. {"https://", 8, 443},
  11004. {"ws://", 5, 80},
  11005. {"wss://", 6, 443},
  11006. {NULL, 0, 0}};
  11007. /* Check if the uri is valid.
  11008. * return 0 for invalid uri,
  11009. * return 1 for *,
  11010. * return 2 for relative uri,
  11011. * return 3 for absolute uri without port,
  11012. * return 4 for absolute uri with port */
  11013. static int
  11014. get_uri_type(const char *uri)
  11015. {
  11016. int i;
  11017. char *hostend, *portbegin, *portend;
  11018. unsigned long port;
  11019. /* According to the HTTP standard
  11020. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  11021. * URI can be an asterisk (*) or should start with slash (relative uri),
  11022. * or it should start with the protocol (absolute uri). */
  11023. if (uri[0] == '*' && uri[1] == '\0') {
  11024. /* asterisk */
  11025. return 1;
  11026. }
  11027. /* Valid URIs according to RFC 3986
  11028. * (https://www.ietf.org/rfc/rfc3986.txt)
  11029. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  11030. * and unreserved characters A-Z a-z 0-9 and -._~
  11031. * and % encoded symbols.
  11032. */
  11033. for (i = 0; uri[i] != 0; i++) {
  11034. if (uri[i] < 33) {
  11035. /* control characters and spaces are invalid */
  11036. return 0;
  11037. }
  11038. if (uri[i] > 126) {
  11039. /* non-ascii characters must be % encoded */
  11040. return 0;
  11041. } else {
  11042. switch (uri[i]) {
  11043. case '"': /* 34 */
  11044. case '<': /* 60 */
  11045. case '>': /* 62 */
  11046. case '\\': /* 92 */
  11047. case '^': /* 94 */
  11048. case '`': /* 96 */
  11049. case '{': /* 123 */
  11050. case '|': /* 124 */
  11051. case '}': /* 125 */
  11052. return 0;
  11053. default:
  11054. /* character is ok */
  11055. break;
  11056. }
  11057. }
  11058. }
  11059. /* A relative uri starts with a / character */
  11060. if (uri[0] == '/') {
  11061. /* relative uri */
  11062. return 2;
  11063. }
  11064. /* It could be an absolute uri: */
  11065. /* This function only checks if the uri is valid, not if it is
  11066. * addressing the current server. So civetweb can also be used
  11067. * as a proxy server. */
  11068. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  11069. if (mg_strncasecmp(uri,
  11070. abs_uri_protocols[i].proto,
  11071. abs_uri_protocols[i].proto_len) == 0) {
  11072. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  11073. if (!hostend) {
  11074. return 0;
  11075. }
  11076. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  11077. if (!portbegin) {
  11078. return 3;
  11079. }
  11080. port = strtoul(portbegin + 1, &portend, 10);
  11081. if ((portend != hostend) || !port || !is_valid_port(port)) {
  11082. return 0;
  11083. }
  11084. return 4;
  11085. }
  11086. }
  11087. return 0;
  11088. }
  11089. /* Return NULL or the relative uri at the current server */
  11090. static const char *
  11091. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  11092. {
  11093. const char *server_domain;
  11094. size_t server_domain_len;
  11095. size_t request_domain_len = 0;
  11096. unsigned long port = 0;
  11097. int i;
  11098. const char *hostbegin = NULL;
  11099. const char *hostend = NULL;
  11100. const char *portbegin;
  11101. char *portend;
  11102. /* DNS is case insensitive, so use case insensitive string compare here
  11103. */
  11104. server_domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  11105. if (!server_domain) {
  11106. return 0;
  11107. }
  11108. server_domain_len = strlen(server_domain);
  11109. if (!server_domain_len) {
  11110. return 0;
  11111. }
  11112. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  11113. if (mg_strncasecmp(uri,
  11114. abs_uri_protocols[i].proto,
  11115. abs_uri_protocols[i].proto_len) == 0) {
  11116. hostbegin = uri + abs_uri_protocols[i].proto_len;
  11117. hostend = strchr(hostbegin, '/');
  11118. if (!hostend) {
  11119. return 0;
  11120. }
  11121. portbegin = strchr(hostbegin, ':');
  11122. if ((!portbegin) || (portbegin > hostend)) {
  11123. port = abs_uri_protocols[i].default_port;
  11124. request_domain_len = (size_t)(hostend - hostbegin);
  11125. } else {
  11126. port = strtoul(portbegin + 1, &portend, 10);
  11127. if ((portend != hostend) || !port || !is_valid_port(port)) {
  11128. return 0;
  11129. }
  11130. request_domain_len = (size_t)(portbegin - hostbegin);
  11131. }
  11132. /* protocol found, port set */
  11133. break;
  11134. }
  11135. }
  11136. if (!port) {
  11137. /* port remains 0 if the protocol is not found */
  11138. return 0;
  11139. }
  11140. /* Check if the request is directed to a different server. */
  11141. /* First check if the port is the same (IPv4 and IPv6). */
  11142. #if defined(USE_IPV6)
  11143. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  11144. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  11145. /* Request is directed to a different port */
  11146. return 0;
  11147. }
  11148. } else
  11149. #endif
  11150. {
  11151. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  11152. /* Request is directed to a different port */
  11153. return 0;
  11154. }
  11155. }
  11156. /* Finally check if the server corresponds to the authentication
  11157. * domain of the server (the server domain).
  11158. * Allow full matches (like http://mydomain.com/path/file.ext), and
  11159. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  11160. * but do not allow substrings (like http://notmydomain.com/path/file.ext
  11161. * or http://mydomain.com.fake/path/file.ext).
  11162. */
  11163. if ((request_domain_len == server_domain_len)
  11164. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  11165. /* Request is directed to this server - full name match. */
  11166. } else {
  11167. if (request_domain_len < (server_domain_len + 2)) {
  11168. /* Request is directed to another server: The server name is longer
  11169. * than
  11170. * the request name. Drop this case here to avoid overflows in the
  11171. * following checks. */
  11172. return 0;
  11173. }
  11174. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  11175. /* Request is directed to another server: It could be a substring
  11176. * like notmyserver.com */
  11177. return 0;
  11178. }
  11179. if (0 != memcmp(server_domain,
  11180. hostbegin + request_domain_len - server_domain_len,
  11181. server_domain_len)) {
  11182. /* Request is directed to another server:
  11183. * The server name is different. */
  11184. return 0;
  11185. }
  11186. }
  11187. return hostend;
  11188. }
  11189. static int
  11190. getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  11191. {
  11192. const char *cl;
  11193. if (ebuf_len > 0) {
  11194. ebuf[0] = '\0';
  11195. }
  11196. *err = 0;
  11197. reset_per_request_attributes(conn);
  11198. if (!conn) {
  11199. mg_snprintf(conn,
  11200. NULL, /* No truncation check for ebuf */
  11201. ebuf,
  11202. ebuf_len,
  11203. "%s",
  11204. "Internal error");
  11205. *err = 500;
  11206. return 0;
  11207. }
  11208. /* Set the time the request was received. This value should be used for
  11209. * timeouts. */
  11210. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  11211. conn->request_len =
  11212. read_request(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  11213. /* assert(conn->request_len < 0 || conn->data_len >= conn->request_len);
  11214. */
  11215. if (conn->request_len >= 0 && conn->data_len < conn->request_len) {
  11216. mg_snprintf(conn,
  11217. NULL, /* No truncation check for ebuf */
  11218. ebuf,
  11219. ebuf_len,
  11220. "%s",
  11221. "Invalid request size");
  11222. *err = 500;
  11223. return 0;
  11224. }
  11225. if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
  11226. mg_snprintf(conn,
  11227. NULL, /* No truncation check for ebuf */
  11228. ebuf,
  11229. ebuf_len,
  11230. "%s",
  11231. "Request Too Large");
  11232. *err = 413;
  11233. return 0;
  11234. } else if (conn->request_len <= 0) {
  11235. if (conn->data_len > 0) {
  11236. mg_snprintf(conn,
  11237. NULL, /* No truncation check for ebuf */
  11238. ebuf,
  11239. ebuf_len,
  11240. "%s",
  11241. "Client sent malformed request");
  11242. *err = 400;
  11243. } else {
  11244. /* Server did not recv anything -> just close the connection */
  11245. conn->must_close = 1;
  11246. mg_snprintf(conn,
  11247. NULL, /* No truncation check for ebuf */
  11248. ebuf,
  11249. ebuf_len,
  11250. "%s",
  11251. "Client did not send a request");
  11252. *err = 0;
  11253. }
  11254. return 0;
  11255. } else if (parse_http_message(conn->buf,
  11256. conn->buf_size,
  11257. &conn->request_info) <= 0) {
  11258. mg_snprintf(conn,
  11259. NULL, /* No truncation check for ebuf */
  11260. ebuf,
  11261. ebuf_len,
  11262. "%s",
  11263. "Bad Request");
  11264. *err = 400;
  11265. return 0;
  11266. } else {
  11267. /* Message is a valid request or response */
  11268. if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) {
  11269. /* Request/response has content length set */
  11270. char *endptr = NULL;
  11271. conn->content_len = strtoll(cl, &endptr, 10);
  11272. if (endptr == cl) {
  11273. mg_snprintf(conn,
  11274. NULL, /* No truncation check for ebuf */
  11275. ebuf,
  11276. ebuf_len,
  11277. "%s",
  11278. "Bad Request");
  11279. *err = 411;
  11280. return 0;
  11281. }
  11282. /* Publish the content length back to the request info. */
  11283. conn->request_info.content_length = conn->content_len;
  11284. } else if ((cl = get_header(&conn->request_info, "Transfer-Encoding"))
  11285. != NULL
  11286. && !mg_strcasecmp(cl, "chunked")) {
  11287. conn->is_chunked = 1;
  11288. } else if (!mg_strcasecmp(conn->request_info.request_method, "POST")
  11289. || !mg_strcasecmp(conn->request_info.request_method,
  11290. "PUT")) {
  11291. /* POST or PUT request without content length set */
  11292. conn->content_len = -1;
  11293. } else if (!mg_strncasecmp(conn->request_info.request_method,
  11294. "HTTP/",
  11295. 5)) {
  11296. /* Response without content length set */
  11297. conn->content_len = -1;
  11298. } else {
  11299. /* Other request */
  11300. conn->content_len = 0;
  11301. }
  11302. }
  11303. return 1;
  11304. }
  11305. int
  11306. mg_get_response(struct mg_connection *conn,
  11307. char *ebuf,
  11308. size_t ebuf_len,
  11309. int timeout)
  11310. {
  11311. if (conn) {
  11312. /* Implementation of API function for HTTP clients */
  11313. int err, ret;
  11314. struct mg_context *octx = conn->ctx;
  11315. struct mg_context rctx = *(conn->ctx);
  11316. char txt[32]; /* will not overflow */
  11317. if (timeout >= 0) {
  11318. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  11319. rctx.config[REQUEST_TIMEOUT] = txt;
  11320. set_sock_timeout(conn->client.sock, timeout);
  11321. } else {
  11322. rctx.config[REQUEST_TIMEOUT] = NULL;
  11323. }
  11324. conn->ctx = &rctx;
  11325. ret = getreq(conn, ebuf, ebuf_len, &err);
  11326. conn->ctx = octx;
  11327. /* TODO: 1) uri is deprecated;
  11328. * 2) here, ri.uri is the http response code */
  11329. conn->request_info.uri = conn->request_info.request_uri;
  11330. /* TODO (mid): Define proper return values - maybe return length?
  11331. * For the first test use <0 for error and >0 for OK */
  11332. return (ret == 0) ? -1 : +1;
  11333. }
  11334. return -1;
  11335. }
  11336. struct mg_connection *
  11337. mg_download(const char *host,
  11338. int port,
  11339. int use_ssl,
  11340. char *ebuf,
  11341. size_t ebuf_len,
  11342. const char *fmt,
  11343. ...)
  11344. {
  11345. struct mg_connection *conn;
  11346. va_list ap;
  11347. int i;
  11348. int reqerr;
  11349. va_start(ap, fmt);
  11350. ebuf[0] = '\0';
  11351. /* open a connection */
  11352. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  11353. if (conn != NULL) {
  11354. i = mg_vprintf(conn, fmt, ap);
  11355. if (i <= 0) {
  11356. mg_snprintf(conn,
  11357. NULL, /* No truncation check for ebuf */
  11358. ebuf,
  11359. ebuf_len,
  11360. "%s",
  11361. "Error sending request");
  11362. } else {
  11363. getreq(conn, ebuf, ebuf_len, &reqerr);
  11364. /* TODO: 1) uri is deprecated;
  11365. * 2) here, ri.uri is the http response code */
  11366. conn->request_info.uri = conn->request_info.request_uri;
  11367. }
  11368. }
  11369. /* if an error occured, close the connection */
  11370. if (ebuf[0] != '\0' && conn != NULL) {
  11371. mg_close_connection(conn);
  11372. conn = NULL;
  11373. }
  11374. va_end(ap);
  11375. return conn;
  11376. }
  11377. struct websocket_client_thread_data {
  11378. struct mg_connection *conn;
  11379. mg_websocket_data_handler data_handler;
  11380. mg_websocket_close_handler close_handler;
  11381. void *callback_data;
  11382. };
  11383. #if defined(USE_WEBSOCKET)
  11384. #ifdef _WIN32
  11385. static unsigned __stdcall websocket_client_thread(void *data)
  11386. #else
  11387. static void *
  11388. websocket_client_thread(void *data)
  11389. #endif
  11390. {
  11391. struct websocket_client_thread_data *cdata =
  11392. (struct websocket_client_thread_data *)data;
  11393. mg_set_thread_name("ws-clnt");
  11394. if (cdata->conn->ctx) {
  11395. if (cdata->conn->ctx->callbacks.init_thread) {
  11396. /* 3 indicates a websocket client thread */
  11397. /* TODO: check if conn->ctx can be set */
  11398. cdata->conn->ctx->callbacks.init_thread(cdata->conn->ctx, 3);
  11399. }
  11400. }
  11401. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  11402. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  11403. if (cdata->close_handler != NULL) {
  11404. cdata->close_handler(cdata->conn, cdata->callback_data);
  11405. }
  11406. /* The websocket_client context has only this thread. If it runs out,
  11407. set the stop_flag to 2 (= "stopped"). */
  11408. cdata->conn->ctx->stop_flag = 2;
  11409. mg_free((void *)cdata);
  11410. #ifdef _WIN32
  11411. return 0;
  11412. #else
  11413. return NULL;
  11414. #endif
  11415. }
  11416. #endif
  11417. struct mg_connection *
  11418. mg_connect_websocket_client(const char *host,
  11419. int port,
  11420. int use_ssl,
  11421. char *error_buffer,
  11422. size_t error_buffer_size,
  11423. const char *path,
  11424. const char *origin,
  11425. mg_websocket_data_handler data_func,
  11426. mg_websocket_close_handler close_func,
  11427. void *user_data)
  11428. {
  11429. struct mg_connection *conn = NULL;
  11430. #if defined(USE_WEBSOCKET)
  11431. struct mg_context *newctx = NULL;
  11432. struct websocket_client_thread_data *thread_data;
  11433. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  11434. static const char *handshake_req;
  11435. if (origin != NULL) {
  11436. handshake_req = "GET %s HTTP/1.1\r\n"
  11437. "Host: %s\r\n"
  11438. "Upgrade: websocket\r\n"
  11439. "Connection: Upgrade\r\n"
  11440. "Sec-WebSocket-Key: %s\r\n"
  11441. "Sec-WebSocket-Version: 13\r\n"
  11442. "Origin: %s\r\n"
  11443. "\r\n";
  11444. } else {
  11445. handshake_req = "GET %s HTTP/1.1\r\n"
  11446. "Host: %s\r\n"
  11447. "Upgrade: websocket\r\n"
  11448. "Connection: Upgrade\r\n"
  11449. "Sec-WebSocket-Key: %s\r\n"
  11450. "Sec-WebSocket-Version: 13\r\n"
  11451. "\r\n";
  11452. }
  11453. /* Establish the client connection and request upgrade */
  11454. conn = mg_download(host,
  11455. port,
  11456. use_ssl,
  11457. error_buffer,
  11458. error_buffer_size,
  11459. handshake_req,
  11460. path,
  11461. host,
  11462. magic,
  11463. origin);
  11464. /* Connection object will be null if something goes wrong */
  11465. if (conn == NULL || (strcmp(conn->request_info.request_uri, "101") != 0)) {
  11466. if (!*error_buffer) {
  11467. /* if there is a connection, but it did not return 101,
  11468. * error_buffer is not yet set */
  11469. mg_snprintf(conn,
  11470. NULL, /* No truncation check for ebuf */
  11471. error_buffer,
  11472. error_buffer_size,
  11473. "Unexpected server reply");
  11474. }
  11475. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  11476. if (conn != NULL) {
  11477. mg_free(conn);
  11478. conn = NULL;
  11479. }
  11480. return conn;
  11481. }
  11482. /* For client connections, mg_context is fake. Since we need to set a
  11483. * callback function, we need to create a copy and modify it. */
  11484. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  11485. memcpy(newctx, conn->ctx, sizeof(struct mg_context));
  11486. newctx->user_data = user_data;
  11487. newctx->context_type = 2; /* ws/wss client context type */
  11488. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  11489. newctx->workerthreadids =
  11490. (pthread_t *)mg_calloc(newctx->cfg_worker_threads, sizeof(pthread_t));
  11491. conn->ctx = newctx;
  11492. thread_data = (struct websocket_client_thread_data *)
  11493. mg_calloc(sizeof(struct websocket_client_thread_data), 1);
  11494. thread_data->conn = conn;
  11495. thread_data->data_handler = data_func;
  11496. thread_data->close_handler = close_func;
  11497. thread_data->callback_data = NULL;
  11498. /* Start a thread to read the websocket client connection
  11499. * This thread will automatically stop when mg_disconnect is
  11500. * called on the client connection */
  11501. if (mg_start_thread_with_id(websocket_client_thread,
  11502. (void *)thread_data,
  11503. newctx->workerthreadids) != 0) {
  11504. mg_free((void *)thread_data);
  11505. mg_free((void *)newctx->workerthreadids);
  11506. mg_free((void *)newctx);
  11507. mg_free((void *)conn);
  11508. conn = NULL;
  11509. DEBUG_TRACE("%s",
  11510. "Websocket client connect thread could not be started\r\n");
  11511. }
  11512. #else
  11513. /* Appease "unused parameter" warnings */
  11514. (void)host;
  11515. (void)port;
  11516. (void)use_ssl;
  11517. (void)error_buffer;
  11518. (void)error_buffer_size;
  11519. (void)path;
  11520. (void)origin;
  11521. (void)user_data;
  11522. (void)data_func;
  11523. (void)close_func;
  11524. #endif
  11525. return conn;
  11526. }
  11527. static void
  11528. process_new_connection(struct mg_connection *conn)
  11529. {
  11530. if (conn && conn->ctx) {
  11531. struct mg_request_info *ri = &conn->request_info;
  11532. int keep_alive_enabled, keep_alive, discard_len;
  11533. char ebuf[100];
  11534. const char *hostend;
  11535. int reqerr, uri_type;
  11536. keep_alive_enabled =
  11537. !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  11538. /* Important: on new connection, reset the receiving buffer. Credit
  11539. * goes to crule42. */
  11540. conn->data_len = 0;
  11541. do {
  11542. DEBUG_TRACE("calling getreq (%i times for this connection)",
  11543. 0); /* TODO */
  11544. if (!getreq(conn, ebuf, sizeof(ebuf), &reqerr)) {
  11545. /* The request sent by the client could not be understood by
  11546. * the server, or it was incomplete or a timeout. Send an
  11547. * error message and close the connection. */
  11548. if (reqerr > 0) {
  11549. /*assert(ebuf[0] != '\0');*/
  11550. send_http_error(conn, reqerr, "%s", ebuf);
  11551. }
  11552. } else if (strcmp(ri->http_version, "1.0")
  11553. && strcmp(ri->http_version, "1.1")) {
  11554. mg_snprintf(conn,
  11555. NULL, /* No truncation check for ebuf */
  11556. ebuf,
  11557. sizeof(ebuf),
  11558. "Bad HTTP version: [%s]",
  11559. ri->http_version);
  11560. send_http_error(conn, 505, "%s", ebuf);
  11561. }
  11562. if (ebuf[0] == '\0') {
  11563. uri_type = get_uri_type(conn->request_info.request_uri);
  11564. switch (uri_type) {
  11565. case 1:
  11566. /* Asterisk */
  11567. conn->request_info.local_uri = NULL;
  11568. break;
  11569. case 2:
  11570. /* relative uri */
  11571. conn->request_info.local_uri =
  11572. conn->request_info.request_uri;
  11573. break;
  11574. case 3:
  11575. case 4:
  11576. /* absolute uri (with/without port) */
  11577. hostend = get_rel_url_at_current_server(
  11578. conn->request_info.request_uri, conn);
  11579. if (hostend) {
  11580. conn->request_info.local_uri = hostend;
  11581. } else {
  11582. conn->request_info.local_uri = NULL;
  11583. }
  11584. break;
  11585. default:
  11586. mg_snprintf(conn,
  11587. NULL, /* No truncation check for ebuf */
  11588. ebuf,
  11589. sizeof(ebuf),
  11590. "Invalid URI");
  11591. send_http_error(conn, 400, "%s", ebuf);
  11592. conn->request_info.local_uri = NULL;
  11593. break;
  11594. }
  11595. /* TODO: cleanup uri, local_uri and request_uri */
  11596. conn->request_info.uri = conn->request_info.local_uri;
  11597. }
  11598. DEBUG_TRACE("http: %s, error: %s",
  11599. (ri->http_version ? ri->http_version : "none"),
  11600. (ebuf[0] ? ebuf : "none"));
  11601. if (ebuf[0] == '\0') {
  11602. if (conn->request_info.local_uri) {
  11603. /* handle request to local server */
  11604. handle_request(conn);
  11605. DEBUG_TRACE("%s", "handle_request done");
  11606. if (conn->ctx->callbacks.end_request != NULL) {
  11607. conn->ctx->callbacks.end_request(conn,
  11608. conn->status_code);
  11609. DEBUG_TRACE("%s", "end_request callback done");
  11610. }
  11611. log_access(conn);
  11612. } else {
  11613. /* TODO: handle non-local request (PROXY) */
  11614. conn->must_close = 1;
  11615. }
  11616. } else {
  11617. conn->must_close = 1;
  11618. }
  11619. if (ri->remote_user != NULL) {
  11620. mg_free((void *)ri->remote_user);
  11621. /* Important! When having connections with and without auth
  11622. * would cause double free and then crash */
  11623. ri->remote_user = NULL;
  11624. }
  11625. /* NOTE(lsm): order is important here. should_keep_alive() call
  11626. * is
  11627. * using parsed request, which will be invalid after memmove's
  11628. * below.
  11629. * Therefore, memorize should_keep_alive() result now for later
  11630. * use
  11631. * in loop exit condition. */
  11632. keep_alive = (conn->ctx->stop_flag == 0) && keep_alive_enabled
  11633. && (conn->content_len >= 0) && should_keep_alive(conn);
  11634. /* Discard all buffered data for this request */
  11635. discard_len = ((conn->content_len >= 0) && (conn->request_len > 0)
  11636. && ((conn->request_len + conn->content_len)
  11637. < (int64_t)conn->data_len))
  11638. ? (int)(conn->request_len + conn->content_len)
  11639. : conn->data_len;
  11640. /*assert(discard_len >= 0);*/
  11641. if (discard_len < 0) {
  11642. DEBUG_TRACE("internal error: discard_len = %li",
  11643. (long int)discard_len);
  11644. break;
  11645. }
  11646. conn->data_len -= discard_len;
  11647. if (conn->data_len > 0) {
  11648. DEBUG_TRACE("discard_len = %lu", (long unsigned)discard_len);
  11649. memmove(conn->buf,
  11650. conn->buf + discard_len,
  11651. (size_t)conn->data_len);
  11652. }
  11653. /* assert(conn->data_len >= 0); */
  11654. /* assert(conn->data_len <= conn->buf_size); */
  11655. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  11656. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  11657. (long int)conn->data_len,
  11658. (long int)conn->buf_size);
  11659. break;
  11660. }
  11661. } while (keep_alive);
  11662. }
  11663. }
  11664. #if defined(ALTERNATIVE_QUEUE)
  11665. static void
  11666. produce_socket(struct mg_context *ctx, const struct socket *sp)
  11667. {
  11668. unsigned int i;
  11669. for (;;) {
  11670. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  11671. /* find a free worker slot and signal it */
  11672. if (ctx->client_socks[i].in_use == 0) {
  11673. ctx->client_socks[i] = *sp;
  11674. ctx->client_socks[i].in_use = 1;
  11675. event_signal(ctx->client_wait_events[i]);
  11676. return;
  11677. }
  11678. }
  11679. /* queue is full */
  11680. mg_sleep(1);
  11681. }
  11682. }
  11683. static int
  11684. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  11685. {
  11686. DEBUG_TRACE("%s", "going idle");
  11687. ctx->client_socks[thread_index].in_use = 0;
  11688. event_wait(ctx->client_wait_events[thread_index]);
  11689. *sp = ctx->client_socks[thread_index];
  11690. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  11691. return !ctx->stop_flag;
  11692. }
  11693. #else /* ALTERNATIVE_QUEUE */
  11694. /* Worker threads take accepted socket from the queue */
  11695. static int
  11696. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  11697. {
  11698. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  11699. (void)thread_index;
  11700. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11701. DEBUG_TRACE("%s", "going idle");
  11702. /* If the queue is empty, wait. We're idle at this point. */
  11703. while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
  11704. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  11705. }
  11706. /* If we're stopping, sq_head may be equal to sq_tail. */
  11707. if (ctx->sq_head > ctx->sq_tail) {
  11708. /* Copy socket from the queue and increment tail */
  11709. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  11710. ctx->sq_tail++;
  11711. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  11712. /* Wrap pointers if needed */
  11713. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  11714. ctx->sq_tail -= QUEUE_SIZE(ctx);
  11715. ctx->sq_head -= QUEUE_SIZE(ctx);
  11716. }
  11717. }
  11718. (void)pthread_cond_signal(&ctx->sq_empty);
  11719. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11720. return !ctx->stop_flag;
  11721. #undef QUEUE_SIZE
  11722. }
  11723. /* Master thread adds accepted socket to a queue */
  11724. static void
  11725. produce_socket(struct mg_context *ctx, const struct socket *sp)
  11726. {
  11727. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  11728. if (!ctx) {
  11729. return;
  11730. }
  11731. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11732. /* If the queue is full, wait */
  11733. while (ctx->stop_flag == 0
  11734. && ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx)) {
  11735. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  11736. }
  11737. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  11738. /* Copy socket to the queue and increment head */
  11739. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  11740. ctx->sq_head++;
  11741. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  11742. }
  11743. (void)pthread_cond_signal(&ctx->sq_full);
  11744. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11745. #undef QUEUE_SIZE
  11746. }
  11747. #endif /* ALTERNATIVE_QUEUE */
  11748. struct worker_thread_args {
  11749. struct mg_context *ctx;
  11750. int index;
  11751. };
  11752. static void *
  11753. worker_thread_run(struct worker_thread_args *thread_args)
  11754. {
  11755. struct mg_context *ctx = thread_args->ctx;
  11756. struct mg_connection *conn;
  11757. struct mg_workerTLS tls;
  11758. #if defined(MG_LEGACY_INTERFACE)
  11759. uint32_t addr;
  11760. #endif
  11761. mg_set_thread_name("worker");
  11762. tls.is_master = 0;
  11763. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  11764. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11765. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  11766. #endif
  11767. if (ctx->callbacks.init_thread) {
  11768. /* call init_thread for a worker thread (type 1) */
  11769. ctx->callbacks.init_thread(ctx, 1);
  11770. }
  11771. conn =
  11772. (struct mg_connection *)mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE);
  11773. if (conn == NULL) {
  11774. mg_cry(fc(ctx), "%s", "Cannot create new connection struct, OOM");
  11775. } else {
  11776. pthread_setspecific(sTlsKey, &tls);
  11777. conn->buf_size = MAX_REQUEST_SIZE;
  11778. conn->buf = (char *)(conn + 1);
  11779. conn->ctx = ctx;
  11780. conn->thread_index = thread_args->index;
  11781. conn->request_info.user_data = ctx->user_data;
  11782. /* Allocate a mutex for this connection to allow communication both
  11783. * within the request handler and from elsewhere in the application
  11784. */
  11785. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  11786. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  11787. * signal sq_empty condvar to wake up the master waiting in
  11788. * produce_socket() */
  11789. while (consume_socket(ctx, &conn->client, conn->thread_index)) {
  11790. conn->conn_birth_time = time(NULL);
  11791. /* Fill in IP, port info early so even if SSL setup below fails,
  11792. * error handler would have the corresponding info.
  11793. * Thanks to Johannes Winkelmann for the patch.
  11794. */
  11795. #if defined(USE_IPV6)
  11796. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  11797. conn->request_info.remote_port =
  11798. ntohs(conn->client.rsa.sin6.sin6_port);
  11799. } else
  11800. #endif
  11801. {
  11802. conn->request_info.remote_port =
  11803. ntohs(conn->client.rsa.sin.sin_port);
  11804. }
  11805. sockaddr_to_string(conn->request_info.remote_addr,
  11806. sizeof(conn->request_info.remote_addr),
  11807. &conn->client.rsa);
  11808. DEBUG_TRACE("Start processing connection from %s",
  11809. conn->request_info.remote_addr);
  11810. #if defined(MG_LEGACY_INTERFACE)
  11811. /* This legacy interface only works for the IPv4 case */
  11812. addr = ntohl(conn->client.rsa.sin.sin_addr.s_addr);
  11813. memcpy(&conn->request_info.remote_ip, &addr, 4);
  11814. #endif
  11815. conn->request_info.is_ssl = conn->client.is_ssl;
  11816. if (conn->client.is_ssl) {
  11817. #ifndef NO_SSL
  11818. /* HTTPS connection */
  11819. if (sslize(conn,
  11820. conn->ctx->ssl_ctx,
  11821. SSL_accept,
  11822. &(conn->ctx->stop_flag))) {
  11823. /* Get SSL client certificate information (if set) */
  11824. ssl_get_client_cert_info(conn);
  11825. /* process HTTPS connection */
  11826. process_new_connection(conn);
  11827. /* Free client certificate info */
  11828. if (conn->request_info.client_cert) {
  11829. mg_free(
  11830. (void *)(conn->request_info.client_cert->subject));
  11831. mg_free(
  11832. (void *)(conn->request_info.client_cert->issuer));
  11833. mg_free(
  11834. (void *)(conn->request_info.client_cert->serial));
  11835. mg_free(
  11836. (void *)(conn->request_info.client_cert->finger));
  11837. conn->request_info.client_cert->subject = 0;
  11838. conn->request_info.client_cert->issuer = 0;
  11839. conn->request_info.client_cert->serial = 0;
  11840. conn->request_info.client_cert->finger = 0;
  11841. mg_free(conn->request_info.client_cert);
  11842. conn->request_info.client_cert = 0;
  11843. }
  11844. }
  11845. #endif
  11846. } else {
  11847. /* process HTTP connection */
  11848. process_new_connection(conn);
  11849. }
  11850. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  11851. conn->request_info.remote_addr,
  11852. difftime(time(NULL), conn->conn_birth_time));
  11853. close_connection(conn);
  11854. DEBUG_TRACE("%s", "Connection closed");
  11855. }
  11856. }
  11857. pthread_setspecific(sTlsKey, NULL);
  11858. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11859. CloseHandle(tls.pthread_cond_helper_mutex);
  11860. #endif
  11861. pthread_mutex_destroy(&conn->mutex);
  11862. mg_free(conn);
  11863. DEBUG_TRACE("%s", "exiting");
  11864. return NULL;
  11865. }
  11866. /* Threads have different return types on Windows and Unix. */
  11867. #ifdef _WIN32
  11868. static unsigned __stdcall worker_thread(void *thread_func_param)
  11869. {
  11870. struct worker_thread_args *pwta =
  11871. (struct worker_thread_args *)thread_func_param;
  11872. worker_thread_run(pwta);
  11873. mg_free(thread_func_param);
  11874. return 0;
  11875. }
  11876. #else
  11877. static void *
  11878. worker_thread(void *thread_func_param)
  11879. {
  11880. struct worker_thread_args *pwta =
  11881. (struct worker_thread_args *)thread_func_param;
  11882. worker_thread_run(pwta);
  11883. mg_free(thread_func_param);
  11884. return NULL;
  11885. }
  11886. #endif /* _WIN32 */
  11887. static void
  11888. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  11889. {
  11890. struct socket so;
  11891. char src_addr[IP_ADDR_STR_LEN];
  11892. socklen_t len = sizeof(so.rsa);
  11893. int on = 1;
  11894. int timeout;
  11895. if (!listener) {
  11896. return;
  11897. }
  11898. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  11899. == INVALID_SOCKET) {
  11900. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  11901. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  11902. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  11903. closesocket(so.sock);
  11904. so.sock = INVALID_SOCKET;
  11905. } else {
  11906. /* Put so socket structure into the queue */
  11907. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  11908. set_close_on_exec(so.sock, fc(ctx));
  11909. so.is_ssl = listener->is_ssl;
  11910. so.ssl_redir = listener->ssl_redir;
  11911. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  11912. mg_cry(fc(ctx),
  11913. "%s: getsockname() failed: %s",
  11914. __func__,
  11915. strerror(ERRNO));
  11916. }
  11917. /* Set TCP keep-alive. This is needed because if HTTP-level
  11918. * keep-alive
  11919. * is enabled, and client resets the connection, server won't get
  11920. * TCP FIN or RST and will keep the connection open forever. With
  11921. * TCP keep-alive, next keep-alive handshake will figure out that
  11922. * the client is down and will close the server end.
  11923. * Thanks to Igor Klopov who suggested the patch. */
  11924. if (setsockopt(so.sock,
  11925. SOL_SOCKET,
  11926. SO_KEEPALIVE,
  11927. (SOCK_OPT_TYPE)&on,
  11928. sizeof(on)) != 0) {
  11929. mg_cry(fc(ctx),
  11930. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  11931. __func__,
  11932. strerror(ERRNO));
  11933. }
  11934. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  11935. * to effectively fill up the underlying IP packet payload and
  11936. * reduce the overhead of sending lots of small buffers. However
  11937. * this hurts the server's throughput (ie. operations per second)
  11938. * when HTTP 1.1 persistent connections are used and the responses
  11939. * are relatively small (eg. less than 1400 bytes).
  11940. */
  11941. if ((ctx != NULL) && (ctx->config[CONFIG_TCP_NODELAY] != NULL)
  11942. && (!strcmp(ctx->config[CONFIG_TCP_NODELAY], "1"))) {
  11943. if (set_tcp_nodelay(so.sock, 1) != 0) {
  11944. mg_cry(fc(ctx),
  11945. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  11946. __func__,
  11947. strerror(ERRNO));
  11948. }
  11949. }
  11950. if (ctx && ctx->config[REQUEST_TIMEOUT]) {
  11951. timeout = atoi(ctx->config[REQUEST_TIMEOUT]);
  11952. } else {
  11953. timeout = -1;
  11954. }
  11955. /* TODO: if non blocking sockets are used, timeouts are implemented
  11956. * differently */
  11957. // if (timeout > 0) {
  11958. // set_sock_timeout(so.sock, timeout);
  11959. //}
  11960. (void)timeout;
  11961. set_non_blocking_mode(so.sock);
  11962. produce_socket(ctx, &so);
  11963. }
  11964. }
  11965. static void
  11966. master_thread_run(void *thread_func_param)
  11967. {
  11968. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  11969. struct mg_workerTLS tls;
  11970. struct pollfd *pfd;
  11971. unsigned int i;
  11972. unsigned int workerthreadcount;
  11973. if (!ctx) {
  11974. return;
  11975. }
  11976. mg_set_thread_name("master");
  11977. /* Increase priority of the master thread */
  11978. #if defined(_WIN32)
  11979. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  11980. #elif defined(USE_MASTER_THREAD_PRIORITY)
  11981. int min_prio = sched_get_priority_min(SCHED_RR);
  11982. int max_prio = sched_get_priority_max(SCHED_RR);
  11983. if ((min_prio >= 0) && (max_prio >= 0)
  11984. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  11985. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  11986. struct sched_param sched_param = {0};
  11987. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  11988. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  11989. }
  11990. #endif
  11991. /* Initialize thread local storage */
  11992. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11993. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  11994. #endif
  11995. tls.is_master = 1;
  11996. pthread_setspecific(sTlsKey, &tls);
  11997. if (ctx->callbacks.init_thread) {
  11998. /* Callback for the master thread (type 0) */
  11999. ctx->callbacks.init_thread(ctx, 0);
  12000. }
  12001. /* Server starts *now* */
  12002. ctx->start_time = time(NULL);
  12003. /* Start the server */
  12004. pfd = ctx->listening_socket_fds;
  12005. while (ctx->stop_flag == 0) {
  12006. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12007. pfd[i].fd = ctx->listening_sockets[i].sock;
  12008. pfd[i].events = POLLIN;
  12009. }
  12010. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  12011. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12012. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  12013. * successful poll, and POLLIN is defined as
  12014. * (POLLRDNORM | POLLRDBAND)
  12015. * Therefore, we're checking pfd[i].revents & POLLIN, not
  12016. * pfd[i].revents == POLLIN. */
  12017. if (ctx->stop_flag == 0 && (pfd[i].revents & POLLIN)) {
  12018. accept_new_connection(&ctx->listening_sockets[i], ctx);
  12019. }
  12020. }
  12021. }
  12022. }
  12023. /* Here stop_flag is 1 - Initiate shutdown. */
  12024. DEBUG_TRACE("%s", "stopping workers");
  12025. /* Stop signal received: somebody called mg_stop. Quit. */
  12026. close_all_listening_sockets(ctx);
  12027. /* Wakeup workers that are waiting for connections to handle. */
  12028. (void)pthread_mutex_lock(&ctx->thread_mutex);
  12029. #if defined(ALTERNATIVE_QUEUE)
  12030. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  12031. event_signal(ctx->client_wait_events[i]);
  12032. /* Since we know all sockets, we can shutdown the connections. */
  12033. if (ctx->client_socks[i].in_use) {
  12034. shutdown(ctx->client_socks[i].sock, SHUTDOWN_BOTH);
  12035. }
  12036. }
  12037. #else
  12038. pthread_cond_broadcast(&ctx->sq_full);
  12039. #endif
  12040. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  12041. /* Join all worker threads to avoid leaking threads. */
  12042. workerthreadcount = ctx->cfg_worker_threads;
  12043. for (i = 0; i < workerthreadcount; i++) {
  12044. if (ctx->workerthreadids[i] != 0) {
  12045. mg_join_thread(ctx->workerthreadids[i]);
  12046. }
  12047. }
  12048. #if !defined(NO_SSL)
  12049. if (ctx->ssl_ctx != NULL) {
  12050. uninitialize_ssl(ctx);
  12051. }
  12052. #endif
  12053. DEBUG_TRACE("%s", "exiting");
  12054. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12055. CloseHandle(tls.pthread_cond_helper_mutex);
  12056. #endif
  12057. pthread_setspecific(sTlsKey, NULL);
  12058. /* Signal mg_stop() that we're done.
  12059. * WARNING: This must be the very last thing this
  12060. * thread does, as ctx becomes invalid after this line. */
  12061. ctx->stop_flag = 2;
  12062. }
  12063. /* Threads have different return types on Windows and Unix. */
  12064. #ifdef _WIN32
  12065. static unsigned __stdcall master_thread(void *thread_func_param)
  12066. {
  12067. master_thread_run(thread_func_param);
  12068. return 0;
  12069. }
  12070. #else
  12071. static void *
  12072. master_thread(void *thread_func_param)
  12073. {
  12074. master_thread_run(thread_func_param);
  12075. return NULL;
  12076. }
  12077. #endif /* _WIN32 */
  12078. static void
  12079. free_context(struct mg_context *ctx)
  12080. {
  12081. int i;
  12082. struct mg_handler_info *tmp_rh;
  12083. if (ctx == NULL) {
  12084. return;
  12085. }
  12086. if (ctx->callbacks.exit_context) {
  12087. ctx->callbacks.exit_context(ctx);
  12088. }
  12089. /* All threads exited, no sync is needed. Destroy thread mutex and
  12090. * condvars
  12091. */
  12092. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  12093. #if defined(ALTERNATIVE_QUEUE)
  12094. mg_free(ctx->client_socks);
  12095. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  12096. event_destroy(ctx->client_wait_events[i]);
  12097. }
  12098. mg_free(ctx->client_wait_events);
  12099. #else
  12100. (void)pthread_cond_destroy(&ctx->sq_empty);
  12101. (void)pthread_cond_destroy(&ctx->sq_full);
  12102. #endif
  12103. /* Destroy other context global data structures mutex */
  12104. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  12105. #if defined(USE_TIMERS)
  12106. timers_exit(ctx);
  12107. #endif
  12108. /* Deallocate config parameters */
  12109. for (i = 0; i < NUM_OPTIONS; i++) {
  12110. if (ctx->config[i] != NULL) {
  12111. #if defined(_MSC_VER)
  12112. #pragma warning(suppress : 6001)
  12113. #endif
  12114. mg_free(ctx->config[i]);
  12115. }
  12116. }
  12117. /* Deallocate request handlers */
  12118. while (ctx->handlers) {
  12119. tmp_rh = ctx->handlers;
  12120. ctx->handlers = tmp_rh->next;
  12121. mg_free(tmp_rh->uri);
  12122. mg_free(tmp_rh);
  12123. }
  12124. #ifndef NO_SSL
  12125. /* Deallocate SSL context */
  12126. if (ctx->ssl_ctx != NULL) {
  12127. SSL_CTX_free(ctx->ssl_ctx);
  12128. }
  12129. #endif /* !NO_SSL */
  12130. /* Deallocate worker thread ID array */
  12131. if (ctx->workerthreadids != NULL) {
  12132. mg_free(ctx->workerthreadids);
  12133. }
  12134. /* Deallocate the tls variable */
  12135. if (mg_atomic_dec(&sTlsInit) == 0) {
  12136. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12137. DeleteCriticalSection(&global_log_file_lock);
  12138. #endif /* _WIN32 && !__SYMBIAN32__ */
  12139. #if !defined(_WIN32)
  12140. pthread_mutexattr_destroy(&pthread_mutex_attr);
  12141. #endif
  12142. pthread_key_delete(sTlsKey);
  12143. #if defined(USE_LUA)
  12144. lua_exit_optional_libraries();
  12145. #endif
  12146. }
  12147. /* deallocate system name string */
  12148. mg_free(ctx->systemName);
  12149. /* Deallocate context itself */
  12150. mg_free(ctx);
  12151. }
  12152. void
  12153. mg_stop(struct mg_context *ctx)
  12154. {
  12155. pthread_t mt;
  12156. if (!ctx) {
  12157. return;
  12158. }
  12159. /* We don't use a lock here. Calling mg_stop with the same ctx from
  12160. * two threads is not allowed. */
  12161. mt = ctx->masterthreadid;
  12162. if (mt == 0) {
  12163. return;
  12164. }
  12165. ctx->masterthreadid = 0;
  12166. /* Set stop flag, so all threads know they have to exit. */
  12167. ctx->stop_flag = 1;
  12168. /* Wait until everything has stopped. */
  12169. while (ctx->stop_flag != 2) {
  12170. (void)mg_sleep(10);
  12171. }
  12172. mg_join_thread(mt);
  12173. free_context(ctx);
  12174. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12175. (void)WSACleanup();
  12176. #endif /* _WIN32 && !__SYMBIAN32__ */
  12177. }
  12178. static void
  12179. get_system_name(char **sysName)
  12180. {
  12181. #if defined(_WIN32)
  12182. #if !defined(__SYMBIAN32__)
  12183. #if defined(_WIN32_WCE)
  12184. *sysName = mg_strdup("WinCE");
  12185. #else
  12186. char name[128];
  12187. DWORD dwVersion = 0;
  12188. DWORD dwMajorVersion = 0;
  12189. DWORD dwMinorVersion = 0;
  12190. DWORD dwBuild = 0;
  12191. #ifdef _MSC_VER
  12192. #pragma warning(push)
  12193. /* GetVersion was declared deprecated */
  12194. #pragma warning(disable : 4996)
  12195. #endif
  12196. dwVersion = GetVersion();
  12197. #ifdef _MSC_VER
  12198. #pragma warning(pop)
  12199. #endif
  12200. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  12201. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  12202. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  12203. (void)dwBuild;
  12204. sprintf(name,
  12205. "Windows %u.%u",
  12206. (unsigned)dwMajorVersion,
  12207. (unsigned)dwMinorVersion);
  12208. *sysName = mg_strdup(name);
  12209. #endif
  12210. #else
  12211. *sysName = mg_strdup("Symbian");
  12212. #endif
  12213. #else
  12214. struct utsname name;
  12215. memset(&name, 0, sizeof(name));
  12216. uname(&name);
  12217. *sysName = mg_strdup(name.sysname);
  12218. #endif
  12219. }
  12220. struct mg_context *
  12221. mg_start(const struct mg_callbacks *callbacks,
  12222. void *user_data,
  12223. const char **options)
  12224. {
  12225. struct mg_context *ctx;
  12226. const char *name, *value, *default_value;
  12227. int idx, ok, workerthreadcount;
  12228. unsigned int i;
  12229. void (*exit_callback)(const struct mg_context *ctx) = 0;
  12230. struct mg_workerTLS tls;
  12231. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12232. WSADATA data;
  12233. WSAStartup(MAKEWORD(2, 2), &data);
  12234. #endif /* _WIN32 && !__SYMBIAN32__ */
  12235. /* Allocate context and initialize reasonable general case defaults. */
  12236. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  12237. return NULL;
  12238. }
  12239. /* Random number generator will initialize at the first call */
  12240. ctx->auth_nonce_mask =
  12241. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  12242. if (mg_atomic_inc(&sTlsInit) == 1) {
  12243. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12244. InitializeCriticalSection(&global_log_file_lock);
  12245. #endif /* _WIN32 && !__SYMBIAN32__ */
  12246. #if !defined(_WIN32)
  12247. pthread_mutexattr_init(&pthread_mutex_attr);
  12248. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  12249. #endif
  12250. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  12251. /* Fatal error - abort start. However, this situation should
  12252. * never
  12253. * occur in practice. */
  12254. mg_atomic_dec(&sTlsInit);
  12255. mg_cry(fc(ctx), "Cannot initialize thread local storage");
  12256. mg_free(ctx);
  12257. return NULL;
  12258. }
  12259. #if defined(USE_LUA)
  12260. lua_init_optional_libraries();
  12261. #endif
  12262. } else {
  12263. /* TODO (low): istead of sleeping, check if sTlsKey is already
  12264. * initialized. */
  12265. mg_sleep(1);
  12266. }
  12267. tls.is_master = -1;
  12268. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  12269. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12270. tls.pthread_cond_helper_mutex = NULL;
  12271. #endif
  12272. pthread_setspecific(sTlsKey, &tls);
  12273. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr);
  12274. #if !defined(ALTERNATIVE_QUEUE)
  12275. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  12276. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  12277. #endif
  12278. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr);
  12279. if (!ok) {
  12280. /* Fatal error - abort start. However, this situation should never
  12281. * occur in practice. */
  12282. mg_cry(fc(ctx), "Cannot initialize thread synchronization objects");
  12283. mg_free(ctx);
  12284. pthread_setspecific(sTlsKey, NULL);
  12285. return NULL;
  12286. }
  12287. if (callbacks) {
  12288. ctx->callbacks = *callbacks;
  12289. exit_callback = callbacks->exit_context;
  12290. ctx->callbacks.exit_context = 0;
  12291. }
  12292. ctx->user_data = user_data;
  12293. ctx->handlers = NULL;
  12294. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  12295. ctx->shared_lua_websockets = 0;
  12296. #endif
  12297. while (options && (name = *options++) != NULL) {
  12298. if ((idx = get_option_index(name)) == -1) {
  12299. mg_cry(fc(ctx), "Invalid option: %s", name);
  12300. free_context(ctx);
  12301. pthread_setspecific(sTlsKey, NULL);
  12302. return NULL;
  12303. } else if ((value = *options++) == NULL) {
  12304. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  12305. free_context(ctx);
  12306. pthread_setspecific(sTlsKey, NULL);
  12307. return NULL;
  12308. }
  12309. if (ctx->config[idx] != NULL) {
  12310. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  12311. mg_free(ctx->config[idx]);
  12312. }
  12313. ctx->config[idx] = mg_strdup(value);
  12314. DEBUG_TRACE("[%s] -> [%s]", name, value);
  12315. }
  12316. /* Set default value if needed */
  12317. for (i = 0; config_options[i].name != NULL; i++) {
  12318. default_value = config_options[i].default_value;
  12319. if (ctx->config[i] == NULL && default_value != NULL) {
  12320. ctx->config[i] = mg_strdup(default_value);
  12321. }
  12322. }
  12323. #if defined(NO_FILES)
  12324. if (ctx->config[DOCUMENT_ROOT] != NULL) {
  12325. mg_cry(fc(ctx), "%s", "Document root must not be set");
  12326. free_context(ctx);
  12327. pthread_setspecific(sTlsKey, NULL);
  12328. return NULL;
  12329. }
  12330. #endif
  12331. get_system_name(&ctx->systemName);
  12332. /* NOTE(lsm): order is important here. SSL certificates must
  12333. * be initialized before listening ports. UID must be set last. */
  12334. if (!set_gpass_option(ctx) ||
  12335. #if !defined(NO_SSL)
  12336. !set_ssl_option(ctx) ||
  12337. #endif
  12338. !set_ports_option(ctx) ||
  12339. #if !defined(_WIN32)
  12340. !set_uid_option(ctx) ||
  12341. #endif
  12342. !set_acl_option(ctx)) {
  12343. free_context(ctx);
  12344. pthread_setspecific(sTlsKey, NULL);
  12345. return NULL;
  12346. }
  12347. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  12348. /* Ignore SIGPIPE signal, so if browser cancels the request, it
  12349. * won't kill the whole process. */
  12350. (void)signal(SIGPIPE, SIG_IGN);
  12351. #endif /* !_WIN32 && !__SYMBIAN32__ */
  12352. workerthreadcount = atoi(ctx->config[NUM_THREADS]);
  12353. if (workerthreadcount > MAX_WORKER_THREADS) {
  12354. mg_cry(fc(ctx), "Too many worker threads");
  12355. free_context(ctx);
  12356. pthread_setspecific(sTlsKey, NULL);
  12357. return NULL;
  12358. }
  12359. if (workerthreadcount > 0) {
  12360. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  12361. ctx->workerthreadids =
  12362. (pthread_t *)mg_calloc(ctx->cfg_worker_threads, sizeof(pthread_t));
  12363. if (ctx->workerthreadids == NULL) {
  12364. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  12365. free_context(ctx);
  12366. pthread_setspecific(sTlsKey, NULL);
  12367. return NULL;
  12368. }
  12369. #if defined(ALTERNATIVE_QUEUE)
  12370. ctx->client_wait_events = mg_calloc(sizeof(ctx->client_wait_events[0]),
  12371. ctx->cfg_worker_threads);
  12372. if (ctx->client_wait_events == NULL) {
  12373. mg_cry(fc(ctx), "Not enough memory for worker event array");
  12374. mg_free(ctx->workerthreadids);
  12375. free_context(ctx);
  12376. pthread_setspecific(sTlsKey, NULL);
  12377. return NULL;
  12378. }
  12379. ctx->client_socks =
  12380. mg_calloc(sizeof(ctx->client_socks[0]), ctx->cfg_worker_threads);
  12381. if (ctx->client_wait_events == NULL) {
  12382. mg_cry(fc(ctx), "Not enough memory for worker socket array");
  12383. mg_free(ctx->client_socks);
  12384. mg_free(ctx->workerthreadids);
  12385. free_context(ctx);
  12386. pthread_setspecific(sTlsKey, NULL);
  12387. return NULL;
  12388. }
  12389. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  12390. ctx->client_wait_events[i] = event_create();
  12391. if (ctx->client_wait_events[i] == 0) {
  12392. mg_cry(fc(ctx), "Error creating worker event %i", i);
  12393. /* TODO: clean all and exit */
  12394. }
  12395. }
  12396. #endif
  12397. }
  12398. #if defined(USE_TIMERS)
  12399. if (timers_init(ctx) != 0) {
  12400. mg_cry(fc(ctx), "Error creating timers");
  12401. free_context(ctx);
  12402. pthread_setspecific(sTlsKey, NULL);
  12403. return NULL;
  12404. }
  12405. #endif
  12406. /* Context has been created - init user libraries */
  12407. if (ctx->callbacks.init_context) {
  12408. ctx->callbacks.init_context(ctx);
  12409. }
  12410. ctx->callbacks.exit_context = exit_callback;
  12411. ctx->context_type = 1; /* server context */
  12412. /* Start master (listening) thread */
  12413. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  12414. /* Start worker threads */
  12415. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  12416. struct worker_thread_args *wta =
  12417. mg_malloc(sizeof(struct worker_thread_args));
  12418. if (wta) {
  12419. wta->ctx = ctx;
  12420. wta->index = (int)i;
  12421. }
  12422. if ((wta == NULL)
  12423. || (mg_start_thread_with_id(worker_thread,
  12424. wta,
  12425. &ctx->workerthreadids[i]) != 0)) {
  12426. /* thread was not created */
  12427. if (wta != NULL) {
  12428. mg_free(wta);
  12429. }
  12430. if (i > 0) {
  12431. mg_cry(fc(ctx),
  12432. "Cannot start worker thread %i: error %ld",
  12433. i + 1,
  12434. (long)ERRNO);
  12435. } else {
  12436. mg_cry(fc(ctx),
  12437. "Cannot create threads: error %ld",
  12438. (long)ERRNO);
  12439. free_context(ctx);
  12440. pthread_setspecific(sTlsKey, NULL);
  12441. return NULL;
  12442. }
  12443. break;
  12444. }
  12445. }
  12446. pthread_setspecific(sTlsKey, NULL);
  12447. return ctx;
  12448. }
  12449. /* Feature check API function */
  12450. unsigned
  12451. mg_check_feature(unsigned feature)
  12452. {
  12453. static const unsigned feature_set = 0
  12454. /* Set bits for available features according to API documentation.
  12455. * This bit mask is created at compile time, according to the active
  12456. * preprocessor defines. It is a single const value at runtime. */
  12457. #if !defined(NO_FILES)
  12458. | 0x0001u
  12459. #endif
  12460. #if !defined(NO_SSL)
  12461. | 0x0002u
  12462. #endif
  12463. #if !defined(NO_CGI)
  12464. | 0x0004u
  12465. #endif
  12466. #if defined(USE_IPV6)
  12467. | 0x0008u
  12468. #endif
  12469. #if defined(USE_WEBSOCKET)
  12470. | 0x0010u
  12471. #endif
  12472. #if defined(USE_LUA)
  12473. | 0x0020u
  12474. #endif
  12475. #if defined(USE_DUKTAPE)
  12476. | 0x0040u
  12477. #endif
  12478. #if !defined(NO_CACHING)
  12479. | 0x0080u
  12480. #endif
  12481. /* Set some extra bits not defined in the API documentation.
  12482. * These bits may change without further notice. */
  12483. #if defined(MG_LEGACY_INTERFACE)
  12484. | 0x8000u
  12485. #endif
  12486. #if defined(MEMORY_DEBUGGING)
  12487. | 0x0100u
  12488. #endif
  12489. #if defined(USE_TIMERS)
  12490. | 0x0200u
  12491. #endif
  12492. #if !defined(NO_NONCE_CHECK)
  12493. | 0x0400u
  12494. #endif
  12495. #if !defined(NO_POPEN)
  12496. | 0x0800u
  12497. #endif
  12498. ;
  12499. return (feature & feature_set);
  12500. }