civetweb.c 356 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776
  1. /* Copyright (c) 2013-2016 the Civetweb developers
  2. * Copyright (c) 2004-2013 Sergey Lyubka
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. * THE SOFTWARE.
  21. */
  22. #if defined(_WIN32)
  23. #if !defined(_CRT_SECURE_NO_WARNINGS)
  24. #define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */
  25. #endif
  26. #ifndef _WIN32_WINNT /* defined for tdm-gcc so we can use getnameinfo */
  27. #define _WIN32_WINNT 0x0501
  28. #endif
  29. #else
  30. #if defined(__GNUC__) && !defined(_GNU_SOURCE)
  31. #define _GNU_SOURCE /* for setgroups() */
  32. #endif
  33. #if defined(__linux__) && !defined(_XOPEN_SOURCE)
  34. #define _XOPEN_SOURCE 600 /* For flockfile() on Linux */
  35. #endif
  36. #ifndef _LARGEFILE_SOURCE
  37. #define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
  38. #endif
  39. #ifndef _FILE_OFFSET_BITS
  40. #define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
  41. #endif
  42. #ifndef __STDC_FORMAT_MACROS
  43. #define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
  44. #endif
  45. #ifndef __STDC_LIMIT_MACROS
  46. #define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
  47. #endif
  48. #ifdef __sun
  49. #define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */
  50. #define __inline inline /* not recognized on older compiler versions */
  51. #endif
  52. #endif
  53. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  54. #define USE_TIMERS
  55. #endif
  56. #if defined(_MSC_VER)
  57. /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
  58. #pragma warning(disable : 4306)
  59. /* conditional expression is constant: introduced by FD_SET(..) */
  60. #pragma warning(disable : 4127)
  61. /* non-constant aggregate initializer: issued due to missing C99 support */
  62. #pragma warning(disable : 4204)
  63. /* padding added after data member */
  64. #pragma warning(disable : 4820)
  65. /* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
  66. #pragma warning(disable : 4668)
  67. /* no function prototype given: converting '()' to '(void)' */
  68. #pragma warning(disable : 4255)
  69. /* function has been selected for automatic inline expansion */
  70. #pragma warning(disable : 4711)
  71. #endif
  72. /* This code uses static_assert to check some conditions.
  73. * Unfortunately some compilers still do not support it, so we have a
  74. * replacement function here. */
  75. #if defined(_MSC_VER) && (_MSC_VER >= 1600)
  76. #define mg_static_assert static_assert
  77. #elif defined(__cplusplus) && (__cplusplus >= 201103L)
  78. #define mg_static_assert static_assert
  79. #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)
  80. #define mg_static_assert _Static_assert
  81. #else
  82. char static_assert_replacement[1];
  83. #define mg_static_assert(cond, txt) \
  84. extern char static_assert_replacement[(cond) ? 1 : -1]
  85. #endif
  86. mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
  87. "int data type size check");
  88. mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
  89. "pointer data type size check");
  90. mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
  91. /* DTL -- including winsock2.h works better if lean and mean */
  92. #ifndef WIN32_LEAN_AND_MEAN
  93. #define WIN32_LEAN_AND_MEAN
  94. #endif
  95. #if defined(__SYMBIAN32__)
  96. #define NO_SSL /* SSL is not supported */
  97. #define NO_CGI /* CGI is not supported */
  98. #define PATH_MAX FILENAME_MAX
  99. #endif /* __SYMBIAN32__ */
  100. /* Include the header file here, so the CivetWeb interface is defined for the
  101. * entire implementation, including the following forward definitions. */
  102. #include "civetweb.h"
  103. #ifndef IGNORE_UNUSED_RESULT
  104. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  105. #endif
  106. #ifndef _WIN32_WCE /* Some ANSI #includes are not available on Windows CE */
  107. #include <sys/types.h>
  108. #include <sys/stat.h>
  109. #include <errno.h>
  110. #include <signal.h>
  111. #include <fcntl.h>
  112. #endif /* !_WIN32_WCE */
  113. #ifdef __MACH__
  114. #define CLOCK_MONOTONIC (1)
  115. #define CLOCK_REALTIME (2)
  116. #include <sys/time.h>
  117. #include <mach/clock.h>
  118. #include <mach/mach.h>
  119. #include <mach/mach_time.h>
  120. #include <assert.h>
  121. /* clock_gettime is not implemented on OSX */
  122. int clock_gettime(int clk_id, struct timespec *t);
  123. int
  124. clock_gettime(int clk_id, struct timespec *t)
  125. {
  126. memset(t, 0, sizeof(*t));
  127. if (clk_id == CLOCK_REALTIME) {
  128. struct timeval now;
  129. int rv = gettimeofday(&now, NULL);
  130. if (rv) {
  131. return rv;
  132. }
  133. t->tv_sec = now.tv_sec;
  134. t->tv_nsec = now.tv_usec * 1000;
  135. return 0;
  136. } else if (clk_id == CLOCK_MONOTONIC) {
  137. static uint64_t clock_start_time = 0;
  138. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  139. uint64_t now = mach_absolute_time();
  140. if (clock_start_time == 0) {
  141. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  142. #if defined(DEBUG)
  143. assert(mach_status == KERN_SUCCESS);
  144. #else
  145. /* appease "unused variable" warning for release builds */
  146. (void)mach_status;
  147. #endif
  148. clock_start_time = now;
  149. }
  150. now = (uint64_t)((double)(now - clock_start_time)
  151. * (double)timebase_ifo.numer
  152. / (double)timebase_ifo.denom);
  153. t->tv_sec = now / 1000000000;
  154. t->tv_nsec = now % 1000000000;
  155. return 0;
  156. }
  157. return -1; /* EINVAL - Clock ID is unknown */
  158. }
  159. #endif
  160. #include <time.h>
  161. #include <stdlib.h>
  162. #include <stdarg.h>
  163. #include <assert.h>
  164. #include <string.h>
  165. #include <ctype.h>
  166. #include <limits.h>
  167. #include <stddef.h>
  168. #include <stdio.h>
  169. #ifndef MAX_WORKER_THREADS
  170. #define MAX_WORKER_THREADS (1024 * 64)
  171. #endif
  172. #define SHUTDOWN_RD (0)
  173. #define SHUTDOWN_WR (1)
  174. #define SHUTDOWN_BOTH (2)
  175. mg_static_assert(MAX_WORKER_THREADS >= 1,
  176. "worker threads must be a positive number");
  177. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  178. "size_t data type size check");
  179. #if defined(_WIN32) \
  180. && !defined(__SYMBIAN32__) /* WINDOWS / UNIX include block */
  181. #include <windows.h>
  182. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  183. #include <ws2tcpip.h>
  184. typedef const char *SOCK_OPT_TYPE;
  185. #if !defined(PATH_MAX)
  186. #define PATH_MAX (MAX_PATH)
  187. #endif
  188. #if !defined(PATH_MAX)
  189. #define PATH_MAX (4096)
  190. #endif
  191. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  192. #ifndef _IN_PORT_T
  193. #ifndef in_port_t
  194. #define in_port_t u_short
  195. #endif
  196. #endif
  197. #ifndef _WIN32_WCE
  198. #include <process.h>
  199. #include <direct.h>
  200. #include <io.h>
  201. #else /* _WIN32_WCE */
  202. #define NO_CGI /* WinCE has no pipes */
  203. #define NO_POPEN /* WinCE has no popen */
  204. typedef long off_t;
  205. #define errno ((int)(GetLastError()))
  206. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  207. #endif /* _WIN32_WCE */
  208. #define MAKEUQUAD(lo, hi) \
  209. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  210. #define RATE_DIFF (10000000) /* 100 nsecs */
  211. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  212. #define SYS2UNIX_TIME(lo, hi) \
  213. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  214. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  215. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  216. * Also use _strtoui64 on modern M$ compilers */
  217. #if defined(_MSC_VER)
  218. #if (_MSC_VER < 1300)
  219. #define STRX(x) #x
  220. #define STR(x) STRX(x)
  221. #define __func__ __FILE__ ":" STR(__LINE__)
  222. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  223. #define strtoll(x, y, z) (_atoi64(x))
  224. #else
  225. #define __func__ __FUNCTION__
  226. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  227. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  228. #endif
  229. #endif /* _MSC_VER */
  230. #define ERRNO ((int)(GetLastError()))
  231. #define NO_SOCKLEN_T
  232. #if defined(_WIN64) || defined(__MINGW64__)
  233. #define SSL_LIB "ssleay64.dll"
  234. #define CRYPTO_LIB "libeay64.dll"
  235. #else
  236. #define SSL_LIB "ssleay32.dll"
  237. #define CRYPTO_LIB "libeay32.dll"
  238. #endif
  239. #define O_NONBLOCK (0)
  240. #ifndef W_OK
  241. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  242. #endif
  243. #if !defined(EWOULDBLOCK)
  244. #define EWOULDBLOCK WSAEWOULDBLOCK
  245. #endif /* !EWOULDBLOCK */
  246. #define _POSIX_
  247. #define INT64_FMT "I64d"
  248. #define UINT64_FMT "I64u"
  249. #define WINCDECL __cdecl
  250. #define vsnprintf_impl _vsnprintf
  251. #define access _access
  252. #define mg_sleep(x) (Sleep(x))
  253. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  254. #ifndef popen
  255. #define popen(x, y) (_popen(x, y))
  256. #endif
  257. #ifndef pclose
  258. #define pclose(x) (_pclose(x))
  259. #endif
  260. #define close(x) (_close(x))
  261. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  262. #define RTLD_LAZY (0)
  263. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  264. #define fdopen(x, y) (_fdopen((x), (y)))
  265. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  266. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  267. #define flockfile(x) (EnterCriticalSection(&global_log_file_lock))
  268. #define funlockfile(x) (LeaveCriticalSection(&global_log_file_lock))
  269. #define sleep(x) (Sleep((x)*1000))
  270. #define rmdir(x) (_rmdir(x))
  271. #define timegm(x) (_mkgmtime(x))
  272. #if !defined(fileno)
  273. #define fileno(x) (_fileno(x))
  274. #endif /* !fileno MINGW #defines fileno */
  275. typedef HANDLE pthread_mutex_t;
  276. typedef DWORD pthread_key_t;
  277. typedef HANDLE pthread_t;
  278. typedef struct {
  279. CRITICAL_SECTION threadIdSec;
  280. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  281. } pthread_cond_t;
  282. #ifndef __clockid_t_defined
  283. typedef DWORD clockid_t;
  284. #endif
  285. #ifndef CLOCK_MONOTONIC
  286. #define CLOCK_MONOTONIC (1)
  287. #endif
  288. #ifndef CLOCK_REALTIME
  289. #define CLOCK_REALTIME (2)
  290. #endif
  291. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  292. #define _TIMESPEC_DEFINED
  293. #endif
  294. #ifndef _TIMESPEC_DEFINED
  295. struct timespec {
  296. time_t tv_sec; /* seconds */
  297. long tv_nsec; /* nanoseconds */
  298. };
  299. #endif
  300. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  301. static int pthread_mutex_lock(pthread_mutex_t *);
  302. static int pthread_mutex_unlock(pthread_mutex_t *);
  303. static void path_to_unicode(const struct mg_connection *conn,
  304. const char *path,
  305. wchar_t *wbuf,
  306. size_t wbuf_len);
  307. struct file;
  308. static const char *
  309. mg_fgets(char *buf, size_t size, struct file *filep, char **p);
  310. #if defined(HAVE_STDINT)
  311. #include <stdint.h>
  312. #else
  313. typedef unsigned char uint8_t;
  314. typedef unsigned short uint16_t;
  315. typedef unsigned int uint32_t;
  316. typedef unsigned __int64 uint64_t;
  317. typedef __int64 int64_t;
  318. #ifndef INT64_MAX
  319. #define INT64_MAX (9223372036854775807)
  320. #endif
  321. #endif /* HAVE_STDINT */
  322. /* POSIX dirent interface */
  323. struct dirent {
  324. char d_name[PATH_MAX];
  325. };
  326. typedef struct DIR {
  327. HANDLE handle;
  328. WIN32_FIND_DATAW info;
  329. struct dirent result;
  330. } DIR;
  331. #if defined(_WIN32) && !defined(POLLIN)
  332. #ifndef HAVE_POLL
  333. struct pollfd {
  334. SOCKET fd;
  335. short events;
  336. short revents;
  337. };
  338. #define POLLIN (0x0300)
  339. #endif
  340. #endif
  341. /* Mark required libraries */
  342. #if defined(_MSC_VER)
  343. #pragma comment(lib, "Ws2_32.lib")
  344. #endif
  345. #else /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  346. WINDOWS / UNIX include block */
  347. #include <sys/wait.h>
  348. #include <sys/socket.h>
  349. #include <sys/poll.h>
  350. #include <netinet/in.h>
  351. #include <arpa/inet.h>
  352. #include <sys/time.h>
  353. #include <sys/utsname.h>
  354. #include <stdint.h>
  355. #include <inttypes.h>
  356. #include <netdb.h>
  357. #include <netinet/tcp.h>
  358. typedef const void *SOCK_OPT_TYPE;
  359. #if defined(ANDROID)
  360. typedef unsigned short int in_port_t;
  361. #endif
  362. #include <pwd.h>
  363. #include <unistd.h>
  364. #include <grp.h>
  365. #include <dirent.h>
  366. #define vsnprintf_impl vsnprintf
  367. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  368. #include <dlfcn.h>
  369. #endif
  370. #include <pthread.h>
  371. #if defined(__MACH__)
  372. #define SSL_LIB "libssl.dylib"
  373. #define CRYPTO_LIB "libcrypto.dylib"
  374. #else
  375. #if !defined(SSL_LIB)
  376. #define SSL_LIB "libssl.so"
  377. #endif
  378. #if !defined(CRYPTO_LIB)
  379. #define CRYPTO_LIB "libcrypto.so"
  380. #endif
  381. #endif
  382. #ifndef O_BINARY
  383. #define O_BINARY (0)
  384. #endif /* O_BINARY */
  385. #define closesocket(a) (close(a))
  386. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  387. #define mg_remove(conn, x) (remove(x))
  388. #define mg_sleep(x) (usleep((x)*1000))
  389. #define mg_opendir(conn, x) (opendir(x))
  390. #define mg_closedir(x) (closedir(x))
  391. #define mg_readdir(x) (readdir(x))
  392. #define ERRNO (errno)
  393. #define INVALID_SOCKET (-1)
  394. #define INT64_FMT PRId64
  395. #define UINT64_FMT PRIu64
  396. typedef int SOCKET;
  397. #define WINCDECL
  398. #if defined(__hpux)
  399. /* HPUX 11 does not have monotonic, fall back to realtime */
  400. #ifndef CLOCK_MONOTONIC
  401. #define CLOCK_MONOTONIC CLOCK_REALTIME
  402. #endif
  403. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  404. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  405. * the prototypes use int* rather than socklen_t* which matches the
  406. * actual library expectation. When called with the wrong size arg
  407. * accept() returns a zero client inet addr and check_acl() always
  408. * fails. Since socklen_t is widely used below, just force replace
  409. * their typedef with int. - DTL
  410. */
  411. #define socklen_t int
  412. #endif /* hpux */
  413. #endif /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  414. WINDOWS / UNIX include block */
  415. /* va_copy should always be a macro, C99 and C++11 - DTL */
  416. #ifndef va_copy
  417. #define va_copy(x, y) ((x) = (y))
  418. #endif
  419. #ifdef _WIN32
  420. /* Create substitutes for POSIX functions in Win32. */
  421. #if defined(__MINGW32__)
  422. /* Show no warning in case system functions are not used. */
  423. #pragma GCC diagnostic push
  424. #pragma GCC diagnostic ignored "-Wunused-function"
  425. #endif
  426. static CRITICAL_SECTION global_log_file_lock;
  427. static DWORD
  428. pthread_self(void)
  429. {
  430. return GetCurrentThreadId();
  431. }
  432. static int
  433. pthread_key_create(
  434. pthread_key_t *key,
  435. void (*_ignored)(void *) /* destructor not supported for Windows */
  436. )
  437. {
  438. (void)_ignored;
  439. if ((key != 0)) {
  440. *key = TlsAlloc();
  441. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  442. }
  443. return -2;
  444. }
  445. static int
  446. pthread_key_delete(pthread_key_t key)
  447. {
  448. return TlsFree(key) ? 0 : 1;
  449. }
  450. static int
  451. pthread_setspecific(pthread_key_t key, void *value)
  452. {
  453. return TlsSetValue(key, value) ? 0 : 1;
  454. }
  455. static void *
  456. pthread_getspecific(pthread_key_t key)
  457. {
  458. return TlsGetValue(key);
  459. }
  460. #if defined(__MINGW32__)
  461. /* Enable unused function warning again */
  462. #pragma GCC diagnostic pop
  463. #endif
  464. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  465. #else
  466. static pthread_mutexattr_t pthread_mutex_attr;
  467. #endif /* _WIN32 */
  468. #define PASSWORDS_FILE_NAME ".htpasswd"
  469. #define CGI_ENVIRONMENT_SIZE (4096)
  470. #define MAX_CGI_ENVIR_VARS (256)
  471. #define MG_BUF_LEN (8192)
  472. #ifndef MAX_REQUEST_SIZE
  473. #define MAX_REQUEST_SIZE (16384)
  474. #endif
  475. mg_static_assert(MAX_REQUEST_SIZE >= 256,
  476. "request size length must be a positive number");
  477. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  478. #if !defined(DEBUG_TRACE)
  479. #if defined(DEBUG)
  480. #if defined(_WIN32_WCE)
  481. /* Create substitutes for POSIX functions in Win32. */
  482. #if defined(__MINGW32__)
  483. /* Show no warning in case system functions are not used. */
  484. #pragma GCC diagnostic push
  485. #pragma GCC diagnostic ignored "-Wunused-function"
  486. #endif
  487. static time_t
  488. time(time_t *ptime)
  489. {
  490. time_t t;
  491. SYSTEMTIME st;
  492. FILETIME ft;
  493. GetSystemTime(&st);
  494. SystemTimeToFileTime(&st, &ft);
  495. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  496. if (ptime != NULL) {
  497. *ptime = t;
  498. }
  499. return t;
  500. }
  501. static struct tm *
  502. localtime_s(const time_t *ptime, struct tm *ptm)
  503. {
  504. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  505. FILETIME ft, lft;
  506. SYSTEMTIME st;
  507. TIME_ZONE_INFORMATION tzinfo;
  508. if (ptm == NULL) {
  509. return NULL;
  510. }
  511. *(int64_t *)&ft = t;
  512. FileTimeToLocalFileTime(&ft, &lft);
  513. FileTimeToSystemTime(&lft, &st);
  514. ptm->tm_year = st.wYear - 1900;
  515. ptm->tm_mon = st.wMonth - 1;
  516. ptm->tm_wday = st.wDayOfWeek;
  517. ptm->tm_mday = st.wDay;
  518. ptm->tm_hour = st.wHour;
  519. ptm->tm_min = st.wMinute;
  520. ptm->tm_sec = st.wSecond;
  521. ptm->tm_yday = 0; /* hope nobody uses this */
  522. ptm->tm_isdst =
  523. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  524. return ptm;
  525. }
  526. static struct tm *
  527. gmtime_s(const time_t *ptime, struct tm *ptm)
  528. {
  529. /* FIXME(lsm): fix this. */
  530. return localtime_s(ptime, ptm);
  531. }
  532. static int mg_atomic_inc(volatile int *addr);
  533. static struct tm tm_array[MAX_WORKER_THREADS];
  534. static int tm_index = 0;
  535. static struct tm *
  536. localtime(const time_t *ptime)
  537. {
  538. int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0]));
  539. return localtime_s(ptime, tm_array + i);
  540. }
  541. static struct tm *
  542. gmtime(const time_t *ptime)
  543. {
  544. int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  545. return gmtime_s(ptime, tm_array + i);
  546. }
  547. static size_t
  548. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  549. {
  550. /* TODO */ //(void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  551. // for WinCE");
  552. return 0;
  553. }
  554. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  555. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  556. #define remove(f) mg_remove(NULL, f)
  557. static int
  558. rename(const char *a, const char *b)
  559. {
  560. wchar_t wa[PATH_MAX];
  561. wchar_t wb[PATH_MAX];
  562. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  563. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  564. return MoveFileW(wa, wb) ? 0 : -1;
  565. }
  566. struct stat {
  567. int64_t st_size;
  568. time_t st_mtime;
  569. };
  570. static int
  571. stat(const char *name, struct stat *st)
  572. {
  573. wchar_t wbuf[PATH_MAX];
  574. WIN32_FILE_ATTRIBUTE_DATA attr;
  575. time_t creation_time, write_time;
  576. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  577. memset(&attr, 0, sizeof(attr));
  578. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  579. st->st_size =
  580. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  581. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  582. attr.ftLastWriteTime.dwHighDateTime);
  583. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  584. attr.ftCreationTime.dwHighDateTime);
  585. if (creation_time > write_time) {
  586. st->st_mtime = creation_time;
  587. } else {
  588. st->st_mtime = write_time;
  589. }
  590. return 0;
  591. }
  592. #define access(x, a) 1 /* not required anyway */
  593. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  594. #define EEXIST 1 /* TODO: See Windows error codes */
  595. #define EACCES 2 /* TODO: See Windows error codes */
  596. #define ENOENT 3 /* TODO: See Windows Error codes */
  597. #if defined(__MINGW32__)
  598. /* Enable unused function warning again */
  599. #pragma GCC diagnostic pop
  600. #endif
  601. #endif /* defined(_WIN32_WCE) */
  602. static void DEBUG_TRACE_FUNC(const char *func,
  603. unsigned line,
  604. PRINTF_FORMAT_STRING(const char *fmt),
  605. ...) PRINTF_ARGS(3, 4);
  606. static void
  607. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  608. {
  609. va_list args;
  610. flockfile(stdout);
  611. printf("*** %lu.%p.%s.%u: ",
  612. (unsigned long)time(NULL),
  613. (void *)pthread_self(),
  614. func,
  615. line);
  616. va_start(args, fmt);
  617. vprintf(fmt, args);
  618. va_end(args);
  619. putchar('\n');
  620. fflush(stdout);
  621. funlockfile(stdout);
  622. }
  623. #define DEBUG_TRACE(fmt, ...) \
  624. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  625. #else
  626. #define DEBUG_TRACE(fmt, ...) \
  627. do { \
  628. } while (0)
  629. #endif /* DEBUG */
  630. #endif /* DEBUG_TRACE */
  631. #if defined(MEMORY_DEBUGGING)
  632. unsigned long mg_memory_debug_blockCount = 0;
  633. unsigned long mg_memory_debug_totalMemUsed = 0;
  634. static void *
  635. mg_malloc_ex(size_t size, const char *file, unsigned line)
  636. {
  637. void *data = malloc(size + sizeof(size_t));
  638. void *memory = 0;
  639. char mallocStr[256];
  640. if (data) {
  641. *(size_t *)data = size;
  642. mg_memory_debug_totalMemUsed += size;
  643. mg_memory_debug_blockCount++;
  644. memory = (void *)(((char *)data) + sizeof(size_t));
  645. }
  646. sprintf(mallocStr,
  647. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  648. memory,
  649. (unsigned long)size,
  650. mg_memory_debug_totalMemUsed,
  651. mg_memory_debug_blockCount,
  652. file,
  653. line);
  654. #if defined(_WIN32)
  655. OutputDebugStringA(mallocStr);
  656. #else
  657. DEBUG_TRACE("%s", mallocStr);
  658. #endif
  659. return memory;
  660. }
  661. static void *
  662. mg_calloc_ex(size_t count, size_t size, const char *file, unsigned line)
  663. {
  664. void *data = mg_malloc_ex(size * count, file, line);
  665. if (data) {
  666. memset(data, 0, size * count);
  667. }
  668. return data;
  669. }
  670. static void
  671. mg_free_ex(void *memory, const char *file, unsigned line)
  672. {
  673. char mallocStr[256];
  674. void *data = (void *)(((char *)memory) - sizeof(size_t));
  675. size_t size;
  676. if (memory) {
  677. size = *(size_t *)data;
  678. mg_memory_debug_totalMemUsed -= size;
  679. mg_memory_debug_blockCount--;
  680. sprintf(mallocStr,
  681. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  682. memory,
  683. (unsigned long)size,
  684. mg_memory_debug_totalMemUsed,
  685. mg_memory_debug_blockCount,
  686. file,
  687. line);
  688. #if defined(_WIN32)
  689. OutputDebugStringA(mallocStr);
  690. #else
  691. DEBUG_TRACE("%s", mallocStr);
  692. #endif
  693. free(data);
  694. }
  695. }
  696. static void *
  697. mg_realloc_ex(void *memory, size_t newsize, const char *file, unsigned line)
  698. {
  699. char mallocStr[256];
  700. void *data;
  701. void *_realloc;
  702. size_t oldsize;
  703. if (newsize) {
  704. if (memory) {
  705. data = (void *)(((char *)memory) - sizeof(size_t));
  706. oldsize = *(size_t *)data;
  707. _realloc = realloc(data, newsize + sizeof(size_t));
  708. if (_realloc) {
  709. data = _realloc;
  710. mg_memory_debug_totalMemUsed -= oldsize;
  711. sprintf(mallocStr,
  712. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  713. memory,
  714. (unsigned long)oldsize,
  715. mg_memory_debug_totalMemUsed,
  716. mg_memory_debug_blockCount,
  717. file,
  718. line);
  719. #if defined(_WIN32)
  720. OutputDebugStringA(mallocStr);
  721. #else
  722. DEBUG_TRACE("%s", mallocStr);
  723. #endif
  724. mg_memory_debug_totalMemUsed += newsize;
  725. sprintf(mallocStr,
  726. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  727. memory,
  728. (unsigned long)newsize,
  729. mg_memory_debug_totalMemUsed,
  730. mg_memory_debug_blockCount,
  731. file,
  732. line);
  733. #if defined(_WIN32)
  734. OutputDebugStringA(mallocStr);
  735. #else
  736. DEBUG_TRACE("%s", mallocStr);
  737. #endif
  738. *(size_t *)data = newsize;
  739. data = (void *)(((char *)data) + sizeof(size_t));
  740. } else {
  741. #if defined(_WIN32)
  742. OutputDebugStringA("MEM: realloc failed\n");
  743. #else
  744. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  745. #endif
  746. return _realloc;
  747. }
  748. } else {
  749. data = mg_malloc_ex(newsize, file, line);
  750. }
  751. } else {
  752. data = 0;
  753. mg_free_ex(memory, file, line);
  754. }
  755. return data;
  756. }
  757. #define mg_malloc(a) mg_malloc_ex(a, __FILE__, __LINE__)
  758. #define mg_calloc(a, b) mg_calloc_ex(a, b, __FILE__, __LINE__)
  759. #define mg_realloc(a, b) mg_realloc_ex(a, b, __FILE__, __LINE__)
  760. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  761. #else
  762. static __inline void *
  763. mg_malloc(size_t a)
  764. {
  765. return malloc(a);
  766. }
  767. static __inline void *
  768. mg_calloc(size_t a, size_t b)
  769. {
  770. return calloc(a, b);
  771. }
  772. static __inline void *
  773. mg_realloc(void *a, size_t b)
  774. {
  775. return realloc(a, b);
  776. }
  777. static __inline void
  778. mg_free(void *a)
  779. {
  780. free(a);
  781. }
  782. #endif
  783. static void mg_vsnprintf(const struct mg_connection *conn,
  784. int *truncated,
  785. char *buf,
  786. size_t buflen,
  787. const char *fmt,
  788. va_list ap);
  789. static void mg_snprintf(const struct mg_connection *conn,
  790. int *truncated,
  791. char *buf,
  792. size_t buflen,
  793. PRINTF_FORMAT_STRING(const char *fmt),
  794. ...) PRINTF_ARGS(5, 6);
  795. /* This following lines are just meant as a reminder to use the mg-functions
  796. * for memory management */
  797. #ifdef malloc
  798. #undef malloc
  799. #endif
  800. #ifdef calloc
  801. #undef calloc
  802. #endif
  803. #ifdef realloc
  804. #undef realloc
  805. #endif
  806. #ifdef free
  807. #undef free
  808. #endif
  809. #ifdef snprintf
  810. #undef snprintf
  811. #endif
  812. #ifdef vsnprintf
  813. #undef vsnprintf
  814. #endif
  815. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  816. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  817. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  818. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  819. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  820. #ifdef _WIN32 /* vsnprintf must not be used in any system, * \ \ \ \
  821. * but this define only works well for Windows. */
  822. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  823. #endif
  824. #define MD5_STATIC static
  825. #include "md5.inl"
  826. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  827. #ifdef NO_SOCKLEN_T
  828. typedef int socklen_t;
  829. #endif /* NO_SOCKLEN_T */
  830. #define _DARWIN_UNLIMITED_SELECT
  831. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  832. #if !defined(MSG_NOSIGNAL)
  833. #define MSG_NOSIGNAL (0)
  834. #endif
  835. #if !defined(SOMAXCONN)
  836. #define SOMAXCONN (100)
  837. #endif
  838. /* Size of the accepted socket queue */
  839. #if !defined(MGSQLEN)
  840. #define MGSQLEN (20)
  841. #endif
  842. #if defined(NO_SSL)
  843. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  844. typedef struct SSL_CTX SSL_CTX;
  845. #else
  846. #if defined(NO_SSL_DL)
  847. #include <openssl/ssl.h>
  848. #include <openssl/err.h>
  849. #include <openssl/crypto.h>
  850. #include <openssl/x509.h>
  851. #include <openssl/pem.h>
  852. #include <openssl/engine.h>
  853. #include <openssl/conf.h>
  854. #else
  855. /* SSL loaded dynamically from DLL.
  856. * I put the prototypes here to be independent from OpenSSL source
  857. * installation. */
  858. typedef struct ssl_st SSL;
  859. typedef struct ssl_method_st SSL_METHOD;
  860. typedef struct ssl_ctx_st SSL_CTX;
  861. typedef struct x509_store_ctx_st X509_STORE_CTX;
  862. typedef struct x509_name X509_NAME;
  863. typedef struct asn1_integer ASN1_INTEGER;
  864. typedef struct evp_md EVP_MD;
  865. typedef struct x509 X509;
  866. #define SSL_CTRL_OPTIONS (32)
  867. #define SSL_CTRL_CLEAR_OPTIONS (77)
  868. #define SSL_CTRL_SET_ECDH_AUTO (94)
  869. #define SSL_VERIFY_NONE (0)
  870. #define SSL_VERIFY_PEER (1)
  871. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  872. #define SSL_VERIFY_CLIENT_ONCE (4)
  873. #define SSL_OP_ALL ((long)(0x80000BFFUL))
  874. #define SSL_OP_NO_SSLv2 (0x01000000L)
  875. #define SSL_OP_NO_SSLv3 (0x02000000L)
  876. #define SSL_OP_NO_TLSv1 (0x04000000L)
  877. #define SSL_OP_NO_TLSv1_2 (0x08000000L)
  878. #define SSL_OP_NO_TLSv1_1 (0x10000000L)
  879. #define SSL_OP_SINGLE_DH_USE (0x00100000L)
  880. #define SSL_ERROR_NONE (0)
  881. #define SSL_ERROR_SSL (1)
  882. #define SSL_ERROR_WANT_READ (2)
  883. #define SSL_ERROR_WANT_WRITE (3)
  884. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  885. #define SSL_ERROR_SYSCALL (5) /* see errno */
  886. #define SSL_ERROR_ZERO_RETURN (6)
  887. #define SSL_ERROR_WANT_CONNECT (7)
  888. #define SSL_ERROR_WANT_ACCEPT (8)
  889. struct ssl_func {
  890. const char *name; /* SSL function name */
  891. void (*ptr)(void); /* Function pointer */
  892. };
  893. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  894. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  895. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  896. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  897. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  898. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  899. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  900. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  901. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  902. #define SSLv23_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  903. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  904. #define SSL_CTX_use_PrivateKey_file \
  905. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  906. #define SSL_CTX_use_certificate_file \
  907. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  908. #define SSL_CTX_set_default_passwd_cb \
  909. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  910. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  911. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  912. #define SSL_CTX_use_certificate_chain_file \
  913. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  914. #define SSLv23_client_method (*(SSL_METHOD * (*)(void))ssl_sw[17].ptr)
  915. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  916. #define SSL_CTX_set_verify \
  917. (*(void (*)(SSL_CTX *, \
  918. int, \
  919. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19].ptr)
  920. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  921. #define SSL_CTX_load_verify_locations \
  922. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  923. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  924. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  925. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[24].ptr)
  926. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  927. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[26].ptr)
  928. #define SSL_CIPHER_get_name \
  929. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  930. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  931. #define SSL_CTX_set_session_id_context \
  932. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  933. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  934. #define SSL_CTX_set_cipher_list \
  935. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  936. #define SSL_CTX_set_options(ctx, op) \
  937. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  938. #define SSL_CTX_clear_options(ctx, op) \
  939. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  940. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  941. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  942. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  943. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  944. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  945. #define CRYPTO_set_locking_callback \
  946. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  947. #define CRYPTO_set_id_callback \
  948. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  949. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  950. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  951. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  952. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  953. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  954. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  955. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  956. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  957. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  958. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[12].ptr)
  959. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[13].ptr)
  960. #define X509_NAME_oneline \
  961. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  962. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[15].ptr)
  963. #define i2c_ASN1_INTEGER \
  964. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  965. #define EVP_get_digestbyname \
  966. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  967. #define ASN1_digest \
  968. (*(int (*)(int (*)(), \
  969. const EVP_MD *, \
  970. char *, \
  971. unsigned char *, \
  972. unsigned int *))crypto_sw[18].ptr)
  973. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  974. /* set_ssl_option() function updates this array.
  975. * It loads SSL library dynamically and changes NULLs to the actual addresses
  976. * of respective functions. The macros above (like SSL_connect()) are really
  977. * just calling these functions indirectly via the pointer. */
  978. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  979. {"SSL_accept", NULL},
  980. {"SSL_connect", NULL},
  981. {"SSL_read", NULL},
  982. {"SSL_write", NULL},
  983. {"SSL_get_error", NULL},
  984. {"SSL_set_fd", NULL},
  985. {"SSL_new", NULL},
  986. {"SSL_CTX_new", NULL},
  987. {"SSLv23_server_method", NULL},
  988. {"SSL_library_init", NULL},
  989. {"SSL_CTX_use_PrivateKey_file", NULL},
  990. {"SSL_CTX_use_certificate_file", NULL},
  991. {"SSL_CTX_set_default_passwd_cb", NULL},
  992. {"SSL_CTX_free", NULL},
  993. {"SSL_load_error_strings", NULL},
  994. {"SSL_CTX_use_certificate_chain_file", NULL},
  995. {"SSLv23_client_method", NULL},
  996. {"SSL_pending", NULL},
  997. {"SSL_CTX_set_verify", NULL},
  998. {"SSL_shutdown", NULL},
  999. {"SSL_CTX_load_verify_locations", NULL},
  1000. {"SSL_CTX_set_default_verify_paths", NULL},
  1001. {"SSL_CTX_set_verify_depth", NULL},
  1002. {"SSL_get_peer_certificate", NULL},
  1003. {"SSL_get_version", NULL},
  1004. {"SSL_get_current_cipher", NULL},
  1005. {"SSL_CIPHER_get_name", NULL},
  1006. {"SSL_CTX_check_private_key", NULL},
  1007. {"SSL_CTX_set_session_id_context", NULL},
  1008. {"SSL_CTX_ctrl", NULL},
  1009. {"SSL_CTX_set_cipher_list", NULL},
  1010. {NULL, NULL}};
  1011. /* Similar array as ssl_sw. These functions could be located in different
  1012. * lib. */
  1013. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  1014. {"CRYPTO_set_locking_callback", NULL},
  1015. {"CRYPTO_set_id_callback", NULL},
  1016. {"ERR_get_error", NULL},
  1017. {"ERR_error_string", NULL},
  1018. {"ERR_remove_state", NULL},
  1019. {"ERR_free_strings", NULL},
  1020. {"ENGINE_cleanup", NULL},
  1021. {"CONF_modules_unload", NULL},
  1022. {"CRYPTO_cleanup_all_ex_data", NULL},
  1023. {"EVP_cleanup", NULL},
  1024. {"X509_free", NULL},
  1025. {"X509_get_subject_name", NULL},
  1026. {"X509_get_issuer_name", NULL},
  1027. {"X509_NAME_oneline", NULL},
  1028. {"X509_get_serialNumber", NULL},
  1029. {"i2c_ASN1_INTEGER", NULL},
  1030. {"EVP_get_digestbyname", NULL},
  1031. {"ASN1_digest", NULL},
  1032. {"i2d_X509", NULL},
  1033. {NULL, NULL}};
  1034. #endif /* NO_SSL_DL */
  1035. #endif /* NO_SSL */
  1036. #if !defined(NO_CACHING)
  1037. static const char *month_names[] = {"Jan",
  1038. "Feb",
  1039. "Mar",
  1040. "Apr",
  1041. "May",
  1042. "Jun",
  1043. "Jul",
  1044. "Aug",
  1045. "Sep",
  1046. "Oct",
  1047. "Nov",
  1048. "Dec"};
  1049. #endif /* !NO_CACHING */
  1050. /* Unified socket address. For IPv6 support, add IPv6 address structure in the
  1051. * union u. */
  1052. union usa {
  1053. struct sockaddr sa;
  1054. struct sockaddr_in sin;
  1055. #if defined(USE_IPV6)
  1056. struct sockaddr_in6 sin6;
  1057. #endif
  1058. };
  1059. /* Describes a string (chunk of memory). */
  1060. struct vec {
  1061. const char *ptr;
  1062. size_t len;
  1063. };
  1064. struct file {
  1065. uint64_t size;
  1066. time_t last_modified;
  1067. FILE *fp;
  1068. const char *membuf; /* Non-NULL if file data is in memory */
  1069. int is_directory;
  1070. int gzipped; /* set to 1 if the content is gzipped
  1071. * in which case we need a content-encoding: gzip header */
  1072. };
  1073. #define STRUCT_FILE_INITIALIZER \
  1074. { \
  1075. (uint64_t)0, (time_t)0, (FILE *)NULL, (const char *)NULL, 0, 0 \
  1076. }
  1077. /* Describes listening socket, or socket which was accept()-ed by the master
  1078. * thread and queued for future handling by the worker thread. */
  1079. struct socket {
  1080. SOCKET sock; /* Listening socket */
  1081. union usa lsa; /* Local socket address */
  1082. union usa rsa; /* Remote socket address */
  1083. unsigned char is_ssl; /* Is port SSL-ed */
  1084. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1085. * port */
  1086. unsigned char in_use; /* Is valid */
  1087. };
  1088. /* NOTE(lsm): this enum shoulds be in sync with the config_options below. */
  1089. enum {
  1090. CGI_EXTENSIONS,
  1091. CGI_ENVIRONMENT,
  1092. PUT_DELETE_PASSWORDS_FILE,
  1093. CGI_INTERPRETER,
  1094. PROTECT_URI,
  1095. AUTHENTICATION_DOMAIN,
  1096. SSI_EXTENSIONS,
  1097. THROTTLE,
  1098. ACCESS_LOG_FILE,
  1099. ENABLE_DIRECTORY_LISTING,
  1100. ERROR_LOG_FILE,
  1101. GLOBAL_PASSWORDS_FILE,
  1102. INDEX_FILES,
  1103. ENABLE_KEEP_ALIVE,
  1104. ACCESS_CONTROL_LIST,
  1105. EXTRA_MIME_TYPES,
  1106. LISTENING_PORTS,
  1107. DOCUMENT_ROOT,
  1108. SSL_CERTIFICATE,
  1109. NUM_THREADS,
  1110. RUN_AS_USER,
  1111. REWRITE,
  1112. HIDE_FILES,
  1113. REQUEST_TIMEOUT,
  1114. SSL_DO_VERIFY_PEER,
  1115. SSL_CA_PATH,
  1116. SSL_CA_FILE,
  1117. SSL_VERIFY_DEPTH,
  1118. SSL_DEFAULT_VERIFY_PATHS,
  1119. SSL_CIPHER_LIST,
  1120. SSL_PROTOCOL_VERSION,
  1121. SSL_SHORT_TRUST,
  1122. #if defined(USE_WEBSOCKET)
  1123. WEBSOCKET_TIMEOUT,
  1124. #endif
  1125. DECODE_URL,
  1126. #if defined(USE_LUA)
  1127. LUA_PRELOAD_FILE,
  1128. LUA_SCRIPT_EXTENSIONS,
  1129. LUA_SERVER_PAGE_EXTENSIONS,
  1130. #endif
  1131. #if defined(USE_DUKTAPE)
  1132. DUKTAPE_SCRIPT_EXTENSIONS,
  1133. #endif
  1134. #if defined(USE_WEBSOCKET)
  1135. WEBSOCKET_ROOT,
  1136. #endif
  1137. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1138. LUA_WEBSOCKET_EXTENSIONS,
  1139. #endif
  1140. ACCESS_CONTROL_ALLOW_ORIGIN,
  1141. ERROR_PAGES,
  1142. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1143. * socket option typedef TCP_NODELAY. */
  1144. #if !defined(NO_CACHING)
  1145. STATIC_FILE_MAX_AGE,
  1146. #endif
  1147. NUM_OPTIONS
  1148. };
  1149. /* Config option name, config types, default value */
  1150. static struct mg_option config_options[] = {
  1151. {"cgi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1152. {"cgi_environment", CONFIG_TYPE_STRING, NULL},
  1153. {"put_delete_auth_file", CONFIG_TYPE_FILE, NULL},
  1154. {"cgi_interpreter", CONFIG_TYPE_FILE, NULL},
  1155. {"protect_uri", CONFIG_TYPE_STRING, NULL},
  1156. {"authentication_domain", CONFIG_TYPE_STRING, "mydomain.com"},
  1157. {"ssi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1158. {"throttle", CONFIG_TYPE_STRING, NULL},
  1159. {"access_log_file", CONFIG_TYPE_FILE, NULL},
  1160. {"enable_directory_listing", CONFIG_TYPE_BOOLEAN, "yes"},
  1161. {"error_log_file", CONFIG_TYPE_FILE, NULL},
  1162. {"global_auth_file", CONFIG_TYPE_FILE, NULL},
  1163. {"index_files",
  1164. CONFIG_TYPE_STRING,
  1165. #ifdef USE_LUA
  1166. "index.xhtml,index.html,index.htm,index.lp,index.lsp,index.lua,index.cgi,"
  1167. "index.shtml,index.php"},
  1168. #else
  1169. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1170. #endif
  1171. {"enable_keep_alive", CONFIG_TYPE_BOOLEAN, "no"},
  1172. {"access_control_list", CONFIG_TYPE_STRING, NULL},
  1173. {"extra_mime_types", CONFIG_TYPE_STRING, NULL},
  1174. {"listening_ports", CONFIG_TYPE_STRING, "8080"},
  1175. {"document_root", CONFIG_TYPE_DIRECTORY, NULL},
  1176. {"ssl_certificate", CONFIG_TYPE_FILE, NULL},
  1177. {"num_threads", CONFIG_TYPE_NUMBER, "50"},
  1178. {"run_as_user", CONFIG_TYPE_STRING, NULL},
  1179. {"url_rewrite_patterns", CONFIG_TYPE_STRING, NULL},
  1180. {"hide_files_patterns", CONFIG_TYPE_EXT_PATTERN, NULL},
  1181. {"request_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1182. {"ssl_verify_peer", CONFIG_TYPE_BOOLEAN, "no"},
  1183. {"ssl_ca_path", CONFIG_TYPE_DIRECTORY, NULL},
  1184. {"ssl_ca_file", CONFIG_TYPE_FILE, NULL},
  1185. {"ssl_verify_depth", CONFIG_TYPE_NUMBER, "9"},
  1186. {"ssl_default_verify_paths", CONFIG_TYPE_BOOLEAN, "yes"},
  1187. {"ssl_cipher_list", CONFIG_TYPE_STRING, NULL},
  1188. {"ssl_protocol_version", CONFIG_TYPE_NUMBER, "0"},
  1189. {"ssl_short_trust", CONFIG_TYPE_BOOLEAN, "no"},
  1190. #if defined(USE_WEBSOCKET)
  1191. {"websocket_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1192. #endif
  1193. {"decode_url", CONFIG_TYPE_BOOLEAN, "yes"},
  1194. #if defined(USE_LUA)
  1195. {"lua_preload_file", CONFIG_TYPE_FILE, NULL},
  1196. {"lua_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1197. {"lua_server_page_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1198. #endif
  1199. #if defined(USE_DUKTAPE)
  1200. /* The support for duktape is still in alpha version state.
  1201. * The name of this config option might change. */
  1202. {"duktape_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1203. #endif
  1204. #if defined(USE_WEBSOCKET)
  1205. {"websocket_root", CONFIG_TYPE_DIRECTORY, NULL},
  1206. #endif
  1207. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1208. {"lua_websocket_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1209. #endif
  1210. {"access_control_allow_origin", CONFIG_TYPE_STRING, "*"},
  1211. {"error_pages", CONFIG_TYPE_DIRECTORY, NULL},
  1212. {"tcp_nodelay", CONFIG_TYPE_NUMBER, "0"},
  1213. #if !defined(NO_CACHING)
  1214. {"static_file_max_age", CONFIG_TYPE_NUMBER, "3600"},
  1215. #endif
  1216. {NULL, CONFIG_TYPE_UNKNOWN, NULL}};
  1217. /* Check if the config_options and the corresponding enum have compatible
  1218. * sizes. */
  1219. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1220. == (NUM_OPTIONS + 1),
  1221. "config_options and enum not sync");
  1222. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1223. struct mg_handler_info {
  1224. /* Name/Pattern of the URI. */
  1225. char *uri;
  1226. size_t uri_len;
  1227. /* handler type */
  1228. int handler_type;
  1229. /* Handler for http/https or authorization requests. */
  1230. mg_request_handler handler;
  1231. /* Handler for ws/wss (websocket) requests. */
  1232. mg_websocket_connect_handler connect_handler;
  1233. mg_websocket_ready_handler ready_handler;
  1234. mg_websocket_data_handler data_handler;
  1235. mg_websocket_close_handler close_handler;
  1236. /* Handler for authorization requests */
  1237. mg_authorization_handler auth_handler;
  1238. /* User supplied argument for the handler function. */
  1239. void *cbdata;
  1240. /* next handler in a linked list */
  1241. struct mg_handler_info *next;
  1242. };
  1243. struct mg_context {
  1244. volatile int stop_flag; /* Should we stop event loop */
  1245. SSL_CTX *ssl_ctx; /* SSL context */
  1246. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1247. struct mg_callbacks callbacks; /* User-defined callback function */
  1248. void *user_data; /* User-defined data */
  1249. int context_type; /* 1 = server context, 2 = client context */
  1250. struct socket *listening_sockets;
  1251. struct pollfd *listening_socket_fds;
  1252. unsigned int num_listening_sockets;
  1253. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  1254. #ifdef ALTERNATIVE_QUEUE
  1255. struct socket *client_socks;
  1256. void **client_wait_events;
  1257. #else
  1258. struct socket queue[MGSQLEN]; /* Accepted sockets */
  1259. volatile int sq_head; /* Head of the socket queue */
  1260. volatile int sq_tail; /* Tail of the socket queue */
  1261. pthread_cond_t sq_full; /* Signaled when socket is produced */
  1262. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  1263. #endif
  1264. pthread_t masterthreadid; /* The master thread ID */
  1265. unsigned int
  1266. cfg_worker_threads; /* The number of configured worker threads. */
  1267. pthread_t *workerthreadids; /* The worker thread IDs */
  1268. time_t start_time; /* Server start time, used for authentication */
  1269. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1270. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  1271. unsigned long nonce_count; /* Used nonces, used for authentication */
  1272. char *systemName; /* What operating system is running */
  1273. /* linked list of uri handlers */
  1274. struct mg_handler_info *handlers;
  1275. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1276. /* linked list of shared lua websockets */
  1277. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1278. #endif
  1279. #ifdef USE_TIMERS
  1280. struct ttimers *timers;
  1281. #endif
  1282. };
  1283. struct mg_connection {
  1284. struct mg_request_info request_info;
  1285. struct mg_context *ctx;
  1286. SSL *ssl; /* SSL descriptor */
  1287. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  1288. struct socket client; /* Connected client */
  1289. time_t conn_birth_time; /* Time (wall clock) when connection was
  1290. * established */
  1291. struct timespec req_time; /* Time (since system start) when the request
  1292. * was received */
  1293. int64_t num_bytes_sent; /* Total bytes sent to client */
  1294. int64_t content_len; /* Content-Length header value */
  1295. int64_t consumed_content; /* How many bytes of content have been read */
  1296. int is_chunked; /* Transfer-Encoding is chunked: 0=no, 1=yes:
  1297. * data available, 2: all data read */
  1298. size_t chunk_remainder; /* Unread data from the last chunk */
  1299. char *buf; /* Buffer for received data */
  1300. char *path_info; /* PATH_INFO part of the URL */
  1301. int must_close; /* 1 if connection must be closed */
  1302. int in_error_handler; /* 1 if in handler for user defined error
  1303. * pages */
  1304. int internal_error; /* 1 if an error occured while processing the
  1305. * request */
  1306. int buf_size; /* Buffer size */
  1307. int request_len; /* Size of the request + headers in a buffer */
  1308. int data_len; /* Total size of data in a buffer */
  1309. int status_code; /* HTTP reply status code, e.g. 200 */
  1310. int throttle; /* Throttling, bytes/sec. <= 0 means no
  1311. * throttle */
  1312. time_t last_throttle_time; /* Last time throttled data was sent */
  1313. int64_t last_throttle_bytes; /* Bytes sent this second */
  1314. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  1315. * atomic transmissions for websockets */
  1316. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1317. void *lua_websocket_state; /* Lua_State for a websocket connection */
  1318. #endif
  1319. int thread_index; /* Thread index within ctx */
  1320. };
  1321. static pthread_key_t sTlsKey; /* Thread local storage index */
  1322. static int sTlsInit = 0;
  1323. static int thread_idx_max = 0;
  1324. struct mg_workerTLS {
  1325. int is_master;
  1326. unsigned long thread_idx;
  1327. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1328. HANDLE pthread_cond_helper_mutex;
  1329. struct mg_workerTLS *next_waiting_thread;
  1330. #endif
  1331. };
  1332. /* Directory entry */
  1333. struct de {
  1334. struct mg_connection *conn;
  1335. char *file_name;
  1336. struct file file;
  1337. };
  1338. #if defined(USE_WEBSOCKET)
  1339. static int is_websocket_protocol(const struct mg_connection *conn);
  1340. #else
  1341. #define is_websocket_protocol(conn) (0)
  1342. #endif
  1343. static int
  1344. mg_atomic_inc(volatile int *addr)
  1345. {
  1346. int ret;
  1347. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1348. /* Depending on the SDK, this function uses either
  1349. * (volatile unsigned int *) or (volatile LONG *),
  1350. * so whatever you use, the other SDK is likely to raise a warning. */
  1351. ret = InterlockedIncrement((volatile long *)addr);
  1352. #elif defined(__GNUC__) \
  1353. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  1354. ret = __sync_add_and_fetch(addr, 1);
  1355. #else
  1356. ret = (++(*addr));
  1357. #endif
  1358. return ret;
  1359. }
  1360. static int
  1361. mg_atomic_dec(volatile int *addr)
  1362. {
  1363. int ret;
  1364. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1365. /* Depending on the SDK, this function uses either
  1366. * (volatile unsigned int *) or (volatile LONG *),
  1367. * so whatever you use, the other SDK is likely to raise a warning. */
  1368. ret = InterlockedDecrement((volatile long *)addr);
  1369. #elif defined(__GNUC__) \
  1370. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  1371. ret = __sync_sub_and_fetch(addr, 1);
  1372. #else
  1373. ret = (--(*addr));
  1374. #endif
  1375. return ret;
  1376. }
  1377. #if !defined(NO_THREAD_NAME)
  1378. #if defined(_WIN32) && defined(_MSC_VER)
  1379. /* Set the thread name for debugging purposes in Visual Studio
  1380. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  1381. */
  1382. #pragma pack(push, 8)
  1383. typedef struct tagTHREADNAME_INFO {
  1384. DWORD dwType; /* Must be 0x1000. */
  1385. LPCSTR szName; /* Pointer to name (in user addr space). */
  1386. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  1387. DWORD dwFlags; /* Reserved for future use, must be zero. */
  1388. } THREADNAME_INFO;
  1389. #pragma pack(pop)
  1390. #elif defined(__linux__)
  1391. #include <sys/prctl.h>
  1392. #include <sys/sendfile.h>
  1393. #include <sys/eventfd.h>
  1394. #if defined(ALTERNATIVE_QUEUE)
  1395. static void *
  1396. event_create(void)
  1397. {
  1398. int ret = eventfd(0, EFD_CLOEXEC);
  1399. if (ret == -1) {
  1400. /* Linux uses -1 on error, Windows NULL. */
  1401. /* However, Linux does not return 0 on success either. */
  1402. return 0;
  1403. }
  1404. return (void *)ret;
  1405. }
  1406. static int
  1407. event_wait(void *eventhdl)
  1408. {
  1409. uint64_t u;
  1410. int s = (int)read((int)eventhdl, &u, sizeof(u));
  1411. if (s != sizeof(uint64_t)) {
  1412. /* error */
  1413. return 0;
  1414. }
  1415. (void)u; /* the value is not required */
  1416. return 1;
  1417. }
  1418. static int
  1419. event_signal(void *eventhdl)
  1420. {
  1421. uint64_t u = 1;
  1422. int s = (int)write((int)eventhdl, &u, sizeof(u));
  1423. if (s != sizeof(uint64_t)) {
  1424. /* error */
  1425. return 0;
  1426. }
  1427. return 1;
  1428. }
  1429. static void
  1430. event_destroy(void *eventhdl)
  1431. {
  1432. close((int)eventhdl);
  1433. }
  1434. #endif
  1435. #endif
  1436. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  1437. struct posix_event {
  1438. pthread_mutex_t mutex;
  1439. pthread_cond_t cond;
  1440. };
  1441. static void *
  1442. event_create(void)
  1443. {
  1444. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  1445. if (ret == 0) {
  1446. /* out of memory */
  1447. return 0;
  1448. }
  1449. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  1450. /* pthread mutex not available */
  1451. mg_free(ret);
  1452. return 0;
  1453. }
  1454. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  1455. /* pthread cond not available */
  1456. pthread_mutex_destroy(&(ret->mutex));
  1457. mg_free(ret);
  1458. return 0;
  1459. }
  1460. return (void *)ret;
  1461. }
  1462. static int
  1463. event_wait(void *eventhdl)
  1464. {
  1465. struct posix_event *ev = (struct posix_event *)eventhdl;
  1466. pthread_mutex_lock(&(ev->mutex));
  1467. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  1468. pthread_mutex_unlock(&(ev->mutex));
  1469. return 1;
  1470. }
  1471. static int
  1472. event_signal(void *eventhdl)
  1473. {
  1474. struct posix_event *ev = (struct posix_event *)eventhdl;
  1475. pthread_mutex_lock(&(ev->mutex));
  1476. pthread_cond_signal(&(ev->cond));
  1477. pthread_mutex_unlock(&(ev->mutex));
  1478. return 1;
  1479. }
  1480. static void
  1481. event_destroy(void *eventhdl)
  1482. {
  1483. struct posix_event *ev = (struct posix_event *)eventhdl;
  1484. pthread_cond_destroy(&(ev->cond));
  1485. pthread_mutex_destroy(&(ev->mutex));
  1486. mg_free(ev);
  1487. }
  1488. #endif
  1489. static void
  1490. mg_set_thread_name(const char *name)
  1491. {
  1492. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  1493. mg_snprintf(
  1494. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  1495. #if defined(_WIN32)
  1496. #if defined(_MSC_VER)
  1497. /* Windows and Visual Studio Compiler */
  1498. __try
  1499. {
  1500. THREADNAME_INFO info;
  1501. info.dwType = 0x1000;
  1502. info.szName = threadName;
  1503. info.dwThreadID = ~0U;
  1504. info.dwFlags = 0;
  1505. RaiseException(0x406D1388,
  1506. 0,
  1507. sizeof(info) / sizeof(ULONG_PTR),
  1508. (ULONG_PTR *)&info);
  1509. }
  1510. __except(EXCEPTION_EXECUTE_HANDLER)
  1511. {
  1512. }
  1513. #elif defined(__MINGW32__)
  1514. /* No option known to set thread name for MinGW */
  1515. #endif
  1516. #elif defined(__GLIBC__) \
  1517. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  1518. /* pthread_setname_np first appeared in glibc in version 2.12*/
  1519. (void)pthread_setname_np(pthread_self(), threadName);
  1520. #elif defined(__linux__)
  1521. /* on linux we can use the old prctl function */
  1522. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  1523. #endif
  1524. }
  1525. #else /* !defined(NO_THREAD_NAME) */
  1526. void
  1527. mg_set_thread_name(const char *threadName)
  1528. {
  1529. }
  1530. #endif
  1531. #if defined(MG_LEGACY_INTERFACE)
  1532. const char **
  1533. mg_get_valid_option_names(void)
  1534. {
  1535. /* This function is deprecated. Use mg_get_valid_options instead. */
  1536. static const char *
  1537. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  1538. int i;
  1539. for (i = 0; config_options[i].name != NULL; i++) {
  1540. data[i * 2] = config_options[i].name;
  1541. data[i * 2 + 1] = config_options[i].default_value;
  1542. }
  1543. return data;
  1544. }
  1545. #endif
  1546. const struct mg_option *
  1547. mg_get_valid_options(void)
  1548. {
  1549. return config_options;
  1550. }
  1551. static int
  1552. is_file_in_memory(const struct mg_connection *conn,
  1553. const char *path,
  1554. struct file *filep)
  1555. {
  1556. size_t size = 0;
  1557. if (!conn || !filep) {
  1558. return 0;
  1559. }
  1560. if (conn->ctx->callbacks.open_file) {
  1561. filep->membuf = conn->ctx->callbacks.open_file(conn, path, &size);
  1562. if (filep->membuf != NULL) {
  1563. /* NOTE: override filep->size only on success. Otherwise, it might
  1564. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  1565. filep->size = size;
  1566. }
  1567. }
  1568. return filep->membuf != NULL;
  1569. }
  1570. static int
  1571. is_file_opened(const struct file *filep)
  1572. {
  1573. if (!filep) {
  1574. return 0;
  1575. }
  1576. return filep->membuf != NULL || filep->fp != NULL;
  1577. }
  1578. /* mg_fopen will open a file either in memory or on the disk.
  1579. * The input parameter path is a string in UTF-8 encoding.
  1580. * The input parameter mode is the same as for fopen.
  1581. * Either fp or membuf will be set in the output struct filep.
  1582. * The function returns 1 on success, 0 on error. */
  1583. static int
  1584. mg_fopen(const struct mg_connection *conn,
  1585. const char *path,
  1586. const char *mode,
  1587. struct file *filep)
  1588. {
  1589. struct stat st;
  1590. if (!filep) {
  1591. return 0;
  1592. }
  1593. /* TODO (high): mg_fopen should only open a file, while mg_stat should
  1594. * only get the file status. They should not work on different members of
  1595. * the same structure (bad cohesion). */
  1596. memset(filep, 0, sizeof(*filep));
  1597. if (stat(path, &st) == 0) {
  1598. filep->size = (uint64_t)(st.st_size);
  1599. }
  1600. if (!is_file_in_memory(conn, path, filep)) {
  1601. #ifdef _WIN32
  1602. wchar_t wbuf[PATH_MAX], wmode[20];
  1603. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  1604. MultiByteToWideChar(CP_UTF8, 0, mode, -1, wmode, ARRAY_SIZE(wmode));
  1605. filep->fp = _wfopen(wbuf, wmode);
  1606. #else
  1607. /* Linux et al already use unicode. No need to convert. */
  1608. filep->fp = fopen(path, mode);
  1609. #endif
  1610. }
  1611. return is_file_opened(filep);
  1612. }
  1613. static void
  1614. mg_fclose(struct file *filep)
  1615. {
  1616. if (filep != NULL && filep->fp != NULL) {
  1617. fclose(filep->fp);
  1618. }
  1619. }
  1620. static void
  1621. mg_strlcpy(register char *dst, register const char *src, size_t n)
  1622. {
  1623. for (; *src != '\0' && n > 1; n--) {
  1624. *dst++ = *src++;
  1625. }
  1626. *dst = '\0';
  1627. }
  1628. static int
  1629. lowercase(const char *s)
  1630. {
  1631. return tolower(*(const unsigned char *)s);
  1632. }
  1633. int
  1634. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  1635. {
  1636. int diff = 0;
  1637. if (len > 0) {
  1638. do {
  1639. diff = lowercase(s1++) - lowercase(s2++);
  1640. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  1641. }
  1642. return diff;
  1643. }
  1644. int
  1645. mg_strcasecmp(const char *s1, const char *s2)
  1646. {
  1647. int diff;
  1648. do {
  1649. diff = lowercase(s1++) - lowercase(s2++);
  1650. } while (diff == 0 && s1[-1] != '\0');
  1651. return diff;
  1652. }
  1653. static char *
  1654. mg_strndup(const char *ptr, size_t len)
  1655. {
  1656. char *p;
  1657. if ((p = (char *)mg_malloc(len + 1)) != NULL) {
  1658. mg_strlcpy(p, ptr, len + 1);
  1659. }
  1660. return p;
  1661. }
  1662. static char *
  1663. mg_strdup(const char *str)
  1664. {
  1665. return mg_strndup(str, strlen(str));
  1666. }
  1667. static const char *
  1668. mg_strcasestr(const char *big_str, const char *small_str)
  1669. {
  1670. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  1671. if (big_len >= small_len) {
  1672. for (i = 0; i <= (big_len - small_len); i++) {
  1673. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  1674. return big_str + i;
  1675. }
  1676. }
  1677. }
  1678. return NULL;
  1679. }
  1680. /* Return null terminated string of given maximum length.
  1681. * Report errors if length is exceeded. */
  1682. static void
  1683. mg_vsnprintf(const struct mg_connection *conn,
  1684. int *truncated,
  1685. char *buf,
  1686. size_t buflen,
  1687. const char *fmt,
  1688. va_list ap)
  1689. {
  1690. int n, ok;
  1691. if (buflen == 0) {
  1692. return;
  1693. }
  1694. #ifdef __clang__
  1695. #pragma clang diagnostic push
  1696. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  1697. /* Using fmt as a non-literal is intended here, since it is mostly called
  1698. * indirectly by mg_snprintf */
  1699. #endif
  1700. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  1701. ok = (n >= 0) && ((size_t)n < buflen);
  1702. #ifdef __clang__
  1703. #pragma clang diagnostic pop
  1704. #endif
  1705. if (ok) {
  1706. if (truncated) {
  1707. *truncated = 0;
  1708. }
  1709. } else {
  1710. if (truncated) {
  1711. *truncated = 1;
  1712. }
  1713. mg_cry(conn,
  1714. "truncating vsnprintf buffer: [%.*s]",
  1715. (int)((buflen > 200) ? 200 : (buflen - 1)),
  1716. buf);
  1717. n = (int)buflen - 1;
  1718. }
  1719. buf[n] = '\0';
  1720. }
  1721. static void
  1722. mg_snprintf(const struct mg_connection *conn,
  1723. int *truncated,
  1724. char *buf,
  1725. size_t buflen,
  1726. const char *fmt,
  1727. ...)
  1728. {
  1729. va_list ap;
  1730. va_start(ap, fmt);
  1731. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  1732. va_end(ap);
  1733. }
  1734. static int
  1735. get_option_index(const char *name)
  1736. {
  1737. int i;
  1738. for (i = 0; config_options[i].name != NULL; i++) {
  1739. if (strcmp(config_options[i].name, name) == 0) {
  1740. return i;
  1741. }
  1742. }
  1743. return -1;
  1744. }
  1745. const char *
  1746. mg_get_option(const struct mg_context *ctx, const char *name)
  1747. {
  1748. int i;
  1749. if ((i = get_option_index(name)) == -1) {
  1750. return NULL;
  1751. } else if (!ctx || ctx->config[i] == NULL) {
  1752. return "";
  1753. } else {
  1754. return ctx->config[i];
  1755. }
  1756. }
  1757. struct mg_context *
  1758. mg_get_context(const struct mg_connection *conn)
  1759. {
  1760. return (conn == NULL) ? (struct mg_context *)NULL : (conn->ctx);
  1761. }
  1762. void *
  1763. mg_get_user_data(const struct mg_context *ctx)
  1764. {
  1765. return (ctx == NULL) ? NULL : ctx->user_data;
  1766. }
  1767. void
  1768. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  1769. {
  1770. if (conn != NULL) {
  1771. conn->request_info.conn_data = data;
  1772. }
  1773. }
  1774. void *
  1775. mg_get_user_connection_data(const struct mg_connection *conn)
  1776. {
  1777. if (conn != NULL) {
  1778. return conn->request_info.conn_data;
  1779. }
  1780. return NULL;
  1781. }
  1782. size_t
  1783. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  1784. {
  1785. size_t i;
  1786. if (!ctx) {
  1787. return 0;
  1788. }
  1789. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  1790. ssl[i] = ctx->listening_sockets[i].is_ssl;
  1791. ports[i] =
  1792. #if defined(USE_IPV6)
  1793. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  1794. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  1795. :
  1796. #endif
  1797. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  1798. }
  1799. return i;
  1800. }
  1801. int
  1802. mg_get_server_ports(const struct mg_context *ctx,
  1803. int size,
  1804. struct mg_server_ports *ports)
  1805. {
  1806. int i, cnt = 0;
  1807. if (size <= 0) {
  1808. return -1;
  1809. }
  1810. memset(ports, 0, sizeof(*ports) * (size_t)size);
  1811. if (!ctx) {
  1812. return -1;
  1813. }
  1814. if (!ctx->listening_sockets) {
  1815. return -1;
  1816. }
  1817. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  1818. ports[cnt].port =
  1819. #if defined(USE_IPV6)
  1820. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  1821. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  1822. :
  1823. #endif
  1824. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  1825. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  1826. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  1827. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  1828. /* IPv4 */
  1829. ports[cnt].protocol = 1;
  1830. cnt++;
  1831. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  1832. /* IPv6 */
  1833. ports[cnt].protocol = 3;
  1834. cnt++;
  1835. }
  1836. }
  1837. return cnt;
  1838. }
  1839. static void
  1840. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  1841. {
  1842. buf[0] = '\0';
  1843. if (!usa) {
  1844. return;
  1845. }
  1846. if (usa->sa.sa_family == AF_INET) {
  1847. getnameinfo(&usa->sa,
  1848. sizeof(usa->sin),
  1849. buf,
  1850. (unsigned)len,
  1851. NULL,
  1852. 0,
  1853. NI_NUMERICHOST);
  1854. }
  1855. #if defined(USE_IPV6)
  1856. else if (usa->sa.sa_family == AF_INET6) {
  1857. getnameinfo(&usa->sa,
  1858. sizeof(usa->sin6),
  1859. buf,
  1860. (unsigned)len,
  1861. NULL,
  1862. 0,
  1863. NI_NUMERICHOST);
  1864. }
  1865. #endif
  1866. }
  1867. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  1868. * included in all responses other than 100, 101, 5xx. */
  1869. static void
  1870. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  1871. {
  1872. struct tm *tm;
  1873. tm = ((t != NULL) ? gmtime(t) : NULL);
  1874. if (tm != NULL) {
  1875. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  1876. } else {
  1877. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  1878. buf[buf_len - 1] = '\0';
  1879. }
  1880. }
  1881. /* difftime for struct timespec. Return value is in seconds. */
  1882. static double
  1883. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  1884. {
  1885. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  1886. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  1887. }
  1888. /* Print error message to the opened error log stream. */
  1889. void
  1890. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  1891. {
  1892. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  1893. va_list ap;
  1894. struct file fi;
  1895. time_t timestamp;
  1896. va_start(ap, fmt);
  1897. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  1898. va_end(ap);
  1899. buf[sizeof(buf) - 1] = 0;
  1900. if (!conn) {
  1901. puts(buf);
  1902. return;
  1903. }
  1904. /* Do not lock when getting the callback value, here and below.
  1905. * I suppose this is fine, since function cannot disappear in the
  1906. * same way string option can. */
  1907. if ((conn->ctx->callbacks.log_message == NULL)
  1908. || (conn->ctx->callbacks.log_message(conn, buf) == 0)) {
  1909. if (conn->ctx->config[ERROR_LOG_FILE] != NULL) {
  1910. if (mg_fopen(conn, conn->ctx->config[ERROR_LOG_FILE], "a+", &fi)
  1911. == 0) {
  1912. fi.fp = NULL;
  1913. }
  1914. } else {
  1915. fi.fp = NULL;
  1916. }
  1917. if (fi.fp != NULL) {
  1918. flockfile(fi.fp);
  1919. timestamp = time(NULL);
  1920. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  1921. fprintf(fi.fp,
  1922. "[%010lu] [error] [client %s] ",
  1923. (unsigned long)timestamp,
  1924. src_addr);
  1925. if (conn->request_info.request_method != NULL) {
  1926. fprintf(fi.fp,
  1927. "%s %s: ",
  1928. conn->request_info.request_method,
  1929. conn->request_info.request_uri);
  1930. }
  1931. fprintf(fi.fp, "%s", buf);
  1932. fputc('\n', fi.fp);
  1933. fflush(fi.fp);
  1934. funlockfile(fi.fp);
  1935. mg_fclose(&fi);
  1936. }
  1937. }
  1938. }
  1939. /* Return fake connection structure. Used for logging, if connection
  1940. * is not applicable at the moment of logging. */
  1941. static struct mg_connection *
  1942. fc(struct mg_context *ctx)
  1943. {
  1944. static struct mg_connection fake_connection;
  1945. fake_connection.ctx = ctx;
  1946. return &fake_connection;
  1947. }
  1948. const char *
  1949. mg_version(void)
  1950. {
  1951. return CIVETWEB_VERSION;
  1952. }
  1953. const struct mg_request_info *
  1954. mg_get_request_info(const struct mg_connection *conn)
  1955. {
  1956. if (!conn) {
  1957. return NULL;
  1958. }
  1959. return &conn->request_info;
  1960. }
  1961. /* Skip the characters until one of the delimiters characters found.
  1962. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  1963. * Advance pointer to buffer to the next word. Return found 0-terminated word.
  1964. * Delimiters can be quoted with quotechar. */
  1965. static char *
  1966. skip_quoted(char **buf,
  1967. const char *delimiters,
  1968. const char *whitespace,
  1969. char quotechar)
  1970. {
  1971. char *p, *begin_word, *end_word, *end_whitespace;
  1972. begin_word = *buf;
  1973. end_word = begin_word + strcspn(begin_word, delimiters);
  1974. /* Check for quotechar */
  1975. if (end_word > begin_word) {
  1976. p = end_word - 1;
  1977. while (*p == quotechar) {
  1978. /* While the delimiter is quoted, look for the next delimiter. */
  1979. /* This happens, e.g., in calls from parse_auth_header,
  1980. * if the user name contains a " character. */
  1981. /* If there is anything beyond end_word, copy it. */
  1982. if (*end_word != '\0') {
  1983. size_t end_off = strcspn(end_word + 1, delimiters);
  1984. memmove(p, end_word, end_off + 1);
  1985. p += end_off; /* p must correspond to end_word - 1 */
  1986. end_word += end_off + 1;
  1987. } else {
  1988. *p = '\0';
  1989. break;
  1990. }
  1991. }
  1992. for (p++; p < end_word; p++) {
  1993. *p = '\0';
  1994. }
  1995. }
  1996. if (*end_word == '\0') {
  1997. *buf = end_word;
  1998. } else {
  1999. end_whitespace = end_word + 1 + strspn(end_word + 1, whitespace);
  2000. for (p = end_word; p < end_whitespace; p++) {
  2001. *p = '\0';
  2002. }
  2003. *buf = end_whitespace;
  2004. }
  2005. return begin_word;
  2006. }
  2007. /* Simplified version of skip_quoted without quote char
  2008. * and whitespace == delimiters */
  2009. static char *
  2010. skip(char **buf, const char *delimiters)
  2011. {
  2012. return skip_quoted(buf, delimiters, delimiters, 0);
  2013. }
  2014. /* Return HTTP header value, or NULL if not found. */
  2015. static const char *
  2016. get_header(const struct mg_request_info *ri, const char *name)
  2017. {
  2018. int i;
  2019. if (ri) {
  2020. for (i = 0; i < ri->num_headers; i++) {
  2021. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  2022. return ri->http_headers[i].value;
  2023. }
  2024. }
  2025. }
  2026. return NULL;
  2027. }
  2028. const char *
  2029. mg_get_header(const struct mg_connection *conn, const char *name)
  2030. {
  2031. if (!conn) {
  2032. return NULL;
  2033. }
  2034. return get_header(&conn->request_info, name);
  2035. }
  2036. /* A helper function for traversing a comma separated list of values.
  2037. * It returns a list pointer shifted to the next value, or NULL if the end
  2038. * of the list found.
  2039. * Value is stored in val vector. If value has form "x=y", then eq_val
  2040. * vector is initialized to point to the "y" part, and val vector length
  2041. * is adjusted to point only to "x". */
  2042. static const char *
  2043. next_option(const char *list, struct vec *val, struct vec *eq_val)
  2044. {
  2045. int end;
  2046. reparse:
  2047. if (val == NULL || list == NULL || *list == '\0') {
  2048. /* End of the list */
  2049. list = NULL;
  2050. } else {
  2051. /* Skip over leading LWS */
  2052. while (*list == ' ' || *list == '\t')
  2053. list++;
  2054. val->ptr = list;
  2055. if ((list = strchr(val->ptr, ',')) != NULL) {
  2056. /* Comma found. Store length and shift the list ptr */
  2057. val->len = ((size_t)(list - val->ptr));
  2058. list++;
  2059. } else {
  2060. /* This value is the last one */
  2061. list = val->ptr + strlen(val->ptr);
  2062. val->len = ((size_t)(list - val->ptr));
  2063. }
  2064. /* Adjust length for trailing LWS */
  2065. end = (int)val->len - 1;
  2066. while (end >= 0 && (val->ptr[end] == ' ' || val->ptr[end] == '\t'))
  2067. end--;
  2068. val->len = (size_t)(end + 1);
  2069. if (val->len == 0) {
  2070. /* Ignore any empty entries. */
  2071. goto reparse;
  2072. }
  2073. if (eq_val != NULL) {
  2074. /* Value has form "x=y", adjust pointers and lengths
  2075. * so that val points to "x", and eq_val points to "y". */
  2076. eq_val->len = 0;
  2077. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  2078. if (eq_val->ptr != NULL) {
  2079. eq_val->ptr++; /* Skip over '=' character */
  2080. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  2081. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  2082. }
  2083. }
  2084. }
  2085. return list;
  2086. }
  2087. /* A helper function for checking if a comma separated list of values contains
  2088. * the given option (case insensitvely).
  2089. * 'header' can be NULL, in which case false is returned. */
  2090. static int
  2091. header_has_option(const char *header, const char *option)
  2092. {
  2093. struct vec opt_vec;
  2094. struct vec eq_vec;
  2095. assert(option != NULL);
  2096. assert(option[0] != '\0');
  2097. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  2098. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  2099. return 1;
  2100. }
  2101. return 0;
  2102. }
  2103. /* Perform case-insensitive match of string against pattern */
  2104. static int
  2105. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  2106. {
  2107. const char *or_str;
  2108. size_t i;
  2109. int j, len, res;
  2110. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  2111. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  2112. return (res > 0) ? res : match_prefix(or_str + 1,
  2113. (size_t)((pattern + pattern_len)
  2114. - (or_str + 1)),
  2115. str);
  2116. }
  2117. for (i = 0, j = 0; i < pattern_len; i++, j++) {
  2118. if (pattern[i] == '?' && str[j] != '\0') {
  2119. continue;
  2120. } else if (pattern[i] == '$') {
  2121. return (str[j] == '\0') ? j : -1;
  2122. } else if (pattern[i] == '*') {
  2123. i++;
  2124. if (pattern[i] == '*') {
  2125. i++;
  2126. len = (int)strlen(str + j);
  2127. } else {
  2128. len = (int)strcspn(str + j, "/");
  2129. }
  2130. if (i == pattern_len) {
  2131. return j + len;
  2132. }
  2133. do {
  2134. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  2135. } while (res == -1 && len-- > 0);
  2136. return (res == -1) ? -1 : j + res + len;
  2137. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  2138. return -1;
  2139. }
  2140. }
  2141. return j;
  2142. }
  2143. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  2144. * This function must tolerate situations when connection info is not
  2145. * set up, for example if request parsing failed. */
  2146. static int
  2147. should_keep_alive(const struct mg_connection *conn)
  2148. {
  2149. if (conn != NULL) {
  2150. const char *http_version = conn->request_info.http_version;
  2151. const char *header = mg_get_header(conn, "Connection");
  2152. if (conn->must_close || conn->internal_error || conn->status_code == 401
  2153. || mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0
  2154. || (header != NULL && !header_has_option(header, "keep-alive"))
  2155. || (header == NULL && http_version
  2156. && 0 != strcmp(http_version, "1.1"))) {
  2157. return 0;
  2158. }
  2159. return 1;
  2160. }
  2161. return 0;
  2162. }
  2163. static int
  2164. should_decode_url(const struct mg_connection *conn)
  2165. {
  2166. if (!conn || !conn->ctx) {
  2167. return 0;
  2168. }
  2169. return (mg_strcasecmp(conn->ctx->config[DECODE_URL], "yes") == 0);
  2170. }
  2171. static const char *
  2172. suggest_connection_header(const struct mg_connection *conn)
  2173. {
  2174. return should_keep_alive(conn) ? "keep-alive" : "close";
  2175. }
  2176. static int
  2177. send_no_cache_header(struct mg_connection *conn)
  2178. {
  2179. /* Send all current and obsolete cache opt-out directives. */
  2180. return mg_printf(conn,
  2181. "Cache-Control: no-cache, no-store, "
  2182. "must-revalidate, private, max-age=0\r\n"
  2183. "Pragma: no-cache\r\n"
  2184. "Expires: 0\r\n");
  2185. }
  2186. static int
  2187. send_static_cache_header(struct mg_connection *conn)
  2188. {
  2189. #if !defined(NO_CACHING)
  2190. /* Read the server config to check how long a file may be cached.
  2191. * The configuration is in seconds. */
  2192. int max_age = atoi(conn->ctx->config[STATIC_FILE_MAX_AGE]);
  2193. if (max_age <= 0) {
  2194. /* 0 means "do not cache". All values <0 are reserved
  2195. * and may be used differently in the future. */
  2196. /* If a file should not be cached, do not only send
  2197. * max-age=0, but also pragmas and Expires headers. */
  2198. return send_no_cache_header(conn);
  2199. }
  2200. /* Use "Cache-Control: max-age" instead of "Expires" header.
  2201. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  2202. /* See also https://www.mnot.net/cache_docs/ */
  2203. /* According to RFC 2616, Section 14.21, caching times should not exceed
  2204. * one year. A year with 365 days corresponds to 31536000 seconds, a leap
  2205. * year to 31622400 seconds. For the moment, we just send whatever has
  2206. * been configured, still the behavior for >1 year should be considered
  2207. * as undefined. */
  2208. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  2209. #else /* NO_CACHING */
  2210. return send_no_cache_header(conn);
  2211. #endif /* !NO_CACHING */
  2212. }
  2213. static void handle_file_based_request(struct mg_connection *conn,
  2214. const char *path,
  2215. struct file *filep);
  2216. static int
  2217. mg_stat(struct mg_connection *conn, const char *path, struct file *filep);
  2218. const char *
  2219. mg_get_response_code_text(struct mg_connection *conn, int response_code)
  2220. {
  2221. /* See IANA HTTP status code assignment:
  2222. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  2223. */
  2224. switch (response_code) {
  2225. /* RFC2616 Section 10.1 - Informational 1xx */
  2226. case 100:
  2227. return "Continue"; /* RFC2616 Section 10.1.1 */
  2228. case 101:
  2229. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  2230. case 102:
  2231. return "Processing"; /* RFC2518 Section 10.1 */
  2232. /* RFC2616 Section 10.2 - Successful 2xx */
  2233. case 200:
  2234. return "OK"; /* RFC2616 Section 10.2.1 */
  2235. case 201:
  2236. return "Created"; /* RFC2616 Section 10.2.2 */
  2237. case 202:
  2238. return "Accepted"; /* RFC2616 Section 10.2.3 */
  2239. case 203:
  2240. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  2241. case 204:
  2242. return "No Content"; /* RFC2616 Section 10.2.5 */
  2243. case 205:
  2244. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  2245. case 206:
  2246. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  2247. case 207:
  2248. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1 */
  2249. case 208:
  2250. return "Already Reported"; /* RFC5842 Section 7.1 */
  2251. case 226:
  2252. return "IM used"; /* RFC3229 Section 10.4.1 */
  2253. /* RFC2616 Section 10.3 - Redirection 3xx */
  2254. case 300:
  2255. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  2256. case 301:
  2257. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  2258. case 302:
  2259. return "Found"; /* RFC2616 Section 10.3.3 */
  2260. case 303:
  2261. return "See Other"; /* RFC2616 Section 10.3.4 */
  2262. case 304:
  2263. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  2264. case 305:
  2265. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  2266. case 307:
  2267. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  2268. case 308:
  2269. return "Permanent Redirect"; /* RFC7238 Section 3 */
  2270. /* RFC2616 Section 10.4 - Client Error 4xx */
  2271. case 400:
  2272. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  2273. case 401:
  2274. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  2275. case 402:
  2276. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  2277. case 403:
  2278. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  2279. case 404:
  2280. return "Not Found"; /* RFC2616 Section 10.4.5 */
  2281. case 405:
  2282. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  2283. case 406:
  2284. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  2285. case 407:
  2286. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  2287. case 408:
  2288. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  2289. case 409:
  2290. return "Conflict"; /* RFC2616 Section 10.4.10 */
  2291. case 410:
  2292. return "Gone"; /* RFC2616 Section 10.4.11 */
  2293. case 411:
  2294. return "Length Required"; /* RFC2616 Section 10.4.12 */
  2295. case 412:
  2296. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  2297. case 413:
  2298. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  2299. case 414:
  2300. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  2301. case 415:
  2302. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  2303. case 416:
  2304. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17 */
  2305. case 417:
  2306. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  2307. case 421:
  2308. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  2309. case 422:
  2310. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  2311. * Section 11.2 */
  2312. case 423:
  2313. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  2314. case 424:
  2315. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  2316. * Section 11.4 */
  2317. case 426:
  2318. return "Upgrade Required"; /* RFC 2817 Section 4 */
  2319. case 428:
  2320. return "Precondition Required"; /* RFC 6585, Section 3 */
  2321. case 429:
  2322. return "Too Many Requests"; /* RFC 6585, Section 4 */
  2323. case 431:
  2324. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  2325. case 451:
  2326. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  2327. * Section 3 */
  2328. /* RFC2616 Section 10.5 - Server Error 5xx */
  2329. case 500:
  2330. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  2331. case 501:
  2332. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  2333. case 502:
  2334. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  2335. case 503:
  2336. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  2337. case 504:
  2338. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  2339. case 505:
  2340. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  2341. case 506:
  2342. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  2343. case 507:
  2344. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  2345. * Section 11.5 */
  2346. case 508:
  2347. return "Loop Detected"; /* RFC5842 Section 7.1 */
  2348. case 510:
  2349. return "Not Extended"; /* RFC 2774, Section 7 */
  2350. case 511:
  2351. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  2352. /* Other status codes, not shown in the IANA HTTP status code assignment.
  2353. * E.g., "de facto" standards due to common use, ... */
  2354. case 418:
  2355. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  2356. case 419:
  2357. return "Authentication Timeout"; /* common use */
  2358. case 420:
  2359. return "Enhance Your Calm"; /* common use */
  2360. case 440:
  2361. return "Login Timeout"; /* common use */
  2362. case 509:
  2363. return "Bandwidth Limit Exceeded"; /* common use */
  2364. default:
  2365. /* This error code is unknown. This should not happen. */
  2366. if (conn) {
  2367. mg_cry(conn, "Unknown HTTP response code: %u", response_code);
  2368. }
  2369. /* Return at least a category according to RFC 2616 Section 10. */
  2370. if (response_code >= 100 && response_code < 200) {
  2371. /* Unknown informational status code */
  2372. return "Information";
  2373. }
  2374. if (response_code >= 200 && response_code < 300) {
  2375. /* Unknown success code */
  2376. return "Success";
  2377. }
  2378. if (response_code >= 300 && response_code < 400) {
  2379. /* Unknown redirection code */
  2380. return "Redirection";
  2381. }
  2382. if (response_code >= 400 && response_code < 500) {
  2383. /* Unknown request error code */
  2384. return "Client Error";
  2385. }
  2386. if (response_code >= 500 && response_code < 600) {
  2387. /* Unknown server error code */
  2388. return "Server Error";
  2389. }
  2390. /* Response code not even within reasonable range */
  2391. return "";
  2392. }
  2393. }
  2394. static void send_http_error(struct mg_connection *,
  2395. int,
  2396. PRINTF_FORMAT_STRING(const char *fmt),
  2397. ...) PRINTF_ARGS(3, 4);
  2398. static void
  2399. send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  2400. {
  2401. char buf[MG_BUF_LEN];
  2402. va_list ap;
  2403. int len, i, page_handler_found, scope, truncated;
  2404. char date[64];
  2405. time_t curtime = time(NULL);
  2406. const char *error_handler = NULL;
  2407. struct file error_page_file = STRUCT_FILE_INITIALIZER;
  2408. const char *error_page_file_ext, *tstr;
  2409. const char *status_text = mg_get_response_code_text(conn, status);
  2410. if (conn == NULL) {
  2411. return;
  2412. }
  2413. conn->status_code = status;
  2414. if (conn->in_error_handler || conn->ctx->callbacks.http_error == NULL
  2415. || conn->ctx->callbacks.http_error(conn, status)) {
  2416. if (!conn->in_error_handler) {
  2417. /* Send user defined error pages, if defined */
  2418. error_handler = conn->ctx->config[ERROR_PAGES];
  2419. error_page_file_ext = conn->ctx->config[INDEX_FILES];
  2420. page_handler_found = 0;
  2421. if (error_handler != NULL) {
  2422. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  2423. switch (scope) {
  2424. case 1: /* Handler for specific error, e.g. 404 error */
  2425. mg_snprintf(conn,
  2426. &truncated,
  2427. buf,
  2428. sizeof(buf) - 32,
  2429. "%serror%03u.",
  2430. error_handler,
  2431. status);
  2432. break;
  2433. case 2: /* Handler for error group, e.g., 5xx error handler
  2434. * for all server errors (500-599) */
  2435. mg_snprintf(conn,
  2436. &truncated,
  2437. buf,
  2438. sizeof(buf) - 32,
  2439. "%serror%01uxx.",
  2440. error_handler,
  2441. status / 100);
  2442. break;
  2443. default: /* Handler for all errors */
  2444. mg_snprintf(conn,
  2445. &truncated,
  2446. buf,
  2447. sizeof(buf) - 32,
  2448. "%serror.",
  2449. error_handler);
  2450. break;
  2451. }
  2452. /* String truncation in buf may only occur if error_handler
  2453. * is too long. This string is from the config, not from a
  2454. * client. */
  2455. (void)truncated;
  2456. len = (int)strlen(buf);
  2457. tstr = strchr(error_page_file_ext, '.');
  2458. while (tstr) {
  2459. for (i = 1; i < 32 && tstr[i] != 0 && tstr[i] != ',';
  2460. i++)
  2461. buf[len + i - 1] = tstr[i];
  2462. buf[len + i - 1] = 0;
  2463. if (mg_stat(conn, buf, &error_page_file)) {
  2464. page_handler_found = 1;
  2465. break;
  2466. }
  2467. tstr = strchr(tstr + i, '.');
  2468. }
  2469. }
  2470. }
  2471. if (page_handler_found) {
  2472. conn->in_error_handler = 1;
  2473. handle_file_based_request(conn, buf, &error_page_file);
  2474. conn->in_error_handler = 0;
  2475. return;
  2476. }
  2477. }
  2478. /* No custom error page. Send default error page. */
  2479. gmt_time_string(date, sizeof(date), &curtime);
  2480. conn->must_close = 1;
  2481. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  2482. send_no_cache_header(conn);
  2483. mg_printf(conn,
  2484. "Date: %s\r\n"
  2485. "Connection: close\r\n\r\n",
  2486. date);
  2487. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  2488. if (status > 199 && status != 204 && status != 304) {
  2489. mg_printf(conn, "Error %d: %s\n", status, status_text);
  2490. if (fmt != NULL) {
  2491. va_start(ap, fmt);
  2492. mg_vsnprintf(conn, NULL, buf, sizeof(buf), fmt, ap);
  2493. va_end(ap);
  2494. mg_write(conn, buf, strlen(buf));
  2495. DEBUG_TRACE("Error %i - [%s]", status, buf);
  2496. }
  2497. } else {
  2498. /* No body allowed. Close the connection. */
  2499. DEBUG_TRACE("Error %i", status);
  2500. }
  2501. }
  2502. }
  2503. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  2504. /* Create substitutes for POSIX functions in Win32. */
  2505. #if defined(__MINGW32__)
  2506. /* Show no warning in case system functions are not used. */
  2507. #pragma GCC diagnostic push
  2508. #pragma GCC diagnostic ignored "-Wunused-function"
  2509. #endif
  2510. static int
  2511. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  2512. {
  2513. (void)unused;
  2514. *mutex = CreateMutex(NULL, FALSE, NULL);
  2515. return (*mutex == NULL) ? -1 : 0;
  2516. }
  2517. static int
  2518. pthread_mutex_destroy(pthread_mutex_t *mutex)
  2519. {
  2520. return (CloseHandle(*mutex) == 0) ? -1 : 0;
  2521. }
  2522. static int
  2523. pthread_mutex_lock(pthread_mutex_t *mutex)
  2524. {
  2525. return (WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0) ? 0 : -1;
  2526. }
  2527. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  2528. static int
  2529. pthread_mutex_trylock(pthread_mutex_t *mutex)
  2530. {
  2531. switch (WaitForSingleObject(*mutex, 0)) {
  2532. case WAIT_OBJECT_0:
  2533. return 0;
  2534. case WAIT_TIMEOUT:
  2535. return -2; /* EBUSY */
  2536. }
  2537. return -1;
  2538. }
  2539. #endif
  2540. static int
  2541. pthread_mutex_unlock(pthread_mutex_t *mutex)
  2542. {
  2543. return (ReleaseMutex(*mutex) == 0) ? -1 : 0;
  2544. }
  2545. #ifndef WIN_PTHREADS_TIME_H
  2546. static int
  2547. clock_gettime(clockid_t clk_id, struct timespec *tp)
  2548. {
  2549. FILETIME ft;
  2550. ULARGE_INTEGER li;
  2551. BOOL ok = FALSE;
  2552. double d;
  2553. static double perfcnt_per_sec = 0.0;
  2554. if (tp) {
  2555. memset(tp, 0, sizeof(*tp));
  2556. if (clk_id == CLOCK_REALTIME) {
  2557. GetSystemTimeAsFileTime(&ft);
  2558. li.LowPart = ft.dwLowDateTime;
  2559. li.HighPart = ft.dwHighDateTime;
  2560. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  2561. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  2562. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  2563. ok = TRUE;
  2564. } else if (clk_id == CLOCK_MONOTONIC) {
  2565. if (perfcnt_per_sec == 0.0) {
  2566. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  2567. perfcnt_per_sec = 1.0 / li.QuadPart;
  2568. }
  2569. if (perfcnt_per_sec != 0.0) {
  2570. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  2571. d = li.QuadPart * perfcnt_per_sec;
  2572. tp->tv_sec = (time_t)d;
  2573. d -= tp->tv_sec;
  2574. tp->tv_nsec = (long)(d * 1.0E9);
  2575. ok = TRUE;
  2576. }
  2577. }
  2578. }
  2579. return ok ? 0 : -1;
  2580. }
  2581. #endif
  2582. static int
  2583. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  2584. {
  2585. (void)unused;
  2586. InitializeCriticalSection(&cv->threadIdSec);
  2587. cv->waiting_thread = NULL;
  2588. return 0;
  2589. }
  2590. static int
  2591. pthread_cond_timedwait(pthread_cond_t *cv,
  2592. pthread_mutex_t *mutex,
  2593. const struct timespec *abstime)
  2594. {
  2595. struct mg_workerTLS **ptls,
  2596. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2597. int ok;
  2598. struct timespec tsnow;
  2599. int64_t nsnow, nswaitabs, nswaitrel;
  2600. DWORD mswaitrel;
  2601. EnterCriticalSection(&cv->threadIdSec);
  2602. /* Add this thread to cv's waiting list */
  2603. ptls = &cv->waiting_thread;
  2604. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  2605. ;
  2606. tls->next_waiting_thread = NULL;
  2607. *ptls = tls;
  2608. LeaveCriticalSection(&cv->threadIdSec);
  2609. if (abstime) {
  2610. clock_gettime(CLOCK_REALTIME, &tsnow);
  2611. nsnow = (((int64_t)tsnow.tv_sec) * 1000000000) + tsnow.tv_nsec;
  2612. nswaitabs =
  2613. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  2614. nswaitrel = nswaitabs - nsnow;
  2615. if (nswaitrel < 0) {
  2616. nswaitrel = 0;
  2617. }
  2618. mswaitrel = (DWORD)(nswaitrel / 1000000);
  2619. } else {
  2620. mswaitrel = INFINITE;
  2621. }
  2622. pthread_mutex_unlock(mutex);
  2623. ok = (WAIT_OBJECT_0
  2624. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  2625. if (!ok) {
  2626. ok = 1;
  2627. EnterCriticalSection(&cv->threadIdSec);
  2628. ptls = &cv->waiting_thread;
  2629. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  2630. if (*ptls == tls) {
  2631. *ptls = tls->next_waiting_thread;
  2632. ok = 0;
  2633. break;
  2634. }
  2635. }
  2636. LeaveCriticalSection(&cv->threadIdSec);
  2637. if (ok) {
  2638. WaitForSingleObject(tls->pthread_cond_helper_mutex, INFINITE);
  2639. }
  2640. }
  2641. /* This thread has been removed from cv's waiting list */
  2642. pthread_mutex_lock(mutex);
  2643. return ok ? 0 : -1;
  2644. }
  2645. static int
  2646. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  2647. {
  2648. return pthread_cond_timedwait(cv, mutex, NULL);
  2649. }
  2650. static int
  2651. pthread_cond_signal(pthread_cond_t *cv)
  2652. {
  2653. HANDLE wkup = NULL;
  2654. BOOL ok = FALSE;
  2655. EnterCriticalSection(&cv->threadIdSec);
  2656. if (cv->waiting_thread) {
  2657. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  2658. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  2659. ok = SetEvent(wkup);
  2660. assert(ok);
  2661. }
  2662. LeaveCriticalSection(&cv->threadIdSec);
  2663. return ok ? 0 : 1;
  2664. }
  2665. static int
  2666. pthread_cond_broadcast(pthread_cond_t *cv)
  2667. {
  2668. EnterCriticalSection(&cv->threadIdSec);
  2669. while (cv->waiting_thread) {
  2670. pthread_cond_signal(cv);
  2671. }
  2672. LeaveCriticalSection(&cv->threadIdSec);
  2673. return 0;
  2674. }
  2675. static int
  2676. pthread_cond_destroy(pthread_cond_t *cv)
  2677. {
  2678. EnterCriticalSection(&cv->threadIdSec);
  2679. assert(cv->waiting_thread == NULL);
  2680. LeaveCriticalSection(&cv->threadIdSec);
  2681. DeleteCriticalSection(&cv->threadIdSec);
  2682. return 0;
  2683. }
  2684. #ifdef ALTERNATIVE_QUEUE
  2685. static void *
  2686. event_create(void)
  2687. {
  2688. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  2689. }
  2690. static int
  2691. event_wait(void *eventhdl)
  2692. {
  2693. int res = WaitForSingleObject((HANDLE)eventhdl, INFINITE);
  2694. return (res == WAIT_OBJECT_0);
  2695. }
  2696. static int
  2697. event_signal(void *eventhdl)
  2698. {
  2699. return (int)SetEvent((HANDLE)eventhdl);
  2700. }
  2701. static void
  2702. event_destroy(void *eventhdl)
  2703. {
  2704. CloseHandle((HANDLE)eventhdl);
  2705. }
  2706. #endif
  2707. #if defined(__MINGW32__)
  2708. /* Enable unused function warning again */
  2709. #pragma GCC diagnostic pop
  2710. #endif
  2711. /* For Windows, change all slashes to backslashes in path names. */
  2712. static void
  2713. change_slashes_to_backslashes(char *path)
  2714. {
  2715. int i;
  2716. for (i = 0; path[i] != '\0'; i++) {
  2717. if (path[i] == '/') {
  2718. path[i] = '\\';
  2719. }
  2720. /* remove double backslash (check i > 0 to preserve UNC paths,
  2721. * like \\server\file.txt) */
  2722. if ((path[i] == '\\') && (i > 0)) {
  2723. while (path[i + 1] == '\\' || path[i + 1] == '/') {
  2724. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  2725. }
  2726. }
  2727. }
  2728. }
  2729. static int
  2730. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  2731. {
  2732. int diff;
  2733. do {
  2734. diff = tolower(*s1) - tolower(*s2);
  2735. s1++;
  2736. s2++;
  2737. } while (diff == 0 && s1[-1] != '\0');
  2738. return diff;
  2739. }
  2740. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  2741. * wbuf and wbuf_len is a target buffer and its length. */
  2742. static void
  2743. path_to_unicode(const struct mg_connection *conn,
  2744. const char *path,
  2745. wchar_t *wbuf,
  2746. size_t wbuf_len)
  2747. {
  2748. char buf[PATH_MAX], buf2[PATH_MAX];
  2749. wchar_t wbuf2[MAX_PATH + 1];
  2750. DWORD long_len, err;
  2751. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  2752. mg_strlcpy(buf, path, sizeof(buf));
  2753. change_slashes_to_backslashes(buf);
  2754. /* Convert to Unicode and back. If doubly-converted string does not
  2755. * match the original, something is fishy, reject. */
  2756. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  2757. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  2758. WideCharToMultiByte(
  2759. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  2760. if (strcmp(buf, buf2) != 0) {
  2761. wbuf[0] = L'\0';
  2762. }
  2763. /* TODO: Add a configuration to switch between case sensitive and
  2764. * case insensitive URIs for Windows server. */
  2765. /*
  2766. if (conn) {
  2767. if (conn->ctx->config[WINDOWS_CASE_SENSITIVE]) {
  2768. fcompare = wcscmp;
  2769. }
  2770. }
  2771. */
  2772. (void)conn; /* conn is currently unused */
  2773. #if !defined(_WIN32_WCE)
  2774. /* Only accept a full file path, not a Windows short (8.3) path. */
  2775. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  2776. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  2777. if (long_len == 0) {
  2778. err = GetLastError();
  2779. if (err == ERROR_FILE_NOT_FOUND) {
  2780. /* File does not exist. This is not always a problem here. */
  2781. return;
  2782. }
  2783. }
  2784. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  2785. /* Short name is used. */
  2786. wbuf[0] = L'\0';
  2787. }
  2788. #else
  2789. (void)long_len;
  2790. (void)wbuf2;
  2791. (void)err;
  2792. if (strchr(path, '~')) {
  2793. wbuf[0] = L'\0';
  2794. }
  2795. #endif
  2796. }
  2797. /* Windows happily opens files with some garbage at the end of file name.
  2798. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  2799. * "a.cgi", despite one would expect an error back.
  2800. * This function returns non-0 if path ends with some garbage. */
  2801. static int
  2802. path_cannot_disclose_cgi(const char *path)
  2803. {
  2804. static const char *allowed_last_characters = "_-";
  2805. int last = path[strlen(path) - 1];
  2806. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  2807. }
  2808. static int
  2809. mg_stat(struct mg_connection *conn, const char *path, struct file *filep)
  2810. {
  2811. wchar_t wbuf[PATH_MAX];
  2812. WIN32_FILE_ATTRIBUTE_DATA info;
  2813. time_t creation_time;
  2814. if (!filep) {
  2815. return 0;
  2816. }
  2817. memset(filep, 0, sizeof(*filep));
  2818. if (conn && is_file_in_memory(conn, path, filep)) {
  2819. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  2820. * memset */
  2821. filep->last_modified = time(NULL);
  2822. /* last_modified = now ... assumes the file may change during runtime,
  2823. * so every mg_fopen call may return different data */
  2824. /* last_modified = conn->ctx.start_time;
  2825. * May be used it the data does not change during runtime. This allows
  2826. * browser caching. Since we do not know, we have to assume the file
  2827. * in memory may change. */
  2828. return 1;
  2829. }
  2830. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2831. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  2832. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  2833. filep->last_modified =
  2834. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  2835. info.ftLastWriteTime.dwHighDateTime);
  2836. /* On Windows, the file creation time can be higher than the
  2837. * modification time, e.g. when a file is copied.
  2838. * Since the Last-Modified timestamp is used for caching
  2839. * it should be based on the most recent timestamp. */
  2840. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  2841. info.ftCreationTime.dwHighDateTime);
  2842. if (creation_time > filep->last_modified) {
  2843. filep->last_modified = creation_time;
  2844. }
  2845. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  2846. /* If file name is fishy, reset the file structure and return
  2847. * error.
  2848. * Note it is important to reset, not just return the error, cause
  2849. * functions like is_file_opened() check the struct. */
  2850. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  2851. memset(filep, 0, sizeof(*filep));
  2852. return 0;
  2853. }
  2854. return 1;
  2855. }
  2856. return 0;
  2857. }
  2858. static int
  2859. mg_remove(const struct mg_connection *conn, const char *path)
  2860. {
  2861. wchar_t wbuf[PATH_MAX];
  2862. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2863. return DeleteFileW(wbuf) ? 0 : -1;
  2864. }
  2865. static int
  2866. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  2867. {
  2868. wchar_t wbuf[PATH_MAX];
  2869. (void)mode;
  2870. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2871. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  2872. }
  2873. /* Create substitutes for POSIX functions in Win32. */
  2874. #if defined(__MINGW32__)
  2875. /* Show no warning in case system functions are not used. */
  2876. #pragma GCC diagnostic push
  2877. #pragma GCC diagnostic ignored "-Wunused-function"
  2878. #endif
  2879. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  2880. static DIR *
  2881. mg_opendir(const struct mg_connection *conn, const char *name)
  2882. {
  2883. DIR *dir = NULL;
  2884. wchar_t wpath[PATH_MAX];
  2885. DWORD attrs;
  2886. if (name == NULL) {
  2887. SetLastError(ERROR_BAD_ARGUMENTS);
  2888. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  2889. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  2890. } else {
  2891. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  2892. attrs = GetFileAttributesW(wpath);
  2893. if (attrs != 0xFFFFFFFF && ((attrs & FILE_ATTRIBUTE_DIRECTORY)
  2894. == FILE_ATTRIBUTE_DIRECTORY)) {
  2895. (void)wcscat(wpath, L"\\*");
  2896. dir->handle = FindFirstFileW(wpath, &dir->info);
  2897. dir->result.d_name[0] = '\0';
  2898. } else {
  2899. mg_free(dir);
  2900. dir = NULL;
  2901. }
  2902. }
  2903. return dir;
  2904. }
  2905. static int
  2906. mg_closedir(DIR *dir)
  2907. {
  2908. int result = 0;
  2909. if (dir != NULL) {
  2910. if (dir->handle != INVALID_HANDLE_VALUE)
  2911. result = FindClose(dir->handle) ? 0 : -1;
  2912. mg_free(dir);
  2913. } else {
  2914. result = -1;
  2915. SetLastError(ERROR_BAD_ARGUMENTS);
  2916. }
  2917. return result;
  2918. }
  2919. static struct dirent *
  2920. mg_readdir(DIR *dir)
  2921. {
  2922. struct dirent *result = 0;
  2923. if (dir) {
  2924. if (dir->handle != INVALID_HANDLE_VALUE) {
  2925. result = &dir->result;
  2926. (void)WideCharToMultiByte(CP_UTF8,
  2927. 0,
  2928. dir->info.cFileName,
  2929. -1,
  2930. result->d_name,
  2931. sizeof(result->d_name),
  2932. NULL,
  2933. NULL);
  2934. if (!FindNextFileW(dir->handle, &dir->info)) {
  2935. (void)FindClose(dir->handle);
  2936. dir->handle = INVALID_HANDLE_VALUE;
  2937. }
  2938. } else {
  2939. SetLastError(ERROR_FILE_NOT_FOUND);
  2940. }
  2941. } else {
  2942. SetLastError(ERROR_BAD_ARGUMENTS);
  2943. }
  2944. return result;
  2945. }
  2946. #ifndef HAVE_POLL
  2947. static int
  2948. poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  2949. {
  2950. struct timeval tv;
  2951. fd_set set;
  2952. unsigned int i;
  2953. int result;
  2954. SOCKET maxfd = 0;
  2955. memset(&tv, 0, sizeof(tv));
  2956. tv.tv_sec = milliseconds / 1000;
  2957. tv.tv_usec = (milliseconds % 1000) * 1000;
  2958. FD_ZERO(&set);
  2959. for (i = 0; i < n; i++) {
  2960. FD_SET((SOCKET)pfd[i].fd, &set);
  2961. pfd[i].revents = 0;
  2962. if (pfd[i].fd > maxfd) {
  2963. maxfd = pfd[i].fd;
  2964. }
  2965. }
  2966. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  2967. for (i = 0; i < n; i++) {
  2968. if (FD_ISSET(pfd[i].fd, &set)) {
  2969. pfd[i].revents = POLLIN;
  2970. }
  2971. }
  2972. }
  2973. return result;
  2974. }
  2975. #endif /* HAVE_POLL */
  2976. #if defined(__MINGW32__)
  2977. /* Enable unused function warning again */
  2978. #pragma GCC diagnostic pop
  2979. #endif
  2980. static void
  2981. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  2982. {
  2983. (void)conn; /* Unused. */
  2984. #if defined(_WIN32_WCE)
  2985. (void)sock;
  2986. #else
  2987. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  2988. #endif
  2989. }
  2990. int
  2991. mg_start_thread(mg_thread_func_t f, void *p)
  2992. {
  2993. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  2994. /* Compile-time option to control stack size, e.g. -DUSE_STACK_SIZE=16384
  2995. */
  2996. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  2997. == ((uintptr_t)(-1L)))
  2998. ? -1
  2999. : 0);
  3000. #else
  3001. return (
  3002. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  3003. ? -1
  3004. : 0);
  3005. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3006. }
  3007. /* Start a thread storing the thread context. */
  3008. static int
  3009. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  3010. void *p,
  3011. pthread_t *threadidptr)
  3012. {
  3013. uintptr_t uip;
  3014. HANDLE threadhandle;
  3015. int result = -1;
  3016. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  3017. threadhandle = (HANDLE)uip;
  3018. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  3019. *threadidptr = threadhandle;
  3020. result = 0;
  3021. }
  3022. return result;
  3023. }
  3024. /* Wait for a thread to finish. */
  3025. static int
  3026. mg_join_thread(pthread_t threadid)
  3027. {
  3028. int result;
  3029. DWORD dwevent;
  3030. result = -1;
  3031. dwevent = WaitForSingleObject(threadid, INFINITE);
  3032. if (dwevent == WAIT_FAILED) {
  3033. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  3034. } else {
  3035. if (dwevent == WAIT_OBJECT_0) {
  3036. CloseHandle(threadid);
  3037. result = 0;
  3038. }
  3039. }
  3040. return result;
  3041. }
  3042. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  3043. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  3044. /* Create substitutes for POSIX functions in Win32. */
  3045. #if defined(__MINGW32__)
  3046. /* Show no warning in case system functions are not used. */
  3047. #pragma GCC diagnostic push
  3048. #pragma GCC diagnostic ignored "-Wunused-function"
  3049. #endif
  3050. static HANDLE
  3051. dlopen(const char *dll_name, int flags)
  3052. {
  3053. wchar_t wbuf[PATH_MAX];
  3054. (void)flags;
  3055. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  3056. return LoadLibraryW(wbuf);
  3057. }
  3058. static int
  3059. dlclose(void *handle)
  3060. {
  3061. int result;
  3062. if (FreeLibrary((HMODULE)handle) != 0) {
  3063. result = 0;
  3064. } else {
  3065. result = -1;
  3066. }
  3067. return result;
  3068. }
  3069. #if defined(__MINGW32__)
  3070. /* Enable unused function warning again */
  3071. #pragma GCC diagnostic pop
  3072. #endif
  3073. #endif
  3074. #if !defined(NO_CGI)
  3075. #define SIGKILL (0)
  3076. static int
  3077. kill(pid_t pid, int sig_num)
  3078. {
  3079. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  3080. (void)CloseHandle((HANDLE)pid);
  3081. return 0;
  3082. }
  3083. static void
  3084. trim_trailing_whitespaces(char *s)
  3085. {
  3086. char *e = s + strlen(s) - 1;
  3087. while (e > s && isspace(*(unsigned char *)e)) {
  3088. *e-- = '\0';
  3089. }
  3090. }
  3091. static pid_t
  3092. spawn_process(struct mg_connection *conn,
  3093. const char *prog,
  3094. char *envblk,
  3095. char *envp[],
  3096. int fdin[2],
  3097. int fdout[2],
  3098. int fderr[2],
  3099. const char *dir)
  3100. {
  3101. HANDLE me;
  3102. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  3103. cmdline[PATH_MAX], buf[PATH_MAX];
  3104. int truncated;
  3105. struct file file = STRUCT_FILE_INITIALIZER;
  3106. STARTUPINFOA si;
  3107. PROCESS_INFORMATION pi = {0};
  3108. (void)envp;
  3109. memset(&si, 0, sizeof(si));
  3110. si.cb = sizeof(si);
  3111. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  3112. si.wShowWindow = SW_HIDE;
  3113. me = GetCurrentProcess();
  3114. DuplicateHandle(me,
  3115. (HANDLE)_get_osfhandle(fdin[0]),
  3116. me,
  3117. &si.hStdInput,
  3118. 0,
  3119. TRUE,
  3120. DUPLICATE_SAME_ACCESS);
  3121. DuplicateHandle(me,
  3122. (HANDLE)_get_osfhandle(fdout[1]),
  3123. me,
  3124. &si.hStdOutput,
  3125. 0,
  3126. TRUE,
  3127. DUPLICATE_SAME_ACCESS);
  3128. DuplicateHandle(me,
  3129. (HANDLE)_get_osfhandle(fderr[1]),
  3130. me,
  3131. &si.hStdError,
  3132. 0,
  3133. TRUE,
  3134. DUPLICATE_SAME_ACCESS);
  3135. /* Mark handles that should not be inherited. See
  3136. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  3137. */
  3138. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  3139. HANDLE_FLAG_INHERIT,
  3140. 0);
  3141. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  3142. HANDLE_FLAG_INHERIT,
  3143. 0);
  3144. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  3145. HANDLE_FLAG_INHERIT,
  3146. 0);
  3147. /* If CGI file is a script, try to read the interpreter line */
  3148. interp = conn->ctx->config[CGI_INTERPRETER];
  3149. if (interp == NULL) {
  3150. buf[0] = buf[1] = '\0';
  3151. /* Read the first line of the script into the buffer */
  3152. mg_snprintf(
  3153. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  3154. if (truncated) {
  3155. pi.hProcess = (pid_t)-1;
  3156. goto spawn_cleanup;
  3157. }
  3158. if (mg_fopen(conn, cmdline, "r", &file)) {
  3159. p = (char *)file.membuf;
  3160. mg_fgets(buf, sizeof(buf), &file, &p);
  3161. mg_fclose(&file);
  3162. buf[sizeof(buf) - 1] = '\0';
  3163. }
  3164. if (buf[0] == '#' && buf[1] == '!') {
  3165. trim_trailing_whitespaces(buf + 2);
  3166. } else {
  3167. buf[2] = '\0';
  3168. }
  3169. interp = buf + 2;
  3170. }
  3171. if (interp[0] != '\0') {
  3172. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  3173. interp = full_interp;
  3174. }
  3175. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  3176. if (interp[0] != '\0') {
  3177. mg_snprintf(conn,
  3178. &truncated,
  3179. cmdline,
  3180. sizeof(cmdline),
  3181. "\"%s\" \"%s\\%s\"",
  3182. interp,
  3183. full_dir,
  3184. prog);
  3185. } else {
  3186. mg_snprintf(conn,
  3187. &truncated,
  3188. cmdline,
  3189. sizeof(cmdline),
  3190. "\"%s\\%s\"",
  3191. full_dir,
  3192. prog);
  3193. }
  3194. if (truncated) {
  3195. pi.hProcess = (pid_t)-1;
  3196. goto spawn_cleanup;
  3197. }
  3198. DEBUG_TRACE("Running [%s]", cmdline);
  3199. if (CreateProcessA(NULL,
  3200. cmdline,
  3201. NULL,
  3202. NULL,
  3203. TRUE,
  3204. CREATE_NEW_PROCESS_GROUP,
  3205. envblk,
  3206. NULL,
  3207. &si,
  3208. &pi) == 0) {
  3209. mg_cry(
  3210. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  3211. pi.hProcess = (pid_t)-1;
  3212. /* goto spawn_cleanup; */
  3213. }
  3214. spawn_cleanup:
  3215. (void)CloseHandle(si.hStdOutput);
  3216. (void)CloseHandle(si.hStdError);
  3217. (void)CloseHandle(si.hStdInput);
  3218. if (pi.hThread != NULL) {
  3219. (void)CloseHandle(pi.hThread);
  3220. }
  3221. return (pid_t)pi.hProcess;
  3222. }
  3223. #endif /* !NO_CGI */
  3224. static int
  3225. set_non_blocking_mode(SOCKET sock)
  3226. {
  3227. unsigned long on = 1;
  3228. return ioctlsocket(sock, (long)FIONBIO, &on);
  3229. }
  3230. #else
  3231. static int
  3232. mg_stat(struct mg_connection *conn, const char *path, struct file *filep)
  3233. {
  3234. struct stat st;
  3235. if (!filep) {
  3236. return 0;
  3237. }
  3238. memset(filep, 0, sizeof(*filep));
  3239. if (conn && is_file_in_memory(conn, path, filep)) {
  3240. return 1;
  3241. }
  3242. if (0 == stat(path, &st)) {
  3243. filep->size = (uint64_t)(st.st_size);
  3244. filep->last_modified = st.st_mtime;
  3245. filep->is_directory = S_ISDIR(st.st_mode);
  3246. return 1;
  3247. }
  3248. return 0;
  3249. }
  3250. static void
  3251. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  3252. {
  3253. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  3254. if (conn) {
  3255. mg_cry(conn,
  3256. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  3257. __func__,
  3258. strerror(ERRNO));
  3259. }
  3260. }
  3261. }
  3262. int
  3263. mg_start_thread(mg_thread_func_t func, void *param)
  3264. {
  3265. pthread_t thread_id;
  3266. pthread_attr_t attr;
  3267. int result;
  3268. (void)pthread_attr_init(&attr);
  3269. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  3270. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3271. /* Compile-time option to control stack size,
  3272. * e.g. -DUSE_STACK_SIZE=16384 */
  3273. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3274. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3275. result = pthread_create(&thread_id, &attr, func, param);
  3276. pthread_attr_destroy(&attr);
  3277. return result;
  3278. }
  3279. /* Start a thread storing the thread context. */
  3280. static int
  3281. mg_start_thread_with_id(mg_thread_func_t func,
  3282. void *param,
  3283. pthread_t *threadidptr)
  3284. {
  3285. pthread_t thread_id;
  3286. pthread_attr_t attr;
  3287. int result;
  3288. (void)pthread_attr_init(&attr);
  3289. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3290. /* Compile-time option to control stack size,
  3291. * e.g. -DUSE_STACK_SIZE=16384 */
  3292. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3293. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  3294. result = pthread_create(&thread_id, &attr, func, param);
  3295. pthread_attr_destroy(&attr);
  3296. if ((result == 0) && (threadidptr != NULL)) {
  3297. *threadidptr = thread_id;
  3298. }
  3299. return result;
  3300. }
  3301. /* Wait for a thread to finish. */
  3302. static int
  3303. mg_join_thread(pthread_t threadid)
  3304. {
  3305. int result;
  3306. result = pthread_join(threadid, NULL);
  3307. return result;
  3308. }
  3309. #ifndef NO_CGI
  3310. static pid_t
  3311. spawn_process(struct mg_connection *conn,
  3312. const char *prog,
  3313. char *envblk,
  3314. char *envp[],
  3315. int fdin[2],
  3316. int fdout[2],
  3317. int fderr[2],
  3318. const char *dir)
  3319. {
  3320. pid_t pid;
  3321. const char *interp;
  3322. (void)envblk;
  3323. if (conn == NULL) {
  3324. return 0;
  3325. }
  3326. if ((pid = fork()) == -1) {
  3327. /* Parent */
  3328. send_http_error(conn,
  3329. 500,
  3330. "Error: Creating CGI process\nfork(): %s",
  3331. strerror(ERRNO));
  3332. } else if (pid == 0) {
  3333. /* Child */
  3334. if (chdir(dir) != 0) {
  3335. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  3336. } else if (dup2(fdin[0], 0) == -1) {
  3337. mg_cry(conn,
  3338. "%s: dup2(%d, 0): %s",
  3339. __func__,
  3340. fdin[0],
  3341. strerror(ERRNO));
  3342. } else if (dup2(fdout[1], 1) == -1) {
  3343. mg_cry(conn,
  3344. "%s: dup2(%d, 1): %s",
  3345. __func__,
  3346. fdout[1],
  3347. strerror(ERRNO));
  3348. } else if (dup2(fderr[1], 2) == -1) {
  3349. mg_cry(conn,
  3350. "%s: dup2(%d, 2): %s",
  3351. __func__,
  3352. fderr[1],
  3353. strerror(ERRNO));
  3354. } else {
  3355. /* Keep stderr and stdout in two different pipes.
  3356. * Stdout will be sent back to the client,
  3357. * stderr should go into a server error log. */
  3358. (void)close(fdin[0]);
  3359. (void)close(fdout[1]);
  3360. (void)close(fderr[1]);
  3361. /* Close write end fdin and read end fdout and fderr */
  3362. (void)close(fdin[1]);
  3363. (void)close(fdout[0]);
  3364. (void)close(fderr[0]);
  3365. /* After exec, all signal handlers are restored to their default
  3366. * values, with one exception of SIGCHLD. According to
  3367. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler will
  3368. * leave unchanged after exec if it was set to be ignored. Restore
  3369. * it to default action. */
  3370. signal(SIGCHLD, SIG_DFL);
  3371. interp = conn->ctx->config[CGI_INTERPRETER];
  3372. if (interp == NULL) {
  3373. (void)execle(prog, prog, NULL, envp);
  3374. mg_cry(conn,
  3375. "%s: execle(%s): %s",
  3376. __func__,
  3377. prog,
  3378. strerror(ERRNO));
  3379. } else {
  3380. (void)execle(interp, interp, prog, NULL, envp);
  3381. mg_cry(conn,
  3382. "%s: execle(%s %s): %s",
  3383. __func__,
  3384. interp,
  3385. prog,
  3386. strerror(ERRNO));
  3387. }
  3388. }
  3389. exit(EXIT_FAILURE);
  3390. }
  3391. return pid;
  3392. }
  3393. #endif /* !NO_CGI */
  3394. static int
  3395. set_non_blocking_mode(SOCKET sock)
  3396. {
  3397. int flags;
  3398. flags = fcntl(sock, F_GETFL, 0);
  3399. (void)fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  3400. return 0;
  3401. }
  3402. #endif /* _WIN32 */
  3403. /* End of initial operating system specific define block. */
  3404. /* Get a random number (independent of C rand function) */
  3405. static uint64_t
  3406. get_random(void)
  3407. {
  3408. static uint64_t lfsr = 0; /* Linear feedback shift register */
  3409. static uint64_t lcg = 0; /* Linear congruential generator */
  3410. struct timespec now;
  3411. memset(&now, 0, sizeof(now));
  3412. clock_gettime(CLOCK_MONOTONIC, &now);
  3413. if (lfsr == 0) {
  3414. /* lfsr will be only 0 if has not been initialized,
  3415. * so this code is called only once. */
  3416. lfsr = (((uint64_t)now.tv_sec) << 21) ^ ((uint64_t)now.tv_nsec)
  3417. ^ ((uint64_t)(ptrdiff_t)&now) ^ (((uint64_t)time(NULL)) << 33);
  3418. lcg = (((uint64_t)now.tv_sec) << 25) + (uint64_t)now.tv_nsec
  3419. + (uint64_t)(ptrdiff_t)&now;
  3420. } else {
  3421. /* Get the next step of both random number generators. */
  3422. lfsr = (lfsr >> 1)
  3423. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  3424. << 63);
  3425. lcg = lcg * 6364136223846793005 + 1442695040888963407;
  3426. }
  3427. /* Combining two pseudo-random number generators and a high resolution part
  3428. * of the current server time will make it hard (impossible?) to guess the
  3429. * next number. */
  3430. return (lfsr ^ lcg ^ (uint64_t)now.tv_nsec);
  3431. }
  3432. /* Write data to the IO channel - opened file descriptor, socket or SSL
  3433. * descriptor. Return number of bytes written. */
  3434. static int
  3435. push(struct mg_context *ctx,
  3436. FILE *fp,
  3437. SOCKET sock,
  3438. SSL *ssl,
  3439. const char *buf,
  3440. int len,
  3441. double timeout)
  3442. {
  3443. struct timespec start, now;
  3444. int n, err;
  3445. #ifdef _WIN32
  3446. typedef int len_t;
  3447. #else
  3448. typedef size_t len_t;
  3449. #endif
  3450. if (timeout > 0) {
  3451. memset(&start, 0, sizeof(start));
  3452. memset(&now, 0, sizeof(now));
  3453. clock_gettime(CLOCK_MONOTONIC, &start);
  3454. }
  3455. if (ctx == NULL) {
  3456. return -1;
  3457. }
  3458. #ifdef NO_SSL
  3459. if (ssl) {
  3460. return -1;
  3461. }
  3462. #endif
  3463. do {
  3464. #ifndef NO_SSL
  3465. if (ssl != NULL) {
  3466. n = SSL_write(ssl, buf, len);
  3467. if (n <= 0) {
  3468. err = SSL_get_error(ssl, n);
  3469. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  3470. err = ERRNO;
  3471. } else if ((err == SSL_ERROR_WANT_READ)
  3472. || (err == SSL_ERROR_WANT_WRITE)) {
  3473. n = 0;
  3474. } else {
  3475. DEBUG_TRACE("SSL_write() failed, error %d", err);
  3476. return -1;
  3477. }
  3478. } else {
  3479. err = 0;
  3480. }
  3481. } else
  3482. #endif
  3483. if (fp != NULL) {
  3484. n = (int)fwrite(buf, 1, (size_t)len, fp);
  3485. if (ferror(fp)) {
  3486. n = -1;
  3487. err = ERRNO;
  3488. } else {
  3489. err = 0;
  3490. }
  3491. } else {
  3492. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  3493. err = (n < 0) ? ERRNO : 0;
  3494. if (n == 0) {
  3495. /* shutdown of the socket at client side */
  3496. return -1;
  3497. }
  3498. }
  3499. if (ctx->stop_flag) {
  3500. return -1;
  3501. }
  3502. if ((n > 0) || (n == 0 && len == 0)) {
  3503. /* some data has been read, or no data was requested */
  3504. return n;
  3505. }
  3506. if (n < 0) {
  3507. /* socket error - check errno */
  3508. DEBUG_TRACE("send() failed, error %d", err);
  3509. /* TODO: error handling depending on the error code.
  3510. * These codes are different between Windows and Linux.
  3511. */
  3512. return -1;
  3513. }
  3514. /* This code is not reached in the moment.
  3515. * ==> Fix the TODOs above first. */
  3516. if (timeout > 0) {
  3517. clock_gettime(CLOCK_MONOTONIC, &now);
  3518. }
  3519. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  3520. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  3521. used */
  3522. return -1;
  3523. }
  3524. static int64_t
  3525. push_all(struct mg_context *ctx,
  3526. FILE *fp,
  3527. SOCKET sock,
  3528. SSL *ssl,
  3529. const char *buf,
  3530. int64_t len)
  3531. {
  3532. double timeout = -1.0;
  3533. int64_t n, nwritten = 0;
  3534. if (ctx == NULL) {
  3535. return -1;
  3536. }
  3537. if (ctx->config[REQUEST_TIMEOUT]) {
  3538. timeout = atoi(ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  3539. }
  3540. while (len > 0 && ctx->stop_flag == 0) {
  3541. n = push(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  3542. if (n < 0) {
  3543. if (nwritten == 0) {
  3544. nwritten = n; /* Propagate the error */
  3545. }
  3546. break;
  3547. } else if (n == 0) {
  3548. break; /* No more data to write */
  3549. } else {
  3550. nwritten += n;
  3551. len -= n;
  3552. }
  3553. }
  3554. return nwritten;
  3555. }
  3556. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  3557. * Return negative value on error, or number of bytes read on success. */
  3558. static int
  3559. pull(FILE *fp, struct mg_connection *conn, char *buf, int len, double timeout)
  3560. {
  3561. int nread, err;
  3562. struct timespec start, now;
  3563. #ifdef _WIN32
  3564. typedef int len_t;
  3565. #else
  3566. typedef size_t len_t;
  3567. #endif
  3568. if (timeout > 0) {
  3569. memset(&start, 0, sizeof(start));
  3570. memset(&now, 0, sizeof(now));
  3571. clock_gettime(CLOCK_MONOTONIC, &start);
  3572. }
  3573. do {
  3574. if (fp != NULL) {
  3575. #if !defined(_WIN32_WCE)
  3576. /* Use read() instead of fread(), because if we're reading from the
  3577. * CGI pipe, fread() may block until IO buffer is filled up. We
  3578. * cannot afford to block and must pass all read bytes immediately
  3579. * to the client. */
  3580. nread = (int)read(fileno(fp), buf, (size_t)len);
  3581. #else
  3582. /* WinCE does not support CGI pipes */
  3583. nread = (int)fread(buf, 1, (size_t)len, fp);
  3584. #endif
  3585. err = (nread < 0) ? ERRNO : 0;
  3586. #ifndef NO_SSL
  3587. } else if (conn->ssl != NULL) {
  3588. nread = SSL_read(conn->ssl, buf, len);
  3589. if (nread <= 0) {
  3590. err = SSL_get_error(conn->ssl, nread);
  3591. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  3592. err = ERRNO;
  3593. } else if ((err == SSL_ERROR_WANT_READ)
  3594. || (err == SSL_ERROR_WANT_WRITE)) {
  3595. nread = 0;
  3596. } else {
  3597. DEBUG_TRACE("SSL_read() failed, error %d", err);
  3598. return -1;
  3599. }
  3600. } else {
  3601. err = 0;
  3602. }
  3603. #endif
  3604. } else {
  3605. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  3606. err = (nread < 0) ? ERRNO : 0;
  3607. if (nread == 0) {
  3608. /* shutdown of the socket at client side */
  3609. return -1;
  3610. }
  3611. }
  3612. if (conn->ctx->stop_flag) {
  3613. return -1;
  3614. }
  3615. if ((nread > 0) || (nread == 0 && len == 0)) {
  3616. /* some data has been read, or no data was requested */
  3617. return nread;
  3618. }
  3619. if (nread < 0) {
  3620. /* socket error - check errno */
  3621. #ifdef _WIN32
  3622. if (err == WSAEWOULDBLOCK) {
  3623. /* standard case if called from close_socket_gracefully */
  3624. return -1;
  3625. } else if (err == WSAETIMEDOUT) {
  3626. /* timeout is handled by the while loop */
  3627. } else {
  3628. DEBUG_TRACE("recv() failed, error %d", err);
  3629. return -1;
  3630. }
  3631. #else
  3632. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  3633. * if the timeout is reached and if the socket was set to non-
  3634. * blocking in close_socket_gracefully, so we can not distinguish
  3635. * here. We have to wait for the timeout in both cases for now.
  3636. */
  3637. if (err == EAGAIN || err == EWOULDBLOCK || err == EINTR) {
  3638. /* EAGAIN/EWOULDBLOCK:
  3639. * standard case if called from close_socket_gracefully
  3640. * => should return -1 */
  3641. /* or timeout occured
  3642. * => the code must stay in the while loop */
  3643. /* EINTR can be generated on a socket with a timeout set even
  3644. * when SA_RESTART is effective for all relevant signals
  3645. * (see signal(7)).
  3646. * => stay in the while loop */
  3647. } else {
  3648. DEBUG_TRACE("recv() failed, error %d", err);
  3649. return -1;
  3650. }
  3651. #endif
  3652. }
  3653. if (timeout > 0) {
  3654. clock_gettime(CLOCK_MONOTONIC, &now);
  3655. }
  3656. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  3657. /* Timeout occured, but no data available. */
  3658. return -1;
  3659. }
  3660. static int
  3661. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  3662. {
  3663. int n, nread = 0;
  3664. double timeout = -1.0;
  3665. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  3666. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  3667. }
  3668. while (len > 0 && conn->ctx->stop_flag == 0) {
  3669. n = pull(fp, conn, buf + nread, len, timeout);
  3670. if (n < 0) {
  3671. if (nread == 0) {
  3672. nread = n; /* Propagate the error */
  3673. }
  3674. break;
  3675. } else if (n == 0) {
  3676. break; /* No more data to read */
  3677. } else {
  3678. conn->consumed_content += n;
  3679. nread += n;
  3680. len -= n;
  3681. }
  3682. }
  3683. return nread;
  3684. }
  3685. static void
  3686. discard_unread_request_data(struct mg_connection *conn)
  3687. {
  3688. char buf[MG_BUF_LEN];
  3689. size_t to_read;
  3690. int nread;
  3691. if (conn == NULL) {
  3692. return;
  3693. }
  3694. to_read = sizeof(buf);
  3695. if (conn->is_chunked) {
  3696. /* Chunked encoding: 1=chunk not read completely, 2=chunk read
  3697. * completely */
  3698. while (conn->is_chunked == 1) {
  3699. nread = mg_read(conn, buf, to_read);
  3700. if (nread <= 0) {
  3701. break;
  3702. }
  3703. }
  3704. } else {
  3705. /* Not chunked: content length is known */
  3706. while (conn->consumed_content < conn->content_len) {
  3707. if (to_read
  3708. > (size_t)(conn->content_len - conn->consumed_content)) {
  3709. to_read = (size_t)(conn->content_len - conn->consumed_content);
  3710. }
  3711. nread = mg_read(conn, buf, to_read);
  3712. if (nread <= 0) {
  3713. break;
  3714. }
  3715. }
  3716. }
  3717. }
  3718. static int
  3719. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  3720. {
  3721. int64_t n, buffered_len, nread;
  3722. int64_t len64 =
  3723. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  3724. * int, we may not read more
  3725. * bytes */
  3726. const char *body;
  3727. if (conn == NULL) {
  3728. return 0;
  3729. }
  3730. /* If Content-Length is not set for a PUT or POST request, read until
  3731. * socket is closed */
  3732. if (conn->consumed_content == 0 && conn->content_len == -1) {
  3733. conn->content_len = INT64_MAX;
  3734. conn->must_close = 1;
  3735. }
  3736. nread = 0;
  3737. if (conn->consumed_content < conn->content_len) {
  3738. /* Adjust number of bytes to read. */
  3739. int64_t left_to_read = conn->content_len - conn->consumed_content;
  3740. if (left_to_read < len64) {
  3741. /* Do not read more than the total content length of the request.
  3742. */
  3743. len64 = left_to_read;
  3744. }
  3745. /* Return buffered data */
  3746. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  3747. - conn->consumed_content;
  3748. if (buffered_len > 0) {
  3749. if (len64 < buffered_len) {
  3750. buffered_len = len64;
  3751. }
  3752. body = conn->buf + conn->request_len + conn->consumed_content;
  3753. memcpy(buf, body, (size_t)buffered_len);
  3754. len64 -= buffered_len;
  3755. conn->consumed_content += buffered_len;
  3756. nread += buffered_len;
  3757. buf = (char *)buf + buffered_len;
  3758. }
  3759. /* We have returned all buffered data. Read new data from the remote
  3760. * socket.
  3761. */
  3762. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  3763. nread += n;
  3764. } else {
  3765. nread = ((nread > 0) ? nread : n);
  3766. }
  3767. }
  3768. return (int)nread;
  3769. }
  3770. static char
  3771. mg_getc(struct mg_connection *conn)
  3772. {
  3773. char c;
  3774. if (conn == NULL) {
  3775. return 0;
  3776. }
  3777. conn->content_len++;
  3778. if (mg_read_inner(conn, &c, 1) <= 0) {
  3779. return (char)0;
  3780. }
  3781. return c;
  3782. }
  3783. int
  3784. mg_read(struct mg_connection *conn, void *buf, size_t len)
  3785. {
  3786. if (len > INT_MAX) {
  3787. len = INT_MAX;
  3788. }
  3789. if (conn == NULL) {
  3790. return 0;
  3791. }
  3792. if (conn->is_chunked) {
  3793. size_t all_read = 0;
  3794. while (len > 0) {
  3795. if (conn->is_chunked == 2) {
  3796. /* No more data left to read */
  3797. return 0;
  3798. }
  3799. if (conn->chunk_remainder) {
  3800. /* copy from the remainder of the last received chunk */
  3801. long read_ret;
  3802. size_t read_now =
  3803. ((conn->chunk_remainder > len) ? (len)
  3804. : (conn->chunk_remainder));
  3805. conn->content_len += (int)read_now;
  3806. read_ret =
  3807. mg_read_inner(conn, (char *)buf + all_read, read_now);
  3808. all_read += (size_t)read_ret;
  3809. conn->chunk_remainder -= read_now;
  3810. len -= read_now;
  3811. if (conn->chunk_remainder == 0) {
  3812. /* the rest of the data in the current chunk has been read
  3813. */
  3814. if ((mg_getc(conn) != '\r') || (mg_getc(conn) != '\n')) {
  3815. /* Protocol violation */
  3816. return -1;
  3817. }
  3818. }
  3819. } else {
  3820. /* fetch a new chunk */
  3821. int i = 0;
  3822. char lenbuf[64];
  3823. char *end = 0;
  3824. unsigned long chunkSize = 0;
  3825. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  3826. lenbuf[i] = mg_getc(conn);
  3827. if (i > 0 && lenbuf[i] == '\r' && lenbuf[i - 1] != '\r') {
  3828. continue;
  3829. }
  3830. if (i > 1 && lenbuf[i] == '\n' && lenbuf[i - 1] == '\r') {
  3831. lenbuf[i + 1] = 0;
  3832. chunkSize = strtoul(lenbuf, &end, 16);
  3833. if (chunkSize == 0) {
  3834. /* regular end of content */
  3835. conn->is_chunked = 2;
  3836. }
  3837. break;
  3838. }
  3839. if (!isalnum(lenbuf[i])) {
  3840. /* illegal character for chunk length */
  3841. return -1;
  3842. }
  3843. }
  3844. if ((end == NULL) || (*end != '\r')) {
  3845. /* chunksize not set correctly */
  3846. return -1;
  3847. }
  3848. if (chunkSize == 0) {
  3849. break;
  3850. }
  3851. conn->chunk_remainder = chunkSize;
  3852. }
  3853. }
  3854. return (int)all_read;
  3855. }
  3856. return mg_read_inner(conn, buf, len);
  3857. }
  3858. int
  3859. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  3860. {
  3861. time_t now;
  3862. int64_t n, total, allowed;
  3863. if (conn == NULL) {
  3864. return 0;
  3865. }
  3866. if (conn->throttle > 0) {
  3867. if ((now = time(NULL)) != conn->last_throttle_time) {
  3868. conn->last_throttle_time = now;
  3869. conn->last_throttle_bytes = 0;
  3870. }
  3871. allowed = conn->throttle - conn->last_throttle_bytes;
  3872. if (allowed > (int64_t)len) {
  3873. allowed = (int64_t)len;
  3874. }
  3875. if ((total = push_all(conn->ctx,
  3876. NULL,
  3877. conn->client.sock,
  3878. conn->ssl,
  3879. (const char *)buf,
  3880. (int64_t)allowed)) == allowed) {
  3881. buf = (const char *)buf + total;
  3882. conn->last_throttle_bytes += total;
  3883. while (total < (int64_t)len && conn->ctx->stop_flag == 0) {
  3884. allowed = (conn->throttle > ((int64_t)len - total))
  3885. ? (int64_t)len - total
  3886. : conn->throttle;
  3887. if ((n = push_all(conn->ctx,
  3888. NULL,
  3889. conn->client.sock,
  3890. conn->ssl,
  3891. (const char *)buf,
  3892. (int64_t)allowed)) != allowed) {
  3893. break;
  3894. }
  3895. sleep(1);
  3896. conn->last_throttle_bytes = allowed;
  3897. conn->last_throttle_time = time(NULL);
  3898. buf = (const char *)buf + n;
  3899. total += n;
  3900. }
  3901. }
  3902. } else {
  3903. total = push_all(conn->ctx,
  3904. NULL,
  3905. conn->client.sock,
  3906. conn->ssl,
  3907. (const char *)buf,
  3908. (int64_t)len);
  3909. }
  3910. return (int)total;
  3911. }
  3912. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  3913. static int
  3914. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  3915. {
  3916. va_list ap_copy;
  3917. size_t size = MG_BUF_LEN / 4;
  3918. int len = -1;
  3919. *buf = NULL;
  3920. while (len < 0) {
  3921. if (*buf) {
  3922. mg_free(*buf);
  3923. }
  3924. size *= 4;
  3925. *buf = (char *)mg_malloc(size);
  3926. if (!*buf) {
  3927. break;
  3928. }
  3929. va_copy(ap_copy, ap);
  3930. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  3931. va_end(ap_copy);
  3932. (*buf)[size - 1] = 0;
  3933. }
  3934. return len;
  3935. }
  3936. /* Print message to buffer. If buffer is large enough to hold the message,
  3937. * return buffer. If buffer is to small, allocate large enough buffer on heap,
  3938. * and return allocated buffer. */
  3939. static int
  3940. alloc_vprintf(char **out_buf,
  3941. char *prealloc_buf,
  3942. size_t prealloc_size,
  3943. const char *fmt,
  3944. va_list ap)
  3945. {
  3946. va_list ap_copy;
  3947. int len;
  3948. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  3949. * buffer is too small. Also, older versions of msvcrt.dll do not have
  3950. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  3951. * Therefore, we make two passes: on first pass, get required message
  3952. * length.
  3953. * On second pass, actually print the message. */
  3954. va_copy(ap_copy, ap);
  3955. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  3956. va_end(ap_copy);
  3957. if (len < 0) {
  3958. /* C runtime is not standard compliant, vsnprintf() returned -1.
  3959. * Switch to alternative code path that uses incremental allocations.
  3960. */
  3961. va_copy(ap_copy, ap);
  3962. len = alloc_vprintf2(out_buf, fmt, ap);
  3963. va_end(ap_copy);
  3964. } else if ((size_t)(len) >= prealloc_size) {
  3965. /* The pre-allocated buffer not large enough. */
  3966. /* Allocate a new buffer. */
  3967. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  3968. if (!*out_buf) {
  3969. /* Allocation failed. Return -1 as "out of memory" error. */
  3970. return -1;
  3971. }
  3972. /* Buffer allocation successful. Store the string there. */
  3973. va_copy(ap_copy, ap);
  3974. IGNORE_UNUSED_RESULT(
  3975. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  3976. va_end(ap_copy);
  3977. } else {
  3978. /* The pre-allocated buffer is large enough.
  3979. * Use it to store the string and return the address. */
  3980. va_copy(ap_copy, ap);
  3981. IGNORE_UNUSED_RESULT(
  3982. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  3983. va_end(ap_copy);
  3984. *out_buf = prealloc_buf;
  3985. }
  3986. return len;
  3987. }
  3988. static int
  3989. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  3990. {
  3991. char mem[MG_BUF_LEN];
  3992. char *buf = NULL;
  3993. int len;
  3994. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  3995. len = mg_write(conn, buf, (size_t)len);
  3996. }
  3997. if (buf != mem && buf != NULL) {
  3998. mg_free(buf);
  3999. }
  4000. return len;
  4001. }
  4002. int
  4003. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  4004. {
  4005. va_list ap;
  4006. int result;
  4007. va_start(ap, fmt);
  4008. result = mg_vprintf(conn, fmt, ap);
  4009. va_end(ap);
  4010. return result;
  4011. }
  4012. int
  4013. mg_url_decode(const char *src,
  4014. int src_len,
  4015. char *dst,
  4016. int dst_len,
  4017. int is_form_url_encoded)
  4018. {
  4019. int i, j, a, b;
  4020. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  4021. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  4022. if (i < src_len - 2 && src[i] == '%'
  4023. && isxdigit(*(const unsigned char *)(src + i + 1))
  4024. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  4025. a = tolower(*(const unsigned char *)(src + i + 1));
  4026. b = tolower(*(const unsigned char *)(src + i + 2));
  4027. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  4028. i += 2;
  4029. } else if (is_form_url_encoded && src[i] == '+') {
  4030. dst[j] = ' ';
  4031. } else {
  4032. dst[j] = src[i];
  4033. }
  4034. }
  4035. dst[j] = '\0'; /* Null-terminate the destination */
  4036. return (i >= src_len) ? j : -1;
  4037. }
  4038. int
  4039. mg_get_var(const char *data,
  4040. size_t data_len,
  4041. const char *name,
  4042. char *dst,
  4043. size_t dst_len)
  4044. {
  4045. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  4046. }
  4047. int
  4048. mg_get_var2(const char *data,
  4049. size_t data_len,
  4050. const char *name,
  4051. char *dst,
  4052. size_t dst_len,
  4053. size_t occurrence)
  4054. {
  4055. const char *p, *e, *s;
  4056. size_t name_len;
  4057. int len;
  4058. if (dst == NULL || dst_len == 0) {
  4059. len = -2;
  4060. } else if (data == NULL || name == NULL || data_len == 0) {
  4061. len = -1;
  4062. dst[0] = '\0';
  4063. } else {
  4064. name_len = strlen(name);
  4065. e = data + data_len;
  4066. len = -1;
  4067. dst[0] = '\0';
  4068. /* data is "var1=val1&var2=val2...". Find variable first */
  4069. for (p = data; p + name_len < e; p++) {
  4070. if ((p == data || p[-1] == '&') && p[name_len] == '='
  4071. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  4072. /* Point p to variable value */
  4073. p += name_len + 1;
  4074. /* Point s to the end of the value */
  4075. s = (const char *)memchr(p, '&', (size_t)(e - p));
  4076. if (s == NULL) {
  4077. s = e;
  4078. }
  4079. /* assert(s >= p); */
  4080. if (s < p) {
  4081. return -3;
  4082. }
  4083. /* Decode variable into destination buffer */
  4084. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  4085. /* Redirect error code from -1 to -2 (destination buffer too
  4086. * small). */
  4087. if (len == -1) {
  4088. len = -2;
  4089. }
  4090. break;
  4091. }
  4092. }
  4093. }
  4094. return len;
  4095. }
  4096. int
  4097. mg_get_cookie(const char *cookie_header,
  4098. const char *var_name,
  4099. char *dst,
  4100. size_t dst_size)
  4101. {
  4102. const char *s, *p, *end;
  4103. int name_len, len = -1;
  4104. if (dst == NULL || dst_size == 0) {
  4105. len = -2;
  4106. } else if (var_name == NULL || (s = cookie_header) == NULL) {
  4107. len = -1;
  4108. dst[0] = '\0';
  4109. } else {
  4110. name_len = (int)strlen(var_name);
  4111. end = s + strlen(s);
  4112. dst[0] = '\0';
  4113. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  4114. if (s[name_len] == '=') {
  4115. s += name_len + 1;
  4116. if ((p = strchr(s, ' ')) == NULL) {
  4117. p = end;
  4118. }
  4119. if (p[-1] == ';') {
  4120. p--;
  4121. }
  4122. if (*s == '"' && p[-1] == '"' && p > s + 1) {
  4123. s++;
  4124. p--;
  4125. }
  4126. if ((size_t)(p - s) < dst_size) {
  4127. len = (int)(p - s);
  4128. mg_strlcpy(dst, s, (size_t)len + 1);
  4129. } else {
  4130. len = -3;
  4131. }
  4132. break;
  4133. }
  4134. }
  4135. }
  4136. return len;
  4137. }
  4138. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  4139. static void
  4140. base64_encode(const unsigned char *src, int src_len, char *dst)
  4141. {
  4142. static const char *b64 =
  4143. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  4144. int i, j, a, b, c;
  4145. for (i = j = 0; i < src_len; i += 3) {
  4146. a = src[i];
  4147. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  4148. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  4149. dst[j++] = b64[a >> 2];
  4150. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  4151. if (i + 1 < src_len) {
  4152. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  4153. }
  4154. if (i + 2 < src_len) {
  4155. dst[j++] = b64[c & 63];
  4156. }
  4157. }
  4158. while (j % 4 != 0) {
  4159. dst[j++] = '=';
  4160. }
  4161. dst[j++] = '\0';
  4162. }
  4163. #endif
  4164. #if defined(USE_LUA)
  4165. static unsigned char
  4166. b64reverse(char letter)
  4167. {
  4168. if (letter >= 'A' && letter <= 'Z') {
  4169. return letter - 'A';
  4170. }
  4171. if (letter >= 'a' && letter <= 'z') {
  4172. return letter - 'a' + 26;
  4173. }
  4174. if (letter >= '0' && letter <= '9') {
  4175. return letter - '0' + 52;
  4176. }
  4177. if (letter == '+') {
  4178. return 62;
  4179. }
  4180. if (letter == '/') {
  4181. return 63;
  4182. }
  4183. if (letter == '=') {
  4184. return 255; /* normal end */
  4185. }
  4186. return 254; /* error */
  4187. }
  4188. static int
  4189. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  4190. {
  4191. int i;
  4192. unsigned char a, b, c, d;
  4193. *dst_len = 0;
  4194. for (i = 0; i < src_len; i += 4) {
  4195. a = b64reverse(src[i]);
  4196. if (a >= 254) {
  4197. return i;
  4198. }
  4199. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  4200. if (b >= 254) {
  4201. return i + 1;
  4202. }
  4203. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  4204. if (c == 254) {
  4205. return i + 2;
  4206. }
  4207. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  4208. if (d == 254) {
  4209. return i + 3;
  4210. }
  4211. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  4212. if (c != 255) {
  4213. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  4214. if (d != 255) {
  4215. dst[(*dst_len)++] = (c << 6) + d;
  4216. }
  4217. }
  4218. }
  4219. return -1;
  4220. }
  4221. #endif
  4222. static int
  4223. is_put_or_delete_method(const struct mg_connection *conn)
  4224. {
  4225. if (conn) {
  4226. const char *s = conn->request_info.request_method;
  4227. return s != NULL && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  4228. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  4229. }
  4230. return 0;
  4231. }
  4232. static void
  4233. interpret_uri(struct mg_connection *conn, /* in: request (must be valid) */
  4234. char *filename, /* out: filename */
  4235. size_t filename_buf_len, /* in: size of filename buffer */
  4236. struct file *filep, /* out: file structure */
  4237. int *is_found, /* out: file is found (directly) */
  4238. int *is_script_resource, /* out: handled by a script? */
  4239. int *is_websocket_request, /* out: websocket connetion? */
  4240. int *is_put_or_delete_request /* out: put/delete a file? */
  4241. )
  4242. {
  4243. /* TODO (high): Restructure this function */
  4244. #if !defined(NO_FILES)
  4245. const char *uri = conn->request_info.local_uri;
  4246. const char *root = conn->ctx->config[DOCUMENT_ROOT];
  4247. const char *rewrite;
  4248. struct vec a, b;
  4249. int match_len;
  4250. char gz_path[PATH_MAX];
  4251. char const *accept_encoding;
  4252. int truncated;
  4253. #if !defined(NO_CGI) || defined(USE_LUA)
  4254. char *p;
  4255. #endif
  4256. #else
  4257. (void)filename_buf_len; /* unused if NO_FILES is defined */
  4258. #endif
  4259. memset(filep, 0, sizeof(*filep));
  4260. *filename = 0;
  4261. *is_found = 0;
  4262. *is_script_resource = 0;
  4263. *is_put_or_delete_request = is_put_or_delete_method(conn);
  4264. #if defined(USE_WEBSOCKET)
  4265. *is_websocket_request = is_websocket_protocol(conn);
  4266. #if !defined(NO_FILES)
  4267. if (*is_websocket_request && conn->ctx->config[WEBSOCKET_ROOT]) {
  4268. root = conn->ctx->config[WEBSOCKET_ROOT];
  4269. }
  4270. #endif /* !NO_FILES */
  4271. #else /* USE_WEBSOCKET */
  4272. *is_websocket_request = 0;
  4273. #endif /* USE_WEBSOCKET */
  4274. #if !defined(NO_FILES)
  4275. /* Note that root == NULL is a regular use case here. This occurs,
  4276. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  4277. * config is not required. */
  4278. if (root == NULL) {
  4279. /* all file related outputs have already been set to 0, just return
  4280. */
  4281. return;
  4282. }
  4283. /* Using buf_len - 1 because memmove() for PATH_INFO may shift part
  4284. * of the path one byte on the right.
  4285. * If document_root is NULL, leave the file empty. */
  4286. mg_snprintf(
  4287. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  4288. if (truncated) {
  4289. goto interpret_cleanup;
  4290. }
  4291. rewrite = conn->ctx->config[REWRITE];
  4292. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  4293. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  4294. mg_snprintf(conn,
  4295. &truncated,
  4296. filename,
  4297. filename_buf_len - 1,
  4298. "%.*s%s",
  4299. (int)b.len,
  4300. b.ptr,
  4301. uri + match_len);
  4302. break;
  4303. }
  4304. }
  4305. if (truncated) {
  4306. goto interpret_cleanup;
  4307. }
  4308. /* Local file path and name, corresponding to requested URI
  4309. * is now stored in "filename" variable. */
  4310. if (mg_stat(conn, filename, filep)) {
  4311. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  4312. /* File exists. Check if it is a script type. */
  4313. if (0
  4314. #if !defined(NO_CGI)
  4315. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  4316. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4317. filename) > 0
  4318. #endif
  4319. #if defined(USE_LUA)
  4320. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  4321. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  4322. filename) > 0
  4323. #endif
  4324. #if defined(USE_DUKTAPE)
  4325. || match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  4326. strlen(
  4327. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  4328. filename) > 0
  4329. #endif
  4330. ) {
  4331. /* The request addresses a CGI script or a Lua script. The URI
  4332. * corresponds to the script itself (like /path/script.cgi),
  4333. * and there is no additional resource path
  4334. * (like /path/script.cgi/something).
  4335. * Requests that modify (replace or delete) a resource, like
  4336. * PUT and DELETE requests, should replace/delete the script
  4337. * file.
  4338. * Requests that read or write from/to a resource, like GET and
  4339. * POST requests, should call the script and return the
  4340. * generated response. */
  4341. *is_script_resource = !*is_put_or_delete_request;
  4342. }
  4343. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  4344. *is_found = 1;
  4345. return;
  4346. }
  4347. /* If we can't find the actual file, look for the file
  4348. * with the same name but a .gz extension. If we find it,
  4349. * use that and set the gzipped flag in the file struct
  4350. * to indicate that the response need to have the content-
  4351. * encoding: gzip header.
  4352. * We can only do this if the browser declares support. */
  4353. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  4354. if (strstr(accept_encoding, "gzip") != NULL) {
  4355. mg_snprintf(
  4356. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  4357. if (truncated) {
  4358. goto interpret_cleanup;
  4359. }
  4360. if (mg_stat(conn, gz_path, filep)) {
  4361. if (filep) {
  4362. filep->gzipped = 1;
  4363. *is_found = 1;
  4364. }
  4365. /* Currently gz files can not be scripts. */
  4366. return;
  4367. }
  4368. }
  4369. }
  4370. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  4371. /* Support PATH_INFO for CGI scripts. */
  4372. for (p = filename + strlen(filename); p > filename + 1; p--) {
  4373. if (*p == '/') {
  4374. *p = '\0';
  4375. if ((0
  4376. #if !defined(NO_CGI)
  4377. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  4378. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4379. filename) > 0
  4380. #endif
  4381. #if defined(USE_LUA)
  4382. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  4383. strlen(
  4384. conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  4385. filename) > 0
  4386. #endif
  4387. #if defined(USE_DUKTAPE)
  4388. || match_prefix(
  4389. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  4390. strlen(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  4391. filename) > 0
  4392. #endif
  4393. ) && mg_stat(conn, filename, filep)) {
  4394. /* Shift PATH_INFO block one character right, e.g.
  4395. * "/x.cgi/foo/bar\x00" => "/x.cgi\x00/foo/bar\x00"
  4396. * conn->path_info is pointing to the local variable "path"
  4397. * declared in handle_request(), so PATH_INFO is not valid
  4398. * after handle_request returns. */
  4399. conn->path_info = p + 1;
  4400. memmove(p + 2, p + 1, strlen(p + 1) + 1); /* +1 is for
  4401. * trailing \0 */
  4402. p[1] = '/';
  4403. *is_script_resource = 1;
  4404. break;
  4405. } else {
  4406. *p = '/';
  4407. }
  4408. }
  4409. }
  4410. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  4411. #endif /* !defined(NO_FILES) */
  4412. return;
  4413. #if !defined(NO_FILES)
  4414. /* Reset all outputs */
  4415. interpret_cleanup:
  4416. memset(filep, 0, sizeof(*filep));
  4417. *filename = 0;
  4418. *is_found = 0;
  4419. *is_script_resource = 0;
  4420. *is_websocket_request = 0;
  4421. *is_put_or_delete_request = 0;
  4422. #endif /* !defined(NO_FILES) */
  4423. }
  4424. /* Check whether full request is buffered. Return:
  4425. * -1 if request is malformed
  4426. * 0 if request is not yet fully buffered
  4427. * >0 actual request length, including last \r\n\r\n */
  4428. static int
  4429. get_request_len(const char *buf, int buflen)
  4430. {
  4431. const char *s, *e;
  4432. int len = 0;
  4433. for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
  4434. /* Control characters are not allowed but >=128 is. */
  4435. if (!isprint(*(const unsigned char *)s) && *s != '\r' && *s != '\n'
  4436. && *(const unsigned char *)s < 128) {
  4437. len = -1;
  4438. break; /* [i_a] abort scan as soon as one malformed character is
  4439. * found; */
  4440. /* don't let subsequent \r\n\r\n win us over anyhow */
  4441. } else if (s[0] == '\n' && s[1] == '\n') {
  4442. len = (int)(s - buf) + 2;
  4443. } else if (s[0] == '\n' && &s[1] < e && s[1] == '\r' && s[2] == '\n') {
  4444. len = (int)(s - buf) + 3;
  4445. }
  4446. return len;
  4447. }
  4448. #if !defined(NO_CACHING)
  4449. /* Convert month to the month number. Return -1 on error, or month number */
  4450. static int
  4451. get_month_index(const char *s)
  4452. {
  4453. size_t i;
  4454. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  4455. if (!strcmp(s, month_names[i])) {
  4456. return (int)i;
  4457. }
  4458. }
  4459. return -1;
  4460. }
  4461. /* Parse UTC date-time string, and return the corresponding time_t value. */
  4462. static time_t
  4463. parse_date_string(const char *datetime)
  4464. {
  4465. char month_str[32] = {0};
  4466. int second, minute, hour, day, month, year;
  4467. time_t result = (time_t)0;
  4468. struct tm tm;
  4469. if ((sscanf(datetime,
  4470. "%d/%3s/%d %d:%d:%d",
  4471. &day,
  4472. month_str,
  4473. &year,
  4474. &hour,
  4475. &minute,
  4476. &second) == 6) || (sscanf(datetime,
  4477. "%d %3s %d %d:%d:%d",
  4478. &day,
  4479. month_str,
  4480. &year,
  4481. &hour,
  4482. &minute,
  4483. &second) == 6)
  4484. || (sscanf(datetime,
  4485. "%*3s, %d %3s %d %d:%d:%d",
  4486. &day,
  4487. month_str,
  4488. &year,
  4489. &hour,
  4490. &minute,
  4491. &second) == 6) || (sscanf(datetime,
  4492. "%d-%3s-%d %d:%d:%d",
  4493. &day,
  4494. month_str,
  4495. &year,
  4496. &hour,
  4497. &minute,
  4498. &second) == 6)) {
  4499. month = get_month_index(month_str);
  4500. if ((month >= 0) && (year >= 1970)) {
  4501. memset(&tm, 0, sizeof(tm));
  4502. tm.tm_year = year - 1900;
  4503. tm.tm_mon = month;
  4504. tm.tm_mday = day;
  4505. tm.tm_hour = hour;
  4506. tm.tm_min = minute;
  4507. tm.tm_sec = second;
  4508. result = timegm(&tm);
  4509. }
  4510. }
  4511. return result;
  4512. }
  4513. #endif /* !NO_CACHING */
  4514. /* Protect against directory disclosure attack by removing '..',
  4515. * excessive '/' and '\' characters */
  4516. static void
  4517. remove_double_dots_and_double_slashes(char *s)
  4518. {
  4519. char *p = s;
  4520. while ((s[0] == '.') && (s[1] == '.')) {
  4521. s++;
  4522. }
  4523. while (*s != '\0') {
  4524. *p++ = *s++;
  4525. if (s[-1] == '/' || s[-1] == '\\') {
  4526. /* Skip all following slashes, backslashes and double-dots */
  4527. while (s[0] != '\0') {
  4528. if (s[0] == '/' || s[0] == '\\') {
  4529. s++;
  4530. } else if (s[0] == '.' && s[1] == '.') {
  4531. s += 2;
  4532. } else {
  4533. break;
  4534. }
  4535. }
  4536. }
  4537. }
  4538. *p = '\0';
  4539. }
  4540. static const struct {
  4541. const char *extension;
  4542. size_t ext_len;
  4543. const char *mime_type;
  4544. } builtin_mime_types[] = {
  4545. /* IANA registered MIME types (http://www.iana.org/assignments/media-types)
  4546. * application types */
  4547. {".doc", 4, "application/msword"},
  4548. {".eps", 4, "application/postscript"},
  4549. {".exe", 4, "application/octet-stream"},
  4550. {".js", 3, "application/javascript"},
  4551. {".json", 5, "application/json"},
  4552. {".pdf", 4, "application/pdf"},
  4553. {".ps", 3, "application/postscript"},
  4554. {".rtf", 4, "application/rtf"},
  4555. {".xhtml", 6, "application/xhtml+xml"},
  4556. {".xsl", 4, "application/xml"},
  4557. {".xslt", 5, "application/xml"},
  4558. /* fonts */
  4559. {".ttf", 4, "application/font-sfnt"},
  4560. {".cff", 4, "application/font-sfnt"},
  4561. {".otf", 4, "application/font-sfnt"},
  4562. {".aat", 4, "application/font-sfnt"},
  4563. {".sil", 4, "application/font-sfnt"},
  4564. {".pfr", 4, "application/font-tdpfr"},
  4565. {".woff", 5, "application/font-woff"},
  4566. /* audio */
  4567. {".mp3", 4, "audio/mpeg"},
  4568. {".oga", 4, "audio/ogg"},
  4569. {".ogg", 4, "audio/ogg"},
  4570. /* image */
  4571. {".gif", 4, "image/gif"},
  4572. {".ief", 4, "image/ief"},
  4573. {".jpeg", 5, "image/jpeg"},
  4574. {".jpg", 4, "image/jpeg"},
  4575. {".jpm", 4, "image/jpm"},
  4576. {".jpx", 4, "image/jpx"},
  4577. {".png", 4, "image/png"},
  4578. {".svg", 4, "image/svg+xml"},
  4579. {".tif", 4, "image/tiff"},
  4580. {".tiff", 5, "image/tiff"},
  4581. /* model */
  4582. {".wrl", 4, "model/vrml"},
  4583. /* text */
  4584. {".css", 4, "text/css"},
  4585. {".csv", 4, "text/csv"},
  4586. {".htm", 4, "text/html"},
  4587. {".html", 5, "text/html"},
  4588. {".sgm", 4, "text/sgml"},
  4589. {".shtm", 5, "text/html"},
  4590. {".shtml", 6, "text/html"},
  4591. {".txt", 4, "text/plain"},
  4592. {".xml", 4, "text/xml"},
  4593. /* video */
  4594. {".mov", 4, "video/quicktime"},
  4595. {".mp4", 4, "video/mp4"},
  4596. {".mpeg", 5, "video/mpeg"},
  4597. {".mpg", 4, "video/mpeg"},
  4598. {".ogv", 4, "video/ogg"},
  4599. {".qt", 3, "video/quicktime"},
  4600. /* not registered types
  4601. * (http://reference.sitepoint.com/html/mime-types-full,
  4602. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  4603. {".arj", 4, "application/x-arj-compressed"},
  4604. {".gz", 3, "application/x-gunzip"},
  4605. {".rar", 4, "application/x-arj-compressed"},
  4606. {".swf", 4, "application/x-shockwave-flash"},
  4607. {".tar", 4, "application/x-tar"},
  4608. {".tgz", 4, "application/x-tar-gz"},
  4609. {".torrent", 8, "application/x-bittorrent"},
  4610. {".ppt", 4, "application/x-mspowerpoint"},
  4611. {".xls", 4, "application/x-msexcel"},
  4612. {".zip", 4, "application/x-zip-compressed"},
  4613. {".aac",
  4614. 4,
  4615. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  4616. {".aif", 4, "audio/x-aif"},
  4617. {".m3u", 4, "audio/x-mpegurl"},
  4618. {".mid", 4, "audio/x-midi"},
  4619. {".ra", 3, "audio/x-pn-realaudio"},
  4620. {".ram", 4, "audio/x-pn-realaudio"},
  4621. {".wav", 4, "audio/x-wav"},
  4622. {".bmp", 4, "image/bmp"},
  4623. {".ico", 4, "image/x-icon"},
  4624. {".pct", 4, "image/x-pct"},
  4625. {".pict", 5, "image/pict"},
  4626. {".rgb", 4, "image/x-rgb"},
  4627. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  4628. {".asf", 4, "video/x-ms-asf"},
  4629. {".avi", 4, "video/x-msvideo"},
  4630. {".m4v", 4, "video/x-m4v"},
  4631. {NULL, 0, NULL}};
  4632. const char *
  4633. mg_get_builtin_mime_type(const char *path)
  4634. {
  4635. const char *ext;
  4636. size_t i, path_len;
  4637. path_len = strlen(path);
  4638. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  4639. ext = path + (path_len - builtin_mime_types[i].ext_len);
  4640. if (path_len > builtin_mime_types[i].ext_len
  4641. && mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {
  4642. return builtin_mime_types[i].mime_type;
  4643. }
  4644. }
  4645. return "text/plain";
  4646. }
  4647. /* Look at the "path" extension and figure what mime type it has.
  4648. * Store mime type in the vector. */
  4649. static void
  4650. get_mime_type(struct mg_context *ctx, const char *path, struct vec *vec)
  4651. {
  4652. struct vec ext_vec, mime_vec;
  4653. const char *list, *ext;
  4654. size_t path_len;
  4655. path_len = strlen(path);
  4656. if (ctx == NULL || vec == NULL) {
  4657. return;
  4658. }
  4659. /* Scan user-defined mime types first, in case user wants to
  4660. * override default mime types. */
  4661. list = ctx->config[EXTRA_MIME_TYPES];
  4662. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  4663. /* ext now points to the path suffix */
  4664. ext = path + path_len - ext_vec.len;
  4665. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  4666. *vec = mime_vec;
  4667. return;
  4668. }
  4669. }
  4670. vec->ptr = mg_get_builtin_mime_type(path);
  4671. vec->len = strlen(vec->ptr);
  4672. }
  4673. /* Stringify binary data. Output buffer must be twice as big as input,
  4674. * because each byte takes 2 bytes in string representation */
  4675. static void
  4676. bin2str(char *to, const unsigned char *p, size_t len)
  4677. {
  4678. static const char *hex = "0123456789abcdef";
  4679. for (; len--; p++) {
  4680. *to++ = hex[p[0] >> 4];
  4681. *to++ = hex[p[0] & 0x0f];
  4682. }
  4683. *to = '\0';
  4684. }
  4685. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes. */
  4686. char *
  4687. mg_md5(char buf[33], ...)
  4688. {
  4689. md5_byte_t hash[16];
  4690. const char *p;
  4691. va_list ap;
  4692. md5_state_t ctx;
  4693. md5_init(&ctx);
  4694. va_start(ap, buf);
  4695. while ((p = va_arg(ap, const char *)) != NULL) {
  4696. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  4697. }
  4698. va_end(ap);
  4699. md5_finish(&ctx, hash);
  4700. bin2str(buf, hash, sizeof(hash));
  4701. return buf;
  4702. }
  4703. /* Check the user's password, return 1 if OK */
  4704. static int
  4705. check_password(const char *method,
  4706. const char *ha1,
  4707. const char *uri,
  4708. const char *nonce,
  4709. const char *nc,
  4710. const char *cnonce,
  4711. const char *qop,
  4712. const char *response)
  4713. {
  4714. char ha2[32 + 1], expected_response[32 + 1];
  4715. /* Some of the parameters may be NULL */
  4716. if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL
  4717. || qop == NULL
  4718. || response == NULL) {
  4719. return 0;
  4720. }
  4721. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  4722. if (strlen(response) != 32) {
  4723. return 0;
  4724. }
  4725. mg_md5(ha2, method, ":", uri, NULL);
  4726. mg_md5(expected_response,
  4727. ha1,
  4728. ":",
  4729. nonce,
  4730. ":",
  4731. nc,
  4732. ":",
  4733. cnonce,
  4734. ":",
  4735. qop,
  4736. ":",
  4737. ha2,
  4738. NULL);
  4739. return mg_strcasecmp(response, expected_response) == 0;
  4740. }
  4741. /* Use the global passwords file, if specified by auth_gpass option,
  4742. * or search for .htpasswd in the requested directory. */
  4743. static void
  4744. open_auth_file(struct mg_connection *conn, const char *path, struct file *filep)
  4745. {
  4746. if (conn != NULL && conn->ctx != NULL) {
  4747. char name[PATH_MAX];
  4748. const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
  4749. struct file file = STRUCT_FILE_INITIALIZER;
  4750. int truncated;
  4751. if (gpass != NULL) {
  4752. /* Use global passwords file */
  4753. if (!mg_fopen(conn, gpass, "r", filep)) {
  4754. #ifdef DEBUG
  4755. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  4756. #endif
  4757. }
  4758. /* Important: using local struct file to test path for is_directory
  4759. * flag. If filep is used, mg_stat() makes it appear as if auth file
  4760. * was opened. */
  4761. } else if (mg_stat(conn, path, &file) && file.is_directory) {
  4762. mg_snprintf(conn,
  4763. &truncated,
  4764. name,
  4765. sizeof(name),
  4766. "%s/%s",
  4767. path,
  4768. PASSWORDS_FILE_NAME);
  4769. if (truncated || !mg_fopen(conn, name, "r", filep)) {
  4770. #ifdef DEBUG
  4771. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  4772. #endif
  4773. }
  4774. } else {
  4775. /* Try to find .htpasswd in requested directory. */
  4776. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  4777. if (e[0] == '/') {
  4778. break;
  4779. }
  4780. }
  4781. mg_snprintf(conn,
  4782. &truncated,
  4783. name,
  4784. sizeof(name),
  4785. "%.*s/%s",
  4786. (int)(e - p),
  4787. p,
  4788. PASSWORDS_FILE_NAME);
  4789. if (truncated || !mg_fopen(conn, name, "r", filep)) {
  4790. #ifdef DEBUG
  4791. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  4792. #endif
  4793. }
  4794. }
  4795. }
  4796. }
  4797. /* Parsed Authorization header */
  4798. struct ah {
  4799. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  4800. };
  4801. /* Return 1 on success. Always initializes the ah structure. */
  4802. static int
  4803. parse_auth_header(struct mg_connection *conn,
  4804. char *buf,
  4805. size_t buf_size,
  4806. struct ah *ah)
  4807. {
  4808. char *name, *value, *s;
  4809. const char *auth_header;
  4810. uint64_t nonce;
  4811. if (!ah || !conn) {
  4812. return 0;
  4813. }
  4814. (void)memset(ah, 0, sizeof(*ah));
  4815. if ((auth_header = mg_get_header(conn, "Authorization")) == NULL
  4816. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  4817. return 0;
  4818. }
  4819. /* Make modifiable copy of the auth header */
  4820. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  4821. s = buf;
  4822. /* Parse authorization header */
  4823. for (;;) {
  4824. /* Gobble initial spaces */
  4825. while (isspace(*(unsigned char *)s)) {
  4826. s++;
  4827. }
  4828. name = skip_quoted(&s, "=", " ", 0);
  4829. /* Value is either quote-delimited, or ends at first comma or space. */
  4830. if (s[0] == '\"') {
  4831. s++;
  4832. value = skip_quoted(&s, "\"", " ", '\\');
  4833. if (s[0] == ',') {
  4834. s++;
  4835. }
  4836. } else {
  4837. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  4838. * spaces */
  4839. }
  4840. if (*name == '\0') {
  4841. break;
  4842. }
  4843. if (!strcmp(name, "username")) {
  4844. ah->user = value;
  4845. } else if (!strcmp(name, "cnonce")) {
  4846. ah->cnonce = value;
  4847. } else if (!strcmp(name, "response")) {
  4848. ah->response = value;
  4849. } else if (!strcmp(name, "uri")) {
  4850. ah->uri = value;
  4851. } else if (!strcmp(name, "qop")) {
  4852. ah->qop = value;
  4853. } else if (!strcmp(name, "nc")) {
  4854. ah->nc = value;
  4855. } else if (!strcmp(name, "nonce")) {
  4856. ah->nonce = value;
  4857. }
  4858. }
  4859. #ifndef NO_NONCE_CHECK
  4860. /* Read the nonce from the response. */
  4861. if (ah->nonce == NULL) {
  4862. return 0;
  4863. }
  4864. s = NULL;
  4865. nonce = strtoull(ah->nonce, &s, 10);
  4866. if ((s == NULL) || (*s != 0)) {
  4867. return 0;
  4868. }
  4869. /* Convert the nonce from the client to a number. */
  4870. nonce ^= conn->ctx->auth_nonce_mask;
  4871. /* The converted number corresponds to the time the nounce has been
  4872. * created. This should not be earlier than the server start. */
  4873. /* Server side nonce check is valuable in all situations but one:
  4874. * if the server restarts frequently, but the client should not see
  4875. * that, so the server should accept nonces from previous starts. */
  4876. /* However, the reasonable default is to not accept a nonce from a
  4877. * previous start, so if anyone changed the access rights between
  4878. * two restarts, a new login is required. */
  4879. if (nonce < (uint64_t)conn->ctx->start_time) {
  4880. /* nonce is from a previous start of the server and no longer valid
  4881. * (replay attack?) */
  4882. return 0;
  4883. }
  4884. /* Check if the nonce is too high, so it has not (yet) been used by the
  4885. * server. */
  4886. if (nonce >= ((uint64_t)conn->ctx->start_time + conn->ctx->nonce_count)) {
  4887. return 0;
  4888. }
  4889. #else
  4890. (void)nonce;
  4891. #endif
  4892. /* CGI needs it as REMOTE_USER */
  4893. if (ah->user != NULL) {
  4894. conn->request_info.remote_user = mg_strdup(ah->user);
  4895. } else {
  4896. return 0;
  4897. }
  4898. return 1;
  4899. }
  4900. static const char *
  4901. mg_fgets(char *buf, size_t size, struct file *filep, char **p)
  4902. {
  4903. const char *eof;
  4904. size_t len;
  4905. const char *memend;
  4906. if (!filep) {
  4907. return NULL;
  4908. }
  4909. if (filep->membuf != NULL && *p != NULL) {
  4910. memend = (const char *)&filep->membuf[filep->size];
  4911. /* Search for \n from p till the end of stream */
  4912. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  4913. if (eof != NULL) {
  4914. eof += 1; /* Include \n */
  4915. } else {
  4916. eof = memend; /* Copy remaining data */
  4917. }
  4918. len =
  4919. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  4920. memcpy(buf, *p, len);
  4921. buf[len] = '\0';
  4922. *p += len;
  4923. return len ? eof : NULL;
  4924. } else if (filep->fp != NULL) {
  4925. return fgets(buf, (int)size, filep->fp);
  4926. } else {
  4927. return NULL;
  4928. }
  4929. }
  4930. struct read_auth_file_struct {
  4931. struct mg_connection *conn;
  4932. struct ah ah;
  4933. char *domain;
  4934. char buf[256 + 256 + 40];
  4935. char *f_user;
  4936. char *f_domain;
  4937. char *f_ha1;
  4938. };
  4939. static int
  4940. read_auth_file(struct file *filep, struct read_auth_file_struct *workdata)
  4941. {
  4942. char *p;
  4943. int is_authorized = 0;
  4944. struct file fp;
  4945. size_t l;
  4946. if (!filep || !workdata) {
  4947. return 0;
  4948. }
  4949. /* Loop over passwords file */
  4950. p = (char *)filep->membuf;
  4951. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  4952. l = strlen(workdata->buf);
  4953. while (l > 0) {
  4954. if (isspace(workdata->buf[l - 1])
  4955. || iscntrl(workdata->buf[l - 1])) {
  4956. l--;
  4957. workdata->buf[l] = 0;
  4958. } else
  4959. break;
  4960. }
  4961. if (l < 1) {
  4962. continue;
  4963. }
  4964. workdata->f_user = workdata->buf;
  4965. if (workdata->f_user[0] == ':') {
  4966. /* user names may not contain a ':' and may not be empty,
  4967. * so lines starting with ':' may be used for a special purpose */
  4968. if (workdata->f_user[1] == '#') {
  4969. /* :# is a comment */
  4970. continue;
  4971. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  4972. if (mg_fopen(workdata->conn, workdata->f_user + 9, "r", &fp)) {
  4973. is_authorized = read_auth_file(&fp, workdata);
  4974. mg_fclose(&fp);
  4975. } else {
  4976. mg_cry(workdata->conn,
  4977. "%s: cannot open authorization file: %s",
  4978. __func__,
  4979. workdata->buf);
  4980. }
  4981. continue;
  4982. }
  4983. /* everything is invalid for the moment (might change in the
  4984. * future) */
  4985. mg_cry(workdata->conn,
  4986. "%s: syntax error in authorization file: %s",
  4987. __func__,
  4988. workdata->buf);
  4989. continue;
  4990. }
  4991. workdata->f_domain = strchr(workdata->f_user, ':');
  4992. if (workdata->f_domain == NULL) {
  4993. mg_cry(workdata->conn,
  4994. "%s: syntax error in authorization file: %s",
  4995. __func__,
  4996. workdata->buf);
  4997. continue;
  4998. }
  4999. *(workdata->f_domain) = 0;
  5000. (workdata->f_domain)++;
  5001. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  5002. if (workdata->f_ha1 == NULL) {
  5003. mg_cry(workdata->conn,
  5004. "%s: syntax error in authorization file: %s",
  5005. __func__,
  5006. workdata->buf);
  5007. continue;
  5008. }
  5009. *(workdata->f_ha1) = 0;
  5010. (workdata->f_ha1)++;
  5011. if (!strcmp(workdata->ah.user, workdata->f_user)
  5012. && !strcmp(workdata->domain, workdata->f_domain)) {
  5013. return check_password(workdata->conn->request_info.request_method,
  5014. workdata->f_ha1,
  5015. workdata->ah.uri,
  5016. workdata->ah.nonce,
  5017. workdata->ah.nc,
  5018. workdata->ah.cnonce,
  5019. workdata->ah.qop,
  5020. workdata->ah.response);
  5021. }
  5022. }
  5023. return is_authorized;
  5024. }
  5025. /* Authorize against the opened passwords file. Return 1 if authorized. */
  5026. static int
  5027. authorize(struct mg_connection *conn, struct file *filep)
  5028. {
  5029. struct read_auth_file_struct workdata;
  5030. char buf[MG_BUF_LEN];
  5031. if (!conn || !conn->ctx) {
  5032. return 0;
  5033. }
  5034. memset(&workdata, 0, sizeof(workdata));
  5035. workdata.conn = conn;
  5036. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  5037. return 0;
  5038. }
  5039. workdata.domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  5040. return read_auth_file(filep, &workdata);
  5041. }
  5042. /* Return 1 if request is authorised, 0 otherwise. */
  5043. static int
  5044. check_authorization(struct mg_connection *conn, const char *path)
  5045. {
  5046. char fname[PATH_MAX];
  5047. struct vec uri_vec, filename_vec;
  5048. const char *list;
  5049. struct file file = STRUCT_FILE_INITIALIZER;
  5050. int authorized = 1, truncated;
  5051. if (!conn || !conn->ctx) {
  5052. return 0;
  5053. }
  5054. list = conn->ctx->config[PROTECT_URI];
  5055. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  5056. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  5057. mg_snprintf(conn,
  5058. &truncated,
  5059. fname,
  5060. sizeof(fname),
  5061. "%.*s",
  5062. (int)filename_vec.len,
  5063. filename_vec.ptr);
  5064. if (truncated || !mg_fopen(conn, fname, "r", &file)) {
  5065. mg_cry(conn,
  5066. "%s: cannot open %s: %s",
  5067. __func__,
  5068. fname,
  5069. strerror(errno));
  5070. }
  5071. break;
  5072. }
  5073. }
  5074. if (!is_file_opened(&file)) {
  5075. open_auth_file(conn, path, &file);
  5076. }
  5077. if (is_file_opened(&file)) {
  5078. authorized = authorize(conn, &file);
  5079. mg_fclose(&file);
  5080. }
  5081. return authorized;
  5082. }
  5083. static void
  5084. send_authorization_request(struct mg_connection *conn)
  5085. {
  5086. char date[64];
  5087. time_t curtime = time(NULL);
  5088. if (conn && conn->ctx) {
  5089. uint64_t nonce = (uint64_t)(conn->ctx->start_time);
  5090. (void)pthread_mutex_lock(&conn->ctx->nonce_mutex);
  5091. nonce += conn->ctx->nonce_count;
  5092. ++conn->ctx->nonce_count;
  5093. (void)pthread_mutex_unlock(&conn->ctx->nonce_mutex);
  5094. nonce ^= conn->ctx->auth_nonce_mask;
  5095. conn->status_code = 401;
  5096. conn->must_close = 1;
  5097. gmt_time_string(date, sizeof(date), &curtime);
  5098. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  5099. send_no_cache_header(conn);
  5100. mg_printf(conn,
  5101. "Date: %s\r\n"
  5102. "Connection: %s\r\n"
  5103. "Content-Length: 0\r\n"
  5104. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  5105. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  5106. date,
  5107. suggest_connection_header(conn),
  5108. conn->ctx->config[AUTHENTICATION_DOMAIN],
  5109. nonce);
  5110. }
  5111. }
  5112. #if !defined(NO_FILES)
  5113. static int
  5114. is_authorized_for_put(struct mg_connection *conn)
  5115. {
  5116. if (conn) {
  5117. struct file file = STRUCT_FILE_INITIALIZER;
  5118. const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
  5119. int ret = 0;
  5120. if (passfile != NULL && mg_fopen(conn, passfile, "r", &file)) {
  5121. ret = authorize(conn, &file);
  5122. mg_fclose(&file);
  5123. }
  5124. return ret;
  5125. }
  5126. return 0;
  5127. }
  5128. #endif
  5129. int
  5130. mg_modify_passwords_file(const char *fname,
  5131. const char *domain,
  5132. const char *user,
  5133. const char *pass)
  5134. {
  5135. int found, i;
  5136. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  5137. FILE *fp, *fp2;
  5138. found = 0;
  5139. fp = fp2 = NULL;
  5140. /* Regard empty password as no password - remove user record. */
  5141. if (pass != NULL && pass[0] == '\0') {
  5142. pass = NULL;
  5143. }
  5144. /* Other arguments must not be empty */
  5145. if (fname == NULL || domain == NULL || user == NULL) {
  5146. return 0;
  5147. }
  5148. /* Using the given file format, user name and domain must not contain ':'
  5149. */
  5150. if (strchr(user, ':') != NULL) {
  5151. return 0;
  5152. }
  5153. if (strchr(domain, ':') != NULL) {
  5154. return 0;
  5155. }
  5156. /* Do not allow control characters like newline in user name and domain.
  5157. * Do not allow excessively long names either. */
  5158. for (i = 0; i < 255 && user[i] != 0; i++) {
  5159. if (iscntrl(user[i])) {
  5160. return 0;
  5161. }
  5162. }
  5163. if (user[i]) {
  5164. return 0;
  5165. }
  5166. for (i = 0; i < 255 && domain[i] != 0; i++) {
  5167. if (iscntrl(domain[i])) {
  5168. return 0;
  5169. }
  5170. }
  5171. if (domain[i]) {
  5172. return 0;
  5173. }
  5174. /* The maximum length of the path to the password file is limited */
  5175. if ((strlen(fname) + 4) >= PATH_MAX) {
  5176. return 0;
  5177. }
  5178. /* Create a temporary file name. Length has been checked before. */
  5179. strcpy(tmp, fname);
  5180. strcat(tmp, ".tmp");
  5181. /* Create the file if does not exist */
  5182. /* Use of fopen here is OK, since fname is only ASCII */
  5183. if ((fp = fopen(fname, "a+")) != NULL) {
  5184. (void)fclose(fp);
  5185. }
  5186. /* Open the given file and temporary file */
  5187. if ((fp = fopen(fname, "r")) == NULL) {
  5188. return 0;
  5189. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  5190. fclose(fp);
  5191. return 0;
  5192. }
  5193. /* Copy the stuff to temporary file */
  5194. while (fgets(line, sizeof(line), fp) != NULL) {
  5195. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  5196. continue;
  5197. }
  5198. u[255] = 0;
  5199. d[255] = 0;
  5200. if (!strcmp(u, user) && !strcmp(d, domain)) {
  5201. found++;
  5202. if (pass != NULL) {
  5203. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  5204. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  5205. }
  5206. } else {
  5207. fprintf(fp2, "%s", line);
  5208. }
  5209. }
  5210. /* If new user, just add it */
  5211. if (!found && pass != NULL) {
  5212. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  5213. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  5214. }
  5215. /* Close files */
  5216. fclose(fp);
  5217. fclose(fp2);
  5218. /* Put the temp file in place of real file */
  5219. IGNORE_UNUSED_RESULT(remove(fname));
  5220. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  5221. return 1;
  5222. }
  5223. static int
  5224. is_valid_port(unsigned long port)
  5225. {
  5226. return port < 0xffff;
  5227. }
  5228. static int
  5229. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  5230. {
  5231. struct addrinfo hints, *res, *ressave;
  5232. int func_ret = 0;
  5233. int gai_ret;
  5234. memset(&hints, 0, sizeof(struct addrinfo));
  5235. hints.ai_family = af;
  5236. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  5237. if (gai_ret != 0) {
  5238. /* gai_strerror could be used to convert gai_ret to a string */
  5239. /* POSIX return values: see
  5240. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  5241. */
  5242. /* Windows return values: see
  5243. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  5244. */
  5245. return 0;
  5246. }
  5247. ressave = res;
  5248. while (res) {
  5249. if (dstlen >= res->ai_addrlen) {
  5250. memcpy(dst, res->ai_addr, res->ai_addrlen);
  5251. func_ret = 1;
  5252. }
  5253. res = res->ai_next;
  5254. }
  5255. freeaddrinfo(ressave);
  5256. return func_ret;
  5257. }
  5258. static int
  5259. connect_socket(struct mg_context *ctx /* may be NULL */,
  5260. const char *host,
  5261. int port,
  5262. int use_ssl,
  5263. char *ebuf,
  5264. size_t ebuf_len,
  5265. SOCKET *sock /* output: socket, must not be NULL */,
  5266. union usa *sa /* output: socket address, must not be NULL */
  5267. )
  5268. {
  5269. int ip_ver = 0;
  5270. *sock = INVALID_SOCKET;
  5271. memset(sa, 0, sizeof(*sa));
  5272. if (ebuf_len > 0) {
  5273. *ebuf = 0;
  5274. }
  5275. if (host == NULL) {
  5276. mg_snprintf(NULL,
  5277. NULL, /* No truncation check for ebuf */
  5278. ebuf,
  5279. ebuf_len,
  5280. "%s",
  5281. "NULL host");
  5282. return 0;
  5283. }
  5284. if (port < 0 || !is_valid_port((unsigned)port)) {
  5285. mg_snprintf(NULL,
  5286. NULL, /* No truncation check for ebuf */
  5287. ebuf,
  5288. ebuf_len,
  5289. "%s",
  5290. "invalid port");
  5291. return 0;
  5292. }
  5293. #if !defined(NO_SSL)
  5294. if (use_ssl && (SSLv23_client_method == NULL)) {
  5295. mg_snprintf(NULL,
  5296. NULL, /* No truncation check for ebuf */
  5297. ebuf,
  5298. ebuf_len,
  5299. "%s",
  5300. "SSL is not initialized");
  5301. return 0;
  5302. }
  5303. #else
  5304. (void)use_ssl;
  5305. #endif
  5306. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  5307. sa->sin.sin_port = htons((uint16_t)port);
  5308. ip_ver = 4;
  5309. #ifdef USE_IPV6
  5310. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  5311. sa->sin6.sin6_port = htons((uint16_t)port);
  5312. ip_ver = 6;
  5313. } else if (host[0] == '[') {
  5314. /* While getaddrinfo on Windows will work with [::1],
  5315. * getaddrinfo on Linux only works with ::1 (without []). */
  5316. size_t l = strlen(host + 1);
  5317. char *h = (l > 1) ? mg_strdup(host + 1) : NULL;
  5318. if (h) {
  5319. h[l - 1] = 0;
  5320. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  5321. sa->sin6.sin6_port = htons((uint16_t)port);
  5322. ip_ver = 6;
  5323. }
  5324. mg_free(h);
  5325. }
  5326. #endif
  5327. }
  5328. if (ip_ver == 0) {
  5329. mg_snprintf(NULL,
  5330. NULL, /* No truncation check for ebuf */
  5331. ebuf,
  5332. ebuf_len,
  5333. "%s",
  5334. "host not found");
  5335. return 0;
  5336. }
  5337. if (ip_ver == 4) {
  5338. *sock = socket(PF_INET, SOCK_STREAM, 0);
  5339. }
  5340. #ifdef USE_IPV6
  5341. else if (ip_ver == 6) {
  5342. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  5343. }
  5344. #endif
  5345. if (*sock == INVALID_SOCKET) {
  5346. mg_snprintf(NULL,
  5347. NULL, /* No truncation check for ebuf */
  5348. ebuf,
  5349. ebuf_len,
  5350. "socket(): %s",
  5351. strerror(ERRNO));
  5352. return 0;
  5353. }
  5354. set_close_on_exec(*sock, fc(ctx));
  5355. if ((ip_ver == 4)
  5356. && (connect(*sock, (struct sockaddr *)&sa->sin, sizeof(sa->sin))
  5357. == 0)) {
  5358. /* connected with IPv4 */
  5359. return 1;
  5360. }
  5361. #ifdef USE_IPV6
  5362. if ((ip_ver == 6)
  5363. && (connect(*sock, (struct sockaddr *)&sa->sin6, sizeof(sa->sin6))
  5364. == 0)) {
  5365. /* connected with IPv6 */
  5366. return 1;
  5367. }
  5368. #endif
  5369. /* Not connected */
  5370. mg_snprintf(NULL,
  5371. NULL, /* No truncation check for ebuf */
  5372. ebuf,
  5373. ebuf_len,
  5374. "connect(%s:%d): %s",
  5375. host,
  5376. port,
  5377. strerror(ERRNO));
  5378. closesocket(*sock);
  5379. *sock = INVALID_SOCKET;
  5380. return 0;
  5381. }
  5382. int
  5383. mg_url_encode(const char *src, char *dst, size_t dst_len)
  5384. {
  5385. static const char *dont_escape = "._-$,;~()";
  5386. static const char *hex = "0123456789abcdef";
  5387. char *pos = dst;
  5388. const char *end = dst + dst_len - 1;
  5389. for (; *src != '\0' && pos < end; src++, pos++) {
  5390. if (isalnum(*(const unsigned char *)src)
  5391. || strchr(dont_escape, *(const unsigned char *)src) != NULL) {
  5392. *pos = *src;
  5393. } else if (pos + 2 < end) {
  5394. pos[0] = '%';
  5395. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  5396. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  5397. pos += 2;
  5398. } else {
  5399. break;
  5400. }
  5401. }
  5402. *pos = '\0';
  5403. return (*src == '\0') ? (int)(pos - dst) : -1;
  5404. }
  5405. static void
  5406. print_dir_entry(struct de *de)
  5407. {
  5408. char size[64], mod[64], href[PATH_MAX * 3 /* worst case */];
  5409. struct tm *tm;
  5410. if (de->file.is_directory) {
  5411. mg_snprintf(de->conn,
  5412. NULL, /* Buffer is big enough */
  5413. size,
  5414. sizeof(size),
  5415. "%s",
  5416. "[DIRECTORY]");
  5417. } else {
  5418. /* We use (signed) cast below because MSVC 6 compiler cannot
  5419. * convert unsigned __int64 to double. Sigh. */
  5420. if (de->file.size < 1024) {
  5421. mg_snprintf(de->conn,
  5422. NULL, /* Buffer is big enough */
  5423. size,
  5424. sizeof(size),
  5425. "%d",
  5426. (int)de->file.size);
  5427. } else if (de->file.size < 0x100000) {
  5428. mg_snprintf(de->conn,
  5429. NULL, /* Buffer is big enough */
  5430. size,
  5431. sizeof(size),
  5432. "%.1fk",
  5433. (double)de->file.size / 1024.0);
  5434. } else if (de->file.size < 0x40000000) {
  5435. mg_snprintf(de->conn,
  5436. NULL, /* Buffer is big enough */
  5437. size,
  5438. sizeof(size),
  5439. "%.1fM",
  5440. (double)de->file.size / 1048576);
  5441. } else {
  5442. mg_snprintf(de->conn,
  5443. NULL, /* Buffer is big enough */
  5444. size,
  5445. sizeof(size),
  5446. "%.1fG",
  5447. (double)de->file.size / 1073741824);
  5448. }
  5449. }
  5450. /* Note: mg_snprintf will not cause a buffer overflow above.
  5451. * So, string truncation checks are not required here. */
  5452. tm = localtime(&de->file.last_modified);
  5453. if (tm != NULL) {
  5454. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  5455. } else {
  5456. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  5457. mod[sizeof(mod) - 1] = '\0';
  5458. }
  5459. mg_url_encode(de->file_name, href, sizeof(href));
  5460. de->conn->num_bytes_sent +=
  5461. mg_printf(de->conn,
  5462. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  5463. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  5464. de->conn->request_info.local_uri,
  5465. href,
  5466. de->file.is_directory ? "/" : "",
  5467. de->file_name,
  5468. de->file.is_directory ? "/" : "",
  5469. mod,
  5470. size);
  5471. }
  5472. /* This function is called from send_directory() and used for
  5473. * sorting directory entries by size, or name, or modification time.
  5474. * On windows, __cdecl specification is needed in case if project is built
  5475. * with __stdcall convention. qsort always requires __cdels callback. */
  5476. static int WINCDECL
  5477. compare_dir_entries(const void *p1, const void *p2)
  5478. {
  5479. if (p1 && p2) {
  5480. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  5481. const char *query_string = a->conn->request_info.query_string;
  5482. int cmp_result = 0;
  5483. if (query_string == NULL) {
  5484. query_string = "na";
  5485. }
  5486. if (a->file.is_directory && !b->file.is_directory) {
  5487. return -1; /* Always put directories on top */
  5488. } else if (!a->file.is_directory && b->file.is_directory) {
  5489. return 1; /* Always put directories on top */
  5490. } else if (*query_string == 'n') {
  5491. cmp_result = strcmp(a->file_name, b->file_name);
  5492. } else if (*query_string == 's') {
  5493. cmp_result = (a->file.size == b->file.size)
  5494. ? 0
  5495. : ((a->file.size > b->file.size) ? 1 : -1);
  5496. } else if (*query_string == 'd') {
  5497. cmp_result =
  5498. (a->file.last_modified == b->file.last_modified)
  5499. ? 0
  5500. : ((a->file.last_modified > b->file.last_modified) ? 1
  5501. : -1);
  5502. }
  5503. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  5504. }
  5505. return 0;
  5506. }
  5507. static int
  5508. must_hide_file(struct mg_connection *conn, const char *path)
  5509. {
  5510. if (conn && conn->ctx) {
  5511. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  5512. const char *pattern = conn->ctx->config[HIDE_FILES];
  5513. return match_prefix(pw_pattern, strlen(pw_pattern), path) > 0
  5514. || (pattern != NULL
  5515. && match_prefix(pattern, strlen(pattern), path) > 0);
  5516. }
  5517. return 0;
  5518. }
  5519. static int
  5520. scan_directory(struct mg_connection *conn,
  5521. const char *dir,
  5522. void *data,
  5523. void (*cb)(struct de *, void *))
  5524. {
  5525. char path[PATH_MAX];
  5526. struct dirent *dp;
  5527. DIR *dirp;
  5528. struct de de;
  5529. int truncated;
  5530. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  5531. return 0;
  5532. } else {
  5533. de.conn = conn;
  5534. while ((dp = mg_readdir(dirp)) != NULL) {
  5535. /* Do not show current dir and hidden files */
  5536. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  5537. || must_hide_file(conn, dp->d_name)) {
  5538. continue;
  5539. }
  5540. mg_snprintf(
  5541. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  5542. /* If we don't memset stat structure to zero, mtime will have
  5543. * garbage and strftime() will segfault later on in
  5544. * print_dir_entry(). memset is required only if mg_stat()
  5545. * fails. For more details, see
  5546. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  5547. memset(&de.file, 0, sizeof(de.file));
  5548. if (truncated) {
  5549. /* If the path is not complete, skip processing. */
  5550. continue;
  5551. }
  5552. if (!mg_stat(conn, path, &de.file)) {
  5553. mg_cry(conn,
  5554. "%s: mg_stat(%s) failed: %s",
  5555. __func__,
  5556. path,
  5557. strerror(ERRNO));
  5558. }
  5559. de.file_name = dp->d_name;
  5560. cb(&de, data);
  5561. }
  5562. (void)mg_closedir(dirp);
  5563. }
  5564. return 1;
  5565. }
  5566. #if !defined(NO_FILES)
  5567. static int
  5568. remove_directory(struct mg_connection *conn, const char *dir)
  5569. {
  5570. char path[PATH_MAX];
  5571. struct dirent *dp;
  5572. DIR *dirp;
  5573. struct de de;
  5574. int truncated;
  5575. int ok = 1;
  5576. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  5577. return 0;
  5578. } else {
  5579. de.conn = conn;
  5580. while ((dp = mg_readdir(dirp)) != NULL) {
  5581. /* Do not show current dir (but show hidden files as they will
  5582. * also be removed) */
  5583. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  5584. continue;
  5585. }
  5586. mg_snprintf(
  5587. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  5588. /* If we don't memset stat structure to zero, mtime will have
  5589. * garbage and strftime() will segfault later on in
  5590. * print_dir_entry(). memset is required only if mg_stat()
  5591. * fails. For more details, see
  5592. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  5593. memset(&de.file, 0, sizeof(de.file));
  5594. if (truncated) {
  5595. /* Do not delete anything shorter */
  5596. ok = 0;
  5597. continue;
  5598. }
  5599. if (!mg_stat(conn, path, &de.file)) {
  5600. mg_cry(conn,
  5601. "%s: mg_stat(%s) failed: %s",
  5602. __func__,
  5603. path,
  5604. strerror(ERRNO));
  5605. ok = 0;
  5606. }
  5607. if (de.file.membuf == NULL) {
  5608. /* file is not in memory */
  5609. if (de.file.is_directory) {
  5610. if (remove_directory(conn, path) == 0) {
  5611. ok = 0;
  5612. }
  5613. } else {
  5614. if (mg_remove(conn, path) == 0) {
  5615. ok = 0;
  5616. }
  5617. }
  5618. } else {
  5619. /* file is in memory. It can not be deleted. */
  5620. ok = 0;
  5621. }
  5622. }
  5623. (void)mg_closedir(dirp);
  5624. IGNORE_UNUSED_RESULT(rmdir(dir));
  5625. }
  5626. return ok;
  5627. }
  5628. #endif
  5629. struct dir_scan_data {
  5630. struct de *entries;
  5631. unsigned int num_entries;
  5632. unsigned int arr_size;
  5633. };
  5634. /* Behaves like realloc(), but frees original pointer on failure */
  5635. static void *
  5636. realloc2(void *ptr, size_t size)
  5637. {
  5638. void *new_ptr = mg_realloc(ptr, size);
  5639. if (new_ptr == NULL) {
  5640. mg_free(ptr);
  5641. }
  5642. return new_ptr;
  5643. }
  5644. static void
  5645. dir_scan_callback(struct de *de, void *data)
  5646. {
  5647. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  5648. if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {
  5649. dsd->arr_size *= 2;
  5650. dsd->entries =
  5651. (struct de *)realloc2(dsd->entries,
  5652. dsd->arr_size * sizeof(dsd->entries[0]));
  5653. }
  5654. if (dsd->entries == NULL) {
  5655. /* TODO(lsm, low): propagate an error to the caller */
  5656. dsd->num_entries = 0;
  5657. } else {
  5658. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  5659. dsd->entries[dsd->num_entries].file = de->file;
  5660. dsd->entries[dsd->num_entries].conn = de->conn;
  5661. dsd->num_entries++;
  5662. }
  5663. }
  5664. static void
  5665. handle_directory_request(struct mg_connection *conn, const char *dir)
  5666. {
  5667. unsigned int i;
  5668. int sort_direction;
  5669. struct dir_scan_data data = {NULL, 0, 128};
  5670. char date[64];
  5671. time_t curtime = time(NULL);
  5672. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  5673. send_http_error(conn,
  5674. 500,
  5675. "Error: Cannot open directory\nopendir(%s): %s",
  5676. dir,
  5677. strerror(ERRNO));
  5678. return;
  5679. }
  5680. gmt_time_string(date, sizeof(date), &curtime);
  5681. if (!conn) {
  5682. return;
  5683. }
  5684. sort_direction = ((conn->request_info.query_string != NULL)
  5685. && (conn->request_info.query_string[1] == 'd'))
  5686. ? 'a'
  5687. : 'd';
  5688. conn->must_close = 1;
  5689. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  5690. send_static_cache_header(conn);
  5691. mg_printf(conn,
  5692. "Date: %s\r\n"
  5693. "Connection: close\r\n"
  5694. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  5695. date);
  5696. conn->num_bytes_sent +=
  5697. mg_printf(conn,
  5698. "<html><head><title>Index of %s</title>"
  5699. "<style>th {text-align: left;}</style></head>"
  5700. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  5701. "<tr><th><a href=\"?n%c\">Name</a></th>"
  5702. "<th><a href=\"?d%c\">Modified</a></th>"
  5703. "<th><a href=\"?s%c\">Size</a></th></tr>"
  5704. "<tr><td colspan=\"3\"><hr></td></tr>",
  5705. conn->request_info.local_uri,
  5706. conn->request_info.local_uri,
  5707. sort_direction,
  5708. sort_direction,
  5709. sort_direction);
  5710. /* Print first entry - link to a parent directory */
  5711. conn->num_bytes_sent +=
  5712. mg_printf(conn,
  5713. "<tr><td><a href=\"%s%s\">%s</a></td>"
  5714. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  5715. conn->request_info.local_uri,
  5716. "..",
  5717. "Parent directory",
  5718. "-",
  5719. "-");
  5720. /* Sort and print directory entries */
  5721. if (data.entries != NULL) {
  5722. qsort(data.entries,
  5723. (size_t)data.num_entries,
  5724. sizeof(data.entries[0]),
  5725. compare_dir_entries);
  5726. for (i = 0; i < data.num_entries; i++) {
  5727. print_dir_entry(&data.entries[i]);
  5728. mg_free(data.entries[i].file_name);
  5729. }
  5730. mg_free(data.entries);
  5731. }
  5732. conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");
  5733. conn->status_code = 200;
  5734. }
  5735. /* Send len bytes from the opened file to the client. */
  5736. static void
  5737. send_file_data(struct mg_connection *conn,
  5738. struct file *filep,
  5739. int64_t offset,
  5740. int64_t len)
  5741. {
  5742. char buf[MG_BUF_LEN];
  5743. int to_read, num_read, num_written;
  5744. int64_t size;
  5745. if (!filep || !conn) {
  5746. return;
  5747. }
  5748. /* Sanity check the offset */
  5749. size = (filep->size > INT64_MAX) ? INT64_MAX : (int64_t)(filep->size);
  5750. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  5751. if (len > 0 && filep->membuf != NULL && size > 0) {
  5752. /* file stored in memory */
  5753. if (len > size - offset) {
  5754. len = size - offset;
  5755. }
  5756. mg_write(conn, filep->membuf + offset, (size_t)len);
  5757. } else if (len > 0 && filep->fp != NULL) {
  5758. /* file stored on disk */
  5759. #if defined(__linux__)
  5760. /* sendfile is only available for Linux */
  5761. if (conn->throttle == 0 && conn->ssl == 0) {
  5762. off_t sf_offs = (off_t)offset;
  5763. ssize_t sf_sent;
  5764. int sf_file = fileno(filep->fp);
  5765. int loop_cnt = 0;
  5766. do {
  5767. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  5768. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  5769. size_t sf_tosend =
  5770. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  5771. sf_sent =
  5772. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  5773. if (sf_sent > 0) {
  5774. conn->num_bytes_sent += sf_sent;
  5775. len -= sf_sent;
  5776. offset += sf_sent;
  5777. } else if (loop_cnt == 0) {
  5778. /* This file can not be sent using sendfile.
  5779. * This might be the case for pseudo-files in the
  5780. * /sys/ and /proc/ file system.
  5781. * Use the regular user mode copy code instead. */
  5782. break;
  5783. } else if (sf_sent == 0) {
  5784. /* No error, but 0 bytes sent. May be EOF? */
  5785. return;
  5786. }
  5787. loop_cnt++;
  5788. } while ((len > 0) && (sf_sent >= 0));
  5789. if (sf_sent > 0) {
  5790. return; /* OK */
  5791. }
  5792. /* sf_sent<0 means error, thus fall back to the classic way */
  5793. /* This is always the case, if sf_file is not a "normal" file,
  5794. * e.g., for sending data from the output of a CGI process. */
  5795. offset = (int64_t)sf_offs;
  5796. }
  5797. #endif
  5798. if ((offset > 0) && (fseeko(filep->fp, offset, SEEK_SET) != 0)) {
  5799. mg_cry(conn, "%s: fseeko() failed: %s", __func__, strerror(ERRNO));
  5800. send_http_error(
  5801. conn,
  5802. 500,
  5803. "%s",
  5804. "Error: Unable to access file at requested position.");
  5805. } else {
  5806. while (len > 0) {
  5807. /* Calculate how much to read from the file in the buffer */
  5808. to_read = sizeof(buf);
  5809. if ((int64_t)to_read > len) {
  5810. to_read = (int)len;
  5811. }
  5812. /* Read from file, exit the loop on error */
  5813. if ((num_read = (int)fread(buf, 1, (size_t)to_read, filep->fp))
  5814. <= 0) {
  5815. break;
  5816. }
  5817. /* Send read bytes to the client, exit the loop on error */
  5818. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  5819. != num_read) {
  5820. break;
  5821. }
  5822. /* Both read and were successful, adjust counters */
  5823. conn->num_bytes_sent += num_written;
  5824. len -= num_written;
  5825. }
  5826. }
  5827. }
  5828. }
  5829. static int
  5830. parse_range_header(const char *header, int64_t *a, int64_t *b)
  5831. {
  5832. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  5833. }
  5834. static void
  5835. construct_etag(char *buf, size_t buf_len, const struct file *filep)
  5836. {
  5837. if (filep != NULL && buf != NULL) {
  5838. mg_snprintf(NULL,
  5839. NULL, /* All calls to construct_etag use 64 byte buffer */
  5840. buf,
  5841. buf_len,
  5842. "\"%lx.%" INT64_FMT "\"",
  5843. (unsigned long)filep->last_modified,
  5844. filep->size);
  5845. }
  5846. }
  5847. static void
  5848. fclose_on_exec(struct file *filep, struct mg_connection *conn)
  5849. {
  5850. if (filep != NULL && filep->fp != NULL) {
  5851. #ifdef _WIN32
  5852. (void)conn; /* Unused. */
  5853. #else
  5854. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  5855. mg_cry(conn,
  5856. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  5857. __func__,
  5858. strerror(ERRNO));
  5859. }
  5860. #endif
  5861. }
  5862. }
  5863. static void
  5864. handle_static_file_request(struct mg_connection *conn,
  5865. const char *path,
  5866. struct file *filep,
  5867. const char *mime_type)
  5868. {
  5869. char date[64], lm[64], etag[64];
  5870. char range[128]; /* large enough, so there will be no overflow */
  5871. const char *msg = "OK", *hdr;
  5872. time_t curtime = time(NULL);
  5873. int64_t cl, r1, r2;
  5874. struct vec mime_vec;
  5875. int n, truncated;
  5876. char gz_path[PATH_MAX];
  5877. const char *encoding = "";
  5878. const char *cors1, *cors2, *cors3;
  5879. if (conn == NULL || conn->ctx == NULL || filep == NULL) {
  5880. return;
  5881. }
  5882. if (mime_type == NULL) {
  5883. get_mime_type(conn->ctx, path, &mime_vec);
  5884. } else {
  5885. mime_vec.ptr = mime_type;
  5886. mime_vec.len = strlen(mime_type);
  5887. }
  5888. if (filep->size > INT64_MAX) {
  5889. send_http_error(conn,
  5890. 500,
  5891. "Error: File size is too large to send\n%" INT64_FMT,
  5892. filep->size);
  5893. }
  5894. cl = (int64_t)filep->size;
  5895. conn->status_code = 200;
  5896. range[0] = '\0';
  5897. /* if this file is in fact a pre-gzipped file, rewrite its filename
  5898. * it's important to rewrite the filename after resolving
  5899. * the mime type from it, to preserve the actual file's type */
  5900. if (filep->gzipped) {
  5901. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  5902. if (truncated) {
  5903. send_http_error(conn,
  5904. 500,
  5905. "Error: Path of zipped file too long (%s)",
  5906. path);
  5907. return;
  5908. }
  5909. path = gz_path;
  5910. encoding = "Content-Encoding: gzip\r\n";
  5911. }
  5912. if (!mg_fopen(conn, path, "rb", filep)) {
  5913. send_http_error(conn,
  5914. 500,
  5915. "Error: Cannot open file\nfopen(%s): %s",
  5916. path,
  5917. strerror(ERRNO));
  5918. return;
  5919. }
  5920. fclose_on_exec(filep, conn);
  5921. /* If Range: header specified, act accordingly */
  5922. r1 = r2 = 0;
  5923. hdr = mg_get_header(conn, "Range");
  5924. if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 && r1 >= 0
  5925. && r2 >= 0) {
  5926. /* actually, range requests don't play well with a pre-gzipped
  5927. * file (since the range is specified in the uncompressed space) */
  5928. if (filep->gzipped) {
  5929. send_http_error(
  5930. conn,
  5931. 501,
  5932. "%s",
  5933. "Error: Range requests in gzipped files are not supported");
  5934. mg_fclose(filep);
  5935. return;
  5936. }
  5937. conn->status_code = 206;
  5938. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  5939. mg_snprintf(conn,
  5940. NULL, /* range buffer is big enough */
  5941. range,
  5942. sizeof(range),
  5943. "Content-Range: bytes "
  5944. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  5945. r1,
  5946. r1 + cl - 1,
  5947. filep->size);
  5948. msg = "Partial Content";
  5949. }
  5950. hdr = mg_get_header(conn, "Origin");
  5951. if (hdr) {
  5952. /* Cross-origin resource sharing (CORS), see
  5953. * http://www.html5rocks.com/en/tutorials/cors/,
  5954. * http://www.html5rocks.com/static/images/cors_server_flowchart.png -
  5955. * preflight is not supported for files. */
  5956. cors1 = "Access-Control-Allow-Origin: ";
  5957. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  5958. cors3 = "\r\n";
  5959. } else {
  5960. cors1 = cors2 = cors3 = "";
  5961. }
  5962. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
  5963. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  5964. gmt_time_string(date, sizeof(date), &curtime);
  5965. gmt_time_string(lm, sizeof(lm), &filep->last_modified);
  5966. construct_etag(etag, sizeof(etag), filep);
  5967. (void)mg_printf(conn,
  5968. "HTTP/1.1 %d %s\r\n"
  5969. "%s%s%s"
  5970. "Date: %s\r\n",
  5971. conn->status_code,
  5972. msg,
  5973. cors1,
  5974. cors2,
  5975. cors3,
  5976. date);
  5977. send_static_cache_header(conn);
  5978. (void)mg_printf(conn,
  5979. "Last-Modified: %s\r\n"
  5980. "Etag: %s\r\n"
  5981. "Content-Type: %.*s\r\n"
  5982. "Content-Length: %" INT64_FMT "\r\n"
  5983. "Connection: %s\r\n"
  5984. "Accept-Ranges: bytes\r\n"
  5985. "%s%s\r\n",
  5986. lm,
  5987. etag,
  5988. (int)mime_vec.len,
  5989. mime_vec.ptr,
  5990. cl,
  5991. suggest_connection_header(conn),
  5992. range,
  5993. encoding);
  5994. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  5995. send_file_data(conn, filep, r1, cl);
  5996. }
  5997. mg_fclose(filep);
  5998. }
  5999. #if !defined(NO_CACHING)
  6000. static void
  6001. handle_not_modified_static_file_request(struct mg_connection *conn,
  6002. struct file *filep)
  6003. {
  6004. char date[64], lm[64], etag[64];
  6005. time_t curtime = time(NULL);
  6006. if (conn == NULL || filep == NULL) {
  6007. return;
  6008. }
  6009. conn->status_code = 304;
  6010. gmt_time_string(date, sizeof(date), &curtime);
  6011. gmt_time_string(lm, sizeof(lm), &filep->last_modified);
  6012. construct_etag(etag, sizeof(etag), filep);
  6013. (void)mg_printf(conn,
  6014. "HTTP/1.1 %d %s\r\n"
  6015. "Date: %s\r\n",
  6016. conn->status_code,
  6017. mg_get_response_code_text(conn, conn->status_code),
  6018. date);
  6019. send_static_cache_header(conn);
  6020. (void)mg_printf(conn,
  6021. "Last-Modified: %s\r\n"
  6022. "Etag: %s\r\n"
  6023. "Connection: %s\r\n"
  6024. "\r\n",
  6025. lm,
  6026. etag,
  6027. suggest_connection_header(conn));
  6028. }
  6029. #endif
  6030. void
  6031. mg_send_file(struct mg_connection *conn, const char *path)
  6032. {
  6033. mg_send_mime_file(conn, path, NULL);
  6034. }
  6035. void
  6036. mg_send_mime_file(struct mg_connection *conn,
  6037. const char *path,
  6038. const char *mime_type)
  6039. {
  6040. struct file file = STRUCT_FILE_INITIALIZER;
  6041. if (mg_stat(conn, path, &file)) {
  6042. if (file.is_directory) {
  6043. if (!conn) {
  6044. return;
  6045. }
  6046. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  6047. "yes")) {
  6048. handle_directory_request(conn, path);
  6049. } else {
  6050. send_http_error(conn,
  6051. 403,
  6052. "%s",
  6053. "Error: Directory listing denied");
  6054. }
  6055. } else {
  6056. handle_static_file_request(conn, path, &file, mime_type);
  6057. }
  6058. } else {
  6059. send_http_error(conn, 404, "%s", "Error: File not found");
  6060. }
  6061. }
  6062. /* For a given PUT path, create all intermediate subdirectories.
  6063. * Return 0 if the path itself is a directory.
  6064. * Return 1 if the path leads to a file.
  6065. * Return -1 for if the path is too long.
  6066. * Return -2 if path can not be created.
  6067. */
  6068. static int
  6069. put_dir(struct mg_connection *conn, const char *path)
  6070. {
  6071. char buf[PATH_MAX];
  6072. const char *s, *p;
  6073. struct file file = STRUCT_FILE_INITIALIZER;
  6074. size_t len;
  6075. int res = 1;
  6076. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  6077. len = (size_t)(p - path);
  6078. if (len >= sizeof(buf)) {
  6079. /* path too long */
  6080. res = -1;
  6081. break;
  6082. }
  6083. memcpy(buf, path, len);
  6084. buf[len] = '\0';
  6085. /* Try to create intermediate directory */
  6086. DEBUG_TRACE("mkdir(%s)", buf);
  6087. if (!mg_stat(conn, buf, &file) && mg_mkdir(conn, buf, 0755) != 0) {
  6088. /* path does not exixt and can not be created */
  6089. res = -2;
  6090. break;
  6091. }
  6092. /* Is path itself a directory? */
  6093. if (p[1] == '\0') {
  6094. res = 0;
  6095. }
  6096. }
  6097. return res;
  6098. }
  6099. static void
  6100. remove_bad_file(const struct mg_connection *conn, const char *path)
  6101. {
  6102. int r = mg_remove(conn, path);
  6103. if (r != 0) {
  6104. mg_cry(conn, "%s: Cannot remove invalid file %s", __func__, path);
  6105. }
  6106. }
  6107. long long
  6108. mg_store_body(struct mg_connection *conn, const char *path)
  6109. {
  6110. char buf[MG_BUF_LEN];
  6111. long long len = 0;
  6112. int ret, n;
  6113. struct file fi;
  6114. if (conn->consumed_content != 0) {
  6115. mg_cry(conn, "%s: Contents already consumed", __func__);
  6116. return -11;
  6117. }
  6118. ret = put_dir(conn, path);
  6119. if (ret < 0) {
  6120. /* -1 for path too long,
  6121. * -2 for path can not be created. */
  6122. return ret;
  6123. }
  6124. if (ret != 1) {
  6125. /* Return 0 means, path itself is a directory. */
  6126. return 0;
  6127. }
  6128. if (mg_fopen(conn, path, "w", &fi) == 0) {
  6129. return -12;
  6130. }
  6131. ret = mg_read(conn, buf, sizeof(buf));
  6132. while (ret > 0) {
  6133. n = (int)fwrite(buf, 1, (size_t)ret, fi.fp);
  6134. if (n != ret) {
  6135. mg_fclose(&fi);
  6136. remove_bad_file(conn, path);
  6137. return -13;
  6138. }
  6139. ret = mg_read(conn, buf, sizeof(buf));
  6140. }
  6141. /* TODO: mg_fclose should return an error,
  6142. * and every caller should check and handle it. */
  6143. if (fclose(fi.fp) != 0) {
  6144. remove_bad_file(conn, path);
  6145. return -14;
  6146. }
  6147. return len;
  6148. }
  6149. /* Parse HTTP headers from the given buffer, advance buf pointer
  6150. * to the point where parsing stopped.
  6151. * All parameters must be valid pointers (not NULL).
  6152. * Return <0 on error. */
  6153. static int
  6154. parse_http_headers(char **buf, struct mg_request_info *ri)
  6155. {
  6156. int i;
  6157. ri->num_headers = 0;
  6158. for (i = 0; i < (int)ARRAY_SIZE(ri->http_headers); i++) {
  6159. char *dp = *buf;
  6160. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  6161. dp++;
  6162. }
  6163. if (dp == *buf) {
  6164. /* End of headers reached. */
  6165. break;
  6166. }
  6167. if (*dp != ':') {
  6168. /* This is not a valid field. */
  6169. return -1;
  6170. }
  6171. /* End of header key (*dp == ':') */
  6172. /* Truncate here and set the key name */
  6173. *dp = 0;
  6174. ri->http_headers[i].name = *buf;
  6175. do {
  6176. dp++;
  6177. } while (*dp == ' ');
  6178. /* The rest of the line is the value */
  6179. ri->http_headers[i].value = dp;
  6180. *buf = dp + strcspn(dp, "\r\n");
  6181. if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) {
  6182. *buf = NULL;
  6183. }
  6184. ri->num_headers = i + 1;
  6185. if (*buf) {
  6186. (*buf)[0] = 0;
  6187. (*buf)[1] = 0;
  6188. *buf += 2;
  6189. } else {
  6190. *buf = dp;
  6191. break;
  6192. }
  6193. if ((*buf)[0] == '\r') {
  6194. /* This is the end of the header */
  6195. break;
  6196. }
  6197. }
  6198. return ri->num_headers;
  6199. }
  6200. static int
  6201. is_valid_http_method(const char *method)
  6202. {
  6203. return !strcmp(method, "GET") /* HTTP (RFC 2616) */
  6204. || !strcmp(method, "POST") /* HTTP (RFC 2616) */
  6205. || !strcmp(method, "HEAD") /* HTTP (RFC 2616) */
  6206. || !strcmp(method, "PUT") /* HTTP (RFC 2616) */
  6207. || !strcmp(method, "DELETE") /* HTTP (RFC 2616) */
  6208. || !strcmp(method, "OPTIONS") /* HTTP (RFC 2616) */
  6209. /* TRACE method (RFC 2616) is not supported for security reasons */
  6210. || !strcmp(method, "CONNECT") /* HTTP (RFC 2616) */
  6211. || !strcmp(method, "PROPFIND") /* WEBDAV (RFC 2518) */
  6212. || !strcmp(method, "MKCOL") /* WEBDAV (RFC 2518) */
  6213. /* Unsupported WEBDAV Methods: */
  6214. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  6215. /* + 11 methods from RFC 3253 */
  6216. /* ORDERPATCH (RFC 3648) */
  6217. /* ACL (RFC 3744) */
  6218. /* SEARCH (RFC 5323) */
  6219. /* + MicroSoft extensions
  6220. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  6221. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  6222. || !strcmp(method, "PATCH"); /* PATCH method (RFC 5789) */
  6223. }
  6224. /* Parse HTTP request, fill in mg_request_info structure.
  6225. * This function modifies the buffer by NUL-terminating
  6226. * HTTP request components, header names and header values.
  6227. * Parameters:
  6228. * buf (in/out): pointer to the HTTP header to parse and split
  6229. * len (in): length of HTTP header buffer
  6230. * re (out): parsed header as mg_request_info
  6231. * buf and ri must be valid pointers (not NULL), len>0.
  6232. * Returns <0 on error. */
  6233. static int
  6234. parse_http_message(char *buf, int len, struct mg_request_info *ri)
  6235. {
  6236. int is_request, request_length;
  6237. char *start_line;
  6238. request_length = get_request_len(buf, len);
  6239. if (request_length > 0) {
  6240. /* Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_addr,
  6241. * remote_port */
  6242. ri->remote_user = ri->request_method = ri->request_uri =
  6243. ri->http_version = NULL;
  6244. ri->num_headers = 0;
  6245. buf[request_length - 1] = '\0';
  6246. /* RFC says that all initial whitespaces should be ingored */
  6247. while (*buf != '\0' && isspace(*(unsigned char *)buf)) {
  6248. buf++;
  6249. }
  6250. start_line = skip(&buf, "\r\n");
  6251. ri->request_method = skip(&start_line, " ");
  6252. ri->request_uri = skip(&start_line, " ");
  6253. ri->http_version = start_line;
  6254. /* HTTP message could be either HTTP request:
  6255. * "GET / HTTP/1.0 ..."
  6256. * or a HTTP response:
  6257. * "HTTP/1.0 200 OK ..."
  6258. * otherwise it is invalid.
  6259. */
  6260. is_request = is_valid_http_method(ri->request_method);
  6261. if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0)
  6262. || (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
  6263. /* Not a valid request or response: invalid */
  6264. return -1;
  6265. }
  6266. if (is_request) {
  6267. ri->http_version += 5;
  6268. }
  6269. if (parse_http_headers(&buf, ri) < 0) {
  6270. /* Error while parsing headers */
  6271. return -1;
  6272. }
  6273. }
  6274. return request_length;
  6275. }
  6276. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  6277. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  6278. * buffer (which marks the end of HTTP request). Buffer buf may already
  6279. * have some data. The length of the data is stored in nread.
  6280. * Upon every read operation, increase nread by the number of bytes read. */
  6281. static int
  6282. read_request(FILE *fp,
  6283. struct mg_connection *conn,
  6284. char *buf,
  6285. int bufsiz,
  6286. int *nread)
  6287. {
  6288. int request_len, n = 0;
  6289. struct timespec last_action_time;
  6290. double request_timeout;
  6291. if (!conn) {
  6292. return 0;
  6293. }
  6294. memset(&last_action_time, 0, sizeof(last_action_time));
  6295. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  6296. /* value of request_timeout is in seconds, config in milliseconds */
  6297. request_timeout = atof(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  6298. } else {
  6299. request_timeout = -1.0;
  6300. }
  6301. request_len = get_request_len(buf, *nread);
  6302. /* first time reading from this connection */
  6303. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  6304. while (
  6305. (conn->ctx->stop_flag == 0) && (*nread < bufsiz) && (request_len == 0)
  6306. && ((mg_difftimespec(&last_action_time, &(conn->req_time))
  6307. <= request_timeout) || (request_timeout < 0))
  6308. && ((n = pull(fp, conn, buf + *nread, bufsiz - *nread, request_timeout))
  6309. > 0)) {
  6310. *nread += n;
  6311. /* assert(*nread <= bufsiz); */
  6312. if (*nread > bufsiz) {
  6313. return -2;
  6314. }
  6315. request_len = get_request_len(buf, *nread);
  6316. if (request_timeout > 0.0) {
  6317. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  6318. }
  6319. }
  6320. return ((request_len <= 0) && (n <= 0)) ? -1 : request_len;
  6321. }
  6322. #if !defined(NO_FILES)
  6323. /* For given directory path, substitute it to valid index file.
  6324. * Return 1 if index file has been found, 0 if not found.
  6325. * If the file is found, it's stats is returned in stp. */
  6326. static int
  6327. substitute_index_file(struct mg_connection *conn,
  6328. char *path,
  6329. size_t path_len,
  6330. struct file *filep)
  6331. {
  6332. if (conn && conn->ctx) {
  6333. const char *list = conn->ctx->config[INDEX_FILES];
  6334. struct file file = STRUCT_FILE_INITIALIZER;
  6335. struct vec filename_vec;
  6336. size_t n = strlen(path);
  6337. int found = 0;
  6338. /* The 'path' given to us points to the directory. Remove all trailing
  6339. * directory separator characters from the end of the path, and
  6340. * then append single directory separator character. */
  6341. while (n > 0 && path[n - 1] == '/') {
  6342. n--;
  6343. }
  6344. path[n] = '/';
  6345. /* Traverse index files list. For each entry, append it to the given
  6346. * path and see if the file exists. If it exists, break the loop */
  6347. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6348. /* Ignore too long entries that may overflow path buffer */
  6349. if (filename_vec.len > path_len - (n + 2)) {
  6350. continue;
  6351. }
  6352. /* Prepare full path to the index file */
  6353. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6354. /* Does it exist? */
  6355. if (mg_stat(conn, path, &file)) {
  6356. /* Yes it does, break the loop */
  6357. *filep = file;
  6358. found = 1;
  6359. break;
  6360. }
  6361. }
  6362. /* If no index file exists, restore directory path */
  6363. if (!found) {
  6364. path[n] = '\0';
  6365. }
  6366. return found;
  6367. }
  6368. return 0;
  6369. }
  6370. #endif
  6371. #if !defined(NO_CACHING)
  6372. /* Return True if we should reply 304 Not Modified. */
  6373. static int
  6374. is_not_modified(const struct mg_connection *conn, const struct file *filep)
  6375. {
  6376. char etag[64];
  6377. const char *ims = mg_get_header(conn, "If-Modified-Since");
  6378. const char *inm = mg_get_header(conn, "If-None-Match");
  6379. construct_etag(etag, sizeof(etag), filep);
  6380. if (!filep) {
  6381. return 0;
  6382. }
  6383. return (inm != NULL && !mg_strcasecmp(etag, inm))
  6384. || (ims != NULL && (filep->last_modified <= parse_date_string(ims)));
  6385. }
  6386. #endif /* !NO_CACHING */
  6387. #if !defined(NO_CGI) || !defined(NO_FILES)
  6388. static int
  6389. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  6390. {
  6391. const char *expect, *body;
  6392. char buf[MG_BUF_LEN];
  6393. int to_read, nread, success = 0;
  6394. int64_t buffered_len;
  6395. double timeout = -1.0;
  6396. if (!conn) {
  6397. return 0;
  6398. }
  6399. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  6400. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  6401. }
  6402. expect = mg_get_header(conn, "Expect");
  6403. /* assert(fp != NULL); */
  6404. if (!fp) {
  6405. send_http_error(conn, 500, "%s", "Error: NULL File");
  6406. return 0;
  6407. }
  6408. if (conn->content_len == -1 && !conn->is_chunked) {
  6409. /* Content length is not specified by the client. */
  6410. send_http_error(conn,
  6411. 411,
  6412. "%s",
  6413. "Error: Client did not specify content length");
  6414. } else if ((expect != NULL)
  6415. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  6416. /* Client sent an "Expect: xyz" header and xyz is not 100-continue. */
  6417. send_http_error(conn,
  6418. 417,
  6419. "Error: Can not fulfill expectation %s",
  6420. expect);
  6421. } else {
  6422. if (expect != NULL) {
  6423. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  6424. conn->status_code = 100;
  6425. } else {
  6426. conn->status_code = 200;
  6427. }
  6428. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  6429. - conn->consumed_content;
  6430. /* assert(buffered_len >= 0); */
  6431. /* assert(conn->consumed_content == 0); */
  6432. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  6433. send_http_error(conn, 500, "%s", "Error: Size mismatch");
  6434. return 0;
  6435. }
  6436. if (buffered_len > 0) {
  6437. if ((int64_t)buffered_len > conn->content_len) {
  6438. buffered_len = (int)conn->content_len;
  6439. }
  6440. body = conn->buf + conn->request_len + conn->consumed_content;
  6441. push_all(conn->ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  6442. conn->consumed_content += buffered_len;
  6443. }
  6444. nread = 0;
  6445. while (conn->consumed_content < conn->content_len) {
  6446. to_read = sizeof(buf);
  6447. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  6448. to_read = (int)(conn->content_len - conn->consumed_content);
  6449. }
  6450. nread = pull(NULL, conn, buf, to_read, timeout);
  6451. if (nread <= 0
  6452. || push_all(conn->ctx, fp, sock, ssl, buf, nread) != nread) {
  6453. break;
  6454. }
  6455. conn->consumed_content += nread;
  6456. }
  6457. if (conn->consumed_content == conn->content_len) {
  6458. success = (nread >= 0);
  6459. }
  6460. /* Each error code path in this function must send an error */
  6461. if (!success) {
  6462. /* NOTE: Maybe some data has already been sent. */
  6463. /* TODO (low): If some data has been sent, a correct error
  6464. * reply can no longer be sent, so just close the connection */
  6465. send_http_error(conn, 500, "%s", "");
  6466. }
  6467. }
  6468. return success;
  6469. }
  6470. #endif
  6471. #if !defined(NO_CGI)
  6472. /* This structure helps to create an environment for the spawned CGI program.
  6473. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  6474. * last element must be NULL.
  6475. * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  6476. * strings must reside in a contiguous buffer. The end of the buffer is
  6477. * marked by two '\0' characters.
  6478. * We satisfy both worlds: we create an envp array (which is vars), all
  6479. * entries are actually pointers inside buf. */
  6480. struct cgi_environment {
  6481. struct mg_connection *conn;
  6482. /* Data block */
  6483. char *buf; /* Environment buffer */
  6484. size_t buflen; /* Space available in buf */
  6485. size_t bufused; /* Space taken in buf */
  6486. /* Index block */
  6487. char **var; /* char **envp */
  6488. size_t varlen; /* Number of variables available in var */
  6489. size_t varused; /* Number of variables stored in var */
  6490. };
  6491. static void addenv(struct cgi_environment *env,
  6492. PRINTF_FORMAT_STRING(const char *fmt),
  6493. ...) PRINTF_ARGS(2, 3);
  6494. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  6495. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  6496. static void
  6497. addenv(struct cgi_environment *env, const char *fmt, ...)
  6498. {
  6499. size_t n, space;
  6500. int truncated;
  6501. char *added;
  6502. va_list ap;
  6503. /* Calculate how much space is left in the buffer */
  6504. space = (env->buflen - env->bufused);
  6505. /* Calculate an estimate for the required space */
  6506. n = strlen(fmt) + 2 + 128;
  6507. do {
  6508. if (space <= n) {
  6509. /* Allocate new buffer */
  6510. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  6511. added = (char *)mg_realloc(env->buf, n);
  6512. if (!added) {
  6513. /* Out of memory */
  6514. mg_cry(env->conn,
  6515. "%s: Cannot allocate memory for CGI variable [%s]",
  6516. __func__,
  6517. fmt);
  6518. return;
  6519. }
  6520. env->buf = added;
  6521. env->buflen = n;
  6522. space = (env->buflen - env->bufused);
  6523. }
  6524. /* Make a pointer to the free space int the buffer */
  6525. added = env->buf + env->bufused;
  6526. /* Copy VARIABLE=VALUE\0 string into the free space */
  6527. va_start(ap, fmt);
  6528. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  6529. va_end(ap);
  6530. /* Do not add truncated strings to the environment */
  6531. if (truncated) {
  6532. /* Reallocate the buffer */
  6533. space = 0;
  6534. n = 1;
  6535. }
  6536. } while (truncated);
  6537. /* Calculate number of bytes added to the environment */
  6538. n = strlen(added) + 1;
  6539. env->bufused += n;
  6540. /* Now update the variable index */
  6541. space = (env->varlen - env->varused);
  6542. if (space < 2) {
  6543. mg_cry(env->conn,
  6544. "%s: Cannot register CGI variable [%s]",
  6545. __func__,
  6546. fmt);
  6547. return;
  6548. }
  6549. /* Append a pointer to the added string into the envp array */
  6550. env->var[env->varused] = added;
  6551. env->varused++;
  6552. }
  6553. static void
  6554. prepare_cgi_environment(struct mg_connection *conn,
  6555. const char *prog,
  6556. struct cgi_environment *env)
  6557. {
  6558. const char *s;
  6559. struct vec var_vec;
  6560. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  6561. int i, truncated;
  6562. if (conn == NULL || prog == NULL || env == NULL) {
  6563. return;
  6564. }
  6565. env->conn = conn;
  6566. env->buflen = CGI_ENVIRONMENT_SIZE;
  6567. env->bufused = 0;
  6568. env->buf = (char *)mg_malloc(env->buflen);
  6569. env->varlen = MAX_CGI_ENVIR_VARS;
  6570. env->varused = 0;
  6571. env->var = (char **)mg_malloc(env->buflen * sizeof(char *));
  6572. addenv(env, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  6573. addenv(env, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6574. addenv(env, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6575. addenv(env, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  6576. /* Prepare the environment block */
  6577. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  6578. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  6579. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  6580. #if defined(USE_IPV6)
  6581. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  6582. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  6583. } else
  6584. #endif
  6585. {
  6586. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  6587. }
  6588. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  6589. addenv(env, "REMOTE_ADDR=%s", src_addr);
  6590. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  6591. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  6592. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  6593. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  6594. /* SCRIPT_NAME */
  6595. addenv(env,
  6596. "SCRIPT_NAME=%.*s",
  6597. (int)strlen(conn->request_info.local_uri)
  6598. - ((conn->path_info == NULL) ? 0 : (int)strlen(conn->path_info)),
  6599. conn->request_info.local_uri);
  6600. addenv(env, "SCRIPT_FILENAME=%s", prog);
  6601. if (conn->path_info == NULL) {
  6602. addenv(env, "PATH_TRANSLATED=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6603. } else {
  6604. addenv(env,
  6605. "PATH_TRANSLATED=%s%s",
  6606. conn->ctx->config[DOCUMENT_ROOT],
  6607. conn->path_info);
  6608. }
  6609. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  6610. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  6611. addenv(env, "CONTENT_TYPE=%s", s);
  6612. }
  6613. if (conn->request_info.query_string != NULL) {
  6614. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  6615. }
  6616. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  6617. addenv(env, "CONTENT_LENGTH=%s", s);
  6618. }
  6619. if ((s = getenv("PATH")) != NULL) {
  6620. addenv(env, "PATH=%s", s);
  6621. }
  6622. if (conn->path_info != NULL) {
  6623. addenv(env, "PATH_INFO=%s", conn->path_info);
  6624. }
  6625. if (conn->status_code > 0) {
  6626. /* CGI error handler should show the status code */
  6627. addenv(env, "STATUS=%d", conn->status_code);
  6628. }
  6629. #if defined(_WIN32)
  6630. if ((s = getenv("COMSPEC")) != NULL) {
  6631. addenv(env, "COMSPEC=%s", s);
  6632. }
  6633. if ((s = getenv("SYSTEMROOT")) != NULL) {
  6634. addenv(env, "SYSTEMROOT=%s", s);
  6635. }
  6636. if ((s = getenv("SystemDrive")) != NULL) {
  6637. addenv(env, "SystemDrive=%s", s);
  6638. }
  6639. if ((s = getenv("ProgramFiles")) != NULL) {
  6640. addenv(env, "ProgramFiles=%s", s);
  6641. }
  6642. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  6643. addenv(env, "ProgramFiles(x86)=%s", s);
  6644. }
  6645. #else
  6646. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  6647. addenv(env, "LD_LIBRARY_PATH=%s", s);
  6648. }
  6649. #endif /* _WIN32 */
  6650. if ((s = getenv("PERLLIB")) != NULL) {
  6651. addenv(env, "PERLLIB=%s", s);
  6652. }
  6653. if (conn->request_info.remote_user != NULL) {
  6654. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  6655. addenv(env, "%s", "AUTH_TYPE=Digest");
  6656. }
  6657. /* Add all headers as HTTP_* variables */
  6658. for (i = 0; i < conn->request_info.num_headers; i++) {
  6659. (void)mg_snprintf(conn,
  6660. &truncated,
  6661. http_var_name,
  6662. sizeof(http_var_name),
  6663. "HTTP_%s",
  6664. conn->request_info.http_headers[i].name);
  6665. if (truncated) {
  6666. mg_cry(conn,
  6667. "%s: HTTP header variable too long [%s]",
  6668. __func__,
  6669. conn->request_info.http_headers[i].name);
  6670. continue;
  6671. }
  6672. /* Convert variable name into uppercase, and change - to _ */
  6673. for (p = http_var_name; *p != '\0'; p++) {
  6674. if (*p == '-') {
  6675. *p = '_';
  6676. }
  6677. *p = (char)toupper(*(unsigned char *)p);
  6678. }
  6679. addenv(env,
  6680. "%s=%s",
  6681. http_var_name,
  6682. conn->request_info.http_headers[i].value);
  6683. }
  6684. /* Add user-specified variables */
  6685. s = conn->ctx->config[CGI_ENVIRONMENT];
  6686. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  6687. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  6688. }
  6689. env->var[env->varused] = NULL;
  6690. env->buf[env->bufused] = '\0';
  6691. }
  6692. static void
  6693. handle_cgi_request(struct mg_connection *conn, const char *prog)
  6694. {
  6695. char *buf;
  6696. size_t buflen;
  6697. int headers_len, data_len, i, truncated;
  6698. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  6699. const char *status, *status_text, *connection_state;
  6700. char *pbuf, dir[PATH_MAX], *p;
  6701. struct mg_request_info ri;
  6702. struct cgi_environment blk;
  6703. FILE *in = NULL, *out = NULL, *err = NULL;
  6704. struct file fout = STRUCT_FILE_INITIALIZER;
  6705. pid_t pid = (pid_t)-1;
  6706. if (conn == NULL) {
  6707. return;
  6708. }
  6709. buf = NULL;
  6710. buflen = 16384;
  6711. prepare_cgi_environment(conn, prog, &blk);
  6712. /* CGI must be executed in its own directory. 'dir' must point to the
  6713. * directory containing executable program, 'p' must point to the
  6714. * executable program name relative to 'dir'. */
  6715. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  6716. if (truncated) {
  6717. mg_cry(conn, "Error: CGI program \"%s\": Path too long", prog);
  6718. send_http_error(conn, 500, "Error: %s", "CGI path too long");
  6719. goto done;
  6720. }
  6721. if ((p = strrchr(dir, '/')) != NULL) {
  6722. *p++ = '\0';
  6723. } else {
  6724. dir[0] = '.', dir[1] = '\0';
  6725. p = (char *)prog;
  6726. }
  6727. if (pipe(fdin) != 0 || pipe(fdout) != 0 || pipe(fderr) != 0) {
  6728. status = strerror(ERRNO);
  6729. mg_cry(conn,
  6730. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  6731. prog,
  6732. status);
  6733. send_http_error(conn, 500, "Error: Cannot create CGI pipe: %s", status);
  6734. goto done;
  6735. }
  6736. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  6737. if (pid == (pid_t)-1) {
  6738. status = strerror(ERRNO);
  6739. mg_cry(conn,
  6740. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  6741. prog,
  6742. status);
  6743. send_http_error(conn,
  6744. 500,
  6745. "Error: Cannot spawn CGI process [%s]: %s",
  6746. prog,
  6747. status);
  6748. goto done;
  6749. }
  6750. /* Make sure child closes all pipe descriptors. It must dup them to 0,1 */
  6751. set_close_on_exec((SOCKET)fdin[0], conn); /* stdin read */
  6752. set_close_on_exec((SOCKET)fdout[1], conn); /* stdout write */
  6753. set_close_on_exec((SOCKET)fderr[1], conn); /* stderr write */
  6754. set_close_on_exec((SOCKET)fdin[1], conn); /* stdin write */
  6755. set_close_on_exec((SOCKET)fdout[0], conn); /* stdout read */
  6756. set_close_on_exec((SOCKET)fderr[0], conn); /* stderr read */
  6757. /* Parent closes only one side of the pipes.
  6758. * If we don't mark them as closed, close() attempt before
  6759. * return from this function throws an exception on Windows.
  6760. * Windows does not like when closed descriptor is closed again. */
  6761. (void)close(fdin[0]);
  6762. (void)close(fdout[1]);
  6763. (void)close(fderr[1]);
  6764. fdin[0] = fdout[1] = fderr[1] = -1;
  6765. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  6766. status = strerror(ERRNO);
  6767. mg_cry(conn,
  6768. "Error: CGI program \"%s\": Can not open stdin: %s",
  6769. prog,
  6770. status);
  6771. send_http_error(conn,
  6772. 500,
  6773. "Error: CGI can not open fdin\nfopen: %s",
  6774. status);
  6775. goto done;
  6776. }
  6777. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  6778. status = strerror(ERRNO);
  6779. mg_cry(conn,
  6780. "Error: CGI program \"%s\": Can not open stdout: %s",
  6781. prog,
  6782. status);
  6783. send_http_error(conn,
  6784. 500,
  6785. "Error: CGI can not open fdout\nfopen: %s",
  6786. status);
  6787. goto done;
  6788. }
  6789. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  6790. status = strerror(ERRNO);
  6791. mg_cry(conn,
  6792. "Error: CGI program \"%s\": Can not open stderr: %s",
  6793. prog,
  6794. status);
  6795. send_http_error(conn,
  6796. 500,
  6797. "Error: CGI can not open fdout\nfopen: %s",
  6798. status);
  6799. goto done;
  6800. }
  6801. setbuf(in, NULL);
  6802. setbuf(out, NULL);
  6803. setbuf(err, NULL);
  6804. fout.fp = out;
  6805. if ((conn->request_info.content_length > 0) || conn->is_chunked) {
  6806. /* This is a POST/PUT request, or another request with body data. */
  6807. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  6808. /* Error sending the body data */
  6809. mg_cry(conn,
  6810. "Error: CGI program \"%s\": Forward body data failed",
  6811. prog);
  6812. goto done;
  6813. }
  6814. }
  6815. /* Close so child gets an EOF. */
  6816. fclose(in);
  6817. in = NULL;
  6818. fdin[1] = -1;
  6819. /* Now read CGI reply into a buffer. We need to set correct
  6820. * status code, thus we need to see all HTTP headers first.
  6821. * Do not send anything back to client, until we buffer in all
  6822. * HTTP headers. */
  6823. data_len = 0;
  6824. buf = (char *)mg_malloc(buflen);
  6825. if (buf == NULL) {
  6826. send_http_error(conn,
  6827. 500,
  6828. "Error: Not enough memory for CGI buffer (%u bytes)",
  6829. (unsigned int)buflen);
  6830. mg_cry(conn,
  6831. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  6832. "bytes)",
  6833. prog,
  6834. (unsigned int)buflen);
  6835. goto done;
  6836. }
  6837. headers_len = read_request(out, conn, buf, (int)buflen, &data_len);
  6838. if (headers_len <= 0) {
  6839. /* Could not parse the CGI response. Check if some error message on
  6840. * stderr. */
  6841. i = pull_all(err, conn, buf, (int)buflen);
  6842. if (i > 0) {
  6843. mg_cry(conn,
  6844. "Error: CGI program \"%s\" sent error "
  6845. "message: [%.*s]",
  6846. prog,
  6847. i,
  6848. buf);
  6849. send_http_error(conn,
  6850. 500,
  6851. "Error: CGI program \"%s\" sent error "
  6852. "message: [%.*s]",
  6853. prog,
  6854. i,
  6855. buf);
  6856. } else {
  6857. mg_cry(conn,
  6858. "Error: CGI program sent malformed or too big "
  6859. "(>%u bytes) HTTP headers: [%.*s]",
  6860. (unsigned)buflen,
  6861. data_len,
  6862. buf);
  6863. send_http_error(conn,
  6864. 500,
  6865. "Error: CGI program sent malformed or too big "
  6866. "(>%u bytes) HTTP headers: [%.*s]",
  6867. (unsigned)buflen,
  6868. data_len,
  6869. buf);
  6870. }
  6871. goto done;
  6872. }
  6873. pbuf = buf;
  6874. buf[headers_len - 1] = '\0';
  6875. parse_http_headers(&pbuf, &ri);
  6876. /* Make up and send the status line */
  6877. status_text = "OK";
  6878. if ((status = get_header(&ri, "Status")) != NULL) {
  6879. conn->status_code = atoi(status);
  6880. status_text = status;
  6881. while (isdigit(*(const unsigned char *)status_text)
  6882. || *status_text == ' ') {
  6883. status_text++;
  6884. }
  6885. } else if (get_header(&ri, "Location") != NULL) {
  6886. conn->status_code = 302;
  6887. } else {
  6888. conn->status_code = 200;
  6889. }
  6890. connection_state = get_header(&ri, "Connection");
  6891. if (!header_has_option(connection_state, "keep-alive")) {
  6892. conn->must_close = 1;
  6893. }
  6894. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  6895. /* Send headers */
  6896. for (i = 0; i < ri.num_headers; i++) {
  6897. mg_printf(conn,
  6898. "%s: %s\r\n",
  6899. ri.http_headers[i].name,
  6900. ri.http_headers[i].value);
  6901. }
  6902. mg_write(conn, "\r\n", 2);
  6903. /* Send chunk of data that may have been read after the headers */
  6904. conn->num_bytes_sent +=
  6905. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  6906. /* Read the rest of CGI output and send to the client */
  6907. send_file_data(conn, &fout, 0, INT64_MAX);
  6908. done:
  6909. mg_free(blk.var);
  6910. mg_free(blk.buf);
  6911. if (pid != (pid_t)-1) {
  6912. kill(pid, SIGKILL);
  6913. #if !defined(_WIN32)
  6914. {
  6915. int st;
  6916. while (waitpid(pid, &st, 0) != -1)
  6917. ; /* clean zombies */
  6918. }
  6919. #endif
  6920. }
  6921. if (fdin[0] != -1) {
  6922. close(fdin[0]);
  6923. }
  6924. if (fdout[1] != -1) {
  6925. close(fdout[1]);
  6926. }
  6927. if (in != NULL) {
  6928. fclose(in);
  6929. } else if (fdin[1] != -1) {
  6930. close(fdin[1]);
  6931. }
  6932. if (out != NULL) {
  6933. fclose(out);
  6934. } else if (fdout[0] != -1) {
  6935. close(fdout[0]);
  6936. }
  6937. if (err != NULL) {
  6938. fclose(err);
  6939. } else if (fderr[0] != -1) {
  6940. close(fderr[0]);
  6941. }
  6942. if (buf != NULL) {
  6943. mg_free(buf);
  6944. }
  6945. }
  6946. #endif /* !NO_CGI */
  6947. #if !defined(NO_FILES)
  6948. static void
  6949. mkcol(struct mg_connection *conn, const char *path)
  6950. {
  6951. int rc, body_len;
  6952. struct de de;
  6953. char date[64];
  6954. time_t curtime = time(NULL);
  6955. if (conn == NULL) {
  6956. return;
  6957. }
  6958. /* TODO (mid): Check the send_http_error situations in this function */
  6959. memset(&de.file, 0, sizeof(de.file));
  6960. if (!mg_stat(conn, path, &de.file)) {
  6961. mg_cry(conn,
  6962. "%s: mg_stat(%s) failed: %s",
  6963. __func__,
  6964. path,
  6965. strerror(ERRNO));
  6966. }
  6967. if (de.file.last_modified) {
  6968. /* TODO (high): This check does not seem to make any sense ! */
  6969. send_http_error(
  6970. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6971. return;
  6972. }
  6973. body_len = conn->data_len - conn->request_len;
  6974. if (body_len > 0) {
  6975. send_http_error(
  6976. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6977. return;
  6978. }
  6979. rc = mg_mkdir(conn, path, 0755);
  6980. if (rc == 0) {
  6981. conn->status_code = 201;
  6982. gmt_time_string(date, sizeof(date), &curtime);
  6983. mg_printf(conn,
  6984. "HTTP/1.1 %d Created\r\n"
  6985. "Date: %s\r\n",
  6986. conn->status_code,
  6987. date);
  6988. send_static_cache_header(conn);
  6989. mg_printf(conn,
  6990. "Content-Length: 0\r\n"
  6991. "Connection: %s\r\n\r\n",
  6992. suggest_connection_header(conn));
  6993. } else if (rc == -1) {
  6994. if (errno == EEXIST) {
  6995. send_http_error(
  6996. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6997. } else if (errno == EACCES) {
  6998. send_http_error(
  6999. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7000. } else if (errno == ENOENT) {
  7001. send_http_error(
  7002. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7003. } else {
  7004. send_http_error(conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  7005. }
  7006. }
  7007. }
  7008. static void
  7009. put_file(struct mg_connection *conn, const char *path)
  7010. {
  7011. struct file file = STRUCT_FILE_INITIALIZER;
  7012. const char *range;
  7013. int64_t r1, r2;
  7014. int rc;
  7015. char date[64];
  7016. time_t curtime = time(NULL);
  7017. if (conn == NULL) {
  7018. return;
  7019. }
  7020. if (mg_stat(conn, path, &file)) {
  7021. /* File already exists */
  7022. conn->status_code = 200;
  7023. if (file.is_directory) {
  7024. /* This is an already existing directory,
  7025. * so there is nothing to do for the server. */
  7026. rc = 0;
  7027. } else {
  7028. /* File exists and is not a directory. */
  7029. /* Can it be replaced? */
  7030. if (file.membuf != NULL) {
  7031. /* This is an "in-memory" file, that can not be replaced */
  7032. send_http_error(
  7033. conn,
  7034. 405,
  7035. "Error: Put not possible\nReplacing %s is not supported",
  7036. path);
  7037. return;
  7038. }
  7039. /* Check if the server may write this file */
  7040. if (access(path, W_OK) == 0) {
  7041. /* Access granted */
  7042. conn->status_code = 200;
  7043. rc = 1;
  7044. } else {
  7045. send_http_error(
  7046. conn,
  7047. 403,
  7048. "Error: Put not possible\nReplacing %s is not allowed",
  7049. path);
  7050. return;
  7051. }
  7052. }
  7053. } else {
  7054. /* File should be created */
  7055. conn->status_code = 201;
  7056. rc = put_dir(conn, path);
  7057. }
  7058. if (rc == 0) {
  7059. /* put_dir returns 0 if path is a directory */
  7060. gmt_time_string(date, sizeof(date), &curtime);
  7061. mg_printf(conn,
  7062. "HTTP/1.1 %d %s\r\n",
  7063. conn->status_code,
  7064. mg_get_response_code_text(NULL, conn->status_code));
  7065. send_no_cache_header(conn);
  7066. mg_printf(conn,
  7067. "Date: %s\r\n"
  7068. "Content-Length: 0\r\n"
  7069. "Connection: %s\r\n\r\n",
  7070. date,
  7071. suggest_connection_header(conn));
  7072. /* Request to create a directory has been fulfilled successfully.
  7073. * No need to put a file. */
  7074. return;
  7075. }
  7076. if (rc == -1) {
  7077. /* put_dir returns -1 if the path is too long */
  7078. send_http_error(conn,
  7079. 414,
  7080. "Error: Path too long\nput_dir(%s): %s",
  7081. path,
  7082. strerror(ERRNO));
  7083. return;
  7084. }
  7085. if (rc == -2) {
  7086. /* put_dir returns -2 if the directory can not be created */
  7087. send_http_error(conn,
  7088. 500,
  7089. "Error: Can not create directory\nput_dir(%s): %s",
  7090. path,
  7091. strerror(ERRNO));
  7092. return;
  7093. }
  7094. /* A file should be created or overwritten. */
  7095. if (!mg_fopen(conn, path, "wb+", &file) || file.fp == NULL) {
  7096. mg_fclose(&file);
  7097. send_http_error(conn,
  7098. 500,
  7099. "Error: Can not create file\nfopen(%s): %s",
  7100. path,
  7101. strerror(ERRNO));
  7102. return;
  7103. }
  7104. fclose_on_exec(&file, conn);
  7105. range = mg_get_header(conn, "Content-Range");
  7106. r1 = r2 = 0;
  7107. if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
  7108. conn->status_code = 206; /* Partial content */
  7109. fseeko(file.fp, r1, SEEK_SET);
  7110. }
  7111. if (!forward_body_data(conn, file.fp, INVALID_SOCKET, NULL)) {
  7112. /* forward_body_data failed.
  7113. * The error code has already been sent to the client,
  7114. * and conn->status_code is already set. */
  7115. mg_fclose(&file);
  7116. return;
  7117. }
  7118. gmt_time_string(date, sizeof(date), &curtime);
  7119. mg_printf(conn,
  7120. "HTTP/1.1 %d %s\r\n",
  7121. conn->status_code,
  7122. mg_get_response_code_text(NULL, conn->status_code));
  7123. send_no_cache_header(conn);
  7124. mg_printf(conn,
  7125. "Date: %s\r\n"
  7126. "Content-Length: 0\r\n"
  7127. "Connection: %s\r\n\r\n",
  7128. date,
  7129. suggest_connection_header(conn));
  7130. mg_fclose(&file);
  7131. }
  7132. static void
  7133. delete_file(struct mg_connection *conn, const char *path)
  7134. {
  7135. struct de de;
  7136. memset(&de.file, 0, sizeof(de.file));
  7137. if (!mg_stat(conn, path, &de.file)) {
  7138. /* mg_stat returns 0 if the file does not exist */
  7139. send_http_error(conn,
  7140. 404,
  7141. "Error: Cannot delete file\nFile %s not found",
  7142. path);
  7143. return;
  7144. }
  7145. if (de.file.membuf != NULL) {
  7146. /* the file is cached in memory */
  7147. send_http_error(
  7148. conn,
  7149. 405,
  7150. "Error: Delete not possible\nDeleting %s is not supported",
  7151. path);
  7152. return;
  7153. }
  7154. if (de.file.is_directory) {
  7155. if (remove_directory(conn, path)) {
  7156. /* Delete is successful: Return 204 without content. */
  7157. send_http_error(conn, 204, "%s", "");
  7158. } else {
  7159. /* Delete is not successful: Return 500 (Server error). */
  7160. send_http_error(conn, 500, "Error: Could not delete %s", path);
  7161. }
  7162. return;
  7163. }
  7164. /* This is an existing file (not a directory).
  7165. * Check if write permission is granted. */
  7166. if (access(path, W_OK) != 0) {
  7167. /* File is read only */
  7168. send_http_error(
  7169. conn,
  7170. 403,
  7171. "Error: Delete not possible\nDeleting %s is not allowed",
  7172. path);
  7173. return;
  7174. }
  7175. /* Try to delete it. */
  7176. if (mg_remove(conn, path) == 0) {
  7177. /* Delete was successful: Return 204 without content. */
  7178. send_http_error(conn, 204, "%s", "");
  7179. } else {
  7180. /* Delete not successful (file locked). */
  7181. send_http_error(conn,
  7182. 423,
  7183. "Error: Cannot delete file\nremove(%s): %s",
  7184. path,
  7185. strerror(ERRNO));
  7186. }
  7187. }
  7188. #endif /* !NO_FILES */
  7189. static void
  7190. send_ssi_file(struct mg_connection *, const char *, struct file *, int);
  7191. static void
  7192. do_ssi_include(struct mg_connection *conn,
  7193. const char *ssi,
  7194. char *tag,
  7195. int include_level)
  7196. {
  7197. char file_name[MG_BUF_LEN], path[512], *p;
  7198. struct file file = STRUCT_FILE_INITIALIZER;
  7199. size_t len;
  7200. int truncated = 0;
  7201. if (conn == NULL) {
  7202. return;
  7203. }
  7204. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  7205. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  7206. * always < MG_BUF_LEN. */
  7207. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  7208. /* File name is relative to the webserver root */
  7209. file_name[511] = 0;
  7210. (void)mg_snprintf(conn,
  7211. &truncated,
  7212. path,
  7213. sizeof(path),
  7214. "%s/%s",
  7215. conn->ctx->config[DOCUMENT_ROOT],
  7216. file_name);
  7217. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  7218. /* File name is relative to the webserver working directory
  7219. * or it is absolute system path */
  7220. file_name[511] = 0;
  7221. (void)
  7222. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  7223. } else if (sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1
  7224. || sscanf(tag, " \"%511[^\"]\"", file_name) == 1) {
  7225. /* File name is relative to the currect document */
  7226. file_name[511] = 0;
  7227. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  7228. if (!truncated) {
  7229. if ((p = strrchr(path, '/')) != NULL) {
  7230. p[1] = '\0';
  7231. }
  7232. len = strlen(path);
  7233. (void)mg_snprintf(conn,
  7234. &truncated,
  7235. path + len,
  7236. sizeof(path) - len,
  7237. "%s",
  7238. file_name);
  7239. }
  7240. } else {
  7241. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  7242. return;
  7243. }
  7244. if (truncated) {
  7245. mg_cry(conn, "SSI #include path length overflow: [%s]", tag);
  7246. return;
  7247. }
  7248. if (!mg_fopen(conn, path, "rb", &file)) {
  7249. mg_cry(conn,
  7250. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  7251. tag,
  7252. path,
  7253. strerror(ERRNO));
  7254. } else {
  7255. fclose_on_exec(&file, conn);
  7256. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  7257. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  7258. path) > 0) {
  7259. send_ssi_file(conn, path, &file, include_level + 1);
  7260. } else {
  7261. send_file_data(conn, &file, 0, INT64_MAX);
  7262. }
  7263. mg_fclose(&file);
  7264. }
  7265. }
  7266. #if !defined(NO_POPEN)
  7267. static void
  7268. do_ssi_exec(struct mg_connection *conn, char *tag)
  7269. {
  7270. char cmd[1024] = "";
  7271. struct file file = STRUCT_FILE_INITIALIZER;
  7272. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  7273. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  7274. } else {
  7275. cmd[1023] = 0;
  7276. if ((file.fp = popen(cmd, "r")) == NULL) {
  7277. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  7278. } else {
  7279. send_file_data(conn, &file, 0, INT64_MAX);
  7280. pclose(file.fp);
  7281. }
  7282. }
  7283. }
  7284. #endif /* !NO_POPEN */
  7285. static int
  7286. mg_fgetc(struct file *filep, int offset)
  7287. {
  7288. if (filep == NULL) {
  7289. return EOF;
  7290. }
  7291. if (filep->membuf != NULL && offset >= 0
  7292. && ((unsigned int)(offset)) < filep->size) {
  7293. return ((const unsigned char *)filep->membuf)[offset];
  7294. } else if (filep->fp != NULL) {
  7295. return fgetc(filep->fp);
  7296. } else {
  7297. return EOF;
  7298. }
  7299. }
  7300. static void
  7301. send_ssi_file(struct mg_connection *conn,
  7302. const char *path,
  7303. struct file *filep,
  7304. int include_level)
  7305. {
  7306. char buf[MG_BUF_LEN];
  7307. int ch, offset, len, in_ssi_tag;
  7308. if (include_level > 10) {
  7309. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  7310. return;
  7311. }
  7312. in_ssi_tag = len = offset = 0;
  7313. while ((ch = mg_fgetc(filep, offset)) != EOF) {
  7314. if (in_ssi_tag && ch == '>') {
  7315. in_ssi_tag = 0;
  7316. buf[len++] = (char)ch;
  7317. buf[len] = '\0';
  7318. /* assert(len <= (int) sizeof(buf)); */
  7319. if (len > (int)sizeof(buf)) {
  7320. break;
  7321. }
  7322. if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
  7323. /* Not an SSI tag, pass it */
  7324. (void)mg_write(conn, buf, (size_t)len);
  7325. } else {
  7326. if (!memcmp(buf + 5, "include", 7)) {
  7327. do_ssi_include(conn, path, buf + 12, include_level);
  7328. #if !defined(NO_POPEN)
  7329. } else if (!memcmp(buf + 5, "exec", 4)) {
  7330. do_ssi_exec(conn, buf + 9);
  7331. #endif /* !NO_POPEN */
  7332. } else {
  7333. mg_cry(conn,
  7334. "%s: unknown SSI "
  7335. "command: \"%s\"",
  7336. path,
  7337. buf);
  7338. }
  7339. }
  7340. len = 0;
  7341. } else if (in_ssi_tag) {
  7342. if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
  7343. /* Not an SSI tag */
  7344. in_ssi_tag = 0;
  7345. } else if (len == (int)sizeof(buf) - 2) {
  7346. mg_cry(conn, "%s: SSI tag is too large", path);
  7347. len = 0;
  7348. }
  7349. buf[len++] = (char)(ch & 0xff);
  7350. } else if (ch == '<') {
  7351. in_ssi_tag = 1;
  7352. if (len > 0) {
  7353. mg_write(conn, buf, (size_t)len);
  7354. }
  7355. len = 0;
  7356. buf[len++] = (char)(ch & 0xff);
  7357. } else {
  7358. buf[len++] = (char)(ch & 0xff);
  7359. if (len == (int)sizeof(buf)) {
  7360. mg_write(conn, buf, (size_t)len);
  7361. len = 0;
  7362. }
  7363. }
  7364. }
  7365. /* Send the rest of buffered data */
  7366. if (len > 0) {
  7367. mg_write(conn, buf, (size_t)len);
  7368. }
  7369. }
  7370. static void
  7371. handle_ssi_file_request(struct mg_connection *conn,
  7372. const char *path,
  7373. struct file *filep)
  7374. {
  7375. char date[64];
  7376. time_t curtime = time(NULL);
  7377. const char *cors1, *cors2, *cors3;
  7378. if (conn == NULL || path == NULL || filep == NULL) {
  7379. return;
  7380. }
  7381. if (mg_get_header(conn, "Origin")) {
  7382. /* Cross-origin resource sharing (CORS). */
  7383. cors1 = "Access-Control-Allow-Origin: ";
  7384. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  7385. cors3 = "\r\n";
  7386. } else {
  7387. cors1 = cors2 = cors3 = "";
  7388. }
  7389. if (!mg_fopen(conn, path, "rb", filep)) {
  7390. /* File exists (precondition for calling this function),
  7391. * but can not be opened by the server. */
  7392. send_http_error(conn,
  7393. 500,
  7394. "Error: Cannot read file\nfopen(%s): %s",
  7395. path,
  7396. strerror(ERRNO));
  7397. } else {
  7398. conn->must_close = 1;
  7399. gmt_time_string(date, sizeof(date), &curtime);
  7400. fclose_on_exec(filep, conn);
  7401. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  7402. send_no_cache_header(conn);
  7403. mg_printf(conn,
  7404. "%s%s%s"
  7405. "Date: %s\r\n"
  7406. "Content-Type: text/html\r\n"
  7407. "Connection: %s\r\n\r\n",
  7408. cors1,
  7409. cors2,
  7410. cors3,
  7411. date,
  7412. suggest_connection_header(conn));
  7413. send_ssi_file(conn, path, filep, 0);
  7414. mg_fclose(filep);
  7415. }
  7416. }
  7417. #if !defined(NO_FILES)
  7418. static void
  7419. send_options(struct mg_connection *conn)
  7420. {
  7421. char date[64];
  7422. time_t curtime = time(NULL);
  7423. if (!conn) {
  7424. return;
  7425. }
  7426. conn->status_code = 200;
  7427. conn->must_close = 1;
  7428. gmt_time_string(date, sizeof(date), &curtime);
  7429. mg_printf(conn,
  7430. "HTTP/1.1 200 OK\r\n"
  7431. "Date: %s\r\n"
  7432. /* TODO: "Cache-Control" (?) */
  7433. "Connection: %s\r\n"
  7434. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  7435. "PROPFIND, MKCOL\r\n"
  7436. "DAV: 1\r\n\r\n",
  7437. date,
  7438. suggest_connection_header(conn));
  7439. }
  7440. /* Writes PROPFIND properties for a collection element */
  7441. static void
  7442. print_props(struct mg_connection *conn, const char *uri, struct file *filep)
  7443. {
  7444. char mtime[64];
  7445. if (conn == NULL || uri == NULL || filep == NULL) {
  7446. return;
  7447. }
  7448. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  7449. conn->num_bytes_sent +=
  7450. mg_printf(conn,
  7451. "<d:response>"
  7452. "<d:href>%s</d:href>"
  7453. "<d:propstat>"
  7454. "<d:prop>"
  7455. "<d:resourcetype>%s</d:resourcetype>"
  7456. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  7457. "<d:getlastmodified>%s</d:getlastmodified>"
  7458. "</d:prop>"
  7459. "<d:status>HTTP/1.1 200 OK</d:status>"
  7460. "</d:propstat>"
  7461. "</d:response>\n",
  7462. uri,
  7463. filep->is_directory ? "<d:collection/>" : "",
  7464. filep->size,
  7465. mtime);
  7466. }
  7467. static void
  7468. print_dav_dir_entry(struct de *de, void *data)
  7469. {
  7470. char href[PATH_MAX];
  7471. char href_encoded[PATH_MAX * 3 /* worst case */];
  7472. int truncated;
  7473. struct mg_connection *conn = (struct mg_connection *)data;
  7474. if (!de || !conn) {
  7475. return;
  7476. }
  7477. mg_snprintf(conn,
  7478. &truncated,
  7479. href,
  7480. sizeof(href),
  7481. "%s%s",
  7482. conn->request_info.local_uri,
  7483. de->file_name);
  7484. if (!truncated) {
  7485. mg_url_encode(href, href_encoded, PATH_MAX * 3);
  7486. print_props(conn, href_encoded, &de->file);
  7487. }
  7488. }
  7489. static void
  7490. handle_propfind(struct mg_connection *conn,
  7491. const char *path,
  7492. struct file *filep)
  7493. {
  7494. const char *depth = mg_get_header(conn, "Depth");
  7495. char date[64];
  7496. time_t curtime = time(NULL);
  7497. gmt_time_string(date, sizeof(date), &curtime);
  7498. if (!conn || !path || !filep || !conn->ctx) {
  7499. return;
  7500. }
  7501. conn->must_close = 1;
  7502. conn->status_code = 207;
  7503. mg_printf(conn,
  7504. "HTTP/1.1 207 Multi-Status\r\n"
  7505. "Date: %s\r\n",
  7506. date);
  7507. send_static_cache_header(conn);
  7508. mg_printf(conn,
  7509. "Connection: %s\r\n"
  7510. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  7511. suggest_connection_header(conn));
  7512. conn->num_bytes_sent +=
  7513. mg_printf(conn,
  7514. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  7515. "<d:multistatus xmlns:d='DAV:'>\n");
  7516. /* Print properties for the requested resource itself */
  7517. print_props(conn, conn->request_info.local_uri, filep);
  7518. /* If it is a directory, print directory entries too if Depth is not 0 */
  7519. if (filep && filep->is_directory
  7520. && !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")
  7521. && (depth == NULL || strcmp(depth, "0") != 0)) {
  7522. scan_directory(conn, path, conn, &print_dav_dir_entry);
  7523. }
  7524. conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");
  7525. }
  7526. #endif
  7527. void
  7528. mg_lock_connection(struct mg_connection *conn)
  7529. {
  7530. if (conn) {
  7531. (void)pthread_mutex_lock(&conn->mutex);
  7532. }
  7533. }
  7534. void
  7535. mg_unlock_connection(struct mg_connection *conn)
  7536. {
  7537. if (conn) {
  7538. (void)pthread_mutex_unlock(&conn->mutex);
  7539. }
  7540. }
  7541. void
  7542. mg_lock_context(struct mg_context *ctx)
  7543. {
  7544. if (ctx) {
  7545. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  7546. }
  7547. }
  7548. void
  7549. mg_unlock_context(struct mg_context *ctx)
  7550. {
  7551. if (ctx) {
  7552. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  7553. }
  7554. }
  7555. #if defined(USE_TIMERS)
  7556. #include "timer.inl"
  7557. #endif /* USE_TIMERS */
  7558. #ifdef USE_LUA
  7559. #include "mod_lua.inl"
  7560. #endif /* USE_LUA */
  7561. #ifdef USE_DUKTAPE
  7562. #include "mod_duktape.inl"
  7563. #endif /* USE_DUKTAPE */
  7564. #if defined(USE_WEBSOCKET)
  7565. /* START OF SHA-1 code
  7566. * Copyright(c) By Steve Reid <steve@edmweb.com> */
  7567. #define SHA1HANDSOFF
  7568. /* According to current tests (May 2015), the <solarisfixes.h> is not required.
  7569. *
  7570. * #if defined(__sun)
  7571. * #include "solarisfixes.h"
  7572. * #endif
  7573. */
  7574. static int
  7575. is_big_endian(void)
  7576. {
  7577. static const int n = 1;
  7578. return ((char *)&n)[0] == 0;
  7579. }
  7580. union char64long16 {
  7581. unsigned char c[64];
  7582. uint32_t l[16];
  7583. };
  7584. #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
  7585. static uint32_t
  7586. blk0(union char64long16 *block, int i)
  7587. {
  7588. /* Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN */
  7589. if (!is_big_endian()) {
  7590. block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00)
  7591. | (rol(block->l[i], 8) & 0x00FF00FF);
  7592. }
  7593. return block->l[i];
  7594. }
  7595. #define blk(i) \
  7596. (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] \
  7597. ^ block->l[(i + 2) & 15] ^ block->l[i & 15], \
  7598. 1))
  7599. #define R0(v, w, x, y, z, i) \
  7600. z += ((w & (x ^ y)) ^ y) + blk0(block, i) + 0x5A827999 + rol(v, 5); \
  7601. w = rol(w, 30);
  7602. #define R1(v, w, x, y, z, i) \
  7603. z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \
  7604. w = rol(w, 30);
  7605. #define R2(v, w, x, y, z, i) \
  7606. z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \
  7607. w = rol(w, 30);
  7608. #define R3(v, w, x, y, z, i) \
  7609. z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \
  7610. w = rol(w, 30);
  7611. #define R4(v, w, x, y, z, i) \
  7612. z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \
  7613. w = rol(w, 30);
  7614. typedef struct {
  7615. uint32_t state[5];
  7616. uint32_t count[2];
  7617. unsigned char buffer[64];
  7618. } SHA1_CTX;
  7619. static void
  7620. SHA1Transform(uint32_t state[5], const unsigned char buffer[64])
  7621. {
  7622. uint32_t a, b, c, d, e;
  7623. union char64long16 block[1];
  7624. memcpy(block, buffer, 64);
  7625. a = state[0];
  7626. b = state[1];
  7627. c = state[2];
  7628. d = state[3];
  7629. e = state[4];
  7630. R0(a, b, c, d, e, 0);
  7631. R0(e, a, b, c, d, 1);
  7632. R0(d, e, a, b, c, 2);
  7633. R0(c, d, e, a, b, 3);
  7634. R0(b, c, d, e, a, 4);
  7635. R0(a, b, c, d, e, 5);
  7636. R0(e, a, b, c, d, 6);
  7637. R0(d, e, a, b, c, 7);
  7638. R0(c, d, e, a, b, 8);
  7639. R0(b, c, d, e, a, 9);
  7640. R0(a, b, c, d, e, 10);
  7641. R0(e, a, b, c, d, 11);
  7642. R0(d, e, a, b, c, 12);
  7643. R0(c, d, e, a, b, 13);
  7644. R0(b, c, d, e, a, 14);
  7645. R0(a, b, c, d, e, 15);
  7646. R1(e, a, b, c, d, 16);
  7647. R1(d, e, a, b, c, 17);
  7648. R1(c, d, e, a, b, 18);
  7649. R1(b, c, d, e, a, 19);
  7650. R2(a, b, c, d, e, 20);
  7651. R2(e, a, b, c, d, 21);
  7652. R2(d, e, a, b, c, 22);
  7653. R2(c, d, e, a, b, 23);
  7654. R2(b, c, d, e, a, 24);
  7655. R2(a, b, c, d, e, 25);
  7656. R2(e, a, b, c, d, 26);
  7657. R2(d, e, a, b, c, 27);
  7658. R2(c, d, e, a, b, 28);
  7659. R2(b, c, d, e, a, 29);
  7660. R2(a, b, c, d, e, 30);
  7661. R2(e, a, b, c, d, 31);
  7662. R2(d, e, a, b, c, 32);
  7663. R2(c, d, e, a, b, 33);
  7664. R2(b, c, d, e, a, 34);
  7665. R2(a, b, c, d, e, 35);
  7666. R2(e, a, b, c, d, 36);
  7667. R2(d, e, a, b, c, 37);
  7668. R2(c, d, e, a, b, 38);
  7669. R2(b, c, d, e, a, 39);
  7670. R3(a, b, c, d, e, 40);
  7671. R3(e, a, b, c, d, 41);
  7672. R3(d, e, a, b, c, 42);
  7673. R3(c, d, e, a, b, 43);
  7674. R3(b, c, d, e, a, 44);
  7675. R3(a, b, c, d, e, 45);
  7676. R3(e, a, b, c, d, 46);
  7677. R3(d, e, a, b, c, 47);
  7678. R3(c, d, e, a, b, 48);
  7679. R3(b, c, d, e, a, 49);
  7680. R3(a, b, c, d, e, 50);
  7681. R3(e, a, b, c, d, 51);
  7682. R3(d, e, a, b, c, 52);
  7683. R3(c, d, e, a, b, 53);
  7684. R3(b, c, d, e, a, 54);
  7685. R3(a, b, c, d, e, 55);
  7686. R3(e, a, b, c, d, 56);
  7687. R3(d, e, a, b, c, 57);
  7688. R3(c, d, e, a, b, 58);
  7689. R3(b, c, d, e, a, 59);
  7690. R4(a, b, c, d, e, 60);
  7691. R4(e, a, b, c, d, 61);
  7692. R4(d, e, a, b, c, 62);
  7693. R4(c, d, e, a, b, 63);
  7694. R4(b, c, d, e, a, 64);
  7695. R4(a, b, c, d, e, 65);
  7696. R4(e, a, b, c, d, 66);
  7697. R4(d, e, a, b, c, 67);
  7698. R4(c, d, e, a, b, 68);
  7699. R4(b, c, d, e, a, 69);
  7700. R4(a, b, c, d, e, 70);
  7701. R4(e, a, b, c, d, 71);
  7702. R4(d, e, a, b, c, 72);
  7703. R4(c, d, e, a, b, 73);
  7704. R4(b, c, d, e, a, 74);
  7705. R4(a, b, c, d, e, 75);
  7706. R4(e, a, b, c, d, 76);
  7707. R4(d, e, a, b, c, 77);
  7708. R4(c, d, e, a, b, 78);
  7709. R4(b, c, d, e, a, 79);
  7710. state[0] += a;
  7711. state[1] += b;
  7712. state[2] += c;
  7713. state[3] += d;
  7714. state[4] += e;
  7715. a = b = c = d = e = 0;
  7716. memset(block, '\0', sizeof(block));
  7717. }
  7718. static void
  7719. SHA1Init(SHA1_CTX *context)
  7720. {
  7721. context->state[0] = 0x67452301;
  7722. context->state[1] = 0xEFCDAB89;
  7723. context->state[2] = 0x98BADCFE;
  7724. context->state[3] = 0x10325476;
  7725. context->state[4] = 0xC3D2E1F0;
  7726. context->count[0] = context->count[1] = 0;
  7727. }
  7728. static void
  7729. SHA1Update(SHA1_CTX *context, const unsigned char *data, uint32_t len)
  7730. {
  7731. uint32_t i, j;
  7732. j = context->count[0];
  7733. if ((context->count[0] += len << 3) < j) {
  7734. context->count[1]++;
  7735. }
  7736. context->count[1] += (len >> 29);
  7737. j = (j >> 3) & 63;
  7738. if ((j + len) > 63) {
  7739. memcpy(&context->buffer[j], data, (i = 64 - j));
  7740. SHA1Transform(context->state, context->buffer);
  7741. for (; i + 63 < len; i += 64) {
  7742. SHA1Transform(context->state, &data[i]);
  7743. }
  7744. j = 0;
  7745. } else
  7746. i = 0;
  7747. memcpy(&context->buffer[j], &data[i], len - i);
  7748. }
  7749. static void
  7750. SHA1Final(unsigned char digest[20], SHA1_CTX *context)
  7751. {
  7752. unsigned i;
  7753. unsigned char finalcount[8], c;
  7754. for (i = 0; i < 8; i++) {
  7755. finalcount[i] = (unsigned char)((context->count[(i >= 4) ? 0 : 1]
  7756. >> ((3 - (i & 3)) * 8)) & 255);
  7757. }
  7758. c = 0200;
  7759. SHA1Update(context, &c, 1);
  7760. while ((context->count[0] & 504) != 448) {
  7761. c = 0000;
  7762. SHA1Update(context, &c, 1);
  7763. }
  7764. SHA1Update(context, finalcount, 8);
  7765. for (i = 0; i < 20; i++) {
  7766. digest[i] = (unsigned char)((context->state[i >> 2]
  7767. >> ((3 - (i & 3)) * 8)) & 255);
  7768. }
  7769. memset(context, '\0', sizeof(*context));
  7770. memset(&finalcount, '\0', sizeof(finalcount));
  7771. }
  7772. /* END OF SHA1 CODE */
  7773. static int
  7774. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  7775. {
  7776. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  7777. const char *protocol = NULL;
  7778. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  7779. SHA1_CTX sha_ctx;
  7780. int truncated;
  7781. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  7782. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  7783. if (truncated) {
  7784. conn->must_close = 1;
  7785. return 0;
  7786. }
  7787. SHA1Init(&sha_ctx);
  7788. SHA1Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  7789. SHA1Final((unsigned char *)sha, &sha_ctx);
  7790. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  7791. mg_printf(conn,
  7792. "HTTP/1.1 101 Switching Protocols\r\n"
  7793. "Upgrade: websocket\r\n"
  7794. "Connection: Upgrade\r\n"
  7795. "Sec-WebSocket-Accept: %s\r\n",
  7796. b64_sha);
  7797. protocol = mg_get_header(conn, "Sec-WebSocket-Protocol");
  7798. if (protocol) {
  7799. /* The protocol is a comma seperated list of names. */
  7800. /* The server must only return one value from this list. */
  7801. /* First check if it is a list or just a single value. */
  7802. const char *sep = strchr(protocol, ',');
  7803. if (sep == NULL) {
  7804. /* Just a single protocol -> accept it. */
  7805. mg_printf(conn, "Sec-WebSocket-Protocol: %s\r\n\r\n", protocol);
  7806. } else {
  7807. /* Multiple protocols -> accept the first one. */
  7808. /* This is just a quick fix if the client offers multiple
  7809. * protocols. In order to get the behavior intended by
  7810. * RFC 6455 (https://tools.ietf.org/rfc/rfc6455.txt), it is
  7811. * required to have a list of websocket subprotocols accepted
  7812. * by the server. Then the server must either select a subprotocol
  7813. * supported by client and server, or the server has to abort the
  7814. * handshake by not returning a Sec-Websocket-Protocol header if
  7815. * no subprotocol is acceptable.
  7816. */
  7817. mg_printf(conn,
  7818. "Sec-WebSocket-Protocol: %.*s\r\n\r\n",
  7819. (int)(sep - protocol),
  7820. protocol);
  7821. }
  7822. /* TODO: Real subprotocol negotiation instead of just taking the first
  7823. * websocket subprotocol suggested by the client. */
  7824. } else {
  7825. mg_printf(conn, "%s", "\r\n");
  7826. }
  7827. return 1;
  7828. }
  7829. static void
  7830. read_websocket(struct mg_connection *conn,
  7831. mg_websocket_data_handler ws_data_handler,
  7832. void *callback_data)
  7833. {
  7834. /* Pointer to the beginning of the portion of the incoming websocket
  7835. * message queue.
  7836. * The original websocket upgrade request is never removed, so the queue
  7837. * begins after it. */
  7838. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  7839. int n, error, exit_by_callback;
  7840. /* body_len is the length of the entire queue in bytes
  7841. * len is the length of the current message
  7842. * data_len is the length of the current message's data payload
  7843. * header_len is the length of the current message's header */
  7844. size_t i, len, mask_len = 0, data_len = 0, header_len, body_len;
  7845. /* "The masking key is a 32-bit value chosen at random by the client."
  7846. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  7847. */
  7848. unsigned char mask[4];
  7849. /* data points to the place where the message is stored when passed to
  7850. * the
  7851. * websocket_data callback. This is either mem on the stack, or a
  7852. * dynamically allocated buffer if it is too large. */
  7853. char mem[4096];
  7854. char *data = mem;
  7855. unsigned char mop; /* mask flag and opcode */
  7856. double timeout = -1.0;
  7857. if (conn->ctx->config[WEBSOCKET_TIMEOUT]) {
  7858. timeout = atoi(conn->ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  7859. }
  7860. if ((timeout <= 0.0) && (conn->ctx->config[REQUEST_TIMEOUT])) {
  7861. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  7862. }
  7863. mg_set_thread_name("wsock");
  7864. /* Loop continuously, reading messages from the socket, invoking the
  7865. * callback, and waiting repeatedly until an error occurs. */
  7866. while (!conn->ctx->stop_flag) {
  7867. header_len = 0;
  7868. assert(conn->data_len >= conn->request_len);
  7869. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  7870. len = buf[1] & 127;
  7871. mask_len = (buf[1] & 128) ? 4 : 0;
  7872. if ((len < 126) && (body_len >= mask_len)) {
  7873. data_len = len;
  7874. header_len = 2 + mask_len;
  7875. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  7876. header_len = 4 + mask_len;
  7877. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  7878. } else if (body_len >= (10 + mask_len)) {
  7879. header_len = 10 + mask_len;
  7880. data_len = (((uint64_t)ntohl(*(uint32_t *)(void *)&buf[2]))
  7881. << 32) + ntohl(*(uint32_t *)(void *)&buf[6]);
  7882. }
  7883. }
  7884. if (header_len > 0 && body_len >= header_len) {
  7885. /* Allocate space to hold websocket payload */
  7886. data = mem;
  7887. if (data_len > sizeof(mem)) {
  7888. data = (char *)mg_malloc(data_len);
  7889. if (data == NULL) {
  7890. /* Allocation failed, exit the loop and then close the
  7891. * connection */
  7892. mg_cry(conn, "websocket out of memory; closing connection");
  7893. break;
  7894. }
  7895. }
  7896. /* Copy the mask before we shift the queue and destroy it */
  7897. if (mask_len > 0) {
  7898. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  7899. } else {
  7900. memset(mask, 0, sizeof(mask));
  7901. }
  7902. /* Read frame payload from the first message in the queue into
  7903. * data and advance the queue by moving the memory in place. */
  7904. assert(body_len >= header_len);
  7905. if (data_len + header_len > body_len) {
  7906. mop = buf[0]; /* current mask and opcode */
  7907. /* Overflow case */
  7908. len = body_len - header_len;
  7909. memcpy(data, buf + header_len, len);
  7910. error = 0;
  7911. while (len < data_len) {
  7912. n = pull(
  7913. NULL, conn, data + len, (int)(data_len - len), timeout);
  7914. if (n <= 0) {
  7915. error = 1;
  7916. break;
  7917. }
  7918. len += (size_t)n;
  7919. }
  7920. if (error) {
  7921. mg_cry(conn, "Websocket pull failed; closing connection");
  7922. break;
  7923. }
  7924. conn->data_len = conn->request_len;
  7925. } else {
  7926. mop = buf[0]; /* current mask and opcode, overwritten by
  7927. * memmove() */
  7928. /* Length of the message being read at the front of the
  7929. * queue */
  7930. len = data_len + header_len;
  7931. /* Copy the data payload into the data pointer for the
  7932. * callback */
  7933. memcpy(data, buf + header_len, data_len);
  7934. /* Move the queue forward len bytes */
  7935. memmove(buf, buf + len, body_len - len);
  7936. /* Mark the queue as advanced */
  7937. conn->data_len -= (int)len;
  7938. }
  7939. /* Apply mask if necessary */
  7940. if (mask_len > 0) {
  7941. for (i = 0; i < data_len; ++i) {
  7942. data[i] ^= mask[i & 3];
  7943. }
  7944. }
  7945. /* Exit the loop if callback signals to exit (server side),
  7946. * or "connection close" opcode received (client side). */
  7947. exit_by_callback = 0;
  7948. if ((ws_data_handler != NULL)
  7949. && !ws_data_handler(conn, mop, data, data_len, callback_data)) {
  7950. exit_by_callback = 1;
  7951. }
  7952. if (data != mem) {
  7953. mg_free(data);
  7954. }
  7955. if (exit_by_callback
  7956. || ((mop & 0xf) == WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  7957. /* Opcode == 8, connection close */
  7958. break;
  7959. }
  7960. /* Not breaking the loop, process next websocket frame. */
  7961. } else {
  7962. /* Read from the socket into the next available location in the
  7963. * message queue. */
  7964. if ((n = pull(NULL,
  7965. conn,
  7966. conn->buf + conn->data_len,
  7967. conn->buf_size - conn->data_len,
  7968. timeout)) <= 0) {
  7969. /* Error, no bytes read */
  7970. break;
  7971. }
  7972. conn->data_len += n;
  7973. }
  7974. }
  7975. mg_set_thread_name("worker");
  7976. }
  7977. static int
  7978. mg_websocket_write_exec(struct mg_connection *conn,
  7979. int opcode,
  7980. const char *data,
  7981. size_t dataLen,
  7982. uint32_t masking_key)
  7983. {
  7984. unsigned char header[14];
  7985. size_t headerLen = 1;
  7986. int retval = -1;
  7987. header[0] = 0x80 + (opcode & 0xF);
  7988. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  7989. if (dataLen < 126) {
  7990. /* inline 7-bit length field */
  7991. header[1] = (unsigned char)dataLen;
  7992. headerLen = 2;
  7993. } else if (dataLen <= 0xFFFF) {
  7994. /* 16-bit length field */
  7995. uint16_t len = htons((uint16_t)dataLen);
  7996. header[1] = 126;
  7997. memcpy(header + 2, &len, 2);
  7998. headerLen = 4;
  7999. } else {
  8000. /* 64-bit length field */
  8001. uint32_t len1 = htonl((uint64_t)dataLen >> 32);
  8002. uint32_t len2 = htonl(dataLen & 0xFFFFFFFF);
  8003. header[1] = 127;
  8004. memcpy(header + 2, &len1, 4);
  8005. memcpy(header + 6, &len2, 4);
  8006. headerLen = 10;
  8007. }
  8008. if (masking_key) {
  8009. /* add mask */
  8010. header[1] |= 0x80;
  8011. memcpy(header + headerLen, &masking_key, 4);
  8012. headerLen += 4;
  8013. }
  8014. /* Note that POSIX/Winsock's send() is threadsafe
  8015. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  8016. * but mongoose's mg_printf/mg_write is not (because of the loop in
  8017. * push(), although that is only a problem if the packet is large or
  8018. * outgoing buffer is full). */
  8019. (void)mg_lock_connection(conn);
  8020. retval = mg_write(conn, header, headerLen);
  8021. if (dataLen > 0) {
  8022. retval = mg_write(conn, data, dataLen);
  8023. }
  8024. mg_unlock_connection(conn);
  8025. return retval;
  8026. }
  8027. int
  8028. mg_websocket_write(struct mg_connection *conn,
  8029. int opcode,
  8030. const char *data,
  8031. size_t dataLen)
  8032. {
  8033. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  8034. }
  8035. static void
  8036. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  8037. {
  8038. size_t i = 0;
  8039. i = 0;
  8040. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  8041. /* Convert in 32 bit words, if data is 4 byte aligned */
  8042. while (i < (in_len - 3)) {
  8043. *(uint32_t *)(void *)(out + i) =
  8044. *(uint32_t *)(void *)(in + i) ^ masking_key;
  8045. i += 4;
  8046. }
  8047. }
  8048. if (i != in_len) {
  8049. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  8050. while (i < in_len) {
  8051. *(uint8_t *)(void *)(out + i) =
  8052. *(uint8_t *)(void *)(in + i)
  8053. ^ *(((uint8_t *)&masking_key) + (i % 4));
  8054. i++;
  8055. }
  8056. }
  8057. }
  8058. int
  8059. mg_websocket_client_write(struct mg_connection *conn,
  8060. int opcode,
  8061. const char *data,
  8062. size_t dataLen)
  8063. {
  8064. int retval = -1;
  8065. char *masked_data = (char *)mg_malloc(((dataLen + 7) / 4) * 4);
  8066. uint32_t masking_key = (uint32_t)get_random();
  8067. if (masked_data == NULL) {
  8068. /* Return -1 in an error case */
  8069. mg_cry(conn,
  8070. "Cannot allocate buffer for masked websocket response: "
  8071. "Out of memory");
  8072. return -1;
  8073. }
  8074. mask_data(data, dataLen, masking_key, masked_data);
  8075. retval = mg_websocket_write_exec(
  8076. conn, opcode, masked_data, dataLen, masking_key);
  8077. mg_free(masked_data);
  8078. return retval;
  8079. }
  8080. static void
  8081. handle_websocket_request(struct mg_connection *conn,
  8082. const char *path,
  8083. int is_callback_resource,
  8084. mg_websocket_connect_handler ws_connect_handler,
  8085. mg_websocket_ready_handler ws_ready_handler,
  8086. mg_websocket_data_handler ws_data_handler,
  8087. mg_websocket_close_handler ws_close_handler,
  8088. void *cbData)
  8089. {
  8090. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  8091. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  8092. int lua_websock = 0;
  8093. #if !defined(USE_LUA)
  8094. (void)path;
  8095. #endif
  8096. /* Step 1: Check websocket protocol version. */
  8097. /* Step 1.1: Check Sec-WebSocket-Key. */
  8098. if (!websock_key) {
  8099. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  8100. * requires a Sec-WebSocket-Key header.
  8101. */
  8102. /* It could be the hixie draft version
  8103. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  8104. */
  8105. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  8106. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  8107. char key3[8];
  8108. if ((key1 != NULL) && (key2 != NULL)) {
  8109. /* This version uses 8 byte body data in a GET request */
  8110. conn->content_len = 8;
  8111. if (8 == mg_read(conn, key3, 8)) {
  8112. /* This is the hixie version */
  8113. send_http_error(conn,
  8114. 426,
  8115. "%s",
  8116. "Protocol upgrade to RFC 6455 required");
  8117. return;
  8118. }
  8119. }
  8120. /* This is an unknown version */
  8121. send_http_error(conn, 400, "%s", "Malformed websocket request");
  8122. return;
  8123. }
  8124. /* Step 1.2: Check websocket protocol version. */
  8125. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  8126. if (version == NULL || strcmp(version, "13") != 0) {
  8127. /* Reject wrong versions */
  8128. send_http_error(conn, 426, "%s", "Protocol upgrade required");
  8129. return;
  8130. }
  8131. /* Step 1.3: Could check for "Host", but we do not really nead this
  8132. * value for anything, so just ignore it. */
  8133. /* Step 2: If a callback is responsible, call it. */
  8134. if (is_callback_resource) {
  8135. if (ws_connect_handler != NULL
  8136. && ws_connect_handler(conn, cbData) != 0) {
  8137. /* C callback has returned non-zero, do not proceed with
  8138. * handshake.
  8139. */
  8140. /* Note that C callbacks are no longer called when Lua is
  8141. * responsible, so C can no longer filter callbacks for Lua. */
  8142. return;
  8143. }
  8144. }
  8145. #if defined(USE_LUA)
  8146. /* Step 3: No callback. Check if Lua is responsible. */
  8147. else {
  8148. /* Step 3.1: Check if Lua is responsible. */
  8149. if (conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  8150. lua_websock =
  8151. match_prefix(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  8152. strlen(
  8153. conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  8154. path);
  8155. }
  8156. if (lua_websock) {
  8157. /* Step 3.2: Lua is responsible: call it. */
  8158. conn->lua_websocket_state = lua_websocket_new(path, conn);
  8159. if (!conn->lua_websocket_state) {
  8160. /* Lua rejected the new client */
  8161. return;
  8162. }
  8163. }
  8164. }
  8165. #endif
  8166. /* Step 4: Check if there is a responsible websocket handler. */
  8167. if (!is_callback_resource && !lua_websock) {
  8168. /* There is no callback, an Lua is not responsible either. */
  8169. /* Reply with a 404 Not Found or with nothing at all?
  8170. * TODO (mid): check the websocket standards, how to reply to
  8171. * requests to invalid websocket addresses. */
  8172. send_http_error(conn, 404, "%s", "Not found");
  8173. return;
  8174. }
  8175. /* Step 5: The websocket connection has been accepted */
  8176. if (!send_websocket_handshake(conn, websock_key)) {
  8177. send_http_error(conn, 500, "%s", "Websocket handshake failed");
  8178. return;
  8179. }
  8180. /* Step 6: Call the ready handler */
  8181. if (is_callback_resource) {
  8182. if (ws_ready_handler != NULL) {
  8183. ws_ready_handler(conn, cbData);
  8184. }
  8185. #if defined(USE_LUA)
  8186. } else if (lua_websock) {
  8187. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  8188. /* the ready handler returned false */
  8189. return;
  8190. }
  8191. #endif
  8192. }
  8193. /* Step 7: Enter the read loop */
  8194. if (is_callback_resource) {
  8195. read_websocket(conn, ws_data_handler, cbData);
  8196. #if defined(USE_LUA)
  8197. } else if (lua_websock) {
  8198. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  8199. #endif
  8200. }
  8201. /* Step 8: Call the close handler */
  8202. if (ws_close_handler) {
  8203. ws_close_handler(conn, cbData);
  8204. }
  8205. }
  8206. static int
  8207. is_websocket_protocol(const struct mg_connection *conn)
  8208. {
  8209. const char *upgrade, *connection;
  8210. /* A websocket protocoll has the following HTTP headers:
  8211. *
  8212. * Connection: Upgrade
  8213. * Upgrade: Websocket
  8214. */
  8215. upgrade = mg_get_header(conn, "Upgrade");
  8216. if (upgrade == NULL) {
  8217. return 0; /* fail early, don't waste time checking other header
  8218. * fields
  8219. */
  8220. }
  8221. if (!mg_strcasestr(upgrade, "websocket")) {
  8222. return 0;
  8223. }
  8224. connection = mg_get_header(conn, "Connection");
  8225. if (connection == NULL) {
  8226. return 0;
  8227. }
  8228. if (!mg_strcasestr(connection, "upgrade")) {
  8229. return 0;
  8230. }
  8231. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  8232. * "Sec-WebSocket-Version" are also required.
  8233. * Don't check them here, since even an unsupported websocket protocol
  8234. * request still IS a websocket request (in contrast to a standard HTTP
  8235. * request). It will fail later in handle_websocket_request.
  8236. */
  8237. return 1;
  8238. }
  8239. #endif /* !USE_WEBSOCKET */
  8240. static int
  8241. isbyte(int n)
  8242. {
  8243. return n >= 0 && n <= 255;
  8244. }
  8245. static int
  8246. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  8247. {
  8248. int n, a, b, c, d, slash = 32, len = 0;
  8249. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5
  8250. || sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) && isbyte(a)
  8251. && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0
  8252. && slash < 33) {
  8253. len = n;
  8254. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  8255. | (uint32_t)d;
  8256. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  8257. }
  8258. return len;
  8259. }
  8260. static int
  8261. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  8262. {
  8263. int throttle = 0;
  8264. struct vec vec, val;
  8265. uint32_t net, mask;
  8266. char mult;
  8267. double v;
  8268. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  8269. mult = ',';
  8270. if (sscanf(val.ptr, "%lf%c", &v, &mult) < 1 || v < 0
  8271. || (lowercase(&mult) != 'k' && lowercase(&mult) != 'm'
  8272. && mult != ',')) {
  8273. continue;
  8274. }
  8275. v *= (lowercase(&mult) == 'k')
  8276. ? 1024
  8277. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  8278. if (vec.len == 1 && vec.ptr[0] == '*') {
  8279. throttle = (int)v;
  8280. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  8281. if ((remote_ip & mask) == net) {
  8282. throttle = (int)v;
  8283. }
  8284. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  8285. throttle = (int)v;
  8286. }
  8287. }
  8288. return throttle;
  8289. }
  8290. static uint32_t
  8291. get_remote_ip(const struct mg_connection *conn)
  8292. {
  8293. if (!conn) {
  8294. return 0;
  8295. }
  8296. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  8297. }
  8298. /* The mg_upload function is superseeded by mg_handle_form_request. */
  8299. #include "handle_form.inl"
  8300. #if defined(MG_LEGACY_INTERFACE)
  8301. /* Implement the deprecated mg_upload function by calling the new
  8302. * mg_handle_form_request function. While mg_upload could only handle
  8303. * HTML forms sent as POST request in multipart/form-data format
  8304. * containing only file input elements, mg_handle_form_request can
  8305. * handle all form input elements and all standard request methods. */
  8306. struct mg_upload_user_data {
  8307. struct mg_connection *conn;
  8308. const char *destination_dir;
  8309. int num_uploaded_files;
  8310. };
  8311. /* Helper function for deprecated mg_upload. */
  8312. static int
  8313. mg_upload_field_found(const char *key,
  8314. const char *filename,
  8315. char *path,
  8316. size_t pathlen,
  8317. void *user_data)
  8318. {
  8319. int truncated = 0;
  8320. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  8321. (void)key;
  8322. if (!filename) {
  8323. mg_cry(fud->conn, "%s: No filename set", __func__);
  8324. return FORM_FIELD_STORAGE_ABORT;
  8325. }
  8326. mg_snprintf(fud->conn,
  8327. &truncated,
  8328. path,
  8329. pathlen - 1,
  8330. "%s/%s",
  8331. fud->destination_dir,
  8332. filename);
  8333. if (!truncated) {
  8334. mg_cry(fud->conn, "%s: File path too long", __func__);
  8335. return FORM_FIELD_STORAGE_ABORT;
  8336. }
  8337. return FORM_FIELD_STORAGE_STORE;
  8338. }
  8339. /* Helper function for deprecated mg_upload. */
  8340. static int
  8341. mg_upload_field_get(const char *key,
  8342. const char *value,
  8343. size_t value_size,
  8344. void *user_data)
  8345. {
  8346. /* Function should never be called */
  8347. (void)key;
  8348. (void)value;
  8349. (void)value_size;
  8350. (void)user_data;
  8351. return 0;
  8352. }
  8353. /* Helper function for deprecated mg_upload. */
  8354. static int
  8355. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  8356. {
  8357. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  8358. (void)file_size;
  8359. fud->num_uploaded_files++;
  8360. fud->conn->ctx->callbacks.upload(fud->conn, path);
  8361. return 0;
  8362. }
  8363. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  8364. int
  8365. mg_upload(struct mg_connection *conn, const char *destination_dir)
  8366. {
  8367. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  8368. struct mg_form_data_handler fdh = {mg_upload_field_found,
  8369. mg_upload_field_get,
  8370. mg_upload_field_stored,
  8371. 0};
  8372. int ret;
  8373. fdh.user_data = (void *)&fud;
  8374. ret = mg_handle_form_request(conn, &fdh);
  8375. if (ret < 0) {
  8376. mg_cry(conn, "%s: Error while parsing the request", __func__);
  8377. }
  8378. return fud.num_uploaded_files;
  8379. }
  8380. #endif
  8381. static int
  8382. get_first_ssl_listener_index(const struct mg_context *ctx)
  8383. {
  8384. unsigned int i;
  8385. int idx = -1;
  8386. if (ctx) {
  8387. for (i = 0; idx == -1 && i < ctx->num_listening_sockets; i++) {
  8388. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  8389. }
  8390. }
  8391. return idx;
  8392. }
  8393. static void
  8394. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  8395. {
  8396. char host[1025];
  8397. const char *host_header;
  8398. size_t hostlen;
  8399. host_header = mg_get_header(conn, "Host");
  8400. hostlen = sizeof(host);
  8401. if (host_header != NULL) {
  8402. char *pos;
  8403. mg_strlcpy(host, host_header, hostlen);
  8404. host[hostlen - 1] = '\0';
  8405. pos = strchr(host, ':');
  8406. if (pos != NULL) {
  8407. *pos = '\0';
  8408. }
  8409. } else {
  8410. /* Cannot get host from the Host: header.
  8411. * Fallback to our IP address. */
  8412. if (conn) {
  8413. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  8414. }
  8415. }
  8416. /* Send host, port, uri and (if it exists) ?query_string */
  8417. if (conn) {
  8418. mg_printf(conn,
  8419. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  8420. host,
  8421. #if defined(USE_IPV6)
  8422. (conn->ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  8423. == AF_INET6)
  8424. ? (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  8425. .lsa.sin6.sin6_port)
  8426. :
  8427. #endif
  8428. (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  8429. .lsa.sin.sin_port),
  8430. conn->request_info.local_uri,
  8431. (conn->request_info.query_string == NULL) ? "" : "?",
  8432. (conn->request_info.query_string == NULL)
  8433. ? ""
  8434. : conn->request_info.query_string);
  8435. }
  8436. }
  8437. static void
  8438. mg_set_handler_type(struct mg_context *ctx,
  8439. const char *uri,
  8440. int handler_type,
  8441. int is_delete_request,
  8442. mg_request_handler handler,
  8443. mg_websocket_connect_handler connect_handler,
  8444. mg_websocket_ready_handler ready_handler,
  8445. mg_websocket_data_handler data_handler,
  8446. mg_websocket_close_handler close_handler,
  8447. mg_authorization_handler auth_handler,
  8448. void *cbdata)
  8449. {
  8450. struct mg_handler_info *tmp_rh, **lastref;
  8451. size_t urilen = strlen(uri);
  8452. if (handler_type == WEBSOCKET_HANDLER) {
  8453. /* assert(handler == NULL); */
  8454. /* assert(is_delete_request || connect_handler!=NULL ||
  8455. * ready_handler!=NULL || data_handler!=NULL ||
  8456. * close_handler!=NULL);
  8457. */
  8458. /* assert(auth_handler == NULL); */
  8459. if (handler != NULL) {
  8460. return;
  8461. }
  8462. if (!is_delete_request && connect_handler == NULL
  8463. && ready_handler == NULL
  8464. && data_handler == NULL
  8465. && close_handler == NULL) {
  8466. return;
  8467. }
  8468. if (auth_handler != NULL) {
  8469. return;
  8470. }
  8471. } else if (handler_type == REQUEST_HANDLER) {
  8472. /* assert(connect_handler==NULL && ready_handler==NULL &&
  8473. * data_handler==NULL && close_handler==NULL); */
  8474. /* assert(is_delete_request || (handler!=NULL));
  8475. */
  8476. /* assert(auth_handler == NULL); */
  8477. if (connect_handler != NULL || ready_handler != NULL
  8478. || data_handler != NULL
  8479. || close_handler != NULL) {
  8480. return;
  8481. }
  8482. if (!is_delete_request && (handler == NULL)) {
  8483. return;
  8484. }
  8485. if (auth_handler != NULL) {
  8486. return;
  8487. }
  8488. } else { /* AUTH_HANDLER */
  8489. /* assert(handler == NULL); */
  8490. /* assert(connect_handler==NULL && ready_handler==NULL &&
  8491. * data_handler==NULL && close_handler==NULL); */
  8492. /* assert(auth_handler != NULL); */
  8493. if (handler != NULL) {
  8494. return;
  8495. }
  8496. if (connect_handler != NULL || ready_handler != NULL
  8497. || data_handler != NULL
  8498. || close_handler != NULL) {
  8499. return;
  8500. }
  8501. if (!is_delete_request && (auth_handler == NULL)) {
  8502. return;
  8503. }
  8504. }
  8505. if (!ctx) {
  8506. return;
  8507. }
  8508. mg_lock_context(ctx);
  8509. /* first try to find an existing handler */
  8510. lastref = &(ctx->handlers);
  8511. for (tmp_rh = ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  8512. if (tmp_rh->handler_type == handler_type) {
  8513. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  8514. if (!is_delete_request) {
  8515. /* update existing handler */
  8516. if (handler_type == REQUEST_HANDLER) {
  8517. tmp_rh->handler = handler;
  8518. } else if (handler_type == WEBSOCKET_HANDLER) {
  8519. tmp_rh->connect_handler = connect_handler;
  8520. tmp_rh->ready_handler = ready_handler;
  8521. tmp_rh->data_handler = data_handler;
  8522. tmp_rh->close_handler = close_handler;
  8523. } else { /* AUTH_HANDLER */
  8524. tmp_rh->auth_handler = auth_handler;
  8525. }
  8526. tmp_rh->cbdata = cbdata;
  8527. } else {
  8528. /* remove existing handler */
  8529. *lastref = tmp_rh->next;
  8530. mg_free(tmp_rh->uri);
  8531. mg_free(tmp_rh);
  8532. }
  8533. mg_unlock_context(ctx);
  8534. return;
  8535. }
  8536. }
  8537. lastref = &(tmp_rh->next);
  8538. }
  8539. if (is_delete_request) {
  8540. /* no handler to set, this was a remove request to a non-existing
  8541. * handler */
  8542. mg_unlock_context(ctx);
  8543. return;
  8544. }
  8545. tmp_rh =
  8546. (struct mg_handler_info *)mg_calloc(sizeof(struct mg_handler_info), 1);
  8547. if (tmp_rh == NULL) {
  8548. mg_unlock_context(ctx);
  8549. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  8550. return;
  8551. }
  8552. tmp_rh->uri = mg_strdup(uri);
  8553. if (!tmp_rh->uri) {
  8554. mg_unlock_context(ctx);
  8555. mg_free(tmp_rh);
  8556. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  8557. return;
  8558. }
  8559. tmp_rh->uri_len = urilen;
  8560. if (handler_type == REQUEST_HANDLER) {
  8561. tmp_rh->handler = handler;
  8562. } else if (handler_type == WEBSOCKET_HANDLER) {
  8563. tmp_rh->connect_handler = connect_handler;
  8564. tmp_rh->ready_handler = ready_handler;
  8565. tmp_rh->data_handler = data_handler;
  8566. tmp_rh->close_handler = close_handler;
  8567. } else { /* AUTH_HANDLER */
  8568. tmp_rh->auth_handler = auth_handler;
  8569. }
  8570. tmp_rh->cbdata = cbdata;
  8571. tmp_rh->handler_type = handler_type;
  8572. tmp_rh->next = NULL;
  8573. *lastref = tmp_rh;
  8574. mg_unlock_context(ctx);
  8575. }
  8576. void
  8577. mg_set_request_handler(struct mg_context *ctx,
  8578. const char *uri,
  8579. mg_request_handler handler,
  8580. void *cbdata)
  8581. {
  8582. mg_set_handler_type(ctx,
  8583. uri,
  8584. REQUEST_HANDLER,
  8585. handler == NULL,
  8586. handler,
  8587. NULL,
  8588. NULL,
  8589. NULL,
  8590. NULL,
  8591. NULL,
  8592. cbdata);
  8593. }
  8594. void
  8595. mg_set_websocket_handler(struct mg_context *ctx,
  8596. const char *uri,
  8597. mg_websocket_connect_handler connect_handler,
  8598. mg_websocket_ready_handler ready_handler,
  8599. mg_websocket_data_handler data_handler,
  8600. mg_websocket_close_handler close_handler,
  8601. void *cbdata)
  8602. {
  8603. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  8604. && (data_handler == NULL)
  8605. && (close_handler == NULL);
  8606. mg_set_handler_type(ctx,
  8607. uri,
  8608. WEBSOCKET_HANDLER,
  8609. is_delete_request,
  8610. NULL,
  8611. connect_handler,
  8612. ready_handler,
  8613. data_handler,
  8614. close_handler,
  8615. NULL,
  8616. cbdata);
  8617. }
  8618. void
  8619. mg_set_auth_handler(struct mg_context *ctx,
  8620. const char *uri,
  8621. mg_request_handler handler,
  8622. void *cbdata)
  8623. {
  8624. mg_set_handler_type(ctx,
  8625. uri,
  8626. AUTH_HANDLER,
  8627. handler == NULL,
  8628. NULL,
  8629. NULL,
  8630. NULL,
  8631. NULL,
  8632. NULL,
  8633. handler,
  8634. cbdata);
  8635. }
  8636. static int
  8637. get_request_handler(struct mg_connection *conn,
  8638. int handler_type,
  8639. mg_request_handler *handler,
  8640. mg_websocket_connect_handler *connect_handler,
  8641. mg_websocket_ready_handler *ready_handler,
  8642. mg_websocket_data_handler *data_handler,
  8643. mg_websocket_close_handler *close_handler,
  8644. mg_authorization_handler *auth_handler,
  8645. void **cbdata)
  8646. {
  8647. const struct mg_request_info *request_info = mg_get_request_info(conn);
  8648. if (request_info) {
  8649. const char *uri = request_info->local_uri;
  8650. size_t urilen = strlen(uri);
  8651. struct mg_handler_info *tmp_rh;
  8652. if (!conn || !conn->ctx) {
  8653. return 0;
  8654. }
  8655. mg_lock_context(conn->ctx);
  8656. /* first try for an exact match */
  8657. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8658. tmp_rh = tmp_rh->next) {
  8659. if (tmp_rh->handler_type == handler_type) {
  8660. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  8661. if (handler_type == WEBSOCKET_HANDLER) {
  8662. *connect_handler = tmp_rh->connect_handler;
  8663. *ready_handler = tmp_rh->ready_handler;
  8664. *data_handler = tmp_rh->data_handler;
  8665. *close_handler = tmp_rh->close_handler;
  8666. } else if (handler_type == REQUEST_HANDLER) {
  8667. *handler = tmp_rh->handler;
  8668. } else { /* AUTH_HANDLER */
  8669. *auth_handler = tmp_rh->auth_handler;
  8670. }
  8671. *cbdata = tmp_rh->cbdata;
  8672. mg_unlock_context(conn->ctx);
  8673. return 1;
  8674. }
  8675. }
  8676. }
  8677. /* next try for a partial match, we will accept uri/something */
  8678. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8679. tmp_rh = tmp_rh->next) {
  8680. if (tmp_rh->handler_type == handler_type) {
  8681. if (tmp_rh->uri_len < urilen && uri[tmp_rh->uri_len] == '/'
  8682. && memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0) {
  8683. if (handler_type == WEBSOCKET_HANDLER) {
  8684. *connect_handler = tmp_rh->connect_handler;
  8685. *ready_handler = tmp_rh->ready_handler;
  8686. *data_handler = tmp_rh->data_handler;
  8687. *close_handler = tmp_rh->close_handler;
  8688. } else if (handler_type == REQUEST_HANDLER) {
  8689. *handler = tmp_rh->handler;
  8690. } else { /* AUTH_HANDLER */
  8691. *auth_handler = tmp_rh->auth_handler;
  8692. }
  8693. *cbdata = tmp_rh->cbdata;
  8694. mg_unlock_context(conn->ctx);
  8695. return 1;
  8696. }
  8697. }
  8698. }
  8699. /* finally try for pattern match */
  8700. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8701. tmp_rh = tmp_rh->next) {
  8702. if (tmp_rh->handler_type == handler_type) {
  8703. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  8704. if (handler_type == WEBSOCKET_HANDLER) {
  8705. *connect_handler = tmp_rh->connect_handler;
  8706. *ready_handler = tmp_rh->ready_handler;
  8707. *data_handler = tmp_rh->data_handler;
  8708. *close_handler = tmp_rh->close_handler;
  8709. } else if (handler_type == REQUEST_HANDLER) {
  8710. *handler = tmp_rh->handler;
  8711. } else { /* AUTH_HANDLER */
  8712. *auth_handler = tmp_rh->auth_handler;
  8713. }
  8714. *cbdata = tmp_rh->cbdata;
  8715. mg_unlock_context(conn->ctx);
  8716. return 1;
  8717. }
  8718. }
  8719. }
  8720. mg_unlock_context(conn->ctx);
  8721. }
  8722. return 0; /* none found */
  8723. }
  8724. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  8725. static int
  8726. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  8727. void *cbdata)
  8728. {
  8729. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  8730. if (pcallbacks->websocket_connect) {
  8731. return pcallbacks->websocket_connect(conn);
  8732. }
  8733. /* No handler set - assume "OK" */
  8734. return 0;
  8735. }
  8736. static void
  8737. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  8738. {
  8739. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  8740. if (pcallbacks->websocket_ready) {
  8741. pcallbacks->websocket_ready(conn);
  8742. }
  8743. }
  8744. static int
  8745. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  8746. int bits,
  8747. char *data,
  8748. size_t len,
  8749. void *cbdata)
  8750. {
  8751. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  8752. if (pcallbacks->websocket_data) {
  8753. return pcallbacks->websocket_data(conn, bits, data, len);
  8754. }
  8755. /* No handler set - assume "OK" */
  8756. return 1;
  8757. }
  8758. #endif
  8759. /* This is the heart of the Civetweb's logic.
  8760. * This function is called when the request is read, parsed and validated,
  8761. * and Civetweb must decide what action to take: serve a file, or
  8762. * a directory, or call embedded function, etcetera. */
  8763. static void
  8764. handle_request(struct mg_connection *conn)
  8765. {
  8766. if (conn) {
  8767. struct mg_request_info *ri = &conn->request_info;
  8768. char path[PATH_MAX];
  8769. int uri_len, ssl_index;
  8770. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  8771. is_put_or_delete_request = 0, is_callback_resource = 0;
  8772. int i;
  8773. struct file file = STRUCT_FILE_INITIALIZER;
  8774. mg_request_handler callback_handler = NULL;
  8775. mg_websocket_connect_handler ws_connect_handler = NULL;
  8776. mg_websocket_ready_handler ws_ready_handler = NULL;
  8777. mg_websocket_data_handler ws_data_handler = NULL;
  8778. mg_websocket_close_handler ws_close_handler = NULL;
  8779. void *callback_data = NULL;
  8780. mg_authorization_handler auth_handler = NULL;
  8781. void *auth_callback_data = NULL;
  8782. #if !defined(NO_FILES)
  8783. time_t curtime = time(NULL);
  8784. char date[64];
  8785. #endif
  8786. path[0] = 0;
  8787. if (!ri) {
  8788. return;
  8789. }
  8790. /* 1. get the request url */
  8791. /* 1.1. split into url and query string */
  8792. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  8793. != NULL) {
  8794. *((char *)conn->request_info.query_string++) = '\0';
  8795. }
  8796. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  8797. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  8798. ssl_index = get_first_ssl_listener_index(conn->ctx);
  8799. if (ssl_index >= 0) {
  8800. redirect_to_https_port(conn, ssl_index);
  8801. } else {
  8802. /* A http to https forward port has been specified,
  8803. * but no https port to forward to. */
  8804. send_http_error(conn,
  8805. 503,
  8806. "%s",
  8807. "Error: SSL forward not configured properly");
  8808. mg_cry(conn, "Can not redirect to SSL, no SSL port available");
  8809. }
  8810. return;
  8811. }
  8812. uri_len = (int)strlen(ri->local_uri);
  8813. /* 1.3. decode url (if config says so) */
  8814. if (should_decode_url(conn)) {
  8815. mg_url_decode(
  8816. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  8817. }
  8818. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  8819. * not possible */
  8820. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  8821. /* step 1. completed, the url is known now */
  8822. uri_len = (int)strlen(ri->local_uri);
  8823. DEBUG_TRACE("URL: %s", ri->local_uri);
  8824. /* 3. if this ip has limited speed, set it for this connection */
  8825. conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
  8826. get_remote_ip(conn),
  8827. ri->local_uri);
  8828. /* 4. call a "handle everything" callback, if registered */
  8829. if (conn->ctx->callbacks.begin_request != NULL) {
  8830. /* Note that since V1.7 the "begin_request" function is called
  8831. * before an authorization check. If an authorization check is
  8832. * required, use a request_handler instead. */
  8833. i = conn->ctx->callbacks.begin_request(conn);
  8834. if (i > 0) {
  8835. /* callback already processed the request. Store the
  8836. return value as a status code for the access log. */
  8837. conn->status_code = i;
  8838. return;
  8839. } else if (i == 0) {
  8840. /* civetweb should process the request */
  8841. } else {
  8842. /* unspecified - may change with the next version */
  8843. return;
  8844. }
  8845. }
  8846. /* request not yet handled by a handler or redirect, so the request
  8847. * is processed here */
  8848. /* 5. interpret the url to find out how the request must be handled
  8849. */
  8850. /* 5.1. first test, if the request targets the regular http(s)://
  8851. * protocol namespace or the websocket ws(s):// protocol namespace.
  8852. */
  8853. is_websocket_request = is_websocket_protocol(conn);
  8854. /* 5.2. check if the request will be handled by a callback */
  8855. if (get_request_handler(conn,
  8856. is_websocket_request ? WEBSOCKET_HANDLER
  8857. : REQUEST_HANDLER,
  8858. &callback_handler,
  8859. &ws_connect_handler,
  8860. &ws_ready_handler,
  8861. &ws_data_handler,
  8862. &ws_close_handler,
  8863. NULL,
  8864. &callback_data)) {
  8865. /* 5.2.1. A callback will handle this request. All requests
  8866. * handled
  8867. * by a callback have to be considered as requests to a script
  8868. * resource. */
  8869. is_callback_resource = 1;
  8870. is_script_resource = 1;
  8871. is_put_or_delete_request = is_put_or_delete_method(conn);
  8872. } else {
  8873. no_callback_resource:
  8874. /* 5.2.2. No callback is responsible for this request. The URI
  8875. * addresses a file based resource (static content or Lua/cgi
  8876. * scripts in the file system). */
  8877. is_callback_resource = 0;
  8878. interpret_uri(conn,
  8879. path,
  8880. sizeof(path),
  8881. &file,
  8882. &is_found,
  8883. &is_script_resource,
  8884. &is_websocket_request,
  8885. &is_put_or_delete_request);
  8886. }
  8887. /* 6. authorization check */
  8888. /* 6.1. a custom authorization handler is installed */
  8889. if (get_request_handler(conn,
  8890. AUTH_HANDLER,
  8891. NULL,
  8892. NULL,
  8893. NULL,
  8894. NULL,
  8895. NULL,
  8896. &auth_handler,
  8897. &auth_callback_data)) {
  8898. if (!auth_handler(conn, auth_callback_data)) {
  8899. return;
  8900. }
  8901. } else if (is_put_or_delete_request && !is_script_resource
  8902. && !is_callback_resource) {
  8903. /* 6.2. this request is a PUT/DELETE to a real file */
  8904. /* 6.2.1. thus, the server must have real files */
  8905. #if defined(NO_FILES)
  8906. if (1) {
  8907. #else
  8908. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  8909. #endif
  8910. /* This server does not have any real files, thus the
  8911. * PUT/DELETE methods are not valid. */
  8912. send_http_error(conn,
  8913. 405,
  8914. "%s method not allowed",
  8915. conn->request_info.request_method);
  8916. return;
  8917. }
  8918. #if !defined(NO_FILES)
  8919. /* 6.2.2. Check if put authorization for static files is
  8920. * available.
  8921. */
  8922. if (!is_authorized_for_put(conn)) {
  8923. send_authorization_request(conn);
  8924. return;
  8925. }
  8926. #endif
  8927. } else {
  8928. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  8929. * or it is a PUT or DELETE request to a resource that does not
  8930. * correspond to a file. Check authorization. */
  8931. if (!check_authorization(conn, path)) {
  8932. send_authorization_request(conn);
  8933. return;
  8934. }
  8935. }
  8936. /* request is authorized or does not need authorization */
  8937. /* 7. check if there are request handlers for this uri */
  8938. if (is_callback_resource) {
  8939. if (!is_websocket_request) {
  8940. i = callback_handler(conn, callback_data);
  8941. if (i > 0) {
  8942. /* Do nothing, callback has served the request. Store
  8943. * the
  8944. * return value as status code for the log and discard
  8945. * all
  8946. * data from the client not used by the callback. */
  8947. conn->status_code = i;
  8948. discard_unread_request_data(conn);
  8949. } else {
  8950. /* TODO (high): what if the handler did NOT handle the
  8951. * request */
  8952. /* The last version did handle this as a file request,
  8953. * but
  8954. * since a file request is not always a script resource,
  8955. * the authorization check might be different */
  8956. interpret_uri(conn,
  8957. path,
  8958. sizeof(path),
  8959. &file,
  8960. &is_found,
  8961. &is_script_resource,
  8962. &is_websocket_request,
  8963. &is_put_or_delete_request);
  8964. callback_handler = NULL;
  8965. /* TODO (very low): goto is deprecated but for the
  8966. * moment,
  8967. * a goto is simpler than some curious loop. */
  8968. /* The situation "callback does not handle the request"
  8969. * needs to be reconsidered anyway. */
  8970. goto no_callback_resource;
  8971. }
  8972. } else {
  8973. #if defined(USE_WEBSOCKET)
  8974. handle_websocket_request(conn,
  8975. path,
  8976. is_callback_resource,
  8977. ws_connect_handler,
  8978. ws_ready_handler,
  8979. ws_data_handler,
  8980. ws_close_handler,
  8981. callback_data);
  8982. #endif
  8983. }
  8984. return;
  8985. }
  8986. /* 8. handle websocket requests */
  8987. #if defined(USE_WEBSOCKET)
  8988. if (is_websocket_request) {
  8989. if (is_script_resource) {
  8990. /* Websocket Lua script */
  8991. handle_websocket_request(conn,
  8992. path,
  8993. 0 /* Lua Script */,
  8994. NULL,
  8995. NULL,
  8996. NULL,
  8997. NULL,
  8998. &conn->ctx->callbacks);
  8999. } else {
  9000. #if defined(MG_LEGACY_INTERFACE)
  9001. handle_websocket_request(
  9002. conn,
  9003. path,
  9004. !is_script_resource /* could be deprecated global callback */,
  9005. deprecated_websocket_connect_wrapper,
  9006. deprecated_websocket_ready_wrapper,
  9007. deprecated_websocket_data_wrapper,
  9008. NULL,
  9009. &conn->ctx->callbacks);
  9010. #else
  9011. send_http_error(conn, 404, "%s", "Not found");
  9012. #endif
  9013. }
  9014. return;
  9015. } else
  9016. #endif
  9017. #if defined(NO_FILES)
  9018. /* 9a. In case the server uses only callbacks, this uri is
  9019. * unknown.
  9020. * Then, all request handling ends here. */
  9021. send_http_error(conn, 404, "%s", "Not Found");
  9022. #else
  9023. /* 9b. This request is either for a static file or resource handled
  9024. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  9025. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  9026. send_http_error(conn, 404, "%s", "Not Found");
  9027. return;
  9028. }
  9029. /* 10. File is handled by a script. */
  9030. if (is_script_resource) {
  9031. handle_file_based_request(conn, path, &file);
  9032. return;
  9033. }
  9034. /* 11. Handle put/delete/mkcol requests */
  9035. if (is_put_or_delete_request) {
  9036. /* 11.1. PUT method */
  9037. if (!strcmp(ri->request_method, "PUT")) {
  9038. put_file(conn, path);
  9039. return;
  9040. }
  9041. /* 11.2. DELETE method */
  9042. if (!strcmp(ri->request_method, "DELETE")) {
  9043. delete_file(conn, path);
  9044. return;
  9045. }
  9046. /* 11.3. MKCOL method */
  9047. if (!strcmp(ri->request_method, "MKCOL")) {
  9048. mkcol(conn, path);
  9049. return;
  9050. }
  9051. /* 11.4. PATCH method
  9052. * This method is not supported for static resources,
  9053. * only for scripts (Lua, CGI) and callbacks. */
  9054. send_http_error(conn,
  9055. 405,
  9056. "%s method not allowed",
  9057. conn->request_info.request_method);
  9058. return;
  9059. }
  9060. /* 11. File does not exist, or it was configured that it should be
  9061. * hidden */
  9062. if (!is_found || (must_hide_file(conn, path))) {
  9063. send_http_error(conn, 404, "%s", "Not found");
  9064. return;
  9065. }
  9066. /* 12. Directory uris should end with a slash */
  9067. if (file.is_directory && (uri_len > 0)
  9068. && (ri->local_uri[uri_len - 1] != '/')) {
  9069. gmt_time_string(date, sizeof(date), &curtime);
  9070. mg_printf(conn,
  9071. "HTTP/1.1 301 Moved Permanently\r\n"
  9072. "Location: %s/\r\n"
  9073. "Date: %s\r\n"
  9074. /* "Cache-Control: private\r\n" (= default) */
  9075. "Content-Length: 0\r\n"
  9076. "Connection: %s\r\n\r\n",
  9077. ri->request_uri,
  9078. date,
  9079. suggest_connection_header(conn));
  9080. return;
  9081. }
  9082. /* 13. Handle other methods than GET/HEAD */
  9083. /* 13.1. Handle PROPFIND */
  9084. if (!strcmp(ri->request_method, "PROPFIND")) {
  9085. handle_propfind(conn, path, &file);
  9086. return;
  9087. }
  9088. /* 13.2. Handle OPTIONS for files */
  9089. if (!strcmp(ri->request_method, "OPTIONS")) {
  9090. /* This standard handler is only used for real files.
  9091. * Scripts should support the OPTIONS method themselves, to allow a
  9092. * maximum flexibility.
  9093. * Lua and CGI scripts may fully support CORS this way (including
  9094. * preflights). */
  9095. send_options(conn);
  9096. return;
  9097. }
  9098. /* 13.3. everything but GET and HEAD (e.g. POST) */
  9099. if (0 != strcmp(ri->request_method, "GET")
  9100. && 0 != strcmp(ri->request_method, "HEAD")) {
  9101. send_http_error(conn,
  9102. 405,
  9103. "%s method not allowed",
  9104. conn->request_info.request_method);
  9105. return;
  9106. }
  9107. /* 14. directories */
  9108. if (file.is_directory) {
  9109. if (substitute_index_file(conn, path, sizeof(path), &file)) {
  9110. /* 14.1. use a substitute file */
  9111. /* TODO (high): substitute index may be a script resource.
  9112. * define what should be possible in this case. */
  9113. } else {
  9114. /* 14.2. no substitute file */
  9115. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  9116. "yes")) {
  9117. handle_directory_request(conn, path);
  9118. } else {
  9119. send_http_error(conn,
  9120. 403,
  9121. "%s",
  9122. "Error: Directory listing denied");
  9123. }
  9124. return;
  9125. }
  9126. }
  9127. handle_file_based_request(conn, path, &file);
  9128. #endif /* !defined(NO_FILES) */
  9129. #if 0
  9130. /* Perform redirect and auth checks before calling begin_request()
  9131. * handler.
  9132. * Otherwise, begin_request() would need to perform auth checks and
  9133. * redirects. */
  9134. #endif
  9135. }
  9136. return;
  9137. }
  9138. static void
  9139. handle_file_based_request(struct mg_connection *conn,
  9140. const char *path,
  9141. struct file *file)
  9142. {
  9143. if (!conn || !conn->ctx) {
  9144. return;
  9145. }
  9146. if (0) {
  9147. #ifdef USE_LUA
  9148. } else if (match_prefix(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  9149. strlen(
  9150. conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  9151. path) > 0) {
  9152. /* Lua server page: an SSI like page containing mostly plain html
  9153. * code
  9154. * plus some tags with server generated contents. */
  9155. handle_lsp_request(conn, path, file, NULL);
  9156. } else if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  9157. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  9158. path) > 0) {
  9159. /* Lua in-server module script: a CGI like script used to generate
  9160. * the
  9161. * entire reply. */
  9162. mg_exec_lua_script(conn, path, NULL);
  9163. #endif
  9164. #if defined(USE_DUKTAPE)
  9165. } else if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  9166. strlen(
  9167. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  9168. path) > 0) {
  9169. /* Call duktape to generate the page */
  9170. mg_exec_duktape_script(conn, path);
  9171. #endif
  9172. #if !defined(NO_CGI)
  9173. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  9174. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  9175. path) > 0) {
  9176. /* CGI scripts may support all HTTP methods */
  9177. handle_cgi_request(conn, path);
  9178. #endif /* !NO_CGI */
  9179. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  9180. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  9181. path) > 0) {
  9182. handle_ssi_file_request(conn, path, file);
  9183. #if !defined(NO_CACHING)
  9184. } else if ((!conn->in_error_handler) && is_not_modified(conn, file)) {
  9185. /* Send 304 "Not Modified" - this must not send any body data */
  9186. handle_not_modified_static_file_request(conn, file);
  9187. #endif /* !NO_CACHING */
  9188. } else {
  9189. handle_static_file_request(conn, path, file, NULL);
  9190. }
  9191. }
  9192. static void
  9193. close_all_listening_sockets(struct mg_context *ctx)
  9194. {
  9195. unsigned int i;
  9196. if (!ctx) {
  9197. return;
  9198. }
  9199. for (i = 0; i < ctx->num_listening_sockets; i++) {
  9200. closesocket(ctx->listening_sockets[i].sock);
  9201. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  9202. }
  9203. mg_free(ctx->listening_sockets);
  9204. ctx->listening_sockets = NULL;
  9205. mg_free(ctx->listening_socket_fds);
  9206. ctx->listening_socket_fds = NULL;
  9207. }
  9208. /* Valid listening port specification is: [ip_address:]port[s]
  9209. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 1.2.3.4:8080s
  9210. * Examples for IPv6: [::]:80, [::1]:80,
  9211. * [FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:443s
  9212. * see https://tools.ietf.org/html/rfc3513#section-2.2 */
  9213. static int
  9214. parse_port_string(const struct vec *vec, struct socket *so)
  9215. {
  9216. unsigned int a, b, c, d, port;
  9217. int ch, len;
  9218. #if defined(USE_IPV6)
  9219. char buf[100] = {0};
  9220. #endif
  9221. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  9222. * Also, all-zeroes in the socket address means binding to all addresses
  9223. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  9224. memset(so, 0, sizeof(*so));
  9225. so->lsa.sin.sin_family = AF_INET;
  9226. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  9227. == 5) {
  9228. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  9229. so->lsa.sin.sin_addr.s_addr =
  9230. htonl((a << 24) | (b << 16) | (c << 8) | d);
  9231. so->lsa.sin.sin_port = htons((uint16_t)port);
  9232. #if defined(USE_IPV6)
  9233. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  9234. && mg_inet_pton(
  9235. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  9236. /* IPv6 address, examples: see above */
  9237. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  9238. */
  9239. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  9240. #endif
  9241. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  9242. /* If only port is specified, bind to IPv4, INADDR_ANY */
  9243. so->lsa.sin.sin_port = htons((uint16_t)port);
  9244. } else {
  9245. /* Parsing failure. Make port invalid. */
  9246. port = 0;
  9247. len = 0;
  9248. }
  9249. /* sscanf and the option splitting code ensure the following condition
  9250. */
  9251. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  9252. return 0;
  9253. }
  9254. ch = vec->ptr[len]; /* Next character after the port number */
  9255. so->is_ssl = (ch == 's');
  9256. so->ssl_redir = (ch == 'r');
  9257. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  9258. return is_valid_port(port)
  9259. && (ch == '\0' || ch == 's' || ch == 'r' || ch == ',');
  9260. }
  9261. static int
  9262. set_ports_option(struct mg_context *ctx)
  9263. {
  9264. const char *list;
  9265. int on = 1;
  9266. #if defined(USE_IPV6)
  9267. int off = 0;
  9268. #endif
  9269. struct vec vec;
  9270. struct socket so, *ptr;
  9271. struct pollfd *pfd;
  9272. union usa usa;
  9273. socklen_t len;
  9274. int portsTotal = 0;
  9275. int portsOk = 0;
  9276. if (!ctx) {
  9277. return 0;
  9278. }
  9279. memset(&so, 0, sizeof(so));
  9280. memset(&usa, 0, sizeof(usa));
  9281. len = sizeof(usa);
  9282. list = ctx->config[LISTENING_PORTS];
  9283. while ((list = next_option(list, &vec, NULL)) != NULL) {
  9284. portsTotal++;
  9285. if (!parse_port_string(&vec, &so)) {
  9286. mg_cry(fc(ctx),
  9287. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  9288. (int)vec.len,
  9289. vec.ptr,
  9290. portsTotal,
  9291. "[IP_ADDRESS:]PORT[s|r]");
  9292. continue;
  9293. }
  9294. #if !defined(NO_SSL)
  9295. if (so.is_ssl && ctx->ssl_ctx == NULL) {
  9296. mg_cry(fc(ctx),
  9297. "Cannot add SSL socket (entry %i). Is -ssl_certificate "
  9298. "option set?",
  9299. portsTotal);
  9300. continue;
  9301. }
  9302. #endif
  9303. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  9304. == INVALID_SOCKET) {
  9305. mg_cry(fc(ctx), "cannot create socket (entry %i)", portsTotal);
  9306. continue;
  9307. }
  9308. #ifdef _WIN32
  9309. /* Windows SO_REUSEADDR lets many procs binds to a
  9310. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  9311. * if someone already has the socket -- DTL */
  9312. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  9313. * Windows might need a few seconds before
  9314. * the same port can be used again in the
  9315. * same process, so a short Sleep may be
  9316. * required between mg_stop and mg_start.
  9317. */
  9318. if (setsockopt(so.sock,
  9319. SOL_SOCKET,
  9320. SO_EXCLUSIVEADDRUSE,
  9321. (SOCK_OPT_TYPE)&on,
  9322. sizeof(on)) != 0) {
  9323. mg_cry(fc(ctx),
  9324. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  9325. portsTotal);
  9326. }
  9327. #else
  9328. if (setsockopt(so.sock,
  9329. SOL_SOCKET,
  9330. SO_REUSEADDR,
  9331. (SOCK_OPT_TYPE)&on,
  9332. sizeof(on)) != 0) {
  9333. mg_cry(fc(ctx),
  9334. "cannot set socket option SO_REUSEADDR (entry %i)",
  9335. portsTotal);
  9336. }
  9337. #endif
  9338. #if defined(USE_IPV6)
  9339. if (so.lsa.sa.sa_family == AF_INET6
  9340. && setsockopt(so.sock,
  9341. IPPROTO_IPV6,
  9342. IPV6_V6ONLY,
  9343. (void *)&off,
  9344. sizeof(off)) != 0) {
  9345. mg_cry(fc(ctx),
  9346. "cannot set socket option IPV6_V6ONLY (entry %i)",
  9347. portsTotal);
  9348. }
  9349. #endif
  9350. if (so.lsa.sa.sa_family == AF_INET) {
  9351. len = sizeof(so.lsa.sin);
  9352. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  9353. mg_cry(fc(ctx),
  9354. "cannot bind to %.*s: %d (%s)",
  9355. (int)vec.len,
  9356. vec.ptr,
  9357. (int)ERRNO,
  9358. strerror(errno));
  9359. closesocket(so.sock);
  9360. so.sock = INVALID_SOCKET;
  9361. continue;
  9362. }
  9363. }
  9364. #if defined(USE_IPV6)
  9365. else if (so.lsa.sa.sa_family == AF_INET6) {
  9366. len = sizeof(so.lsa.sin6);
  9367. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  9368. mg_cry(fc(ctx),
  9369. "cannot bind to IPv6 %.*s: %d (%s)",
  9370. (int)vec.len,
  9371. vec.ptr,
  9372. (int)ERRNO,
  9373. strerror(errno));
  9374. closesocket(so.sock);
  9375. so.sock = INVALID_SOCKET;
  9376. continue;
  9377. }
  9378. }
  9379. #endif
  9380. else {
  9381. mg_cry(fc(ctx),
  9382. "cannot bind: address family not supported (entry %i)",
  9383. portsTotal);
  9384. continue;
  9385. }
  9386. if (listen(so.sock, SOMAXCONN) != 0) {
  9387. mg_cry(fc(ctx),
  9388. "cannot listen to %.*s: %d (%s)",
  9389. (int)vec.len,
  9390. vec.ptr,
  9391. (int)ERRNO,
  9392. strerror(errno));
  9393. closesocket(so.sock);
  9394. so.sock = INVALID_SOCKET;
  9395. continue;
  9396. }
  9397. if (getsockname(so.sock, &(usa.sa), &len) != 0
  9398. || usa.sa.sa_family != so.lsa.sa.sa_family) {
  9399. int err = (int)ERRNO;
  9400. mg_cry(fc(ctx),
  9401. "call to getsockname failed %.*s: %d (%s)",
  9402. (int)vec.len,
  9403. vec.ptr,
  9404. err,
  9405. strerror(errno));
  9406. closesocket(so.sock);
  9407. so.sock = INVALID_SOCKET;
  9408. continue;
  9409. }
  9410. /* Update lsa port in case of random free ports */
  9411. #if defined(USE_IPV6)
  9412. if (so.lsa.sa.sa_family == AF_INET6) {
  9413. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  9414. } else
  9415. #endif
  9416. {
  9417. so.lsa.sin.sin_port = usa.sin.sin_port;
  9418. }
  9419. if ((ptr = (struct socket *)
  9420. mg_realloc(ctx->listening_sockets,
  9421. (ctx->num_listening_sockets + 1)
  9422. * sizeof(ctx->listening_sockets[0]))) == NULL) {
  9423. mg_cry(fc(ctx), "%s", "Out of memory");
  9424. closesocket(so.sock);
  9425. so.sock = INVALID_SOCKET;
  9426. continue;
  9427. }
  9428. if ((pfd = (struct pollfd *)mg_realloc(
  9429. ctx->listening_socket_fds,
  9430. (ctx->num_listening_sockets + 1)
  9431. * sizeof(ctx->listening_socket_fds[0]))) == NULL) {
  9432. mg_cry(fc(ctx), "%s", "Out of memory");
  9433. closesocket(so.sock);
  9434. so.sock = INVALID_SOCKET;
  9435. mg_free(ptr);
  9436. continue;
  9437. }
  9438. set_close_on_exec(so.sock, fc(ctx));
  9439. ctx->listening_sockets = ptr;
  9440. ctx->listening_sockets[ctx->num_listening_sockets] = so;
  9441. ctx->listening_socket_fds = pfd;
  9442. ctx->num_listening_sockets++;
  9443. portsOk++;
  9444. }
  9445. if (portsOk != portsTotal) {
  9446. close_all_listening_sockets(ctx);
  9447. portsOk = 0;
  9448. }
  9449. return portsOk;
  9450. }
  9451. static const char *
  9452. header_val(const struct mg_connection *conn, const char *header)
  9453. {
  9454. const char *header_value;
  9455. if ((header_value = mg_get_header(conn, header)) == NULL) {
  9456. return "-";
  9457. } else {
  9458. return header_value;
  9459. }
  9460. }
  9461. static void
  9462. log_access(const struct mg_connection *conn)
  9463. {
  9464. const struct mg_request_info *ri;
  9465. struct file fi;
  9466. char date[64], src_addr[IP_ADDR_STR_LEN];
  9467. struct tm *tm;
  9468. const char *referer;
  9469. const char *user_agent;
  9470. char buf[4096];
  9471. if (!conn || !conn->ctx) {
  9472. return;
  9473. }
  9474. if (conn->ctx->config[ACCESS_LOG_FILE] != NULL) {
  9475. if (mg_fopen(conn, conn->ctx->config[ACCESS_LOG_FILE], "a+", &fi)
  9476. == 0) {
  9477. fi.fp = NULL;
  9478. }
  9479. } else {
  9480. fi.fp = NULL;
  9481. }
  9482. if (fi.fp == NULL && conn->ctx->callbacks.log_message == NULL) {
  9483. return;
  9484. }
  9485. tm = localtime(&conn->conn_birth_time);
  9486. if (tm != NULL) {
  9487. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  9488. } else {
  9489. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  9490. date[sizeof(date) - 1] = '\0';
  9491. }
  9492. ri = &conn->request_info;
  9493. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9494. referer = header_val(conn, "Referer");
  9495. user_agent = header_val(conn, "User-Agent");
  9496. mg_snprintf(conn,
  9497. NULL, /* Ignore truncation in access log */
  9498. buf,
  9499. sizeof(buf),
  9500. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  9501. src_addr,
  9502. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  9503. date,
  9504. ri->request_method ? ri->request_method : "-",
  9505. ri->request_uri ? ri->request_uri : "-",
  9506. ri->query_string ? "?" : "",
  9507. ri->query_string ? ri->query_string : "",
  9508. ri->http_version,
  9509. conn->status_code,
  9510. conn->num_bytes_sent,
  9511. referer,
  9512. user_agent);
  9513. if (conn->ctx->callbacks.log_access) {
  9514. conn->ctx->callbacks.log_access(conn, buf);
  9515. }
  9516. if (fi.fp) {
  9517. flockfile(fi.fp);
  9518. fprintf(fi.fp, "%s\n", buf);
  9519. fflush(fi.fp);
  9520. funlockfile(fi.fp);
  9521. mg_fclose(&fi);
  9522. }
  9523. }
  9524. /* Verify given socket address against the ACL.
  9525. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  9526. */
  9527. static int
  9528. check_acl(struct mg_context *ctx, uint32_t remote_ip)
  9529. {
  9530. int allowed, flag;
  9531. uint32_t net, mask;
  9532. struct vec vec;
  9533. if (ctx) {
  9534. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  9535. /* If any ACL is set, deny by default */
  9536. allowed = (list == NULL) ? '+' : '-';
  9537. while ((list = next_option(list, &vec, NULL)) != NULL) {
  9538. flag = vec.ptr[0];
  9539. if ((flag != '+' && flag != '-')
  9540. || parse_net(&vec.ptr[1], &net, &mask) == 0) {
  9541. mg_cry(fc(ctx),
  9542. "%s: subnet must be [+|-]x.x.x.x[/x]",
  9543. __func__);
  9544. return -1;
  9545. }
  9546. if (net == (remote_ip & mask)) {
  9547. allowed = flag;
  9548. }
  9549. }
  9550. return allowed == '+';
  9551. }
  9552. return -1;
  9553. }
  9554. #if !defined(_WIN32)
  9555. static int
  9556. set_uid_option(struct mg_context *ctx)
  9557. {
  9558. struct passwd *pw;
  9559. if (ctx) {
  9560. const char *uid = ctx->config[RUN_AS_USER];
  9561. int success = 0;
  9562. if (uid == NULL) {
  9563. success = 1;
  9564. } else {
  9565. if ((pw = getpwnam(uid)) == NULL) {
  9566. mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  9567. } else if (setgid(pw->pw_gid) == -1) {
  9568. mg_cry(fc(ctx),
  9569. "%s: setgid(%s): %s",
  9570. __func__,
  9571. uid,
  9572. strerror(errno));
  9573. } else if (setgroups(0, NULL)) {
  9574. mg_cry(fc(ctx),
  9575. "%s: setgroups(): %s",
  9576. __func__,
  9577. strerror(errno));
  9578. } else if (setuid(pw->pw_uid) == -1) {
  9579. mg_cry(fc(ctx),
  9580. "%s: setuid(%s): %s",
  9581. __func__,
  9582. uid,
  9583. strerror(errno));
  9584. } else {
  9585. success = 1;
  9586. }
  9587. }
  9588. return success;
  9589. }
  9590. return 0;
  9591. }
  9592. #endif /* !_WIN32 */
  9593. static void
  9594. tls_dtor(void *key)
  9595. {
  9596. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  9597. /* key == pthread_getspecific(sTlsKey); */
  9598. if (tls) {
  9599. if (tls->is_master == 2) {
  9600. tls->is_master = -3; /* Mark memory as dead */
  9601. mg_free(tls);
  9602. }
  9603. }
  9604. pthread_setspecific(sTlsKey, NULL);
  9605. }
  9606. #if !defined(NO_SSL)
  9607. /* Must be set if sizeof(pthread_t) > sizeof(unsigned long) */
  9608. static unsigned long
  9609. ssl_id_callback(void)
  9610. {
  9611. #ifdef _WIN32
  9612. return GetCurrentThreadId();
  9613. #else
  9614. #ifdef __clang__
  9615. #pragma clang diagnostic push
  9616. #pragma clang diagnostic ignored "-Wunreachable-code"
  9617. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  9618. * or not, so one of the two conditions will be unreachable by construction.
  9619. * Unfortunately the C standard does not define a way to check this at
  9620. * compile time, since the #if preprocessor conditions can not use the sizeof
  9621. * operator as an argument. */
  9622. #endif
  9623. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  9624. /* This is the problematic case for CRYPTO_set_id_callback:
  9625. * The OS pthread_t can not be cast to unsigned long. */
  9626. struct mg_workerTLS *tls =
  9627. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  9628. if (tls == NULL) {
  9629. /* SSL called from an unknown thread: Create some thread index.
  9630. */
  9631. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  9632. tls->is_master = -2; /* -2 means "3rd party thread" */
  9633. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  9634. pthread_setspecific(sTlsKey, tls);
  9635. }
  9636. return tls->thread_idx;
  9637. } else {
  9638. /* pthread_t may be any data type, so a simple cast to unsigned long
  9639. * can rise a warning/error, depending on the platform.
  9640. * Here memcpy is used as an anything-to-anything cast. */
  9641. unsigned long ret = 0;
  9642. pthread_t t = pthread_self();
  9643. memcpy(&ret, &t, sizeof(pthread_t));
  9644. return ret;
  9645. }
  9646. #ifdef __clang__
  9647. #pragma clang diagnostic pop
  9648. #endif
  9649. #endif
  9650. }
  9651. static int ssl_use_pem_file(struct mg_context *ctx, const char *pem);
  9652. static const char *ssl_error(void);
  9653. static int
  9654. refresh_trust(struct mg_connection *conn)
  9655. {
  9656. static int reload_lock = 0;
  9657. static long int data_check = 0;
  9658. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  9659. struct stat cert_buf;
  9660. long int t;
  9661. char *pem;
  9662. int should_verify_peer;
  9663. if ((pem = conn->ctx->config[SSL_CERTIFICATE]) == NULL
  9664. && conn->ctx->callbacks.init_ssl == NULL) {
  9665. return 0;
  9666. }
  9667. t = data_check;
  9668. if (stat(pem, &cert_buf) != -1) {
  9669. t = (long int)cert_buf.st_mtime;
  9670. }
  9671. if (data_check != t) {
  9672. data_check = t;
  9673. should_verify_peer =
  9674. (conn->ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  9675. && (mg_strcasecmp(conn->ctx->config[SSL_DO_VERIFY_PEER], "yes")
  9676. == 0);
  9677. if (should_verify_peer) {
  9678. char *ca_path = conn->ctx->config[SSL_CA_PATH];
  9679. char *ca_file = conn->ctx->config[SSL_CA_FILE];
  9680. if (SSL_CTX_load_verify_locations(conn->ctx->ssl_ctx,
  9681. ca_file,
  9682. ca_path) != 1) {
  9683. mg_cry(fc(conn->ctx),
  9684. "SSL_CTX_load_verify_locations error: %s "
  9685. "ssl_verify_peer requires setting "
  9686. "either ssl_ca_path or ssl_ca_file. Is any of them "
  9687. "present in "
  9688. "the .conf file?",
  9689. ssl_error());
  9690. return 0;
  9691. }
  9692. }
  9693. if (1 == mg_atomic_inc(p_reload_lock)) {
  9694. if (ssl_use_pem_file(conn->ctx, pem) == 0) {
  9695. return 0;
  9696. }
  9697. *p_reload_lock = 0;
  9698. }
  9699. }
  9700. /* lock while cert is reloading */
  9701. while (*p_reload_lock) {
  9702. sleep(1);
  9703. }
  9704. return 1;
  9705. }
  9706. static pthread_mutex_t *ssl_mutexes;
  9707. static int
  9708. sslize(struct mg_connection *conn, SSL_CTX *s, int (*func)(SSL *))
  9709. {
  9710. int ret, err;
  9711. int short_trust;
  9712. unsigned i;
  9713. if (!conn) {
  9714. return 0;
  9715. }
  9716. short_trust =
  9717. (conn->ctx->config[SSL_SHORT_TRUST] != NULL)
  9718. && (mg_strcasecmp(conn->ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  9719. if (short_trust) {
  9720. int trust_ret = refresh_trust(conn);
  9721. if (!trust_ret) {
  9722. return trust_ret;
  9723. }
  9724. }
  9725. conn->ssl = SSL_new(s);
  9726. if (conn->ssl == NULL) {
  9727. return 0;
  9728. }
  9729. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  9730. if (ret != 1) {
  9731. err = SSL_get_error(conn->ssl, ret);
  9732. (void)err; /* TODO: set some error message */
  9733. SSL_free(conn->ssl);
  9734. conn->ssl = NULL;
  9735. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  9736. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  9737. ERR_remove_state(0);
  9738. return 0;
  9739. }
  9740. /* SSL functions may fail and require to be called again:
  9741. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  9742. * Here "func" could be SSL_connect or SSL_accept. */
  9743. for (i = 0; i <= 16; i *= 2) {
  9744. ret = func(conn->ssl);
  9745. if (ret != 1) {
  9746. err = SSL_get_error(conn->ssl, ret);
  9747. if ((err == SSL_ERROR_WANT_CONNECT)
  9748. || (err == SSL_ERROR_WANT_ACCEPT)) {
  9749. /* Retry */
  9750. mg_sleep(i);
  9751. } else {
  9752. /* This is an error */
  9753. /* TODO: set some error message */
  9754. break;
  9755. }
  9756. } else {
  9757. /* success */
  9758. break;
  9759. }
  9760. }
  9761. if (ret != 1) {
  9762. SSL_free(conn->ssl);
  9763. conn->ssl = NULL;
  9764. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  9765. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  9766. ERR_remove_state(0);
  9767. return 0;
  9768. }
  9769. return 1;
  9770. }
  9771. /* Return OpenSSL error message (from CRYPTO lib) */
  9772. static const char *
  9773. ssl_error(void)
  9774. {
  9775. unsigned long err;
  9776. err = ERR_get_error();
  9777. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  9778. }
  9779. static int
  9780. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  9781. {
  9782. int i;
  9783. const char hexdigit[] = "0123456789abcdef";
  9784. if (memlen <= 0 || buflen <= 0) {
  9785. return 0;
  9786. }
  9787. if (buflen < (3 * memlen)) {
  9788. return 0;
  9789. }
  9790. for (i = 0; i < memlen; i++) {
  9791. if (i > 0) {
  9792. buf[3 * i - 1] = ' ';
  9793. }
  9794. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  9795. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  9796. }
  9797. buf[3 * memlen - 1] = 0;
  9798. return 1;
  9799. }
  9800. static void
  9801. ssl_get_client_cert_info(struct mg_connection *conn)
  9802. {
  9803. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  9804. if (cert) {
  9805. char str_subject[1024];
  9806. char str_issuer[1024];
  9807. char str_serial[1024];
  9808. char str_finger[1024];
  9809. unsigned char buf[256];
  9810. int len;
  9811. /* Handle to algorithm used for fingerprint */
  9812. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  9813. /* Get Subject and issuer */
  9814. X509_NAME *subj = X509_get_subject_name(cert);
  9815. X509_NAME *iss = X509_get_issuer_name(cert);
  9816. /* Get serial number */
  9817. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  9818. /* Translate subject and issuer to a string */
  9819. (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
  9820. (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
  9821. /* Translate serial number to a hex string */
  9822. len = i2c_ASN1_INTEGER(serial, NULL);
  9823. if (len < sizeof(buf)) {
  9824. unsigned char *pbuf = buf;
  9825. int len2 = i2c_ASN1_INTEGER(serial, &pbuf);
  9826. if (!hexdump2string(
  9827. buf, len2, str_serial, (int)sizeof(str_serial))) {
  9828. *str_serial = 0;
  9829. }
  9830. } else {
  9831. *str_serial = 0;
  9832. }
  9833. /* Calculate SHA1 fingerprint and store as a hex string */
  9834. len = 0;
  9835. ASN1_digest((int (*)())i2d_X509, digest, (char *)cert, buf, &len);
  9836. if (!hexdump2string(buf, len, str_finger, (int)sizeof(str_finger))) {
  9837. *str_finger = 0;
  9838. }
  9839. conn->request_info.client_cert =
  9840. (struct client_cert *)mg_malloc(sizeof(struct client_cert));
  9841. if (conn->request_info.client_cert) {
  9842. conn->request_info.client_cert->subject = mg_strdup(str_subject);
  9843. conn->request_info.client_cert->issuer = mg_strdup(str_issuer);
  9844. conn->request_info.client_cert->serial = mg_strdup(str_serial);
  9845. conn->request_info.client_cert->finger = mg_strdup(str_finger);
  9846. } else {
  9847. /* TODO: write some OOM message */
  9848. }
  9849. X509_free(cert);
  9850. }
  9851. }
  9852. static void
  9853. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  9854. {
  9855. (void)line;
  9856. (void)file;
  9857. if (mode & 1) {
  9858. /* 1 is CRYPTO_LOCK */
  9859. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  9860. } else {
  9861. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  9862. }
  9863. }
  9864. #if !defined(NO_SSL_DL)
  9865. static void *
  9866. load_dll(struct mg_context *ctx, const char *dll_name, struct ssl_func *sw)
  9867. {
  9868. union {
  9869. void *p;
  9870. void (*fp)(void);
  9871. } u;
  9872. void *dll_handle;
  9873. struct ssl_func *fp;
  9874. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  9875. mg_cry(fc(ctx), "%s: cannot load %s", __func__, dll_name);
  9876. return NULL;
  9877. }
  9878. for (fp = sw; fp->name != NULL; fp++) {
  9879. #ifdef _WIN32
  9880. /* GetProcAddress() returns pointer to function */
  9881. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  9882. #else
  9883. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  9884. * pointers to function pointers. We need to use a union to make a
  9885. * cast. */
  9886. u.p = dlsym(dll_handle, fp->name);
  9887. #endif /* _WIN32 */
  9888. if (u.fp == NULL) {
  9889. mg_cry(fc(ctx),
  9890. "%s: %s: cannot find %s",
  9891. __func__,
  9892. dll_name,
  9893. fp->name);
  9894. dlclose(dll_handle);
  9895. return NULL;
  9896. } else {
  9897. fp->ptr = u.fp;
  9898. }
  9899. }
  9900. return dll_handle;
  9901. }
  9902. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  9903. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  9904. #endif /* NO_SSL_DL */
  9905. #if defined(SSL_ALREADY_INITIALIZED)
  9906. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  9907. #else
  9908. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  9909. #endif
  9910. static int
  9911. initialize_ssl(struct mg_context *ctx)
  9912. {
  9913. int i;
  9914. size_t size;
  9915. #if !defined(NO_SSL_DL)
  9916. if (!cryptolib_dll_handle) {
  9917. cryptolib_dll_handle = load_dll(ctx, CRYPTO_LIB, crypto_sw);
  9918. if (!cryptolib_dll_handle) {
  9919. return 0;
  9920. }
  9921. }
  9922. #endif /* NO_SSL_DL */
  9923. if (mg_atomic_inc(&cryptolib_users) > 1) {
  9924. return 1;
  9925. }
  9926. /* Initialize locking callbacks, needed for thread safety.
  9927. * http://www.openssl.org/support/faq.html#PROG1
  9928. */
  9929. i = CRYPTO_num_locks();
  9930. if (i < 0) {
  9931. i = 0;
  9932. }
  9933. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  9934. if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  9935. mg_cry(fc(ctx),
  9936. "%s: cannot allocate mutexes: %s",
  9937. __func__,
  9938. ssl_error());
  9939. return 0;
  9940. }
  9941. for (i = 0; i < CRYPTO_num_locks(); i++) {
  9942. pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr);
  9943. }
  9944. CRYPTO_set_locking_callback(&ssl_locking_callback);
  9945. CRYPTO_set_id_callback(&ssl_id_callback);
  9946. return 1;
  9947. }
  9948. static int
  9949. ssl_use_pem_file(struct mg_context *ctx, const char *pem)
  9950. {
  9951. if (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0) {
  9952. mg_cry(fc(ctx),
  9953. "%s: cannot open certificate file %s: %s",
  9954. __func__,
  9955. pem,
  9956. ssl_error());
  9957. return 0;
  9958. }
  9959. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  9960. if (SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0) {
  9961. mg_cry(fc(ctx),
  9962. "%s: cannot open private key file %s: %s",
  9963. __func__,
  9964. pem,
  9965. ssl_error());
  9966. return 0;
  9967. }
  9968. if (SSL_CTX_check_private_key(ctx->ssl_ctx) == 0) {
  9969. mg_cry(fc(ctx),
  9970. "%s: certificate and private key do not match: %s",
  9971. __func__,
  9972. pem);
  9973. return 0;
  9974. }
  9975. if (SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem) == 0) {
  9976. mg_cry(fc(ctx),
  9977. "%s: cannot use certificate chain file %s: %s",
  9978. __func__,
  9979. pem,
  9980. ssl_error());
  9981. return 0;
  9982. }
  9983. return 1;
  9984. }
  9985. static long
  9986. ssl_get_protocol(int version_id)
  9987. {
  9988. long ret = SSL_OP_ALL;
  9989. if (version_id > 0)
  9990. ret |= SSL_OP_NO_SSLv2;
  9991. if (version_id > 1)
  9992. ret |= SSL_OP_NO_SSLv3;
  9993. if (version_id > 2)
  9994. ret |= SSL_OP_NO_TLSv1;
  9995. if (version_id > 3)
  9996. ret |= SSL_OP_NO_TLSv1_1;
  9997. return ret;
  9998. }
  9999. /* Dynamically load SSL library. Set up ctx->ssl_ctx pointer. */
  10000. static int
  10001. set_ssl_option(struct mg_context *ctx)
  10002. {
  10003. const char *pem;
  10004. int callback_ret;
  10005. int should_verify_peer;
  10006. const char *ca_path;
  10007. const char *ca_file;
  10008. int use_default_verify_paths;
  10009. int verify_depth;
  10010. time_t now_rt = time(NULL);
  10011. struct timespec now_mt;
  10012. md5_byte_t ssl_context_id[16];
  10013. md5_state_t md5state;
  10014. int protocol_ver;
  10015. /* If PEM file is not specified and the init_ssl callback
  10016. * is not specified, skip SSL initialization. */
  10017. if (!ctx) {
  10018. return 0;
  10019. }
  10020. if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL
  10021. && ctx->callbacks.init_ssl == NULL) {
  10022. return 1;
  10023. }
  10024. if (!initialize_ssl(ctx)) {
  10025. return 0;
  10026. }
  10027. #if !defined(NO_SSL_DL)
  10028. if (!ssllib_dll_handle) {
  10029. ssllib_dll_handle = load_dll(ctx, SSL_LIB, ssl_sw);
  10030. if (!ssllib_dll_handle) {
  10031. return 0;
  10032. }
  10033. }
  10034. #endif /* NO_SSL_DL */
  10035. /* Initialize SSL library */
  10036. SSL_library_init();
  10037. SSL_load_error_strings();
  10038. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  10039. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  10040. return 0;
  10041. }
  10042. SSL_CTX_clear_options(ctx->ssl_ctx,
  10043. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  10044. | SSL_OP_NO_TLSv1_1);
  10045. protocol_ver = atoi(ctx->config[SSL_PROTOCOL_VERSION]);
  10046. SSL_CTX_set_options(ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  10047. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  10048. SSL_CTX_set_ecdh_auto(ctx->ssl_ctx, 1);
  10049. /* If a callback has been specified, call it. */
  10050. callback_ret =
  10051. (ctx->callbacks.init_ssl == NULL)
  10052. ? 0
  10053. : (ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data));
  10054. /* If callback returns 0, civetweb sets up the SSL certificate.
  10055. * If it returns 1, civetweb assumes the calback already did this.
  10056. * If it returns -1, initializing ssl fails. */
  10057. if (callback_ret < 0) {
  10058. mg_cry(fc(ctx), "SSL callback returned error: %i", callback_ret);
  10059. return 0;
  10060. }
  10061. if (callback_ret > 0) {
  10062. if (pem != NULL) {
  10063. (void)SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
  10064. }
  10065. return 1;
  10066. }
  10067. /* Use some UID as session context ID. */
  10068. md5_init(&md5state);
  10069. md5_append(&md5state, (const md5_byte_t *)&now_rt, sizeof(now_rt));
  10070. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  10071. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  10072. md5_append(&md5state,
  10073. (const md5_byte_t *)ctx->config[LISTENING_PORTS],
  10074. strlen(ctx->config[LISTENING_PORTS]));
  10075. md5_append(&md5state, (const md5_byte_t *)ctx, sizeof(*ctx));
  10076. md5_finish(&md5state, ssl_context_id);
  10077. SSL_CTX_set_session_id_context(ctx->ssl_ctx,
  10078. (const unsigned char *)&ssl_context_id,
  10079. sizeof(ssl_context_id));
  10080. if (pem != NULL) {
  10081. if (!ssl_use_pem_file(ctx, pem)) {
  10082. return 0;
  10083. }
  10084. }
  10085. should_verify_peer =
  10086. (ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  10087. && (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0);
  10088. use_default_verify_paths =
  10089. (ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  10090. && (mg_strcasecmp(ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes") == 0);
  10091. if (should_verify_peer) {
  10092. ca_path = ctx->config[SSL_CA_PATH];
  10093. ca_file = ctx->config[SSL_CA_FILE];
  10094. if (SSL_CTX_load_verify_locations(ctx->ssl_ctx, ca_file, ca_path)
  10095. != 1) {
  10096. mg_cry(fc(ctx),
  10097. "SSL_CTX_load_verify_locations error: %s "
  10098. "ssl_verify_peer requires setting "
  10099. "either ssl_ca_path or ssl_ca_file. Is any of them "
  10100. "present in "
  10101. "the .conf file?",
  10102. ssl_error());
  10103. return 0;
  10104. }
  10105. SSL_CTX_set_verify(ctx->ssl_ctx,
  10106. SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  10107. NULL);
  10108. if (use_default_verify_paths
  10109. && SSL_CTX_set_default_verify_paths(ctx->ssl_ctx) != 1) {
  10110. mg_cry(fc(ctx),
  10111. "SSL_CTX_set_default_verify_paths error: %s",
  10112. ssl_error());
  10113. return 0;
  10114. }
  10115. if (ctx->config[SSL_VERIFY_DEPTH]) {
  10116. verify_depth = atoi(ctx->config[SSL_VERIFY_DEPTH]);
  10117. SSL_CTX_set_verify_depth(ctx->ssl_ctx, verify_depth);
  10118. }
  10119. }
  10120. if (ctx->config[SSL_CIPHER_LIST] != NULL) {
  10121. if (SSL_CTX_set_cipher_list(ctx->ssl_ctx, ctx->config[SSL_CIPHER_LIST])
  10122. != 1) {
  10123. mg_cry(fc(ctx), "SSL_CTX_set_cipher_list error: %s", ssl_error());
  10124. }
  10125. }
  10126. return 1;
  10127. }
  10128. static void
  10129. uninitialize_ssl(struct mg_context *ctx)
  10130. {
  10131. int i;
  10132. (void)ctx;
  10133. if (mg_atomic_dec(&cryptolib_users) == 0) {
  10134. /* Shutdown according to
  10135. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  10136. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  10137. */
  10138. CRYPTO_set_locking_callback(NULL);
  10139. CRYPTO_set_id_callback(NULL);
  10140. ENGINE_cleanup();
  10141. CONF_modules_unload(1);
  10142. ERR_free_strings();
  10143. EVP_cleanup();
  10144. CRYPTO_cleanup_all_ex_data();
  10145. ERR_remove_state(0);
  10146. for (i = 0; i < CRYPTO_num_locks(); i++) {
  10147. pthread_mutex_destroy(&ssl_mutexes[i]);
  10148. }
  10149. mg_free(ssl_mutexes);
  10150. ssl_mutexes = NULL;
  10151. }
  10152. }
  10153. #endif /* !NO_SSL */
  10154. static int
  10155. set_gpass_option(struct mg_context *ctx)
  10156. {
  10157. if (ctx) {
  10158. struct file file = STRUCT_FILE_INITIALIZER;
  10159. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  10160. if (path != NULL && !mg_stat(fc(ctx), path, &file)) {
  10161. mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  10162. return 0;
  10163. }
  10164. return 1;
  10165. }
  10166. return 0;
  10167. }
  10168. static int
  10169. set_acl_option(struct mg_context *ctx)
  10170. {
  10171. return check_acl(ctx, (uint32_t)0x7f000001UL) != -1;
  10172. }
  10173. static void
  10174. reset_per_request_attributes(struct mg_connection *conn)
  10175. {
  10176. if (!conn) {
  10177. return;
  10178. }
  10179. conn->path_info = NULL;
  10180. conn->num_bytes_sent = conn->consumed_content = 0;
  10181. conn->status_code = -1;
  10182. conn->is_chunked = 0;
  10183. conn->must_close = conn->request_len = conn->throttle = 0;
  10184. conn->request_info.content_length = -1;
  10185. conn->request_info.remote_user = NULL;
  10186. conn->request_info.request_method = NULL;
  10187. conn->request_info.request_uri = NULL;
  10188. conn->request_info.local_uri = NULL;
  10189. conn->request_info.uri = NULL; /* TODO: cleanup uri,
  10190. * local_uri and request_uri */
  10191. conn->request_info.http_version = NULL;
  10192. conn->request_info.num_headers = 0;
  10193. conn->data_len = 0;
  10194. conn->chunk_remainder = 0;
  10195. conn->internal_error = 0;
  10196. }
  10197. static int
  10198. set_sock_timeout(SOCKET sock, int milliseconds)
  10199. {
  10200. int r0 = 0, r1, r2;
  10201. #ifdef _WIN32
  10202. /* Windows specific */
  10203. DWORD tv = (DWORD)milliseconds;
  10204. #else
  10205. /* Linux, ... (not Windows) */
  10206. struct timeval tv;
  10207. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  10208. * max. time waiting for the acknowledged of TCP data before the connection
  10209. * will be forcefully closed and ETIMEDOUT is returned to the application.
  10210. * If this option is not set, the default timeout of 20-30 minutes is used.
  10211. */
  10212. /* #define TCP_USER_TIMEOUT (18) */
  10213. #if defined(TCP_USER_TIMEOUT)
  10214. unsigned int uto = (unsigned int)milliseconds;
  10215. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  10216. #endif
  10217. memset(&tv, 0, sizeof(tv));
  10218. tv.tv_sec = milliseconds / 1000;
  10219. tv.tv_usec = (milliseconds * 1000) % 1000000;
  10220. #endif /* _WIN32 */
  10221. r1 = setsockopt(
  10222. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  10223. r2 = setsockopt(
  10224. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  10225. return r0 || r1 || r2;
  10226. }
  10227. static int
  10228. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  10229. {
  10230. if (setsockopt(sock,
  10231. IPPROTO_TCP,
  10232. TCP_NODELAY,
  10233. (SOCK_OPT_TYPE)&nodelay_on,
  10234. sizeof(nodelay_on)) != 0) {
  10235. /* Error */
  10236. return 1;
  10237. }
  10238. /* OK */
  10239. return 0;
  10240. }
  10241. static void
  10242. close_socket_gracefully(struct mg_connection *conn)
  10243. {
  10244. #if defined(_WIN32)
  10245. char buf[MG_BUF_LEN];
  10246. int n;
  10247. #endif
  10248. struct linger linger;
  10249. if (!conn) {
  10250. return;
  10251. }
  10252. /* Set linger option to avoid socket hanging out after close. This
  10253. * prevent
  10254. * ephemeral port exhaust problem under high QPS. */
  10255. linger.l_onoff = 1;
  10256. linger.l_linger = 1;
  10257. if (setsockopt(conn->client.sock,
  10258. SOL_SOCKET,
  10259. SO_LINGER,
  10260. (char *)&linger,
  10261. sizeof(linger)) != 0) {
  10262. mg_cry(conn,
  10263. "%s: setsockopt(SOL_SOCKET SO_LINGER) failed: %s",
  10264. __func__,
  10265. strerror(ERRNO));
  10266. }
  10267. /* Send FIN to the client */
  10268. shutdown(conn->client.sock, SHUTDOWN_WR);
  10269. set_non_blocking_mode(conn->client.sock);
  10270. #if defined(_WIN32)
  10271. /* Read and discard pending incoming data. If we do not do that and
  10272. * close
  10273. * the socket, the data in the send buffer may be discarded. This
  10274. * behaviour is seen on Windows, when client keeps sending data
  10275. * when server decides to close the connection; then when client
  10276. * does recv() it gets no data back. */
  10277. do {
  10278. n = pull(
  10279. NULL, conn, buf, sizeof(buf), 1E-10 /* TODO: allow 0 as timeout */);
  10280. } while (n > 0);
  10281. #endif
  10282. /* Now we know that our FIN is ACK-ed, safe to close */
  10283. closesocket(conn->client.sock);
  10284. conn->client.sock = INVALID_SOCKET;
  10285. }
  10286. static void
  10287. close_connection(struct mg_connection *conn)
  10288. {
  10289. if (!conn || !conn->ctx) {
  10290. return;
  10291. }
  10292. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  10293. if (conn->lua_websocket_state) {
  10294. lua_websocket_close(conn, conn->lua_websocket_state);
  10295. conn->lua_websocket_state = NULL;
  10296. }
  10297. #endif
  10298. /* call the connection_close callback if assigned */
  10299. if ((conn->ctx->callbacks.connection_close != NULL)
  10300. && (conn->ctx->context_type == 1)) {
  10301. conn->ctx->callbacks.connection_close(conn);
  10302. }
  10303. mg_lock_connection(conn);
  10304. conn->must_close = 1;
  10305. #ifndef NO_SSL
  10306. if (conn->ssl != NULL) {
  10307. /* Run SSL_shutdown twice to ensure completly close SSL connection
  10308. */
  10309. SSL_shutdown(conn->ssl);
  10310. SSL_free(conn->ssl);
  10311. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  10312. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  10313. ERR_remove_state(0);
  10314. conn->ssl = NULL;
  10315. }
  10316. #endif
  10317. if (conn->client.sock != INVALID_SOCKET) {
  10318. close_socket_gracefully(conn);
  10319. conn->client.sock = INVALID_SOCKET;
  10320. }
  10321. mg_unlock_connection(conn);
  10322. }
  10323. void
  10324. mg_close_connection(struct mg_connection *conn)
  10325. {
  10326. struct mg_context *client_ctx = NULL;
  10327. unsigned int i;
  10328. if (conn == NULL) {
  10329. return;
  10330. }
  10331. if (conn->ctx->context_type == 2) {
  10332. client_ctx = conn->ctx;
  10333. /* client context: loops must end */
  10334. conn->ctx->stop_flag = 1;
  10335. }
  10336. #ifndef NO_SSL
  10337. if (conn->client_ssl_ctx != NULL) {
  10338. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  10339. }
  10340. #endif
  10341. close_connection(conn);
  10342. if (client_ctx != NULL) {
  10343. /* join worker thread and free context */
  10344. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  10345. if (client_ctx->workerthreadids[i] != 0) {
  10346. mg_join_thread(client_ctx->workerthreadids[i]);
  10347. }
  10348. }
  10349. mg_free(client_ctx->workerthreadids);
  10350. mg_free(client_ctx);
  10351. (void)pthread_mutex_destroy(&conn->mutex);
  10352. mg_free(conn);
  10353. }
  10354. }
  10355. static struct mg_connection *
  10356. mg_connect_client_impl(const struct mg_client_options *client_options,
  10357. int use_ssl,
  10358. char *ebuf,
  10359. size_t ebuf_len)
  10360. {
  10361. static struct mg_context fake_ctx;
  10362. struct mg_connection *conn = NULL;
  10363. SOCKET sock;
  10364. union usa sa;
  10365. if (!connect_socket(&fake_ctx,
  10366. client_options->host,
  10367. client_options->port,
  10368. use_ssl,
  10369. ebuf,
  10370. ebuf_len,
  10371. &sock,
  10372. &sa)) {
  10373. ;
  10374. } else if ((conn = (struct mg_connection *)
  10375. mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) {
  10376. mg_snprintf(NULL,
  10377. NULL, /* No truncation check for ebuf */
  10378. ebuf,
  10379. ebuf_len,
  10380. "calloc(): %s",
  10381. strerror(ERRNO));
  10382. closesocket(sock);
  10383. #ifndef NO_SSL
  10384. } else if (use_ssl
  10385. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  10386. == NULL) {
  10387. mg_snprintf(NULL,
  10388. NULL, /* No truncation check for ebuf */
  10389. ebuf,
  10390. ebuf_len,
  10391. "SSL_CTX_new error");
  10392. closesocket(sock);
  10393. mg_free(conn);
  10394. conn = NULL;
  10395. #endif /* NO_SSL */
  10396. } else {
  10397. #ifdef USE_IPV6
  10398. socklen_t len = (sa.sa.sa_family == AF_INET)
  10399. ? sizeof(conn->client.rsa.sin)
  10400. : sizeof(conn->client.rsa.sin6);
  10401. struct sockaddr *psa =
  10402. (sa.sa.sa_family == AF_INET)
  10403. ? (struct sockaddr *)&(conn->client.rsa.sin)
  10404. : (struct sockaddr *)&(conn->client.rsa.sin6);
  10405. #else
  10406. socklen_t len = sizeof(conn->client.rsa.sin);
  10407. struct sockaddr *psa = (struct sockaddr *)&(conn->client.rsa.sin);
  10408. #endif
  10409. conn->buf_size = MAX_REQUEST_SIZE;
  10410. conn->buf = (char *)(conn + 1);
  10411. conn->ctx = &fake_ctx;
  10412. conn->client.sock = sock;
  10413. conn->client.lsa = sa;
  10414. if (getsockname(sock, psa, &len) != 0) {
  10415. mg_cry(conn,
  10416. "%s: getsockname() failed: %s",
  10417. __func__,
  10418. strerror(ERRNO));
  10419. }
  10420. conn->client.is_ssl = use_ssl ? 1 : 0;
  10421. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  10422. #ifndef NO_SSL
  10423. if (use_ssl) {
  10424. fake_ctx.ssl_ctx = conn->client_ssl_ctx;
  10425. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  10426. * SSL_CTX_set_verify call is needed to switch off server
  10427. * certificate checking, which is off by default in OpenSSL and
  10428. * on in yaSSL. */
  10429. /* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  10430. * SSL_VERIFY_PEER, verify_ssl_server); */
  10431. if (client_options->client_cert) {
  10432. if (!ssl_use_pem_file(&fake_ctx, client_options->client_cert)) {
  10433. mg_snprintf(NULL,
  10434. NULL, /* No truncation check for ebuf */
  10435. ebuf,
  10436. ebuf_len,
  10437. "Can not use SSL client certificate");
  10438. SSL_CTX_free(conn->client_ssl_ctx);
  10439. closesocket(sock);
  10440. mg_free(conn);
  10441. conn = NULL;
  10442. }
  10443. }
  10444. if (client_options->server_cert) {
  10445. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  10446. client_options->server_cert,
  10447. NULL);
  10448. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  10449. } else {
  10450. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  10451. }
  10452. if (!sslize(conn, conn->client_ssl_ctx, SSL_connect)) {
  10453. mg_snprintf(NULL,
  10454. NULL, /* No truncation check for ebuf */
  10455. ebuf,
  10456. ebuf_len,
  10457. "SSL connection error");
  10458. SSL_CTX_free(conn->client_ssl_ctx);
  10459. closesocket(sock);
  10460. mg_free(conn);
  10461. conn = NULL;
  10462. }
  10463. }
  10464. #endif
  10465. }
  10466. return conn;
  10467. }
  10468. CIVETWEB_API struct mg_connection *
  10469. mg_connect_client_secure(const struct mg_client_options *client_options,
  10470. char *error_buffer,
  10471. size_t error_buffer_size)
  10472. {
  10473. return mg_connect_client_impl(client_options,
  10474. 1,
  10475. error_buffer,
  10476. error_buffer_size);
  10477. }
  10478. struct mg_connection *
  10479. mg_connect_client(const char *host,
  10480. int port,
  10481. int use_ssl,
  10482. char *error_buffer,
  10483. size_t error_buffer_size)
  10484. {
  10485. struct mg_client_options opts;
  10486. memset(&opts, 0, sizeof(opts));
  10487. opts.host = host;
  10488. opts.port = port;
  10489. return mg_connect_client_impl(&opts,
  10490. use_ssl,
  10491. error_buffer,
  10492. error_buffer_size);
  10493. }
  10494. static const struct {
  10495. const char *proto;
  10496. size_t proto_len;
  10497. unsigned default_port;
  10498. } abs_uri_protocols[] = {{"http://", 7, 80},
  10499. {"https://", 8, 443},
  10500. {"ws://", 5, 80},
  10501. {"wss://", 6, 443},
  10502. {NULL, 0, 0}};
  10503. /* Check if the uri is valid.
  10504. * return 0 for invalid uri,
  10505. * return 1 for *,
  10506. * return 2 for relative uri,
  10507. * return 3 for absolute uri without port,
  10508. * return 4 for absolute uri with port */
  10509. static int
  10510. get_uri_type(const char *uri)
  10511. {
  10512. int i;
  10513. char *hostend, *portbegin, *portend;
  10514. unsigned long port;
  10515. /* According to the HTTP standard
  10516. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  10517. * URI can be an asterisk (*) or should start with slash (relative uri),
  10518. * or it should start with the protocol (absolute uri). */
  10519. if (uri[0] == '*' && uri[1] == '\0') {
  10520. /* asterisk */
  10521. return 1;
  10522. }
  10523. if (uri[0] == '/') {
  10524. /* relative uri */
  10525. return 2;
  10526. }
  10527. /* It could be an absolute uri: */
  10528. /* This function only checks if the uri is valid, not if it is
  10529. * addressing the current server. So civetweb can also be used
  10530. * as a proxy server. */
  10531. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  10532. if (mg_strncasecmp(uri,
  10533. abs_uri_protocols[i].proto,
  10534. abs_uri_protocols[i].proto_len) == 0) {
  10535. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  10536. if (!hostend) {
  10537. return 0;
  10538. }
  10539. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  10540. if (!portbegin) {
  10541. return 3;
  10542. }
  10543. port = strtoul(portbegin + 1, &portend, 10);
  10544. if ((portend != hostend) || !port || !is_valid_port(port)) {
  10545. return 0;
  10546. }
  10547. return 4;
  10548. }
  10549. }
  10550. return 0;
  10551. }
  10552. /* Return NULL or the relative uri at the current server */
  10553. static const char *
  10554. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  10555. {
  10556. const char *server_domain;
  10557. size_t server_domain_len;
  10558. size_t request_domain_len = 0;
  10559. unsigned long port = 0;
  10560. int i;
  10561. const char *hostbegin = NULL;
  10562. const char *hostend = NULL;
  10563. const char *portbegin;
  10564. char *portend;
  10565. /* DNS is case insensitive, so use case insensitive string compare here
  10566. */
  10567. server_domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  10568. if (!server_domain) {
  10569. return 0;
  10570. }
  10571. server_domain_len = strlen(server_domain);
  10572. if (!server_domain_len) {
  10573. return 0;
  10574. }
  10575. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  10576. if (mg_strncasecmp(uri,
  10577. abs_uri_protocols[i].proto,
  10578. abs_uri_protocols[i].proto_len) == 0) {
  10579. hostbegin = uri + abs_uri_protocols[i].proto_len;
  10580. hostend = strchr(hostbegin, '/');
  10581. if (!hostend) {
  10582. return 0;
  10583. }
  10584. portbegin = strchr(hostbegin, ':');
  10585. if ((!portbegin) || (portbegin > hostend)) {
  10586. port = abs_uri_protocols[i].default_port;
  10587. request_domain_len = (size_t)(hostend - hostbegin);
  10588. } else {
  10589. port = strtoul(portbegin + 1, &portend, 10);
  10590. if ((portend != hostend) || !port || !is_valid_port(port)) {
  10591. return 0;
  10592. }
  10593. request_domain_len = (size_t)(portbegin - hostbegin);
  10594. }
  10595. /* protocol found, port set */
  10596. break;
  10597. }
  10598. }
  10599. if (!port) {
  10600. /* port remains 0 if the protocol is not found */
  10601. return 0;
  10602. }
  10603. #if defined(USE_IPV6)
  10604. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  10605. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  10606. /* Request is directed to a different port */
  10607. return 0;
  10608. }
  10609. } else
  10610. #endif
  10611. {
  10612. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  10613. /* Request is directed to a different port */
  10614. return 0;
  10615. }
  10616. }
  10617. if ((request_domain_len != server_domain_len)
  10618. || (0 != memcmp(server_domain, hostbegin, server_domain_len))) {
  10619. /* Request is directed to another server */
  10620. return 0;
  10621. }
  10622. return hostend;
  10623. }
  10624. static int
  10625. getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  10626. {
  10627. const char *cl;
  10628. if (ebuf_len > 0) {
  10629. ebuf[0] = '\0';
  10630. }
  10631. *err = 0;
  10632. reset_per_request_attributes(conn);
  10633. if (!conn) {
  10634. mg_snprintf(conn,
  10635. NULL, /* No truncation check for ebuf */
  10636. ebuf,
  10637. ebuf_len,
  10638. "%s",
  10639. "Internal error");
  10640. *err = 500;
  10641. return 0;
  10642. }
  10643. /* Set the time the request was received. This value should be used for
  10644. * timeouts. */
  10645. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  10646. conn->request_len =
  10647. read_request(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  10648. /* assert(conn->request_len < 0 || conn->data_len >= conn->request_len);
  10649. */
  10650. if (conn->request_len >= 0 && conn->data_len < conn->request_len) {
  10651. mg_snprintf(conn,
  10652. NULL, /* No truncation check for ebuf */
  10653. ebuf,
  10654. ebuf_len,
  10655. "%s",
  10656. "Invalid request size");
  10657. *err = 500;
  10658. return 0;
  10659. }
  10660. if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
  10661. mg_snprintf(conn,
  10662. NULL, /* No truncation check for ebuf */
  10663. ebuf,
  10664. ebuf_len,
  10665. "%s",
  10666. "Request Too Large");
  10667. *err = 413;
  10668. return 0;
  10669. } else if (conn->request_len <= 0) {
  10670. if (conn->data_len > 0) {
  10671. mg_snprintf(conn,
  10672. NULL, /* No truncation check for ebuf */
  10673. ebuf,
  10674. ebuf_len,
  10675. "%s",
  10676. "Client sent malformed request");
  10677. *err = 400;
  10678. } else {
  10679. /* Server did not send anything -> just close the connection */
  10680. conn->must_close = 1;
  10681. mg_snprintf(conn,
  10682. NULL, /* No truncation check for ebuf */
  10683. ebuf,
  10684. ebuf_len,
  10685. "%s",
  10686. "Client did not send a request");
  10687. *err = 0;
  10688. }
  10689. return 0;
  10690. } else if (parse_http_message(conn->buf,
  10691. conn->buf_size,
  10692. &conn->request_info) <= 0) {
  10693. mg_snprintf(conn,
  10694. NULL, /* No truncation check for ebuf */
  10695. ebuf,
  10696. ebuf_len,
  10697. "%s",
  10698. "Bad Request");
  10699. *err = 400;
  10700. return 0;
  10701. } else {
  10702. /* Message is a valid request or response */
  10703. if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) {
  10704. /* Request/response has content length set */
  10705. char *endptr = NULL;
  10706. conn->content_len = strtoll(cl, &endptr, 10);
  10707. if (endptr == cl) {
  10708. mg_snprintf(conn,
  10709. NULL, /* No truncation check for ebuf */
  10710. ebuf,
  10711. ebuf_len,
  10712. "%s",
  10713. "Bad Request");
  10714. *err = 411;
  10715. return 0;
  10716. }
  10717. /* Publish the content length back to the request info. */
  10718. conn->request_info.content_length = conn->content_len;
  10719. } else if ((cl = get_header(&conn->request_info, "Transfer-Encoding"))
  10720. != NULL
  10721. && !mg_strcasecmp(cl, "chunked")) {
  10722. conn->is_chunked = 1;
  10723. } else if (!mg_strcasecmp(conn->request_info.request_method, "POST")
  10724. || !mg_strcasecmp(conn->request_info.request_method,
  10725. "PUT")) {
  10726. /* POST or PUT request without content length set */
  10727. conn->content_len = -1;
  10728. } else if (!mg_strncasecmp(conn->request_info.request_method,
  10729. "HTTP/",
  10730. 5)) {
  10731. /* Response without content length set */
  10732. conn->content_len = -1;
  10733. } else {
  10734. /* Other request */
  10735. conn->content_len = 0;
  10736. }
  10737. }
  10738. return 1;
  10739. }
  10740. int
  10741. mg_get_response(struct mg_connection *conn,
  10742. char *ebuf,
  10743. size_t ebuf_len,
  10744. int timeout)
  10745. {
  10746. if (conn) {
  10747. /* Implementation of API function for HTTP clients */
  10748. int err, ret;
  10749. struct mg_context *octx = conn->ctx;
  10750. struct mg_context rctx = *(conn->ctx);
  10751. char txt[32]; /* will not overflow */
  10752. if (timeout >= 0) {
  10753. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  10754. rctx.config[REQUEST_TIMEOUT] = txt;
  10755. set_sock_timeout(conn->client.sock, timeout);
  10756. } else {
  10757. rctx.config[REQUEST_TIMEOUT] = NULL;
  10758. }
  10759. conn->ctx = &rctx;
  10760. ret = getreq(conn, ebuf, ebuf_len, &err);
  10761. conn->ctx = octx;
  10762. /* TODO: 1) uri is deprecated;
  10763. * 2) here, ri.uri is the http response code */
  10764. conn->request_info.uri = conn->request_info.request_uri;
  10765. /* TODO (mid): Define proper return values - maybe return length?
  10766. * For the first test use <0 for error and >0 for OK */
  10767. return (ret == 0) ? -1 : +1;
  10768. }
  10769. return -1;
  10770. }
  10771. struct mg_connection *
  10772. mg_download(const char *host,
  10773. int port,
  10774. int use_ssl,
  10775. char *ebuf,
  10776. size_t ebuf_len,
  10777. const char *fmt,
  10778. ...)
  10779. {
  10780. struct mg_connection *conn;
  10781. va_list ap;
  10782. int i;
  10783. int reqerr;
  10784. va_start(ap, fmt);
  10785. ebuf[0] = '\0';
  10786. /* open a connection */
  10787. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  10788. if (conn != NULL) {
  10789. i = mg_vprintf(conn, fmt, ap);
  10790. if (i <= 0) {
  10791. mg_snprintf(conn,
  10792. NULL, /* No truncation check for ebuf */
  10793. ebuf,
  10794. ebuf_len,
  10795. "%s",
  10796. "Error sending request");
  10797. } else {
  10798. getreq(conn, ebuf, ebuf_len, &reqerr);
  10799. /* TODO: 1) uri is deprecated;
  10800. * 2) here, ri.uri is the http response code */
  10801. conn->request_info.uri = conn->request_info.request_uri;
  10802. }
  10803. }
  10804. /* if an error occured, close the connection */
  10805. if (ebuf[0] != '\0' && conn != NULL) {
  10806. mg_close_connection(conn);
  10807. conn = NULL;
  10808. }
  10809. va_end(ap);
  10810. return conn;
  10811. }
  10812. struct websocket_client_thread_data {
  10813. struct mg_connection *conn;
  10814. mg_websocket_data_handler data_handler;
  10815. mg_websocket_close_handler close_handler;
  10816. void *callback_data;
  10817. };
  10818. #if defined(USE_WEBSOCKET)
  10819. #ifdef _WIN32
  10820. static unsigned __stdcall websocket_client_thread(void *data)
  10821. #else
  10822. static void *
  10823. websocket_client_thread(void *data)
  10824. #endif
  10825. {
  10826. struct websocket_client_thread_data *cdata =
  10827. (struct websocket_client_thread_data *)data;
  10828. mg_set_thread_name("ws-client");
  10829. if (cdata->conn->ctx) {
  10830. if (cdata->conn->ctx->callbacks.init_thread) {
  10831. /* 3 indicates a websocket client thread */
  10832. /* TODO: check if conn->ctx can be set */
  10833. cdata->conn->ctx->callbacks.init_thread(cdata->conn->ctx, 3);
  10834. }
  10835. }
  10836. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  10837. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  10838. if (cdata->close_handler != NULL) {
  10839. cdata->close_handler(cdata->conn, cdata->callback_data);
  10840. }
  10841. mg_free((void *)cdata);
  10842. #ifdef _WIN32
  10843. return 0;
  10844. #else
  10845. return NULL;
  10846. #endif
  10847. }
  10848. #endif
  10849. struct mg_connection *
  10850. mg_connect_websocket_client(const char *host,
  10851. int port,
  10852. int use_ssl,
  10853. char *error_buffer,
  10854. size_t error_buffer_size,
  10855. const char *path,
  10856. const char *origin,
  10857. mg_websocket_data_handler data_func,
  10858. mg_websocket_close_handler close_func,
  10859. void *user_data)
  10860. {
  10861. struct mg_connection *conn = NULL;
  10862. #if defined(USE_WEBSOCKET)
  10863. struct mg_context *newctx = NULL;
  10864. struct websocket_client_thread_data *thread_data;
  10865. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  10866. static const char *handshake_req;
  10867. if (origin != NULL) {
  10868. handshake_req = "GET %s HTTP/1.1\r\n"
  10869. "Host: %s\r\n"
  10870. "Upgrade: websocket\r\n"
  10871. "Connection: Upgrade\r\n"
  10872. "Sec-WebSocket-Key: %s\r\n"
  10873. "Sec-WebSocket-Version: 13\r\n"
  10874. "Origin: %s\r\n"
  10875. "\r\n";
  10876. } else {
  10877. handshake_req = "GET %s HTTP/1.1\r\n"
  10878. "Host: %s\r\n"
  10879. "Upgrade: websocket\r\n"
  10880. "Connection: Upgrade\r\n"
  10881. "Sec-WebSocket-Key: %s\r\n"
  10882. "Sec-WebSocket-Version: 13\r\n"
  10883. "\r\n";
  10884. }
  10885. /* Establish the client connection and request upgrade */
  10886. conn = mg_download(host,
  10887. port,
  10888. use_ssl,
  10889. error_buffer,
  10890. error_buffer_size,
  10891. handshake_req,
  10892. path,
  10893. host,
  10894. magic,
  10895. origin);
  10896. /* Connection object will be null if something goes wrong */
  10897. if (conn == NULL || (strcmp(conn->request_info.request_uri, "101") != 0)) {
  10898. if (!*error_buffer) {
  10899. /* if there is a connection, but it did not return 101,
  10900. * error_buffer is not yet set */
  10901. mg_snprintf(conn,
  10902. NULL, /* No truncation check for ebuf */
  10903. error_buffer,
  10904. error_buffer_size,
  10905. "Unexpected server reply");
  10906. }
  10907. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  10908. if (conn != NULL) {
  10909. mg_free(conn);
  10910. conn = NULL;
  10911. }
  10912. return conn;
  10913. }
  10914. /* For client connections, mg_context is fake. Since we need to set a
  10915. * callback function, we need to create a copy and modify it. */
  10916. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  10917. memcpy(newctx, conn->ctx, sizeof(struct mg_context));
  10918. newctx->user_data = user_data;
  10919. newctx->context_type = 2; /* client context type */
  10920. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  10921. newctx->workerthreadids =
  10922. (pthread_t *)mg_calloc(newctx->cfg_worker_threads, sizeof(pthread_t));
  10923. conn->ctx = newctx;
  10924. thread_data = (struct websocket_client_thread_data *)
  10925. mg_calloc(sizeof(struct websocket_client_thread_data), 1);
  10926. thread_data->conn = conn;
  10927. thread_data->data_handler = data_func;
  10928. thread_data->close_handler = close_func;
  10929. thread_data->callback_data = NULL;
  10930. /* Start a thread to read the websocket client connection
  10931. * This thread will automatically stop when mg_disconnect is
  10932. * called on the client connection */
  10933. if (mg_start_thread_with_id(websocket_client_thread,
  10934. (void *)thread_data,
  10935. newctx->workerthreadids) != 0) {
  10936. mg_free((void *)thread_data);
  10937. mg_free((void *)newctx->workerthreadids);
  10938. mg_free((void *)newctx);
  10939. mg_free((void *)conn);
  10940. conn = NULL;
  10941. DEBUG_TRACE("%s",
  10942. "Websocket client connect thread could not be started\r\n");
  10943. }
  10944. #else
  10945. /* Appease "unused parameter" warnings */
  10946. (void)host;
  10947. (void)port;
  10948. (void)use_ssl;
  10949. (void)error_buffer;
  10950. (void)error_buffer_size;
  10951. (void)path;
  10952. (void)origin;
  10953. (void)user_data;
  10954. (void)data_func;
  10955. (void)close_func;
  10956. #endif
  10957. return conn;
  10958. }
  10959. static void
  10960. process_new_connection(struct mg_connection *conn)
  10961. {
  10962. if (conn && conn->ctx) {
  10963. struct mg_request_info *ri = &conn->request_info;
  10964. int keep_alive_enabled, keep_alive, discard_len;
  10965. char ebuf[100];
  10966. const char *hostend;
  10967. int reqerr, uri_type;
  10968. keep_alive_enabled =
  10969. !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  10970. /* Important: on new connection, reset the receiving buffer. Credit
  10971. * goes to crule42. */
  10972. conn->data_len = 0;
  10973. do {
  10974. if (!getreq(conn, ebuf, sizeof(ebuf), &reqerr)) {
  10975. /* The request sent by the client could not be understood by
  10976. * the server, or it was incomplete or a timeout. Send an
  10977. * error message and close the connection. */
  10978. if (reqerr > 0) {
  10979. /*assert(ebuf[0] != '\0');*/
  10980. send_http_error(conn, reqerr, "%s", ebuf);
  10981. }
  10982. } else if (strcmp(ri->http_version, "1.0")
  10983. && strcmp(ri->http_version, "1.1")) {
  10984. mg_snprintf(conn,
  10985. NULL, /* No truncation check for ebuf */
  10986. ebuf,
  10987. sizeof(ebuf),
  10988. "Bad HTTP version: [%s]",
  10989. ri->http_version);
  10990. send_http_error(conn, 505, "%s", ebuf);
  10991. }
  10992. if (ebuf[0] == '\0') {
  10993. uri_type = get_uri_type(conn->request_info.request_uri);
  10994. switch (uri_type) {
  10995. case 1:
  10996. /* Asterisk */
  10997. conn->request_info.local_uri = NULL;
  10998. break;
  10999. case 2:
  11000. /* relative uri */
  11001. conn->request_info.local_uri =
  11002. conn->request_info.request_uri;
  11003. break;
  11004. case 3:
  11005. case 4:
  11006. /* absolute uri (with/without port) */
  11007. hostend = get_rel_url_at_current_server(
  11008. conn->request_info.request_uri, conn);
  11009. if (hostend) {
  11010. conn->request_info.local_uri = hostend;
  11011. } else {
  11012. conn->request_info.local_uri = NULL;
  11013. }
  11014. break;
  11015. default:
  11016. mg_snprintf(conn,
  11017. NULL, /* No truncation check for ebuf */
  11018. ebuf,
  11019. sizeof(ebuf),
  11020. "Invalid URI: [%s]",
  11021. ri->request_uri);
  11022. send_http_error(conn, 400, "%s", ebuf);
  11023. break;
  11024. }
  11025. /* TODO: cleanup uri, local_uri and request_uri */
  11026. conn->request_info.uri = conn->request_info.local_uri;
  11027. }
  11028. if (ebuf[0] == '\0') {
  11029. if (conn->request_info.local_uri) {
  11030. /* handle request to local server */
  11031. handle_request(conn);
  11032. if (conn->ctx->callbacks.end_request != NULL) {
  11033. conn->ctx->callbacks.end_request(conn,
  11034. conn->status_code);
  11035. }
  11036. log_access(conn);
  11037. } else {
  11038. /* TODO: handle non-local request (PROXY) */
  11039. conn->must_close = 1;
  11040. }
  11041. } else {
  11042. conn->must_close = 1;
  11043. }
  11044. if (ri->remote_user != NULL) {
  11045. mg_free((void *)ri->remote_user);
  11046. /* Important! When having connections with and without auth
  11047. * would cause double free and then crash */
  11048. ri->remote_user = NULL;
  11049. }
  11050. /* NOTE(lsm): order is important here. should_keep_alive() call
  11051. * is
  11052. * using parsed request, which will be invalid after memmove's
  11053. * below.
  11054. * Therefore, memorize should_keep_alive() result now for later
  11055. * use
  11056. * in loop exit condition. */
  11057. keep_alive = conn->ctx->stop_flag == 0 && keep_alive_enabled
  11058. && conn->content_len >= 0 && should_keep_alive(conn);
  11059. /* Discard all buffered data for this request */
  11060. discard_len = ((conn->content_len >= 0) && (conn->request_len > 0)
  11061. && ((conn->request_len + conn->content_len)
  11062. < (int64_t)conn->data_len))
  11063. ? (int)(conn->request_len + conn->content_len)
  11064. : conn->data_len;
  11065. /*assert(discard_len >= 0);*/
  11066. if (discard_len < 0)
  11067. break;
  11068. conn->data_len -= discard_len;
  11069. if (conn->data_len > 0) {
  11070. memmove(conn->buf,
  11071. conn->buf + discard_len,
  11072. (size_t)conn->data_len);
  11073. }
  11074. /* assert(conn->data_len >= 0); */
  11075. /* assert(conn->data_len <= conn->buf_size); */
  11076. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  11077. break;
  11078. }
  11079. } while (keep_alive);
  11080. }
  11081. }
  11082. #if defined(ALTERNATIVE_QUEUE)
  11083. static void
  11084. produce_socket(struct mg_context *ctx, const struct socket *sp)
  11085. {
  11086. unsigned int i;
  11087. for (;;) {
  11088. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  11089. /* find a free worker slot and signal it */
  11090. if (ctx->client_socks[i].in_use == 0) {
  11091. ctx->client_socks[i] = *sp;
  11092. ctx->client_socks[i].in_use = 1;
  11093. event_signal(ctx->client_wait_events[i]);
  11094. return;
  11095. }
  11096. }
  11097. /* queue is full */
  11098. mg_sleep(1);
  11099. }
  11100. }
  11101. static int
  11102. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  11103. {
  11104. ctx->client_socks[thread_index].in_use = 0;
  11105. event_wait(ctx->client_wait_events[thread_index]);
  11106. *sp = ctx->client_socks[thread_index];
  11107. return !ctx->stop_flag;
  11108. }
  11109. #else /* ALTERNATIVE_QUEUE */
  11110. /* Worker threads take accepted socket from the queue */
  11111. static int
  11112. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  11113. {
  11114. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  11115. (void)thread_index;
  11116. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11117. DEBUG_TRACE("%s", "going idle");
  11118. /* If the queue is empty, wait. We're idle at this point. */
  11119. while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
  11120. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  11121. }
  11122. /* If we're stopping, sq_head may be equal to sq_tail. */
  11123. if (ctx->sq_head > ctx->sq_tail) {
  11124. /* Copy socket from the queue and increment tail */
  11125. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  11126. ctx->sq_tail++;
  11127. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  11128. /* Wrap pointers if needed */
  11129. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  11130. ctx->sq_tail -= QUEUE_SIZE(ctx);
  11131. ctx->sq_head -= QUEUE_SIZE(ctx);
  11132. }
  11133. }
  11134. (void)pthread_cond_signal(&ctx->sq_empty);
  11135. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11136. return !ctx->stop_flag;
  11137. #undef QUEUE_SIZE
  11138. }
  11139. /* Master thread adds accepted socket to a queue */
  11140. static void
  11141. produce_socket(struct mg_context *ctx, const struct socket *sp)
  11142. {
  11143. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  11144. if (!ctx) {
  11145. return;
  11146. }
  11147. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11148. /* If the queue is full, wait */
  11149. while (ctx->stop_flag == 0
  11150. && ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx)) {
  11151. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  11152. }
  11153. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  11154. /* Copy socket to the queue and increment head */
  11155. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  11156. ctx->sq_head++;
  11157. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  11158. }
  11159. (void)pthread_cond_signal(&ctx->sq_full);
  11160. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11161. #undef QUEUE_SIZE
  11162. }
  11163. #endif /* ALTERNATIVE_QUEUE */
  11164. struct worker_thread_args {
  11165. struct mg_context *ctx;
  11166. int index;
  11167. };
  11168. static void *
  11169. worker_thread_run(struct worker_thread_args *thread_args)
  11170. {
  11171. struct mg_context *ctx = thread_args->ctx;
  11172. struct mg_connection *conn;
  11173. struct mg_workerTLS tls;
  11174. #if defined(MG_LEGACY_INTERFACE)
  11175. uint32_t addr;
  11176. #endif
  11177. mg_set_thread_name("worker");
  11178. tls.is_master = 0;
  11179. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  11180. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11181. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  11182. #endif
  11183. if (ctx->callbacks.init_thread) {
  11184. /* call init_thread for a worker thread (type 1) */
  11185. ctx->callbacks.init_thread(ctx, 1);
  11186. }
  11187. conn =
  11188. (struct mg_connection *)mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE);
  11189. if (conn == NULL) {
  11190. mg_cry(fc(ctx), "%s", "Cannot create new connection struct, OOM");
  11191. } else {
  11192. pthread_setspecific(sTlsKey, &tls);
  11193. conn->buf_size = MAX_REQUEST_SIZE;
  11194. conn->buf = (char *)(conn + 1);
  11195. conn->ctx = ctx;
  11196. conn->thread_index = thread_args->index;
  11197. conn->request_info.user_data = ctx->user_data;
  11198. /* Allocate a mutex for this connection to allow communication both
  11199. * within the request handler and from elsewhere in the application
  11200. */
  11201. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  11202. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  11203. * signal sq_empty condvar to wake up the master waiting in
  11204. * produce_socket() */
  11205. while (consume_socket(ctx, &conn->client, conn->thread_index)) {
  11206. conn->conn_birth_time = time(NULL);
  11207. /* Fill in IP, port info early so even if SSL setup below fails,
  11208. * error handler would have the corresponding info.
  11209. * Thanks to Johannes Winkelmann for the patch.
  11210. */
  11211. #if defined(USE_IPV6)
  11212. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  11213. conn->request_info.remote_port =
  11214. ntohs(conn->client.rsa.sin6.sin6_port);
  11215. } else
  11216. #endif
  11217. {
  11218. conn->request_info.remote_port =
  11219. ntohs(conn->client.rsa.sin.sin_port);
  11220. }
  11221. sockaddr_to_string(conn->request_info.remote_addr,
  11222. sizeof(conn->request_info.remote_addr),
  11223. &conn->client.rsa);
  11224. #if defined(MG_LEGACY_INTERFACE)
  11225. /* This legacy interface only works for the IPv4 case */
  11226. addr = ntohl(conn->client.rsa.sin.sin_addr.s_addr);
  11227. memcpy(&conn->request_info.remote_ip, &addr, 4);
  11228. #endif
  11229. conn->request_info.is_ssl = conn->client.is_ssl;
  11230. if (conn->client.is_ssl) {
  11231. #ifndef NO_SSL
  11232. /* HTTPS connection */
  11233. if (sslize(conn, conn->ctx->ssl_ctx, SSL_accept)) {
  11234. /* Get SSL client certificate information (if set) */
  11235. ssl_get_client_cert_info(conn);
  11236. /* process HTTPS connection */
  11237. process_new_connection(conn);
  11238. /* Free client certificate info */
  11239. if (conn->request_info.client_cert) {
  11240. mg_free((void*)(conn->request_info.client_cert->subject));
  11241. mg_free((void*)(conn->request_info.client_cert->issuer));
  11242. mg_free((void*)(conn->request_info.client_cert->serial));
  11243. mg_free((void*)(conn->request_info.client_cert->finger));
  11244. conn->request_info.client_cert->subject = 0;
  11245. conn->request_info.client_cert->issuer = 0;
  11246. conn->request_info.client_cert->serial = 0;
  11247. conn->request_info.client_cert->finger = 0;
  11248. mg_free(conn->request_info.client_cert);
  11249. conn->request_info.client_cert = 0;
  11250. }
  11251. }
  11252. #endif
  11253. } else {
  11254. /* process HTTP connection */
  11255. process_new_connection(conn);
  11256. }
  11257. close_connection(conn);
  11258. }
  11259. }
  11260. pthread_setspecific(sTlsKey, NULL);
  11261. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11262. CloseHandle(tls.pthread_cond_helper_mutex);
  11263. #endif
  11264. pthread_mutex_destroy(&conn->mutex);
  11265. mg_free(conn);
  11266. DEBUG_TRACE("%s", "exiting");
  11267. return NULL;
  11268. }
  11269. /* Threads have different return types on Windows and Unix. */
  11270. #ifdef _WIN32
  11271. static unsigned __stdcall worker_thread(void *thread_func_param)
  11272. {
  11273. struct worker_thread_args *pwta =
  11274. (struct worker_thread_args *)thread_func_param;
  11275. worker_thread_run(pwta);
  11276. mg_free(thread_func_param);
  11277. return 0;
  11278. }
  11279. #else
  11280. static void *
  11281. worker_thread(void *thread_func_param)
  11282. {
  11283. struct worker_thread_args *pwta =
  11284. (struct worker_thread_args *)thread_func_param;
  11285. worker_thread_run(pwta);
  11286. mg_free(thread_func_param);
  11287. return NULL;
  11288. }
  11289. #endif /* _WIN32 */
  11290. static void
  11291. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  11292. {
  11293. struct socket so;
  11294. char src_addr[IP_ADDR_STR_LEN];
  11295. socklen_t len = sizeof(so.rsa);
  11296. int on = 1;
  11297. int timeout;
  11298. if (!listener) {
  11299. return;
  11300. }
  11301. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  11302. == INVALID_SOCKET) {
  11303. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  11304. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  11305. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  11306. closesocket(so.sock);
  11307. so.sock = INVALID_SOCKET;
  11308. } else {
  11309. /* Put so socket structure into the queue */
  11310. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  11311. set_close_on_exec(so.sock, fc(ctx));
  11312. so.is_ssl = listener->is_ssl;
  11313. so.ssl_redir = listener->ssl_redir;
  11314. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  11315. mg_cry(fc(ctx),
  11316. "%s: getsockname() failed: %s",
  11317. __func__,
  11318. strerror(ERRNO));
  11319. }
  11320. /* Set TCP keep-alive. This is needed because if HTTP-level
  11321. * keep-alive
  11322. * is enabled, and client resets the connection, server won't get
  11323. * TCP FIN or RST and will keep the connection open forever. With
  11324. * TCP keep-alive, next keep-alive handshake will figure out that
  11325. * the client is down and will close the server end.
  11326. * Thanks to Igor Klopov who suggested the patch. */
  11327. if (setsockopt(so.sock,
  11328. SOL_SOCKET,
  11329. SO_KEEPALIVE,
  11330. (SOCK_OPT_TYPE)&on,
  11331. sizeof(on)) != 0) {
  11332. mg_cry(fc(ctx),
  11333. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  11334. __func__,
  11335. strerror(ERRNO));
  11336. }
  11337. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  11338. * to effectively fill up the underlying IP packet payload and
  11339. * reduce the overhead of sending lots of small buffers. However
  11340. * this hurts the server's throughput (ie. operations per second)
  11341. * when HTTP 1.1 persistent connections are used and the responses
  11342. * are relatively small (eg. less than 1400 bytes).
  11343. */
  11344. if ((ctx != NULL) && (ctx->config[CONFIG_TCP_NODELAY] != NULL)
  11345. && (!strcmp(ctx->config[CONFIG_TCP_NODELAY], "1"))) {
  11346. if (set_tcp_nodelay(so.sock, 1) != 0) {
  11347. mg_cry(fc(ctx),
  11348. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  11349. __func__,
  11350. strerror(ERRNO));
  11351. }
  11352. }
  11353. if (ctx && ctx->config[REQUEST_TIMEOUT]) {
  11354. timeout = atoi(ctx->config[REQUEST_TIMEOUT]);
  11355. } else {
  11356. timeout = -1;
  11357. }
  11358. if (timeout > 0) {
  11359. set_sock_timeout(so.sock, timeout);
  11360. }
  11361. produce_socket(ctx, &so);
  11362. }
  11363. }
  11364. static void
  11365. master_thread_run(void *thread_func_param)
  11366. {
  11367. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  11368. struct mg_workerTLS tls;
  11369. struct pollfd *pfd;
  11370. unsigned int i;
  11371. unsigned int workerthreadcount;
  11372. if (!ctx) {
  11373. return;
  11374. }
  11375. mg_set_thread_name("master");
  11376. /* Increase priority of the master thread */
  11377. #if defined(_WIN32)
  11378. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  11379. #elif defined(USE_MASTER_THREAD_PRIORITY)
  11380. int min_prio = sched_get_priority_min(SCHED_RR);
  11381. int max_prio = sched_get_priority_max(SCHED_RR);
  11382. if ((min_prio >= 0) && (max_prio >= 0)
  11383. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  11384. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  11385. struct sched_param sched_param = {0};
  11386. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  11387. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  11388. }
  11389. #endif
  11390. /* Initialize thread local storage */
  11391. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11392. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  11393. #endif
  11394. tls.is_master = 1;
  11395. pthread_setspecific(sTlsKey, &tls);
  11396. if (ctx->callbacks.init_thread) {
  11397. /* Callback for the master thread (type 0) */
  11398. ctx->callbacks.init_thread(ctx, 0);
  11399. }
  11400. /* Server starts *now* */
  11401. ctx->start_time = time(NULL);
  11402. /* Start the server */
  11403. pfd = ctx->listening_socket_fds;
  11404. while (ctx->stop_flag == 0) {
  11405. for (i = 0; i < ctx->num_listening_sockets; i++) {
  11406. pfd[i].fd = ctx->listening_sockets[i].sock;
  11407. pfd[i].events = POLLIN;
  11408. }
  11409. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  11410. for (i = 0; i < ctx->num_listening_sockets; i++) {
  11411. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  11412. * successful poll, and POLLIN is defined as
  11413. * (POLLRDNORM | POLLRDBAND)
  11414. * Therefore, we're checking pfd[i].revents & POLLIN, not
  11415. * pfd[i].revents == POLLIN. */
  11416. if (ctx->stop_flag == 0 && (pfd[i].revents & POLLIN)) {
  11417. accept_new_connection(&ctx->listening_sockets[i], ctx);
  11418. }
  11419. }
  11420. }
  11421. }
  11422. /* Here stop_flag is 1 - Initiate shutdown. */
  11423. DEBUG_TRACE("%s", "stopping workers");
  11424. /* Stop signal received: somebody called mg_stop. Quit. */
  11425. close_all_listening_sockets(ctx);
  11426. /* Wakeup workers that are waiting for connections to handle. */
  11427. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11428. #if defined(ALTERNATIVE_QUEUE)
  11429. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  11430. event_signal(ctx->client_wait_events[i]);
  11431. /* Since we know all sockets, we can shutdown the connections. */
  11432. if (ctx->client_socks[i].in_use) {
  11433. shutdown(ctx->client_socks[i].sock, SHUTDOWN_BOTH);
  11434. }
  11435. }
  11436. #else
  11437. pthread_cond_broadcast(&ctx->sq_full);
  11438. #endif
  11439. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11440. /* Join all worker threads to avoid leaking threads. */
  11441. workerthreadcount = ctx->cfg_worker_threads;
  11442. for (i = 0; i < workerthreadcount; i++) {
  11443. if (ctx->workerthreadids[i] != 0) {
  11444. mg_join_thread(ctx->workerthreadids[i]);
  11445. }
  11446. }
  11447. #if !defined(NO_SSL)
  11448. if (ctx->ssl_ctx != NULL) {
  11449. uninitialize_ssl(ctx);
  11450. }
  11451. #endif
  11452. DEBUG_TRACE("%s", "exiting");
  11453. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11454. CloseHandle(tls.pthread_cond_helper_mutex);
  11455. #endif
  11456. pthread_setspecific(sTlsKey, NULL);
  11457. /* Signal mg_stop() that we're done.
  11458. * WARNING: This must be the very last thing this
  11459. * thread does, as ctx becomes invalid after this line. */
  11460. ctx->stop_flag = 2;
  11461. }
  11462. /* Threads have different return types on Windows and Unix. */
  11463. #ifdef _WIN32
  11464. static unsigned __stdcall master_thread(void *thread_func_param)
  11465. {
  11466. master_thread_run(thread_func_param);
  11467. return 0;
  11468. }
  11469. #else
  11470. static void *
  11471. master_thread(void *thread_func_param)
  11472. {
  11473. master_thread_run(thread_func_param);
  11474. return NULL;
  11475. }
  11476. #endif /* _WIN32 */
  11477. static void
  11478. free_context(struct mg_context *ctx)
  11479. {
  11480. int i;
  11481. struct mg_handler_info *tmp_rh;
  11482. if (ctx == NULL) {
  11483. return;
  11484. }
  11485. if (ctx->callbacks.exit_context) {
  11486. ctx->callbacks.exit_context(ctx);
  11487. }
  11488. /* All threads exited, no sync is needed. Destroy thread mutex and
  11489. * condvars
  11490. */
  11491. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  11492. #if defined(ALTERNATIVE_QUEUE)
  11493. mg_free(ctx->client_socks);
  11494. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  11495. event_destroy(ctx->client_wait_events[i]);
  11496. }
  11497. mg_free(ctx->client_wait_events);
  11498. #else
  11499. (void)pthread_cond_destroy(&ctx->sq_empty);
  11500. (void)pthread_cond_destroy(&ctx->sq_full);
  11501. #endif
  11502. /* Destroy other context global data structures mutex */
  11503. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  11504. #if defined(USE_TIMERS)
  11505. timers_exit(ctx);
  11506. #endif
  11507. /* Deallocate config parameters */
  11508. for (i = 0; i < NUM_OPTIONS; i++) {
  11509. if (ctx->config[i] != NULL) {
  11510. #if defined(_MSC_VER)
  11511. #pragma warning(suppress : 6001)
  11512. #endif
  11513. mg_free(ctx->config[i]);
  11514. }
  11515. }
  11516. /* Deallocate request handlers */
  11517. while (ctx->handlers) {
  11518. tmp_rh = ctx->handlers;
  11519. ctx->handlers = tmp_rh->next;
  11520. mg_free(tmp_rh->uri);
  11521. mg_free(tmp_rh);
  11522. }
  11523. #ifndef NO_SSL
  11524. /* Deallocate SSL context */
  11525. if (ctx->ssl_ctx != NULL) {
  11526. SSL_CTX_free(ctx->ssl_ctx);
  11527. }
  11528. #endif /* !NO_SSL */
  11529. /* Deallocate worker thread ID array */
  11530. if (ctx->workerthreadids != NULL) {
  11531. mg_free(ctx->workerthreadids);
  11532. }
  11533. /* Deallocate the tls variable */
  11534. if (mg_atomic_dec(&sTlsInit) == 0) {
  11535. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11536. DeleteCriticalSection(&global_log_file_lock);
  11537. #endif /* _WIN32 && !__SYMBIAN32__ */
  11538. #if !defined(_WIN32)
  11539. pthread_mutexattr_destroy(&pthread_mutex_attr);
  11540. #endif
  11541. pthread_key_delete(sTlsKey);
  11542. }
  11543. /* deallocate system name string */
  11544. mg_free(ctx->systemName);
  11545. /* Deallocate context itself */
  11546. mg_free(ctx);
  11547. }
  11548. void
  11549. mg_stop(struct mg_context *ctx)
  11550. {
  11551. pthread_t mt;
  11552. if (!ctx) {
  11553. return;
  11554. }
  11555. /* We don't use a lock here. Calling mg_stop with the same ctx from
  11556. * two threads is not allowed. */
  11557. mt = ctx->masterthreadid;
  11558. if (mt == 0) {
  11559. return;
  11560. }
  11561. ctx->masterthreadid = 0;
  11562. /* Set stop flag, so all threads know they have to exit. */
  11563. ctx->stop_flag = 1;
  11564. /* Wait until everything has stopped. */
  11565. while (ctx->stop_flag != 2) {
  11566. (void)mg_sleep(10);
  11567. }
  11568. mg_join_thread(mt);
  11569. free_context(ctx);
  11570. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11571. (void)WSACleanup();
  11572. #endif /* _WIN32 && !__SYMBIAN32__ */
  11573. }
  11574. static void
  11575. get_system_name(char **sysName)
  11576. {
  11577. #if defined(_WIN32)
  11578. #if !defined(__SYMBIAN32__)
  11579. #if defined(_WIN32_WCE)
  11580. *sysName = mg_strdup("WinCE");
  11581. #else
  11582. char name[128];
  11583. DWORD dwVersion = 0;
  11584. DWORD dwMajorVersion = 0;
  11585. DWORD dwMinorVersion = 0;
  11586. DWORD dwBuild = 0;
  11587. #ifdef _MSC_VER
  11588. #pragma warning(push)
  11589. // GetVersion was declared deprecated
  11590. #pragma warning(disable : 4996)
  11591. #endif
  11592. dwVersion = GetVersion();
  11593. #ifdef _MSC_VER
  11594. #pragma warning(pop)
  11595. #endif
  11596. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  11597. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  11598. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  11599. (void)dwBuild;
  11600. sprintf(name,
  11601. "Windows %u.%u",
  11602. (unsigned)dwMajorVersion,
  11603. (unsigned)dwMinorVersion);
  11604. *sysName = mg_strdup(name);
  11605. #endif
  11606. #else
  11607. *sysName = mg_strdup("Symbian");
  11608. #endif
  11609. #else
  11610. struct utsname name;
  11611. memset(&name, 0, sizeof(name));
  11612. uname(&name);
  11613. *sysName = mg_strdup(name.sysname);
  11614. #endif
  11615. }
  11616. struct mg_context *
  11617. mg_start(const struct mg_callbacks *callbacks,
  11618. void *user_data,
  11619. const char **options)
  11620. {
  11621. struct mg_context *ctx;
  11622. const char *name, *value, *default_value;
  11623. int idx, ok, workerthreadcount;
  11624. unsigned int i;
  11625. void (*exit_callback)(const struct mg_context *ctx) = 0;
  11626. struct mg_workerTLS tls;
  11627. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11628. WSADATA data;
  11629. WSAStartup(MAKEWORD(2, 2), &data);
  11630. #endif /* _WIN32 && !__SYMBIAN32__ */
  11631. /* Allocate context and initialize reasonable general case defaults. */
  11632. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  11633. return NULL;
  11634. }
  11635. /* Random number generator will initialize at the first call */
  11636. ctx->auth_nonce_mask =
  11637. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  11638. if (mg_atomic_inc(&sTlsInit) == 1) {
  11639. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11640. InitializeCriticalSection(&global_log_file_lock);
  11641. #endif /* _WIN32 && !__SYMBIAN32__ */
  11642. #if !defined(_WIN32)
  11643. pthread_mutexattr_init(&pthread_mutex_attr);
  11644. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  11645. #endif
  11646. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  11647. /* Fatal error - abort start. However, this situation should
  11648. * never
  11649. * occur in practice. */
  11650. mg_atomic_dec(&sTlsInit);
  11651. mg_cry(fc(ctx), "Cannot initialize thread local storage");
  11652. mg_free(ctx);
  11653. return NULL;
  11654. }
  11655. } else {
  11656. /* TODO (low): istead of sleeping, check if sTlsKey is already
  11657. * initialized. */
  11658. mg_sleep(1);
  11659. }
  11660. tls.is_master = -1;
  11661. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  11662. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11663. tls.pthread_cond_helper_mutex = NULL;
  11664. #endif
  11665. pthread_setspecific(sTlsKey, &tls);
  11666. #if defined(USE_LUA)
  11667. lua_init_optional_libraries();
  11668. #endif
  11669. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr);
  11670. #if !defined(ALTERNATIVE_QUEUE)
  11671. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  11672. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  11673. #endif
  11674. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr);
  11675. if (!ok) {
  11676. /* Fatal error - abort start. However, this situation should never
  11677. * occur in practice. */
  11678. mg_cry(fc(ctx), "Cannot initialize thread synchronization objects");
  11679. mg_free(ctx);
  11680. pthread_setspecific(sTlsKey, NULL);
  11681. return NULL;
  11682. }
  11683. if (callbacks) {
  11684. ctx->callbacks = *callbacks;
  11685. exit_callback = callbacks->exit_context;
  11686. ctx->callbacks.exit_context = 0;
  11687. }
  11688. ctx->user_data = user_data;
  11689. ctx->handlers = NULL;
  11690. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  11691. ctx->shared_lua_websockets = 0;
  11692. #endif
  11693. while (options && (name = *options++) != NULL) {
  11694. if ((idx = get_option_index(name)) == -1) {
  11695. mg_cry(fc(ctx), "Invalid option: %s", name);
  11696. free_context(ctx);
  11697. pthread_setspecific(sTlsKey, NULL);
  11698. return NULL;
  11699. } else if ((value = *options++) == NULL) {
  11700. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  11701. free_context(ctx);
  11702. pthread_setspecific(sTlsKey, NULL);
  11703. return NULL;
  11704. }
  11705. if (ctx->config[idx] != NULL) {
  11706. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  11707. mg_free(ctx->config[idx]);
  11708. }
  11709. ctx->config[idx] = mg_strdup(value);
  11710. DEBUG_TRACE("[%s] -> [%s]", name, value);
  11711. }
  11712. /* Set default value if needed */
  11713. for (i = 0; config_options[i].name != NULL; i++) {
  11714. default_value = config_options[i].default_value;
  11715. if (ctx->config[i] == NULL && default_value != NULL) {
  11716. ctx->config[i] = mg_strdup(default_value);
  11717. }
  11718. }
  11719. #if defined(NO_FILES)
  11720. if (ctx->config[DOCUMENT_ROOT] != NULL) {
  11721. mg_cry(fc(ctx), "%s", "Document root must not be set");
  11722. free_context(ctx);
  11723. pthread_setspecific(sTlsKey, NULL);
  11724. return NULL;
  11725. }
  11726. #endif
  11727. get_system_name(&ctx->systemName);
  11728. /* NOTE(lsm): order is important here. SSL certificates must
  11729. * be initialized before listening ports. UID must be set last. */
  11730. if (!set_gpass_option(ctx) ||
  11731. #if !defined(NO_SSL)
  11732. !set_ssl_option(ctx) ||
  11733. #endif
  11734. !set_ports_option(ctx) ||
  11735. #if !defined(_WIN32)
  11736. !set_uid_option(ctx) ||
  11737. #endif
  11738. !set_acl_option(ctx)) {
  11739. free_context(ctx);
  11740. pthread_setspecific(sTlsKey, NULL);
  11741. return NULL;
  11742. }
  11743. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  11744. /* Ignore SIGPIPE signal, so if browser cancels the request, it
  11745. * won't kill the whole process. */
  11746. (void)signal(SIGPIPE, SIG_IGN);
  11747. #endif /* !_WIN32 && !__SYMBIAN32__ */
  11748. workerthreadcount = atoi(ctx->config[NUM_THREADS]);
  11749. if (workerthreadcount > MAX_WORKER_THREADS) {
  11750. mg_cry(fc(ctx), "Too many worker threads");
  11751. free_context(ctx);
  11752. pthread_setspecific(sTlsKey, NULL);
  11753. return NULL;
  11754. }
  11755. if (workerthreadcount > 0) {
  11756. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  11757. ctx->workerthreadids =
  11758. (pthread_t *)mg_calloc(ctx->cfg_worker_threads, sizeof(pthread_t));
  11759. if (ctx->workerthreadids == NULL) {
  11760. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  11761. free_context(ctx);
  11762. pthread_setspecific(sTlsKey, NULL);
  11763. return NULL;
  11764. }
  11765. #if defined(ALTERNATIVE_QUEUE)
  11766. ctx->client_wait_events = mg_calloc(sizeof(ctx->client_wait_events[0]),
  11767. ctx->cfg_worker_threads);
  11768. if (ctx->client_wait_events == NULL) {
  11769. mg_cry(fc(ctx), "Not enough memory for worker event array");
  11770. mg_free(ctx->workerthreadids);
  11771. free_context(ctx);
  11772. pthread_setspecific(sTlsKey, NULL);
  11773. return NULL;
  11774. }
  11775. ctx->client_socks =
  11776. mg_calloc(sizeof(ctx->client_socks[0]), ctx->cfg_worker_threads);
  11777. if (ctx->client_wait_events == NULL) {
  11778. mg_cry(fc(ctx), "Not enough memory for worker socket array");
  11779. mg_free(ctx->client_socks);
  11780. mg_free(ctx->workerthreadids);
  11781. free_context(ctx);
  11782. pthread_setspecific(sTlsKey, NULL);
  11783. return NULL;
  11784. }
  11785. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  11786. ctx->client_wait_events[i] = event_create();
  11787. if (ctx->client_wait_events[i] == 0) {
  11788. mg_cry(fc(ctx), "Error creating worker event %i", i);
  11789. /* TODO: clean all and exit */
  11790. }
  11791. }
  11792. #endif
  11793. }
  11794. #if defined(USE_TIMERS)
  11795. if (timers_init(ctx) != 0) {
  11796. mg_cry(fc(ctx), "Error creating timers");
  11797. free_context(ctx);
  11798. pthread_setspecific(sTlsKey, NULL);
  11799. return NULL;
  11800. }
  11801. #endif
  11802. /* Context has been created - init user libraries */
  11803. if (ctx->callbacks.init_context) {
  11804. ctx->callbacks.init_context(ctx);
  11805. }
  11806. ctx->callbacks.exit_context = exit_callback;
  11807. ctx->context_type = 1; /* server context */
  11808. /* Start master (listening) thread */
  11809. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  11810. /* Start worker threads */
  11811. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  11812. struct worker_thread_args *wta =
  11813. mg_malloc(sizeof(struct worker_thread_args));
  11814. if (wta) {
  11815. wta->ctx = ctx;
  11816. wta->index = (int)i;
  11817. }
  11818. if ((wta == NULL)
  11819. || (mg_start_thread_with_id(worker_thread,
  11820. wta,
  11821. &ctx->workerthreadids[i]) != 0)) {
  11822. /* thread was not created */
  11823. if (wta != NULL) {
  11824. mg_free(wta);
  11825. }
  11826. if (i > 0) {
  11827. mg_cry(fc(ctx),
  11828. "Cannot start worker thread %i: error %ld",
  11829. i + 1,
  11830. (long)ERRNO);
  11831. } else {
  11832. mg_cry(fc(ctx),
  11833. "Cannot create threads: error %ld",
  11834. (long)ERRNO);
  11835. free_context(ctx);
  11836. pthread_setspecific(sTlsKey, NULL);
  11837. return NULL;
  11838. }
  11839. break;
  11840. }
  11841. }
  11842. pthread_setspecific(sTlsKey, NULL);
  11843. return ctx;
  11844. }
  11845. /* Feature check API function */
  11846. unsigned
  11847. mg_check_feature(unsigned feature)
  11848. {
  11849. static const unsigned feature_set = 0
  11850. /* Set bits for available features according to API documentation.
  11851. * This bit mask is created at compile time, according to the active
  11852. * preprocessor defines. It is a single const value at runtime. */
  11853. #if !defined(NO_FILES)
  11854. | 0x0001u
  11855. #endif
  11856. #if !defined(NO_SSL)
  11857. | 0x0002u
  11858. #endif
  11859. #if !defined(NO_CGI)
  11860. | 0x0004u
  11861. #endif
  11862. #if defined(USE_IPV6)
  11863. | 0x0008u
  11864. #endif
  11865. #if defined(USE_WEBSOCKET)
  11866. | 0x0010u
  11867. #endif
  11868. #if defined(USE_LUA)
  11869. | 0x0020u
  11870. #endif
  11871. #if defined(USE_DUKTAPE)
  11872. | 0x0040u
  11873. #endif
  11874. #if !defined(NO_CACHING)
  11875. | 0x0080u
  11876. #endif
  11877. /* Set some extra bits not defined in the API documentation.
  11878. * These bits may change without further notice. */
  11879. #if defined(MG_LEGACY_INTERFACE)
  11880. | 0x8000u
  11881. #endif
  11882. #if defined(MEMORY_DEBUGGING)
  11883. | 0x0100u
  11884. #endif
  11885. #if defined(USE_TIMERS)
  11886. | 0x0200u
  11887. #endif
  11888. #if !defined(NO_NONCE_CHECK)
  11889. | 0x0400u
  11890. #endif
  11891. #if !defined(NO_POPEN)
  11892. | 0x0800u
  11893. #endif
  11894. ;
  11895. return (feature & feature_set);
  11896. }