civetweb.c 319 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174
  1. /* Copyright (c) 2013-2015 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. #ifdef __linux__
  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. /* mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8, "size_t data
  92. * type size check"); */
  93. /* DTL -- including winsock2.h works better if lean and mean */
  94. #ifndef WIN32_LEAN_AND_MEAN
  95. #define WIN32_LEAN_AND_MEAN
  96. #endif
  97. #if defined(__SYMBIAN32__)
  98. #define NO_SSL /* SSL is not supported */
  99. #define NO_CGI /* CGI is not supported */
  100. #define PATH_MAX FILENAME_MAX
  101. #endif /* __SYMBIAN32__ */
  102. #ifndef IGNORE_UNUSED_RESULT
  103. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  104. #endif
  105. #ifndef _WIN32_WCE /* Some ANSI #includes are not available on Windows CE */
  106. #include <sys/types.h>
  107. #include <sys/stat.h>
  108. #include <errno.h>
  109. #include <signal.h>
  110. #include <fcntl.h>
  111. #endif /* !_WIN32_WCE */
  112. #ifdef __MACH__
  113. #define CLOCK_MONOTONIC (1)
  114. #define CLOCK_REALTIME (2)
  115. #include <sys/time.h>
  116. #include <mach/clock.h>
  117. #include <mach/mach.h>
  118. #include <mach/mach_time.h>
  119. #include <assert.h>
  120. /* clock_gettime is not implemented on OSX */
  121. int clock_gettime(int clk_id, struct timespec *t);
  122. int
  123. clock_gettime(int clk_id, struct timespec *t)
  124. {
  125. memset(t, 0, sizeof(*t));
  126. if (clk_id == CLOCK_REALTIME) {
  127. struct timeval now;
  128. int rv = gettimeofday(&now, NULL);
  129. if (rv) {
  130. return rv;
  131. }
  132. t->tv_sec = now.tv_sec;
  133. t->tv_nsec = now.tv_usec * 1000;
  134. return 0;
  135. } else if (clk_id == CLOCK_MONOTONIC) {
  136. static uint64_t clock_start_time = 0;
  137. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  138. uint64_t now = mach_absolute_time();
  139. if (clock_start_time == 0) {
  140. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  141. #if defined(DEBUG)
  142. assert(mach_status == KERN_SUCCESS);
  143. #else
  144. /* appease "unused variable" warning for release builds */
  145. (void)mach_status;
  146. #endif
  147. clock_start_time = now;
  148. }
  149. now = (uint64_t)((double)(now - clock_start_time)
  150. * (double)timebase_ifo.numer
  151. / (double)timebase_ifo.denom);
  152. t->tv_sec = now / 1000000000;
  153. t->tv_nsec = now % 1000000000;
  154. return 0;
  155. }
  156. return -1; /* EINVAL - Clock ID is unknown */
  157. }
  158. #endif
  159. #include <time.h>
  160. #include <stdlib.h>
  161. #include <stdarg.h>
  162. #include <assert.h>
  163. #include <string.h>
  164. #include <ctype.h>
  165. #include <limits.h>
  166. #include <stddef.h>
  167. #include <stdio.h>
  168. #ifndef MAX_WORKER_THREADS
  169. #define MAX_WORKER_THREADS (1024 * 64)
  170. #endif
  171. #ifndef SOCKET_TIMEOUT_QUANTUM
  172. #define SOCKET_TIMEOUT_QUANTUM (10000)
  173. #endif
  174. mg_static_assert(MAX_WORKER_THREADS >= 1,
  175. "worker threads must be a positive number");
  176. #if defined(_WIN32) \
  177. && !defined(__SYMBIAN32__) /* WINDOWS / UNIX include block */
  178. #include <windows.h>
  179. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  180. #include <ws2tcpip.h>
  181. typedef const char *SOCK_OPT_TYPE;
  182. #if !defined(PATH_MAX)
  183. #define PATH_MAX (MAX_PATH)
  184. #endif
  185. #if !defined(PATH_MAX)
  186. #define PATH_MAX (4096)
  187. #endif
  188. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  189. #ifndef _IN_PORT_T
  190. #ifndef in_port_t
  191. #define in_port_t u_short
  192. #endif
  193. #endif
  194. #ifndef _WIN32_WCE
  195. #include <process.h>
  196. #include <direct.h>
  197. #include <io.h>
  198. #else /* _WIN32_WCE */
  199. #define NO_CGI /* WinCE has no pipes */
  200. typedef long off_t;
  201. #define errno ((int)(GetLastError()))
  202. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  203. #endif /* _WIN32_WCE */
  204. #define MAKEUQUAD(lo, hi) \
  205. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  206. #define RATE_DIFF (10000000) /* 100 nsecs */
  207. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  208. #define SYS2UNIX_TIME(lo, hi) \
  209. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  210. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  211. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  212. * Also use _strtoui64 on modern M$ compilers */
  213. #if defined(_MSC_VER)
  214. #if (_MSC_VER < 1300)
  215. #define STRX(x) #x
  216. #define STR(x) STRX(x)
  217. #define __func__ __FILE__ ":" STR(__LINE__)
  218. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  219. #define strtoll(x, y, z) (_atoi64(x))
  220. #else
  221. #define __func__ __FUNCTION__
  222. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  223. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  224. #endif
  225. #endif /* _MSC_VER */
  226. #define ERRNO ((int)(GetLastError()))
  227. #define NO_SOCKLEN_T
  228. #define SSL_LIB "ssleay32.dll"
  229. #define CRYPTO_LIB "libeay32.dll"
  230. #define O_NONBLOCK (0)
  231. #ifndef W_OK
  232. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  233. #endif
  234. #if !defined(EWOULDBLOCK)
  235. #define EWOULDBLOCK WSAEWOULDBLOCK
  236. #endif /* !EWOULDBLOCK */
  237. #define _POSIX_
  238. #define INT64_FMT "I64d"
  239. #define UINT64_FMT "I64u"
  240. #define WINCDECL __cdecl
  241. #define SHUT_RD (0)
  242. #define SHUT_WR (1)
  243. #define SHUT_BOTH (2)
  244. #define vsnprintf_impl _vsnprintf
  245. #define access _access
  246. #define mg_sleep(x) (Sleep(x))
  247. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  248. #ifndef popen
  249. #define popen(x, y) (_popen(x, y))
  250. #endif
  251. #ifndef pclose
  252. #define pclose(x) (_pclose(x))
  253. #endif
  254. #define close(x) (_close(x))
  255. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  256. #define RTLD_LAZY (0)
  257. #define fseeko(x, y, z) (_lseeki64(_fileno(x), (y), (z)) == -1 ? -1 : 0)
  258. #define fdopen(x, y) (_fdopen((x), (y)))
  259. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  260. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  261. #define flockfile(x) (EnterCriticalSection(&global_log_file_lock))
  262. #define funlockfile(x) (LeaveCriticalSection(&global_log_file_lock))
  263. #define sleep(x) (Sleep((x)*1000))
  264. #define rmdir(x) (_rmdir(x))
  265. #if !defined(fileno)
  266. #define fileno(x) (_fileno(x))
  267. #endif /* !fileno MINGW #defines fileno */
  268. typedef HANDLE pthread_mutex_t;
  269. typedef DWORD pthread_key_t;
  270. typedef HANDLE pthread_t;
  271. typedef struct {
  272. CRITICAL_SECTION threadIdSec;
  273. int waitingthreadcount; /* The number of threads queued. */
  274. pthread_t *waitingthreadhdls; /* The thread handles. */
  275. } pthread_cond_t;
  276. #ifndef __clockid_t_defined
  277. typedef DWORD clockid_t;
  278. #endif
  279. #ifndef CLOCK_MONOTONIC
  280. #define CLOCK_MONOTONIC (1)
  281. #endif
  282. #ifndef CLOCK_REALTIME
  283. #define CLOCK_REALTIME (2)
  284. #endif
  285. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  286. #define _TIMESPEC_DEFINED
  287. #endif
  288. #ifndef _TIMESPEC_DEFINED
  289. struct timespec {
  290. time_t tv_sec; /* seconds */
  291. long tv_nsec; /* nanoseconds */
  292. };
  293. #endif
  294. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  295. static int pthread_mutex_lock(pthread_mutex_t *);
  296. static int pthread_mutex_unlock(pthread_mutex_t *);
  297. static void to_unicode(const char *path, wchar_t *wbuf, size_t wbuf_len);
  298. struct file;
  299. static char *mg_fgets(char *buf, size_t size, struct file *filep, char **p);
  300. #if defined(HAVE_STDINT)
  301. #include <stdint.h>
  302. #else
  303. typedef unsigned char uint8_t;
  304. typedef unsigned short uint16_t;
  305. typedef unsigned int uint32_t;
  306. typedef unsigned __int64 uint64_t;
  307. typedef __int64 int64_t;
  308. #define INT64_MAX (9223372036854775807)
  309. #endif /* HAVE_STDINT */
  310. /* POSIX dirent interface */
  311. struct dirent {
  312. char d_name[PATH_MAX];
  313. };
  314. typedef struct DIR {
  315. HANDLE handle;
  316. WIN32_FIND_DATAW info;
  317. struct dirent result;
  318. } DIR;
  319. #if defined(_WIN32) && !defined(POLLIN)
  320. #ifndef HAVE_POLL
  321. struct pollfd {
  322. SOCKET fd;
  323. short events;
  324. short revents;
  325. };
  326. #define POLLIN (0x0300)
  327. #endif
  328. #endif
  329. /* Mark required libraries */
  330. #if defined(_MSC_VER)
  331. #pragma comment(lib, "Ws2_32.lib")
  332. #endif
  333. #else /* defined(_WIN32) && !defined(__SYMBIAN32__) - WINDOWS / UNIX include \
  334. block */
  335. #include <sys/wait.h>
  336. #include <sys/socket.h>
  337. #include <sys/poll.h>
  338. #include <netinet/in.h>
  339. #include <arpa/inet.h>
  340. #include <sys/time.h>
  341. #include <sys/utsname.h>
  342. #include <stdint.h>
  343. #include <inttypes.h>
  344. #include <netdb.h>
  345. typedef const void *SOCK_OPT_TYPE;
  346. #if defined(ANDROID)
  347. typedef unsigned short int in_port_t;
  348. #endif
  349. #include <pwd.h>
  350. #include <unistd.h>
  351. #include <grp.h>
  352. #include <dirent.h>
  353. #define vsnprintf_impl vsnprintf
  354. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  355. #include <dlfcn.h>
  356. #endif
  357. #include <pthread.h>
  358. #if defined(__MACH__)
  359. #define SSL_LIB "libssl.dylib"
  360. #define CRYPTO_LIB "libcrypto.dylib"
  361. #else
  362. #if !defined(SSL_LIB)
  363. #define SSL_LIB "libssl.so"
  364. #endif
  365. #if !defined(CRYPTO_LIB)
  366. #define CRYPTO_LIB "libcrypto.so"
  367. #endif
  368. #endif
  369. #ifndef O_BINARY
  370. #define O_BINARY (0)
  371. #endif /* O_BINARY */
  372. #define closesocket(a) (close(a))
  373. #define mg_mkdir(x, y) (mkdir(x, y))
  374. #define mg_remove(x) (remove(x))
  375. #define mg_sleep(x) (usleep((x)*1000))
  376. #define ERRNO (errno)
  377. #define INVALID_SOCKET (-1)
  378. #define INT64_FMT PRId64
  379. #define UINT64_FMT PRIu64
  380. typedef int SOCKET;
  381. #define WINCDECL
  382. #if defined(__hpux)
  383. /* HPUX 11 does not have monotonic, fall back to realtime */
  384. #ifndef CLOCK_MONOTONIC
  385. #define CLOCK_MONOTONIC CLOCK_REALTIME
  386. #endif
  387. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  388. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  389. * the prototypes use int* rather than socklen_t* which matches the
  390. * actual library expectation. When called with the wrong size arg
  391. * accept() returns a zero client inet addr and check_acl() always
  392. * fails. Since socklen_t is widely used below, just force replace
  393. * their typedef with int. - DTL
  394. */
  395. #define socklen_t int
  396. #endif /* hpux */
  397. #endif /* defined(_WIN32) && !defined(__SYMBIAN32__) - WINDOWS / UNIX include \
  398. block */
  399. /* va_copy should always be a macro, C99 and C++11 - DTL */
  400. #ifndef va_copy
  401. #define va_copy(x, y) ((x) = (y))
  402. #endif
  403. #ifdef _WIN32
  404. /* Create substitutes for POSIX functions in Win32. */
  405. #if defined(__MINGW32__)
  406. /* Show no warning in case system functions are not used. */
  407. #pragma GCC diagnostic push
  408. #pragma GCC diagnostic ignored "-Wunused-function"
  409. #endif
  410. static CRITICAL_SECTION global_log_file_lock;
  411. static DWORD
  412. pthread_self(void)
  413. {
  414. return GetCurrentThreadId();
  415. }
  416. static int
  417. pthread_key_create(
  418. pthread_key_t *key,
  419. void (*_ignored)(void *) /* destructor not supported for Windows */
  420. )
  421. {
  422. (void)_ignored;
  423. if ((key != 0)) {
  424. *key = TlsAlloc();
  425. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  426. }
  427. return -2;
  428. }
  429. static int
  430. pthread_key_delete(pthread_key_t key)
  431. {
  432. return TlsFree(key) ? 0 : 1;
  433. }
  434. static int
  435. pthread_setspecific(pthread_key_t key, void *value)
  436. {
  437. return TlsSetValue(key, value) ? 0 : 1;
  438. }
  439. static void *
  440. pthread_getspecific(pthread_key_t key)
  441. {
  442. return TlsGetValue(key);
  443. }
  444. #if defined(__MINGW32__)
  445. /* Enable unused function warning again */
  446. #pragma GCC diagnostic pop
  447. #endif
  448. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  449. #else
  450. static pthread_mutexattr_t pthread_mutex_attr;
  451. #endif /* _WIN32 */
  452. #include "civetweb.h"
  453. #define PASSWORDS_FILE_NAME ".htpasswd"
  454. #define CGI_ENVIRONMENT_SIZE (4096)
  455. #define MAX_CGI_ENVIR_VARS (256)
  456. #define MG_BUF_LEN (8192)
  457. #ifndef MAX_REQUEST_SIZE
  458. #define MAX_REQUEST_SIZE (16384)
  459. #endif
  460. mg_static_assert(MAX_REQUEST_SIZE >= 256,
  461. "request size length must be a positive number");
  462. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  463. #if !defined(DEBUG_TRACE)
  464. #if defined(DEBUG)
  465. static void DEBUG_TRACE_FUNC(const char *func,
  466. unsigned line,
  467. PRINTF_FORMAT_STRING(const char *fmt),
  468. ...) PRINTF_ARGS(3, 4);
  469. static void
  470. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  471. {
  472. va_list args;
  473. flockfile(stdout);
  474. printf("*** %lu.%p.%s.%u: ",
  475. (unsigned long)time(NULL),
  476. (void *)pthread_self(),
  477. func,
  478. line);
  479. va_start(args, fmt);
  480. vprintf(fmt, args);
  481. va_end(args);
  482. putchar('\n');
  483. fflush(stdout);
  484. funlockfile(stdout);
  485. }
  486. #define DEBUG_TRACE(fmt, ...) \
  487. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  488. #else
  489. #define DEBUG_TRACE(fmt, ...) \
  490. do { \
  491. } while (0)
  492. #endif /* DEBUG */
  493. #endif /* DEBUG_TRACE */
  494. #if defined(MEMORY_DEBUGGING)
  495. unsigned long mg_memory_debug_blockCount = 0;
  496. unsigned long mg_memory_debug_totalMemUsed = 0;
  497. static void *
  498. mg_malloc_ex(size_t size, const char *file, unsigned line)
  499. {
  500. void *data = malloc(size + sizeof(size_t));
  501. void *memory = 0;
  502. char mallocStr[256];
  503. if (data) {
  504. *(size_t *)data = size;
  505. mg_memory_debug_totalMemUsed += size;
  506. mg_memory_debug_blockCount++;
  507. memory = (void *)(((char *)data) + sizeof(size_t));
  508. }
  509. sprintf(mallocStr,
  510. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  511. memory,
  512. (unsigned long)size,
  513. mg_memory_debug_totalMemUsed,
  514. mg_memory_debug_blockCount,
  515. file,
  516. line);
  517. #if defined(_WIN32)
  518. OutputDebugStringA(mallocStr);
  519. #else
  520. DEBUG_TRACE("%s", mallocStr);
  521. #endif
  522. return memory;
  523. }
  524. static void *
  525. mg_calloc_ex(size_t count, size_t size, const char *file, unsigned line)
  526. {
  527. void *data = mg_malloc_ex(size * count, file, line);
  528. if (data) {
  529. memset(data, 0, size);
  530. }
  531. return data;
  532. }
  533. static void
  534. mg_free_ex(void *memory, const char *file, unsigned line)
  535. {
  536. char mallocStr[256];
  537. void *data = (void *)(((char *)memory) - sizeof(size_t));
  538. size_t size;
  539. if (memory) {
  540. size = *(size_t *)data;
  541. mg_memory_debug_totalMemUsed -= size;
  542. mg_memory_debug_blockCount--;
  543. sprintf(mallocStr,
  544. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  545. memory,
  546. (unsigned long)size,
  547. mg_memory_debug_totalMemUsed,
  548. mg_memory_debug_blockCount,
  549. file,
  550. line);
  551. #if defined(_WIN32)
  552. OutputDebugStringA(mallocStr);
  553. #else
  554. DEBUG_TRACE("%s", mallocStr);
  555. #endif
  556. free(data);
  557. }
  558. }
  559. static void *
  560. mg_realloc_ex(void *memory, size_t newsize, const char *file, unsigned line)
  561. {
  562. char mallocStr[256];
  563. void *data;
  564. void *_realloc;
  565. size_t oldsize;
  566. if (newsize) {
  567. if (memory) {
  568. data = (void *)(((char *)memory) - sizeof(size_t));
  569. oldsize = *(size_t *)data;
  570. _realloc = realloc(data, newsize + sizeof(size_t));
  571. if (_realloc) {
  572. data = _realloc;
  573. mg_memory_debug_totalMemUsed -= oldsize;
  574. sprintf(mallocStr,
  575. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  576. memory,
  577. (unsigned long)oldsize,
  578. mg_memory_debug_totalMemUsed,
  579. mg_memory_debug_blockCount,
  580. file,
  581. line);
  582. #if defined(_WIN32)
  583. OutputDebugStringA(mallocStr);
  584. #else
  585. DEBUG_TRACE("%s", mallocStr);
  586. #endif
  587. mg_memory_debug_totalMemUsed += newsize;
  588. sprintf(mallocStr,
  589. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  590. memory,
  591. (unsigned long)newsize,
  592. mg_memory_debug_totalMemUsed,
  593. mg_memory_debug_blockCount,
  594. file,
  595. line);
  596. #if defined(_WIN32)
  597. OutputDebugStringA(mallocStr);
  598. #else
  599. DEBUG_TRACE("%s", mallocStr);
  600. #endif
  601. *(size_t *)data = newsize;
  602. data = (void *)(((char *)data) + sizeof(size_t));
  603. } else {
  604. #if defined(_WIN32)
  605. OutputDebugStringA("MEM: realloc failed\n");
  606. #else
  607. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  608. #endif
  609. return _realloc;
  610. }
  611. } else {
  612. data = mg_malloc_ex(newsize, file, line);
  613. }
  614. } else {
  615. data = 0;
  616. mg_free_ex(memory, file, line);
  617. }
  618. return data;
  619. }
  620. #define mg_malloc(a) mg_malloc_ex(a, __FILE__, __LINE__)
  621. #define mg_calloc(a, b) mg_calloc_ex(a, b, __FILE__, __LINE__)
  622. #define mg_realloc(a, b) mg_realloc_ex(a, b, __FILE__, __LINE__)
  623. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  624. #else
  625. static __inline void *
  626. mg_malloc(size_t a)
  627. {
  628. return malloc(a);
  629. }
  630. static __inline void *
  631. mg_calloc(size_t a, size_t b)
  632. {
  633. return calloc(a, b);
  634. }
  635. static __inline void *
  636. mg_realloc(void *a, size_t b)
  637. {
  638. return realloc(a, b);
  639. }
  640. static __inline void
  641. mg_free(void *a)
  642. {
  643. free(a);
  644. }
  645. #endif
  646. static void mg_vsnprintf(const struct mg_connection *conn,
  647. int *truncated,
  648. char *buf,
  649. size_t buflen,
  650. const char *fmt,
  651. va_list ap);
  652. static void mg_snprintf(const struct mg_connection *conn,
  653. int *truncated,
  654. char *buf,
  655. size_t buflen,
  656. PRINTF_FORMAT_STRING(const char *fmt),
  657. ...) PRINTF_ARGS(5, 6);
  658. /* This following lines are just meant as a reminder to use the mg-functions
  659. * for memory management */
  660. #ifdef malloc
  661. #undef malloc
  662. #endif
  663. #ifdef calloc
  664. #undef calloc
  665. #endif
  666. #ifdef realloc
  667. #undef realloc
  668. #endif
  669. #ifdef free
  670. #undef free
  671. #endif
  672. #ifdef snprintf
  673. #undef snprintf
  674. #endif
  675. #ifdef vsnprintf
  676. #undef vsnprintf
  677. #endif
  678. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  679. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  680. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  681. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  682. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  683. #ifdef _WIN32 /* vsnprintf must not be used in any system, * \
  684. * but this define only works well for Windows. */
  685. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  686. #endif
  687. #define MD5_STATIC static
  688. #include "md5.inl"
  689. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  690. #ifdef NO_SOCKLEN_T
  691. typedef int socklen_t;
  692. #endif /* NO_SOCKLEN_T */
  693. #define _DARWIN_UNLIMITED_SELECT
  694. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  695. #if !defined(MSG_NOSIGNAL)
  696. #define MSG_NOSIGNAL (0)
  697. #endif
  698. #if !defined(SOMAXCONN)
  699. #define SOMAXCONN (100)
  700. #endif
  701. /* Size of the accepted socket queue */
  702. #if !defined(MGSQLEN)
  703. #define MGSQLEN (20)
  704. #endif
  705. #if defined(NO_SSL_DL)
  706. #include <openssl/ssl.h>
  707. #include <openssl/err.h>
  708. #include <openssl/crypto.h>
  709. #include <openssl/x509.h>
  710. #include <openssl/pem.h>
  711. #else
  712. /* SSL loaded dynamically from DLL.
  713. * I put the prototypes here to be independent from OpenSSL source
  714. * installation. */
  715. typedef struct ssl_st SSL;
  716. typedef struct ssl_method_st SSL_METHOD;
  717. typedef struct ssl_ctx_st SSL_CTX;
  718. typedef struct x509_store_ctx_st X509_STORE_CTX;
  719. #define SSL_VERIFY_NONE (0)
  720. #define SSL_VERIFY_PEER (1)
  721. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  722. #define SSL_VERIFY_CLIENT_ONCE (4)
  723. struct ssl_func {
  724. const char *name; /* SSL function name */
  725. void (*ptr)(void); /* Function pointer */
  726. };
  727. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  728. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  729. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  730. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  731. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  732. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  733. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  734. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  735. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  736. #define SSLv23_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  737. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  738. #define SSL_CTX_use_PrivateKey_file \
  739. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  740. #define SSL_CTX_use_certificate_file \
  741. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  742. #define SSL_CTX_set_default_passwd_cb \
  743. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  744. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  745. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  746. #define SSL_CTX_use_certificate_chain_file \
  747. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  748. #define SSLv23_client_method (*(SSL_METHOD * (*)(void))ssl_sw[17].ptr)
  749. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  750. #define SSL_CTX_set_verify \
  751. (*(void (*)(SSL_CTX *, \
  752. int, \
  753. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19].ptr)
  754. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  755. #define SSL_CTX_load_verify_locations \
  756. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  757. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  758. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  759. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[24].ptr)
  760. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  761. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[26].ptr)
  762. #define SSL_CIPHER_get_name \
  763. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  764. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  765. #define SSL_CTX_set_session_id_context \
  766. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  767. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  768. #define CRYPTO_set_locking_callback \
  769. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  770. #define CRYPTO_set_id_callback \
  771. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  772. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  773. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  774. /* set_ssl_option() function updates this array.
  775. * It loads SSL library dynamically and changes NULLs to the actual addresses
  776. * of respective functions. The macros above (like SSL_connect()) are really
  777. * just calling these functions indirectly via the pointer. */
  778. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  779. {"SSL_accept", NULL},
  780. {"SSL_connect", NULL},
  781. {"SSL_read", NULL},
  782. {"SSL_write", NULL},
  783. {"SSL_get_error", NULL},
  784. {"SSL_set_fd", NULL},
  785. {"SSL_new", NULL},
  786. {"SSL_CTX_new", NULL},
  787. {"SSLv23_server_method", NULL},
  788. {"SSL_library_init", NULL},
  789. {"SSL_CTX_use_PrivateKey_file", NULL},
  790. {"SSL_CTX_use_certificate_file", NULL},
  791. {"SSL_CTX_set_default_passwd_cb", NULL},
  792. {"SSL_CTX_free", NULL},
  793. {"SSL_load_error_strings", NULL},
  794. {"SSL_CTX_use_certificate_chain_file", NULL},
  795. {"SSLv23_client_method", NULL},
  796. {"SSL_pending", NULL},
  797. {"SSL_CTX_set_verify", NULL},
  798. {"SSL_shutdown", NULL},
  799. {"SSL_CTX_load_verify_locations", NULL},
  800. {"SSL_CTX_set_default_verify_paths", NULL},
  801. {"SSL_CTX_set_verify_depth", NULL},
  802. {"SSL_get_peer_certificate", NULL},
  803. {"SSL_get_version", NULL},
  804. {"SSL_get_current_cipher", NULL},
  805. {"SSL_CIPHER_get_name", NULL},
  806. {"SSL_CTX_check_private_key", NULL},
  807. {"SSL_CTX_set_session_id_context", NULL},
  808. {NULL, NULL}};
  809. /* Similar array as ssl_sw. These functions could be located in different
  810. * lib. */
  811. #if !defined(NO_SSL)
  812. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  813. {"CRYPTO_set_locking_callback", NULL},
  814. {"CRYPTO_set_id_callback", NULL},
  815. {"ERR_get_error", NULL},
  816. {"ERR_error_string", NULL},
  817. {NULL, NULL}};
  818. #endif /* NO_SSL */
  819. #endif /* NO_SSL_DL */
  820. static const char *month_names[] = {"Jan",
  821. "Feb",
  822. "Mar",
  823. "Apr",
  824. "May",
  825. "Jun",
  826. "Jul",
  827. "Aug",
  828. "Sep",
  829. "Oct",
  830. "Nov",
  831. "Dec"};
  832. /* Unified socket address. For IPv6 support, add IPv6 address structure in the
  833. * union u. */
  834. union usa {
  835. struct sockaddr sa;
  836. struct sockaddr_in sin;
  837. #if defined(USE_IPV6)
  838. struct sockaddr_in6 sin6;
  839. #endif
  840. };
  841. /* Describes a string (chunk of memory). */
  842. struct vec {
  843. const char *ptr;
  844. size_t len;
  845. };
  846. struct file {
  847. uint64_t size;
  848. time_t last_modified;
  849. FILE *fp;
  850. const char *membuf; /* Non-NULL if file data is in memory */
  851. int is_directory;
  852. int gzipped; /* set to 1 if the content is gzipped
  853. * in which case we need a content-encoding: gzip header */
  854. };
  855. #define STRUCT_FILE_INITIALIZER \
  856. { \
  857. (uint64_t)0, (time_t)0, (FILE *)NULL, (const char *)NULL, 0, 0 \
  858. }
  859. /* Describes listening socket, or socket which was accept()-ed by the master
  860. * thread and queued for future handling by the worker thread. */
  861. struct socket {
  862. SOCKET sock; /* Listening socket */
  863. union usa lsa; /* Local socket address */
  864. union usa rsa; /* Remote socket address */
  865. unsigned char is_ssl; /* Is port SSL-ed */
  866. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  867. * port */
  868. };
  869. /* NOTE(lsm): this enum shoulds be in sync with the config_options below. */
  870. enum {
  871. CGI_EXTENSIONS,
  872. CGI_ENVIRONMENT,
  873. PUT_DELETE_PASSWORDS_FILE,
  874. CGI_INTERPRETER,
  875. PROTECT_URI,
  876. AUTHENTICATION_DOMAIN,
  877. SSI_EXTENSIONS,
  878. THROTTLE,
  879. ACCESS_LOG_FILE,
  880. ENABLE_DIRECTORY_LISTING,
  881. ERROR_LOG_FILE,
  882. GLOBAL_PASSWORDS_FILE,
  883. INDEX_FILES,
  884. ENABLE_KEEP_ALIVE,
  885. ACCESS_CONTROL_LIST,
  886. EXTRA_MIME_TYPES,
  887. LISTENING_PORTS,
  888. DOCUMENT_ROOT,
  889. SSL_CERTIFICATE,
  890. NUM_THREADS,
  891. RUN_AS_USER,
  892. REWRITE,
  893. HIDE_FILES,
  894. REQUEST_TIMEOUT,
  895. SSL_DO_VERIFY_PEER,
  896. SSL_CA_PATH,
  897. SSL_CA_FILE,
  898. SSL_VERIFY_DEPTH,
  899. SSL_DEFAULT_VERIFY_PATHS,
  900. SSL_FORWARD_SECRECY,
  901. #if defined(USE_WEBSOCKET)
  902. WEBSOCKET_TIMEOUT,
  903. #endif
  904. DECODE_URL,
  905. #if defined(USE_LUA)
  906. LUA_PRELOAD_FILE,
  907. LUA_SCRIPT_EXTENSIONS,
  908. LUA_SERVER_PAGE_EXTENSIONS,
  909. #endif
  910. #if defined(USE_DUKTAPE)
  911. DUKTAPE_SCRIPT_EXTENSIONS,
  912. #endif
  913. #if defined(USE_WEBSOCKET)
  914. WEBSOCKET_ROOT,
  915. #endif
  916. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  917. LUA_WEBSOCKET_EXTENSIONS,
  918. #endif
  919. ACCESS_CONTROL_ALLOW_ORIGIN,
  920. ERROR_PAGES,
  921. NUM_OPTIONS
  922. };
  923. /* Config option name, config types, default value */
  924. static struct mg_option config_options[] = {
  925. {"cgi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  926. {"cgi_environment", CONFIG_TYPE_STRING, NULL},
  927. {"put_delete_auth_file", CONFIG_TYPE_FILE, NULL},
  928. {"cgi_interpreter", CONFIG_TYPE_FILE, NULL},
  929. {"protect_uri", CONFIG_TYPE_STRING, NULL},
  930. {"authentication_domain", CONFIG_TYPE_STRING, "mydomain.com"},
  931. {"ssi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  932. {"throttle", CONFIG_TYPE_STRING, NULL},
  933. {"access_log_file", CONFIG_TYPE_FILE, NULL},
  934. {"enable_directory_listing", CONFIG_TYPE_BOOLEAN, "yes"},
  935. {"error_log_file", CONFIG_TYPE_FILE, NULL},
  936. {"global_auth_file", CONFIG_TYPE_FILE, NULL},
  937. {"index_files",
  938. CONFIG_TYPE_STRING,
  939. #ifdef USE_LUA
  940. "index.xhtml,index.html,index.htm,index.lp,index.lsp,index.lua,index.cgi,"
  941. "index.shtml,index.php"},
  942. #else
  943. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  944. #endif
  945. {"enable_keep_alive", CONFIG_TYPE_BOOLEAN, "no"},
  946. {"access_control_list", CONFIG_TYPE_STRING, NULL},
  947. {"extra_mime_types", CONFIG_TYPE_STRING, NULL},
  948. {"listening_ports", CONFIG_TYPE_STRING, "8080"},
  949. {"document_root", CONFIG_TYPE_DIRECTORY, NULL},
  950. {"ssl_certificate", CONFIG_TYPE_FILE, NULL},
  951. {"num_threads", CONFIG_TYPE_NUMBER, "50"},
  952. {"run_as_user", CONFIG_TYPE_STRING, NULL},
  953. {"url_rewrite_patterns", CONFIG_TYPE_STRING, NULL},
  954. {"hide_files_patterns", CONFIG_TYPE_EXT_PATTERN, NULL},
  955. {"request_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  956. {"ssl_verify_peer", CONFIG_TYPE_BOOLEAN, "no"},
  957. {"ssl_ca_path", CONFIG_TYPE_DIRECTORY, NULL},
  958. {"ssl_ca_file", CONFIG_TYPE_FILE, NULL},
  959. {"ssl_verify_depth", CONFIG_TYPE_NUMBER, "9"},
  960. {"ssl_default_verify_paths", CONFIG_TYPE_BOOLEAN, "yes"},
  961. {"ssl_forward_secrecy", CONFIG_TYPE_BOOLEAN, "yes"},
  962. #if defined(USE_WEBSOCKET)
  963. {"websocket_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  964. #endif
  965. {"decode_url", CONFIG_TYPE_BOOLEAN, "yes"},
  966. #if defined(USE_LUA)
  967. {"lua_preload_file", CONFIG_TYPE_FILE, NULL},
  968. {"lua_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  969. {"lua_server_page_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  970. #endif
  971. #if defined(USE_DUKTAPE)
  972. {"_experimental_duktape_script_pattern",
  973. CONFIG_TYPE_EXT_PATTERN,
  974. "**.ssjs$"}, /* TODO: redefine parameter */
  975. #endif
  976. #if defined(USE_WEBSOCKET)
  977. {"websocket_root", CONFIG_TYPE_DIRECTORY, NULL},
  978. #endif
  979. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  980. {"lua_websocket_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  981. #endif
  982. {"access_control_allow_origin", CONFIG_TYPE_STRING, "*"},
  983. {"error_pages", CONFIG_TYPE_DIRECTORY, NULL},
  984. {NULL, CONFIG_TYPE_UNKNOWN, NULL}};
  985. /* Check if the config_options and the corresponding enum have compatible
  986. * sizes. */
  987. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  988. == (NUM_OPTIONS + 1),
  989. "config_options and enum not sync");
  990. struct mg_request_handler_info {
  991. /* Name/Pattern of the URI. */
  992. char *uri;
  993. size_t uri_len;
  994. /* URI type: ws/wss (websocket) or http/https (web page). */
  995. int is_websocket_handler;
  996. /* Handler for http/https requests. */
  997. mg_request_handler handler;
  998. /* Handler for ws/wss (websocket) requests. */
  999. mg_websocket_connect_handler connect_handler;
  1000. mg_websocket_ready_handler ready_handler;
  1001. mg_websocket_data_handler data_handler;
  1002. mg_websocket_close_handler close_handler;
  1003. /* User supplied argument for the handler function. */
  1004. void *cbdata;
  1005. /* next request handler in a linked list */
  1006. struct mg_request_handler_info *next;
  1007. };
  1008. struct mg_context {
  1009. volatile int stop_flag; /* Should we stop event loop */
  1010. SSL_CTX *ssl_ctx; /* SSL context */
  1011. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1012. struct mg_callbacks callbacks; /* User-defined callback function */
  1013. void *user_data; /* User-defined data */
  1014. int context_type; /* 1 = server context, 2 = client context */
  1015. struct socket *listening_sockets;
  1016. in_port_t *listening_ports;
  1017. unsigned int num_listening_sockets;
  1018. volatile int
  1019. running_worker_threads; /* Number of currently running worker threads */
  1020. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  1021. pthread_cond_t thread_cond; /* Condvar for tracking workers terminations */
  1022. struct socket queue[MGSQLEN]; /* Accepted sockets */
  1023. volatile int sq_head; /* Head of the socket queue */
  1024. volatile int sq_tail; /* Tail of the socket queue */
  1025. pthread_cond_t sq_full; /* Signaled when socket is produced */
  1026. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  1027. pthread_t masterthreadid; /* The master thread ID */
  1028. unsigned int
  1029. cfg_worker_threads; /* The number of configured worker threads. */
  1030. pthread_t *workerthreadids; /* The worker thread IDs */
  1031. time_t start_time; /* Server start time, used for authentication */
  1032. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1033. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  1034. unsigned long nonce_count; /* Used nonces, used for authentication */
  1035. char *systemName; /* What operating system is running */
  1036. /* linked list of uri handlers */
  1037. struct mg_request_handler_info *request_handlers;
  1038. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1039. /* linked list of shared lua websockets */
  1040. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1041. #endif
  1042. #ifdef USE_TIMERS
  1043. struct ttimers *timers;
  1044. #endif
  1045. };
  1046. struct mg_connection {
  1047. struct mg_request_info request_info;
  1048. struct mg_context *ctx;
  1049. SSL *ssl; /* SSL descriptor */
  1050. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  1051. struct socket client; /* Connected client */
  1052. time_t conn_birth_time; /* Time (wall clock) when connection was
  1053. * established */
  1054. struct timespec req_time; /* Time (since system start) when the request
  1055. * was received */
  1056. int64_t num_bytes_sent; /* Total bytes sent to client */
  1057. int64_t content_len; /* Content-Length header value */
  1058. int64_t consumed_content; /* How many bytes of content have been read */
  1059. int is_chunked; /* Transfer-Encoding is chunked: 0=no, 1=yes:
  1060. * data available, 2: all data read */
  1061. size_t chunk_remainder; /* Unread data from the last chunk */
  1062. char *buf; /* Buffer for received data */
  1063. char *path_info; /* PATH_INFO part of the URL */
  1064. int must_close; /* 1 if connection must be closed */
  1065. int in_error_handler; /* 1 if in handler for user defined error
  1066. * pages */
  1067. int internal_error; /* 1 if an error occured while processing the
  1068. * request */
  1069. int buf_size; /* Buffer size */
  1070. int request_len; /* Size of the request + headers in a buffer */
  1071. int data_len; /* Total size of data in a buffer */
  1072. int status_code; /* HTTP reply status code, e.g. 200 */
  1073. int throttle; /* Throttling, bytes/sec. <= 0 means no
  1074. * throttle */
  1075. time_t last_throttle_time; /* Last time throttled data was sent */
  1076. int64_t last_throttle_bytes; /* Bytes sent this second */
  1077. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  1078. * atomic transmissions for websockets */
  1079. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1080. void *lua_websocket_state; /* Lua_State for a websocket connection */
  1081. #endif
  1082. };
  1083. static pthread_key_t sTlsKey; /* Thread local storage index */
  1084. static int sTlsInit = 0;
  1085. static int thread_idx_max = 0;
  1086. struct mg_workerTLS {
  1087. int is_master;
  1088. unsigned long thread_idx;
  1089. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1090. HANDLE pthread_cond_helper_mutex;
  1091. #endif
  1092. };
  1093. /* Directory entry */
  1094. struct de {
  1095. struct mg_connection *conn;
  1096. char *file_name;
  1097. struct file file;
  1098. };
  1099. #if defined(USE_WEBSOCKET)
  1100. static int is_websocket_protocol(const struct mg_connection *conn);
  1101. #else
  1102. #define is_websocket_protocol(conn) (0)
  1103. #endif
  1104. static int
  1105. mg_atomic_inc(volatile int *addr)
  1106. {
  1107. int ret;
  1108. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1109. /* Depending on the SDK, this function uses either
  1110. * (volatile unsigned int *) or (volatile LONG *),
  1111. * so whatever you use, the other SDK is likely to raise a warning. */
  1112. ret = InterlockedIncrement((volatile long *)addr);
  1113. #elif defined(__GNUC__) \
  1114. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  1115. ret = __sync_add_and_fetch(addr, 1);
  1116. #else
  1117. ret = (++(*addr));
  1118. #endif
  1119. return ret;
  1120. }
  1121. static int
  1122. mg_atomic_dec(volatile int *addr)
  1123. {
  1124. int ret;
  1125. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1126. /* Depending on the SDK, this function uses either
  1127. * (volatile unsigned int *) or (volatile LONG *),
  1128. * so whatever you use, the other SDK is likely to raise a warning. */
  1129. ret = InterlockedDecrement((volatile long *)addr);
  1130. #elif defined(__GNUC__) \
  1131. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  1132. ret = __sync_sub_and_fetch(addr, 1);
  1133. #else
  1134. ret = (--(*addr));
  1135. #endif
  1136. return ret;
  1137. }
  1138. #if !defined(NO_THREAD_NAME)
  1139. #if defined(_WIN32) && defined(_MSC_VER)
  1140. /* Set the thread name for debugging purposes in Visual Studio
  1141. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  1142. */
  1143. #pragma pack(push, 8)
  1144. typedef struct tagTHREADNAME_INFO {
  1145. DWORD dwType; /* Must be 0x1000. */
  1146. LPCSTR szName; /* Pointer to name (in user addr space). */
  1147. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  1148. DWORD dwFlags; /* Reserved for future use, must be zero. */
  1149. } THREADNAME_INFO;
  1150. #pragma pack(pop)
  1151. #elif defined(__linux__)
  1152. #include <sys/prctl.h>
  1153. #include <sys/sendfile.h>
  1154. #endif
  1155. static void
  1156. mg_set_thread_name(const char *name)
  1157. {
  1158. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  1159. mg_snprintf(
  1160. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  1161. #if defined(_WIN32)
  1162. #if defined(_MSC_VER)
  1163. /* Windows and Visual Studio Compiler */
  1164. __try
  1165. {
  1166. THREADNAME_INFO info;
  1167. info.dwType = 0x1000;
  1168. info.szName = threadName;
  1169. info.dwThreadID = ~0U;
  1170. info.dwFlags = 0;
  1171. RaiseException(0x406D1388,
  1172. 0,
  1173. sizeof(info) / sizeof(ULONG_PTR),
  1174. (ULONG_PTR *)&info);
  1175. }
  1176. __except(EXCEPTION_EXECUTE_HANDLER)
  1177. {
  1178. }
  1179. #elif defined(__MINGW32__)
  1180. /* No option known to set thread name for MinGW */
  1181. #endif
  1182. #elif defined(__GLIBC__) \
  1183. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  1184. /* pthread_setname_np first appeared in glibc in version 2.12*/
  1185. (void)pthread_setname_np(pthread_self(), threadName);
  1186. #elif defined(__linux__)
  1187. /* on linux we can use the old prctl function */
  1188. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  1189. #endif
  1190. }
  1191. #else /* !defined(NO_THREAD_NAME) */
  1192. void
  1193. mg_set_thread_name(const char *threadName)
  1194. {
  1195. }
  1196. #endif
  1197. #if defined(MG_LEGACY_INTERFACE)
  1198. const char **
  1199. mg_get_valid_option_names(void)
  1200. {
  1201. /* This function is deprecated. Use mg_get_valid_options instead. */
  1202. static const char *
  1203. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  1204. int i;
  1205. for (i = 0; config_options[i].name != NULL; i++) {
  1206. data[i * 2] = config_options[i].name;
  1207. data[i * 2 + 1] = config_options[i].default_value;
  1208. }
  1209. return data;
  1210. }
  1211. #endif
  1212. const struct mg_option *
  1213. mg_get_valid_options(void)
  1214. {
  1215. return config_options;
  1216. }
  1217. static int
  1218. is_file_in_memory(struct mg_connection *conn,
  1219. const char *path,
  1220. struct file *filep)
  1221. {
  1222. size_t size = 0;
  1223. if (!conn || !filep) {
  1224. return 0;
  1225. }
  1226. if (conn->ctx->callbacks.open_file) {
  1227. filep->membuf = conn->ctx->callbacks.open_file(conn, path, &size);
  1228. if (filep->membuf != NULL) {
  1229. /* NOTE: override filep->size only on success. Otherwise, it might
  1230. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  1231. filep->size = size;
  1232. }
  1233. }
  1234. return filep->membuf != NULL;
  1235. }
  1236. static int
  1237. is_file_opened(const struct file *filep)
  1238. {
  1239. if (!filep) {
  1240. return 0;
  1241. }
  1242. return filep->membuf != NULL || filep->fp != NULL;
  1243. }
  1244. static int
  1245. mg_fopen(struct mg_connection *conn,
  1246. const char *path,
  1247. const char *mode,
  1248. struct file *filep)
  1249. {
  1250. if (!filep) {
  1251. return 0;
  1252. }
  1253. memset(filep, 0, sizeof(*filep));
  1254. if (!is_file_in_memory(conn, path, filep)) {
  1255. #ifdef _WIN32
  1256. wchar_t wbuf[PATH_MAX], wmode[20];
  1257. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  1258. MultiByteToWideChar(CP_UTF8, 0, mode, -1, wmode, ARRAY_SIZE(wmode));
  1259. filep->fp = _wfopen(wbuf, wmode);
  1260. #else
  1261. filep->fp = fopen(path, mode);
  1262. #endif
  1263. }
  1264. return is_file_opened(filep);
  1265. }
  1266. static void
  1267. mg_fclose(struct file *filep)
  1268. {
  1269. if (filep != NULL && filep->fp != NULL) {
  1270. fclose(filep->fp);
  1271. }
  1272. }
  1273. static void
  1274. mg_strlcpy(register char *dst, register const char *src, size_t n)
  1275. {
  1276. for (; *src != '\0' && n > 1; n--) {
  1277. *dst++ = *src++;
  1278. }
  1279. *dst = '\0';
  1280. }
  1281. static int
  1282. lowercase(const char *s)
  1283. {
  1284. return tolower(*(const unsigned char *)s);
  1285. }
  1286. int
  1287. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  1288. {
  1289. int diff = 0;
  1290. if (len > 0) {
  1291. do {
  1292. diff = lowercase(s1++) - lowercase(s2++);
  1293. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  1294. }
  1295. return diff;
  1296. }
  1297. static int
  1298. mg_strcasecmp(const char *s1, const char *s2)
  1299. {
  1300. int diff;
  1301. do {
  1302. diff = lowercase(s1++) - lowercase(s2++);
  1303. } while (diff == 0 && s1[-1] != '\0');
  1304. return diff;
  1305. }
  1306. static char *
  1307. mg_strndup(const char *ptr, size_t len)
  1308. {
  1309. char *p;
  1310. if ((p = (char *)mg_malloc(len + 1)) != NULL) {
  1311. mg_strlcpy(p, ptr, len + 1);
  1312. }
  1313. return p;
  1314. }
  1315. static char *
  1316. mg_strdup(const char *str)
  1317. {
  1318. return mg_strndup(str, strlen(str));
  1319. }
  1320. static const char *
  1321. mg_strcasestr(const char *big_str, const char *small_str)
  1322. {
  1323. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  1324. if (big_len >= small_len) {
  1325. for (i = 0; i <= (big_len - small_len); i++) {
  1326. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  1327. return big_str + i;
  1328. }
  1329. }
  1330. }
  1331. return NULL;
  1332. }
  1333. /* Return null terminated string of given maximum length.
  1334. * Report errors if length is exceeded. */
  1335. static void
  1336. mg_vsnprintf(const struct mg_connection *conn,
  1337. int *truncated,
  1338. char *buf,
  1339. size_t buflen,
  1340. const char *fmt,
  1341. va_list ap)
  1342. {
  1343. int n, ok;
  1344. if (buflen == 0) {
  1345. return;
  1346. }
  1347. #ifdef __clang__
  1348. #pragma clang diagnostic push
  1349. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  1350. /* Using fmt as a non-literal is intended here, since it is mostly called
  1351. * indirectly by mg_snprintf */
  1352. #endif
  1353. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  1354. ok = (n >= 0) && ((size_t)n < buflen);
  1355. #ifdef __clang__
  1356. #pragma clang diagnostic pop
  1357. #endif
  1358. if (ok) {
  1359. if (truncated) {
  1360. *truncated = 0;
  1361. }
  1362. } else {
  1363. if (truncated) {
  1364. *truncated = 1;
  1365. }
  1366. mg_cry(conn,
  1367. "truncating vsnprintf buffer: [%.*s]",
  1368. (int)((buflen > 200) ? 200 : (buflen - 1)),
  1369. buf);
  1370. n = (int)buflen - 1;
  1371. }
  1372. buf[n] = '\0';
  1373. }
  1374. static void
  1375. mg_snprintf(const struct mg_connection *conn,
  1376. int *truncated,
  1377. char *buf,
  1378. size_t buflen,
  1379. const char *fmt,
  1380. ...)
  1381. {
  1382. va_list ap;
  1383. va_start(ap, fmt);
  1384. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  1385. va_end(ap);
  1386. }
  1387. static int
  1388. get_option_index(const char *name)
  1389. {
  1390. int i;
  1391. for (i = 0; config_options[i].name != NULL; i++) {
  1392. if (strcmp(config_options[i].name, name) == 0) {
  1393. return i;
  1394. }
  1395. }
  1396. return -1;
  1397. }
  1398. const char *
  1399. mg_get_option(const struct mg_context *ctx, const char *name)
  1400. {
  1401. int i;
  1402. if ((i = get_option_index(name)) == -1) {
  1403. return NULL;
  1404. } else if (!ctx || ctx->config[i] == NULL) {
  1405. return "";
  1406. } else {
  1407. return ctx->config[i];
  1408. }
  1409. }
  1410. struct mg_context *
  1411. mg_get_context(const struct mg_connection *conn)
  1412. {
  1413. return (conn == NULL) ? (struct mg_context *)NULL : (conn->ctx);
  1414. }
  1415. void *
  1416. mg_get_user_data(const struct mg_context *ctx)
  1417. {
  1418. return (ctx == NULL) ? NULL : ctx->user_data;
  1419. }
  1420. void
  1421. mg_set_user_connection_data(const struct mg_connection *conn, void *data)
  1422. {
  1423. if (conn != NULL) {
  1424. ((struct mg_connection *)conn)->request_info.conn_data = data;
  1425. }
  1426. }
  1427. void *
  1428. mg_get_user_connection_data(const struct mg_connection *conn)
  1429. {
  1430. if (conn != NULL) {
  1431. return conn->request_info.conn_data;
  1432. }
  1433. return NULL;
  1434. }
  1435. size_t
  1436. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  1437. {
  1438. size_t i;
  1439. if (!ctx) {
  1440. return 0;
  1441. }
  1442. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  1443. ssl[i] = ctx->listening_sockets[i].is_ssl;
  1444. ports[i] = ctx->listening_ports[i];
  1445. }
  1446. return i;
  1447. }
  1448. int
  1449. mg_get_server_ports(const struct mg_context *ctx,
  1450. int size,
  1451. struct mg_server_ports *ports)
  1452. {
  1453. int i, cnt = 0;
  1454. if (size <= 0) {
  1455. return -1;
  1456. }
  1457. memset(ports, 0, sizeof(*ports) * (size_t)size);
  1458. if (!ctx) {
  1459. return -1;
  1460. }
  1461. if (!ctx->listening_sockets || !ctx->listening_ports) {
  1462. return -1;
  1463. }
  1464. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  1465. ports[cnt].port = ctx->listening_ports[i];
  1466. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  1467. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  1468. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  1469. /* IPv4 */
  1470. ports[cnt].protocol = 1;
  1471. cnt++;
  1472. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  1473. /* IPv6 */
  1474. ports[cnt].protocol = 3;
  1475. cnt++;
  1476. }
  1477. }
  1478. return cnt;
  1479. }
  1480. static void
  1481. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  1482. {
  1483. buf[0] = '\0';
  1484. if (!usa) {
  1485. return;
  1486. }
  1487. if (usa->sa.sa_family == AF_INET) {
  1488. getnameinfo(&usa->sa,
  1489. sizeof(usa->sin),
  1490. buf,
  1491. (unsigned)len,
  1492. NULL,
  1493. 0,
  1494. NI_NUMERICHOST);
  1495. }
  1496. #if defined(USE_IPV6)
  1497. else if (usa->sa.sa_family == AF_INET6) {
  1498. getnameinfo(&usa->sa,
  1499. sizeof(usa->sin6),
  1500. buf,
  1501. (unsigned)len,
  1502. NULL,
  1503. 0,
  1504. NI_NUMERICHOST);
  1505. }
  1506. #endif
  1507. }
  1508. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  1509. * included in all responses other than 100, 101, 5xx. */
  1510. static void
  1511. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  1512. {
  1513. struct tm *tm;
  1514. tm = gmtime(t);
  1515. if (tm != NULL) {
  1516. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  1517. } else {
  1518. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  1519. buf[buf_len - 1] = '\0';
  1520. }
  1521. }
  1522. /* difftime for struct timespec. Return value is in seconds. */
  1523. static double
  1524. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  1525. {
  1526. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  1527. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  1528. }
  1529. /* Print error message to the opened error log stream. */
  1530. void
  1531. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  1532. {
  1533. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  1534. va_list ap;
  1535. FILE *fp;
  1536. time_t timestamp;
  1537. va_start(ap, fmt);
  1538. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  1539. va_end(ap);
  1540. buf[sizeof(buf) - 1] = 0;
  1541. /* Do not lock when getting the callback value, here and below.
  1542. * I suppose this is fine, since function cannot disappear in the
  1543. * same way string option can. */
  1544. if (conn && (conn->ctx->callbacks.log_message == NULL
  1545. || conn->ctx->callbacks.log_message(conn, buf) == 0)) {
  1546. fp = conn->ctx->config[ERROR_LOG_FILE] == NULL
  1547. ? NULL
  1548. : fopen(conn->ctx->config[ERROR_LOG_FILE], "a+");
  1549. if (fp != NULL) {
  1550. flockfile(fp);
  1551. timestamp = time(NULL);
  1552. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  1553. fprintf(fp,
  1554. "[%010lu] [error] [client %s] ",
  1555. (unsigned long)timestamp,
  1556. src_addr);
  1557. if (conn->request_info.request_method != NULL) {
  1558. fprintf(fp,
  1559. "%s %s: ",
  1560. conn->request_info.request_method,
  1561. conn->request_info.request_uri);
  1562. }
  1563. fprintf(fp, "%s", buf);
  1564. fputc('\n', fp);
  1565. funlockfile(fp);
  1566. fclose(fp);
  1567. }
  1568. }
  1569. }
  1570. /* Return fake connection structure. Used for logging, if connection
  1571. * is not applicable at the moment of logging. */
  1572. static struct mg_connection *
  1573. fc(struct mg_context *ctx)
  1574. {
  1575. static struct mg_connection fake_connection;
  1576. fake_connection.ctx = ctx;
  1577. return &fake_connection;
  1578. }
  1579. const char *
  1580. mg_version(void)
  1581. {
  1582. return CIVETWEB_VERSION;
  1583. }
  1584. const struct mg_request_info *
  1585. mg_get_request_info(const struct mg_connection *conn)
  1586. {
  1587. if (!conn) {
  1588. return NULL;
  1589. }
  1590. return &conn->request_info;
  1591. }
  1592. /* Skip the characters until one of the delimiters characters found.
  1593. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  1594. * Advance pointer to buffer to the next word. Return found 0-terminated word.
  1595. * Delimiters can be quoted with quotechar. */
  1596. static char *
  1597. skip_quoted(char **buf,
  1598. const char *delimiters,
  1599. const char *whitespace,
  1600. char quotechar)
  1601. {
  1602. char *p, *begin_word, *end_word, *end_whitespace;
  1603. begin_word = *buf;
  1604. end_word = begin_word + strcspn(begin_word, delimiters);
  1605. /* Check for quotechar */
  1606. if (end_word > begin_word) {
  1607. p = end_word - 1;
  1608. while (*p == quotechar) {
  1609. /* While the delimiter is quoted, look for the next delimiter. */
  1610. /* This happens, e.g., in calls from parse_auth_header,
  1611. * if the user name contains a " character. */
  1612. /* If there is anything beyond end_word, copy it. */
  1613. if (*end_word != '\0') {
  1614. size_t end_off = strcspn(end_word + 1, delimiters);
  1615. memmove(p, end_word, end_off + 1);
  1616. p += end_off; /* p must correspond to end_word - 1 */
  1617. end_word += end_off + 1;
  1618. } else {
  1619. *p = '\0';
  1620. break;
  1621. }
  1622. }
  1623. for (p++; p < end_word; p++) {
  1624. *p = '\0';
  1625. }
  1626. }
  1627. if (*end_word == '\0') {
  1628. *buf = end_word;
  1629. } else {
  1630. end_whitespace = end_word + 1 + strspn(end_word + 1, whitespace);
  1631. for (p = end_word; p < end_whitespace; p++) {
  1632. *p = '\0';
  1633. }
  1634. *buf = end_whitespace;
  1635. }
  1636. return begin_word;
  1637. }
  1638. /* Simplified version of skip_quoted without quote char
  1639. * and whitespace == delimiters */
  1640. static char *
  1641. skip(char **buf, const char *delimiters)
  1642. {
  1643. return skip_quoted(buf, delimiters, delimiters, 0);
  1644. }
  1645. /* Return HTTP header value, or NULL if not found. */
  1646. static const char *
  1647. get_header(const struct mg_request_info *ri, const char *name)
  1648. {
  1649. int i;
  1650. if (ri) {
  1651. for (i = 0; i < ri->num_headers; i++) {
  1652. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  1653. return ri->http_headers[i].value;
  1654. }
  1655. }
  1656. }
  1657. return NULL;
  1658. }
  1659. const char *
  1660. mg_get_header(const struct mg_connection *conn, const char *name)
  1661. {
  1662. if (!conn) {
  1663. return NULL;
  1664. }
  1665. return get_header(&conn->request_info, name);
  1666. }
  1667. /* A helper function for traversing a comma separated list of values.
  1668. * It returns a list pointer shifted to the next value, or NULL if the end
  1669. * of the list found.
  1670. * Value is stored in val vector. If value has form "x=y", then eq_val
  1671. * vector is initialized to point to the "y" part, and val vector length
  1672. * is adjusted to point only to "x". */
  1673. static const char *
  1674. next_option(const char *list, struct vec *val, struct vec *eq_val)
  1675. {
  1676. if (val == NULL || list == NULL || *list == '\0') {
  1677. /* End of the list */
  1678. list = NULL;
  1679. } else {
  1680. val->ptr = list;
  1681. if ((list = strchr(val->ptr, ',')) != NULL) {
  1682. /* Comma found. Store length and shift the list ptr */
  1683. val->len = ((size_t)(list - val->ptr));
  1684. list++;
  1685. } else {
  1686. /* This value is the last one */
  1687. list = val->ptr + strlen(val->ptr);
  1688. val->len = ((size_t)(list - val->ptr));
  1689. }
  1690. if (eq_val != NULL) {
  1691. /* Value has form "x=y", adjust pointers and lengths
  1692. * so that val points to "x", and eq_val points to "y". */
  1693. eq_val->len = 0;
  1694. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  1695. if (eq_val->ptr != NULL) {
  1696. eq_val->ptr++; /* Skip over '=' character */
  1697. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  1698. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  1699. }
  1700. }
  1701. }
  1702. return list;
  1703. }
  1704. /* Perform case-insensitive match of string against pattern */
  1705. static int
  1706. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  1707. {
  1708. const char *or_str;
  1709. size_t i;
  1710. int j, len, res;
  1711. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  1712. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  1713. return res > 0 ? res : match_prefix(or_str + 1,
  1714. (size_t)((pattern + pattern_len)
  1715. - (or_str + 1)),
  1716. str);
  1717. }
  1718. for (i = 0, j = 0; i < pattern_len; i++, j++) {
  1719. if (pattern[i] == '?' && str[j] != '\0') {
  1720. continue;
  1721. } else if (pattern[i] == '$') {
  1722. return str[j] == '\0' ? j : -1;
  1723. } else if (pattern[i] == '*') {
  1724. i++;
  1725. if (pattern[i] == '*') {
  1726. i++;
  1727. len = (int)strlen(str + j);
  1728. } else {
  1729. len = (int)strcspn(str + j, "/");
  1730. }
  1731. if (i == pattern_len) {
  1732. return j + len;
  1733. }
  1734. do {
  1735. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  1736. } while (res == -1 && len-- > 0);
  1737. return res == -1 ? -1 : j + res + len;
  1738. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  1739. return -1;
  1740. }
  1741. }
  1742. return j;
  1743. }
  1744. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  1745. * This function must tolerate situations when connection info is not
  1746. * set up, for example if request parsing failed. */
  1747. static int
  1748. should_keep_alive(const struct mg_connection *conn)
  1749. {
  1750. if (conn != NULL) {
  1751. const char *http_version = conn->request_info.http_version;
  1752. const char *header = mg_get_header(conn, "Connection");
  1753. if (conn->must_close || conn->internal_error || conn->status_code == 401
  1754. || mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0
  1755. || (header != NULL && mg_strcasecmp(header, "keep-alive") != 0)
  1756. || (header == NULL && http_version
  1757. && 0 != strcmp(http_version, "1.1"))) {
  1758. return 0;
  1759. }
  1760. return 1;
  1761. }
  1762. return 0;
  1763. }
  1764. static int
  1765. should_decode_url(const struct mg_connection *conn)
  1766. {
  1767. if (!conn || !conn->ctx) {
  1768. return 0;
  1769. }
  1770. return (mg_strcasecmp(conn->ctx->config[DECODE_URL], "yes") == 0);
  1771. }
  1772. static const char *
  1773. suggest_connection_header(const struct mg_connection *conn)
  1774. {
  1775. return should_keep_alive(conn) ? "keep-alive" : "close";
  1776. }
  1777. static void handle_file_based_request(struct mg_connection *conn,
  1778. const char *path,
  1779. struct file *filep);
  1780. static int
  1781. mg_stat(struct mg_connection *conn, const char *path, struct file *filep);
  1782. static const char *
  1783. mg_get_response_code_text(int response_code, struct mg_connection *conn)
  1784. {
  1785. switch (response_code) {
  1786. /* RFC2616 Section 10.1 - Informational 1xx */
  1787. case 100:
  1788. return "Continue"; /* RFC2616 Section 10.1.1 */
  1789. case 101:
  1790. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  1791. case 102:
  1792. return "Processing"; /* RFC2518 Section 10.1 */
  1793. /* RFC2616 Section 10.2 - Successful 2xx */
  1794. case 200:
  1795. return "OK"; /* RFC2616 Section 10.2.1 */
  1796. case 201:
  1797. return "Created"; /* RFC2616 Section 10.2.2 */
  1798. case 202:
  1799. return "Accepted"; /* RFC2616 Section 10.2.3 */
  1800. case 203:
  1801. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  1802. case 204:
  1803. return "No Content"; /* RFC2616 Section 10.2.5 */
  1804. case 205:
  1805. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  1806. case 206:
  1807. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  1808. case 207:
  1809. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1 */
  1810. /* RFC2616 Section 10.3 - Redirection 3xx */
  1811. case 300:
  1812. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  1813. case 301:
  1814. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  1815. case 302:
  1816. return "Found"; /* RFC2616 Section 10.3.3 */
  1817. case 303:
  1818. return "See Other"; /* RFC2616 Section 10.3.4 */
  1819. case 304:
  1820. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  1821. case 305:
  1822. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  1823. case 307:
  1824. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  1825. /* RFC2616 Section 10.4 - Client Error 4xx */
  1826. case 400:
  1827. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  1828. case 401:
  1829. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  1830. case 402:
  1831. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  1832. case 403:
  1833. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  1834. case 404:
  1835. return "Not Found"; /* RFC2616 Section 10.4.5 */
  1836. case 405:
  1837. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  1838. case 406:
  1839. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  1840. case 407:
  1841. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  1842. case 408:
  1843. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  1844. case 409:
  1845. return "Conflict"; /* RFC2616 Section 10.4.10 */
  1846. case 410:
  1847. return "Gone"; /* RFC2616 Section 10.4.11 */
  1848. case 411:
  1849. return "Length Required"; /* RFC2616 Section 10.4.12 */
  1850. case 412:
  1851. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  1852. case 413:
  1853. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  1854. case 414:
  1855. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  1856. case 415:
  1857. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  1858. case 416:
  1859. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17 */
  1860. case 417:
  1861. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  1862. case 422:
  1863. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  1864. * Section 11.2 */
  1865. case 423:
  1866. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  1867. case 424:
  1868. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  1869. * Section 11.4 */
  1870. case 428:
  1871. return "Precondition Required"; /* RFC 6585, Section 3 */
  1872. case 429:
  1873. return "Too Many Requests"; /* RFC 6585, Section 4 */
  1874. case 431:
  1875. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  1876. /* RFC2616 Section 10.5 - Server Error 5xx */
  1877. case 500:
  1878. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  1879. case 501:
  1880. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  1881. case 502:
  1882. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  1883. case 503:
  1884. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  1885. case 504:
  1886. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  1887. case 505:
  1888. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  1889. case 507:
  1890. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  1891. * Section 11.5 */
  1892. case 511:
  1893. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  1894. /* Other RFCs */
  1895. case 426:
  1896. return "Upgrade Required"; /* RFC 2817 */
  1897. /* Return codes from non normative RFCs: */
  1898. /* Informative and experimental RFCs, "de facto" standards due to common
  1899. * use, ... */
  1900. case 208:
  1901. return "Already Reported"; /* RFC5842 Section 7.1 */
  1902. case 226:
  1903. return "IM used"; /* RFC3229 Section 10.4.1 */
  1904. case 308:
  1905. return "Permanent Redirect"; /* RFC7238 Section 3 */
  1906. case 418:
  1907. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  1908. case 419:
  1909. return "Authentication Timeout"; /* common use */
  1910. case 451:
  1911. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  1912. * Section 3 */
  1913. case 506:
  1914. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  1915. case 508:
  1916. return "Loop Detected"; /* RFC5842 Section 7.1 */
  1917. case 510:
  1918. return "Not Extended"; /* RFC 2774, Section 7 */
  1919. default:
  1920. /* This error code is unknown. This should not happen. */
  1921. if (conn) {
  1922. mg_cry(conn, "Unknown HTTP response code: %u", response_code);
  1923. }
  1924. /* Return at least a category according to RFC 2616 Section 10. */
  1925. if (response_code >= 100 && response_code < 200) {
  1926. /* Unknown informational status code */
  1927. return "Information";
  1928. }
  1929. if (response_code >= 200 && response_code < 300) {
  1930. /* Unknown success code */
  1931. return "Success";
  1932. }
  1933. if (response_code >= 300 && response_code < 400) {
  1934. /* Unknown redirection code */
  1935. return "Redirection";
  1936. }
  1937. if (response_code >= 400 && response_code < 500) {
  1938. /* Unknown request error code */
  1939. return "Client Error";
  1940. }
  1941. if (response_code >= 500 && response_code < 600) {
  1942. /* Unknown server error code */
  1943. return "Server Error";
  1944. }
  1945. /* Response code not even within reasonable range */
  1946. return "";
  1947. }
  1948. }
  1949. static void send_http_error(struct mg_connection *,
  1950. int,
  1951. PRINTF_FORMAT_STRING(const char *fmt),
  1952. ...) PRINTF_ARGS(3, 4);
  1953. static void
  1954. send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  1955. {
  1956. char buf[MG_BUF_LEN];
  1957. va_list ap;
  1958. int len, i, page_handler_found, scope, truncated;
  1959. char date[64];
  1960. time_t curtime = time(NULL);
  1961. const char *error_handler = NULL;
  1962. struct file error_page_file = STRUCT_FILE_INITIALIZER;
  1963. const char *error_page_file_ext, *tstr;
  1964. const char *status_text = mg_get_response_code_text(status, conn);
  1965. if (conn == NULL) {
  1966. return;
  1967. }
  1968. conn->status_code = status;
  1969. if (conn->in_error_handler || conn->ctx->callbacks.http_error == NULL
  1970. || conn->ctx->callbacks.http_error(conn, status)) {
  1971. if (!conn->in_error_handler) {
  1972. /* Send user defined error pages, if defined */
  1973. error_handler = conn->ctx->config[ERROR_PAGES];
  1974. error_page_file_ext = conn->ctx->config[INDEX_FILES];
  1975. page_handler_found = 0;
  1976. if (error_handler != NULL) {
  1977. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  1978. switch (scope) {
  1979. case 1: /* Handler for specific error, e.g. 404 error */
  1980. mg_snprintf(conn,
  1981. &truncated,
  1982. buf,
  1983. sizeof(buf) - 32,
  1984. "%serror%03u.",
  1985. error_handler,
  1986. status);
  1987. break;
  1988. case 2: /* Handler for error group, e.g., 5xx error handler
  1989. * for all server errors (500-599) */
  1990. mg_snprintf(conn,
  1991. &truncated,
  1992. buf,
  1993. sizeof(buf) - 32,
  1994. "%serror%01uxx.",
  1995. error_handler,
  1996. status / 100);
  1997. break;
  1998. default: /* Handler for all errors */
  1999. mg_snprintf(conn,
  2000. &truncated,
  2001. buf,
  2002. sizeof(buf) - 32,
  2003. "%serror.",
  2004. error_handler);
  2005. break;
  2006. }
  2007. /* String truncation in buf may only occur if error_handler
  2008. * is too long. This string is from the config, not from a
  2009. * client. */
  2010. (void)truncated;
  2011. len = (int)strlen(buf);
  2012. tstr = strchr(error_page_file_ext, '.');
  2013. while (tstr) {
  2014. for (i = 1; i < 32 && tstr[i] != 0 && tstr[i] != ',';
  2015. i++)
  2016. buf[len + i - 1] = tstr[i];
  2017. buf[len + i - 1] = 0;
  2018. if (mg_stat(conn, buf, &error_page_file)) {
  2019. page_handler_found = 1;
  2020. break;
  2021. }
  2022. tstr = strchr(tstr + i, '.');
  2023. }
  2024. }
  2025. }
  2026. if (page_handler_found) {
  2027. conn->in_error_handler = 1;
  2028. handle_file_based_request(conn, buf, &error_page_file);
  2029. conn->in_error_handler = 0;
  2030. return;
  2031. }
  2032. }
  2033. /* No custom error page. Send default error page. */
  2034. gmt_time_string(date, sizeof(date), &curtime);
  2035. conn->must_close = 1;
  2036. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  2037. mg_printf(conn,
  2038. "Date: %s\r\n"
  2039. "Cache-Control: no-cache\r\n"
  2040. "Connection: close\r\n\r\n",
  2041. date);
  2042. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  2043. if (status > 199 && status != 204 && status != 304) {
  2044. mg_printf(conn, "Error %d: %s\n", status, status_text);
  2045. if (fmt != NULL) {
  2046. va_start(ap, fmt);
  2047. mg_vsnprintf(conn, NULL, buf, sizeof(buf), fmt, ap);
  2048. va_end(ap);
  2049. mg_write(conn, buf, strlen(buf));
  2050. DEBUG_TRACE("Error %i - [%s]", status, buf);
  2051. }
  2052. } else {
  2053. /* No body allowed. Close the connection. */
  2054. DEBUG_TRACE("Error %i", status);
  2055. }
  2056. }
  2057. }
  2058. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  2059. /* Create substitutes for POSIX functions in Win32. */
  2060. #if defined(__MINGW32__)
  2061. /* Show no warning in case system functions are not used. */
  2062. #pragma GCC diagnostic push
  2063. #pragma GCC diagnostic ignored "-Wunused-function"
  2064. #endif
  2065. static int
  2066. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  2067. {
  2068. (void)unused;
  2069. *mutex = CreateMutex(NULL, FALSE, NULL);
  2070. return *mutex == NULL ? -1 : 0;
  2071. }
  2072. static int
  2073. pthread_mutex_destroy(pthread_mutex_t *mutex)
  2074. {
  2075. return CloseHandle(*mutex) == 0 ? -1 : 0;
  2076. }
  2077. static int
  2078. pthread_mutex_lock(pthread_mutex_t *mutex)
  2079. {
  2080. return WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0 ? 0 : -1;
  2081. }
  2082. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  2083. static int
  2084. pthread_mutex_trylock(pthread_mutex_t *mutex)
  2085. {
  2086. switch (WaitForSingleObject(*mutex, 0)) {
  2087. case WAIT_OBJECT_0:
  2088. return 0;
  2089. case WAIT_TIMEOUT:
  2090. return -2; /* EBUSY */
  2091. }
  2092. return -1;
  2093. }
  2094. #endif
  2095. static int
  2096. pthread_mutex_unlock(pthread_mutex_t *mutex)
  2097. {
  2098. return ReleaseMutex(*mutex) == 0 ? -1 : 0;
  2099. }
  2100. #ifndef WIN_PTHREADS_TIME_H
  2101. static int
  2102. clock_gettime(clockid_t clk_id, struct timespec *tp)
  2103. {
  2104. FILETIME ft;
  2105. ULARGE_INTEGER li;
  2106. BOOL ok = FALSE;
  2107. double d;
  2108. static double perfcnt_per_sec = 0.0;
  2109. if (tp) {
  2110. memset(tp, 0, sizeof(*tp));
  2111. if (clk_id == CLOCK_REALTIME) {
  2112. GetSystemTimeAsFileTime(&ft);
  2113. li.LowPart = ft.dwLowDateTime;
  2114. li.HighPart = ft.dwHighDateTime;
  2115. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  2116. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  2117. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  2118. ok = TRUE;
  2119. } else if (clk_id == CLOCK_MONOTONIC) {
  2120. if (perfcnt_per_sec == 0.0) {
  2121. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  2122. perfcnt_per_sec = 1.0 / li.QuadPart;
  2123. }
  2124. if (perfcnt_per_sec != 0.0) {
  2125. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  2126. d = li.QuadPart * perfcnt_per_sec;
  2127. tp->tv_sec = (time_t)d;
  2128. d -= tp->tv_sec;
  2129. tp->tv_nsec = (long)(d * 1.0E9);
  2130. ok = TRUE;
  2131. }
  2132. }
  2133. }
  2134. return ok ? 0 : -1;
  2135. }
  2136. #endif
  2137. static int
  2138. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  2139. {
  2140. (void)unused;
  2141. InitializeCriticalSection(&cv->threadIdSec);
  2142. cv->waitingthreadcount = 0;
  2143. cv->waitingthreadhdls =
  2144. (pthread_t *)mg_calloc(MAX_WORKER_THREADS, sizeof(pthread_t));
  2145. return (cv->waitingthreadhdls != NULL) ? 0 : -1;
  2146. }
  2147. static int
  2148. pthread_cond_timedwait(pthread_cond_t *cv,
  2149. pthread_mutex_t *mutex,
  2150. const struct timespec *abstime)
  2151. {
  2152. struct mg_workerTLS *tls =
  2153. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2154. int ok;
  2155. struct timespec tsnow;
  2156. int64_t nsnow, nswaitabs, nswaitrel;
  2157. DWORD mswaitrel;
  2158. EnterCriticalSection(&cv->threadIdSec);
  2159. assert(cv->waitingthreadcount < MAX_WORKER_THREADS);
  2160. cv->waitingthreadhdls[cv->waitingthreadcount] =
  2161. tls->pthread_cond_helper_mutex;
  2162. cv->waitingthreadcount++;
  2163. LeaveCriticalSection(&cv->threadIdSec);
  2164. if (abstime) {
  2165. clock_gettime(CLOCK_REALTIME, &tsnow);
  2166. nsnow = (((int64_t)tsnow.tv_sec) * 1000000000) + tsnow.tv_nsec;
  2167. nswaitabs =
  2168. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  2169. nswaitrel = nswaitabs - nsnow;
  2170. if (nswaitrel < 0) {
  2171. nswaitrel = 0;
  2172. }
  2173. mswaitrel = (DWORD)(nswaitrel / 1000000);
  2174. } else {
  2175. mswaitrel = INFINITE;
  2176. }
  2177. pthread_mutex_unlock(mutex);
  2178. ok = (WAIT_OBJECT_0
  2179. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  2180. pthread_mutex_lock(mutex);
  2181. return ok ? 0 : -1;
  2182. }
  2183. static int
  2184. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  2185. {
  2186. return pthread_cond_timedwait(cv, mutex, NULL);
  2187. }
  2188. static int
  2189. pthread_cond_signal(pthread_cond_t *cv)
  2190. {
  2191. int i;
  2192. HANDLE wkup = NULL;
  2193. BOOL ok = FALSE;
  2194. EnterCriticalSection(&cv->threadIdSec);
  2195. if (cv->waitingthreadcount) {
  2196. wkup = cv->waitingthreadhdls[0];
  2197. ok = SetEvent(wkup);
  2198. for (i = 1; i < cv->waitingthreadcount; i++) {
  2199. cv->waitingthreadhdls[i - 1] = cv->waitingthreadhdls[i];
  2200. }
  2201. cv->waitingthreadcount--;
  2202. assert(ok);
  2203. }
  2204. LeaveCriticalSection(&cv->threadIdSec);
  2205. return ok ? 0 : 1;
  2206. }
  2207. static int
  2208. pthread_cond_broadcast(pthread_cond_t *cv)
  2209. {
  2210. EnterCriticalSection(&cv->threadIdSec);
  2211. while (cv->waitingthreadcount) {
  2212. pthread_cond_signal(cv);
  2213. }
  2214. LeaveCriticalSection(&cv->threadIdSec);
  2215. return 0;
  2216. }
  2217. static int
  2218. pthread_cond_destroy(pthread_cond_t *cv)
  2219. {
  2220. EnterCriticalSection(&cv->threadIdSec);
  2221. assert(cv->waitingthreadcount == 0);
  2222. mg_free(cv->waitingthreadhdls);
  2223. cv->waitingthreadhdls = 0;
  2224. LeaveCriticalSection(&cv->threadIdSec);
  2225. DeleteCriticalSection(&cv->threadIdSec);
  2226. return 0;
  2227. }
  2228. #if defined(__MINGW32__)
  2229. /* Enable unused function warning again */
  2230. #pragma GCC diagnostic pop
  2231. #endif
  2232. /* For Windows, change all slashes to backslashes in path names. */
  2233. static void
  2234. change_slashes_to_backslashes(char *path)
  2235. {
  2236. int i;
  2237. for (i = 0; path[i] != '\0'; i++) {
  2238. if (path[i] == '/') {
  2239. path[i] = '\\';
  2240. }
  2241. /* remove double backslash (check i > 0 to preserve UNC paths,
  2242. * like \\server\file.txt) */
  2243. if ((path[i] == '\\') && (i > 0)) {
  2244. while (path[i + 1] == '\\' || path[i + 1] == '/') {
  2245. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  2246. }
  2247. }
  2248. }
  2249. }
  2250. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  2251. * wbuf and wbuf_len is a target buffer and its length. */
  2252. static void
  2253. to_unicode(const char *path, wchar_t *wbuf, size_t wbuf_len)
  2254. {
  2255. char buf[PATH_MAX], buf2[PATH_MAX];
  2256. mg_strlcpy(buf, path, sizeof(buf));
  2257. change_slashes_to_backslashes(buf);
  2258. /* Convert to Unicode and back. If doubly-converted string does not
  2259. * match the original, something is fishy, reject. */
  2260. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  2261. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  2262. WideCharToMultiByte(
  2263. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  2264. if (strcmp(buf, buf2) != 0) {
  2265. wbuf[0] = L'\0';
  2266. }
  2267. }
  2268. #if defined(_WIN32_WCE)
  2269. /* Create substitutes for POSIX functions in Win32. */
  2270. #if defined(__MINGW32__)
  2271. /* Show no warning in case system functions are not used. */
  2272. #pragma GCC diagnostic push
  2273. #pragma GCC diagnostic ignored "-Wunused-function"
  2274. #endif
  2275. static time_t
  2276. time(time_t *ptime)
  2277. {
  2278. time_t t;
  2279. SYSTEMTIME st;
  2280. FILETIME ft;
  2281. GetSystemTime(&st);
  2282. SystemTimeToFileTime(&st, &ft);
  2283. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  2284. if (ptime != NULL) {
  2285. *ptime = t;
  2286. }
  2287. return t;
  2288. }
  2289. static struct tm *
  2290. localtime(const time_t *ptime, struct tm *ptm)
  2291. {
  2292. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  2293. FILETIME ft, lft;
  2294. SYSTEMTIME st;
  2295. TIME_ZONE_INFORMATION tzinfo;
  2296. if (ptm == NULL) {
  2297. return NULL;
  2298. }
  2299. *(int64_t *)&ft = t;
  2300. FileTimeToLocalFileTime(&ft, &lft);
  2301. FileTimeToSystemTime(&lft, &st);
  2302. ptm->tm_year = st.wYear - 1900;
  2303. ptm->tm_mon = st.wMonth - 1;
  2304. ptm->tm_wday = st.wDayOfWeek;
  2305. ptm->tm_mday = st.wDay;
  2306. ptm->tm_hour = st.wHour;
  2307. ptm->tm_min = st.wMinute;
  2308. ptm->tm_sec = st.wSecond;
  2309. ptm->tm_yday = 0; /* hope nobody uses this */
  2310. ptm->tm_isdst =
  2311. GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT ? 1 : 0;
  2312. return ptm;
  2313. }
  2314. static struct tm *
  2315. gmtime(const time_t *ptime, struct tm *ptm)
  2316. {
  2317. /* FIXME(lsm): fix this. */
  2318. return localtime(ptime, ptm);
  2319. }
  2320. static size_t
  2321. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  2322. {
  2323. (void)mg_snprintf(NULL, dst, dst_size, "implement strftime() for WinCE");
  2324. return 0;
  2325. }
  2326. #if defined(__MINGW32__)
  2327. /* Enable unused function warning again */
  2328. #pragma GCC diagnostic pop
  2329. #endif
  2330. #endif
  2331. /* Windows happily opens files with some garbage at the end of file name.
  2332. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  2333. * "a.cgi", despite one would expect an error back.
  2334. * This function returns non-0 if path ends with some garbage. */
  2335. static int
  2336. path_cannot_disclose_cgi(const char *path)
  2337. {
  2338. static const char *allowed_last_characters = "_-";
  2339. int last = path[strlen(path) - 1];
  2340. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  2341. }
  2342. static int
  2343. mg_stat(struct mg_connection *conn, const char *path, struct file *filep)
  2344. {
  2345. wchar_t wbuf[PATH_MAX];
  2346. WIN32_FILE_ATTRIBUTE_DATA info;
  2347. time_t creation_time;
  2348. if (!filep) {
  2349. return 0;
  2350. }
  2351. memset(filep, 0, sizeof(*filep));
  2352. if (conn && is_file_in_memory(conn, path, filep)) {
  2353. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  2354. * memset */
  2355. filep->last_modified = time(NULL);
  2356. /* last_modified = now ... assumes the file may change during runtime,
  2357. * so every mg_fopen call may return different data */
  2358. /* last_modified = conn->ctx.start_time;
  2359. * May be used it the data does not change during runtime. This allows
  2360. * browser caching. Since we do not know, we have to assume the file
  2361. * in memory may change. */
  2362. return 1;
  2363. }
  2364. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  2365. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  2366. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  2367. filep->last_modified =
  2368. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  2369. info.ftLastWriteTime.dwHighDateTime);
  2370. /* On Windows, the file creation time can be higher than the
  2371. * modification time, e.g. when a file is copied.
  2372. * Since the Last-Modified timestamp is used for caching
  2373. * it should be based on the most recent timestamp. */
  2374. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  2375. info.ftCreationTime.dwHighDateTime);
  2376. if (creation_time > filep->last_modified) {
  2377. filep->last_modified = creation_time;
  2378. }
  2379. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  2380. /* If file name is fishy, reset the file structure and return
  2381. * error.
  2382. * Note it is important to reset, not just return the error, cause
  2383. * functions like is_file_opened() check the struct. */
  2384. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  2385. memset(filep, 0, sizeof(*filep));
  2386. return 0;
  2387. }
  2388. return 1;
  2389. }
  2390. return 0;
  2391. }
  2392. #if !defined(NO_FILES)
  2393. static int
  2394. mg_remove(const char *path)
  2395. {
  2396. wchar_t wbuf[PATH_MAX];
  2397. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  2398. return DeleteFileW(wbuf) ? 0 : -1;
  2399. }
  2400. static int
  2401. mg_mkdir(const char *path, int mode)
  2402. {
  2403. char buf[PATH_MAX];
  2404. wchar_t wbuf[PATH_MAX];
  2405. (void)mode;
  2406. mg_strlcpy(buf, path, sizeof(buf));
  2407. change_slashes_to_backslashes(buf);
  2408. (void)MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, ARRAY_SIZE(wbuf));
  2409. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  2410. }
  2411. #endif
  2412. /* Create substitutes for POSIX functions in Win32. */
  2413. #if defined(__MINGW32__)
  2414. /* Show no warning in case system functions are not used. */
  2415. #pragma GCC diagnostic push
  2416. #pragma GCC diagnostic ignored "-Wunused-function"
  2417. #endif
  2418. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  2419. static DIR *
  2420. opendir(const char *name)
  2421. {
  2422. DIR *dir = NULL;
  2423. wchar_t wpath[PATH_MAX];
  2424. DWORD attrs;
  2425. if (name == NULL) {
  2426. SetLastError(ERROR_BAD_ARGUMENTS);
  2427. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  2428. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  2429. } else {
  2430. to_unicode(name, wpath, ARRAY_SIZE(wpath));
  2431. attrs = GetFileAttributesW(wpath);
  2432. if (attrs != 0xFFFFFFFF && ((attrs & FILE_ATTRIBUTE_DIRECTORY)
  2433. == FILE_ATTRIBUTE_DIRECTORY)) {
  2434. (void)wcscat(wpath, L"\\*");
  2435. dir->handle = FindFirstFileW(wpath, &dir->info);
  2436. dir->result.d_name[0] = '\0';
  2437. } else {
  2438. mg_free(dir);
  2439. dir = NULL;
  2440. }
  2441. }
  2442. return dir;
  2443. }
  2444. static int
  2445. closedir(DIR *dir)
  2446. {
  2447. int result = 0;
  2448. if (dir != NULL) {
  2449. if (dir->handle != INVALID_HANDLE_VALUE)
  2450. result = FindClose(dir->handle) ? 0 : -1;
  2451. mg_free(dir);
  2452. } else {
  2453. result = -1;
  2454. SetLastError(ERROR_BAD_ARGUMENTS);
  2455. }
  2456. return result;
  2457. }
  2458. static struct dirent *
  2459. readdir(DIR *dir)
  2460. {
  2461. struct dirent *result = 0;
  2462. if (dir) {
  2463. if (dir->handle != INVALID_HANDLE_VALUE) {
  2464. result = &dir->result;
  2465. (void)WideCharToMultiByte(CP_UTF8,
  2466. 0,
  2467. dir->info.cFileName,
  2468. -1,
  2469. result->d_name,
  2470. sizeof(result->d_name),
  2471. NULL,
  2472. NULL);
  2473. if (!FindNextFileW(dir->handle, &dir->info)) {
  2474. (void)FindClose(dir->handle);
  2475. dir->handle = INVALID_HANDLE_VALUE;
  2476. }
  2477. } else {
  2478. SetLastError(ERROR_FILE_NOT_FOUND);
  2479. }
  2480. } else {
  2481. SetLastError(ERROR_BAD_ARGUMENTS);
  2482. }
  2483. return result;
  2484. }
  2485. #ifndef HAVE_POLL
  2486. static int
  2487. poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  2488. {
  2489. struct timeval tv;
  2490. fd_set set;
  2491. unsigned int i;
  2492. int result;
  2493. SOCKET maxfd = 0;
  2494. memset(&tv, 0, sizeof(tv));
  2495. tv.tv_sec = milliseconds / 1000;
  2496. tv.tv_usec = (milliseconds % 1000) * 1000;
  2497. FD_ZERO(&set);
  2498. for (i = 0; i < n; i++) {
  2499. FD_SET((SOCKET)pfd[i].fd, &set);
  2500. pfd[i].revents = 0;
  2501. if (pfd[i].fd > maxfd) {
  2502. maxfd = pfd[i].fd;
  2503. }
  2504. }
  2505. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  2506. for (i = 0; i < n; i++) {
  2507. if (FD_ISSET(pfd[i].fd, &set)) {
  2508. pfd[i].revents = POLLIN;
  2509. }
  2510. }
  2511. }
  2512. return result;
  2513. }
  2514. #endif /* HAVE_POLL */
  2515. #if defined(__MINGW32__)
  2516. /* Enable unused function warning again */
  2517. #pragma GCC diagnostic pop
  2518. #endif
  2519. static void
  2520. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  2521. {
  2522. (void)conn; /* Unused. */
  2523. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  2524. }
  2525. int
  2526. mg_start_thread(mg_thread_func_t f, void *p)
  2527. {
  2528. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  2529. /* Compile-time option to control stack size, e.g. -DUSE_STACK_SIZE=16384
  2530. */
  2531. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  2532. == ((uintptr_t)(-1L)))
  2533. ? -1
  2534. : 0);
  2535. #else
  2536. return (
  2537. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  2538. ? -1
  2539. : 0);
  2540. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  2541. }
  2542. /* Start a thread storing the thread context. */
  2543. static int
  2544. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  2545. void *p,
  2546. pthread_t *threadidptr)
  2547. {
  2548. uintptr_t uip;
  2549. HANDLE threadhandle;
  2550. int result = -1;
  2551. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  2552. threadhandle = (HANDLE)uip;
  2553. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  2554. *threadidptr = threadhandle;
  2555. result = 0;
  2556. }
  2557. return result;
  2558. }
  2559. /* Wait for a thread to finish. */
  2560. static int
  2561. mg_join_thread(pthread_t threadid)
  2562. {
  2563. int result;
  2564. DWORD dwevent;
  2565. result = -1;
  2566. dwevent = WaitForSingleObject(threadid, INFINITE);
  2567. if (dwevent == WAIT_FAILED) {
  2568. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  2569. } else {
  2570. if (dwevent == WAIT_OBJECT_0) {
  2571. CloseHandle(threadid);
  2572. result = 0;
  2573. }
  2574. }
  2575. return result;
  2576. }
  2577. #if !defined(NO_SSL_DL)
  2578. /* Create substitutes for POSIX functions in Win32. */
  2579. #if defined(__MINGW32__)
  2580. /* Show no warning in case system functions are not used. */
  2581. #pragma GCC diagnostic push
  2582. #pragma GCC diagnostic ignored "-Wunused-function"
  2583. #endif
  2584. static HANDLE
  2585. dlopen(const char *dll_name, int flags)
  2586. {
  2587. wchar_t wbuf[PATH_MAX];
  2588. (void)flags;
  2589. to_unicode(dll_name, wbuf, ARRAY_SIZE(wbuf));
  2590. return LoadLibraryW(wbuf);
  2591. }
  2592. static int
  2593. dlclose(void *handle)
  2594. {
  2595. int result;
  2596. if (FreeLibrary((HMODULE)handle) != 0) {
  2597. result = 0;
  2598. } else {
  2599. result = -1;
  2600. }
  2601. return result;
  2602. }
  2603. #if defined(__MINGW32__)
  2604. /* Enable unused function warning again */
  2605. #pragma GCC diagnostic pop
  2606. #endif
  2607. #endif
  2608. #if !defined(NO_CGI)
  2609. #define SIGKILL (0)
  2610. static int
  2611. kill(pid_t pid, int sig_num)
  2612. {
  2613. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  2614. (void)CloseHandle((HANDLE)pid);
  2615. return 0;
  2616. }
  2617. static void
  2618. trim_trailing_whitespaces(char *s)
  2619. {
  2620. char *e = s + strlen(s) - 1;
  2621. while (e > s && isspace(*(unsigned char *)e)) {
  2622. *e-- = '\0';
  2623. }
  2624. }
  2625. static pid_t
  2626. spawn_process(struct mg_connection *conn,
  2627. const char *prog,
  2628. char *envblk,
  2629. char *envp[],
  2630. int fdin,
  2631. int fdout,
  2632. int fderr,
  2633. const char *dir)
  2634. {
  2635. HANDLE me;
  2636. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  2637. cmdline[PATH_MAX], buf[PATH_MAX];
  2638. int truncated;
  2639. struct file file = STRUCT_FILE_INITIALIZER;
  2640. STARTUPINFOA si;
  2641. PROCESS_INFORMATION pi = {0};
  2642. (void)envp;
  2643. memset(&si, 0, sizeof(si));
  2644. si.cb = sizeof(si);
  2645. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  2646. si.wShowWindow = SW_HIDE;
  2647. me = GetCurrentProcess();
  2648. DuplicateHandle(me,
  2649. (HANDLE)_get_osfhandle(fdin),
  2650. me,
  2651. &si.hStdInput,
  2652. 0,
  2653. TRUE,
  2654. DUPLICATE_SAME_ACCESS);
  2655. DuplicateHandle(me,
  2656. (HANDLE)_get_osfhandle(fdout),
  2657. me,
  2658. &si.hStdOutput,
  2659. 0,
  2660. TRUE,
  2661. DUPLICATE_SAME_ACCESS);
  2662. DuplicateHandle(me,
  2663. (HANDLE)_get_osfhandle(fderr),
  2664. me,
  2665. &si.hStdError,
  2666. 0,
  2667. TRUE,
  2668. DUPLICATE_SAME_ACCESS);
  2669. /* If CGI file is a script, try to read the interpreter line */
  2670. interp = conn->ctx->config[CGI_INTERPRETER];
  2671. if (interp == NULL) {
  2672. buf[0] = buf[1] = '\0';
  2673. /* Read the first line of the script into the buffer */
  2674. mg_snprintf(
  2675. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  2676. if (truncated) {
  2677. pi.hProcess = (pid_t)-1;
  2678. goto spawn_cleanup;
  2679. }
  2680. if (mg_fopen(conn, cmdline, "r", &file)) {
  2681. p = (char *)file.membuf;
  2682. mg_fgets(buf, sizeof(buf), &file, &p);
  2683. mg_fclose(&file);
  2684. buf[sizeof(buf) - 1] = '\0';
  2685. }
  2686. if (buf[0] == '#' && buf[1] == '!') {
  2687. trim_trailing_whitespaces(buf + 2);
  2688. } else {
  2689. buf[2] = '\0';
  2690. }
  2691. interp = buf + 2;
  2692. }
  2693. if (interp[0] != '\0') {
  2694. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  2695. interp = full_interp;
  2696. }
  2697. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  2698. if (interp[0] != '\0') {
  2699. mg_snprintf(conn,
  2700. &truncated,
  2701. cmdline,
  2702. sizeof(cmdline),
  2703. "\"%s\" \"%s\\%s\"",
  2704. interp,
  2705. full_dir,
  2706. prog);
  2707. } else {
  2708. mg_snprintf(conn,
  2709. &truncated,
  2710. cmdline,
  2711. sizeof(cmdline),
  2712. "\"%s\\%s\"",
  2713. full_dir,
  2714. prog);
  2715. }
  2716. if (truncated) {
  2717. pi.hProcess = (pid_t)-1;
  2718. goto spawn_cleanup;
  2719. }
  2720. DEBUG_TRACE("Running [%s]", cmdline);
  2721. if (CreateProcessA(NULL,
  2722. cmdline,
  2723. NULL,
  2724. NULL,
  2725. TRUE,
  2726. CREATE_NEW_PROCESS_GROUP,
  2727. envblk,
  2728. NULL,
  2729. &si,
  2730. &pi) == 0) {
  2731. mg_cry(
  2732. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  2733. pi.hProcess = (pid_t)-1;
  2734. /* goto spawn_cleanup; */
  2735. }
  2736. spawn_cleanup:
  2737. (void)CloseHandle(si.hStdOutput);
  2738. (void)CloseHandle(si.hStdError);
  2739. (void)CloseHandle(si.hStdInput);
  2740. if (pi.hThread != NULL) {
  2741. (void)CloseHandle(pi.hThread);
  2742. }
  2743. return (pid_t)pi.hProcess;
  2744. }
  2745. #endif /* !NO_CGI */
  2746. static int
  2747. set_non_blocking_mode(SOCKET sock)
  2748. {
  2749. unsigned long on = 1;
  2750. return ioctlsocket(sock, (long)FIONBIO, &on);
  2751. }
  2752. #else
  2753. static int
  2754. mg_stat(struct mg_connection *conn, const char *path, struct file *filep)
  2755. {
  2756. struct stat st;
  2757. if (!filep) {
  2758. return 0;
  2759. }
  2760. memset(filep, 0, sizeof(*filep));
  2761. if (conn && is_file_in_memory(conn, path, filep)) {
  2762. return 1;
  2763. }
  2764. if (0 == stat(path, &st)) {
  2765. filep->size = (uint64_t)(st.st_size);
  2766. filep->last_modified = st.st_mtime;
  2767. filep->is_directory = S_ISDIR(st.st_mode);
  2768. return 1;
  2769. }
  2770. return 0;
  2771. }
  2772. static void
  2773. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  2774. {
  2775. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  2776. if (conn) {
  2777. mg_cry(conn,
  2778. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  2779. __func__,
  2780. strerror(ERRNO));
  2781. }
  2782. }
  2783. }
  2784. int
  2785. mg_start_thread(mg_thread_func_t func, void *param)
  2786. {
  2787. pthread_t thread_id;
  2788. pthread_attr_t attr;
  2789. int result;
  2790. (void)pthread_attr_init(&attr);
  2791. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  2792. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  2793. /* Compile-time option to control stack size,
  2794. * e.g. -DUSE_STACK_SIZE=16384 */
  2795. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  2796. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  2797. result = pthread_create(&thread_id, &attr, func, param);
  2798. pthread_attr_destroy(&attr);
  2799. return result;
  2800. }
  2801. /* Start a thread storing the thread context. */
  2802. static int
  2803. mg_start_thread_with_id(mg_thread_func_t func,
  2804. void *param,
  2805. pthread_t *threadidptr)
  2806. {
  2807. pthread_t thread_id;
  2808. pthread_attr_t attr;
  2809. int result;
  2810. (void)pthread_attr_init(&attr);
  2811. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  2812. /* Compile-time option to control stack size,
  2813. * e.g. -DUSE_STACK_SIZE=16384 */
  2814. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  2815. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  2816. result = pthread_create(&thread_id, &attr, func, param);
  2817. pthread_attr_destroy(&attr);
  2818. if ((result == 0) && (threadidptr != NULL)) {
  2819. *threadidptr = thread_id;
  2820. }
  2821. return result;
  2822. }
  2823. /* Wait for a thread to finish. */
  2824. static int
  2825. mg_join_thread(pthread_t threadid)
  2826. {
  2827. int result;
  2828. result = pthread_join(threadid, NULL);
  2829. return result;
  2830. }
  2831. #ifndef NO_CGI
  2832. static pid_t
  2833. spawn_process(struct mg_connection *conn,
  2834. const char *prog,
  2835. char *envblk,
  2836. char *envp[],
  2837. int fdin,
  2838. int fdout,
  2839. int fderr,
  2840. const char *dir)
  2841. {
  2842. pid_t pid;
  2843. const char *interp;
  2844. (void)envblk;
  2845. if (conn == NULL) {
  2846. return 0;
  2847. }
  2848. if ((pid = fork()) == -1) {
  2849. /* Parent */
  2850. send_http_error(conn,
  2851. 500,
  2852. "Error: Creating CGI process\nfork(): %s",
  2853. strerror(ERRNO));
  2854. } else if (pid == 0) {
  2855. /* Child */
  2856. if (chdir(dir) != 0) {
  2857. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  2858. } else if (dup2(fdin, 0) == -1) {
  2859. mg_cry(
  2860. conn, "%s: dup2(%d, 0): %s", __func__, fdin, strerror(ERRNO));
  2861. } else if (dup2(fdout, 1) == -1) {
  2862. mg_cry(
  2863. conn, "%s: dup2(%d, 1): %s", __func__, fdout, strerror(ERRNO));
  2864. } else if (dup2(fderr, 2) == -1) {
  2865. mg_cry(
  2866. conn, "%s: dup2(%d, 2): %s", __func__, fderr, strerror(ERRNO));
  2867. } else {
  2868. /* Keep stderr and stdout in two different pipes.
  2869. * Stdout will be sent back to the client,
  2870. * stderr should go into a server error log. */
  2871. (void)close(fdin);
  2872. (void)close(fdout);
  2873. (void)close(fderr);
  2874. /* After exec, all signal handlers are restored to their default
  2875. * values, with one exception of SIGCHLD. According to
  2876. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler will
  2877. * leave unchanged after exec if it was set to be ignored. Restore
  2878. * it to default action. */
  2879. signal(SIGCHLD, SIG_DFL);
  2880. interp = conn->ctx->config[CGI_INTERPRETER];
  2881. if (interp == NULL) {
  2882. (void)execle(prog, prog, NULL, envp);
  2883. mg_cry(conn,
  2884. "%s: execle(%s): %s",
  2885. __func__,
  2886. prog,
  2887. strerror(ERRNO));
  2888. } else {
  2889. (void)execle(interp, interp, prog, NULL, envp);
  2890. mg_cry(conn,
  2891. "%s: execle(%s %s): %s",
  2892. __func__,
  2893. interp,
  2894. prog,
  2895. strerror(ERRNO));
  2896. }
  2897. }
  2898. exit(EXIT_FAILURE);
  2899. }
  2900. return pid;
  2901. }
  2902. #endif /* !NO_CGI */
  2903. static int
  2904. set_non_blocking_mode(SOCKET sock)
  2905. {
  2906. int flags;
  2907. flags = fcntl(sock, F_GETFL, 0);
  2908. (void)fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  2909. return 0;
  2910. }
  2911. #endif /* _WIN32 */
  2912. /* End of initial operating system specific define block. */
  2913. /* Get a random number (independent of C rand function) */
  2914. static uint64_t
  2915. get_random(void)
  2916. {
  2917. static uint64_t lfsr = 0; /* Linear feedback shift register */
  2918. static uint64_t lcg = 0; /* Linear congruential generator */
  2919. struct timespec now;
  2920. memset(&now, 0, sizeof(now));
  2921. clock_gettime(CLOCK_MONOTONIC, &now);
  2922. if (lfsr == 0) {
  2923. /* lfsr will be only 0 if has not been initialized,
  2924. * so this code is called only once. */
  2925. lfsr = (((uint64_t)now.tv_sec) << 21) ^ ((uint64_t)now.tv_nsec)
  2926. ^ ((uint64_t)(ptrdiff_t)&now) ^ ((uint64_t)pthread_self())
  2927. ^ (((uint64_t)time(NULL)) << 33);
  2928. lcg = (((uint64_t)now.tv_sec) << 25) + (uint64_t)now.tv_nsec
  2929. + (uint64_t)(ptrdiff_t)&now;
  2930. } else {
  2931. /* Get the next step of both random number generators. */
  2932. lfsr = (lfsr >> 1)
  2933. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  2934. << 63);
  2935. lcg = lcg * 6364136223846793005 + 1442695040888963407;
  2936. }
  2937. /* Combining two pseudo-random number generators and a high resolution part
  2938. * of the current server time will make it hard (impossible?) to guess the
  2939. * next number. */
  2940. return (lfsr ^ lcg ^ (uint64_t)now.tv_nsec);
  2941. }
  2942. /* Write data to the IO channel - opened file descriptor, socket or SSL
  2943. * descriptor. Return number of bytes written. */
  2944. static int
  2945. push(struct mg_context *ctx,
  2946. FILE *fp,
  2947. SOCKET sock,
  2948. SSL *ssl,
  2949. const char *buf,
  2950. int len,
  2951. double timeout)
  2952. {
  2953. struct timespec start, now;
  2954. int n, err;
  2955. #ifdef _WIN32
  2956. typedef int len_t;
  2957. #else
  2958. typedef size_t len_t;
  2959. #endif
  2960. if (timeout > 0) {
  2961. memset(&start, 0, sizeof(start));
  2962. memset(&now, 0, sizeof(now));
  2963. clock_gettime(CLOCK_MONOTONIC, &start);
  2964. }
  2965. if (ctx == NULL) {
  2966. return -1;
  2967. }
  2968. #ifdef NO_SSL
  2969. if (ssl) {
  2970. return -1;
  2971. }
  2972. #endif
  2973. do {
  2974. #ifndef NO_SSL
  2975. if (ssl != NULL) {
  2976. n = SSL_write(ssl, buf, len);
  2977. if (n <= 0) {
  2978. err = SSL_get_error(ssl, n);
  2979. if ((err == 5 /* SSL_ERROR_SYSCALL */) && (n == -1)) {
  2980. err = ERRNO;
  2981. } else {
  2982. DEBUG_TRACE("SSL_write() failed, error %d", err);
  2983. return -1;
  2984. }
  2985. } else {
  2986. err = 0;
  2987. }
  2988. } else
  2989. #endif
  2990. if (fp != NULL) {
  2991. n = (int)fwrite(buf, 1, (size_t)len, fp);
  2992. if (ferror(fp)) {
  2993. n = -1;
  2994. err = ERRNO;
  2995. } else {
  2996. err = 0;
  2997. }
  2998. } else {
  2999. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  3000. err = (n < 0) ? ERRNO : 0;
  3001. }
  3002. if (ctx->stop_flag) {
  3003. return -1;
  3004. }
  3005. if ((n > 0) || (n == 0 && len == 0)) {
  3006. /* some data has been read, or no data was requested */
  3007. return n;
  3008. }
  3009. if (n == 0) {
  3010. /* shutdown of the socket at client side */
  3011. return -1;
  3012. }
  3013. if (n < 0) {
  3014. /* socket error - check errno */
  3015. DEBUG_TRACE("send() failed, error %d", err);
  3016. /* TODO: error handling depending on the error code.
  3017. * These codes are different between Windows and Linux.
  3018. */
  3019. return -1;
  3020. }
  3021. if (timeout > 0) {
  3022. clock_gettime(CLOCK_MONOTONIC, &now);
  3023. }
  3024. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  3025. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  3026. used */
  3027. return -1;
  3028. }
  3029. static int64_t
  3030. push_all(struct mg_context *ctx,
  3031. FILE *fp,
  3032. SOCKET sock,
  3033. SSL *ssl,
  3034. const char *buf,
  3035. int64_t len)
  3036. {
  3037. double timeout = -1.0;
  3038. int64_t n, nwritten = 0;
  3039. if (ctx == NULL) {
  3040. return -1;
  3041. }
  3042. if (ctx->config[REQUEST_TIMEOUT]) {
  3043. timeout = atoi(ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  3044. }
  3045. while (len > 0 && ctx->stop_flag == 0) {
  3046. n = push(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  3047. if (n < 0) {
  3048. if (nwritten == 0) {
  3049. nwritten = n; /* Propagate the error */
  3050. }
  3051. break;
  3052. } else if (n == 0) {
  3053. break; /* No more data to write */
  3054. } else {
  3055. nwritten += n;
  3056. len -= n;
  3057. }
  3058. }
  3059. return nwritten;
  3060. }
  3061. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  3062. * Return negative value on error, or number of bytes read on success. */
  3063. static int
  3064. pull(FILE *fp, struct mg_connection *conn, char *buf, int len, double timeout)
  3065. {
  3066. int nread, err;
  3067. struct timespec start, now;
  3068. #ifdef _WIN32
  3069. typedef int len_t;
  3070. #else
  3071. typedef size_t len_t;
  3072. #endif
  3073. if (timeout > 0) {
  3074. memset(&start, 0, sizeof(start));
  3075. memset(&now, 0, sizeof(now));
  3076. clock_gettime(CLOCK_MONOTONIC, &start);
  3077. }
  3078. do {
  3079. if (fp != NULL) {
  3080. /* Use read() instead of fread(), because if we're reading from the
  3081. * CGI pipe, fread() may block until IO buffer is filled up. We
  3082. * cannot afford to block and must pass all read bytes immediately
  3083. * to the client. */
  3084. nread = (int)read(fileno(fp), buf, (size_t)len);
  3085. err = (nread < 0) ? ERRNO : 0;
  3086. #ifndef NO_SSL
  3087. } else if (conn->ssl != NULL) {
  3088. nread = SSL_read(conn->ssl, buf, len);
  3089. if (nread <= 0) {
  3090. err = SSL_get_error(conn->ssl, nread);
  3091. if ((err == 5 /* SSL_ERROR_SYSCALL */) && (nread == -1)) {
  3092. err = ERRNO;
  3093. } else {
  3094. DEBUG_TRACE("SSL_read() failed, error %d", err);
  3095. return -1;
  3096. }
  3097. } else {
  3098. err = 0;
  3099. }
  3100. #endif
  3101. } else {
  3102. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  3103. err = (nread < 0) ? ERRNO : 0;
  3104. }
  3105. if (conn->ctx->stop_flag) {
  3106. return -1;
  3107. }
  3108. if ((nread > 0) || (nread == 0 && len == 0)) {
  3109. /* some data has been read, or no data was requested */
  3110. return nread;
  3111. }
  3112. if (nread == 0) {
  3113. /* shutdown of the socket at client side */
  3114. return -1;
  3115. }
  3116. if (nread < 0) {
  3117. /* socket error - check errno */
  3118. #ifdef _WIN32
  3119. if (err == WSAEWOULDBLOCK) {
  3120. /* standard case if called from close_socket_gracefully */
  3121. return -1;
  3122. } else if (err == WSAETIMEDOUT) {
  3123. /* timeout is handled by the while loop */
  3124. } else {
  3125. DEBUG_TRACE("recv() failed, error %d", err);
  3126. return -1;
  3127. }
  3128. #else
  3129. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  3130. * if the timeout is reached and if the socket was set to non-
  3131. * blocking in close_socket_gracefully, so we can not distinguish
  3132. * here. We have to wait for the timeout in both cases for now.
  3133. */
  3134. if (err == EAGAIN || err == EWOULDBLOCK) {
  3135. /* standard case if called from close_socket_gracefully
  3136. * => should return -1 */
  3137. /* or timeout occured
  3138. * => the code must stay in the while loop */
  3139. } else {
  3140. DEBUG_TRACE("recv() failed, error %d", err);
  3141. return -1;
  3142. }
  3143. #endif
  3144. }
  3145. if (timeout > 0) {
  3146. clock_gettime(CLOCK_MONOTONIC, &now);
  3147. }
  3148. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  3149. /* Timeout occured, but no data available. */
  3150. return -1;
  3151. }
  3152. static int
  3153. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  3154. {
  3155. int n, nread = 0;
  3156. double timeout = -1.0;
  3157. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  3158. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  3159. }
  3160. while (len > 0 && conn->ctx->stop_flag == 0) {
  3161. n = pull(fp, conn, buf + nread, len, timeout);
  3162. if (n < 0) {
  3163. if (nread == 0) {
  3164. nread = n; /* Propagate the error */
  3165. }
  3166. break;
  3167. } else if (n == 0) {
  3168. break; /* No more data to read */
  3169. } else {
  3170. conn->consumed_content += n;
  3171. nread += n;
  3172. len -= n;
  3173. }
  3174. }
  3175. return nread;
  3176. }
  3177. static void
  3178. discard_unread_request_data(struct mg_connection *conn)
  3179. {
  3180. char buf[MG_BUF_LEN];
  3181. size_t to_read;
  3182. int nread;
  3183. if (conn == NULL) {
  3184. return;
  3185. }
  3186. to_read = sizeof(buf);
  3187. if (conn->is_chunked) {
  3188. /* Chunked encoding: 1=chunk not read completely, 2=chunk read
  3189. * completely */
  3190. while (conn->is_chunked == 1) {
  3191. nread = mg_read(conn, buf, to_read);
  3192. if (nread <= 0) {
  3193. break;
  3194. }
  3195. }
  3196. } else {
  3197. /* Not chunked: content length is known */
  3198. while (conn->consumed_content < conn->content_len) {
  3199. if (to_read
  3200. > (size_t)(conn->content_len - conn->consumed_content)) {
  3201. to_read = (size_t)(conn->content_len - conn->consumed_content);
  3202. }
  3203. nread = mg_read(conn, buf, to_read);
  3204. if (nread <= 0) {
  3205. break;
  3206. }
  3207. }
  3208. }
  3209. }
  3210. static int
  3211. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  3212. {
  3213. int64_t n, buffered_len, nread;
  3214. int64_t len64 =
  3215. (int64_t)(len > INT_MAX ? INT_MAX : len); /* since the return value is
  3216. * int, we may not read more
  3217. * bytes */
  3218. const char *body;
  3219. if (conn == NULL) {
  3220. return 0;
  3221. }
  3222. /* If Content-Length is not set for a PUT or POST request, read until
  3223. * socket is closed */
  3224. if (conn->consumed_content == 0 && conn->content_len == -1) {
  3225. conn->content_len = INT64_MAX;
  3226. conn->must_close = 1;
  3227. }
  3228. nread = 0;
  3229. if (conn->consumed_content < conn->content_len) {
  3230. /* Adjust number of bytes to read. */
  3231. int64_t left_to_read = conn->content_len - conn->consumed_content;
  3232. if (left_to_read < len64) {
  3233. /* Do not read more than the total content length of the request.
  3234. */
  3235. len64 = left_to_read;
  3236. }
  3237. /* Return buffered data */
  3238. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  3239. - conn->consumed_content;
  3240. if (buffered_len > 0) {
  3241. if (len64 < buffered_len) {
  3242. buffered_len = len64;
  3243. }
  3244. body = conn->buf + conn->request_len + conn->consumed_content;
  3245. memcpy(buf, body, (size_t)buffered_len);
  3246. len64 -= buffered_len;
  3247. conn->consumed_content += buffered_len;
  3248. nread += buffered_len;
  3249. buf = (char *)buf + buffered_len;
  3250. }
  3251. /* We have returned all buffered data. Read new data from the remote
  3252. * socket.
  3253. */
  3254. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  3255. nread += n;
  3256. } else {
  3257. nread = (nread > 0 ? nread : n);
  3258. }
  3259. }
  3260. return (int)nread;
  3261. }
  3262. static char
  3263. mg_getc(struct mg_connection *conn)
  3264. {
  3265. char c;
  3266. if (conn == NULL) {
  3267. return 0;
  3268. }
  3269. conn->content_len++;
  3270. if (mg_read_inner(conn, &c, 1) <= 0) {
  3271. return (char)0;
  3272. }
  3273. return c;
  3274. }
  3275. int
  3276. mg_read(struct mg_connection *conn, void *buf, size_t len)
  3277. {
  3278. if (len > INT_MAX) {
  3279. len = INT_MAX;
  3280. }
  3281. if (conn == NULL) {
  3282. return 0;
  3283. }
  3284. if (conn->is_chunked) {
  3285. size_t all_read = 0;
  3286. while (len > 0) {
  3287. if (conn->chunk_remainder) {
  3288. /* copy from the remainder of the last received chunk */
  3289. long read_ret;
  3290. size_t read_now =
  3291. ((conn->chunk_remainder > len) ? (len)
  3292. : (conn->chunk_remainder));
  3293. conn->content_len += (int)read_now;
  3294. read_ret =
  3295. mg_read_inner(conn, (char *)buf + all_read, read_now);
  3296. all_read += (size_t)read_ret;
  3297. conn->chunk_remainder -= read_now;
  3298. len -= read_now;
  3299. if (conn->chunk_remainder == 0) {
  3300. /* the rest of the data in the current chunk has been read
  3301. */
  3302. if ((mg_getc(conn) != '\r') || (mg_getc(conn) != '\n')) {
  3303. /* Protocol violation */
  3304. return -1;
  3305. }
  3306. }
  3307. } else {
  3308. /* fetch a new chunk */
  3309. int i = 0;
  3310. char lenbuf[64];
  3311. char *end = 0;
  3312. unsigned long chunkSize = 0;
  3313. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  3314. lenbuf[i] = mg_getc(conn);
  3315. if (i > 0 && lenbuf[i] == '\r' && lenbuf[i - 1] != '\r') {
  3316. continue;
  3317. }
  3318. if (i > 1 && lenbuf[i] == '\n' && lenbuf[i - 1] == '\r') {
  3319. lenbuf[i + 1] = 0;
  3320. chunkSize = strtoul(lenbuf, &end, 16);
  3321. break;
  3322. }
  3323. if (!isalnum(lenbuf[i])) {
  3324. /* illegal character for chunk length */
  3325. return -1;
  3326. }
  3327. }
  3328. if ((end == NULL) || (*end != '\r')) {
  3329. /* chunksize not set correctly */
  3330. return -1;
  3331. }
  3332. conn->chunk_remainder = chunkSize;
  3333. if (chunkSize == 0) {
  3334. /* regular end of content */
  3335. conn->is_chunked = 2;
  3336. break;
  3337. }
  3338. }
  3339. }
  3340. return (int)all_read;
  3341. }
  3342. return mg_read_inner(conn, buf, len);
  3343. }
  3344. int
  3345. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  3346. {
  3347. time_t now;
  3348. int64_t n, total, allowed;
  3349. if (conn == NULL) {
  3350. return 0;
  3351. }
  3352. if (conn->throttle > 0) {
  3353. if ((now = time(NULL)) != conn->last_throttle_time) {
  3354. conn->last_throttle_time = now;
  3355. conn->last_throttle_bytes = 0;
  3356. }
  3357. allowed = conn->throttle - conn->last_throttle_bytes;
  3358. if (allowed > (int64_t)len) {
  3359. allowed = (int64_t)len;
  3360. }
  3361. if ((total = push_all(conn->ctx,
  3362. NULL,
  3363. conn->client.sock,
  3364. conn->ssl,
  3365. (const char *)buf,
  3366. (int64_t)allowed)) == allowed) {
  3367. buf = (char *)buf + total;
  3368. conn->last_throttle_bytes += total;
  3369. while (total < (int64_t)len && conn->ctx->stop_flag == 0) {
  3370. allowed = conn->throttle > (int64_t)len - total
  3371. ? (int64_t)len - total
  3372. : conn->throttle;
  3373. if ((n = push_all(conn->ctx,
  3374. NULL,
  3375. conn->client.sock,
  3376. conn->ssl,
  3377. (const char *)buf,
  3378. (int64_t)allowed)) != allowed) {
  3379. break;
  3380. }
  3381. sleep(1);
  3382. conn->last_throttle_bytes = allowed;
  3383. conn->last_throttle_time = time(NULL);
  3384. buf = (char *)buf + n;
  3385. total += n;
  3386. }
  3387. }
  3388. } else {
  3389. total = push_all(conn->ctx,
  3390. NULL,
  3391. conn->client.sock,
  3392. conn->ssl,
  3393. (const char *)buf,
  3394. (int64_t)len);
  3395. }
  3396. return (int)total;
  3397. }
  3398. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  3399. static int
  3400. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  3401. {
  3402. va_list ap_copy;
  3403. size_t size = MG_BUF_LEN;
  3404. int len = -1;
  3405. *buf = NULL;
  3406. while (len < 0) {
  3407. if (*buf) {
  3408. mg_free(*buf);
  3409. }
  3410. *buf = (char *)mg_malloc(size *= 4);
  3411. if (!*buf) {
  3412. break;
  3413. }
  3414. va_copy(ap_copy, ap);
  3415. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  3416. va_end(ap_copy);
  3417. *buf[size - 1] = 0;
  3418. }
  3419. return len;
  3420. }
  3421. /* Print message to buffer. If buffer is large enough to hold the message,
  3422. * return buffer. If buffer is to small, allocate large enough buffer on heap,
  3423. * and return allocated buffer. */
  3424. static int
  3425. alloc_vprintf(char **buf, size_t size, const char *fmt, va_list ap)
  3426. {
  3427. va_list ap_copy;
  3428. int len;
  3429. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  3430. * buffer is too small. Also, older versions of msvcrt.dll do not have
  3431. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  3432. * Therefore, we make two passes: on first pass, get required message
  3433. * length.
  3434. * On second pass, actually print the message. */
  3435. va_copy(ap_copy, ap);
  3436. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  3437. va_end(ap_copy);
  3438. if (len < 0) {
  3439. /* C runtime is not standard compliant, vsnprintf() returned -1.
  3440. * Switch to alternative code path that uses incremental allocations.
  3441. */
  3442. va_copy(ap_copy, ap);
  3443. len = alloc_vprintf2(buf, fmt, ap);
  3444. va_end(ap_copy);
  3445. } else if ((size_t)(len) > size && (size = (size_t)(len) + 1) > 0
  3446. && (*buf = (char *)mg_malloc(size)) == NULL) {
  3447. len = -1; /* Allocation failed, mark failure */
  3448. } else {
  3449. va_copy(ap_copy, ap);
  3450. IGNORE_UNUSED_RESULT(vsnprintf_impl(*buf, size, fmt, ap_copy));
  3451. va_end(ap_copy);
  3452. }
  3453. return len;
  3454. }
  3455. static int
  3456. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  3457. {
  3458. char mem[MG_BUF_LEN], *buf = mem;
  3459. int len;
  3460. if ((len = alloc_vprintf(&buf, sizeof(mem), fmt, ap)) > 0) {
  3461. len = mg_write(conn, buf, (size_t)len);
  3462. }
  3463. if (buf != mem && buf != NULL) {
  3464. mg_free(buf);
  3465. }
  3466. return len;
  3467. }
  3468. int
  3469. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  3470. {
  3471. va_list ap;
  3472. int result;
  3473. va_start(ap, fmt);
  3474. result = mg_vprintf(conn, fmt, ap);
  3475. va_end(ap);
  3476. return result;
  3477. }
  3478. int
  3479. mg_url_decode(const char *src,
  3480. int src_len,
  3481. char *dst,
  3482. int dst_len,
  3483. int is_form_url_encoded)
  3484. {
  3485. int i, j, a, b;
  3486. #define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W')
  3487. for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) {
  3488. if (i < src_len - 2 && src[i] == '%'
  3489. && isxdigit(*(const unsigned char *)(src + i + 1))
  3490. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  3491. a = tolower(*(const unsigned char *)(src + i + 1));
  3492. b = tolower(*(const unsigned char *)(src + i + 2));
  3493. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  3494. i += 2;
  3495. } else if (is_form_url_encoded && src[i] == '+') {
  3496. dst[j] = ' ';
  3497. } else {
  3498. dst[j] = src[i];
  3499. }
  3500. }
  3501. dst[j] = '\0'; /* Null-terminate the destination */
  3502. return i >= src_len ? j : -1;
  3503. }
  3504. int
  3505. mg_get_var(const char *data,
  3506. size_t data_len,
  3507. const char *name,
  3508. char *dst,
  3509. size_t dst_len)
  3510. {
  3511. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  3512. }
  3513. int
  3514. mg_get_var2(const char *data,
  3515. size_t data_len,
  3516. const char *name,
  3517. char *dst,
  3518. size_t dst_len,
  3519. size_t occurrence)
  3520. {
  3521. const char *p, *e, *s;
  3522. size_t name_len;
  3523. int len;
  3524. if (dst == NULL || dst_len == 0) {
  3525. len = -2;
  3526. } else if (data == NULL || name == NULL || data_len == 0) {
  3527. len = -1;
  3528. dst[0] = '\0';
  3529. } else {
  3530. name_len = strlen(name);
  3531. e = data + data_len;
  3532. len = -1;
  3533. dst[0] = '\0';
  3534. /* data is "var1=val1&var2=val2...". Find variable first */
  3535. for (p = data; p + name_len < e; p++) {
  3536. if ((p == data || p[-1] == '&') && p[name_len] == '='
  3537. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  3538. /* Point p to variable value */
  3539. p += name_len + 1;
  3540. /* Point s to the end of the value */
  3541. s = (const char *)memchr(p, '&', (size_t)(e - p));
  3542. if (s == NULL) {
  3543. s = e;
  3544. }
  3545. /* assert(s >= p); */
  3546. if (s < p) {
  3547. return -3;
  3548. }
  3549. /* Decode variable into destination buffer */
  3550. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  3551. /* Redirect error code from -1 to -2 (destination buffer too
  3552. * small). */
  3553. if (len == -1) {
  3554. len = -2;
  3555. }
  3556. break;
  3557. }
  3558. }
  3559. }
  3560. return len;
  3561. }
  3562. int
  3563. mg_get_cookie(const char *cookie_header,
  3564. const char *var_name,
  3565. char *dst,
  3566. size_t dst_size)
  3567. {
  3568. const char *s, *p, *end;
  3569. int name_len, len = -1;
  3570. if (dst == NULL || dst_size == 0) {
  3571. len = -2;
  3572. } else if (var_name == NULL || (s = cookie_header) == NULL) {
  3573. len = -1;
  3574. dst[0] = '\0';
  3575. } else {
  3576. name_len = (int)strlen(var_name);
  3577. end = s + strlen(s);
  3578. dst[0] = '\0';
  3579. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  3580. if (s[name_len] == '=') {
  3581. s += name_len + 1;
  3582. if ((p = strchr(s, ' ')) == NULL) {
  3583. p = end;
  3584. }
  3585. if (p[-1] == ';') {
  3586. p--;
  3587. }
  3588. if (*s == '"' && p[-1] == '"' && p > s + 1) {
  3589. s++;
  3590. p--;
  3591. }
  3592. if ((size_t)(p - s) < dst_size) {
  3593. len = (int)(p - s);
  3594. mg_strlcpy(dst, s, (size_t)len + 1);
  3595. } else {
  3596. len = -3;
  3597. }
  3598. break;
  3599. }
  3600. }
  3601. }
  3602. return len;
  3603. }
  3604. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  3605. static void
  3606. base64_encode(const unsigned char *src, int src_len, char *dst)
  3607. {
  3608. static const char *b64 =
  3609. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3610. int i, j, a, b, c;
  3611. for (i = j = 0; i < src_len; i += 3) {
  3612. a = src[i];
  3613. b = i + 1 >= src_len ? 0 : src[i + 1];
  3614. c = i + 2 >= src_len ? 0 : src[i + 2];
  3615. dst[j++] = b64[a >> 2];
  3616. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  3617. if (i + 1 < src_len) {
  3618. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  3619. }
  3620. if (i + 2 < src_len) {
  3621. dst[j++] = b64[c & 63];
  3622. }
  3623. }
  3624. while (j % 4 != 0) {
  3625. dst[j++] = '=';
  3626. }
  3627. dst[j++] = '\0';
  3628. }
  3629. #endif
  3630. #if defined(USE_LUA)
  3631. static unsigned char
  3632. b64reverse(char letter)
  3633. {
  3634. if (letter >= 'A' && letter <= 'Z') {
  3635. return letter - 'A';
  3636. }
  3637. if (letter >= 'a' && letter <= 'z') {
  3638. return letter - 'a' + 26;
  3639. }
  3640. if (letter >= '0' && letter <= '9') {
  3641. return letter - '0' + 52;
  3642. }
  3643. if (letter == '+') {
  3644. return 62;
  3645. }
  3646. if (letter == '/') {
  3647. return 63;
  3648. }
  3649. if (letter == '=') {
  3650. return 255; /* normal end */
  3651. }
  3652. return 254; /* error */
  3653. }
  3654. static int
  3655. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  3656. {
  3657. int i;
  3658. unsigned char a, b, c, d;
  3659. *dst_len = 0;
  3660. for (i = 0; i < src_len; i += 4) {
  3661. a = b64reverse(src[i]);
  3662. if (a >= 254) {
  3663. return i;
  3664. }
  3665. b = b64reverse(i + 1 >= src_len ? 0 : src[i + 1]);
  3666. if (b >= 254) {
  3667. return i + 1;
  3668. }
  3669. c = b64reverse(i + 2 >= src_len ? 0 : src[i + 2]);
  3670. if (c == 254) {
  3671. return i + 2;
  3672. }
  3673. d = b64reverse(i + 3 >= src_len ? 0 : src[i + 3]);
  3674. if (d == 254) {
  3675. return i + 3;
  3676. }
  3677. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  3678. if (c != 255) {
  3679. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  3680. if (d != 255) {
  3681. dst[(*dst_len)++] = (c << 6) + d;
  3682. }
  3683. }
  3684. }
  3685. return -1;
  3686. }
  3687. #endif
  3688. static int
  3689. is_put_or_delete_method(const struct mg_connection *conn)
  3690. {
  3691. if (conn) {
  3692. const char *s = conn->request_info.request_method;
  3693. return s != NULL && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  3694. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  3695. }
  3696. return 0;
  3697. }
  3698. static void
  3699. interpret_uri(struct mg_connection *conn, /* in: request (must be valid) */
  3700. char *filename, /* out: filename */
  3701. size_t filename_buf_len, /* in: size of filename buffer */
  3702. struct file *filep, /* out: file structure */
  3703. int *is_found, /* out: file is found (directly) */
  3704. int *is_script_resource, /* out: handled by a script? */
  3705. int *is_websocket_request, /* out: websocket connetion? */
  3706. int *is_put_or_delete_request /* out: put/delete a file? */
  3707. )
  3708. {
  3709. /* TODO (high): Restructure this function */
  3710. #if !defined(NO_FILES)
  3711. const char *uri = conn->request_info.local_uri;
  3712. const char *root = conn->ctx->config[DOCUMENT_ROOT];
  3713. const char *rewrite;
  3714. struct vec a, b;
  3715. int match_len;
  3716. char gz_path[PATH_MAX];
  3717. char const *accept_encoding;
  3718. int truncated;
  3719. #if !defined(NO_CGI) || defined(USE_LUA)
  3720. char *p;
  3721. #endif
  3722. #else
  3723. (void)filename_buf_len; /* unused if NO_FILES is defined */
  3724. #endif
  3725. memset(filep, 0, sizeof(*filep));
  3726. *filename = 0;
  3727. *is_found = 0;
  3728. *is_script_resource = 0;
  3729. *is_put_or_delete_request = is_put_or_delete_method(conn);
  3730. #if defined(USE_WEBSOCKET)
  3731. *is_websocket_request = is_websocket_protocol(conn);
  3732. #if !defined(NO_FILES)
  3733. if (*is_websocket_request && conn->ctx->config[WEBSOCKET_ROOT]) {
  3734. root = conn->ctx->config[WEBSOCKET_ROOT];
  3735. }
  3736. #endif /* !NO_FILES */
  3737. #else /* USE_WEBSOCKET */
  3738. *is_websocket_request = 0;
  3739. #endif /* USE_WEBSOCKET */
  3740. #if !defined(NO_FILES)
  3741. /* Note that root == NULL is a regular use case here. This occurs,
  3742. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  3743. * config is not required. */
  3744. if (root == NULL) {
  3745. /* all file related outputs have already been set to 0, just return
  3746. */
  3747. return;
  3748. }
  3749. /* Using buf_len - 1 because memmove() for PATH_INFO may shift part
  3750. * of the path one byte on the right.
  3751. * If document_root is NULL, leave the file empty. */
  3752. mg_snprintf(
  3753. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  3754. if (truncated) {
  3755. goto interpret_cleanup;
  3756. }
  3757. rewrite = conn->ctx->config[REWRITE];
  3758. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  3759. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  3760. mg_snprintf(conn,
  3761. &truncated,
  3762. filename,
  3763. filename_buf_len - 1,
  3764. "%.*s%s",
  3765. (int)b.len,
  3766. b.ptr,
  3767. uri + match_len);
  3768. break;
  3769. }
  3770. }
  3771. if (truncated) {
  3772. goto interpret_cleanup;
  3773. }
  3774. /* Local file path and name, corresponding to requested URI
  3775. * is now stored in "filename" variable. */
  3776. if (mg_stat(conn, filename, filep)) {
  3777. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  3778. /* File exists. Check if it is a script type. */
  3779. if (0
  3780. #if !defined(NO_CGI)
  3781. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  3782. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  3783. filename) > 0
  3784. #endif
  3785. #if defined(USE_LUA)
  3786. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  3787. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  3788. filename) > 0
  3789. #endif
  3790. #if defined(USE_DUKTAPE)
  3791. || match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  3792. strlen(
  3793. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  3794. filename) > 0
  3795. #endif
  3796. ) {
  3797. /* The request addresses a CGI script or a Lua script. The URI
  3798. * corresponds to the script itself (like /path/script.cgi),
  3799. * and there is no additional resource path
  3800. * (like /path/script.cgi/something).
  3801. * Requests that modify (replace or delete) a resource, like
  3802. * PUT and DELETE requests, should replace/delete the script
  3803. * file.
  3804. * Requests that read or write from/to a resource, like GET and
  3805. * POST requests, should call the script and return the
  3806. * generated response. */
  3807. *is_script_resource = !*is_put_or_delete_request;
  3808. }
  3809. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  3810. *is_found = 1;
  3811. return;
  3812. }
  3813. /* If we can't find the actual file, look for the file
  3814. * with the same name but a .gz extension. If we find it,
  3815. * use that and set the gzipped flag in the file struct
  3816. * to indicate that the response need to have the content-
  3817. * encoding: gzip header.
  3818. * We can only do this if the browser declares support. */
  3819. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  3820. if (strstr(accept_encoding, "gzip") != NULL) {
  3821. mg_snprintf(
  3822. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  3823. if (truncated) {
  3824. goto interpret_cleanup;
  3825. }
  3826. if (mg_stat(conn, gz_path, filep)) {
  3827. if (filep) {
  3828. filep->gzipped = 1;
  3829. *is_found = 1;
  3830. }
  3831. /* Currently gz files can not be scripts. */
  3832. return;
  3833. }
  3834. }
  3835. }
  3836. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  3837. /* Support PATH_INFO for CGI scripts. */
  3838. for (p = filename + strlen(filename); p > filename + 1; p--) {
  3839. if (*p == '/') {
  3840. *p = '\0';
  3841. if ((0
  3842. #if !defined(NO_CGI)
  3843. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  3844. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  3845. filename) > 0
  3846. #endif
  3847. #if defined(USE_LUA)
  3848. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  3849. strlen(
  3850. conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  3851. filename) > 0
  3852. #endif
  3853. #if defined(USE_DUKTAPE)
  3854. || match_prefix(
  3855. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  3856. strlen(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  3857. filename) > 0
  3858. #endif
  3859. ) && mg_stat(conn, filename, filep)) {
  3860. /* Shift PATH_INFO block one character right, e.g.
  3861. * "/x.cgi/foo/bar\x00" => "/x.cgi\x00/foo/bar\x00"
  3862. * conn->path_info is pointing to the local variable "path"
  3863. * declared in handle_request(), so PATH_INFO is not valid
  3864. * after handle_request returns. */
  3865. conn->path_info = p + 1;
  3866. memmove(p + 2, p + 1, strlen(p + 1) + 1); /* +1 is for
  3867. * trailing \0 */
  3868. p[1] = '/';
  3869. *is_script_resource = 1;
  3870. break;
  3871. } else {
  3872. *p = '/';
  3873. }
  3874. }
  3875. }
  3876. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  3877. #endif /* !defined(NO_FILES) */
  3878. return;
  3879. #if !defined(NO_FILES)
  3880. /* Reset all outputs */
  3881. interpret_cleanup:
  3882. memset(filep, 0, sizeof(*filep));
  3883. *filename = 0;
  3884. *is_found = 0;
  3885. *is_script_resource = 0;
  3886. *is_websocket_request = 0;
  3887. *is_put_or_delete_request = 0;
  3888. #endif /* !defined(NO_FILES) */
  3889. }
  3890. /* Check whether full request is buffered. Return:
  3891. * -1 if request is malformed
  3892. * 0 if request is not yet fully buffered
  3893. * >0 actual request length, including last \r\n\r\n */
  3894. static int
  3895. get_request_len(const char *buf, int buflen)
  3896. {
  3897. const char *s, *e;
  3898. int len = 0;
  3899. for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
  3900. /* Control characters are not allowed but >=128 is. */
  3901. if (!isprint(*(const unsigned char *)s) && *s != '\r' && *s != '\n'
  3902. && *(const unsigned char *)s < 128) {
  3903. len = -1;
  3904. break; /* [i_a] abort scan as soon as one malformed character is
  3905. * found; */
  3906. /* don't let subsequent \r\n\r\n win us over anyhow */
  3907. } else if (s[0] == '\n' && s[1] == '\n') {
  3908. len = (int)(s - buf) + 2;
  3909. } else if (s[0] == '\n' && &s[1] < e && s[1] == '\r' && s[2] == '\n') {
  3910. len = (int)(s - buf) + 3;
  3911. }
  3912. return len;
  3913. }
  3914. /* Convert month to the month number. Return -1 on error, or month number */
  3915. static int
  3916. get_month_index(const char *s)
  3917. {
  3918. size_t i;
  3919. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  3920. if (!strcmp(s, month_names[i])) {
  3921. return (int)i;
  3922. }
  3923. }
  3924. return -1;
  3925. }
  3926. static int
  3927. num_leap_years(int year)
  3928. {
  3929. return year / 4 - year / 100 + year / 400;
  3930. }
  3931. /* Parse UTC date-time string, and return the corresponding time_t value. */
  3932. static time_t
  3933. parse_date_string(const char *datetime)
  3934. {
  3935. static const unsigned short days_before_month[] = {
  3936. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
  3937. char month_str[32] = {0};
  3938. int second, minute, hour, day, month, year, leap_days, days;
  3939. time_t result = (time_t)0;
  3940. if ((sscanf(datetime,
  3941. "%d/%3s/%d %d:%d:%d",
  3942. &day,
  3943. month_str,
  3944. &year,
  3945. &hour,
  3946. &minute,
  3947. &second) == 6) || (sscanf(datetime,
  3948. "%d %3s %d %d:%d:%d",
  3949. &day,
  3950. month_str,
  3951. &year,
  3952. &hour,
  3953. &minute,
  3954. &second) == 6)
  3955. || (sscanf(datetime,
  3956. "%*3s, %d %3s %d %d:%d:%d",
  3957. &day,
  3958. month_str,
  3959. &year,
  3960. &hour,
  3961. &minute,
  3962. &second) == 6) || (sscanf(datetime,
  3963. "%d-%3s-%d %d:%d:%d",
  3964. &day,
  3965. month_str,
  3966. &year,
  3967. &hour,
  3968. &minute,
  3969. &second) == 6)) {
  3970. month = get_month_index(month_str);
  3971. if ((month >= 0) && (year > 1970)) {
  3972. leap_days = num_leap_years(year) - num_leap_years(1970);
  3973. year -= 1970;
  3974. days =
  3975. year * 365 + days_before_month[month] + (day - 1) + leap_days;
  3976. result = (time_t)days * 24 * 3600 + (time_t)hour * 3600
  3977. + minute * 60 + second;
  3978. }
  3979. }
  3980. return result;
  3981. }
  3982. /* Protect against directory disclosure attack by removing '..',
  3983. * excessive '/' and '\' characters */
  3984. static void
  3985. remove_double_dots_and_double_slashes(char *s)
  3986. {
  3987. char *p = s;
  3988. while (*s != '\0') {
  3989. *p++ = *s++;
  3990. if (s[-1] == '/' || s[-1] == '\\') {
  3991. /* Skip all following slashes, backslashes and double-dots */
  3992. while (s[0] != '\0') {
  3993. if (s[0] == '/' || s[0] == '\\') {
  3994. s++;
  3995. } else if (s[0] == '.' && s[1] == '.') {
  3996. s += 2;
  3997. } else {
  3998. break;
  3999. }
  4000. }
  4001. }
  4002. }
  4003. *p = '\0';
  4004. }
  4005. static const struct {
  4006. const char *extension;
  4007. size_t ext_len;
  4008. const char *mime_type;
  4009. } builtin_mime_types[] = {
  4010. /* IANA registered MIME types (http://www.iana.org/assignments/media-types)
  4011. * application types */
  4012. {".doc", 4, "application/msword"},
  4013. {".eps", 4, "application/postscript"},
  4014. {".exe", 4, "application/octet-stream"},
  4015. {".js", 3, "application/javascript"},
  4016. {".json", 5, "application/json"},
  4017. {".pdf", 4, "application/pdf"},
  4018. {".ps", 3, "application/postscript"},
  4019. {".rtf", 4, "application/rtf"},
  4020. {".xhtml", 6, "application/xhtml+xml"},
  4021. {".xsl", 4, "application/xml"},
  4022. {".xslt", 5, "application/xml"},
  4023. /* audio */
  4024. {".mp3", 4, "audio/mpeg"},
  4025. {".oga", 4, "audio/ogg"},
  4026. {".ogg", 4, "audio/ogg"},
  4027. /* image */
  4028. {".gif", 4, "image/gif"},
  4029. {".ief", 4, "image/ief"},
  4030. {".jpeg", 5, "image/jpeg"},
  4031. {".jpg", 4, "image/jpeg"},
  4032. {".jpm", 4, "image/jpm"},
  4033. {".jpx", 4, "image/jpx"},
  4034. {".png", 4, "image/png"},
  4035. {".svg", 4, "image/svg+xml"},
  4036. {".tif", 4, "image/tiff"},
  4037. {".tiff", 5, "image/tiff"},
  4038. /* model */
  4039. {".wrl", 4, "model/vrml"},
  4040. /* text */
  4041. {".css", 4, "text/css"},
  4042. {".csv", 4, "text/csv"},
  4043. {".htm", 4, "text/html"},
  4044. {".html", 5, "text/html"},
  4045. {".sgm", 4, "text/sgml"},
  4046. {".shtm", 5, "text/html"},
  4047. {".shtml", 6, "text/html"},
  4048. {".txt", 4, "text/plain"},
  4049. {".xml", 4, "text/xml"},
  4050. /* video */
  4051. {".mov", 4, "video/quicktime"},
  4052. {".mp4", 4, "video/mp4"},
  4053. {".mpeg", 5, "video/mpeg"},
  4054. {".mpg", 4, "video/mpeg"},
  4055. {".ogv", 4, "video/ogg"},
  4056. {".qt", 3, "video/quicktime"},
  4057. /* not registered types
  4058. * (http://reference.sitepoint.com/html/mime-types-full,
  4059. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  4060. {".arj", 4, "application/x-arj-compressed"},
  4061. {".gz", 3, "application/x-gunzip"},
  4062. {".rar", 4, "application/x-arj-compressed"},
  4063. {".swf", 4, "application/x-shockwave-flash"},
  4064. {".tar", 4, "application/x-tar"},
  4065. {".tgz", 4, "application/x-tar-gz"},
  4066. {".torrent", 8, "application/x-bittorrent"},
  4067. {".ppt", 4, "application/x-mspowerpoint"},
  4068. {".xls", 4, "application/x-msexcel"},
  4069. {".zip", 4, "application/x-zip-compressed"},
  4070. {".aac",
  4071. 4,
  4072. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  4073. {".aif", 4, "audio/x-aif"},
  4074. {".m3u", 4, "audio/x-mpegurl"},
  4075. {".mid", 4, "audio/x-midi"},
  4076. {".ra", 3, "audio/x-pn-realaudio"},
  4077. {".ram", 4, "audio/x-pn-realaudio"},
  4078. {".wav", 4, "audio/x-wav"},
  4079. {".bmp", 4, "image/bmp"},
  4080. {".ico", 4, "image/x-icon"},
  4081. {".pct", 4, "image/x-pct"},
  4082. {".pict", 5, "image/pict"},
  4083. {".rgb", 4, "image/x-rgb"},
  4084. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  4085. {".asf", 4, "video/x-ms-asf"},
  4086. {".avi", 4, "video/x-msvideo"},
  4087. {".m4v", 4, "video/x-m4v"},
  4088. {NULL, 0, NULL}};
  4089. const char *
  4090. mg_get_builtin_mime_type(const char *path)
  4091. {
  4092. const char *ext;
  4093. size_t i, path_len;
  4094. path_len = strlen(path);
  4095. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  4096. ext = path + (path_len - builtin_mime_types[i].ext_len);
  4097. if (path_len > builtin_mime_types[i].ext_len
  4098. && mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {
  4099. return builtin_mime_types[i].mime_type;
  4100. }
  4101. }
  4102. return "text/plain";
  4103. }
  4104. /* Look at the "path" extension and figure what mime type it has.
  4105. * Store mime type in the vector. */
  4106. static void
  4107. get_mime_type(struct mg_context *ctx, const char *path, struct vec *vec)
  4108. {
  4109. struct vec ext_vec, mime_vec;
  4110. const char *list, *ext;
  4111. size_t path_len;
  4112. path_len = strlen(path);
  4113. if (ctx == NULL || vec == NULL) {
  4114. return;
  4115. }
  4116. /* Scan user-defined mime types first, in case user wants to
  4117. * override default mime types. */
  4118. list = ctx->config[EXTRA_MIME_TYPES];
  4119. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  4120. /* ext now points to the path suffix */
  4121. ext = path + path_len - ext_vec.len;
  4122. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  4123. *vec = mime_vec;
  4124. return;
  4125. }
  4126. }
  4127. vec->ptr = mg_get_builtin_mime_type(path);
  4128. vec->len = strlen(vec->ptr);
  4129. }
  4130. /* Stringify binary data. Output buffer must be twice as big as input,
  4131. * because each byte takes 2 bytes in string representation */
  4132. static void
  4133. bin2str(char *to, const unsigned char *p, size_t len)
  4134. {
  4135. static const char *hex = "0123456789abcdef";
  4136. for (; len--; p++) {
  4137. *to++ = hex[p[0] >> 4];
  4138. *to++ = hex[p[0] & 0x0f];
  4139. }
  4140. *to = '\0';
  4141. }
  4142. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes. */
  4143. char *
  4144. mg_md5(char buf[33], ...)
  4145. {
  4146. md5_byte_t hash[16];
  4147. const char *p;
  4148. va_list ap;
  4149. md5_state_t ctx;
  4150. md5_init(&ctx);
  4151. va_start(ap, buf);
  4152. while ((p = va_arg(ap, const char *)) != NULL) {
  4153. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  4154. }
  4155. va_end(ap);
  4156. md5_finish(&ctx, hash);
  4157. bin2str(buf, hash, sizeof(hash));
  4158. return buf;
  4159. }
  4160. /* Check the user's password, return 1 if OK */
  4161. static int
  4162. check_password(const char *method,
  4163. const char *ha1,
  4164. const char *uri,
  4165. const char *nonce,
  4166. const char *nc,
  4167. const char *cnonce,
  4168. const char *qop,
  4169. const char *response)
  4170. {
  4171. char ha2[32 + 1], expected_response[32 + 1];
  4172. /* Some of the parameters may be NULL */
  4173. if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL
  4174. || qop == NULL
  4175. || response == NULL) {
  4176. return 0;
  4177. }
  4178. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  4179. if (strlen(response) != 32) {
  4180. return 0;
  4181. }
  4182. mg_md5(ha2, method, ":", uri, NULL);
  4183. mg_md5(expected_response,
  4184. ha1,
  4185. ":",
  4186. nonce,
  4187. ":",
  4188. nc,
  4189. ":",
  4190. cnonce,
  4191. ":",
  4192. qop,
  4193. ":",
  4194. ha2,
  4195. NULL);
  4196. return mg_strcasecmp(response, expected_response) == 0;
  4197. }
  4198. /* Use the global passwords file, if specified by auth_gpass option,
  4199. * or search for .htpasswd in the requested directory. */
  4200. static void
  4201. open_auth_file(struct mg_connection *conn, const char *path, struct file *filep)
  4202. {
  4203. if (conn != NULL && conn->ctx != NULL) {
  4204. char name[PATH_MAX];
  4205. const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
  4206. struct file file = STRUCT_FILE_INITIALIZER;
  4207. int truncated;
  4208. if (gpass != NULL) {
  4209. /* Use global passwords file */
  4210. if (!mg_fopen(conn, gpass, "r", filep)) {
  4211. #ifdef DEBUG
  4212. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  4213. #endif
  4214. }
  4215. /* Important: using local struct file to test path for is_directory
  4216. * flag. If filep is used, mg_stat() makes it appear as if auth file
  4217. * was opened. */
  4218. } else if (mg_stat(conn, path, &file) && file.is_directory) {
  4219. mg_snprintf(conn,
  4220. &truncated,
  4221. name,
  4222. sizeof(name),
  4223. "%s/%s",
  4224. path,
  4225. PASSWORDS_FILE_NAME);
  4226. if (truncated || !mg_fopen(conn, name, "r", filep)) {
  4227. #ifdef DEBUG
  4228. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  4229. #endif
  4230. }
  4231. } else {
  4232. /* Try to find .htpasswd in requested directory. */
  4233. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  4234. if (e[0] == '/') {
  4235. break;
  4236. }
  4237. }
  4238. mg_snprintf(conn,
  4239. &truncated,
  4240. name,
  4241. sizeof(name),
  4242. "%.*s%s",
  4243. (int)(e - p),
  4244. p,
  4245. PASSWORDS_FILE_NAME);
  4246. if (truncated || !mg_fopen(conn, name, "r", filep)) {
  4247. #ifdef DEBUG
  4248. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  4249. #endif
  4250. }
  4251. }
  4252. }
  4253. }
  4254. /* Parsed Authorization header */
  4255. struct ah {
  4256. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  4257. };
  4258. /* Return 1 on success. Always initializes the ah structure. */
  4259. static int
  4260. parse_auth_header(struct mg_connection *conn,
  4261. char *buf,
  4262. size_t buf_size,
  4263. struct ah *ah)
  4264. {
  4265. char *name, *value, *s;
  4266. const char *auth_header;
  4267. uint64_t nonce;
  4268. if (!ah || !conn) {
  4269. return 0;
  4270. }
  4271. (void)memset(ah, 0, sizeof(*ah));
  4272. if ((auth_header = mg_get_header(conn, "Authorization")) == NULL
  4273. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  4274. return 0;
  4275. }
  4276. /* Make modifiable copy of the auth header */
  4277. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  4278. s = buf;
  4279. /* Parse authorization header */
  4280. for (;;) {
  4281. /* Gobble initial spaces */
  4282. while (isspace(*(unsigned char *)s)) {
  4283. s++;
  4284. }
  4285. name = skip_quoted(&s, "=", " ", 0);
  4286. /* Value is either quote-delimited, or ends at first comma or space. */
  4287. if (s[0] == '\"') {
  4288. s++;
  4289. value = skip_quoted(&s, "\"", " ", '\\');
  4290. if (s[0] == ',') {
  4291. s++;
  4292. }
  4293. } else {
  4294. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  4295. * spaces */
  4296. }
  4297. if (*name == '\0') {
  4298. break;
  4299. }
  4300. if (!strcmp(name, "username")) {
  4301. ah->user = value;
  4302. } else if (!strcmp(name, "cnonce")) {
  4303. ah->cnonce = value;
  4304. } else if (!strcmp(name, "response")) {
  4305. ah->response = value;
  4306. } else if (!strcmp(name, "uri")) {
  4307. ah->uri = value;
  4308. } else if (!strcmp(name, "qop")) {
  4309. ah->qop = value;
  4310. } else if (!strcmp(name, "nc")) {
  4311. ah->nc = value;
  4312. } else if (!strcmp(name, "nonce")) {
  4313. ah->nonce = value;
  4314. }
  4315. }
  4316. #ifndef NO_NONCE_CHECK
  4317. /* Read the nonce from the response. */
  4318. if (ah->nonce == NULL) {
  4319. return 0;
  4320. }
  4321. s = NULL;
  4322. nonce = strtoull(ah->nonce, &s, 10);
  4323. if ((s == NULL) || (*s != 0)) {
  4324. return 0;
  4325. }
  4326. /* Convert the nonce from the client to a number. */
  4327. nonce ^= conn->ctx->auth_nonce_mask;
  4328. /* The converted number corresponds to the time the nounce has been
  4329. * created. This should not be earlier than the server start. */
  4330. /* Server side nonce check is valuable in all situations but one:
  4331. * if the server restarts frequently, but the client should not see
  4332. * that, so the server should accept nonces from previous starts. */
  4333. /* However, the reasonable default is to not accept a nonce from a
  4334. * previous start, so if anyone changed the access rights between
  4335. * two restarts, a new login is required. */
  4336. if (nonce < (uint64_t)conn->ctx->start_time) {
  4337. /* nonce is from a previous start of the server and no longer valid
  4338. * (replay attack?) */
  4339. return 0;
  4340. }
  4341. /* Check if the nonce is too high, so it has not (yet) been used by the
  4342. * server. */
  4343. if (nonce >= ((uint64_t)conn->ctx->start_time + conn->ctx->nonce_count)) {
  4344. return 0;
  4345. }
  4346. #endif
  4347. /* CGI needs it as REMOTE_USER */
  4348. if (ah->user != NULL) {
  4349. conn->request_info.remote_user = mg_strdup(ah->user);
  4350. } else {
  4351. return 0;
  4352. }
  4353. return 1;
  4354. }
  4355. static char *
  4356. mg_fgets(char *buf, size_t size, struct file *filep, char **p)
  4357. {
  4358. char *eof;
  4359. size_t len;
  4360. char *memend;
  4361. if (!filep) {
  4362. return NULL;
  4363. }
  4364. if (filep->membuf != NULL && *p != NULL) {
  4365. memend = (char *)&filep->membuf[filep->size];
  4366. /* Search for \n from p till the end of stream */
  4367. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  4368. if (eof != NULL) {
  4369. eof += 1; /* Include \n */
  4370. } else {
  4371. eof = memend; /* Copy remaining data */
  4372. }
  4373. len = (size_t)(eof - *p) > size - 1 ? size - 1 : (size_t)(eof - *p);
  4374. memcpy(buf, *p, len);
  4375. buf[len] = '\0';
  4376. *p += len;
  4377. return len ? eof : NULL;
  4378. } else if (filep->fp != NULL) {
  4379. return fgets(buf, (int)size, filep->fp);
  4380. } else {
  4381. return NULL;
  4382. }
  4383. }
  4384. struct read_auth_file_struct {
  4385. struct mg_connection *conn;
  4386. struct ah ah;
  4387. char *domain;
  4388. char buf[256 + 256 + 40];
  4389. char *f_user;
  4390. char *f_domain;
  4391. char *f_ha1;
  4392. };
  4393. static int
  4394. read_auth_file(struct file *filep, struct read_auth_file_struct *workdata)
  4395. {
  4396. char *p;
  4397. int is_authorized = 0;
  4398. struct file fp;
  4399. size_t l;
  4400. if (!filep || !workdata) {
  4401. return 0;
  4402. }
  4403. /* Loop over passwords file */
  4404. p = (char *)filep->membuf;
  4405. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  4406. l = strlen(workdata->buf);
  4407. while (l > 0) {
  4408. if (isspace(workdata->buf[l - 1])
  4409. || iscntrl(workdata->buf[l - 1])) {
  4410. l--;
  4411. workdata->buf[l] = 0;
  4412. } else
  4413. break;
  4414. }
  4415. if (l < 1) {
  4416. continue;
  4417. }
  4418. workdata->f_user = workdata->buf;
  4419. if (workdata->f_user[0] == ':') {
  4420. /* user names may not contain a ':' and may not be empty,
  4421. * so lines starting with ':' may be used for a special purpose */
  4422. if (workdata->f_user[1] == '#') {
  4423. /* :# is a comment */
  4424. continue;
  4425. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  4426. if (mg_fopen(workdata->conn, workdata->f_user + 9, "r", &fp)) {
  4427. is_authorized = read_auth_file(&fp, workdata);
  4428. mg_fclose(&fp);
  4429. } else {
  4430. mg_cry(workdata->conn,
  4431. "%s: cannot open authorization file: %s",
  4432. __func__,
  4433. workdata->buf);
  4434. }
  4435. continue;
  4436. }
  4437. /* everything is invalid for the moment (might change in the
  4438. * future) */
  4439. mg_cry(workdata->conn,
  4440. "%s: syntax error in authorization file: %s",
  4441. __func__,
  4442. workdata->buf);
  4443. continue;
  4444. }
  4445. workdata->f_domain = strchr(workdata->f_user, ':');
  4446. if (workdata->f_domain == NULL) {
  4447. mg_cry(workdata->conn,
  4448. "%s: syntax error in authorization file: %s",
  4449. __func__,
  4450. workdata->buf);
  4451. continue;
  4452. }
  4453. *(workdata->f_domain) = 0;
  4454. (workdata->f_domain)++;
  4455. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  4456. if (workdata->f_ha1 == NULL) {
  4457. mg_cry(workdata->conn,
  4458. "%s: syntax error in authorization file: %s",
  4459. __func__,
  4460. workdata->buf);
  4461. continue;
  4462. }
  4463. *(workdata->f_ha1) = 0;
  4464. (workdata->f_ha1)++;
  4465. if (!strcmp(workdata->ah.user, workdata->f_user)
  4466. && !strcmp(workdata->domain, workdata->f_domain)) {
  4467. return check_password(workdata->conn->request_info.request_method,
  4468. workdata->f_ha1,
  4469. workdata->ah.uri,
  4470. workdata->ah.nonce,
  4471. workdata->ah.nc,
  4472. workdata->ah.cnonce,
  4473. workdata->ah.qop,
  4474. workdata->ah.response);
  4475. }
  4476. }
  4477. return is_authorized;
  4478. }
  4479. /* Authorize against the opened passwords file. Return 1 if authorized. */
  4480. static int
  4481. authorize(struct mg_connection *conn, struct file *filep)
  4482. {
  4483. struct read_auth_file_struct workdata;
  4484. char buf[MG_BUF_LEN];
  4485. if (!conn || !conn->ctx) {
  4486. return 0;
  4487. }
  4488. memset(&workdata, 0, sizeof(workdata));
  4489. workdata.conn = conn;
  4490. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  4491. return 0;
  4492. }
  4493. workdata.domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  4494. return read_auth_file(filep, &workdata);
  4495. }
  4496. /* Return 1 if request is authorised, 0 otherwise. */
  4497. static int
  4498. check_authorization(struct mg_connection *conn, const char *path)
  4499. {
  4500. char fname[PATH_MAX];
  4501. struct vec uri_vec, filename_vec;
  4502. const char *list;
  4503. struct file file = STRUCT_FILE_INITIALIZER;
  4504. int authorized = 1, truncated;
  4505. if (!conn || !conn->ctx) {
  4506. return 0;
  4507. }
  4508. list = conn->ctx->config[PROTECT_URI];
  4509. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  4510. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  4511. mg_snprintf(conn,
  4512. &truncated,
  4513. fname,
  4514. sizeof(fname),
  4515. "%.*s",
  4516. (int)filename_vec.len,
  4517. filename_vec.ptr);
  4518. if (truncated || !mg_fopen(conn, fname, "r", &file)) {
  4519. mg_cry(conn,
  4520. "%s: cannot open %s: %s",
  4521. __func__,
  4522. fname,
  4523. strerror(errno));
  4524. }
  4525. break;
  4526. }
  4527. }
  4528. if (!is_file_opened(&file)) {
  4529. open_auth_file(conn, path, &file);
  4530. }
  4531. if (is_file_opened(&file)) {
  4532. authorized = authorize(conn, &file);
  4533. mg_fclose(&file);
  4534. }
  4535. return authorized;
  4536. }
  4537. static void
  4538. send_authorization_request(struct mg_connection *conn)
  4539. {
  4540. char date[64];
  4541. time_t curtime = time(NULL);
  4542. if (conn && conn->ctx) {
  4543. uint64_t nonce = (uint64_t)(conn->ctx->start_time);
  4544. (void)pthread_mutex_lock(&conn->ctx->nonce_mutex);
  4545. nonce += conn->ctx->nonce_count;
  4546. ++conn->ctx->nonce_count;
  4547. (void)pthread_mutex_unlock(&conn->ctx->nonce_mutex);
  4548. nonce ^= conn->ctx->auth_nonce_mask;
  4549. conn->status_code = 401;
  4550. conn->must_close = 1;
  4551. gmt_time_string(date, sizeof(date), &curtime);
  4552. mg_printf(conn,
  4553. "HTTP/1.1 401 Unauthorized\r\n"
  4554. "Date: %s\r\n"
  4555. "Cache-Control: no-cache\r\n"
  4556. "Connection: %s\r\n"
  4557. "Content-Length: 0\r\n"
  4558. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  4559. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  4560. date,
  4561. suggest_connection_header(conn),
  4562. conn->ctx->config[AUTHENTICATION_DOMAIN],
  4563. nonce);
  4564. }
  4565. }
  4566. #if !defined(NO_FILES)
  4567. static int
  4568. is_authorized_for_put(struct mg_connection *conn)
  4569. {
  4570. if (conn) {
  4571. struct file file = STRUCT_FILE_INITIALIZER;
  4572. const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
  4573. int ret = 0;
  4574. if (passfile != NULL && mg_fopen(conn, passfile, "r", &file)) {
  4575. ret = authorize(conn, &file);
  4576. mg_fclose(&file);
  4577. }
  4578. return ret;
  4579. }
  4580. return 0;
  4581. }
  4582. #endif
  4583. int
  4584. mg_modify_passwords_file(const char *fname,
  4585. const char *domain,
  4586. const char *user,
  4587. const char *pass)
  4588. {
  4589. int found, i;
  4590. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  4591. FILE *fp, *fp2;
  4592. found = 0;
  4593. fp = fp2 = NULL;
  4594. /* Regard empty password as no password - remove user record. */
  4595. if (pass != NULL && pass[0] == '\0') {
  4596. pass = NULL;
  4597. }
  4598. /* Other arguments must not be empty */
  4599. if (fname == NULL || domain == NULL || user == NULL) {
  4600. return 0;
  4601. }
  4602. /* Using the given file format, user name and domain must not contain ':'
  4603. */
  4604. if (strchr(user, ':') != NULL) {
  4605. return 0;
  4606. }
  4607. if (strchr(domain, ':') != NULL) {
  4608. return 0;
  4609. }
  4610. /* Do not allow control characters like newline in user name and domain.
  4611. * Do not allow excessively long names either. */
  4612. for (i = 0; i < 255 && user[i] != 0; i++) {
  4613. if (iscntrl(user[i])) {
  4614. return 0;
  4615. }
  4616. }
  4617. if (user[i]) {
  4618. return 0;
  4619. }
  4620. for (i = 0; i < 255 && domain[i] != 0; i++) {
  4621. if (iscntrl(domain[i])) {
  4622. return 0;
  4623. }
  4624. }
  4625. if (domain[i]) {
  4626. return 0;
  4627. }
  4628. /* The maximum length of the path to the password file is limited */
  4629. if ((strlen(fname) + 4) >= PATH_MAX) {
  4630. return 0;
  4631. }
  4632. /* Create a temporary file name. Length has been checked before. */
  4633. strcpy(tmp, fname);
  4634. strcat(tmp, ".tmp");
  4635. /* Create the file if does not exist */
  4636. if ((fp = fopen(fname, "a+")) != NULL) {
  4637. (void)fclose(fp);
  4638. }
  4639. /* Open the given file and temporary file */
  4640. if ((fp = fopen(fname, "r")) == NULL) {
  4641. return 0;
  4642. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  4643. fclose(fp);
  4644. return 0;
  4645. }
  4646. /* Copy the stuff to temporary file */
  4647. while (fgets(line, sizeof(line), fp) != NULL) {
  4648. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  4649. continue;
  4650. }
  4651. u[255] = 0;
  4652. d[255] = 0;
  4653. if (!strcmp(u, user) && !strcmp(d, domain)) {
  4654. found++;
  4655. if (pass != NULL) {
  4656. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  4657. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  4658. }
  4659. } else {
  4660. fprintf(fp2, "%s", line);
  4661. }
  4662. }
  4663. /* If new user, just add it */
  4664. if (!found && pass != NULL) {
  4665. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  4666. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  4667. }
  4668. /* Close files */
  4669. fclose(fp);
  4670. fclose(fp2);
  4671. /* Put the temp file in place of real file */
  4672. IGNORE_UNUSED_RESULT(remove(fname));
  4673. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  4674. return 1;
  4675. }
  4676. static int
  4677. is_valid_port(unsigned long port)
  4678. {
  4679. return port < 0xffff;
  4680. }
  4681. static int
  4682. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  4683. {
  4684. struct addrinfo hints, *res, *ressave;
  4685. int ret = 0;
  4686. memset(&hints, 0, sizeof(struct addrinfo));
  4687. hints.ai_family = af;
  4688. if (getaddrinfo(src, NULL, &hints, &res) != 0) {
  4689. /* bad src string or bad address family */
  4690. return 0;
  4691. }
  4692. ressave = res;
  4693. while (res) {
  4694. if (dstlen >= res->ai_addrlen) {
  4695. memcpy(dst, res->ai_addr, res->ai_addrlen);
  4696. ret = 1;
  4697. }
  4698. res = res->ai_next;
  4699. }
  4700. freeaddrinfo(ressave);
  4701. return ret;
  4702. }
  4703. static int
  4704. connect_socket(struct mg_context *ctx /* may be NULL */,
  4705. const char *host,
  4706. int port,
  4707. int use_ssl,
  4708. char *ebuf,
  4709. size_t ebuf_len,
  4710. SOCKET *sock /* output: socket, must not be NULL */,
  4711. union usa *sa /* output: socket address, must not be NULL */
  4712. )
  4713. {
  4714. int ip_ver = 0;
  4715. *sock = INVALID_SOCKET;
  4716. memset(sa, 0, sizeof(*sa));
  4717. if (ebuf_len > 0) {
  4718. *ebuf = 0;
  4719. }
  4720. if (host == NULL) {
  4721. mg_snprintf(NULL,
  4722. NULL, /* No truncation check for ebuf */
  4723. ebuf,
  4724. ebuf_len,
  4725. "%s",
  4726. "NULL host");
  4727. return 0;
  4728. }
  4729. if (port < 0 || !is_valid_port((unsigned)port)) {
  4730. mg_snprintf(NULL,
  4731. NULL, /* No truncation check for ebuf */
  4732. ebuf,
  4733. ebuf_len,
  4734. "%s",
  4735. "invalid port");
  4736. return 0;
  4737. }
  4738. if (use_ssl && (SSLv23_client_method == NULL)) {
  4739. mg_snprintf(NULL,
  4740. NULL, /* No truncation check for ebuf */
  4741. ebuf,
  4742. ebuf_len,
  4743. "%s",
  4744. "SSL is not initialized");
  4745. return 0;
  4746. }
  4747. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  4748. sa->sin.sin_port = htons((uint16_t)port);
  4749. ip_ver = 4;
  4750. #ifdef USE_IPV6
  4751. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  4752. sa->sin6.sin6_port = htons((uint16_t)port);
  4753. ip_ver = 6;
  4754. } else if (host[0] == '[') {
  4755. /* While getaddrinfo on Windows will work with [::1],
  4756. * getaddrinfo on Linux only works with ::1 (without []). */
  4757. size_t l = strlen(host + 1);
  4758. char *h = l > 1 ? mg_strdup(host + 1) : NULL;
  4759. if (h) {
  4760. h[l - 1] = 0;
  4761. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  4762. sa->sin6.sin6_port = htons((uint16_t)port);
  4763. ip_ver = 6;
  4764. }
  4765. mg_free(h);
  4766. }
  4767. #endif
  4768. }
  4769. if (ip_ver == 0) {
  4770. mg_snprintf(NULL,
  4771. NULL, /* No truncation check for ebuf */
  4772. ebuf,
  4773. ebuf_len,
  4774. "%s",
  4775. "host not found");
  4776. return 0;
  4777. }
  4778. if (ip_ver == 4) {
  4779. *sock = socket(PF_INET, SOCK_STREAM, 0);
  4780. }
  4781. #ifdef USE_IPV6
  4782. else if (ip_ver == 6) {
  4783. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  4784. }
  4785. #endif
  4786. if (*sock == INVALID_SOCKET) {
  4787. mg_snprintf(NULL,
  4788. NULL, /* No truncation check for ebuf */
  4789. ebuf,
  4790. ebuf_len,
  4791. "socket(): %s",
  4792. strerror(ERRNO));
  4793. return 0;
  4794. }
  4795. set_close_on_exec(*sock, fc(ctx));
  4796. if ((ip_ver == 4)
  4797. && (connect(*sock, (struct sockaddr *)&sa->sin, sizeof(sa->sin))
  4798. == 0)) {
  4799. /* connected with IPv4 */
  4800. return 1;
  4801. }
  4802. #ifdef USE_IPV6
  4803. if ((ip_ver == 6)
  4804. && (connect(*sock, (struct sockaddr *)&sa->sin6, sizeof(sa->sin6))
  4805. == 0)) {
  4806. /* connected with IPv6 */
  4807. return 1;
  4808. }
  4809. #endif
  4810. /* Not connected */
  4811. mg_snprintf(NULL,
  4812. NULL, /* No truncation check for ebuf */
  4813. ebuf,
  4814. ebuf_len,
  4815. "connect(%s:%d): %s",
  4816. host,
  4817. port,
  4818. strerror(ERRNO));
  4819. closesocket(*sock);
  4820. *sock = INVALID_SOCKET;
  4821. return 0;
  4822. }
  4823. int
  4824. mg_url_encode(const char *src, char *dst, size_t dst_len)
  4825. {
  4826. static const char *dont_escape = "._-$,;~()";
  4827. static const char *hex = "0123456789abcdef";
  4828. char *pos = dst;
  4829. const char *end = dst + dst_len - 1;
  4830. for (; *src != '\0' && pos < end; src++, pos++) {
  4831. if (isalnum(*(const unsigned char *)src)
  4832. || strchr(dont_escape, *(const unsigned char *)src) != NULL) {
  4833. *pos = *src;
  4834. } else if (pos + 2 < end) {
  4835. pos[0] = '%';
  4836. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  4837. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  4838. pos += 2;
  4839. } else {
  4840. break;
  4841. }
  4842. }
  4843. *pos = '\0';
  4844. return (*src == '\0') ? (int)(pos - dst) : -1;
  4845. }
  4846. static void
  4847. print_dir_entry(struct de *de)
  4848. {
  4849. char size[64], mod[64], href[PATH_MAX];
  4850. struct tm *tm;
  4851. if (de->file.is_directory) {
  4852. mg_snprintf(de->conn,
  4853. NULL, /* Buffer is big enough */
  4854. size,
  4855. sizeof(size),
  4856. "%s",
  4857. "[DIRECTORY]");
  4858. } else {
  4859. /* We use (signed) cast below because MSVC 6 compiler cannot
  4860. * convert unsigned __int64 to double. Sigh. */
  4861. if (de->file.size < 1024) {
  4862. mg_snprintf(de->conn,
  4863. NULL, /* Buffer is big enough */
  4864. size,
  4865. sizeof(size),
  4866. "%d",
  4867. (int)de->file.size);
  4868. } else if (de->file.size < 0x100000) {
  4869. mg_snprintf(de->conn,
  4870. NULL, /* Buffer is big enough */
  4871. size,
  4872. sizeof(size),
  4873. "%.1fk",
  4874. (double)de->file.size / 1024.0);
  4875. } else if (de->file.size < 0x40000000) {
  4876. mg_snprintf(de->conn,
  4877. NULL, /* Buffer is big enough */
  4878. size,
  4879. sizeof(size),
  4880. "%.1fM",
  4881. (double)de->file.size / 1048576);
  4882. } else {
  4883. mg_snprintf(de->conn,
  4884. NULL, /* Buffer is big enough */
  4885. size,
  4886. sizeof(size),
  4887. "%.1fG",
  4888. (double)de->file.size / 1073741824);
  4889. }
  4890. }
  4891. /* Note: mg_snprintf will not cause a buffer overflow above.
  4892. * So, string truncation checks are not required here. */
  4893. tm = localtime(&de->file.last_modified);
  4894. if (tm != NULL) {
  4895. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  4896. } else {
  4897. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  4898. mod[sizeof(mod) - 1] = '\0';
  4899. }
  4900. mg_url_encode(de->file_name, href, sizeof(href));
  4901. de->conn->num_bytes_sent +=
  4902. mg_printf(de->conn,
  4903. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  4904. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  4905. de->conn->request_info.local_uri,
  4906. href,
  4907. de->file.is_directory ? "/" : "",
  4908. de->file_name,
  4909. de->file.is_directory ? "/" : "",
  4910. mod,
  4911. size);
  4912. }
  4913. /* This function is called from send_directory() and used for
  4914. * sorting directory entries by size, or name, or modification time.
  4915. * On windows, __cdecl specification is needed in case if project is built
  4916. * with __stdcall convention. qsort always requires __cdels callback. */
  4917. static int WINCDECL
  4918. compare_dir_entries(const void *p1, const void *p2)
  4919. {
  4920. if (p1 && p2) {
  4921. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  4922. const char *query_string = a->conn->request_info.query_string;
  4923. int cmp_result = 0;
  4924. if (query_string == NULL) {
  4925. query_string = "na";
  4926. }
  4927. if (a->file.is_directory && !b->file.is_directory) {
  4928. return -1; /* Always put directories on top */
  4929. } else if (!a->file.is_directory && b->file.is_directory) {
  4930. return 1; /* Always put directories on top */
  4931. } else if (*query_string == 'n') {
  4932. cmp_result = strcmp(a->file_name, b->file_name);
  4933. } else if (*query_string == 's') {
  4934. cmp_result = a->file.size == b->file.size
  4935. ? 0
  4936. : a->file.size > b->file.size ? 1 : -1;
  4937. } else if (*query_string == 'd') {
  4938. cmp_result =
  4939. (a->file.last_modified == b->file.last_modified)
  4940. ? 0
  4941. : ((a->file.last_modified > b->file.last_modified) ? 1
  4942. : -1);
  4943. }
  4944. return query_string[1] == 'd' ? -cmp_result : cmp_result;
  4945. }
  4946. return 0;
  4947. }
  4948. static int
  4949. must_hide_file(struct mg_connection *conn, const char *path)
  4950. {
  4951. if (conn && conn->ctx) {
  4952. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  4953. const char *pattern = conn->ctx->config[HIDE_FILES];
  4954. return match_prefix(pw_pattern, strlen(pw_pattern), path) > 0
  4955. || (pattern != NULL
  4956. && match_prefix(pattern, strlen(pattern), path) > 0);
  4957. }
  4958. return 0;
  4959. }
  4960. static int
  4961. scan_directory(struct mg_connection *conn,
  4962. const char *dir,
  4963. void *data,
  4964. void (*cb)(struct de *, void *))
  4965. {
  4966. char path[PATH_MAX];
  4967. struct dirent *dp;
  4968. DIR *dirp;
  4969. struct de de;
  4970. int truncated;
  4971. if ((dirp = opendir(dir)) == NULL) {
  4972. return 0;
  4973. } else {
  4974. de.conn = conn;
  4975. while ((dp = readdir(dirp)) != NULL) {
  4976. /* Do not show current dir and hidden files */
  4977. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  4978. || must_hide_file(conn, dp->d_name)) {
  4979. continue;
  4980. }
  4981. mg_snprintf(
  4982. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  4983. /* If we don't memset stat structure to zero, mtime will have
  4984. * garbage and strftime() will segfault later on in
  4985. * print_dir_entry(). memset is required only if mg_stat()
  4986. * fails. For more details, see
  4987. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  4988. memset(&de.file, 0, sizeof(de.file));
  4989. if (truncated) {
  4990. /* If the path is not complete, skip processing. */
  4991. continue;
  4992. }
  4993. if (!mg_stat(conn, path, &de.file)) {
  4994. mg_cry(conn,
  4995. "%s: mg_stat(%s) failed: %s",
  4996. __func__,
  4997. path,
  4998. strerror(ERRNO));
  4999. }
  5000. de.file_name = dp->d_name;
  5001. cb(&de, data);
  5002. }
  5003. (void)closedir(dirp);
  5004. }
  5005. return 1;
  5006. }
  5007. #if !defined(NO_FILES)
  5008. static int
  5009. remove_directory(struct mg_connection *conn, const char *dir)
  5010. {
  5011. char path[PATH_MAX];
  5012. struct dirent *dp;
  5013. DIR *dirp;
  5014. struct de de;
  5015. int truncated;
  5016. int ok = 1;
  5017. if ((dirp = opendir(dir)) == NULL) {
  5018. return 0;
  5019. } else {
  5020. de.conn = conn;
  5021. while ((dp = readdir(dirp)) != NULL) {
  5022. /* Do not show current dir (but show hidden files as they will
  5023. * also be removed) */
  5024. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  5025. continue;
  5026. }
  5027. mg_snprintf(
  5028. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  5029. /* If we don't memset stat structure to zero, mtime will have
  5030. * garbage and strftime() will segfault later on in
  5031. * print_dir_entry(). memset is required only if mg_stat()
  5032. * fails. For more details, see
  5033. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  5034. memset(&de.file, 0, sizeof(de.file));
  5035. if (truncated) {
  5036. /* Do not delete anything shorter */
  5037. ok = 0;
  5038. continue;
  5039. }
  5040. if (!mg_stat(conn, path, &de.file)) {
  5041. mg_cry(conn,
  5042. "%s: mg_stat(%s) failed: %s",
  5043. __func__,
  5044. path,
  5045. strerror(ERRNO));
  5046. ok = 0;
  5047. }
  5048. if (de.file.membuf == NULL) {
  5049. /* file is not in memory */
  5050. if (de.file.is_directory) {
  5051. if (remove_directory(conn, path) == 0) {
  5052. ok = 0;
  5053. }
  5054. } else {
  5055. if (mg_remove(path) == 0) {
  5056. ok = 0;
  5057. }
  5058. }
  5059. } else {
  5060. /* file is in memory. It can not be deleted. */
  5061. ok = 0;
  5062. }
  5063. }
  5064. (void)closedir(dirp);
  5065. IGNORE_UNUSED_RESULT(rmdir(dir));
  5066. }
  5067. return ok;
  5068. }
  5069. #endif
  5070. struct dir_scan_data {
  5071. struct de *entries;
  5072. unsigned int num_entries;
  5073. unsigned int arr_size;
  5074. };
  5075. /* Behaves like realloc(), but frees original pointer on failure */
  5076. static void *
  5077. realloc2(void *ptr, size_t size)
  5078. {
  5079. void *new_ptr = mg_realloc(ptr, size);
  5080. if (new_ptr == NULL) {
  5081. mg_free(ptr);
  5082. }
  5083. return new_ptr;
  5084. }
  5085. static void
  5086. dir_scan_callback(struct de *de, void *data)
  5087. {
  5088. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  5089. if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {
  5090. dsd->arr_size *= 2;
  5091. dsd->entries =
  5092. (struct de *)realloc2(dsd->entries,
  5093. dsd->arr_size * sizeof(dsd->entries[0]));
  5094. }
  5095. if (dsd->entries == NULL) {
  5096. /* TODO(lsm, low): propagate an error to the caller */
  5097. dsd->num_entries = 0;
  5098. } else {
  5099. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  5100. dsd->entries[dsd->num_entries].file = de->file;
  5101. dsd->entries[dsd->num_entries].conn = de->conn;
  5102. dsd->num_entries++;
  5103. }
  5104. }
  5105. static void
  5106. handle_directory_request(struct mg_connection *conn, const char *dir)
  5107. {
  5108. unsigned int i;
  5109. int sort_direction;
  5110. struct dir_scan_data data = {NULL, 0, 128};
  5111. char date[64];
  5112. time_t curtime = time(NULL);
  5113. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  5114. send_http_error(conn,
  5115. 500,
  5116. "Error: Cannot open directory\nopendir(%s): %s",
  5117. dir,
  5118. strerror(ERRNO));
  5119. return;
  5120. }
  5121. gmt_time_string(date, sizeof(date), &curtime);
  5122. if (!conn) {
  5123. return;
  5124. }
  5125. sort_direction = conn->request_info.query_string != NULL
  5126. && conn->request_info.query_string[1] == 'd'
  5127. ? 'a'
  5128. : 'd';
  5129. conn->must_close = 1;
  5130. mg_printf(conn,
  5131. "HTTP/1.1 200 OK\r\n"
  5132. "Date: %s\r\n"
  5133. /* TODO: Cache-Control */
  5134. "Connection: close\r\n"
  5135. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  5136. date);
  5137. conn->num_bytes_sent +=
  5138. mg_printf(conn,
  5139. "<html><head><title>Index of %s</title>"
  5140. "<style>th {text-align: left;}</style></head>"
  5141. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  5142. "<tr><th><a href=\"?n%c\">Name</a></th>"
  5143. "<th><a href=\"?d%c\">Modified</a></th>"
  5144. "<th><a href=\"?s%c\">Size</a></th></tr>"
  5145. "<tr><td colspan=\"3\"><hr></td></tr>",
  5146. conn->request_info.local_uri,
  5147. conn->request_info.local_uri,
  5148. sort_direction,
  5149. sort_direction,
  5150. sort_direction);
  5151. /* Print first entry - link to a parent directory */
  5152. conn->num_bytes_sent +=
  5153. mg_printf(conn,
  5154. "<tr><td><a href=\"%s%s\">%s</a></td>"
  5155. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  5156. conn->request_info.local_uri,
  5157. "..",
  5158. "Parent directory",
  5159. "-",
  5160. "-");
  5161. /* Sort and print directory entries */
  5162. if (data.entries != NULL) {
  5163. qsort(data.entries,
  5164. (size_t)data.num_entries,
  5165. sizeof(data.entries[0]),
  5166. compare_dir_entries);
  5167. for (i = 0; i < data.num_entries; i++) {
  5168. print_dir_entry(&data.entries[i]);
  5169. mg_free(data.entries[i].file_name);
  5170. }
  5171. mg_free(data.entries);
  5172. }
  5173. conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");
  5174. conn->status_code = 200;
  5175. }
  5176. /* Send len bytes from the opened file to the client. */
  5177. static void
  5178. send_file_data(struct mg_connection *conn,
  5179. struct file *filep,
  5180. int64_t offset,
  5181. int64_t len)
  5182. {
  5183. char buf[MG_BUF_LEN];
  5184. int to_read, num_read, num_written;
  5185. int64_t size;
  5186. if (!filep || !conn) {
  5187. return;
  5188. }
  5189. /* Sanity check the offset */
  5190. size = filep->size > INT64_MAX ? INT64_MAX : (int64_t)(filep->size);
  5191. offset = offset < 0 ? 0 : offset > size ? size : offset;
  5192. if (len > 0 && filep->membuf != NULL && size > 0) {
  5193. /* file stored in memory */
  5194. if (len > size - offset) {
  5195. len = size - offset;
  5196. }
  5197. mg_write(conn, filep->membuf + offset, (size_t)len);
  5198. } else if (len > 0 && filep->fp != NULL) {
  5199. /* file stored on disk */
  5200. #if defined(__linux__)
  5201. /* sendfile is only available for Linux */
  5202. if (conn->throttle == 0 && conn->ssl == 0) {
  5203. off_t sf_offs = (off_t)offset;
  5204. ssize_t sf_sent;
  5205. int sf_file = fileno(filep->fp);
  5206. int loop_cnt = 0;
  5207. do {
  5208. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  5209. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  5210. size_t sf_tosend =
  5211. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  5212. sf_sent =
  5213. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  5214. if (sf_sent > 0) {
  5215. conn->num_bytes_sent += sf_sent;
  5216. len -= sf_sent;
  5217. offset += sf_sent;
  5218. } else if (loop_cnt == 0) {
  5219. /* This file can not be sent using sendfile.
  5220. * This might be the case for pseudo-files in the
  5221. * /sys/ and /proc/ file system.
  5222. * Use the regular user mode copy code instead. */
  5223. break;
  5224. } else if (sf_sent == 0) {
  5225. /* No error, but 0 bytes sent. May be EOF? */
  5226. return;
  5227. }
  5228. loop_cnt++;
  5229. } while ((len > 0) && (sf_sent >= 0));
  5230. if (sf_sent > 0) {
  5231. return; /* OK */
  5232. }
  5233. /* sf_sent<0 means error, thus fall back to the classic way */
  5234. /* This is always the case, if sf_file is not a "normal" file,
  5235. * e.g., for sending data from the output of a CGI process. */
  5236. offset = (int64_t)sf_offs;
  5237. }
  5238. #endif
  5239. if ((offset > 0) && (fseeko(filep->fp, offset, SEEK_SET) != 0)) {
  5240. mg_cry(conn, "%s: fseeko() failed: %s", __func__, strerror(ERRNO));
  5241. send_http_error(
  5242. conn,
  5243. 500,
  5244. "%s",
  5245. "Error: Unable to access file at requested position.");
  5246. } else {
  5247. while (len > 0) {
  5248. /* Calculate how much to read from the file in the buffer */
  5249. to_read = sizeof(buf);
  5250. if ((int64_t)to_read > len) {
  5251. to_read = (int)len;
  5252. }
  5253. /* Read from file, exit the loop on error */
  5254. if ((num_read = (int)fread(buf, 1, (size_t)to_read, filep->fp))
  5255. <= 0) {
  5256. break;
  5257. }
  5258. /* Send read bytes to the client, exit the loop on error */
  5259. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  5260. != num_read) {
  5261. break;
  5262. }
  5263. /* Both read and were successful, adjust counters */
  5264. conn->num_bytes_sent += num_written;
  5265. len -= num_written;
  5266. }
  5267. }
  5268. }
  5269. }
  5270. static int
  5271. parse_range_header(const char *header, int64_t *a, int64_t *b)
  5272. {
  5273. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  5274. }
  5275. static void
  5276. construct_etag(char *buf, size_t buf_len, const struct file *filep)
  5277. {
  5278. if (filep != NULL && buf != NULL) {
  5279. mg_snprintf(NULL,
  5280. NULL, /* All calls to construct_etag use 64 byte buffer */
  5281. buf,
  5282. buf_len,
  5283. "\"%lx.%" INT64_FMT "\"",
  5284. (unsigned long)filep->last_modified,
  5285. filep->size);
  5286. }
  5287. }
  5288. static void
  5289. fclose_on_exec(struct file *filep, struct mg_connection *conn)
  5290. {
  5291. if (filep != NULL && filep->fp != NULL) {
  5292. #ifdef _WIN32
  5293. (void)conn; /* Unused. */
  5294. #else
  5295. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  5296. mg_cry(conn,
  5297. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  5298. __func__,
  5299. strerror(ERRNO));
  5300. }
  5301. #endif
  5302. }
  5303. }
  5304. static void
  5305. handle_static_file_request(struct mg_connection *conn,
  5306. const char *path,
  5307. struct file *filep)
  5308. {
  5309. char date[64], lm[64], etag[64];
  5310. char range[128]; /* large enough, so there will be no overflow */
  5311. const char *msg = "OK", *hdr;
  5312. time_t curtime = time(NULL);
  5313. int64_t cl, r1, r2;
  5314. struct vec mime_vec;
  5315. int n, truncated;
  5316. char gz_path[PATH_MAX];
  5317. const char *encoding = "";
  5318. const char *cors1, *cors2, *cors3;
  5319. if (conn == NULL || conn->ctx == NULL || filep == NULL) {
  5320. return;
  5321. }
  5322. get_mime_type(conn->ctx, path, &mime_vec);
  5323. if (filep->size > INT64_MAX) {
  5324. send_http_error(conn,
  5325. 500,
  5326. "Error: File size is too large to send\n%" INT64_FMT,
  5327. filep->size);
  5328. }
  5329. cl = (int64_t)filep->size;
  5330. conn->status_code = 200;
  5331. range[0] = '\0';
  5332. /* if this file is in fact a pre-gzipped file, rewrite its filename
  5333. * it's important to rewrite the filename after resolving
  5334. * the mime type from it, to preserve the actual file's type */
  5335. if (filep->gzipped) {
  5336. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  5337. if (truncated) {
  5338. send_http_error(conn,
  5339. 500,
  5340. "Error: Path of zipped file too long (%s)",
  5341. path);
  5342. return;
  5343. }
  5344. path = gz_path;
  5345. encoding = "Content-Encoding: gzip\r\n";
  5346. }
  5347. if (!mg_fopen(conn, path, "rb", filep)) {
  5348. send_http_error(conn,
  5349. 500,
  5350. "Error: Cannot open file\nfopen(%s): %s",
  5351. path,
  5352. strerror(ERRNO));
  5353. return;
  5354. }
  5355. fclose_on_exec(filep, conn);
  5356. /* If Range: header specified, act accordingly */
  5357. r1 = r2 = 0;
  5358. hdr = mg_get_header(conn, "Range");
  5359. if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 && r1 >= 0
  5360. && r2 >= 0) {
  5361. /* actually, range requests don't play well with a pre-gzipped
  5362. * file (since the range is specified in the uncompressed space) */
  5363. if (filep->gzipped) {
  5364. send_http_error(
  5365. conn,
  5366. 501,
  5367. "%s",
  5368. "Error: Range requests in gzipped files are not supported");
  5369. mg_fclose(filep);
  5370. return;
  5371. }
  5372. conn->status_code = 206;
  5373. cl = n == 2 ? (r2 > cl ? cl : r2) - r1 + 1 : cl - r1;
  5374. mg_snprintf(conn,
  5375. NULL, /* range buffer is big enough */
  5376. range,
  5377. sizeof(range),
  5378. "Content-Range: bytes "
  5379. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  5380. r1,
  5381. r1 + cl - 1,
  5382. filep->size);
  5383. msg = "Partial Content";
  5384. }
  5385. hdr = mg_get_header(conn, "Origin");
  5386. if (hdr) {
  5387. /* Cross-origin resource sharing (CORS), see
  5388. * http://www.html5rocks.com/en/tutorials/cors/,
  5389. * http://www.html5rocks.com/static/images/cors_server_flowchart.png -
  5390. * preflight is not supported for files. */
  5391. cors1 = "Access-Control-Allow-Origin: ";
  5392. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  5393. cors3 = "\r\n";
  5394. } else {
  5395. cors1 = cors2 = cors3 = "";
  5396. }
  5397. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
  5398. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  5399. gmt_time_string(date, sizeof(date), &curtime);
  5400. gmt_time_string(lm, sizeof(lm), &filep->last_modified);
  5401. construct_etag(etag, sizeof(etag), filep);
  5402. (void)mg_printf(conn,
  5403. "HTTP/1.1 %d %s\r\n"
  5404. "%s%s%s"
  5405. "Date: %s\r\n"
  5406. /* TODO: "Cache-Control" */
  5407. "Last-Modified: %s\r\n"
  5408. "Etag: %s\r\n"
  5409. "Content-Type: %.*s\r\n"
  5410. "Content-Length: %" INT64_FMT "\r\n"
  5411. "Connection: %s\r\n"
  5412. "Accept-Ranges: bytes\r\n"
  5413. "%s%s\r\n",
  5414. conn->status_code,
  5415. msg,
  5416. cors1,
  5417. cors2,
  5418. cors3,
  5419. date,
  5420. lm,
  5421. etag,
  5422. (int)mime_vec.len,
  5423. mime_vec.ptr,
  5424. cl,
  5425. suggest_connection_header(conn),
  5426. range,
  5427. encoding);
  5428. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  5429. send_file_data(conn, filep, r1, cl);
  5430. }
  5431. mg_fclose(filep);
  5432. }
  5433. void
  5434. mg_send_file(struct mg_connection *conn, const char *path)
  5435. {
  5436. struct file file = STRUCT_FILE_INITIALIZER;
  5437. if (mg_stat(conn, path, &file)) {
  5438. if (file.is_directory) {
  5439. if (!conn) {
  5440. return;
  5441. }
  5442. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  5443. "yes")) {
  5444. handle_directory_request(conn, path);
  5445. } else {
  5446. send_http_error(conn,
  5447. 403,
  5448. "%s",
  5449. "Error: Directory listing denied");
  5450. }
  5451. } else {
  5452. handle_static_file_request(conn, path, &file);
  5453. }
  5454. } else {
  5455. send_http_error(conn, 404, "%s", "Error: File not found");
  5456. }
  5457. }
  5458. /* Parse HTTP headers from the given buffer, advance buffer to the point
  5459. * where parsing stopped. */
  5460. static void
  5461. parse_http_headers(char **buf, struct mg_request_info *ri)
  5462. {
  5463. int i;
  5464. if (!ri) {
  5465. return;
  5466. }
  5467. ri->num_headers = 0;
  5468. for (i = 0; i < (int)ARRAY_SIZE(ri->http_headers); i++) {
  5469. ri->http_headers[i].name = skip_quoted(buf, ":", " ", 0);
  5470. ri->http_headers[i].value = skip(buf, "\r\n");
  5471. if (ri->http_headers[i].name[0] == '\0') {
  5472. break;
  5473. }
  5474. ri->num_headers = i + 1;
  5475. }
  5476. }
  5477. static int
  5478. is_valid_http_method(const char *method)
  5479. {
  5480. return !strcmp(method, "GET") /* HTTP (RFC 2616) */
  5481. || !strcmp(method, "POST") /* HTTP (RFC 2616) */
  5482. || !strcmp(method, "HEAD") /* HTTP (RFC 2616) */
  5483. || !strcmp(method, "PUT") /* HTTP (RFC 2616) */
  5484. || !strcmp(method, "DELETE") /* HTTP (RFC 2616) */
  5485. || !strcmp(method, "OPTIONS") /* HTTP (RFC 2616) */
  5486. /* TRACE method (RFC 2616) is not supported for security reasons */
  5487. || !strcmp(method, "CONNECT") /* HTTP (RFC 2616) */
  5488. || !strcmp(method, "PROPFIND") /* WEBDAV (RFC 2518) */
  5489. || !strcmp(method, "MKCOL") /* WEBDAV (RFC 2518) */
  5490. /* Unsupported WEBDAV Methods: */
  5491. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  5492. /* + 11 methods from RFC 3253 */
  5493. /* ORDERPATCH (RFC 3648) */
  5494. /* ACL (RFC 3744) */
  5495. /* SEARCH (RFC 5323) */
  5496. /* + MicroSoft extensions
  5497. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  5498. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  5499. || !strcmp(method, "PATCH"); /* PATCH method (RFC 5789) */
  5500. }
  5501. /* Parse HTTP request, fill in mg_request_info structure.
  5502. * This function modifies the buffer by NUL-terminating
  5503. * HTTP request components, header names and header values. */
  5504. static int
  5505. parse_http_message(char *buf, int len, struct mg_request_info *ri)
  5506. {
  5507. int is_request, request_length;
  5508. if (!ri) {
  5509. return 0;
  5510. }
  5511. request_length = get_request_len(buf, len);
  5512. if (request_length > 0) {
  5513. /* Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_addr,
  5514. * remote_port */
  5515. ri->remote_user = ri->request_method = ri->request_uri =
  5516. ri->http_version = NULL;
  5517. ri->num_headers = 0;
  5518. buf[request_length - 1] = '\0';
  5519. /* RFC says that all initial whitespaces should be ingored */
  5520. while (*buf != '\0' && isspace(*(unsigned char *)buf)) {
  5521. buf++;
  5522. }
  5523. ri->request_method = skip(&buf, " ");
  5524. ri->request_uri = skip(&buf, " ");
  5525. ri->http_version = skip(&buf, "\r\n");
  5526. /* HTTP message could be either HTTP request or HTTP response, e.g.
  5527. * "GET / HTTP/1.0 ...." or "HTTP/1.0 200 OK ..." */
  5528. is_request = is_valid_http_method(ri->request_method);
  5529. if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0)
  5530. || (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
  5531. request_length = -1;
  5532. } else {
  5533. if (is_request) {
  5534. ri->http_version += 5;
  5535. }
  5536. parse_http_headers(&buf, ri);
  5537. }
  5538. }
  5539. return request_length;
  5540. }
  5541. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  5542. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  5543. * buffer (which marks the end of HTTP request). Buffer buf may already
  5544. * have some data. The length of the data is stored in nread.
  5545. * Upon every read operation, increase nread by the number of bytes read. */
  5546. static int
  5547. read_request(FILE *fp,
  5548. struct mg_connection *conn,
  5549. char *buf,
  5550. int bufsiz,
  5551. int *nread)
  5552. {
  5553. int request_len, n = 0;
  5554. struct timespec last_action_time;
  5555. double request_timeout;
  5556. if (!conn) {
  5557. return 0;
  5558. }
  5559. memset(&last_action_time, 0, sizeof(last_action_time));
  5560. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  5561. /* value of request_timeout is in seconds, config in milliseconds */
  5562. request_timeout = atof(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5563. } else {
  5564. request_timeout = -1.0;
  5565. }
  5566. request_len = get_request_len(buf, *nread);
  5567. while (
  5568. (conn->ctx->stop_flag == 0) && (*nread < bufsiz) && (request_len == 0)
  5569. && ((mg_difftimespec(&last_action_time, &(conn->req_time))
  5570. <= request_timeout) || (request_timeout < 0))
  5571. && ((n = pull(fp, conn, buf + *nread, bufsiz - *nread, request_timeout))
  5572. > 0)) {
  5573. *nread += n;
  5574. /* assert(*nread <= bufsiz); */
  5575. if (*nread > bufsiz) {
  5576. return -2;
  5577. }
  5578. request_len = get_request_len(buf, *nread);
  5579. if (request_timeout > 0.0) {
  5580. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  5581. }
  5582. }
  5583. return (request_len <= 0 && n <= 0) ? -1 : request_len;
  5584. }
  5585. #if !defined(NO_FILES)
  5586. /* For given directory path, substitute it to valid index file.
  5587. * Return 1 if index file has been found, 0 if not found.
  5588. * If the file is found, it's stats is returned in stp. */
  5589. static int
  5590. substitute_index_file(struct mg_connection *conn,
  5591. char *path,
  5592. size_t path_len,
  5593. struct file *filep)
  5594. {
  5595. if (conn && conn->ctx) {
  5596. const char *list = conn->ctx->config[INDEX_FILES];
  5597. struct file file = STRUCT_FILE_INITIALIZER;
  5598. struct vec filename_vec;
  5599. size_t n = strlen(path);
  5600. int found = 0;
  5601. /* The 'path' given to us points to the directory. Remove all trailing
  5602. * directory separator characters from the end of the path, and
  5603. * then append single directory separator character. */
  5604. while (n > 0 && path[n - 1] == '/') {
  5605. n--;
  5606. }
  5607. path[n] = '/';
  5608. /* Traverse index files list. For each entry, append it to the given
  5609. * path and see if the file exists. If it exists, break the loop */
  5610. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  5611. /* Ignore too long entries that may overflow path buffer */
  5612. if (filename_vec.len > path_len - (n + 2)) {
  5613. continue;
  5614. }
  5615. /* Prepare full path to the index file */
  5616. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  5617. /* Does it exist? */
  5618. if (mg_stat(conn, path, &file)) {
  5619. /* Yes it does, break the loop */
  5620. *filep = file;
  5621. found = 1;
  5622. break;
  5623. }
  5624. }
  5625. /* If no index file exists, restore directory path */
  5626. if (!found) {
  5627. path[n] = '\0';
  5628. }
  5629. return found;
  5630. }
  5631. return 0;
  5632. }
  5633. #endif
  5634. /* Return True if we should reply 304 Not Modified. */
  5635. static int
  5636. is_not_modified(const struct mg_connection *conn, const struct file *filep)
  5637. {
  5638. char etag[64];
  5639. const char *ims = mg_get_header(conn, "If-Modified-Since");
  5640. const char *inm = mg_get_header(conn, "If-None-Match");
  5641. construct_etag(etag, sizeof(etag), filep);
  5642. if (!filep) {
  5643. return 0;
  5644. }
  5645. return (inm != NULL && !mg_strcasecmp(etag, inm))
  5646. || (ims != NULL && (filep->last_modified <= parse_date_string(ims)));
  5647. }
  5648. #if !defined(NO_CGI) || !defined(NO_FILES)
  5649. static int
  5650. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  5651. {
  5652. const char *expect, *body;
  5653. char buf[MG_BUF_LEN];
  5654. int to_read, nread, success = 0;
  5655. int64_t buffered_len;
  5656. double timeout = -1.0;
  5657. if (!conn) {
  5658. return 0;
  5659. }
  5660. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  5661. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5662. }
  5663. expect = mg_get_header(conn, "Expect");
  5664. /* assert(fp != NULL); */
  5665. if (!fp) {
  5666. send_http_error(conn, 500, "%s", "Error: NULL File");
  5667. return 0;
  5668. }
  5669. if (conn->content_len == -1 && !conn->is_chunked) {
  5670. /* Content length is not specified by the client. */
  5671. send_http_error(conn,
  5672. 411,
  5673. "%s",
  5674. "Error: Client did not specify content length");
  5675. } else if ((expect != NULL)
  5676. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  5677. /* Client sent an "Expect: xyz" header and xyz is not 100-continue. */
  5678. send_http_error(conn,
  5679. 417,
  5680. "Error: Can not fulfill expectation %s",
  5681. expect);
  5682. } else {
  5683. if (expect != NULL) {
  5684. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  5685. conn->status_code = 100;
  5686. } else {
  5687. conn->status_code = 200;
  5688. }
  5689. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5690. - conn->consumed_content;
  5691. /* assert(buffered_len >= 0); */
  5692. /* assert(conn->consumed_content == 0); */
  5693. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  5694. send_http_error(conn, 500, "%s", "Error: Size mismatch");
  5695. return 0;
  5696. }
  5697. if (buffered_len > 0) {
  5698. if ((int64_t)buffered_len > conn->content_len) {
  5699. buffered_len = (int)conn->content_len;
  5700. }
  5701. body = conn->buf + conn->request_len + conn->consumed_content;
  5702. push_all(conn->ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  5703. conn->consumed_content += buffered_len;
  5704. }
  5705. nread = 0;
  5706. while (conn->consumed_content < conn->content_len) {
  5707. to_read = sizeof(buf);
  5708. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  5709. to_read = (int)(conn->content_len - conn->consumed_content);
  5710. }
  5711. nread = pull(NULL, conn, buf, to_read, timeout);
  5712. if (nread <= 0
  5713. || push_all(conn->ctx, fp, sock, ssl, buf, nread) != nread) {
  5714. break;
  5715. }
  5716. conn->consumed_content += nread;
  5717. }
  5718. if (conn->consumed_content == conn->content_len) {
  5719. success = nread >= 0;
  5720. }
  5721. /* Each error code path in this function must send an error */
  5722. if (!success) {
  5723. /* NOTE: Maybe some data has already been sent. */
  5724. /* TODO (low): If some data has been sent, a correct error
  5725. * reply can no longer be sent, so just close the connection */
  5726. send_http_error(conn, 500, "%s", "");
  5727. }
  5728. }
  5729. return success;
  5730. }
  5731. #endif
  5732. #if !defined(NO_CGI)
  5733. /* This structure helps to create an environment for the spawned CGI program.
  5734. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  5735. * last element must be NULL.
  5736. * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  5737. * strings must reside in a contiguous buffer. The end of the buffer is
  5738. * marked by two '\0' characters.
  5739. * We satisfy both worlds: we create an envp array (which is vars), all
  5740. * entries are actually pointers inside buf. */
  5741. struct cgi_environment {
  5742. struct mg_connection *conn;
  5743. /* Data block */
  5744. char *buf; /* Environment buffer */
  5745. size_t buflen; /* Space available in buf */
  5746. size_t bufused; /* Space taken in buf */
  5747. /* Index block */
  5748. char **var; /* char **envp */
  5749. size_t varlen; /* Number of variables available in var */
  5750. size_t varused; /* Number of variables stored in var */
  5751. };
  5752. static void addenv(struct cgi_environment *env,
  5753. PRINTF_FORMAT_STRING(const char *fmt),
  5754. ...) PRINTF_ARGS(2, 3);
  5755. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  5756. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  5757. static void
  5758. addenv(struct cgi_environment *env, const char *fmt, ...)
  5759. {
  5760. size_t n, space;
  5761. int truncated;
  5762. char *added;
  5763. va_list ap;
  5764. /* Calculate how much space is left in the buffer */
  5765. space = (env->buflen - env->bufused);
  5766. /* Calculate an estimate for the required space */
  5767. n = strlen(fmt) + 2 + 128;
  5768. do {
  5769. if (space <= n) {
  5770. /* Allocate new buffer */
  5771. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  5772. added = (char *)mg_realloc(env->buf, n);
  5773. if (!added) {
  5774. /* Out of memory */
  5775. mg_cry(env->conn,
  5776. "%s: Cannot allocate memory for CGI variable [%s]",
  5777. __func__,
  5778. fmt);
  5779. return;
  5780. }
  5781. env->buf = added;
  5782. env->buflen = n;
  5783. space = (env->buflen - env->bufused);
  5784. }
  5785. /* Make a pointer to the free space int the buffer */
  5786. added = env->buf + env->bufused;
  5787. /* Copy VARIABLE=VALUE\0 string into the free space */
  5788. va_start(ap, fmt);
  5789. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  5790. va_end(ap);
  5791. /* Do not add truncated strings to the environment */
  5792. if (truncated) {
  5793. /* Reallocate the buffer */
  5794. space = 0;
  5795. n = 1;
  5796. }
  5797. } while (truncated);
  5798. /* Calculate number of bytes added to the environment */
  5799. n = strlen(added) + 1;
  5800. env->bufused += n;
  5801. /* Now update the variable index */
  5802. space = (env->varlen - env->varused);
  5803. if (space < 2) {
  5804. mg_cry(env->conn,
  5805. "%s: Cannot register CGI variable [%s]",
  5806. __func__,
  5807. fmt);
  5808. return;
  5809. }
  5810. /* Append a pointer to the added string into the envp array */
  5811. env->var[env->varused] = added;
  5812. env->varused++;
  5813. }
  5814. static void
  5815. prepare_cgi_environment(struct mg_connection *conn,
  5816. const char *prog,
  5817. struct cgi_environment *env)
  5818. {
  5819. const char *s;
  5820. struct vec var_vec;
  5821. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  5822. int i, truncated;
  5823. if (conn == NULL || prog == NULL || env == NULL) {
  5824. return;
  5825. }
  5826. env->conn = conn;
  5827. env->buflen = CGI_ENVIRONMENT_SIZE;
  5828. env->bufused = 0;
  5829. env->buf = (char *)mg_malloc(env->buflen);
  5830. env->varlen = MAX_CGI_ENVIR_VARS;
  5831. env->varused = 0;
  5832. env->var = (char **)mg_malloc(env->buflen * sizeof(char *));
  5833. addenv(env, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  5834. addenv(env, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  5835. addenv(env, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  5836. addenv(env, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  5837. /* Prepare the environment block */
  5838. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  5839. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  5840. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  5841. #if defined(USE_IPV6)
  5842. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  5843. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  5844. } else
  5845. #endif
  5846. {
  5847. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  5848. }
  5849. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  5850. addenv(env, "REMOTE_ADDR=%s", src_addr);
  5851. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  5852. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  5853. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  5854. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  5855. /* SCRIPT_NAME */
  5856. addenv(env,
  5857. "SCRIPT_NAME=%.*s",
  5858. (int)strlen(conn->request_info.local_uri)
  5859. - ((conn->path_info == NULL) ? 0 : (int)strlen(conn->path_info)),
  5860. conn->request_info.local_uri);
  5861. addenv(env, "SCRIPT_FILENAME=%s", prog);
  5862. if (conn->path_info == NULL) {
  5863. addenv(env, "PATH_TRANSLATED=%s", conn->ctx->config[DOCUMENT_ROOT]);
  5864. } else {
  5865. addenv(env,
  5866. "PATH_TRANSLATED=%s%s",
  5867. conn->ctx->config[DOCUMENT_ROOT],
  5868. conn->path_info);
  5869. }
  5870. addenv(env, "HTTPS=%s", conn->ssl == NULL ? "off" : "on");
  5871. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  5872. addenv(env, "CONTENT_TYPE=%s", s);
  5873. }
  5874. if (conn->request_info.query_string != NULL) {
  5875. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  5876. }
  5877. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  5878. addenv(env, "CONTENT_LENGTH=%s", s);
  5879. }
  5880. if ((s = getenv("PATH")) != NULL) {
  5881. addenv(env, "PATH=%s", s);
  5882. }
  5883. if (conn->path_info != NULL) {
  5884. addenv(env, "PATH_INFO=%s", conn->path_info);
  5885. }
  5886. if (conn->status_code > 0) {
  5887. /* CGI error handler should show the status code */
  5888. addenv(env, "STATUS=%d", conn->status_code);
  5889. }
  5890. #if defined(_WIN32)
  5891. if ((s = getenv("COMSPEC")) != NULL) {
  5892. addenv(env, "COMSPEC=%s", s);
  5893. }
  5894. if ((s = getenv("SYSTEMROOT")) != NULL) {
  5895. addenv(env, "SYSTEMROOT=%s", s);
  5896. }
  5897. if ((s = getenv("SystemDrive")) != NULL) {
  5898. addenv(env, "SystemDrive=%s", s);
  5899. }
  5900. if ((s = getenv("ProgramFiles")) != NULL) {
  5901. addenv(env, "ProgramFiles=%s", s);
  5902. }
  5903. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  5904. addenv(env, "ProgramFiles(x86)=%s", s);
  5905. }
  5906. #else
  5907. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  5908. addenv(env, "LD_LIBRARY_PATH=%s", s);
  5909. }
  5910. #endif /* _WIN32 */
  5911. if ((s = getenv("PERLLIB")) != NULL) {
  5912. addenv(env, "PERLLIB=%s", s);
  5913. }
  5914. if (conn->request_info.remote_user != NULL) {
  5915. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  5916. addenv(env, "%s", "AUTH_TYPE=Digest");
  5917. }
  5918. /* Add all headers as HTTP_* variables */
  5919. for (i = 0; i < conn->request_info.num_headers; i++) {
  5920. (void)mg_snprintf(conn,
  5921. &truncated,
  5922. http_var_name,
  5923. sizeof(http_var_name),
  5924. "HTTP_%s",
  5925. conn->request_info.http_headers[i].name);
  5926. if (truncated) {
  5927. mg_cry(conn,
  5928. "%s: HTTP header variable too long [%s]",
  5929. __func__,
  5930. conn->request_info.http_headers[i].name);
  5931. continue;
  5932. }
  5933. /* Convert variable name into uppercase, and change - to _ */
  5934. for (p = http_var_name; *p != '\0'; p++) {
  5935. if (*p == '-') {
  5936. *p = '_';
  5937. }
  5938. *p = (char)toupper(*(unsigned char *)p);
  5939. }
  5940. addenv(env,
  5941. "%s=%s",
  5942. http_var_name,
  5943. conn->request_info.http_headers[i].value);
  5944. }
  5945. /* Add user-specified variables */
  5946. s = conn->ctx->config[CGI_ENVIRONMENT];
  5947. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  5948. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  5949. }
  5950. env->var[env->varused] = NULL;
  5951. env->buf[env->bufused] = '\0';
  5952. }
  5953. static void
  5954. handle_cgi_request(struct mg_connection *conn, const char *prog)
  5955. {
  5956. char *buf;
  5957. size_t buflen;
  5958. int headers_len, data_len, i, truncated;
  5959. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  5960. const char *status, *status_text, *connection_state;
  5961. char *pbuf, dir[PATH_MAX], *p;
  5962. struct mg_request_info ri;
  5963. struct cgi_environment blk;
  5964. FILE *in = NULL, *out = NULL, *err = NULL;
  5965. struct file fout = STRUCT_FILE_INITIALIZER;
  5966. pid_t pid = (pid_t)-1;
  5967. if (conn == NULL) {
  5968. return;
  5969. }
  5970. buf = NULL;
  5971. buflen = 16384;
  5972. prepare_cgi_environment(conn, prog, &blk);
  5973. /* CGI must be executed in its own directory. 'dir' must point to the
  5974. * directory containing executable program, 'p' must point to the
  5975. * executable program name relative to 'dir'. */
  5976. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  5977. if (truncated) {
  5978. mg_cry(conn, "Error: CGI program \"%s\": Path too long", prog);
  5979. send_http_error(conn, 500, "Error: %s", "CGI path too long");
  5980. goto done;
  5981. }
  5982. if ((p = strrchr(dir, '/')) != NULL) {
  5983. *p++ = '\0';
  5984. } else {
  5985. dir[0] = '.', dir[1] = '\0';
  5986. p = (char *)prog;
  5987. }
  5988. if (pipe(fdin) != 0 || pipe(fdout) != 0 || pipe(fderr) != 0) {
  5989. status = strerror(ERRNO);
  5990. mg_cry(conn,
  5991. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  5992. prog,
  5993. status);
  5994. send_http_error(conn, 500, "Error: Cannot create CGI pipe: %s", status);
  5995. goto done;
  5996. }
  5997. pid = spawn_process(
  5998. conn, p, blk.buf, blk.var, fdin[0], fdout[1], fderr[1], dir);
  5999. if (pid == (pid_t)-1) {
  6000. status = strerror(ERRNO);
  6001. mg_cry(conn,
  6002. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  6003. prog,
  6004. status);
  6005. send_http_error(conn,
  6006. 500,
  6007. "Error: Cannot spawn CGI process [%s]: %s",
  6008. prog,
  6009. status);
  6010. goto done;
  6011. }
  6012. /* Make sure child closes all pipe descriptors. It must dup them to 0,1 */
  6013. set_close_on_exec((SOCKET)fdin[0], conn);
  6014. set_close_on_exec((SOCKET)fdin[1], conn);
  6015. set_close_on_exec((SOCKET)fdout[0], conn);
  6016. set_close_on_exec((SOCKET)fdout[1], conn);
  6017. set_close_on_exec((SOCKET)fderr[0], conn);
  6018. set_close_on_exec((SOCKET)fderr[1], conn);
  6019. /* Parent closes only one side of the pipes.
  6020. * If we don't mark them as closed, close() attempt before
  6021. * return from this function throws an exception on Windows.
  6022. * Windows does not like when closed descriptor is closed again. */
  6023. (void)close(fdin[0]);
  6024. (void)close(fdout[1]);
  6025. (void)close(fderr[1]);
  6026. fdin[0] = fdout[1] = fderr[1] = -1;
  6027. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  6028. status = strerror(ERRNO);
  6029. mg_cry(conn,
  6030. "Error: CGI program \"%s\": Can not open stdin: %s",
  6031. prog,
  6032. status);
  6033. send_http_error(conn,
  6034. 500,
  6035. "Error: CGI can not open fdin\nfopen: %s",
  6036. status);
  6037. goto done;
  6038. }
  6039. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  6040. status = strerror(ERRNO);
  6041. mg_cry(conn,
  6042. "Error: CGI program \"%s\": Can not open stdout: %s",
  6043. prog,
  6044. status);
  6045. send_http_error(conn,
  6046. 500,
  6047. "Error: CGI can not open fdout\nfopen: %s",
  6048. status);
  6049. goto done;
  6050. }
  6051. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  6052. status = strerror(ERRNO);
  6053. mg_cry(conn,
  6054. "Error: CGI program \"%s\": Can not open stderr: %s",
  6055. prog,
  6056. status);
  6057. send_http_error(conn,
  6058. 500,
  6059. "Error: CGI can not open fdout\nfopen: %s",
  6060. status);
  6061. goto done;
  6062. }
  6063. setbuf(in, NULL);
  6064. setbuf(out, NULL);
  6065. setbuf(err, NULL);
  6066. fout.fp = out;
  6067. /* Send POST or PUT data to the CGI process if needed */
  6068. /* TODO(high): Methods like PATCH, MKCOL, ... also have body data. */
  6069. if (!mg_strcasecmp(conn->request_info.request_method, "POST")
  6070. || !mg_strcasecmp(conn->request_info.request_method, "PUT")) {
  6071. /* This is a POST/PUT request */
  6072. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  6073. /* Error sending the body data */
  6074. mg_cry(conn,
  6075. "Error: CGI program \"%s\": Forward body data failed",
  6076. prog);
  6077. goto done;
  6078. }
  6079. }
  6080. /* Close so child gets an EOF. */
  6081. fclose(in);
  6082. in = NULL;
  6083. fdin[1] = -1;
  6084. /* Now read CGI reply into a buffer. We need to set correct
  6085. * status code, thus we need to see all HTTP headers first.
  6086. * Do not send anything back to client, until we buffer in all
  6087. * HTTP headers. */
  6088. data_len = 0;
  6089. buf = (char *)mg_malloc(buflen);
  6090. if (buf == NULL) {
  6091. send_http_error(conn,
  6092. 500,
  6093. "Error: Not enough memory for CGI buffer (%u bytes)",
  6094. (unsigned int)buflen);
  6095. mg_cry(conn,
  6096. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  6097. "bytes)",
  6098. prog,
  6099. (unsigned int)buflen);
  6100. goto done;
  6101. }
  6102. headers_len = read_request(out, conn, buf, (int)buflen, &data_len);
  6103. if (headers_len <= 0) {
  6104. /* Could not parse the CGI response. Check if some error message on
  6105. * stderr. */
  6106. i = pull_all(err, conn, buf, (int)buflen);
  6107. if (i > 0) {
  6108. mg_cry(conn,
  6109. "Error: CGI program \"%s\" sent error "
  6110. "message: [%.*s]",
  6111. prog,
  6112. i,
  6113. buf);
  6114. send_http_error(conn,
  6115. 500,
  6116. "Error: CGI program \"%s\" sent error "
  6117. "message: [%.*s]",
  6118. prog,
  6119. i,
  6120. buf);
  6121. } else {
  6122. mg_cry(conn,
  6123. "Error: CGI program sent malformed or too big "
  6124. "(>%u bytes) HTTP headers: [%.*s]",
  6125. (unsigned)buflen,
  6126. data_len,
  6127. buf);
  6128. send_http_error(conn,
  6129. 500,
  6130. "Error: CGI program sent malformed or too big "
  6131. "(>%u bytes) HTTP headers: [%.*s]",
  6132. (unsigned)buflen,
  6133. data_len,
  6134. buf);
  6135. }
  6136. goto done;
  6137. }
  6138. pbuf = buf;
  6139. buf[headers_len - 1] = '\0';
  6140. parse_http_headers(&pbuf, &ri);
  6141. /* Make up and send the status line */
  6142. status_text = "OK";
  6143. if ((status = get_header(&ri, "Status")) != NULL) {
  6144. conn->status_code = atoi(status);
  6145. status_text = status;
  6146. while (isdigit(*(unsigned char *)status_text) || *status_text == ' ') {
  6147. status_text++;
  6148. }
  6149. } else if (get_header(&ri, "Location") != NULL) {
  6150. conn->status_code = 302;
  6151. } else {
  6152. conn->status_code = 200;
  6153. }
  6154. connection_state = get_header(&ri, "Connection");
  6155. if (connection_state == NULL
  6156. || mg_strcasecmp(connection_state, "keep-alive")) {
  6157. conn->must_close = 1;
  6158. }
  6159. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  6160. /* Send headers */
  6161. for (i = 0; i < ri.num_headers; i++) {
  6162. mg_printf(conn,
  6163. "%s: %s\r\n",
  6164. ri.http_headers[i].name,
  6165. ri.http_headers[i].value);
  6166. }
  6167. mg_write(conn, "\r\n", 2);
  6168. /* Send chunk of data that may have been read after the headers */
  6169. conn->num_bytes_sent +=
  6170. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  6171. /* Read the rest of CGI output and send to the client */
  6172. send_file_data(conn, &fout, 0, INT64_MAX);
  6173. done:
  6174. mg_free(blk.var);
  6175. mg_free(blk.buf);
  6176. if (pid != (pid_t)-1) {
  6177. kill(pid, SIGKILL);
  6178. #if !defined(_WIN32)
  6179. {
  6180. int st;
  6181. while (waitpid(pid, &st, 0) != -1)
  6182. ; /* clean zombies */
  6183. }
  6184. #endif
  6185. }
  6186. if (fdin[0] != -1) {
  6187. close(fdin[0]);
  6188. }
  6189. if (fdout[1] != -1) {
  6190. close(fdout[1]);
  6191. }
  6192. if (in != NULL) {
  6193. fclose(in);
  6194. } else if (fdin[1] != -1) {
  6195. close(fdin[1]);
  6196. }
  6197. if (out != NULL) {
  6198. fclose(out);
  6199. } else if (fdout[0] != -1) {
  6200. close(fdout[0]);
  6201. }
  6202. if (err != NULL) {
  6203. fclose(err);
  6204. } else if (fderr[0] != -1) {
  6205. close(fderr[0]);
  6206. }
  6207. if (buf != NULL) {
  6208. mg_free(buf);
  6209. }
  6210. }
  6211. #endif /* !NO_CGI */
  6212. #if !defined(NO_FILES)
  6213. /* For a given PUT path, create all intermediate subdirectories.
  6214. * Return 0 if the path itself is a directory.
  6215. * Return 1 if the path leads to a file.
  6216. * Return -1 for if the path is too long.
  6217. * Return -2 if path can not be created.
  6218. */
  6219. static int
  6220. put_dir(struct mg_connection *conn, const char *path)
  6221. {
  6222. char buf[PATH_MAX];
  6223. const char *s, *p;
  6224. struct file file = STRUCT_FILE_INITIALIZER;
  6225. size_t len;
  6226. int res = 1;
  6227. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  6228. len = (size_t)(p - path);
  6229. if (len >= sizeof(buf)) {
  6230. /* path too long */
  6231. res = -1;
  6232. break;
  6233. }
  6234. memcpy(buf, path, len);
  6235. buf[len] = '\0';
  6236. /* Try to create intermediate directory */
  6237. DEBUG_TRACE("mkdir(%s)", buf);
  6238. if (!mg_stat(conn, buf, &file) && mg_mkdir(buf, 0755) != 0) {
  6239. /* path does not exixt and can not be created */
  6240. res = -2;
  6241. break;
  6242. }
  6243. /* Is path itself a directory? */
  6244. if (p[1] == '\0') {
  6245. res = 0;
  6246. }
  6247. }
  6248. return res;
  6249. }
  6250. static void
  6251. mkcol(struct mg_connection *conn, const char *path)
  6252. {
  6253. int rc, body_len;
  6254. struct de de;
  6255. char date[64];
  6256. time_t curtime = time(NULL);
  6257. if (conn == NULL) {
  6258. return;
  6259. }
  6260. /* TODO (mid): Check the send_http_error situations in this function */
  6261. memset(&de.file, 0, sizeof(de.file));
  6262. if (!mg_stat(conn, path, &de.file)) {
  6263. mg_cry(conn,
  6264. "%s: mg_stat(%s) failed: %s",
  6265. __func__,
  6266. path,
  6267. strerror(ERRNO));
  6268. }
  6269. if (de.file.last_modified) {
  6270. /* TODO (high): This check does not seem to make any sense ! */
  6271. send_http_error(
  6272. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6273. return;
  6274. }
  6275. body_len = conn->data_len - conn->request_len;
  6276. if (body_len > 0) {
  6277. send_http_error(
  6278. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6279. return;
  6280. }
  6281. rc = mg_mkdir(path, 0755);
  6282. if (rc == 0) {
  6283. conn->status_code = 201;
  6284. gmt_time_string(date, sizeof(date), &curtime);
  6285. mg_printf(conn,
  6286. "HTTP/1.1 %d Created\r\n"
  6287. "Date: %s\r\n"
  6288. /* TODO: "Cache-Control" */
  6289. "Content-Length: 0\r\n"
  6290. "Connection: %s\r\n\r\n",
  6291. conn->status_code,
  6292. date,
  6293. suggest_connection_header(conn));
  6294. } else if (rc == -1) {
  6295. if (errno == EEXIST) {
  6296. send_http_error(
  6297. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6298. } else if (errno == EACCES) {
  6299. send_http_error(
  6300. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6301. } else if (errno == ENOENT) {
  6302. send_http_error(
  6303. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6304. } else {
  6305. send_http_error(conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  6306. }
  6307. }
  6308. }
  6309. static void
  6310. put_file(struct mg_connection *conn, const char *path)
  6311. {
  6312. struct file file = STRUCT_FILE_INITIALIZER;
  6313. const char *range;
  6314. int64_t r1, r2;
  6315. int rc;
  6316. char date[64];
  6317. time_t curtime = time(NULL);
  6318. if (conn == NULL) {
  6319. return;
  6320. }
  6321. if (mg_stat(conn, path, &file)) {
  6322. /* File already exists */
  6323. conn->status_code = 200;
  6324. if (file.is_directory) {
  6325. /* This is an already existing directory,
  6326. * so there is nothing to do for the server. */
  6327. rc = 0;
  6328. } else {
  6329. /* File exists and is not a directory. */
  6330. /* Can it be replaced? */
  6331. if (file.membuf != NULL) {
  6332. /* This is an "in-memory" file, that can not be replaced */
  6333. send_http_error(
  6334. conn,
  6335. 405,
  6336. "Error: Put not possible\nReplacing %s is not supported",
  6337. path);
  6338. return;
  6339. }
  6340. /* Check if the server may write this file */
  6341. if (access(path, W_OK) == 0) {
  6342. /* Access granted */
  6343. conn->status_code = 200;
  6344. rc = 1;
  6345. } else {
  6346. send_http_error(
  6347. conn,
  6348. 403,
  6349. "Error: Put not possible\nReplacing %s is not allowed",
  6350. path);
  6351. return;
  6352. }
  6353. }
  6354. } else {
  6355. /* File should be created */
  6356. conn->status_code = 201;
  6357. rc = put_dir(conn, path);
  6358. }
  6359. if (rc == 0) {
  6360. /* put_dir returns 0 if path is a directory */
  6361. gmt_time_string(date, sizeof(date), &curtime);
  6362. mg_printf(conn,
  6363. "HTTP/1.1 %d %s\r\n"
  6364. "Date: %s\r\n"
  6365. "Cache-Control: no-cache\r\n"
  6366. "Content-Length: 0\r\n"
  6367. "Connection: %s\r\n\r\n",
  6368. conn->status_code,
  6369. mg_get_response_code_text(conn->status_code, NULL),
  6370. date,
  6371. suggest_connection_header(conn));
  6372. /* Request to create a directory has been fulfilled successfully.
  6373. * No need to put a file. */
  6374. return;
  6375. }
  6376. if (rc == -1) {
  6377. /* put_dir returns -1 if the path is too long */
  6378. send_http_error(conn,
  6379. 414,
  6380. "Error: Path too long\nput_dir(%s): %s",
  6381. path,
  6382. strerror(ERRNO));
  6383. return;
  6384. }
  6385. if (rc == -2) {
  6386. /* put_dir returns -2 if the directory can not be created */
  6387. send_http_error(conn,
  6388. 500,
  6389. "Error: Can not create directory\nput_dir(%s): %s",
  6390. path,
  6391. strerror(ERRNO));
  6392. return;
  6393. }
  6394. /* A file should be created or overwritten. */
  6395. if (!mg_fopen(conn, path, "wb+", &file) || file.fp == NULL) {
  6396. mg_fclose(&file);
  6397. send_http_error(conn,
  6398. 500,
  6399. "Error: Can not create file\nfopen(%s): %s",
  6400. path,
  6401. strerror(ERRNO));
  6402. return;
  6403. }
  6404. fclose_on_exec(&file, conn);
  6405. range = mg_get_header(conn, "Content-Range");
  6406. r1 = r2 = 0;
  6407. if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
  6408. conn->status_code = 206; /* Partial content */
  6409. fseeko(file.fp, r1, SEEK_SET);
  6410. }
  6411. if (!forward_body_data(conn, file.fp, INVALID_SOCKET, NULL)) {
  6412. /* forward_body_data failed.
  6413. * The error code has already been sent to the client,
  6414. * and conn->status_code is already set. */
  6415. return;
  6416. }
  6417. gmt_time_string(date, sizeof(date), &curtime);
  6418. mg_printf(conn,
  6419. "HTTP/1.1 %d %s\r\n"
  6420. "Date: %s\r\n"
  6421. "Cache-Control: no-cache\r\n"
  6422. "Content-Length: 0\r\n"
  6423. "Connection: %s\r\n\r\n",
  6424. conn->status_code,
  6425. mg_get_response_code_text(conn->status_code, NULL),
  6426. date,
  6427. suggest_connection_header(conn));
  6428. mg_fclose(&file);
  6429. }
  6430. static void
  6431. delete_file(struct mg_connection *conn, const char *path)
  6432. {
  6433. struct de de;
  6434. memset(&de.file, 0, sizeof(de.file));
  6435. if (!mg_stat(conn, path, &de.file)) {
  6436. /* mg_stat returns 0 if the file does not exist */
  6437. send_http_error(conn,
  6438. 404,
  6439. "Error: Cannot delete file\nFile %s not found",
  6440. path);
  6441. return;
  6442. }
  6443. if (de.file.membuf != NULL) {
  6444. /* the file is cached in memory */
  6445. send_http_error(
  6446. conn,
  6447. 405,
  6448. "Error: Delete not possible\nDeleting %s is not supported",
  6449. path);
  6450. return;
  6451. }
  6452. if (de.file.is_directory) {
  6453. if (remove_directory(conn, path)) {
  6454. /* Delete is successful: Return 204 without content. */
  6455. send_http_error(conn, 204, "%s", "");
  6456. } else {
  6457. /* Delete is not successful: Return 500 (Server error). */
  6458. send_http_error(conn, 500, "Error: Could not delete %s", path);
  6459. }
  6460. return;
  6461. }
  6462. /* This is an existing file (not a directory).
  6463. * Check if write permission is granted. */
  6464. if (access(path, W_OK) != 0) {
  6465. /* File is read only */
  6466. send_http_error(
  6467. conn,
  6468. 403,
  6469. "Error: Delete not possible\nDeleting %s is not allowed",
  6470. path);
  6471. return;
  6472. }
  6473. /* Try to delete it. */
  6474. if (mg_remove(path) == 0) {
  6475. /* Delete was successful: Return 204 without content. */
  6476. send_http_error(conn, 204, "%s", "");
  6477. } else {
  6478. /* Delete not successful (file locked). */
  6479. send_http_error(conn,
  6480. 423,
  6481. "Error: Cannot delete file\nremove(%s): %s",
  6482. path,
  6483. strerror(ERRNO));
  6484. }
  6485. }
  6486. #endif /* !NO_FILES */
  6487. static void
  6488. send_ssi_file(struct mg_connection *, const char *, struct file *, int);
  6489. static void
  6490. do_ssi_include(struct mg_connection *conn,
  6491. const char *ssi,
  6492. char *tag,
  6493. int include_level)
  6494. {
  6495. char file_name[MG_BUF_LEN], path[512], *p;
  6496. struct file file = STRUCT_FILE_INITIALIZER;
  6497. size_t len;
  6498. int truncated = 0;
  6499. if (conn == NULL) {
  6500. return;
  6501. }
  6502. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  6503. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  6504. * always < MG_BUF_LEN. */
  6505. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  6506. /* File name is relative to the webserver root */
  6507. file_name[511] = 0;
  6508. (void)mg_snprintf(conn,
  6509. &truncated,
  6510. path,
  6511. sizeof(path),
  6512. "%s/%s",
  6513. conn->ctx->config[DOCUMENT_ROOT],
  6514. file_name);
  6515. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  6516. /* File name is relative to the webserver working directory
  6517. * or it is absolute system path */
  6518. file_name[511] = 0;
  6519. (void)
  6520. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  6521. } else if (sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1
  6522. || sscanf(tag, " \"%511[^\"]\"", file_name) == 1) {
  6523. /* File name is relative to the currect document */
  6524. file_name[511] = 0;
  6525. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  6526. if (!truncated) {
  6527. if ((p = strrchr(path, '/')) != NULL) {
  6528. p[1] = '\0';
  6529. }
  6530. len = strlen(path);
  6531. (void)mg_snprintf(conn,
  6532. &truncated,
  6533. path + len,
  6534. sizeof(path) - len,
  6535. "%s",
  6536. file_name);
  6537. }
  6538. } else {
  6539. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  6540. return;
  6541. }
  6542. if (truncated) {
  6543. mg_cry(conn, "SSI #include path length overflow: [%s]", tag);
  6544. return;
  6545. }
  6546. if (!mg_fopen(conn, path, "rb", &file)) {
  6547. mg_cry(conn,
  6548. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  6549. tag,
  6550. path,
  6551. strerror(ERRNO));
  6552. } else {
  6553. fclose_on_exec(&file, conn);
  6554. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  6555. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  6556. path) > 0) {
  6557. send_ssi_file(conn, path, &file, include_level + 1);
  6558. } else {
  6559. send_file_data(conn, &file, 0, INT64_MAX);
  6560. }
  6561. mg_fclose(&file);
  6562. }
  6563. }
  6564. #if !defined(NO_POPEN)
  6565. static void
  6566. do_ssi_exec(struct mg_connection *conn, char *tag)
  6567. {
  6568. char cmd[1024] = "";
  6569. struct file file = STRUCT_FILE_INITIALIZER;
  6570. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  6571. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  6572. } else {
  6573. cmd[1023] = 0;
  6574. if ((file.fp = popen(cmd, "r")) == NULL) {
  6575. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  6576. } else {
  6577. send_file_data(conn, &file, 0, INT64_MAX);
  6578. pclose(file.fp);
  6579. }
  6580. }
  6581. }
  6582. #endif /* !NO_POPEN */
  6583. static int
  6584. mg_fgetc(struct file *filep, int offset)
  6585. {
  6586. if (filep == NULL) {
  6587. return EOF;
  6588. }
  6589. if (filep->membuf != NULL && offset >= 0
  6590. && ((unsigned int)(offset)) < filep->size) {
  6591. return ((unsigned char *)filep->membuf)[offset];
  6592. } else if (filep->fp != NULL) {
  6593. return fgetc(filep->fp);
  6594. } else {
  6595. return EOF;
  6596. }
  6597. }
  6598. static void
  6599. send_ssi_file(struct mg_connection *conn,
  6600. const char *path,
  6601. struct file *filep,
  6602. int include_level)
  6603. {
  6604. char buf[MG_BUF_LEN];
  6605. int ch, offset, len, in_ssi_tag;
  6606. if (include_level > 10) {
  6607. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  6608. return;
  6609. }
  6610. in_ssi_tag = len = offset = 0;
  6611. while ((ch = mg_fgetc(filep, offset)) != EOF) {
  6612. if (in_ssi_tag && ch == '>') {
  6613. in_ssi_tag = 0;
  6614. buf[len++] = (char)ch;
  6615. buf[len] = '\0';
  6616. /* assert(len <= (int) sizeof(buf)); */
  6617. if (len > (int)sizeof(buf)) {
  6618. break;
  6619. }
  6620. if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
  6621. /* Not an SSI tag, pass it */
  6622. (void)mg_write(conn, buf, (size_t)len);
  6623. } else {
  6624. if (!memcmp(buf + 5, "include", 7)) {
  6625. do_ssi_include(conn, path, buf + 12, include_level);
  6626. #if !defined(NO_POPEN)
  6627. } else if (!memcmp(buf + 5, "exec", 4)) {
  6628. do_ssi_exec(conn, buf + 9);
  6629. #endif /* !NO_POPEN */
  6630. } else {
  6631. mg_cry(conn,
  6632. "%s: unknown SSI "
  6633. "command: \"%s\"",
  6634. path,
  6635. buf);
  6636. }
  6637. }
  6638. len = 0;
  6639. } else if (in_ssi_tag) {
  6640. if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
  6641. /* Not an SSI tag */
  6642. in_ssi_tag = 0;
  6643. } else if (len == (int)sizeof(buf) - 2) {
  6644. mg_cry(conn, "%s: SSI tag is too large", path);
  6645. len = 0;
  6646. }
  6647. buf[len++] = (char)(ch & 0xff);
  6648. } else if (ch == '<') {
  6649. in_ssi_tag = 1;
  6650. if (len > 0) {
  6651. mg_write(conn, buf, (size_t)len);
  6652. }
  6653. len = 0;
  6654. buf[len++] = (char)(ch & 0xff);
  6655. } else {
  6656. buf[len++] = (char)(ch & 0xff);
  6657. if (len == (int)sizeof(buf)) {
  6658. mg_write(conn, buf, (size_t)len);
  6659. len = 0;
  6660. }
  6661. }
  6662. }
  6663. /* Send the rest of buffered data */
  6664. if (len > 0) {
  6665. mg_write(conn, buf, (size_t)len);
  6666. }
  6667. }
  6668. static void
  6669. handle_ssi_file_request(struct mg_connection *conn,
  6670. const char *path,
  6671. struct file *filep)
  6672. {
  6673. char date[64];
  6674. time_t curtime = time(NULL);
  6675. const char *cors1, *cors2, *cors3;
  6676. if (conn == NULL || path == NULL || filep == NULL) {
  6677. return;
  6678. }
  6679. if (mg_get_header(conn, "Origin")) {
  6680. /* Cross-origin resource sharing (CORS). */
  6681. cors1 = "Access-Control-Allow-Origin: ";
  6682. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  6683. cors3 = "\r\n";
  6684. } else {
  6685. cors1 = cors2 = cors3 = "";
  6686. }
  6687. if (!mg_fopen(conn, path, "rb", filep)) {
  6688. /* File exists (precondition for calling this function),
  6689. * but can not be opened by the server. */
  6690. send_http_error(conn,
  6691. 500,
  6692. "Error: Cannot read file\nfopen(%s): %s",
  6693. path,
  6694. strerror(ERRNO));
  6695. } else {
  6696. conn->must_close = 1;
  6697. gmt_time_string(date, sizeof(date), &curtime);
  6698. fclose_on_exec(filep, conn);
  6699. mg_printf(conn,
  6700. "HTTP/1.1 200 OK\r\n"
  6701. "%s%s%s"
  6702. "Date: %s\r\n"
  6703. "Cache-Control: no-cache\r\n"
  6704. "Content-Type: text/html\r\n"
  6705. "Connection: %s\r\n\r\n",
  6706. cors1,
  6707. cors2,
  6708. cors3,
  6709. date,
  6710. suggest_connection_header(conn));
  6711. send_ssi_file(conn, path, filep, 0);
  6712. mg_fclose(filep);
  6713. }
  6714. }
  6715. #if !defined(NO_FILES)
  6716. static void
  6717. send_options(struct mg_connection *conn)
  6718. {
  6719. char date[64];
  6720. time_t curtime = time(NULL);
  6721. if (!conn) {
  6722. return;
  6723. }
  6724. conn->status_code = 200;
  6725. conn->must_close = 1;
  6726. gmt_time_string(date, sizeof(date), &curtime);
  6727. mg_printf(conn,
  6728. "HTTP/1.1 200 OK\r\n"
  6729. "Date: %s\r\n"
  6730. /* TODO: "Cache-Control" ? */
  6731. "Connection: %s\r\n"
  6732. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  6733. "PROPFIND, MKCOL\r\n"
  6734. "DAV: 1\r\n\r\n",
  6735. date,
  6736. suggest_connection_header(conn));
  6737. }
  6738. /* Writes PROPFIND properties for a collection element */
  6739. static void
  6740. print_props(struct mg_connection *conn, const char *uri, struct file *filep)
  6741. {
  6742. char mtime[64];
  6743. if (conn == NULL || uri == NULL || filep == NULL) {
  6744. return;
  6745. }
  6746. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  6747. conn->num_bytes_sent +=
  6748. mg_printf(conn,
  6749. "<d:response>"
  6750. "<d:href>%s</d:href>"
  6751. "<d:propstat>"
  6752. "<d:prop>"
  6753. "<d:resourcetype>%s</d:resourcetype>"
  6754. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  6755. "<d:getlastmodified>%s</d:getlastmodified>"
  6756. "</d:prop>"
  6757. "<d:status>HTTP/1.1 200 OK</d:status>"
  6758. "</d:propstat>"
  6759. "</d:response>\n",
  6760. uri,
  6761. filep->is_directory ? "<d:collection/>" : "",
  6762. filep->size,
  6763. mtime);
  6764. }
  6765. static void
  6766. print_dav_dir_entry(struct de *de, void *data)
  6767. {
  6768. char href[PATH_MAX];
  6769. char href_encoded[PATH_MAX];
  6770. int truncated;
  6771. struct mg_connection *conn = (struct mg_connection *)data;
  6772. if (!de || !conn) {
  6773. return;
  6774. }
  6775. mg_snprintf(conn,
  6776. &truncated,
  6777. href,
  6778. sizeof(href),
  6779. "%s%s",
  6780. conn->request_info.local_uri,
  6781. de->file_name);
  6782. if (!truncated) {
  6783. mg_url_encode(href, href_encoded, PATH_MAX - 1);
  6784. print_props(conn, href_encoded, &de->file);
  6785. }
  6786. }
  6787. static void
  6788. handle_propfind(struct mg_connection *conn,
  6789. const char *path,
  6790. struct file *filep)
  6791. {
  6792. const char *depth = mg_get_header(conn, "Depth");
  6793. char date[64];
  6794. time_t curtime = time(NULL);
  6795. gmt_time_string(date, sizeof(date), &curtime);
  6796. if (!conn || !path || !filep) {
  6797. return;
  6798. }
  6799. conn->must_close = 1;
  6800. conn->status_code = 207;
  6801. mg_printf(conn,
  6802. "HTTP/1.1 207 Multi-Status\r\n"
  6803. "Date: %s\r\n"
  6804. /* TODO: "Cache-Control" */
  6805. "Connection: %s\r\n"
  6806. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  6807. date,
  6808. suggest_connection_header(conn));
  6809. conn->num_bytes_sent +=
  6810. mg_printf(conn,
  6811. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  6812. "<d:multistatus xmlns:d='DAV:'>\n");
  6813. /* Print properties for the requested resource itself */
  6814. print_props(conn, conn->request_info.local_uri, filep);
  6815. /* If it is a directory, print directory entries too if Depth is not 0 */
  6816. if (filep && conn->ctx && filep->is_directory
  6817. && !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")
  6818. && (depth == NULL || strcmp(depth, "0") != 0)) {
  6819. scan_directory(conn, path, conn, &print_dav_dir_entry);
  6820. }
  6821. conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");
  6822. }
  6823. #endif
  6824. void
  6825. mg_lock_connection(struct mg_connection *conn)
  6826. {
  6827. if (conn) {
  6828. (void)pthread_mutex_lock(&conn->mutex);
  6829. }
  6830. }
  6831. void
  6832. mg_unlock_connection(struct mg_connection *conn)
  6833. {
  6834. if (conn) {
  6835. (void)pthread_mutex_unlock(&conn->mutex);
  6836. }
  6837. }
  6838. void
  6839. mg_lock_context(struct mg_context *ctx)
  6840. {
  6841. if (ctx) {
  6842. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  6843. }
  6844. }
  6845. void
  6846. mg_unlock_context(struct mg_context *ctx)
  6847. {
  6848. if (ctx) {
  6849. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  6850. }
  6851. }
  6852. #if defined(USE_TIMERS)
  6853. #include "timer.inl"
  6854. #endif /* USE_TIMERS */
  6855. #ifdef USE_LUA
  6856. #include "mod_lua.inl"
  6857. #endif /* USE_LUA */
  6858. #ifdef USE_DUKTAPE
  6859. #include "mod_duktape.inl"
  6860. #endif /* USE_DUKTAPE */
  6861. #if defined(USE_WEBSOCKET)
  6862. /* START OF SHA-1 code
  6863. * Copyright(c) By Steve Reid <steve@edmweb.com> */
  6864. #define SHA1HANDSOFF
  6865. /* According to current tests (May 2015), the <solarisfixes.h> is not required.
  6866. *
  6867. * #if defined(__sun)
  6868. * #include "solarisfixes.h"
  6869. * #endif
  6870. */
  6871. static int
  6872. is_big_endian(void)
  6873. {
  6874. static const int n = 1;
  6875. return ((char *)&n)[0] == 0;
  6876. }
  6877. union char64long16 {
  6878. unsigned char c[64];
  6879. uint32_t l[16];
  6880. };
  6881. #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
  6882. static uint32_t
  6883. blk0(union char64long16 *block, int i)
  6884. {
  6885. /* Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN */
  6886. if (!is_big_endian()) {
  6887. block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00)
  6888. | (rol(block->l[i], 8) & 0x00FF00FF);
  6889. }
  6890. return block->l[i];
  6891. }
  6892. #define blk(i) \
  6893. (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] \
  6894. ^ block->l[(i + 2) & 15] ^ block->l[i & 15], \
  6895. 1))
  6896. #define R0(v, w, x, y, z, i) \
  6897. z += ((w & (x ^ y)) ^ y) + blk0(block, i) + 0x5A827999 + rol(v, 5); \
  6898. w = rol(w, 30);
  6899. #define R1(v, w, x, y, z, i) \
  6900. z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \
  6901. w = rol(w, 30);
  6902. #define R2(v, w, x, y, z, i) \
  6903. z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \
  6904. w = rol(w, 30);
  6905. #define R3(v, w, x, y, z, i) \
  6906. z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \
  6907. w = rol(w, 30);
  6908. #define R4(v, w, x, y, z, i) \
  6909. z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \
  6910. w = rol(w, 30);
  6911. typedef struct {
  6912. uint32_t state[5];
  6913. uint32_t count[2];
  6914. unsigned char buffer[64];
  6915. } SHA1_CTX;
  6916. static void
  6917. SHA1Transform(uint32_t state[5], const unsigned char buffer[64])
  6918. {
  6919. uint32_t a, b, c, d, e;
  6920. union char64long16 block[1];
  6921. memcpy(block, buffer, 64);
  6922. a = state[0];
  6923. b = state[1];
  6924. c = state[2];
  6925. d = state[3];
  6926. e = state[4];
  6927. R0(a, b, c, d, e, 0);
  6928. R0(e, a, b, c, d, 1);
  6929. R0(d, e, a, b, c, 2);
  6930. R0(c, d, e, a, b, 3);
  6931. R0(b, c, d, e, a, 4);
  6932. R0(a, b, c, d, e, 5);
  6933. R0(e, a, b, c, d, 6);
  6934. R0(d, e, a, b, c, 7);
  6935. R0(c, d, e, a, b, 8);
  6936. R0(b, c, d, e, a, 9);
  6937. R0(a, b, c, d, e, 10);
  6938. R0(e, a, b, c, d, 11);
  6939. R0(d, e, a, b, c, 12);
  6940. R0(c, d, e, a, b, 13);
  6941. R0(b, c, d, e, a, 14);
  6942. R0(a, b, c, d, e, 15);
  6943. R1(e, a, b, c, d, 16);
  6944. R1(d, e, a, b, c, 17);
  6945. R1(c, d, e, a, b, 18);
  6946. R1(b, c, d, e, a, 19);
  6947. R2(a, b, c, d, e, 20);
  6948. R2(e, a, b, c, d, 21);
  6949. R2(d, e, a, b, c, 22);
  6950. R2(c, d, e, a, b, 23);
  6951. R2(b, c, d, e, a, 24);
  6952. R2(a, b, c, d, e, 25);
  6953. R2(e, a, b, c, d, 26);
  6954. R2(d, e, a, b, c, 27);
  6955. R2(c, d, e, a, b, 28);
  6956. R2(b, c, d, e, a, 29);
  6957. R2(a, b, c, d, e, 30);
  6958. R2(e, a, b, c, d, 31);
  6959. R2(d, e, a, b, c, 32);
  6960. R2(c, d, e, a, b, 33);
  6961. R2(b, c, d, e, a, 34);
  6962. R2(a, b, c, d, e, 35);
  6963. R2(e, a, b, c, d, 36);
  6964. R2(d, e, a, b, c, 37);
  6965. R2(c, d, e, a, b, 38);
  6966. R2(b, c, d, e, a, 39);
  6967. R3(a, b, c, d, e, 40);
  6968. R3(e, a, b, c, d, 41);
  6969. R3(d, e, a, b, c, 42);
  6970. R3(c, d, e, a, b, 43);
  6971. R3(b, c, d, e, a, 44);
  6972. R3(a, b, c, d, e, 45);
  6973. R3(e, a, b, c, d, 46);
  6974. R3(d, e, a, b, c, 47);
  6975. R3(c, d, e, a, b, 48);
  6976. R3(b, c, d, e, a, 49);
  6977. R3(a, b, c, d, e, 50);
  6978. R3(e, a, b, c, d, 51);
  6979. R3(d, e, a, b, c, 52);
  6980. R3(c, d, e, a, b, 53);
  6981. R3(b, c, d, e, a, 54);
  6982. R3(a, b, c, d, e, 55);
  6983. R3(e, a, b, c, d, 56);
  6984. R3(d, e, a, b, c, 57);
  6985. R3(c, d, e, a, b, 58);
  6986. R3(b, c, d, e, a, 59);
  6987. R4(a, b, c, d, e, 60);
  6988. R4(e, a, b, c, d, 61);
  6989. R4(d, e, a, b, c, 62);
  6990. R4(c, d, e, a, b, 63);
  6991. R4(b, c, d, e, a, 64);
  6992. R4(a, b, c, d, e, 65);
  6993. R4(e, a, b, c, d, 66);
  6994. R4(d, e, a, b, c, 67);
  6995. R4(c, d, e, a, b, 68);
  6996. R4(b, c, d, e, a, 69);
  6997. R4(a, b, c, d, e, 70);
  6998. R4(e, a, b, c, d, 71);
  6999. R4(d, e, a, b, c, 72);
  7000. R4(c, d, e, a, b, 73);
  7001. R4(b, c, d, e, a, 74);
  7002. R4(a, b, c, d, e, 75);
  7003. R4(e, a, b, c, d, 76);
  7004. R4(d, e, a, b, c, 77);
  7005. R4(c, d, e, a, b, 78);
  7006. R4(b, c, d, e, a, 79);
  7007. state[0] += a;
  7008. state[1] += b;
  7009. state[2] += c;
  7010. state[3] += d;
  7011. state[4] += e;
  7012. a = b = c = d = e = 0;
  7013. memset(block, '\0', sizeof(block));
  7014. }
  7015. static void
  7016. SHA1Init(SHA1_CTX *context)
  7017. {
  7018. context->state[0] = 0x67452301;
  7019. context->state[1] = 0xEFCDAB89;
  7020. context->state[2] = 0x98BADCFE;
  7021. context->state[3] = 0x10325476;
  7022. context->state[4] = 0xC3D2E1F0;
  7023. context->count[0] = context->count[1] = 0;
  7024. }
  7025. static void
  7026. SHA1Update(SHA1_CTX *context, const unsigned char *data, uint32_t len)
  7027. {
  7028. uint32_t i, j;
  7029. j = context->count[0];
  7030. if ((context->count[0] += len << 3) < j) {
  7031. context->count[1]++;
  7032. }
  7033. context->count[1] += (len >> 29);
  7034. j = (j >> 3) & 63;
  7035. if ((j + len) > 63) {
  7036. memcpy(&context->buffer[j], data, (i = 64 - j));
  7037. SHA1Transform(context->state, context->buffer);
  7038. for (; i + 63 < len; i += 64) {
  7039. SHA1Transform(context->state, &data[i]);
  7040. }
  7041. j = 0;
  7042. } else
  7043. i = 0;
  7044. memcpy(&context->buffer[j], &data[i], len - i);
  7045. }
  7046. static void
  7047. SHA1Final(unsigned char digest[20], SHA1_CTX *context)
  7048. {
  7049. unsigned i;
  7050. unsigned char finalcount[8], c;
  7051. for (i = 0; i < 8; i++) {
  7052. finalcount[i] = (unsigned char)((context->count[(i >= 4 ? 0 : 1)]
  7053. >> ((3 - (i & 3)) * 8)) & 255);
  7054. }
  7055. c = 0200;
  7056. SHA1Update(context, &c, 1);
  7057. while ((context->count[0] & 504) != 448) {
  7058. c = 0000;
  7059. SHA1Update(context, &c, 1);
  7060. }
  7061. SHA1Update(context, finalcount, 8);
  7062. for (i = 0; i < 20; i++) {
  7063. digest[i] = (unsigned char)((context->state[i >> 2]
  7064. >> ((3 - (i & 3)) * 8)) & 255);
  7065. }
  7066. memset(context, '\0', sizeof(*context));
  7067. memset(&finalcount, '\0', sizeof(finalcount));
  7068. }
  7069. /* END OF SHA1 CODE */
  7070. static int
  7071. send_websocket_handshake(struct mg_connection *conn)
  7072. {
  7073. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  7074. const char *protocol = NULL;
  7075. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  7076. SHA1_CTX sha_ctx;
  7077. int truncated;
  7078. mg_snprintf(conn,
  7079. &truncated,
  7080. buf,
  7081. sizeof(buf),
  7082. "%s%s",
  7083. mg_get_header(conn, "Sec-WebSocket-Key"),
  7084. magic);
  7085. if (truncated) {
  7086. conn->must_close = 1;
  7087. return 0;
  7088. }
  7089. SHA1Init(&sha_ctx);
  7090. SHA1Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  7091. SHA1Final((unsigned char *)sha, &sha_ctx);
  7092. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  7093. mg_printf(conn,
  7094. "HTTP/1.1 101 Switching Protocols\r\n"
  7095. "Upgrade: websocket\r\n"
  7096. "Connection: Upgrade\r\n"
  7097. "Sec-WebSocket-Accept: %s\r\n",
  7098. b64_sha);
  7099. protocol = mg_get_header(conn, "Sec-WebSocket-Protocol");
  7100. if (protocol) {
  7101. mg_printf(conn, "Sec-WebSocket-Protocol: %s\r\n\r\n", protocol);
  7102. } else {
  7103. mg_printf(conn, "%s", "\r\n");
  7104. }
  7105. return 1;
  7106. }
  7107. static void
  7108. read_websocket(struct mg_connection *conn,
  7109. mg_websocket_data_handler ws_data_handler,
  7110. void *callback_data)
  7111. {
  7112. /* Pointer to the beginning of the portion of the incoming websocket
  7113. * message queue.
  7114. * The original websocket upgrade request is never removed, so the queue
  7115. * begins after it. */
  7116. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  7117. int n, error, exit_by_callback;
  7118. /* body_len is the length of the entire queue in bytes
  7119. * len is the length of the current message
  7120. * data_len is the length of the current message's data payload
  7121. * header_len is the length of the current message's header */
  7122. size_t i, len, mask_len = 0, data_len = 0, header_len, body_len;
  7123. /* "The masking key is a 32-bit value chosen at random by the client."
  7124. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  7125. */
  7126. unsigned char mask[4];
  7127. /* data points to the place where the message is stored when passed to the
  7128. * websocket_data callback. This is either mem on the stack, or a
  7129. * dynamically allocated buffer if it is too large. */
  7130. char mem[4096];
  7131. char *data = mem;
  7132. unsigned char mop; /* mask flag and opcode */
  7133. double timeout = -1.0;
  7134. if (conn->ctx->config[WEBSOCKET_TIMEOUT]) {
  7135. timeout = atoi(conn->ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  7136. }
  7137. if ((timeout <= 0.0) && (conn->ctx->config[REQUEST_TIMEOUT])) {
  7138. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  7139. }
  7140. mg_set_thread_name("wsock");
  7141. /* Loop continuously, reading messages from the socket, invoking the
  7142. * callback, and waiting repeatedly until an error occurs. */
  7143. while (!conn->ctx->stop_flag) {
  7144. header_len = 0;
  7145. assert(conn->data_len >= conn->request_len);
  7146. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  7147. len = buf[1] & 127;
  7148. mask_len = buf[1] & 128 ? 4 : 0;
  7149. if (len < 126 && body_len >= mask_len) {
  7150. data_len = len;
  7151. header_len = 2 + mask_len;
  7152. } else if (len == 126 && body_len >= 4 + mask_len) {
  7153. header_len = 4 + mask_len;
  7154. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  7155. } else if (body_len >= 10 + mask_len) {
  7156. header_len = 10 + mask_len;
  7157. data_len = (((uint64_t)ntohl(*(uint32_t *)(void *)&buf[2]))
  7158. << 32) + ntohl(*(uint32_t *)(void *)&buf[6]);
  7159. }
  7160. }
  7161. if (header_len > 0 && body_len >= header_len) {
  7162. /* Allocate space to hold websocket payload */
  7163. data = mem;
  7164. if (data_len > sizeof(mem)) {
  7165. data = (char *)mg_malloc(data_len);
  7166. if (data == NULL) {
  7167. /* Allocation failed, exit the loop and then close the
  7168. * connection */
  7169. mg_cry(conn, "websocket out of memory; closing connection");
  7170. break;
  7171. }
  7172. }
  7173. /* Copy the mask before we shift the queue and destroy it */
  7174. if (mask_len > 0) {
  7175. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  7176. } else {
  7177. memset(mask, 0, sizeof(mask));
  7178. }
  7179. /* Read frame payload from the first message in the queue into
  7180. * data and advance the queue by moving the memory in place. */
  7181. assert(body_len >= header_len);
  7182. if (data_len + header_len > body_len) {
  7183. mop = buf[0]; /* current mask and opcode */
  7184. /* Overflow case */
  7185. len = body_len - header_len;
  7186. memcpy(data, buf + header_len, len);
  7187. error = 0;
  7188. while (len < data_len) {
  7189. n = pull(
  7190. NULL, conn, data + len, (int)(data_len - len), timeout);
  7191. if (n <= 0) {
  7192. error = 1;
  7193. break;
  7194. }
  7195. len += (size_t)n;
  7196. }
  7197. if (error) {
  7198. mg_cry(conn, "Websocket pull failed; closing connection");
  7199. break;
  7200. }
  7201. conn->data_len = conn->request_len;
  7202. } else {
  7203. mop = buf[0]; /* current mask and opcode, overwritten by
  7204. * memmove() */
  7205. /* Length of the message being read at the front of the
  7206. * queue */
  7207. len = data_len + header_len;
  7208. /* Copy the data payload into the data pointer for the
  7209. * callback */
  7210. memcpy(data, buf + header_len, data_len);
  7211. /* Move the queue forward len bytes */
  7212. memmove(buf, buf + len, body_len - len);
  7213. /* Mark the queue as advanced */
  7214. conn->data_len -= (int)len;
  7215. }
  7216. /* Apply mask if necessary */
  7217. if (mask_len > 0) {
  7218. for (i = 0; i < data_len; ++i) {
  7219. data[i] ^= mask[i & 3];
  7220. }
  7221. }
  7222. /* Exit the loop if callback signals to exit (server side),
  7223. * or "connection close" opcode received (client side). */
  7224. exit_by_callback = 0;
  7225. if ((ws_data_handler != NULL)
  7226. && !ws_data_handler(conn, mop, data, data_len, callback_data)) {
  7227. exit_by_callback = 1;
  7228. }
  7229. if (data != mem) {
  7230. mg_free(data);
  7231. }
  7232. if (exit_by_callback
  7233. || ((mop & 0xf) == WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  7234. /* Opcode == 8, connection close */
  7235. break;
  7236. }
  7237. /* Not breaking the loop, process next websocket frame. */
  7238. } else {
  7239. /* Read from the socket into the next available location in the
  7240. * message queue. */
  7241. if ((n = pull(NULL,
  7242. conn,
  7243. conn->buf + conn->data_len,
  7244. conn->buf_size - conn->data_len,
  7245. timeout)) <= 0) {
  7246. /* Error, no bytes read */
  7247. break;
  7248. }
  7249. conn->data_len += n;
  7250. }
  7251. }
  7252. mg_set_thread_name("worker");
  7253. }
  7254. static int
  7255. mg_websocket_write_exec(struct mg_connection *conn,
  7256. int opcode,
  7257. const char *data,
  7258. size_t dataLen,
  7259. uint32_t masking_key)
  7260. {
  7261. unsigned char header[14];
  7262. size_t headerLen = 1;
  7263. int retval = -1;
  7264. header[0] = 0x80 + (opcode & 0xF);
  7265. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  7266. if (dataLen < 126) {
  7267. /* inline 7-bit length field */
  7268. header[1] = (unsigned char)dataLen;
  7269. headerLen = 2;
  7270. } else if (dataLen <= 0xFFFF) {
  7271. /* 16-bit length field */
  7272. header[1] = 126;
  7273. *(uint16_t *)(void *)(header + 2) = htons((uint16_t)dataLen);
  7274. headerLen = 4;
  7275. } else {
  7276. /* 64-bit length field */
  7277. header[1] = 127;
  7278. *(uint32_t *)(void *)(header + 2) = htonl((uint64_t)dataLen >> 32);
  7279. *(uint32_t *)(void *)(header + 6) = htonl(dataLen & 0xFFFFFFFF);
  7280. headerLen = 10;
  7281. }
  7282. if (masking_key) {
  7283. /* add mask */
  7284. header[1] |= 0x80;
  7285. *(uint32_t *)(void *)(header + headerLen) = masking_key;
  7286. headerLen += 4;
  7287. }
  7288. /* Note that POSIX/Winsock's send() is threadsafe
  7289. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  7290. * but mongoose's mg_printf/mg_write is not (because of the loop in
  7291. * push(), although that is only a problem if the packet is large or
  7292. * outgoing buffer is full). */
  7293. (void)mg_lock_connection(conn);
  7294. retval = mg_write(conn, header, headerLen);
  7295. if (dataLen > 0) {
  7296. retval = mg_write(conn, data, dataLen);
  7297. }
  7298. mg_unlock_connection(conn);
  7299. return retval;
  7300. }
  7301. int
  7302. mg_websocket_write(struct mg_connection *conn,
  7303. int opcode,
  7304. const char *data,
  7305. size_t dataLen)
  7306. {
  7307. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  7308. }
  7309. static void
  7310. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  7311. {
  7312. size_t i = 0;
  7313. i = 0;
  7314. if (((ptrdiff_t)in % 4) == 0) {
  7315. /* Convert in 32 bit words, if data is 4 byte aligned */
  7316. while (i < (in_len - 3)) {
  7317. *(uint32_t *)(void *)(out + i) =
  7318. *(uint32_t *)(void *)(in + i) ^ masking_key;
  7319. i += 4;
  7320. }
  7321. }
  7322. if (i != in_len) {
  7323. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  7324. while (i < in_len) {
  7325. *(uint8_t *)(void *)(out + i) =
  7326. *(uint8_t *)(void *)(in + i)
  7327. ^ *(((uint8_t *)&masking_key) + (i % 4));
  7328. i++;
  7329. }
  7330. }
  7331. }
  7332. int
  7333. mg_websocket_client_write(struct mg_connection *conn,
  7334. int opcode,
  7335. const char *data,
  7336. size_t dataLen)
  7337. {
  7338. int retval = -1;
  7339. char *masked_data = (char *)mg_malloc(((dataLen + 7) / 4) * 4);
  7340. uint32_t masking_key = (uint32_t)get_random();
  7341. if (masked_data == NULL) {
  7342. /* Return -1 in an error case */
  7343. mg_cry(conn,
  7344. "Cannot allocate buffer for masked websocket response: "
  7345. "Out of memory");
  7346. return -1;
  7347. }
  7348. mask_data(data, dataLen, masking_key, masked_data);
  7349. retval = mg_websocket_write_exec(
  7350. conn, opcode, masked_data, dataLen, masking_key);
  7351. mg_free(masked_data);
  7352. return retval;
  7353. }
  7354. static void
  7355. handle_websocket_request(struct mg_connection *conn,
  7356. const char *path,
  7357. int is_callback_resource,
  7358. mg_websocket_connect_handler ws_connect_handler,
  7359. mg_websocket_ready_handler ws_ready_handler,
  7360. mg_websocket_data_handler ws_data_handler,
  7361. mg_websocket_close_handler ws_close_handler,
  7362. void *cbData)
  7363. {
  7364. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  7365. int lua_websock = 0;
  7366. #if !defined(USE_LUA)
  7367. (void)path;
  7368. #endif
  7369. /* Step 1: Check websocket protocol version. */
  7370. if (version == NULL || strcmp(version, "13") != 0) {
  7371. /* Reject wrong versions */
  7372. send_http_error(conn, 426, "%s", "Protocol upgrade required");
  7373. return;
  7374. }
  7375. /* Step 2: If a callback is responsible, call it. */
  7376. if (is_callback_resource) {
  7377. if (ws_connect_handler != NULL
  7378. && ws_connect_handler(conn, cbData) != 0) {
  7379. /* C callback has returned non-zero, do not proceed with handshake.
  7380. */
  7381. /* Note that C callbacks are no longer called when Lua is
  7382. * responsible, so C can no longer filter callbacks for Lua. */
  7383. return;
  7384. }
  7385. }
  7386. #if defined(USE_LUA)
  7387. /* Step 3: No callback. Check if Lua is responsible. */
  7388. else {
  7389. /* Step 3.1: Check if Lua is responsible. */
  7390. if (conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  7391. lua_websock =
  7392. match_prefix(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  7393. strlen(
  7394. conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  7395. path);
  7396. }
  7397. if (lua_websock) {
  7398. /* Step 3.2: Lua is responsible: call it. */
  7399. conn->lua_websocket_state = lua_websocket_new(path, conn);
  7400. if (!conn->lua_websocket_state) {
  7401. /* Lua rejected the new client */
  7402. return;
  7403. }
  7404. }
  7405. }
  7406. #endif
  7407. /* Step 4: Check if there is a responsible websocket handler. */
  7408. if (!is_callback_resource && !lua_websock) {
  7409. /* There is no callback, an Lua is not responsible either. */
  7410. /* Reply with a 404 Not Found or with nothing at all?
  7411. * TODO (mid): check the websocket standards, how to reply to
  7412. * requests to invalid websocket addresses. */
  7413. send_http_error(conn, 404, "%s", "Not found");
  7414. return;
  7415. }
  7416. /* Step 5: The websocket connection has been accepted */
  7417. if (!send_websocket_handshake(conn)) {
  7418. send_http_error(conn, 500, "%s", "Websocket handshake failed");
  7419. return;
  7420. }
  7421. /* Step 6: Call the ready handler */
  7422. if (is_callback_resource) {
  7423. if (ws_ready_handler != NULL) {
  7424. ws_ready_handler(conn, cbData);
  7425. }
  7426. #if defined(USE_LUA)
  7427. } else if (lua_websock) {
  7428. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  7429. /* the ready handler returned false */
  7430. return;
  7431. }
  7432. #endif
  7433. }
  7434. /* Step 7: Enter the read loop */
  7435. if (is_callback_resource) {
  7436. read_websocket(conn, ws_data_handler, cbData);
  7437. #if defined(USE_LUA)
  7438. } else if (lua_websock) {
  7439. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  7440. #endif
  7441. }
  7442. /* Step 8: Call the close handler */
  7443. if (ws_close_handler) {
  7444. ws_close_handler(conn, cbData);
  7445. }
  7446. }
  7447. static int
  7448. is_websocket_protocol(const struct mg_connection *conn)
  7449. {
  7450. const char *host, *upgrade, *connection, *version, *key;
  7451. upgrade = mg_get_header(conn, "Upgrade");
  7452. if (upgrade == NULL) {
  7453. return 0; /* fail early, don't waste time checking other header fields
  7454. */
  7455. }
  7456. if (!mg_strcasestr(upgrade, "websocket")) {
  7457. return 0;
  7458. }
  7459. connection = mg_get_header(conn, "Connection");
  7460. if (connection == NULL) {
  7461. return 0;
  7462. }
  7463. if (!mg_strcasestr(connection, "upgrade")) {
  7464. return 0;
  7465. }
  7466. host = mg_get_header(conn, "Host");
  7467. key = mg_get_header(conn, "Sec-WebSocket-Key");
  7468. version = mg_get_header(conn, "Sec-WebSocket-Version");
  7469. return (host != NULL && key != NULL && version != NULL);
  7470. }
  7471. #endif /* !USE_WEBSOCKET */
  7472. static int
  7473. isbyte(int n)
  7474. {
  7475. return n >= 0 && n <= 255;
  7476. }
  7477. static int
  7478. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  7479. {
  7480. int n, a, b, c, d, slash = 32, len = 0;
  7481. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5
  7482. || sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) && isbyte(a)
  7483. && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0
  7484. && slash < 33) {
  7485. len = n;
  7486. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  7487. | (uint32_t)d;
  7488. *mask = slash ? 0xffffffffU << (32 - slash) : 0;
  7489. }
  7490. return len;
  7491. }
  7492. static int
  7493. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  7494. {
  7495. int throttle = 0;
  7496. struct vec vec, val;
  7497. uint32_t net, mask;
  7498. char mult;
  7499. double v;
  7500. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  7501. mult = ',';
  7502. if (sscanf(val.ptr, "%lf%c", &v, &mult) < 1 || v < 0
  7503. || (lowercase(&mult) != 'k' && lowercase(&mult) != 'm'
  7504. && mult != ',')) {
  7505. continue;
  7506. }
  7507. v *= lowercase(&mult) == 'k' ? 1024 : lowercase(&mult) == 'm' ? 1048576
  7508. : 1;
  7509. if (vec.len == 1 && vec.ptr[0] == '*') {
  7510. throttle = (int)v;
  7511. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  7512. if ((remote_ip & mask) == net) {
  7513. throttle = (int)v;
  7514. }
  7515. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  7516. throttle = (int)v;
  7517. }
  7518. }
  7519. return throttle;
  7520. }
  7521. static uint32_t
  7522. get_remote_ip(const struct mg_connection *conn)
  7523. {
  7524. if (!conn) {
  7525. return 0;
  7526. }
  7527. return ntohl(*(uint32_t *)&conn->client.rsa.sin.sin_addr);
  7528. }
  7529. int
  7530. mg_upload(struct mg_connection *conn, const char *destination_dir)
  7531. {
  7532. /* TODO (high): completely rewrite this function. See issue #180. */
  7533. /* TODO (mid): set a timeout */
  7534. const char *content_type_header, *boundary_start, *sc;
  7535. char *s;
  7536. char buf[MG_BUF_LEN], path[PATH_MAX], tmp_path[PATH_MAX];
  7537. char fname[1024], boundary[100];
  7538. FILE *fp;
  7539. int bl, n, i, headers_len, boundary_len, eof, truncated;
  7540. int len = 0, num_uploaded_files = 0;
  7541. struct mg_request_info part_request_info;
  7542. /* Request looks like this:
  7543. *
  7544. * POST /upload HTTP/1.1
  7545. * Host: 127.0.0.1:8080
  7546. * Content-Length: 244894
  7547. * Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryRVr
  7548. *
  7549. * ------WebKitFormBoundaryRVr
  7550. * Content-Disposition: form-data; name="file"; filename="accum.png"
  7551. * Content-Type: image/png
  7552. *
  7553. * <89>PNG
  7554. * <PNG DATA>
  7555. * ------WebKitFormBoundaryRVr */
  7556. /* Extract boundary string from the Content-Type header */
  7557. if ((content_type_header = mg_get_header(conn, "Content-Type")) == NULL
  7558. || (boundary_start = mg_strcasestr(content_type_header, "boundary="))
  7559. == NULL
  7560. || (sscanf(boundary_start, "boundary=\"%99[^\"]\"", boundary) == 0
  7561. && sscanf(boundary_start, "boundary=%99s", boundary) == 0)
  7562. || boundary[0] == '\0') {
  7563. return num_uploaded_files;
  7564. }
  7565. boundary[99] = 0;
  7566. boundary_len = (int)strlen(boundary);
  7567. bl = boundary_len + 4; /* \r\n--<boundary> */
  7568. for (;;) {
  7569. /* Pull in headers */
  7570. /* assert(len >= 0 && len <= (int) sizeof(buf)); */
  7571. if ((len < 0) || (len > (int)sizeof(buf))) {
  7572. break;
  7573. }
  7574. while ((n = mg_read(conn, buf + len, sizeof(buf) - (size_t)len)) > 0) {
  7575. len += n;
  7576. /* assert(len <= (int) sizeof(buf)); */
  7577. if (len > (int)sizeof(buf)) {
  7578. break;
  7579. }
  7580. }
  7581. if ((headers_len = get_request_len(buf, len)) <= 0) {
  7582. break;
  7583. }
  7584. /* terminate header */
  7585. buf[headers_len - 1] = 0;
  7586. /* Scan for the boundary string and skip it */
  7587. if (buf[0] == '-' && buf[1] == '-'
  7588. && !memcmp(buf + 2, boundary, (size_t)boundary_len)) {
  7589. s = &buf[bl];
  7590. } else {
  7591. s = &buf[2];
  7592. }
  7593. /* Get headers for this part of the multipart message */
  7594. memset(&part_request_info, 0, sizeof(part_request_info));
  7595. parse_http_headers(&s, &part_request_info);
  7596. /* assert(&buf[headers_len-1] == s); */
  7597. if (&buf[headers_len - 1] != s) {
  7598. break;
  7599. }
  7600. /* Fetch file name. */
  7601. sc = get_header(&part_request_info, "Content-Disposition");
  7602. if (!sc) {
  7603. /* invalid part of a multipart message */
  7604. break;
  7605. }
  7606. sc = strstr(sc, "filename");
  7607. if (!sc) {
  7608. /* no filename set */
  7609. break;
  7610. }
  7611. sc += 8; /* skip "filename" */
  7612. fname[0] = '\0';
  7613. IGNORE_UNUSED_RESULT(sscanf(sc, " = \"%1023[^\"]", fname));
  7614. fname[1023] = 0;
  7615. /* Give up if the headers are not what we expect */
  7616. if (fname[0] == '\0') {
  7617. break;
  7618. }
  7619. /* Construct destination file name. Do not allow paths to have
  7620. * slashes. */
  7621. if ((s = strrchr(fname, '/')) == NULL
  7622. && (s = strrchr(fname, '\\')) == NULL) {
  7623. s = fname;
  7624. } else {
  7625. s++;
  7626. }
  7627. /* There data is written to a temporary file first. */
  7628. /* Different users should use a different destination_dir. */
  7629. mg_snprintf(conn,
  7630. &truncated,
  7631. path,
  7632. sizeof(path) - 1,
  7633. "%s/%s",
  7634. destination_dir,
  7635. s);
  7636. /* TODO(high): kick client on buffer overflow */
  7637. strcpy(tmp_path, path);
  7638. strcat(tmp_path, "~");
  7639. /* We open the file with exclusive lock held. This guarantee us
  7640. * there is no other thread can save into the same file
  7641. * simultaneously. */
  7642. fp = NULL;
  7643. /* Open file in binary mode. */
  7644. if ((fp = fopen(tmp_path, "wb")) == NULL) {
  7645. break;
  7646. }
  7647. /* Move data to the beginning of the buffer */
  7648. /* part_request_info is no longer valid after this operation */
  7649. /* assert(len >= headers_len); */
  7650. if (len < headers_len) {
  7651. break;
  7652. }
  7653. memmove(buf, &buf[headers_len], (size_t)(len - headers_len));
  7654. len -= headers_len;
  7655. /* Read POST data, write into file until boundary is found. */
  7656. eof = n = 0;
  7657. do {
  7658. len += n;
  7659. for (i = 0; i < len - bl; i++) {
  7660. if (!memcmp(&buf[i], "\r\n--", 4)
  7661. && !memcmp(&buf[i + 4], boundary, (size_t)boundary_len)) {
  7662. /* Found boundary, that's the end of file data. */
  7663. fwrite(buf, 1, (size_t)i, fp);
  7664. eof = 1;
  7665. memmove(buf, &buf[i + bl], (size_t)(len - (i + bl)));
  7666. len -= i + bl;
  7667. break;
  7668. }
  7669. }
  7670. if (!eof && len > bl) {
  7671. fwrite(buf, 1, (size_t)(len - bl), fp);
  7672. memmove(buf, &buf[len - bl], (size_t)bl);
  7673. len = bl;
  7674. }
  7675. if (!eof) {
  7676. n = mg_read(conn, buf + len, sizeof(buf) - ((size_t)(len)));
  7677. }
  7678. } while (!eof && (n > 0));
  7679. fclose(fp);
  7680. if (eof) {
  7681. remove(path);
  7682. rename(tmp_path, path);
  7683. num_uploaded_files++;
  7684. if (conn && conn->ctx && conn->ctx->callbacks.upload != NULL) {
  7685. conn->ctx->callbacks.upload(conn, path);
  7686. }
  7687. } else {
  7688. remove(tmp_path);
  7689. }
  7690. }
  7691. return num_uploaded_files;
  7692. }
  7693. static int
  7694. get_first_ssl_listener_index(const struct mg_context *ctx)
  7695. {
  7696. unsigned int i;
  7697. int idx = -1;
  7698. if (ctx) {
  7699. for (i = 0; idx == -1 && i < ctx->num_listening_sockets; i++) {
  7700. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  7701. }
  7702. }
  7703. return idx;
  7704. }
  7705. static void
  7706. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  7707. {
  7708. char host[1025];
  7709. const char *host_header;
  7710. size_t hostlen;
  7711. host_header = mg_get_header(conn, "Host");
  7712. hostlen = sizeof(host);
  7713. if (host_header != NULL) {
  7714. char *pos;
  7715. mg_strlcpy(host, host_header, hostlen);
  7716. host[hostlen - 1] = '\0';
  7717. pos = strchr(host, ':');
  7718. if (pos != NULL) {
  7719. *pos = '\0';
  7720. }
  7721. } else {
  7722. /* Cannot get host from the Host: header.
  7723. * Fallback to our IP address. */
  7724. if (conn) {
  7725. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  7726. }
  7727. }
  7728. /* Send host, port, uri and (if it exists) ?query_string */
  7729. if (conn) {
  7730. mg_printf(conn,
  7731. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  7732. host,
  7733. (int)ntohs(
  7734. conn->ctx->listening_sockets[ssl_index].lsa.sin.sin_port),
  7735. conn->request_info.local_uri,
  7736. (conn->request_info.query_string == NULL) ? "" : "?",
  7737. (conn->request_info.query_string == NULL)
  7738. ? ""
  7739. : conn->request_info.query_string);
  7740. }
  7741. }
  7742. static void
  7743. mg_set_request_handler_type(struct mg_context *ctx,
  7744. const char *uri,
  7745. int is_websocket_handler,
  7746. int is_delete_request,
  7747. mg_request_handler handler,
  7748. mg_websocket_connect_handler connect_handler,
  7749. mg_websocket_ready_handler ready_handler,
  7750. mg_websocket_data_handler data_handler,
  7751. mg_websocket_close_handler close_handler,
  7752. void *cbdata)
  7753. {
  7754. struct mg_request_handler_info *tmp_rh, **lastref;
  7755. size_t urilen = strlen(uri);
  7756. if (is_websocket_handler) {
  7757. /* assert(handler == NULL); */
  7758. /* assert(is_delete_request || connect_handler!=NULL ||
  7759. * ready_handler!=NULL || data_handler!=NULL ||
  7760. * close_handler!=NULL);
  7761. */
  7762. if (handler != NULL) {
  7763. return;
  7764. }
  7765. if (!is_delete_request && connect_handler == NULL
  7766. && ready_handler == NULL
  7767. && data_handler == NULL
  7768. && close_handler == NULL) {
  7769. return;
  7770. }
  7771. } else {
  7772. /* assert(connect_handler==NULL && ready_handler==NULL &&
  7773. * data_handler==NULL && close_handler==NULL); */
  7774. /* assert(is_delete_request || (handler!=NULL));
  7775. */
  7776. if (connect_handler != NULL || ready_handler != NULL
  7777. || data_handler != NULL
  7778. || close_handler != NULL) {
  7779. return;
  7780. }
  7781. if (!is_delete_request && (handler == NULL)) {
  7782. return;
  7783. }
  7784. }
  7785. if (!ctx) {
  7786. return;
  7787. }
  7788. mg_lock_context(ctx);
  7789. /* first try to find an existing handler */
  7790. lastref = &(ctx->request_handlers);
  7791. for (tmp_rh = ctx->request_handlers; tmp_rh != NULL;
  7792. tmp_rh = tmp_rh->next) {
  7793. if (tmp_rh->is_websocket_handler == is_websocket_handler) {
  7794. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  7795. if (!is_delete_request) {
  7796. /* update existing handler */
  7797. if (!is_websocket_handler) {
  7798. tmp_rh->handler = handler;
  7799. } else {
  7800. tmp_rh->connect_handler = connect_handler;
  7801. tmp_rh->ready_handler = ready_handler;
  7802. tmp_rh->data_handler = data_handler;
  7803. tmp_rh->close_handler = close_handler;
  7804. }
  7805. tmp_rh->cbdata = cbdata;
  7806. } else {
  7807. /* remove existing handler */
  7808. *lastref = tmp_rh->next;
  7809. mg_free(tmp_rh->uri);
  7810. mg_free(tmp_rh);
  7811. }
  7812. mg_unlock_context(ctx);
  7813. return;
  7814. }
  7815. }
  7816. lastref = &(tmp_rh->next);
  7817. }
  7818. if (is_delete_request) {
  7819. /* no handler to set, this was a remove request to a non-existing
  7820. * handler */
  7821. mg_unlock_context(ctx);
  7822. return;
  7823. }
  7824. tmp_rh = (struct mg_request_handler_info *)
  7825. mg_calloc(sizeof(struct mg_request_handler_info), 1);
  7826. if (tmp_rh == NULL) {
  7827. mg_unlock_context(ctx);
  7828. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  7829. return;
  7830. }
  7831. tmp_rh->uri = mg_strdup(uri);
  7832. if (!tmp_rh->uri) {
  7833. mg_unlock_context(ctx);
  7834. mg_free(tmp_rh);
  7835. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  7836. return;
  7837. }
  7838. tmp_rh->uri_len = urilen;
  7839. if (!is_websocket_handler) {
  7840. tmp_rh->handler = handler;
  7841. } else {
  7842. tmp_rh->connect_handler = connect_handler;
  7843. tmp_rh->ready_handler = ready_handler;
  7844. tmp_rh->data_handler = data_handler;
  7845. tmp_rh->close_handler = close_handler;
  7846. }
  7847. tmp_rh->cbdata = cbdata;
  7848. tmp_rh->is_websocket_handler = is_websocket_handler;
  7849. tmp_rh->next = NULL;
  7850. *lastref = tmp_rh;
  7851. mg_unlock_context(ctx);
  7852. }
  7853. void
  7854. mg_set_request_handler(struct mg_context *ctx,
  7855. const char *uri,
  7856. mg_request_handler handler,
  7857. void *cbdata)
  7858. {
  7859. mg_set_request_handler_type(
  7860. ctx, uri, 0, handler == NULL, handler, NULL, NULL, NULL, NULL, cbdata);
  7861. }
  7862. void
  7863. mg_set_websocket_handler(struct mg_context *ctx,
  7864. const char *uri,
  7865. mg_websocket_connect_handler connect_handler,
  7866. mg_websocket_ready_handler ready_handler,
  7867. mg_websocket_data_handler data_handler,
  7868. mg_websocket_close_handler close_handler,
  7869. void *cbdata)
  7870. {
  7871. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  7872. && (data_handler == NULL)
  7873. && (close_handler == NULL);
  7874. mg_set_request_handler_type(ctx,
  7875. uri,
  7876. 1,
  7877. is_delete_request,
  7878. NULL,
  7879. connect_handler,
  7880. ready_handler,
  7881. data_handler,
  7882. close_handler,
  7883. cbdata);
  7884. }
  7885. static int
  7886. get_request_handler(struct mg_connection *conn,
  7887. int is_websocket_request,
  7888. mg_request_handler *handler,
  7889. mg_websocket_connect_handler *connect_handler,
  7890. mg_websocket_ready_handler *ready_handler,
  7891. mg_websocket_data_handler *data_handler,
  7892. mg_websocket_close_handler *close_handler,
  7893. void **cbdata)
  7894. {
  7895. const struct mg_request_info *request_info = mg_get_request_info(conn);
  7896. if (request_info) {
  7897. const char *uri = request_info->local_uri;
  7898. size_t urilen = strlen(uri);
  7899. struct mg_request_handler_info *tmp_rh;
  7900. if (!conn || !conn->ctx) {
  7901. return 0;
  7902. }
  7903. mg_lock_context(conn->ctx);
  7904. /* first try for an exact match */
  7905. for (tmp_rh = conn->ctx->request_handlers; tmp_rh != NULL;
  7906. tmp_rh = tmp_rh->next) {
  7907. if (tmp_rh->is_websocket_handler == is_websocket_request) {
  7908. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  7909. if (is_websocket_request) {
  7910. *connect_handler = tmp_rh->connect_handler;
  7911. *ready_handler = tmp_rh->ready_handler;
  7912. *data_handler = tmp_rh->data_handler;
  7913. *close_handler = tmp_rh->close_handler;
  7914. } else {
  7915. *handler = tmp_rh->handler;
  7916. }
  7917. *cbdata = tmp_rh->cbdata;
  7918. mg_unlock_context(conn->ctx);
  7919. return 1;
  7920. }
  7921. }
  7922. }
  7923. /* next try for a partial match, we will accept uri/something */
  7924. for (tmp_rh = conn->ctx->request_handlers; tmp_rh != NULL;
  7925. tmp_rh = tmp_rh->next) {
  7926. if (tmp_rh->is_websocket_handler == is_websocket_request) {
  7927. if (tmp_rh->uri_len < urilen && uri[tmp_rh->uri_len] == '/'
  7928. && memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0) {
  7929. if (is_websocket_request) {
  7930. *connect_handler = tmp_rh->connect_handler;
  7931. *ready_handler = tmp_rh->ready_handler;
  7932. *data_handler = tmp_rh->data_handler;
  7933. *close_handler = tmp_rh->close_handler;
  7934. } else {
  7935. *handler = tmp_rh->handler;
  7936. }
  7937. *cbdata = tmp_rh->cbdata;
  7938. mg_unlock_context(conn->ctx);
  7939. return 1;
  7940. }
  7941. }
  7942. }
  7943. /* finally try for pattern match */
  7944. for (tmp_rh = conn->ctx->request_handlers; tmp_rh != NULL;
  7945. tmp_rh = tmp_rh->next) {
  7946. if (tmp_rh->is_websocket_handler == is_websocket_request) {
  7947. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  7948. if (is_websocket_request) {
  7949. *connect_handler = tmp_rh->connect_handler;
  7950. *ready_handler = tmp_rh->ready_handler;
  7951. *data_handler = tmp_rh->data_handler;
  7952. *close_handler = tmp_rh->close_handler;
  7953. } else {
  7954. *handler = tmp_rh->handler;
  7955. }
  7956. *cbdata = tmp_rh->cbdata;
  7957. mg_unlock_context(conn->ctx);
  7958. return 1;
  7959. }
  7960. }
  7961. }
  7962. mg_unlock_context(conn->ctx);
  7963. }
  7964. return 0; /* none found */
  7965. }
  7966. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  7967. static int
  7968. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  7969. void *cbdata)
  7970. {
  7971. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  7972. if (pcallbacks->websocket_connect) {
  7973. return pcallbacks->websocket_connect(conn);
  7974. }
  7975. /* No handler set - assume "OK" */
  7976. return 0;
  7977. }
  7978. static void
  7979. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  7980. {
  7981. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  7982. if (pcallbacks->websocket_ready) {
  7983. pcallbacks->websocket_ready(conn);
  7984. }
  7985. }
  7986. static int
  7987. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  7988. int bits,
  7989. char *data,
  7990. size_t len,
  7991. void *cbdata)
  7992. {
  7993. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  7994. if (pcallbacks->websocket_data) {
  7995. return pcallbacks->websocket_data(conn, bits, data, len);
  7996. }
  7997. /* No handler set - assume "OK" */
  7998. return 1;
  7999. }
  8000. #endif
  8001. /* This is the heart of the Civetweb's logic.
  8002. * This function is called when the request is read, parsed and validated,
  8003. * and Civetweb must decide what action to take: serve a file, or
  8004. * a directory, or call embedded function, etcetera. */
  8005. static void
  8006. handle_request(struct mg_connection *conn)
  8007. {
  8008. if (conn) {
  8009. struct mg_request_info *ri = &conn->request_info;
  8010. char path[PATH_MAX];
  8011. int uri_len, ssl_index;
  8012. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  8013. is_put_or_delete_request = 0, is_callback_resource = 0;
  8014. int i;
  8015. struct file file = STRUCT_FILE_INITIALIZER;
  8016. mg_request_handler callback_handler = NULL;
  8017. mg_websocket_connect_handler ws_connect_handler = NULL;
  8018. mg_websocket_ready_handler ws_ready_handler = NULL;
  8019. mg_websocket_data_handler ws_data_handler = NULL;
  8020. mg_websocket_close_handler ws_close_handler = NULL;
  8021. void *callback_data = NULL;
  8022. #if !defined(NO_FILES)
  8023. time_t curtime = time(NULL);
  8024. char date[64];
  8025. #endif
  8026. path[0] = 0;
  8027. if (!ri) {
  8028. return;
  8029. }
  8030. /* 1. get the request url */
  8031. /* 1.1. split into url and query string */
  8032. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  8033. != NULL) {
  8034. *((char *)conn->request_info.query_string++) = '\0';
  8035. }
  8036. uri_len = (int)strlen(ri->local_uri);
  8037. /* 1.2. decode url (if config says so) */
  8038. if (should_decode_url(conn)) {
  8039. mg_url_decode(
  8040. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  8041. }
  8042. /* 1.3. clean URIs, so a path like allowed_dir/../forbidden_file is not
  8043. * possible */
  8044. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  8045. /* step 1. completed, the url is known now */
  8046. DEBUG_TRACE("URL: %s", ri->local_uri);
  8047. /* 2. do a https redirect, if required */
  8048. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  8049. ssl_index = get_first_ssl_listener_index(conn->ctx);
  8050. if (ssl_index >= 0) {
  8051. redirect_to_https_port(conn, ssl_index);
  8052. } else {
  8053. /* A http to https forward port has been specified,
  8054. * but no https port to forward to. */
  8055. send_http_error(conn,
  8056. 503,
  8057. "%s",
  8058. "Error: SSL forward not configured properly");
  8059. mg_cry(conn, "Can not redirect to SSL, no SSL port available");
  8060. }
  8061. return;
  8062. }
  8063. /* 3. if this ip has limited speed, set it for this connection */
  8064. conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
  8065. get_remote_ip(conn),
  8066. ri->local_uri);
  8067. /* 4. call a "handle everything" callback, if registered */
  8068. if (conn->ctx->callbacks.begin_request != NULL) {
  8069. /* Note that since V1.7 the "begin_request" function is called
  8070. * before an authorization check. If an authorization check is
  8071. * required, use a request_handler instead. */
  8072. i = conn->ctx->callbacks.begin_request(conn);
  8073. if (i > 0) {
  8074. /* callback already processed the request. Store the
  8075. return value as a status code for the access log. */
  8076. conn->status_code = i;
  8077. return;
  8078. } else if (i == 0) {
  8079. /* civetweb should process the request */
  8080. } else {
  8081. /* unspecified - may change with the next version */
  8082. return;
  8083. }
  8084. }
  8085. /* request not yet handled by a handler or redirect, so the request
  8086. * is processed here */
  8087. /* 5. interpret the url to find out how the request must be handled */
  8088. /* 5.1. first test, if the request targets the regular http(s)://
  8089. * protocol namespace or the websocket ws(s):// protocol namespace. */
  8090. is_websocket_request = is_websocket_protocol(conn);
  8091. /* 5.2. check if the request will be handled by a callback */
  8092. if (get_request_handler(conn,
  8093. is_websocket_request,
  8094. &callback_handler,
  8095. &ws_connect_handler,
  8096. &ws_ready_handler,
  8097. &ws_data_handler,
  8098. &ws_close_handler,
  8099. &callback_data)) {
  8100. /* 5.2.1. A callback will handle this request. All requests handled
  8101. * by a callback have to be considered as requests to a script
  8102. * resource. */
  8103. is_callback_resource = 1;
  8104. is_script_resource = 1;
  8105. is_put_or_delete_request = is_put_or_delete_method(conn);
  8106. } else {
  8107. no_callback_resource:
  8108. /* 5.2.2. No callback is responsible for this request. The URI
  8109. * addresses a file based resource (static content or Lua/cgi
  8110. * scripts in the file system). */
  8111. is_callback_resource = 0;
  8112. interpret_uri(conn,
  8113. path,
  8114. sizeof(path),
  8115. &file,
  8116. &is_found,
  8117. &is_script_resource,
  8118. &is_websocket_request,
  8119. &is_put_or_delete_request);
  8120. }
  8121. /* 6. authorization check */
  8122. if (is_put_or_delete_request && !is_script_resource
  8123. && !is_callback_resource) {
  8124. /* 6.1. this request is a PUT/DELETE to a real file */
  8125. /* 6.1.1. thus, the server must have real files */
  8126. #if defined(NO_FILES)
  8127. if (1) {
  8128. #else
  8129. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  8130. #endif
  8131. /* This server does not have any real files, thus the
  8132. * PUT/DELETE methods are not valid. */
  8133. send_http_error(conn,
  8134. 405,
  8135. "%s method not allowed",
  8136. conn->request_info.request_method);
  8137. return;
  8138. }
  8139. #if !defined(NO_FILES)
  8140. /* 6.1.2. Check if put authorization for static files is available.
  8141. */
  8142. if (!is_authorized_for_put(conn)) {
  8143. send_authorization_request(conn);
  8144. return;
  8145. }
  8146. #endif
  8147. } else {
  8148. /* 6.2. This is either a OPTIONS, GET, HEAD or POST request,
  8149. * or it is a PUT or DELETE request to a resource that does not
  8150. * correspond to a file. Check authorization. */
  8151. if (!check_authorization(conn, path)) {
  8152. send_authorization_request(conn);
  8153. return;
  8154. }
  8155. }
  8156. /* request is authorized or does not need authorization */
  8157. /* 7. check if there are request handlers for this uri */
  8158. if (is_callback_resource) {
  8159. if (!is_websocket_request) {
  8160. i = callback_handler(conn, callback_data);
  8161. if (i > 0) {
  8162. /* Do nothing, callback has served the request. Store the
  8163. * return value as status code for the log and discard all
  8164. * data from the client not used by the callback. */
  8165. conn->status_code = i;
  8166. discard_unread_request_data(conn);
  8167. } else {
  8168. /* TODO (high): what if the handler did NOT handle the
  8169. * request */
  8170. /* The last version did handle this as a file request, but
  8171. * since a file request is not always a script resource,
  8172. * the authorization check might be different */
  8173. interpret_uri(conn,
  8174. path,
  8175. sizeof(path),
  8176. &file,
  8177. &is_found,
  8178. &is_script_resource,
  8179. &is_websocket_request,
  8180. &is_put_or_delete_request);
  8181. callback_handler = NULL;
  8182. /* TODO (very low): goto is deprecated but for the moment,
  8183. * a goto is simpler than some curious loop. */
  8184. /* The situation "callback does not handle the request"
  8185. * needs to be reconsidered anyway. */
  8186. goto no_callback_resource;
  8187. }
  8188. } else {
  8189. #if defined(USE_WEBSOCKET)
  8190. handle_websocket_request(conn,
  8191. path,
  8192. is_callback_resource,
  8193. ws_connect_handler,
  8194. ws_ready_handler,
  8195. ws_data_handler,
  8196. ws_close_handler,
  8197. callback_data);
  8198. #endif
  8199. }
  8200. return;
  8201. }
  8202. /* 8. handle websocket requests */
  8203. #if defined(USE_WEBSOCKET)
  8204. if (is_websocket_request) {
  8205. if (is_script_resource) {
  8206. /* Websocket Lua script */
  8207. handle_websocket_request(conn,
  8208. path,
  8209. 0 /* Lua Script */,
  8210. NULL,
  8211. NULL,
  8212. NULL,
  8213. NULL,
  8214. &conn->ctx->callbacks);
  8215. } else {
  8216. #if defined(MG_LEGACY_INTERFACE)
  8217. handle_websocket_request(
  8218. conn,
  8219. path,
  8220. !is_script_resource /* could be deprecated global callback */,
  8221. deprecated_websocket_connect_wrapper,
  8222. deprecated_websocket_ready_wrapper,
  8223. deprecated_websocket_data_wrapper,
  8224. NULL,
  8225. &conn->ctx->callbacks);
  8226. #else
  8227. send_http_error(conn, 404, "%s", "Not found");
  8228. #endif
  8229. }
  8230. return;
  8231. } else
  8232. #endif
  8233. #if defined(NO_FILES)
  8234. /* 9a. In case the server uses only callbacks, this uri is unknown.
  8235. * Then, all request handling ends here. */
  8236. send_http_error(conn, 404, "%s", "Not Found");
  8237. #else
  8238. /* 9b. This request is either for a static file or resource handled
  8239. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  8240. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  8241. send_http_error(conn, 404, "%s", "Not Found");
  8242. return;
  8243. }
  8244. /* 10. File is handled by a script. */
  8245. if (is_script_resource) {
  8246. handle_file_based_request(conn, path, &file);
  8247. return;
  8248. }
  8249. /* 11. Handle put/delete/mkcol requests */
  8250. if (is_put_or_delete_request) {
  8251. /* 11.1. PUT method */
  8252. if (!strcmp(ri->request_method, "PUT")) {
  8253. put_file(conn, path);
  8254. return;
  8255. }
  8256. /* 11.2. DELETE method */
  8257. if (!strcmp(ri->request_method, "DELETE")) {
  8258. delete_file(conn, path);
  8259. return;
  8260. }
  8261. /* 11.3. MKCOL method */
  8262. if (!strcmp(ri->request_method, "MKCOL")) {
  8263. mkcol(conn, path);
  8264. return;
  8265. }
  8266. /* 11.4. PATCH method
  8267. * This method is not supported for static resources,
  8268. * only for scripts (Lua, CGI) and callbacks. */
  8269. send_http_error(conn,
  8270. 405,
  8271. "%s method not allowed",
  8272. conn->request_info.request_method);
  8273. return;
  8274. }
  8275. /* 11. File does not exist, or it was configured that it should be
  8276. * hidden */
  8277. if (!is_found || (must_hide_file(conn, path))) {
  8278. send_http_error(conn, 404, "%s", "Not found");
  8279. return;
  8280. }
  8281. /* 12. Directories uris should end with a slash */
  8282. if (file.is_directory && ri->local_uri[uri_len - 1] != '/') {
  8283. gmt_time_string(date, sizeof(date), &curtime);
  8284. mg_printf(conn,
  8285. "HTTP/1.1 301 Moved Permanently\r\n"
  8286. "Location: %s/\r\n"
  8287. "Date: %s\r\n"
  8288. /* TODO: "Cache-Control" ? */
  8289. "Content-Length: 0\r\n"
  8290. "Connection: %s\r\n\r\n",
  8291. ri->request_uri,
  8292. date,
  8293. suggest_connection_header(conn));
  8294. return;
  8295. }
  8296. /* 13. Handle other methods than GET/HEAD */
  8297. /* 13.1. Handle PROPFIND */
  8298. if (!strcmp(ri->request_method, "PROPFIND")) {
  8299. handle_propfind(conn, path, &file);
  8300. return;
  8301. }
  8302. /* 13.2. Handle OPTIONS for files */
  8303. if (!strcmp(ri->request_method, "OPTIONS")) {
  8304. /* This standard handler is only used for real files.
  8305. * Scripts should support the OPTIONS method themselves, to allow a
  8306. * maximum flexibility.
  8307. * Lua and CGI scripts may fully support CORS this way (including
  8308. * preflights). */
  8309. send_options(conn);
  8310. return;
  8311. }
  8312. /* 13.3. everything but GET and HEAD (e.g. POST) */
  8313. if (0 != strcmp(ri->request_method, "GET")
  8314. && 0 != strcmp(ri->request_method, "HEAD")) {
  8315. send_http_error(conn,
  8316. 405,
  8317. "%s method not allowed",
  8318. conn->request_info.request_method);
  8319. return;
  8320. }
  8321. /* 14. directories */
  8322. if (file.is_directory) {
  8323. if (substitute_index_file(conn, path, sizeof(path), &file)) {
  8324. /* 14.1. use a substitute file */
  8325. /* TODO (high): substitute index may be a script resource.
  8326. * define what should be possible in this case. */
  8327. } else {
  8328. /* 14.2. no substitute file */
  8329. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  8330. "yes")) {
  8331. handle_directory_request(conn, path);
  8332. } else {
  8333. send_http_error(conn,
  8334. 403,
  8335. "%s",
  8336. "Error: Directory listing denied");
  8337. }
  8338. return;
  8339. }
  8340. }
  8341. handle_file_based_request(conn, path, &file);
  8342. #endif /* !defined(NO_FILES) */
  8343. #if 0
  8344. /* Perform redirect and auth checks before calling begin_request()
  8345. * handler.
  8346. * Otherwise, begin_request() would need to perform auth checks and
  8347. * redirects. */
  8348. #endif
  8349. }
  8350. return;
  8351. }
  8352. static void
  8353. handle_file_based_request(struct mg_connection *conn,
  8354. const char *path,
  8355. struct file *file)
  8356. {
  8357. if (!conn || !conn->ctx) {
  8358. return;
  8359. }
  8360. if (0) {
  8361. #ifdef USE_LUA
  8362. } else if (match_prefix(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  8363. strlen(
  8364. conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  8365. path) > 0) {
  8366. /* Lua server page: an SSI like page containing mostly plain html code
  8367. * plus some tags with server generated contents. */
  8368. handle_lsp_request(conn, path, file, NULL);
  8369. } else if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  8370. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  8371. path) > 0) {
  8372. /* Lua in-server module script: a CGI like script used to generate the
  8373. * entire reply. */
  8374. mg_exec_lua_script(conn, path, NULL);
  8375. #endif
  8376. #if defined(USE_DUKTAPE)
  8377. } else if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  8378. strlen(
  8379. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  8380. path) > 0) {
  8381. /* Call duktape to generate the page */
  8382. mg_exec_duktape_script(conn, path);
  8383. #endif
  8384. #if !defined(NO_CGI)
  8385. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  8386. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  8387. path) > 0) {
  8388. /* CGI scripts may support all HTTP methods */
  8389. handle_cgi_request(conn, path);
  8390. #endif /* !NO_CGI */
  8391. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  8392. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  8393. path) > 0) {
  8394. handle_ssi_file_request(conn, path, file);
  8395. } else if ((!conn->in_error_handler) && is_not_modified(conn, file)) {
  8396. /* Send 304 "Not Modified" - this must not send any body data */
  8397. send_http_error(conn, 304, "%s", "");
  8398. } else {
  8399. handle_static_file_request(conn, path, file);
  8400. }
  8401. }
  8402. static void
  8403. close_all_listening_sockets(struct mg_context *ctx)
  8404. {
  8405. unsigned int i;
  8406. if (!ctx) {
  8407. return;
  8408. }
  8409. for (i = 0; i < ctx->num_listening_sockets; i++) {
  8410. closesocket(ctx->listening_sockets[i].sock);
  8411. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  8412. }
  8413. mg_free(ctx->listening_sockets);
  8414. ctx->listening_sockets = NULL;
  8415. mg_free(ctx->listening_ports);
  8416. ctx->listening_ports = NULL;
  8417. }
  8418. /* Valid listening port specification is: [ip_address:]port[s]
  8419. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 1.2.3.4:8080s
  8420. * Examples for IPv6: [::]:80, [::1]:80,
  8421. * [FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:443s
  8422. * see https://tools.ietf.org/html/rfc3513#section-2.2 */
  8423. static int
  8424. parse_port_string(const struct vec *vec, struct socket *so)
  8425. {
  8426. unsigned int a, b, c, d, port;
  8427. int ch, len;
  8428. #if defined(USE_IPV6)
  8429. char buf[100] = {0};
  8430. #endif
  8431. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  8432. * Also, all-zeroes in the socket address means binding to all addresses
  8433. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  8434. memset(so, 0, sizeof(*so));
  8435. so->lsa.sin.sin_family = AF_INET;
  8436. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  8437. == 5) {
  8438. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  8439. so->lsa.sin.sin_addr.s_addr =
  8440. htonl((a << 24) | (b << 16) | (c << 8) | d);
  8441. so->lsa.sin.sin_port = htons((uint16_t)port);
  8442. #if defined(USE_IPV6)
  8443. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  8444. && mg_inet_pton(
  8445. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  8446. /* IPv6 address, examples: see above */
  8447. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton */
  8448. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  8449. #endif
  8450. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  8451. /* If only port is specified, bind to IPv4, INADDR_ANY */
  8452. so->lsa.sin.sin_port = htons((uint16_t)port);
  8453. } else {
  8454. /* Parsing failure. Make port invalid. */
  8455. port = 0;
  8456. len = 0;
  8457. }
  8458. /* sscanf and the option splitting code ensure the following condition */
  8459. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  8460. return 0;
  8461. }
  8462. ch = vec->ptr[len]; /* Next character after the port number */
  8463. so->is_ssl = (ch == 's');
  8464. so->ssl_redir = (ch == 'r');
  8465. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  8466. return is_valid_port(port)
  8467. && (ch == '\0' || ch == 's' || ch == 'r' || ch == ',');
  8468. }
  8469. static int
  8470. set_ports_option(struct mg_context *ctx)
  8471. {
  8472. const char *list;
  8473. int on = 1;
  8474. #if defined(USE_IPV6)
  8475. int off = 0;
  8476. #endif
  8477. struct vec vec;
  8478. struct socket so, *ptr;
  8479. in_port_t *portPtr;
  8480. union usa usa;
  8481. socklen_t len;
  8482. int portsTotal = 0;
  8483. int portsOk = 0;
  8484. if (!ctx) {
  8485. return 0;
  8486. }
  8487. memset(&so, 0, sizeof(so));
  8488. memset(&usa, 0, sizeof(usa));
  8489. len = sizeof(usa);
  8490. list = ctx->config[LISTENING_PORTS];
  8491. while ((list = next_option(list, &vec, NULL)) != NULL) {
  8492. portsTotal++;
  8493. if (!parse_port_string(&vec, &so)) {
  8494. mg_cry(fc(ctx),
  8495. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  8496. (int)vec.len,
  8497. vec.ptr,
  8498. portsTotal,
  8499. "[IP_ADDRESS:]PORT[s|r]");
  8500. continue;
  8501. }
  8502. if (so.is_ssl && ctx->ssl_ctx == NULL) {
  8503. mg_cry(fc(ctx),
  8504. "Cannot add SSL socket (entry %i). Is -ssl_certificate "
  8505. "option set?",
  8506. portsTotal);
  8507. continue;
  8508. }
  8509. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  8510. == INVALID_SOCKET) {
  8511. mg_cry(fc(ctx), "cannot create socket (entry %i)", portsTotal);
  8512. continue;
  8513. }
  8514. #ifdef _WIN32
  8515. /* Windows SO_REUSEADDR lets many procs binds to a
  8516. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  8517. * if someone already has the socket -- DTL */
  8518. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  8519. * Windows might need a few seconds before
  8520. * the same port can be used again in the
  8521. * same process, so a short Sleep may be
  8522. * required between mg_stop and mg_start.
  8523. */
  8524. if (setsockopt(so.sock,
  8525. SOL_SOCKET,
  8526. SO_EXCLUSIVEADDRUSE,
  8527. (SOCK_OPT_TYPE)&on,
  8528. sizeof(on)) != 0) {
  8529. mg_cry(fc(ctx),
  8530. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  8531. portsTotal);
  8532. }
  8533. #else
  8534. if (setsockopt(so.sock,
  8535. SOL_SOCKET,
  8536. SO_REUSEADDR,
  8537. (SOCK_OPT_TYPE)&on,
  8538. sizeof(on)) != 0) {
  8539. mg_cry(fc(ctx),
  8540. "cannot set socket option SO_REUSEADDR (entry %i)",
  8541. portsTotal);
  8542. }
  8543. #endif
  8544. #if defined(USE_IPV6)
  8545. if (so.lsa.sa.sa_family == AF_INET6
  8546. && setsockopt(so.sock,
  8547. IPPROTO_IPV6,
  8548. IPV6_V6ONLY,
  8549. (void *)&off,
  8550. sizeof(off)) != 0) {
  8551. mg_cry(fc(ctx),
  8552. "cannot set socket option IPV6_V6ONLY (entry %i)",
  8553. portsTotal);
  8554. }
  8555. #endif
  8556. if (so.lsa.sa.sa_family == AF_INET) {
  8557. len = sizeof(so.lsa.sin);
  8558. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  8559. mg_cry(fc(ctx),
  8560. "cannot bind to %.*s: %d (%s)",
  8561. (int)vec.len,
  8562. vec.ptr,
  8563. (int)ERRNO,
  8564. strerror(errno));
  8565. closesocket(so.sock);
  8566. so.sock = INVALID_SOCKET;
  8567. continue;
  8568. }
  8569. }
  8570. #if defined(USE_IPV6)
  8571. else if (so.lsa.sa.sa_family == AF_INET6) {
  8572. len = sizeof(so.lsa.sin6);
  8573. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  8574. mg_cry(fc(ctx),
  8575. "cannot bind to IPv6 %.*s: %d (%s)",
  8576. (int)vec.len,
  8577. vec.ptr,
  8578. (int)ERRNO,
  8579. strerror(errno));
  8580. closesocket(so.sock);
  8581. so.sock = INVALID_SOCKET;
  8582. continue;
  8583. }
  8584. }
  8585. #endif
  8586. else {
  8587. mg_cry(fc(ctx),
  8588. "cannot bind: address family not supported (entry %i)",
  8589. portsTotal);
  8590. continue;
  8591. }
  8592. if (listen(so.sock, SOMAXCONN) != 0) {
  8593. mg_cry(fc(ctx),
  8594. "cannot listen to %.*s: %d (%s)",
  8595. (int)vec.len,
  8596. vec.ptr,
  8597. (int)ERRNO,
  8598. strerror(errno));
  8599. closesocket(so.sock);
  8600. so.sock = INVALID_SOCKET;
  8601. continue;
  8602. }
  8603. if (getsockname(so.sock, &(usa.sa), &len) != 0) {
  8604. int err = (int)ERRNO;
  8605. mg_cry(fc(ctx),
  8606. "call to getsockname failed %.*s: %d (%s)",
  8607. (int)vec.len,
  8608. vec.ptr,
  8609. err,
  8610. strerror(errno));
  8611. closesocket(so.sock);
  8612. so.sock = INVALID_SOCKET;
  8613. continue;
  8614. }
  8615. if ((ptr = (struct socket *)
  8616. mg_realloc(ctx->listening_sockets,
  8617. (ctx->num_listening_sockets + 1)
  8618. * sizeof(ctx->listening_sockets[0]))) == NULL) {
  8619. mg_cry(fc(ctx), "%s", "Out of memory");
  8620. closesocket(so.sock);
  8621. so.sock = INVALID_SOCKET;
  8622. continue;
  8623. }
  8624. if ((portPtr =
  8625. (in_port_t *)mg_realloc(ctx->listening_ports,
  8626. (ctx->num_listening_sockets + 1)
  8627. * sizeof(ctx->listening_ports[0])))
  8628. == NULL) {
  8629. mg_cry(fc(ctx), "%s", "Out of memory");
  8630. closesocket(so.sock);
  8631. so.sock = INVALID_SOCKET;
  8632. mg_free(ptr);
  8633. continue;
  8634. }
  8635. set_close_on_exec(so.sock, fc(ctx));
  8636. ctx->listening_sockets = ptr;
  8637. ctx->listening_sockets[ctx->num_listening_sockets] = so;
  8638. ctx->listening_ports = portPtr;
  8639. ctx->listening_ports[ctx->num_listening_sockets] =
  8640. ntohs(usa.sin.sin_port);
  8641. ctx->num_listening_sockets++;
  8642. portsOk++;
  8643. }
  8644. if (portsOk != portsTotal) {
  8645. close_all_listening_sockets(ctx);
  8646. portsOk = 0;
  8647. }
  8648. return portsOk;
  8649. }
  8650. static const char *
  8651. header_val(const struct mg_connection *conn, const char *header)
  8652. {
  8653. const char *header_value;
  8654. if ((header_value = mg_get_header(conn, header)) == NULL) {
  8655. return "-";
  8656. } else {
  8657. return header_value;
  8658. }
  8659. }
  8660. static void
  8661. log_access(const struct mg_connection *conn)
  8662. {
  8663. const struct mg_request_info *ri;
  8664. FILE *fp;
  8665. char date[64], src_addr[IP_ADDR_STR_LEN];
  8666. struct tm *tm;
  8667. const char *referer;
  8668. const char *user_agent;
  8669. char buf[4096];
  8670. if (!conn || !conn->ctx) {
  8671. return;
  8672. }
  8673. fp = conn->ctx->config[ACCESS_LOG_FILE] == NULL
  8674. ? NULL
  8675. : fopen(conn->ctx->config[ACCESS_LOG_FILE], "a+");
  8676. if (fp == NULL && conn->ctx->callbacks.log_message == NULL) {
  8677. return;
  8678. }
  8679. tm = localtime(&conn->conn_birth_time);
  8680. if (tm != NULL) {
  8681. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  8682. } else {
  8683. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  8684. date[sizeof(date) - 1] = '\0';
  8685. }
  8686. ri = &conn->request_info;
  8687. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  8688. referer = header_val(conn, "Referer");
  8689. user_agent = header_val(conn, "User-Agent");
  8690. mg_snprintf(conn,
  8691. NULL, /* Ignore truncation in access log */
  8692. buf,
  8693. sizeof(buf),
  8694. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  8695. src_addr,
  8696. ri->remote_user == NULL ? "-" : ri->remote_user,
  8697. date,
  8698. ri->request_method ? ri->request_method : "-",
  8699. ri->request_uri ? ri->request_uri : "-",
  8700. ri->query_string ? "?" : "",
  8701. ri->query_string ? ri->query_string : "",
  8702. ri->http_version,
  8703. conn->status_code,
  8704. conn->num_bytes_sent,
  8705. referer,
  8706. user_agent);
  8707. if (conn->ctx->callbacks.log_access) {
  8708. conn->ctx->callbacks.log_access(conn, buf);
  8709. }
  8710. if (fp) {
  8711. flockfile(fp);
  8712. fprintf(fp, "%s", buf);
  8713. fputc('\n', fp);
  8714. fflush(fp);
  8715. funlockfile(fp);
  8716. fclose(fp);
  8717. }
  8718. }
  8719. /* Verify given socket address against the ACL.
  8720. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed. */
  8721. static int
  8722. check_acl(struct mg_context *ctx, uint32_t remote_ip)
  8723. {
  8724. int allowed, flag;
  8725. uint32_t net, mask;
  8726. struct vec vec;
  8727. if (ctx) {
  8728. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  8729. /* If any ACL is set, deny by default */
  8730. allowed = list == NULL ? '+' : '-';
  8731. while ((list = next_option(list, &vec, NULL)) != NULL) {
  8732. flag = vec.ptr[0];
  8733. if ((flag != '+' && flag != '-')
  8734. || parse_net(&vec.ptr[1], &net, &mask) == 0) {
  8735. mg_cry(fc(ctx),
  8736. "%s: subnet must be [+|-]x.x.x.x[/x]",
  8737. __func__);
  8738. return -1;
  8739. }
  8740. if (net == (remote_ip & mask)) {
  8741. allowed = flag;
  8742. }
  8743. }
  8744. return allowed == '+';
  8745. }
  8746. return -1;
  8747. }
  8748. #if !defined(_WIN32)
  8749. static int
  8750. set_uid_option(struct mg_context *ctx)
  8751. {
  8752. struct passwd *pw;
  8753. if (ctx) {
  8754. const char *uid = ctx->config[RUN_AS_USER];
  8755. int success = 0;
  8756. if (uid == NULL) {
  8757. success = 1;
  8758. } else {
  8759. if ((pw = getpwnam(uid)) == NULL) {
  8760. mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  8761. } else if (setgid(pw->pw_gid) == -1) {
  8762. mg_cry(fc(ctx),
  8763. "%s: setgid(%s): %s",
  8764. __func__,
  8765. uid,
  8766. strerror(errno));
  8767. } else if (setgroups(0, NULL)) {
  8768. mg_cry(fc(ctx),
  8769. "%s: setgroups(): %s",
  8770. __func__,
  8771. strerror(errno));
  8772. } else if (setuid(pw->pw_uid) == -1) {
  8773. mg_cry(fc(ctx),
  8774. "%s: setuid(%s): %s",
  8775. __func__,
  8776. uid,
  8777. strerror(errno));
  8778. } else {
  8779. success = 1;
  8780. }
  8781. }
  8782. return success;
  8783. }
  8784. return 0;
  8785. }
  8786. #endif /* !_WIN32 */
  8787. static void
  8788. tls_dtor(void *key)
  8789. {
  8790. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  8791. /* key == pthread_getspecific(sTlsKey); */
  8792. if (tls) {
  8793. if (tls->is_master == 2) {
  8794. tls->is_master = -3; /* Mark memory as dead */
  8795. mg_free(tls);
  8796. }
  8797. }
  8798. pthread_setspecific(sTlsKey, NULL);
  8799. }
  8800. #if !defined(NO_SSL)
  8801. /* Must be set if sizeof(pthread_t) > sizeof(unsigned long) */
  8802. static unsigned long
  8803. ssl_id_callback(void)
  8804. {
  8805. #ifdef _WIN32
  8806. return GetCurrentThreadId();
  8807. #else
  8808. #ifdef __clang__
  8809. #pragma clang diagnostic push
  8810. #pragma clang diagnostic ignored "-Wunreachable-code"
  8811. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  8812. * or not, so one of the two conditions will be unreachable by construction.
  8813. * Unfortunately the C standard does not define a way to check this at
  8814. * compile time, since the #if preprocessor conditions can not use the sizeof
  8815. * operator as an argument. */
  8816. #endif
  8817. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  8818. /* This is the problematic case for CRYPTO_set_id_callback:
  8819. * The OS pthread_t can not be cast to unsigned long. */
  8820. struct mg_workerTLS *tls =
  8821. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  8822. if (tls == NULL) {
  8823. /* SSL called from an unknown thread: Create some thread index. */
  8824. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  8825. tls->is_master = -2; /* -2 means "3rd party thread" */
  8826. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  8827. pthread_setspecific(sTlsKey, tls);
  8828. }
  8829. return tls->thread_idx;
  8830. } else {
  8831. return (unsigned long)pthread_self();
  8832. }
  8833. #ifdef __clang__
  8834. #pragma clang diagnostic pop
  8835. #endif
  8836. #endif
  8837. }
  8838. static pthread_mutex_t *ssl_mutexes;
  8839. static int
  8840. sslize(struct mg_connection *conn, SSL_CTX *s, int (*func)(SSL *))
  8841. {
  8842. int ret, err;
  8843. if (!conn) {
  8844. return 0;
  8845. }
  8846. conn->ssl = SSL_new(s);
  8847. if (conn->ssl == NULL) {
  8848. return 0;
  8849. }
  8850. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  8851. if (ret != 1) {
  8852. err = SSL_get_error(conn->ssl, ret);
  8853. (void)err; /* TODO: set some error message */
  8854. SSL_free(conn->ssl);
  8855. conn->ssl = NULL;
  8856. return 0;
  8857. }
  8858. ret = func(conn->ssl);
  8859. if (ret != 1) {
  8860. err = SSL_get_error(conn->ssl, ret);
  8861. (void)err; /* TODO: set some error message */
  8862. SSL_free(conn->ssl);
  8863. conn->ssl = NULL;
  8864. return 0;
  8865. }
  8866. return 1;
  8867. }
  8868. /* Return OpenSSL error message (from CRYPTO lib) */
  8869. static const char *
  8870. ssl_error(void)
  8871. {
  8872. unsigned long err;
  8873. err = ERR_get_error();
  8874. return err == 0 ? "" : ERR_error_string(err, NULL);
  8875. }
  8876. static void
  8877. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  8878. {
  8879. (void)line;
  8880. (void)file;
  8881. if (mode & 1) {
  8882. /* 1 is CRYPTO_LOCK */
  8883. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  8884. } else {
  8885. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  8886. }
  8887. }
  8888. #if !defined(NO_SSL_DL)
  8889. static void *
  8890. load_dll(struct mg_context *ctx, const char *dll_name, struct ssl_func *sw)
  8891. {
  8892. union {
  8893. void *p;
  8894. void (*fp)(void);
  8895. } u;
  8896. void *dll_handle;
  8897. struct ssl_func *fp;
  8898. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  8899. mg_cry(fc(ctx), "%s: cannot load %s", __func__, dll_name);
  8900. return NULL;
  8901. }
  8902. for (fp = sw; fp->name != NULL; fp++) {
  8903. #ifdef _WIN32
  8904. /* GetProcAddress() returns pointer to function */
  8905. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  8906. #else
  8907. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  8908. * pointers to function pointers. We need to use a union to make a
  8909. * cast. */
  8910. u.p = dlsym(dll_handle, fp->name);
  8911. #endif /* _WIN32 */
  8912. if (u.fp == NULL) {
  8913. mg_cry(fc(ctx),
  8914. "%s: %s: cannot find %s",
  8915. __func__,
  8916. dll_name,
  8917. fp->name);
  8918. dlclose(dll_handle);
  8919. return NULL;
  8920. } else {
  8921. fp->ptr = u.fp;
  8922. }
  8923. }
  8924. return dll_handle;
  8925. }
  8926. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  8927. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  8928. #endif /* NO_SSL_DL */
  8929. #if defined(SSL_ALREADY_INITIALIZED)
  8930. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  8931. #else
  8932. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  8933. #endif
  8934. static int
  8935. initialize_ssl(struct mg_context *ctx)
  8936. {
  8937. int i;
  8938. size_t size;
  8939. #if !defined(NO_SSL_DL)
  8940. if (!cryptolib_dll_handle) {
  8941. cryptolib_dll_handle = load_dll(ctx, CRYPTO_LIB, crypto_sw);
  8942. if (!cryptolib_dll_handle) {
  8943. return 0;
  8944. }
  8945. }
  8946. #endif /* NO_SSL_DL */
  8947. if (mg_atomic_inc(&cryptolib_users) > 1) {
  8948. return 1;
  8949. }
  8950. /* Initialize locking callbacks, needed for thread safety.
  8951. * http://www.openssl.org/support/faq.html#PROG1
  8952. */
  8953. i = CRYPTO_num_locks();
  8954. if (i < 0) {
  8955. i = 0;
  8956. }
  8957. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  8958. if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  8959. mg_cry(fc(ctx),
  8960. "%s: cannot allocate mutexes: %s",
  8961. __func__,
  8962. ssl_error());
  8963. return 0;
  8964. }
  8965. for (i = 0; i < CRYPTO_num_locks(); i++) {
  8966. pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr);
  8967. }
  8968. CRYPTO_set_locking_callback(&ssl_locking_callback);
  8969. CRYPTO_set_id_callback(&ssl_id_callback);
  8970. return 1;
  8971. }
  8972. static int
  8973. ssl_use_pem_file(struct mg_context *ctx, const char *pem)
  8974. {
  8975. if (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0) {
  8976. mg_cry(fc(ctx),
  8977. "%s: cannot open certificate file %s: %s",
  8978. __func__,
  8979. pem,
  8980. ssl_error());
  8981. return 0;
  8982. }
  8983. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  8984. if (SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0) {
  8985. mg_cry(fc(ctx),
  8986. "%s: cannot open private key file %s: %s",
  8987. __func__,
  8988. pem,
  8989. ssl_error());
  8990. return 0;
  8991. }
  8992. if (SSL_CTX_check_private_key(ctx->ssl_ctx) == 0) {
  8993. mg_cry(fc(ctx),
  8994. "%s: certificate and private key do not match: %s",
  8995. __func__,
  8996. pem);
  8997. return 0;
  8998. }
  8999. if (SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem) == 0) {
  9000. mg_cry(fc(ctx),
  9001. "%s: cannot use certificate chain file %s: %s",
  9002. __func__,
  9003. pem,
  9004. ssl_error());
  9005. return 0;
  9006. }
  9007. return 1;
  9008. }
  9009. /* Dynamically load SSL library. Set up ctx->ssl_ctx pointer. */
  9010. static int
  9011. set_ssl_option(struct mg_context *ctx)
  9012. {
  9013. const char *pem;
  9014. int callback_ret;
  9015. int should_verify_peer;
  9016. const char *ca_path;
  9017. const char *ca_file;
  9018. int use_default_verify_paths;
  9019. int verify_depth;
  9020. time_t now_rt = time(NULL);
  9021. struct timespec now_mt;
  9022. md5_byte_t ssl_context_id[16];
  9023. md5_state_t md5state;
  9024. /* If PEM file is not specified and the init_ssl callback
  9025. * is not specified, skip SSL initialization. */
  9026. if (!ctx) {
  9027. return 0;
  9028. }
  9029. if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL
  9030. && ctx->callbacks.init_ssl == NULL) {
  9031. return 1;
  9032. }
  9033. if (!initialize_ssl(ctx)) {
  9034. return 0;
  9035. }
  9036. #if !defined(NO_SSL_DL)
  9037. if (!ssllib_dll_handle) {
  9038. ssllib_dll_handle = load_dll(ctx, SSL_LIB, ssl_sw);
  9039. if (!ssllib_dll_handle) {
  9040. return 0;
  9041. }
  9042. }
  9043. #endif /* NO_SSL_DL */
  9044. /* Initialize SSL library */
  9045. SSL_library_init();
  9046. SSL_load_error_strings();
  9047. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  9048. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  9049. return 0;
  9050. }
  9051. /* If a callback has been specified, call it. */
  9052. callback_ret =
  9053. (ctx->callbacks.init_ssl == NULL)
  9054. ? 0
  9055. : (ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data));
  9056. /* If callback returns 0, civetweb sets up the SSL certificate.
  9057. * If it returns 1, civetweb assumes the calback already did this.
  9058. * If it returns -1, initializing ssl fails. */
  9059. if (callback_ret < 0) {
  9060. mg_cry(fc(ctx), "SSL callback returned error: %i", callback_ret);
  9061. return 0;
  9062. }
  9063. if (callback_ret > 0) {
  9064. if (pem != NULL) {
  9065. (void)SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
  9066. }
  9067. return 1;
  9068. }
  9069. /* Use some UID as session context ID. */
  9070. md5_init(&md5state);
  9071. md5_append(&md5state, (const md5_byte_t *)&now_rt, sizeof(now_rt));
  9072. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  9073. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  9074. md5_append(&md5state,
  9075. (const md5_byte_t *)ctx->config[LISTENING_PORTS],
  9076. strlen(ctx->config[LISTENING_PORTS]));
  9077. md5_append(&md5state, (const md5_byte_t *)ctx, sizeof(*ctx));
  9078. md5_finish(&md5state, ssl_context_id);
  9079. SSL_CTX_set_session_id_context(ctx->ssl_ctx,
  9080. (const unsigned char *)&ssl_context_id,
  9081. sizeof(ssl_context_id));
  9082. if (pem != NULL) {
  9083. if (!ssl_use_pem_file(ctx, pem)) {
  9084. return 0;
  9085. }
  9086. }
  9087. should_verify_peer =
  9088. (ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  9089. && (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0);
  9090. use_default_verify_paths =
  9091. (ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  9092. && (mg_strcasecmp(ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes") == 0);
  9093. if (should_verify_peer) {
  9094. ca_path = ctx->config[SSL_CA_PATH];
  9095. ca_file = ctx->config[SSL_CA_FILE];
  9096. if (SSL_CTX_load_verify_locations(ctx->ssl_ctx, ca_file, ca_path)
  9097. != 1) {
  9098. mg_cry(
  9099. fc(ctx),
  9100. "SSL_CTX_load_verify_locations error: %s "
  9101. "ssl_verify_peer requires setting "
  9102. "either ssl_ca_path or ssl_ca_file. Is any of them present in "
  9103. "the .conf file?",
  9104. ssl_error());
  9105. return 0;
  9106. }
  9107. SSL_CTX_set_verify(ctx->ssl_ctx,
  9108. SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  9109. NULL);
  9110. if (use_default_verify_paths
  9111. && SSL_CTX_set_default_verify_paths(ctx->ssl_ctx) != 1) {
  9112. mg_cry(fc(ctx),
  9113. "SSL_CTX_set_default_verify_paths error: %s",
  9114. ssl_error());
  9115. return 0;
  9116. }
  9117. if (ctx->config[SSL_VERIFY_DEPTH]) {
  9118. verify_depth = atoi(ctx->config[SSL_VERIFY_DEPTH]);
  9119. SSL_CTX_set_verify_depth(ctx->ssl_ctx, verify_depth);
  9120. }
  9121. }
  9122. /* TODO: could set use SSL_CTX_set_cipher_list if set */
  9123. return 1;
  9124. }
  9125. static void
  9126. uninitialize_ssl(struct mg_context *ctx)
  9127. {
  9128. int i;
  9129. (void)ctx;
  9130. if (mg_atomic_dec(&cryptolib_users) == 0) {
  9131. CRYPTO_set_locking_callback(NULL);
  9132. for (i = 0; i < CRYPTO_num_locks(); i++) {
  9133. pthread_mutex_destroy(&ssl_mutexes[i]);
  9134. }
  9135. CRYPTO_set_locking_callback(NULL);
  9136. CRYPTO_set_id_callback(NULL);
  9137. }
  9138. }
  9139. #endif /* !NO_SSL */
  9140. static int
  9141. set_gpass_option(struct mg_context *ctx)
  9142. {
  9143. if (ctx) {
  9144. struct file file = STRUCT_FILE_INITIALIZER;
  9145. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  9146. if (path != NULL && !mg_stat(fc(ctx), path, &file)) {
  9147. mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  9148. return 0;
  9149. }
  9150. return 1;
  9151. }
  9152. return 0;
  9153. }
  9154. static int
  9155. set_acl_option(struct mg_context *ctx)
  9156. {
  9157. return check_acl(ctx, (uint32_t)0x7f000001UL) != -1;
  9158. }
  9159. static void
  9160. reset_per_request_attributes(struct mg_connection *conn)
  9161. {
  9162. if (!conn) {
  9163. return;
  9164. }
  9165. conn->path_info = NULL;
  9166. conn->num_bytes_sent = conn->consumed_content = 0;
  9167. conn->status_code = -1;
  9168. conn->is_chunked = 0;
  9169. conn->must_close = conn->request_len = conn->throttle = 0;
  9170. conn->request_info.content_length = -1;
  9171. conn->request_info.remote_user = NULL;
  9172. conn->request_info.request_method = NULL;
  9173. conn->request_info.request_uri = NULL;
  9174. conn->request_info.local_uri = NULL;
  9175. conn->request_info.uri = NULL; /* TODO: cleanup uri,
  9176. * local_uri and request_uri */
  9177. conn->request_info.http_version = NULL;
  9178. conn->request_info.num_headers = 0;
  9179. conn->data_len = 0;
  9180. conn->chunk_remainder = 0;
  9181. conn->internal_error = 0;
  9182. }
  9183. static int
  9184. set_sock_timeout(SOCKET sock, int milliseconds)
  9185. {
  9186. int r1, r2;
  9187. #ifdef _WIN32
  9188. /* Windows specific */
  9189. DWORD tv = (DWORD)milliseconds;
  9190. #else
  9191. /* Linux, ... (not Windows) */
  9192. struct timeval tv;
  9193. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  9194. * max. time waiting for the acknowledged of TCP data before the connection
  9195. * will be forcefully closed and ETIMEDOUT is returned to the application.
  9196. * If this option is not set, the default timeout of 20-30 minutes is used.
  9197. */
  9198. /* #define TCP_USER_TIMEOUT (18) */
  9199. #if defined(TCP_USER_TIMEOUT)
  9200. unsigned int uto = (unsigned int)milliseconds;
  9201. setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  9202. #endif
  9203. memset(&tv, 0, sizeof(tv));
  9204. tv.tv_sec = milliseconds / 1000;
  9205. tv.tv_usec = (milliseconds * 1000) % 1000000;
  9206. #endif /* _WIN32 */
  9207. r1 = setsockopt(
  9208. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  9209. r2 = setsockopt(
  9210. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  9211. return r1 || r2;
  9212. }
  9213. static void
  9214. close_socket_gracefully(struct mg_connection *conn)
  9215. {
  9216. #if defined(_WIN32)
  9217. char buf[MG_BUF_LEN];
  9218. int n;
  9219. #endif
  9220. struct linger linger;
  9221. if (!conn) {
  9222. return;
  9223. }
  9224. /* Set linger option to avoid socket hanging out after close. This prevent
  9225. * ephemeral port exhaust problem under high QPS. */
  9226. linger.l_onoff = 1;
  9227. linger.l_linger = 1;
  9228. if (setsockopt(conn->client.sock,
  9229. SOL_SOCKET,
  9230. SO_LINGER,
  9231. (char *)&linger,
  9232. sizeof(linger)) != 0) {
  9233. mg_cry(conn,
  9234. "%s: setsockopt(SOL_SOCKET SO_LINGER) failed: %s",
  9235. __func__,
  9236. strerror(ERRNO));
  9237. }
  9238. /* Send FIN to the client */
  9239. shutdown(conn->client.sock, SHUT_WR);
  9240. set_non_blocking_mode(conn->client.sock);
  9241. #if defined(_WIN32)
  9242. /* Read and discard pending incoming data. If we do not do that and close
  9243. * the socket, the data in the send buffer may be discarded. This
  9244. * behaviour is seen on Windows, when client keeps sending data
  9245. * when server decides to close the connection; then when client
  9246. * does recv() it gets no data back. */
  9247. do {
  9248. n = pull(
  9249. NULL, conn, buf, sizeof(buf), 1E-10 /* TODO: allow 0 as timeout */);
  9250. } while (n > 0);
  9251. #endif
  9252. /* Now we know that our FIN is ACK-ed, safe to close */
  9253. closesocket(conn->client.sock);
  9254. conn->client.sock = INVALID_SOCKET;
  9255. }
  9256. static void
  9257. close_connection(struct mg_connection *conn)
  9258. {
  9259. if (!conn || !conn->ctx) {
  9260. return;
  9261. }
  9262. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  9263. if (conn->lua_websocket_state) {
  9264. lua_websocket_close(conn, conn->lua_websocket_state);
  9265. conn->lua_websocket_state = NULL;
  9266. }
  9267. #endif
  9268. /* call the connection_close callback if assigned */
  9269. if ((conn->ctx->callbacks.connection_close != NULL)
  9270. && (conn->ctx->context_type == 1)) {
  9271. conn->ctx->callbacks.connection_close(conn);
  9272. }
  9273. mg_lock_connection(conn);
  9274. conn->must_close = 1;
  9275. #ifndef NO_SSL
  9276. if (conn->ssl != NULL) {
  9277. /* Run SSL_shutdown twice to ensure completly close SSL connection */
  9278. SSL_shutdown(conn->ssl);
  9279. SSL_free(conn->ssl);
  9280. conn->ssl = NULL;
  9281. }
  9282. #endif
  9283. if (conn->client.sock != INVALID_SOCKET) {
  9284. close_socket_gracefully(conn);
  9285. conn->client.sock = INVALID_SOCKET;
  9286. }
  9287. mg_unlock_connection(conn);
  9288. }
  9289. void
  9290. mg_close_connection(struct mg_connection *conn)
  9291. {
  9292. struct mg_context *client_ctx = NULL;
  9293. unsigned int i;
  9294. if (conn == NULL) {
  9295. return;
  9296. }
  9297. if (conn->ctx->context_type == 2) {
  9298. client_ctx = conn->ctx;
  9299. /* client context: loops must end */
  9300. conn->ctx->stop_flag = 1;
  9301. }
  9302. #ifndef NO_SSL
  9303. if (conn->client_ssl_ctx != NULL) {
  9304. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  9305. }
  9306. #endif
  9307. close_connection(conn);
  9308. if (client_ctx != NULL) {
  9309. /* join worker thread and free context */
  9310. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  9311. if (client_ctx->workerthreadids[i] != 0) {
  9312. mg_join_thread(client_ctx->workerthreadids[i]);
  9313. }
  9314. }
  9315. mg_free(client_ctx->workerthreadids);
  9316. mg_free(client_ctx);
  9317. }
  9318. (void)pthread_mutex_destroy(&conn->mutex);
  9319. mg_free(conn);
  9320. }
  9321. static struct mg_connection *
  9322. mg_connect_client_impl(const struct mg_client_options *client_options,
  9323. int use_ssl,
  9324. char *ebuf,
  9325. size_t ebuf_len)
  9326. {
  9327. static struct mg_context fake_ctx;
  9328. struct mg_connection *conn = NULL;
  9329. SOCKET sock;
  9330. union usa sa;
  9331. if (!connect_socket(&fake_ctx,
  9332. client_options->host,
  9333. client_options->port,
  9334. use_ssl,
  9335. ebuf,
  9336. ebuf_len,
  9337. &sock,
  9338. &sa)) {
  9339. ;
  9340. } else if ((conn = (struct mg_connection *)
  9341. mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) {
  9342. mg_snprintf(NULL,
  9343. NULL, /* No truncation check for ebuf */
  9344. ebuf,
  9345. ebuf_len,
  9346. "calloc(): %s",
  9347. strerror(ERRNO));
  9348. closesocket(sock);
  9349. #ifndef NO_SSL
  9350. } else if (use_ssl
  9351. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  9352. == NULL) {
  9353. mg_snprintf(NULL,
  9354. NULL, /* No truncation check for ebuf */
  9355. ebuf,
  9356. ebuf_len,
  9357. "SSL_CTX_new error");
  9358. closesocket(sock);
  9359. mg_free(conn);
  9360. conn = NULL;
  9361. #endif /* NO_SSL */
  9362. } else {
  9363. #ifdef USE_IPV6
  9364. socklen_t len = (sa.sa.sa_family == AF_INET)
  9365. ? sizeof(conn->client.rsa.sin)
  9366. : sizeof(conn->client.rsa.sin6);
  9367. struct sockaddr *psa =
  9368. (sa.sa.sa_family == AF_INET)
  9369. ? (struct sockaddr *)&(conn->client.rsa.sin)
  9370. : (struct sockaddr *)&(conn->client.rsa.sin6);
  9371. #else
  9372. socklen_t len = sizeof(conn->client.rsa.sin);
  9373. struct sockaddr *psa = (struct sockaddr *)&(conn->client.rsa.sin);
  9374. #endif
  9375. conn->buf_size = MAX_REQUEST_SIZE;
  9376. conn->buf = (char *)(conn + 1);
  9377. conn->ctx = &fake_ctx;
  9378. conn->client.sock = sock;
  9379. conn->client.lsa = sa;
  9380. if (getsockname(sock, psa, &len) != 0) {
  9381. mg_cry(conn,
  9382. "%s: getsockname() failed: %s",
  9383. __func__,
  9384. strerror(ERRNO));
  9385. }
  9386. conn->client.is_ssl = use_ssl ? 1 : 0;
  9387. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  9388. #ifndef NO_SSL
  9389. if (use_ssl) {
  9390. fake_ctx.ssl_ctx = conn->client_ssl_ctx;
  9391. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  9392. SSL_CTX_set_verify call is needed to switch off server
  9393. * certificate checking, which is off by default in OpenSSL and on
  9394. * in yaSSL. */
  9395. // TODO: SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER,
  9396. // verify_ssl_server);
  9397. if (client_options->client_cert) {
  9398. if (!ssl_use_pem_file(&fake_ctx, client_options->client_cert)) {
  9399. mg_snprintf(NULL,
  9400. NULL, /* No truncation check for ebuf */
  9401. ebuf,
  9402. ebuf_len,
  9403. "Can not use SSL client certificate");
  9404. SSL_CTX_free(conn->client_ssl_ctx);
  9405. closesocket(sock);
  9406. mg_free(conn);
  9407. conn = NULL;
  9408. }
  9409. }
  9410. if (client_options->server_cert) {
  9411. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  9412. client_options->server_cert,
  9413. NULL);
  9414. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  9415. } else {
  9416. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  9417. }
  9418. if (!sslize(conn, conn->client_ssl_ctx, SSL_connect)) {
  9419. mg_snprintf(NULL,
  9420. NULL, /* No truncation check for ebuf */
  9421. ebuf,
  9422. ebuf_len,
  9423. "SSL connection error");
  9424. SSL_CTX_free(conn->client_ssl_ctx);
  9425. closesocket(sock);
  9426. mg_free(conn);
  9427. conn = NULL;
  9428. }
  9429. }
  9430. #endif
  9431. }
  9432. return conn;
  9433. }
  9434. CIVETWEB_API struct mg_connection *
  9435. mg_connect_client_secure(const struct mg_client_options *client_options,
  9436. char *error_buffer,
  9437. size_t error_buffer_size)
  9438. {
  9439. return mg_connect_client_impl(client_options,
  9440. 1,
  9441. error_buffer,
  9442. error_buffer_size);
  9443. }
  9444. struct mg_connection *
  9445. mg_connect_client(const char *host,
  9446. int port,
  9447. int use_ssl,
  9448. char *error_buffer,
  9449. size_t error_buffer_size)
  9450. {
  9451. struct mg_client_options opts;
  9452. memset(&opts, 0, sizeof(opts));
  9453. opts.host = host;
  9454. opts.port = port;
  9455. return mg_connect_client_impl(&opts,
  9456. use_ssl,
  9457. error_buffer,
  9458. error_buffer_size);
  9459. }
  9460. static const struct {
  9461. const char *proto;
  9462. size_t proto_len;
  9463. unsigned default_port;
  9464. } abs_uri_protocols[] = {{"http://", 7, 80},
  9465. {"https://", 8, 443},
  9466. {"ws://", 5, 80},
  9467. {"wss://", 6, 443},
  9468. {NULL, 0, 0}};
  9469. /* Check if the uri is valid.
  9470. * return 0 for invalid uri,
  9471. * return 1 for *,
  9472. * return 2 for relative uri,
  9473. * return 3 for absolute uri without port,
  9474. * return 4 for absolute uri with port */
  9475. static int
  9476. get_uri_type(const char *uri)
  9477. {
  9478. int i;
  9479. char *hostend, *portbegin, *portend;
  9480. unsigned long port;
  9481. /* According to the HTTP standard
  9482. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  9483. * URI can be an asterisk (*) or should start with slash (relative uri),
  9484. * or it should start with the protocol (absolute uri). */
  9485. if (uri[0] == '*' && uri[1] == '\0') {
  9486. /* asterisk */
  9487. return 1;
  9488. }
  9489. if (uri[0] == '/') {
  9490. /* relative uri */
  9491. return 2;
  9492. }
  9493. /* It could be an absolute uri: */
  9494. /* This function only checks if the uri is valid, not if it is
  9495. * addressing the current server. So civetweb can also be used
  9496. * as a proxy server. */
  9497. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  9498. if (mg_strncasecmp(uri,
  9499. abs_uri_protocols[i].proto,
  9500. abs_uri_protocols[i].proto_len) == 0) {
  9501. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  9502. if (!hostend) {
  9503. return 0;
  9504. }
  9505. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  9506. if (!portbegin) {
  9507. return 3;
  9508. }
  9509. port = strtoul(portbegin + 1, &portend, 10);
  9510. if ((portend != hostend) || !port || !is_valid_port(port)) {
  9511. return 0;
  9512. }
  9513. return 4;
  9514. }
  9515. }
  9516. return 0;
  9517. }
  9518. /* Return NULL or the relative uri at the current server */
  9519. static const char *
  9520. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  9521. {
  9522. const char *domain;
  9523. size_t domain_len;
  9524. unsigned long port = 0;
  9525. int i;
  9526. char *hostend = NULL;
  9527. char *portbegin, *portend;
  9528. /* DNS is case insensitive, so use case insensitive string compare here */
  9529. domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  9530. if (!domain) {
  9531. return 0;
  9532. }
  9533. domain_len = strlen(domain);
  9534. if (!domain_len) {
  9535. return 0;
  9536. }
  9537. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  9538. if (mg_strncasecmp(uri,
  9539. abs_uri_protocols[i].proto,
  9540. abs_uri_protocols[i].proto_len) == 0) {
  9541. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  9542. if (!hostend) {
  9543. return 0;
  9544. }
  9545. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  9546. if (!portbegin) {
  9547. port = abs_uri_protocols[i].default_port;
  9548. } else {
  9549. port = strtoul(portbegin + 1, &portend, 10);
  9550. if ((portend != hostend) || !port || !is_valid_port(port)) {
  9551. return 0;
  9552. }
  9553. }
  9554. /* protocol found, port set */
  9555. break;
  9556. }
  9557. }
  9558. if (!port) {
  9559. /* port remains 0 if the protocol is not found */
  9560. return 0;
  9561. }
  9562. #if defined(USE_IPV6)
  9563. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  9564. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  9565. return 0;
  9566. }
  9567. } else
  9568. #endif
  9569. {
  9570. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  9571. return 0;
  9572. }
  9573. }
  9574. return hostend;
  9575. }
  9576. static int
  9577. getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  9578. {
  9579. const char *cl;
  9580. if (ebuf_len > 0) {
  9581. ebuf[0] = '\0';
  9582. }
  9583. *err = 0;
  9584. reset_per_request_attributes(conn);
  9585. if (!conn) {
  9586. mg_snprintf(conn,
  9587. NULL, /* No truncation check for ebuf */
  9588. ebuf,
  9589. ebuf_len,
  9590. "%s",
  9591. "Internal error");
  9592. *err = 500;
  9593. return 0;
  9594. }
  9595. /* Set the time the request was received. This value should be used for
  9596. * timeouts. */
  9597. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  9598. conn->request_len =
  9599. read_request(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  9600. /* assert(conn->request_len < 0 || conn->data_len >= conn->request_len); */
  9601. if (conn->request_len >= 0 && conn->data_len < conn->request_len) {
  9602. mg_snprintf(conn,
  9603. NULL, /* No truncation check for ebuf */
  9604. ebuf,
  9605. ebuf_len,
  9606. "%s",
  9607. "Invalid request size");
  9608. *err = 500;
  9609. return 0;
  9610. }
  9611. if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
  9612. mg_snprintf(conn,
  9613. NULL, /* No truncation check for ebuf */
  9614. ebuf,
  9615. ebuf_len,
  9616. "%s",
  9617. "Request Too Large");
  9618. *err = 413;
  9619. return 0;
  9620. } else if (conn->request_len <= 0) {
  9621. if (conn->data_len > 0) {
  9622. mg_snprintf(conn,
  9623. NULL, /* No truncation check for ebuf */
  9624. ebuf,
  9625. ebuf_len,
  9626. "%s",
  9627. "Client sent malformed request");
  9628. *err = 400;
  9629. } else {
  9630. /* Server did not send anything -> just close the connection */
  9631. conn->must_close = 1;
  9632. mg_snprintf(conn,
  9633. NULL, /* No truncation check for ebuf */
  9634. ebuf,
  9635. ebuf_len,
  9636. "%s",
  9637. "Client did not send a request");
  9638. *err = 0;
  9639. }
  9640. return 0;
  9641. } else if (parse_http_message(conn->buf,
  9642. conn->buf_size,
  9643. &conn->request_info) <= 0) {
  9644. mg_snprintf(conn,
  9645. NULL, /* No truncation check for ebuf */
  9646. ebuf,
  9647. ebuf_len,
  9648. "%s",
  9649. "Bad Request");
  9650. *err = 400;
  9651. return 0;
  9652. } else {
  9653. /* Message is a valid request or response */
  9654. if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) {
  9655. /* Request/response has content length set */
  9656. char *endptr = NULL;
  9657. conn->content_len = strtoll(cl, &endptr, 10);
  9658. if (endptr == cl) {
  9659. mg_snprintf(conn,
  9660. NULL, /* No truncation check for ebuf */
  9661. ebuf,
  9662. ebuf_len,
  9663. "%s",
  9664. "Bad Request");
  9665. *err = 411;
  9666. return 0;
  9667. }
  9668. /* Publish the content length back to the request info. */
  9669. conn->request_info.content_length = conn->content_len;
  9670. } else if ((cl = get_header(&conn->request_info, "Transfer-Encoding"))
  9671. != NULL
  9672. && strcmp(cl, "chunked") == 0) {
  9673. conn->is_chunked = 1;
  9674. } else if (!mg_strcasecmp(conn->request_info.request_method, "POST")
  9675. || !mg_strcasecmp(conn->request_info.request_method,
  9676. "PUT")) {
  9677. /* POST or PUT request without content length set */
  9678. conn->content_len = -1;
  9679. } else if (!mg_strncasecmp(conn->request_info.request_method,
  9680. "HTTP/",
  9681. 5)) {
  9682. /* Response without content length set */
  9683. conn->content_len = -1;
  9684. } else {
  9685. /* Other request */
  9686. conn->content_len = 0;
  9687. }
  9688. }
  9689. return 1;
  9690. }
  9691. int
  9692. mg_get_response(struct mg_connection *conn,
  9693. char *ebuf,
  9694. size_t ebuf_len,
  9695. int timeout)
  9696. {
  9697. if (conn) {
  9698. /* Implementation of API function for HTTP clients */
  9699. int err, ret;
  9700. struct mg_context *octx = conn->ctx;
  9701. struct mg_context rctx = *(conn->ctx);
  9702. char txt[32]; /* will not overflow */
  9703. if (timeout >= 0) {
  9704. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  9705. rctx.config[REQUEST_TIMEOUT] = txt;
  9706. set_sock_timeout(conn->client.sock, timeout);
  9707. } else {
  9708. rctx.config[REQUEST_TIMEOUT] = NULL;
  9709. }
  9710. conn->ctx = &rctx;
  9711. ret = getreq(conn, ebuf, ebuf_len, &err);
  9712. conn->ctx = octx;
  9713. /* TODO: 1) uri is deprecated;
  9714. * 2) here, ri.uri is the http response code */
  9715. conn->request_info.uri = conn->request_info.request_uri;
  9716. /* TODO (mid): Define proper return values - maybe return length?
  9717. * For the first test use <0 for error and >0 for OK */
  9718. return (ret == 0) ? -1 : +1;
  9719. }
  9720. return -1;
  9721. }
  9722. struct mg_connection *
  9723. mg_download(const char *host,
  9724. int port,
  9725. int use_ssl,
  9726. char *ebuf,
  9727. size_t ebuf_len,
  9728. const char *fmt,
  9729. ...)
  9730. {
  9731. struct mg_connection *conn;
  9732. va_list ap;
  9733. int i;
  9734. int reqerr;
  9735. va_start(ap, fmt);
  9736. ebuf[0] = '\0';
  9737. /* open a connection */
  9738. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  9739. if (conn != NULL) {
  9740. i = mg_vprintf(conn, fmt, ap);
  9741. if (i <= 0) {
  9742. mg_snprintf(conn,
  9743. NULL, /* No truncation check for ebuf */
  9744. ebuf,
  9745. ebuf_len,
  9746. "%s",
  9747. "Error sending request");
  9748. } else {
  9749. getreq(conn, ebuf, ebuf_len, &reqerr);
  9750. /* TODO: 1) uri is deprecated;
  9751. * 2) here, ri.uri is the http response code */
  9752. conn->request_info.uri = conn->request_info.request_uri;
  9753. }
  9754. }
  9755. /* if an error occured, close the connection */
  9756. if (ebuf[0] != '\0' && conn != NULL) {
  9757. mg_close_connection(conn);
  9758. conn = NULL;
  9759. }
  9760. va_end(ap);
  9761. return conn;
  9762. }
  9763. struct websocket_client_thread_data {
  9764. struct mg_connection *conn;
  9765. mg_websocket_data_handler data_handler;
  9766. mg_websocket_close_handler close_handler;
  9767. void *callback_data;
  9768. };
  9769. #if defined(USE_WEBSOCKET)
  9770. #ifdef _WIN32
  9771. static unsigned __stdcall websocket_client_thread(void *data)
  9772. #else
  9773. static void *
  9774. websocket_client_thread(void *data)
  9775. #endif
  9776. {
  9777. struct websocket_client_thread_data *cdata =
  9778. (struct websocket_client_thread_data *)data;
  9779. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  9780. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  9781. if (cdata->close_handler != NULL) {
  9782. cdata->close_handler(cdata->conn, cdata->callback_data);
  9783. }
  9784. mg_free((void *)cdata);
  9785. #ifdef _WIN32
  9786. return 0;
  9787. #else
  9788. return NULL;
  9789. #endif
  9790. }
  9791. #endif
  9792. struct mg_connection *
  9793. mg_connect_websocket_client(const char *host,
  9794. int port,
  9795. int use_ssl,
  9796. char *error_buffer,
  9797. size_t error_buffer_size,
  9798. const char *path,
  9799. const char *origin,
  9800. mg_websocket_data_handler data_func,
  9801. mg_websocket_close_handler close_func,
  9802. void *user_data)
  9803. {
  9804. struct mg_connection *conn = NULL;
  9805. #if defined(USE_WEBSOCKET)
  9806. struct mg_context *newctx = NULL;
  9807. struct websocket_client_thread_data *thread_data;
  9808. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  9809. static const char *handshake_req;
  9810. if (origin != NULL) {
  9811. handshake_req = "GET %s HTTP/1.1\r\n"
  9812. "Host: %s\r\n"
  9813. "Upgrade: websocket\r\n"
  9814. "Connection: Upgrade\r\n"
  9815. "Sec-WebSocket-Key: %s\r\n"
  9816. "Sec-WebSocket-Version: 13\r\n"
  9817. "Origin: %s\r\n"
  9818. "\r\n";
  9819. } else {
  9820. handshake_req = "GET %s HTTP/1.1\r\n"
  9821. "Host: %s\r\n"
  9822. "Upgrade: websocket\r\n"
  9823. "Connection: Upgrade\r\n"
  9824. "Sec-WebSocket-Key: %s\r\n"
  9825. "Sec-WebSocket-Version: 13\r\n"
  9826. "\r\n";
  9827. }
  9828. /* Establish the client connection and request upgrade */
  9829. conn = mg_download(host,
  9830. port,
  9831. use_ssl,
  9832. error_buffer,
  9833. error_buffer_size,
  9834. handshake_req,
  9835. path,
  9836. host,
  9837. magic,
  9838. origin);
  9839. /* Connection object will be null if something goes wrong */
  9840. if (conn == NULL || (strcmp(conn->request_info.request_uri, "101") != 0)) {
  9841. if (!*error_buffer) {
  9842. /* if there is a connection, but it did not return 101,
  9843. * error_buffer is not yet set */
  9844. mg_snprintf(conn,
  9845. NULL, /* No truncation check for ebuf */
  9846. error_buffer,
  9847. error_buffer_size,
  9848. "Unexpected server reply");
  9849. }
  9850. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  9851. if (conn != NULL) {
  9852. mg_free(conn);
  9853. conn = NULL;
  9854. }
  9855. return conn;
  9856. }
  9857. /* For client connections, mg_context is fake. Since we need to set a
  9858. * callback function, we need to create a copy and modify it. */
  9859. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  9860. memcpy(newctx, conn->ctx, sizeof(struct mg_context));
  9861. newctx->user_data = user_data;
  9862. newctx->context_type = 2; /* client context type */
  9863. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  9864. newctx->workerthreadids =
  9865. (pthread_t *)mg_calloc(newctx->cfg_worker_threads, sizeof(pthread_t));
  9866. conn->ctx = newctx;
  9867. thread_data = (struct websocket_client_thread_data *)
  9868. mg_calloc(sizeof(struct websocket_client_thread_data), 1);
  9869. thread_data->conn = conn;
  9870. thread_data->data_handler = data_func;
  9871. thread_data->close_handler = close_func;
  9872. thread_data->callback_data = NULL;
  9873. /* Start a thread to read the websocket client connection
  9874. * This thread will automatically stop when mg_disconnect is
  9875. * called on the client connection */
  9876. if (mg_start_thread_with_id(websocket_client_thread,
  9877. (void *)thread_data,
  9878. newctx->workerthreadids) != 0) {
  9879. mg_free((void *)thread_data);
  9880. mg_free((void *)newctx->workerthreadids);
  9881. mg_free((void *)newctx);
  9882. mg_free((void *)conn);
  9883. conn = NULL;
  9884. DEBUG_TRACE("%s",
  9885. "Websocket client connect thread could not be started\r\n");
  9886. }
  9887. #else
  9888. /* Appease "unused parameter" warnings */
  9889. (void)host;
  9890. (void)port;
  9891. (void)use_ssl;
  9892. (void)error_buffer;
  9893. (void)error_buffer_size;
  9894. (void)path;
  9895. (void)origin;
  9896. (void)user_data;
  9897. (void)data_func;
  9898. (void)close_func;
  9899. #endif
  9900. return conn;
  9901. }
  9902. static void
  9903. process_new_connection(struct mg_connection *conn)
  9904. {
  9905. if (conn && conn->ctx) {
  9906. struct mg_request_info *ri = &conn->request_info;
  9907. int keep_alive_enabled, keep_alive, discard_len;
  9908. char ebuf[100];
  9909. const char *hostend;
  9910. int reqerr, uri_type;
  9911. keep_alive_enabled =
  9912. !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  9913. /* Important: on new connection, reset the receiving buffer. Credit
  9914. * goes to crule42. */
  9915. conn->data_len = 0;
  9916. do {
  9917. if (!getreq(conn, ebuf, sizeof(ebuf), &reqerr)) {
  9918. /* The request sent by the client could not be understood by
  9919. * the server, or it was incomplete or a timeout. Send an
  9920. * error message and close the connection. */
  9921. if (reqerr > 0) {
  9922. /*assert(ebuf[0] != '\0');*/
  9923. send_http_error(conn, reqerr, "%s", ebuf);
  9924. }
  9925. } else if (strcmp(ri->http_version, "1.0")
  9926. && strcmp(ri->http_version, "1.1")) {
  9927. mg_snprintf(conn,
  9928. NULL, /* No truncation check for ebuf */
  9929. ebuf,
  9930. sizeof(ebuf),
  9931. "Bad HTTP version: [%s]",
  9932. ri->http_version);
  9933. send_http_error(conn, 505, "%s", ebuf);
  9934. }
  9935. if (ebuf[0] == '\0') {
  9936. uri_type = get_uri_type(conn->request_info.request_uri);
  9937. switch (uri_type) {
  9938. case 1:
  9939. /* Asterisk */
  9940. conn->request_info.local_uri = NULL;
  9941. break;
  9942. case 2:
  9943. /* relative uri */
  9944. conn->request_info.local_uri =
  9945. conn->request_info.request_uri;
  9946. break;
  9947. case 3:
  9948. case 4:
  9949. /* absolute uri (with/without port) */
  9950. hostend = get_rel_url_at_current_server(
  9951. conn->request_info.request_uri, conn);
  9952. if (hostend) {
  9953. conn->request_info.local_uri = hostend;
  9954. } else {
  9955. conn->request_info.local_uri = NULL;
  9956. }
  9957. break;
  9958. default:
  9959. mg_snprintf(conn,
  9960. NULL, /* No truncation check for ebuf */
  9961. ebuf,
  9962. sizeof(ebuf),
  9963. "Invalid URI: [%s]",
  9964. ri->request_uri);
  9965. send_http_error(conn, 400, "%s", ebuf);
  9966. break;
  9967. }
  9968. /* TODO: cleanup uri, local_uri and request_uri */
  9969. conn->request_info.uri = conn->request_info.local_uri;
  9970. }
  9971. if (ebuf[0] == '\0') {
  9972. handle_request(conn);
  9973. if (conn->ctx->callbacks.end_request != NULL) {
  9974. conn->ctx->callbacks.end_request(conn, conn->status_code);
  9975. }
  9976. log_access(conn);
  9977. } else {
  9978. conn->must_close = 1;
  9979. }
  9980. if (ri->remote_user != NULL) {
  9981. mg_free((void *)ri->remote_user);
  9982. /* Important! When having connections with and without auth
  9983. * would cause double free and then crash */
  9984. ri->remote_user = NULL;
  9985. }
  9986. /* NOTE(lsm): order is important here. should_keep_alive() call is
  9987. * using parsed request, which will be invalid after memmove's
  9988. * below.
  9989. * Therefore, memorize should_keep_alive() result now for later use
  9990. * in loop exit condition. */
  9991. keep_alive = conn->ctx->stop_flag == 0 && keep_alive_enabled
  9992. && conn->content_len >= 0 && should_keep_alive(conn);
  9993. /* Discard all buffered data for this request */
  9994. discard_len = conn->content_len >= 0 && conn->request_len > 0
  9995. && conn->request_len + conn->content_len
  9996. < (int64_t)conn->data_len
  9997. ? (int)(conn->request_len + conn->content_len)
  9998. : conn->data_len;
  9999. /*assert(discard_len >= 0);*/
  10000. if (discard_len < 0)
  10001. break;
  10002. conn->data_len -= discard_len;
  10003. if (conn->data_len > 0) {
  10004. memmove(conn->buf,
  10005. conn->buf + discard_len,
  10006. (size_t)conn->data_len);
  10007. }
  10008. /* assert(conn->data_len >= 0); */
  10009. /* assert(conn->data_len <= conn->buf_size); */
  10010. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  10011. break;
  10012. }
  10013. } while (keep_alive);
  10014. }
  10015. }
  10016. /* Worker threads take accepted socket from the queue */
  10017. static int
  10018. consume_socket(struct mg_context *ctx, struct socket *sp)
  10019. {
  10020. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  10021. if (!ctx) {
  10022. return 0;
  10023. }
  10024. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10025. DEBUG_TRACE("%s", "going idle");
  10026. /* If the queue is empty, wait. We're idle at this point. */
  10027. while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
  10028. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  10029. }
  10030. /* If we're stopping, sq_head may be equal to sq_tail. */
  10031. if (ctx->sq_head > ctx->sq_tail) {
  10032. /* Copy socket from the queue and increment tail */
  10033. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  10034. ctx->sq_tail++;
  10035. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  10036. /* Wrap pointers if needed */
  10037. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  10038. ctx->sq_tail -= QUEUE_SIZE(ctx);
  10039. ctx->sq_head -= QUEUE_SIZE(ctx);
  10040. }
  10041. }
  10042. (void)pthread_cond_signal(&ctx->sq_empty);
  10043. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10044. return !ctx->stop_flag;
  10045. #undef QUEUE_SIZE
  10046. }
  10047. static void *
  10048. worker_thread_run(void *thread_func_param)
  10049. {
  10050. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  10051. struct mg_connection *conn;
  10052. struct mg_workerTLS tls;
  10053. #if defined(MG_LEGACY_INTERFACE)
  10054. uint32_t addr;
  10055. #endif
  10056. mg_set_thread_name("worker");
  10057. tls.is_master = 0;
  10058. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  10059. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10060. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  10061. #endif
  10062. conn =
  10063. (struct mg_connection *)mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE);
  10064. if (conn == NULL) {
  10065. mg_cry(fc(ctx), "%s", "Cannot create new connection struct, OOM");
  10066. } else {
  10067. pthread_setspecific(sTlsKey, &tls);
  10068. conn->buf_size = MAX_REQUEST_SIZE;
  10069. conn->buf = (char *)(conn + 1);
  10070. conn->ctx = ctx;
  10071. conn->request_info.user_data = ctx->user_data;
  10072. /* Allocate a mutex for this connection to allow communication both
  10073. * within the request handler and from elsewhere in the application */
  10074. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  10075. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  10076. * signal sq_empty condvar to wake up the master waiting in
  10077. * produce_socket() */
  10078. while (consume_socket(ctx, &conn->client)) {
  10079. conn->conn_birth_time = time(NULL);
  10080. /* Fill in IP, port info early so even if SSL setup below fails,
  10081. * error handler would have the corresponding info.
  10082. * Thanks to Johannes Winkelmann for the patch.
  10083. */
  10084. #if defined(USE_IPV6)
  10085. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  10086. conn->request_info.remote_port =
  10087. ntohs(conn->client.rsa.sin6.sin6_port);
  10088. } else
  10089. #endif
  10090. {
  10091. conn->request_info.remote_port =
  10092. ntohs(conn->client.rsa.sin.sin_port);
  10093. }
  10094. sockaddr_to_string(conn->request_info.remote_addr,
  10095. sizeof(conn->request_info.remote_addr),
  10096. &conn->client.rsa);
  10097. #if defined(MG_LEGACY_INTERFACE)
  10098. /* This legacy interface only works for the IPv4 case */
  10099. addr = ntohl(conn->client.rsa.sin.sin_addr.s_addr);
  10100. memcpy(&conn->request_info.remote_ip, &addr, 4);
  10101. #endif
  10102. conn->request_info.is_ssl = conn->client.is_ssl;
  10103. if (!conn->client.is_ssl
  10104. #ifndef NO_SSL
  10105. || sslize(conn, conn->ctx->ssl_ctx, SSL_accept)
  10106. #endif
  10107. ) {
  10108. process_new_connection(conn);
  10109. }
  10110. close_connection(conn);
  10111. }
  10112. }
  10113. /* Signal master that we're done with connection and exiting */
  10114. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10115. ctx->running_worker_threads--;
  10116. (void)pthread_cond_signal(&ctx->thread_cond);
  10117. /* assert(ctx->running_worker_threads >= 0); */
  10118. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10119. pthread_setspecific(sTlsKey, NULL);
  10120. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10121. CloseHandle(tls.pthread_cond_helper_mutex);
  10122. #endif
  10123. mg_free(conn);
  10124. DEBUG_TRACE("%s", "exiting");
  10125. return NULL;
  10126. }
  10127. /* Threads have different return types on Windows and Unix. */
  10128. #ifdef _WIN32
  10129. static unsigned __stdcall worker_thread(void *thread_func_param)
  10130. {
  10131. worker_thread_run(thread_func_param);
  10132. return 0;
  10133. }
  10134. #else
  10135. static void *
  10136. worker_thread(void *thread_func_param)
  10137. {
  10138. worker_thread_run(thread_func_param);
  10139. return NULL;
  10140. }
  10141. #endif /* _WIN32 */
  10142. /* Master thread adds accepted socket to a queue */
  10143. static void
  10144. produce_socket(struct mg_context *ctx, const struct socket *sp)
  10145. {
  10146. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  10147. if (!ctx) {
  10148. return;
  10149. }
  10150. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10151. /* If the queue is full, wait */
  10152. while (ctx->stop_flag == 0
  10153. && ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx)) {
  10154. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  10155. }
  10156. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  10157. /* Copy socket to the queue and increment head */
  10158. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  10159. ctx->sq_head++;
  10160. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  10161. }
  10162. (void)pthread_cond_signal(&ctx->sq_full);
  10163. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10164. #undef QUEUE_SIZE
  10165. }
  10166. static void
  10167. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  10168. {
  10169. struct socket so;
  10170. char src_addr[IP_ADDR_STR_LEN];
  10171. socklen_t len = sizeof(so.rsa);
  10172. int on = 1;
  10173. int timeout;
  10174. if (!listener) {
  10175. return;
  10176. }
  10177. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  10178. == INVALID_SOCKET) {
  10179. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  10180. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  10181. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  10182. closesocket(so.sock);
  10183. so.sock = INVALID_SOCKET;
  10184. } else {
  10185. /* Put so socket structure into the queue */
  10186. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  10187. set_close_on_exec(so.sock, fc(ctx));
  10188. so.is_ssl = listener->is_ssl;
  10189. so.ssl_redir = listener->ssl_redir;
  10190. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  10191. mg_cry(fc(ctx),
  10192. "%s: getsockname() failed: %s",
  10193. __func__,
  10194. strerror(ERRNO));
  10195. }
  10196. /* Set TCP keep-alive. This is needed because if HTTP-level keep-alive
  10197. * is enabled, and client resets the connection, server won't get
  10198. * TCP FIN or RST and will keep the connection open forever. With TCP
  10199. * keep-alive, next keep-alive handshake will figure out that the
  10200. * client is down and will close the server end.
  10201. * Thanks to Igor Klopov who suggested the patch. */
  10202. if (setsockopt(so.sock,
  10203. SOL_SOCKET,
  10204. SO_KEEPALIVE,
  10205. (SOCK_OPT_TYPE)&on,
  10206. sizeof(on)) != 0) {
  10207. mg_cry(fc(ctx),
  10208. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  10209. __func__,
  10210. strerror(ERRNO));
  10211. }
  10212. if (ctx && ctx->config[REQUEST_TIMEOUT]) {
  10213. timeout = atoi(ctx->config[REQUEST_TIMEOUT]);
  10214. } else {
  10215. timeout = -1;
  10216. }
  10217. /* Set socket timeout to the given value, but not more than a
  10218. * a certain limit (SOCKET_TIMEOUT_QUANTUM, default 10 seconds),
  10219. * so the server can exit after that time if requested. */
  10220. if ((timeout > 0) && (timeout < SOCKET_TIMEOUT_QUANTUM)) {
  10221. set_sock_timeout(so.sock, timeout);
  10222. } else {
  10223. set_sock_timeout(so.sock, SOCKET_TIMEOUT_QUANTUM);
  10224. }
  10225. produce_socket(ctx, &so);
  10226. }
  10227. }
  10228. static void
  10229. master_thread_run(void *thread_func_param)
  10230. {
  10231. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  10232. struct mg_workerTLS tls;
  10233. struct pollfd *pfd;
  10234. unsigned int i;
  10235. unsigned int workerthreadcount;
  10236. if (!ctx) {
  10237. return;
  10238. }
  10239. mg_set_thread_name("master");
  10240. /* Increase priority of the master thread */
  10241. #if defined(_WIN32)
  10242. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  10243. #elif defined(USE_MASTER_THREAD_PRIORITY)
  10244. int min_prio = sched_get_priority_min(SCHED_RR);
  10245. int max_prio = sched_get_priority_max(SCHED_RR);
  10246. if ((min_prio >= 0) && (max_prio >= 0)
  10247. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  10248. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  10249. struct sched_param sched_param = {0};
  10250. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  10251. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  10252. }
  10253. #endif
  10254. /* Initialize thread local storage */
  10255. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10256. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  10257. #endif
  10258. tls.is_master = 1;
  10259. pthread_setspecific(sTlsKey, &tls);
  10260. /* Server starts *now* */
  10261. ctx->start_time = time(NULL);
  10262. /* Allocate memory for the listening sockets, and start the server */
  10263. pfd =
  10264. (struct pollfd *)mg_calloc(ctx->num_listening_sockets, sizeof(pfd[0]));
  10265. while (pfd != NULL && ctx->stop_flag == 0) {
  10266. for (i = 0; i < ctx->num_listening_sockets; i++) {
  10267. pfd[i].fd = ctx->listening_sockets[i].sock;
  10268. pfd[i].events = POLLIN;
  10269. }
  10270. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  10271. for (i = 0; i < ctx->num_listening_sockets; i++) {
  10272. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  10273. * successful poll, and POLLIN is defined as
  10274. * (POLLRDNORM | POLLRDBAND)
  10275. * Therefore, we're checking pfd[i].revents & POLLIN, not
  10276. * pfd[i].revents == POLLIN. */
  10277. if (ctx->stop_flag == 0 && (pfd[i].revents & POLLIN)) {
  10278. accept_new_connection(&ctx->listening_sockets[i], ctx);
  10279. }
  10280. }
  10281. }
  10282. }
  10283. mg_free(pfd);
  10284. DEBUG_TRACE("%s", "stopping workers");
  10285. /* Stop signal received: somebody called mg_stop. Quit. */
  10286. close_all_listening_sockets(ctx);
  10287. /* Wakeup workers that are waiting for connections to handle. */
  10288. pthread_cond_broadcast(&ctx->sq_full);
  10289. /* Wait until all threads finish */
  10290. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10291. while (ctx->running_worker_threads > 0) {
  10292. (void)pthread_cond_wait(&ctx->thread_cond, &ctx->thread_mutex);
  10293. }
  10294. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10295. /* Join all worker threads to avoid leaking threads. */
  10296. workerthreadcount = ctx->cfg_worker_threads;
  10297. for (i = 0; i < workerthreadcount; i++) {
  10298. if (ctx->workerthreadids[i] != 0) {
  10299. mg_join_thread(ctx->workerthreadids[i]);
  10300. }
  10301. }
  10302. #if !defined(NO_SSL)
  10303. if (ctx->ssl_ctx != NULL) {
  10304. uninitialize_ssl(ctx);
  10305. }
  10306. #endif
  10307. DEBUG_TRACE("%s", "exiting");
  10308. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10309. CloseHandle(tls.pthread_cond_helper_mutex);
  10310. #endif
  10311. pthread_setspecific(sTlsKey, NULL);
  10312. /* Signal mg_stop() that we're done.
  10313. * WARNING: This must be the very last thing this
  10314. * thread does, as ctx becomes invalid after this line. */
  10315. ctx->stop_flag = 2;
  10316. }
  10317. /* Threads have different return types on Windows and Unix. */
  10318. #ifdef _WIN32
  10319. static unsigned __stdcall master_thread(void *thread_func_param)
  10320. {
  10321. master_thread_run(thread_func_param);
  10322. return 0;
  10323. }
  10324. #else
  10325. static void *
  10326. master_thread(void *thread_func_param)
  10327. {
  10328. master_thread_run(thread_func_param);
  10329. return NULL;
  10330. }
  10331. #endif /* _WIN32 */
  10332. static void
  10333. free_context(struct mg_context *ctx)
  10334. {
  10335. int i;
  10336. struct mg_request_handler_info *tmp_rh;
  10337. if (ctx == NULL) {
  10338. return;
  10339. }
  10340. if (ctx->callbacks.exit_context) {
  10341. ctx->callbacks.exit_context(ctx);
  10342. }
  10343. /* All threads exited, no sync is needed. Destroy thread mutex and condvars
  10344. */
  10345. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  10346. (void)pthread_cond_destroy(&ctx->thread_cond);
  10347. (void)pthread_cond_destroy(&ctx->sq_empty);
  10348. (void)pthread_cond_destroy(&ctx->sq_full);
  10349. /* Destroy other context global data structures mutex */
  10350. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  10351. #if defined(USE_TIMERS)
  10352. timers_exit(ctx);
  10353. #endif
  10354. /* Deallocate config parameters */
  10355. for (i = 0; i < NUM_OPTIONS; i++) {
  10356. if (ctx->config[i] != NULL) {
  10357. #if defined(_MSC_VER)
  10358. #pragma warning(suppress : 6001)
  10359. #endif
  10360. mg_free(ctx->config[i]);
  10361. }
  10362. }
  10363. /* Deallocate request handlers */
  10364. while (ctx->request_handlers) {
  10365. tmp_rh = ctx->request_handlers;
  10366. ctx->request_handlers = tmp_rh->next;
  10367. mg_free(tmp_rh->uri);
  10368. mg_free(tmp_rh);
  10369. }
  10370. #ifndef NO_SSL
  10371. /* Deallocate SSL context */
  10372. if (ctx->ssl_ctx != NULL) {
  10373. SSL_CTX_free(ctx->ssl_ctx);
  10374. }
  10375. if (ssl_mutexes != NULL) {
  10376. mg_free(ssl_mutexes);
  10377. ssl_mutexes = NULL;
  10378. }
  10379. #endif /* !NO_SSL */
  10380. /* Deallocate worker thread ID array */
  10381. if (ctx->workerthreadids != NULL) {
  10382. mg_free(ctx->workerthreadids);
  10383. }
  10384. /* Deallocate the tls variable */
  10385. if (mg_atomic_dec(&sTlsInit) == 0) {
  10386. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10387. DeleteCriticalSection(&global_log_file_lock);
  10388. #endif /* _WIN32 && !__SYMBIAN32__ */
  10389. #if !defined(_WIN32)
  10390. pthread_mutexattr_destroy(&pthread_mutex_attr);
  10391. #endif
  10392. pthread_key_delete(sTlsKey);
  10393. }
  10394. /* deallocate system name string */
  10395. mg_free(ctx->systemName);
  10396. /* Deallocate context itself */
  10397. mg_free(ctx);
  10398. }
  10399. void
  10400. mg_stop(struct mg_context *ctx)
  10401. {
  10402. pthread_t mt;
  10403. if (!ctx) {
  10404. return;
  10405. }
  10406. /* We don't use a lock here. Calling mg_stop with the same ctx from
  10407. * two threads is not allowed. */
  10408. mt = ctx->masterthreadid;
  10409. if (mt == 0) {
  10410. return;
  10411. }
  10412. ctx->masterthreadid = 0;
  10413. ctx->stop_flag = 1;
  10414. /* Wait until mg_fini() stops */
  10415. while (ctx->stop_flag != 2) {
  10416. (void)mg_sleep(10);
  10417. }
  10418. mg_join_thread(mt);
  10419. free_context(ctx);
  10420. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10421. (void)WSACleanup();
  10422. #endif /* _WIN32 && !__SYMBIAN32__ */
  10423. }
  10424. static void
  10425. get_system_name(char **sysName)
  10426. {
  10427. #if defined(_WIN32)
  10428. #if !defined(__SYMBIAN32__)
  10429. char name[128];
  10430. DWORD dwVersion = 0;
  10431. DWORD dwMajorVersion = 0;
  10432. DWORD dwMinorVersion = 0;
  10433. DWORD dwBuild = 0;
  10434. #ifdef _MSC_VER
  10435. #pragma warning(push)
  10436. // GetVersion was declared deprecated
  10437. #pragma warning(disable : 4996)
  10438. #endif
  10439. dwVersion = GetVersion();
  10440. #ifdef _MSC_VER
  10441. #pragma warning(pop)
  10442. #endif
  10443. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  10444. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  10445. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  10446. (void)dwBuild;
  10447. sprintf(name,
  10448. "Windows %u.%u",
  10449. (unsigned)dwMajorVersion,
  10450. (unsigned)dwMinorVersion);
  10451. *sysName = mg_strdup(name);
  10452. #else
  10453. *sysName = mg_strdup("Symbian");
  10454. #endif
  10455. #else
  10456. struct utsname name;
  10457. memset(&name, 0, sizeof(name));
  10458. uname(&name);
  10459. *sysName = mg_strdup(name.sysname);
  10460. #endif
  10461. }
  10462. struct mg_context *
  10463. mg_start(const struct mg_callbacks *callbacks,
  10464. void *user_data,
  10465. const char **options)
  10466. {
  10467. struct mg_context *ctx;
  10468. const char *name, *value, *default_value;
  10469. int idx, ok, workerthreadcount;
  10470. unsigned int i;
  10471. void (*exit_callback)(const struct mg_context *ctx) = 0;
  10472. struct mg_workerTLS tls;
  10473. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10474. WSADATA data;
  10475. WSAStartup(MAKEWORD(2, 2), &data);
  10476. #endif /* _WIN32 && !__SYMBIAN32__ */
  10477. /* Allocate context and initialize reasonable general case defaults. */
  10478. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  10479. return NULL;
  10480. }
  10481. /* Random number generator will initialize at the first call */
  10482. ctx->auth_nonce_mask =
  10483. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  10484. if (mg_atomic_inc(&sTlsInit) == 1) {
  10485. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10486. InitializeCriticalSection(&global_log_file_lock);
  10487. #endif /* _WIN32 && !__SYMBIAN32__ */
  10488. #if !defined(_WIN32)
  10489. pthread_mutexattr_init(&pthread_mutex_attr);
  10490. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  10491. #endif
  10492. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  10493. /* Fatal error - abort start. However, this situation should never
  10494. * occur in practice. */
  10495. mg_atomic_dec(&sTlsInit);
  10496. mg_cry(fc(ctx), "Cannot initialize thread local storage");
  10497. mg_free(ctx);
  10498. return NULL;
  10499. }
  10500. } else {
  10501. /* TODO (low): istead of sleeping, check if sTlsKey is already
  10502. * initialized. */
  10503. mg_sleep(1);
  10504. }
  10505. tls.is_master = -1;
  10506. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  10507. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10508. tls.pthread_cond_helper_mutex = NULL;
  10509. #endif
  10510. pthread_setspecific(sTlsKey, &tls);
  10511. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr);
  10512. ok &= 0 == pthread_cond_init(&ctx->thread_cond, NULL);
  10513. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  10514. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  10515. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr);
  10516. if (!ok) {
  10517. /* Fatal error - abort start. However, this situation should never
  10518. * occur in practice. */
  10519. mg_cry(fc(ctx), "Cannot initialize thread synchronization objects");
  10520. mg_free(ctx);
  10521. pthread_setspecific(sTlsKey, NULL);
  10522. return NULL;
  10523. }
  10524. if (callbacks) {
  10525. ctx->callbacks = *callbacks;
  10526. exit_callback = callbacks->exit_context;
  10527. ctx->callbacks.exit_context = 0;
  10528. }
  10529. ctx->user_data = user_data;
  10530. ctx->request_handlers = NULL;
  10531. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  10532. ctx->shared_lua_websockets = 0;
  10533. #endif
  10534. while (options && (name = *options++) != NULL) {
  10535. if ((idx = get_option_index(name)) == -1) {
  10536. mg_cry(fc(ctx), "Invalid option: %s", name);
  10537. free_context(ctx);
  10538. pthread_setspecific(sTlsKey, NULL);
  10539. return NULL;
  10540. } else if ((value = *options++) == NULL) {
  10541. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  10542. free_context(ctx);
  10543. pthread_setspecific(sTlsKey, NULL);
  10544. return NULL;
  10545. }
  10546. if (ctx->config[idx] != NULL) {
  10547. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  10548. mg_free(ctx->config[idx]);
  10549. }
  10550. ctx->config[idx] = mg_strdup(value);
  10551. DEBUG_TRACE("[%s] -> [%s]", name, value);
  10552. }
  10553. /* Set default value if needed */
  10554. for (i = 0; config_options[i].name != NULL; i++) {
  10555. default_value = config_options[i].default_value;
  10556. if (ctx->config[i] == NULL && default_value != NULL) {
  10557. ctx->config[i] = mg_strdup(default_value);
  10558. }
  10559. }
  10560. #if defined(NO_FILES)
  10561. if (ctx->config[DOCUMENT_ROOT] != NULL) {
  10562. mg_cry(fc(ctx), "%s", "Document root must not be set");
  10563. free_context(ctx);
  10564. pthread_setspecific(sTlsKey, NULL);
  10565. return NULL;
  10566. }
  10567. #endif
  10568. get_system_name(&ctx->systemName);
  10569. /* NOTE(lsm): order is important here. SSL certificates must
  10570. * be initialized before listening ports. UID must be set last. */
  10571. if (!set_gpass_option(ctx) ||
  10572. #if !defined(NO_SSL)
  10573. !set_ssl_option(ctx) ||
  10574. #endif
  10575. !set_ports_option(ctx) ||
  10576. #if !defined(_WIN32)
  10577. !set_uid_option(ctx) ||
  10578. #endif
  10579. !set_acl_option(ctx)) {
  10580. free_context(ctx);
  10581. pthread_setspecific(sTlsKey, NULL);
  10582. return NULL;
  10583. }
  10584. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  10585. /* Ignore SIGPIPE signal, so if browser cancels the request, it
  10586. * won't kill the whole process. */
  10587. (void)signal(SIGPIPE, SIG_IGN);
  10588. #endif /* !_WIN32 && !__SYMBIAN32__ */
  10589. workerthreadcount = atoi(ctx->config[NUM_THREADS]);
  10590. if (workerthreadcount > MAX_WORKER_THREADS) {
  10591. mg_cry(fc(ctx), "Too many worker threads");
  10592. free_context(ctx);
  10593. pthread_setspecific(sTlsKey, NULL);
  10594. return NULL;
  10595. }
  10596. if (workerthreadcount > 0) {
  10597. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  10598. ctx->workerthreadids =
  10599. (pthread_t *)mg_calloc(ctx->cfg_worker_threads, sizeof(pthread_t));
  10600. if (ctx->workerthreadids == NULL) {
  10601. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  10602. free_context(ctx);
  10603. pthread_setspecific(sTlsKey, NULL);
  10604. return NULL;
  10605. }
  10606. }
  10607. #if defined(USE_TIMERS)
  10608. if (timers_init(ctx) != 0) {
  10609. mg_cry(fc(ctx), "Error creating timers");
  10610. free_context(ctx);
  10611. pthread_setspecific(sTlsKey, NULL);
  10612. return NULL;
  10613. }
  10614. #endif
  10615. /* Context has been created - init user libraries */
  10616. if (ctx->callbacks.init_context) {
  10617. ctx->callbacks.init_context(ctx);
  10618. }
  10619. ctx->callbacks.exit_context = exit_callback;
  10620. ctx->context_type = 1; /* server context */
  10621. /* Start master (listening) thread */
  10622. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  10623. /* Start worker threads */
  10624. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  10625. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10626. ctx->running_worker_threads++;
  10627. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10628. if (mg_start_thread_with_id(worker_thread,
  10629. ctx,
  10630. &ctx->workerthreadids[i]) != 0) {
  10631. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10632. ctx->running_worker_threads--;
  10633. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10634. if (i > 0) {
  10635. mg_cry(fc(ctx),
  10636. "Cannot start worker thread %i: error %ld",
  10637. i + 1,
  10638. (long)ERRNO);
  10639. } else {
  10640. mg_cry(fc(ctx),
  10641. "Cannot create threads: error %ld",
  10642. (long)ERRNO);
  10643. free_context(ctx);
  10644. pthread_setspecific(sTlsKey, NULL);
  10645. return NULL;
  10646. }
  10647. break;
  10648. }
  10649. }
  10650. pthread_setspecific(sTlsKey, NULL);
  10651. return ctx;
  10652. }
  10653. /* Feature check API function */
  10654. unsigned
  10655. mg_check_feature(unsigned feature)
  10656. {
  10657. static const unsigned feature_set = 0
  10658. /* Set bits for available features according to API documentation.
  10659. * This bit mask is created at compile time, according to the active
  10660. * preprocessor defines. It is a single const value at runtime. */
  10661. #if !defined(NO_FILES)
  10662. | 1
  10663. #endif
  10664. #if !defined(NO_SSL)
  10665. | 2
  10666. #endif
  10667. #if !defined(NO_CGI)
  10668. | 4
  10669. #endif
  10670. #if defined(USE_IPV6)
  10671. | 8
  10672. #endif
  10673. #if defined(USE_WEBSOCKET)
  10674. | 16
  10675. #endif
  10676. #if defined(USE_LUA)
  10677. | 32
  10678. #endif
  10679. #if defined(USE_DUKTAPE)
  10680. | 64
  10681. #endif
  10682. /* Set some extra bits not defined in the API documentation.
  10683. * These bits may change without further notice. */
  10684. #if defined(MG_LEGACY_INTERFACE)
  10685. | 128
  10686. #endif
  10687. #if defined(MEMORY_DEBUGGING)
  10688. | 256
  10689. #endif
  10690. #if defined(USE_TIMERS)
  10691. | 512
  10692. #endif
  10693. #if !defined(NO_NONCE_CHECK)
  10694. | 1024
  10695. #endif
  10696. #if !defined(NO_POPEN)
  10697. | 2048
  10698. #endif
  10699. ;
  10700. return (feature & feature_set);
  10701. }