civetweb.c 358 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830
  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, has_body;
  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. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  2481. has_body = (status > 199 && status != 204 && status != 304);
  2482. conn->must_close = 1;
  2483. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  2484. send_no_cache_header(conn);
  2485. if (has_body) {
  2486. mg_printf(conn,
  2487. "%s",
  2488. "Content-Type: text/plain; charset=utf-8\r\n");
  2489. }
  2490. mg_printf(conn,
  2491. "Date: %s\r\n"
  2492. "Connection: close\r\n\r\n",
  2493. date);
  2494. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  2495. if (has_body) {
  2496. mg_printf(conn, "Error %d: %s\n", status, status_text);
  2497. if (fmt != NULL) {
  2498. va_start(ap, fmt);
  2499. mg_vsnprintf(conn, NULL, buf, sizeof(buf), fmt, ap);
  2500. va_end(ap);
  2501. mg_write(conn, buf, strlen(buf));
  2502. DEBUG_TRACE("Error %i - [%s]", status, buf);
  2503. }
  2504. } else {
  2505. /* No body allowed. Close the connection. */
  2506. DEBUG_TRACE("Error %i", status);
  2507. }
  2508. }
  2509. }
  2510. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  2511. /* Create substitutes for POSIX functions in Win32. */
  2512. #if defined(__MINGW32__)
  2513. /* Show no warning in case system functions are not used. */
  2514. #pragma GCC diagnostic push
  2515. #pragma GCC diagnostic ignored "-Wunused-function"
  2516. #endif
  2517. static int
  2518. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  2519. {
  2520. (void)unused;
  2521. *mutex = CreateMutex(NULL, FALSE, NULL);
  2522. return (*mutex == NULL) ? -1 : 0;
  2523. }
  2524. static int
  2525. pthread_mutex_destroy(pthread_mutex_t *mutex)
  2526. {
  2527. return (CloseHandle(*mutex) == 0) ? -1 : 0;
  2528. }
  2529. static int
  2530. pthread_mutex_lock(pthread_mutex_t *mutex)
  2531. {
  2532. return (WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0) ? 0 : -1;
  2533. }
  2534. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  2535. static int
  2536. pthread_mutex_trylock(pthread_mutex_t *mutex)
  2537. {
  2538. switch (WaitForSingleObject(*mutex, 0)) {
  2539. case WAIT_OBJECT_0:
  2540. return 0;
  2541. case WAIT_TIMEOUT:
  2542. return -2; /* EBUSY */
  2543. }
  2544. return -1;
  2545. }
  2546. #endif
  2547. static int
  2548. pthread_mutex_unlock(pthread_mutex_t *mutex)
  2549. {
  2550. return (ReleaseMutex(*mutex) == 0) ? -1 : 0;
  2551. }
  2552. #ifndef WIN_PTHREADS_TIME_H
  2553. static int
  2554. clock_gettime(clockid_t clk_id, struct timespec *tp)
  2555. {
  2556. FILETIME ft;
  2557. ULARGE_INTEGER li;
  2558. BOOL ok = FALSE;
  2559. double d;
  2560. static double perfcnt_per_sec = 0.0;
  2561. if (tp) {
  2562. memset(tp, 0, sizeof(*tp));
  2563. if (clk_id == CLOCK_REALTIME) {
  2564. GetSystemTimeAsFileTime(&ft);
  2565. li.LowPart = ft.dwLowDateTime;
  2566. li.HighPart = ft.dwHighDateTime;
  2567. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  2568. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  2569. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  2570. ok = TRUE;
  2571. } else if (clk_id == CLOCK_MONOTONIC) {
  2572. if (perfcnt_per_sec == 0.0) {
  2573. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  2574. perfcnt_per_sec = 1.0 / li.QuadPart;
  2575. }
  2576. if (perfcnt_per_sec != 0.0) {
  2577. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  2578. d = li.QuadPart * perfcnt_per_sec;
  2579. tp->tv_sec = (time_t)d;
  2580. d -= tp->tv_sec;
  2581. tp->tv_nsec = (long)(d * 1.0E9);
  2582. ok = TRUE;
  2583. }
  2584. }
  2585. }
  2586. return ok ? 0 : -1;
  2587. }
  2588. #endif
  2589. static int
  2590. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  2591. {
  2592. (void)unused;
  2593. InitializeCriticalSection(&cv->threadIdSec);
  2594. cv->waiting_thread = NULL;
  2595. return 0;
  2596. }
  2597. static int
  2598. pthread_cond_timedwait(pthread_cond_t *cv,
  2599. pthread_mutex_t *mutex,
  2600. const struct timespec *abstime)
  2601. {
  2602. struct mg_workerTLS **ptls,
  2603. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2604. int ok;
  2605. struct timespec tsnow;
  2606. int64_t nsnow, nswaitabs, nswaitrel;
  2607. DWORD mswaitrel;
  2608. EnterCriticalSection(&cv->threadIdSec);
  2609. /* Add this thread to cv's waiting list */
  2610. ptls = &cv->waiting_thread;
  2611. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  2612. ;
  2613. tls->next_waiting_thread = NULL;
  2614. *ptls = tls;
  2615. LeaveCriticalSection(&cv->threadIdSec);
  2616. if (abstime) {
  2617. clock_gettime(CLOCK_REALTIME, &tsnow);
  2618. nsnow = (((int64_t)tsnow.tv_sec) * 1000000000) + tsnow.tv_nsec;
  2619. nswaitabs =
  2620. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  2621. nswaitrel = nswaitabs - nsnow;
  2622. if (nswaitrel < 0) {
  2623. nswaitrel = 0;
  2624. }
  2625. mswaitrel = (DWORD)(nswaitrel / 1000000);
  2626. } else {
  2627. mswaitrel = INFINITE;
  2628. }
  2629. pthread_mutex_unlock(mutex);
  2630. ok = (WAIT_OBJECT_0
  2631. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  2632. if (!ok) {
  2633. ok = 1;
  2634. EnterCriticalSection(&cv->threadIdSec);
  2635. ptls = &cv->waiting_thread;
  2636. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  2637. if (*ptls == tls) {
  2638. *ptls = tls->next_waiting_thread;
  2639. ok = 0;
  2640. break;
  2641. }
  2642. }
  2643. LeaveCriticalSection(&cv->threadIdSec);
  2644. if (ok) {
  2645. WaitForSingleObject(tls->pthread_cond_helper_mutex, INFINITE);
  2646. }
  2647. }
  2648. /* This thread has been removed from cv's waiting list */
  2649. pthread_mutex_lock(mutex);
  2650. return ok ? 0 : -1;
  2651. }
  2652. static int
  2653. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  2654. {
  2655. return pthread_cond_timedwait(cv, mutex, NULL);
  2656. }
  2657. static int
  2658. pthread_cond_signal(pthread_cond_t *cv)
  2659. {
  2660. HANDLE wkup = NULL;
  2661. BOOL ok = FALSE;
  2662. EnterCriticalSection(&cv->threadIdSec);
  2663. if (cv->waiting_thread) {
  2664. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  2665. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  2666. ok = SetEvent(wkup);
  2667. assert(ok);
  2668. }
  2669. LeaveCriticalSection(&cv->threadIdSec);
  2670. return ok ? 0 : 1;
  2671. }
  2672. static int
  2673. pthread_cond_broadcast(pthread_cond_t *cv)
  2674. {
  2675. EnterCriticalSection(&cv->threadIdSec);
  2676. while (cv->waiting_thread) {
  2677. pthread_cond_signal(cv);
  2678. }
  2679. LeaveCriticalSection(&cv->threadIdSec);
  2680. return 0;
  2681. }
  2682. static int
  2683. pthread_cond_destroy(pthread_cond_t *cv)
  2684. {
  2685. EnterCriticalSection(&cv->threadIdSec);
  2686. assert(cv->waiting_thread == NULL);
  2687. LeaveCriticalSection(&cv->threadIdSec);
  2688. DeleteCriticalSection(&cv->threadIdSec);
  2689. return 0;
  2690. }
  2691. #ifdef ALTERNATIVE_QUEUE
  2692. static void *
  2693. event_create(void)
  2694. {
  2695. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  2696. }
  2697. static int
  2698. event_wait(void *eventhdl)
  2699. {
  2700. int res = WaitForSingleObject((HANDLE)eventhdl, INFINITE);
  2701. return (res == WAIT_OBJECT_0);
  2702. }
  2703. static int
  2704. event_signal(void *eventhdl)
  2705. {
  2706. return (int)SetEvent((HANDLE)eventhdl);
  2707. }
  2708. static void
  2709. event_destroy(void *eventhdl)
  2710. {
  2711. CloseHandle((HANDLE)eventhdl);
  2712. }
  2713. #endif
  2714. #if defined(__MINGW32__)
  2715. /* Enable unused function warning again */
  2716. #pragma GCC diagnostic pop
  2717. #endif
  2718. /* For Windows, change all slashes to backslashes in path names. */
  2719. static void
  2720. change_slashes_to_backslashes(char *path)
  2721. {
  2722. int i;
  2723. for (i = 0; path[i] != '\0'; i++) {
  2724. if (path[i] == '/') {
  2725. path[i] = '\\';
  2726. }
  2727. /* remove double backslash (check i > 0 to preserve UNC paths,
  2728. * like \\server\file.txt) */
  2729. if ((path[i] == '\\') && (i > 0)) {
  2730. while (path[i + 1] == '\\' || path[i + 1] == '/') {
  2731. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  2732. }
  2733. }
  2734. }
  2735. }
  2736. static int
  2737. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  2738. {
  2739. int diff;
  2740. do {
  2741. diff = tolower(*s1) - tolower(*s2);
  2742. s1++;
  2743. s2++;
  2744. } while (diff == 0 && s1[-1] != '\0');
  2745. return diff;
  2746. }
  2747. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  2748. * wbuf and wbuf_len is a target buffer and its length. */
  2749. static void
  2750. path_to_unicode(const struct mg_connection *conn,
  2751. const char *path,
  2752. wchar_t *wbuf,
  2753. size_t wbuf_len)
  2754. {
  2755. char buf[PATH_MAX], buf2[PATH_MAX];
  2756. wchar_t wbuf2[MAX_PATH + 1];
  2757. DWORD long_len, err;
  2758. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  2759. mg_strlcpy(buf, path, sizeof(buf));
  2760. change_slashes_to_backslashes(buf);
  2761. /* Convert to Unicode and back. If doubly-converted string does not
  2762. * match the original, something is fishy, reject. */
  2763. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  2764. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  2765. WideCharToMultiByte(
  2766. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  2767. if (strcmp(buf, buf2) != 0) {
  2768. wbuf[0] = L'\0';
  2769. }
  2770. /* TODO: Add a configuration to switch between case sensitive and
  2771. * case insensitive URIs for Windows server. */
  2772. /*
  2773. if (conn) {
  2774. if (conn->ctx->config[WINDOWS_CASE_SENSITIVE]) {
  2775. fcompare = wcscmp;
  2776. }
  2777. }
  2778. */
  2779. (void)conn; /* conn is currently unused */
  2780. #if !defined(_WIN32_WCE)
  2781. /* Only accept a full file path, not a Windows short (8.3) path. */
  2782. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  2783. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  2784. if (long_len == 0) {
  2785. err = GetLastError();
  2786. if (err == ERROR_FILE_NOT_FOUND) {
  2787. /* File does not exist. This is not always a problem here. */
  2788. return;
  2789. }
  2790. }
  2791. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  2792. /* Short name is used. */
  2793. wbuf[0] = L'\0';
  2794. }
  2795. #else
  2796. (void)long_len;
  2797. (void)wbuf2;
  2798. (void)err;
  2799. if (strchr(path, '~')) {
  2800. wbuf[0] = L'\0';
  2801. }
  2802. #endif
  2803. }
  2804. /* Windows happily opens files with some garbage at the end of file name.
  2805. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  2806. * "a.cgi", despite one would expect an error back.
  2807. * This function returns non-0 if path ends with some garbage. */
  2808. static int
  2809. path_cannot_disclose_cgi(const char *path)
  2810. {
  2811. static const char *allowed_last_characters = "_-";
  2812. int last = path[strlen(path) - 1];
  2813. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  2814. }
  2815. static int
  2816. mg_stat(struct mg_connection *conn, const char *path, struct file *filep)
  2817. {
  2818. wchar_t wbuf[PATH_MAX];
  2819. WIN32_FILE_ATTRIBUTE_DATA info;
  2820. time_t creation_time;
  2821. if (!filep) {
  2822. return 0;
  2823. }
  2824. memset(filep, 0, sizeof(*filep));
  2825. if (conn && is_file_in_memory(conn, path, filep)) {
  2826. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  2827. * memset */
  2828. filep->last_modified = time(NULL);
  2829. /* last_modified = now ... assumes the file may change during runtime,
  2830. * so every mg_fopen call may return different data */
  2831. /* last_modified = conn->ctx.start_time;
  2832. * May be used it the data does not change during runtime. This allows
  2833. * browser caching. Since we do not know, we have to assume the file
  2834. * in memory may change. */
  2835. return 1;
  2836. }
  2837. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2838. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  2839. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  2840. filep->last_modified =
  2841. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  2842. info.ftLastWriteTime.dwHighDateTime);
  2843. /* On Windows, the file creation time can be higher than the
  2844. * modification time, e.g. when a file is copied.
  2845. * Since the Last-Modified timestamp is used for caching
  2846. * it should be based on the most recent timestamp. */
  2847. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  2848. info.ftCreationTime.dwHighDateTime);
  2849. if (creation_time > filep->last_modified) {
  2850. filep->last_modified = creation_time;
  2851. }
  2852. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  2853. /* If file name is fishy, reset the file structure and return
  2854. * error.
  2855. * Note it is important to reset, not just return the error, cause
  2856. * functions like is_file_opened() check the struct. */
  2857. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  2858. memset(filep, 0, sizeof(*filep));
  2859. return 0;
  2860. }
  2861. return 1;
  2862. }
  2863. return 0;
  2864. }
  2865. static int
  2866. mg_remove(const struct mg_connection *conn, const char *path)
  2867. {
  2868. wchar_t wbuf[PATH_MAX];
  2869. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2870. return DeleteFileW(wbuf) ? 0 : -1;
  2871. }
  2872. static int
  2873. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  2874. {
  2875. wchar_t wbuf[PATH_MAX];
  2876. (void)mode;
  2877. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2878. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  2879. }
  2880. /* Create substitutes for POSIX functions in Win32. */
  2881. #if defined(__MINGW32__)
  2882. /* Show no warning in case system functions are not used. */
  2883. #pragma GCC diagnostic push
  2884. #pragma GCC diagnostic ignored "-Wunused-function"
  2885. #endif
  2886. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  2887. static DIR *
  2888. mg_opendir(const struct mg_connection *conn, const char *name)
  2889. {
  2890. DIR *dir = NULL;
  2891. wchar_t wpath[PATH_MAX];
  2892. DWORD attrs;
  2893. if (name == NULL) {
  2894. SetLastError(ERROR_BAD_ARGUMENTS);
  2895. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  2896. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  2897. } else {
  2898. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  2899. attrs = GetFileAttributesW(wpath);
  2900. if (attrs != 0xFFFFFFFF && ((attrs & FILE_ATTRIBUTE_DIRECTORY)
  2901. == FILE_ATTRIBUTE_DIRECTORY)) {
  2902. (void)wcscat(wpath, L"\\*");
  2903. dir->handle = FindFirstFileW(wpath, &dir->info);
  2904. dir->result.d_name[0] = '\0';
  2905. } else {
  2906. mg_free(dir);
  2907. dir = NULL;
  2908. }
  2909. }
  2910. return dir;
  2911. }
  2912. static int
  2913. mg_closedir(DIR *dir)
  2914. {
  2915. int result = 0;
  2916. if (dir != NULL) {
  2917. if (dir->handle != INVALID_HANDLE_VALUE)
  2918. result = FindClose(dir->handle) ? 0 : -1;
  2919. mg_free(dir);
  2920. } else {
  2921. result = -1;
  2922. SetLastError(ERROR_BAD_ARGUMENTS);
  2923. }
  2924. return result;
  2925. }
  2926. static struct dirent *
  2927. mg_readdir(DIR *dir)
  2928. {
  2929. struct dirent *result = 0;
  2930. if (dir) {
  2931. if (dir->handle != INVALID_HANDLE_VALUE) {
  2932. result = &dir->result;
  2933. (void)WideCharToMultiByte(CP_UTF8,
  2934. 0,
  2935. dir->info.cFileName,
  2936. -1,
  2937. result->d_name,
  2938. sizeof(result->d_name),
  2939. NULL,
  2940. NULL);
  2941. if (!FindNextFileW(dir->handle, &dir->info)) {
  2942. (void)FindClose(dir->handle);
  2943. dir->handle = INVALID_HANDLE_VALUE;
  2944. }
  2945. } else {
  2946. SetLastError(ERROR_FILE_NOT_FOUND);
  2947. }
  2948. } else {
  2949. SetLastError(ERROR_BAD_ARGUMENTS);
  2950. }
  2951. return result;
  2952. }
  2953. #ifndef HAVE_POLL
  2954. static int
  2955. poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  2956. {
  2957. struct timeval tv;
  2958. fd_set set;
  2959. unsigned int i;
  2960. int result;
  2961. SOCKET maxfd = 0;
  2962. memset(&tv, 0, sizeof(tv));
  2963. tv.tv_sec = milliseconds / 1000;
  2964. tv.tv_usec = (milliseconds % 1000) * 1000;
  2965. FD_ZERO(&set);
  2966. for (i = 0; i < n; i++) {
  2967. FD_SET((SOCKET)pfd[i].fd, &set);
  2968. pfd[i].revents = 0;
  2969. if (pfd[i].fd > maxfd) {
  2970. maxfd = pfd[i].fd;
  2971. }
  2972. }
  2973. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  2974. for (i = 0; i < n; i++) {
  2975. if (FD_ISSET(pfd[i].fd, &set)) {
  2976. pfd[i].revents = POLLIN;
  2977. }
  2978. }
  2979. }
  2980. return result;
  2981. }
  2982. #endif /* HAVE_POLL */
  2983. #if defined(__MINGW32__)
  2984. /* Enable unused function warning again */
  2985. #pragma GCC diagnostic pop
  2986. #endif
  2987. static void
  2988. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  2989. {
  2990. (void)conn; /* Unused. */
  2991. #if defined(_WIN32_WCE)
  2992. (void)sock;
  2993. #else
  2994. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  2995. #endif
  2996. }
  2997. int
  2998. mg_start_thread(mg_thread_func_t f, void *p)
  2999. {
  3000. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3001. /* Compile-time option to control stack size, e.g. -DUSE_STACK_SIZE=16384
  3002. */
  3003. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  3004. == ((uintptr_t)(-1L)))
  3005. ? -1
  3006. : 0);
  3007. #else
  3008. return (
  3009. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  3010. ? -1
  3011. : 0);
  3012. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3013. }
  3014. /* Start a thread storing the thread context. */
  3015. static int
  3016. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  3017. void *p,
  3018. pthread_t *threadidptr)
  3019. {
  3020. uintptr_t uip;
  3021. HANDLE threadhandle;
  3022. int result = -1;
  3023. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  3024. threadhandle = (HANDLE)uip;
  3025. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  3026. *threadidptr = threadhandle;
  3027. result = 0;
  3028. }
  3029. return result;
  3030. }
  3031. /* Wait for a thread to finish. */
  3032. static int
  3033. mg_join_thread(pthread_t threadid)
  3034. {
  3035. int result;
  3036. DWORD dwevent;
  3037. result = -1;
  3038. dwevent = WaitForSingleObject(threadid, INFINITE);
  3039. if (dwevent == WAIT_FAILED) {
  3040. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  3041. } else {
  3042. if (dwevent == WAIT_OBJECT_0) {
  3043. CloseHandle(threadid);
  3044. result = 0;
  3045. }
  3046. }
  3047. return result;
  3048. }
  3049. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  3050. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  3051. /* Create substitutes for POSIX functions in Win32. */
  3052. #if defined(__MINGW32__)
  3053. /* Show no warning in case system functions are not used. */
  3054. #pragma GCC diagnostic push
  3055. #pragma GCC diagnostic ignored "-Wunused-function"
  3056. #endif
  3057. static HANDLE
  3058. dlopen(const char *dll_name, int flags)
  3059. {
  3060. wchar_t wbuf[PATH_MAX];
  3061. (void)flags;
  3062. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  3063. return LoadLibraryW(wbuf);
  3064. }
  3065. static int
  3066. dlclose(void *handle)
  3067. {
  3068. int result;
  3069. if (FreeLibrary((HMODULE)handle) != 0) {
  3070. result = 0;
  3071. } else {
  3072. result = -1;
  3073. }
  3074. return result;
  3075. }
  3076. #if defined(__MINGW32__)
  3077. /* Enable unused function warning again */
  3078. #pragma GCC diagnostic pop
  3079. #endif
  3080. #endif
  3081. #if !defined(NO_CGI)
  3082. #define SIGKILL (0)
  3083. static int
  3084. kill(pid_t pid, int sig_num)
  3085. {
  3086. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  3087. (void)CloseHandle((HANDLE)pid);
  3088. return 0;
  3089. }
  3090. static void
  3091. trim_trailing_whitespaces(char *s)
  3092. {
  3093. char *e = s + strlen(s) - 1;
  3094. while (e > s && isspace(*(unsigned char *)e)) {
  3095. *e-- = '\0';
  3096. }
  3097. }
  3098. static pid_t
  3099. spawn_process(struct mg_connection *conn,
  3100. const char *prog,
  3101. char *envblk,
  3102. char *envp[],
  3103. int fdin[2],
  3104. int fdout[2],
  3105. int fderr[2],
  3106. const char *dir)
  3107. {
  3108. HANDLE me;
  3109. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  3110. cmdline[PATH_MAX], buf[PATH_MAX];
  3111. int truncated;
  3112. struct file file = STRUCT_FILE_INITIALIZER;
  3113. STARTUPINFOA si;
  3114. PROCESS_INFORMATION pi = {0};
  3115. (void)envp;
  3116. memset(&si, 0, sizeof(si));
  3117. si.cb = sizeof(si);
  3118. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  3119. si.wShowWindow = SW_HIDE;
  3120. me = GetCurrentProcess();
  3121. DuplicateHandle(me,
  3122. (HANDLE)_get_osfhandle(fdin[0]),
  3123. me,
  3124. &si.hStdInput,
  3125. 0,
  3126. TRUE,
  3127. DUPLICATE_SAME_ACCESS);
  3128. DuplicateHandle(me,
  3129. (HANDLE)_get_osfhandle(fdout[1]),
  3130. me,
  3131. &si.hStdOutput,
  3132. 0,
  3133. TRUE,
  3134. DUPLICATE_SAME_ACCESS);
  3135. DuplicateHandle(me,
  3136. (HANDLE)_get_osfhandle(fderr[1]),
  3137. me,
  3138. &si.hStdError,
  3139. 0,
  3140. TRUE,
  3141. DUPLICATE_SAME_ACCESS);
  3142. /* Mark handles that should not be inherited. See
  3143. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  3144. */
  3145. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  3146. HANDLE_FLAG_INHERIT,
  3147. 0);
  3148. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  3149. HANDLE_FLAG_INHERIT,
  3150. 0);
  3151. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  3152. HANDLE_FLAG_INHERIT,
  3153. 0);
  3154. /* If CGI file is a script, try to read the interpreter line */
  3155. interp = conn->ctx->config[CGI_INTERPRETER];
  3156. if (interp == NULL) {
  3157. buf[0] = buf[1] = '\0';
  3158. /* Read the first line of the script into the buffer */
  3159. mg_snprintf(
  3160. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  3161. if (truncated) {
  3162. pi.hProcess = (pid_t)-1;
  3163. goto spawn_cleanup;
  3164. }
  3165. if (mg_fopen(conn, cmdline, "r", &file)) {
  3166. p = (char *)file.membuf;
  3167. mg_fgets(buf, sizeof(buf), &file, &p);
  3168. mg_fclose(&file);
  3169. buf[sizeof(buf) - 1] = '\0';
  3170. }
  3171. if (buf[0] == '#' && buf[1] == '!') {
  3172. trim_trailing_whitespaces(buf + 2);
  3173. } else {
  3174. buf[2] = '\0';
  3175. }
  3176. interp = buf + 2;
  3177. }
  3178. if (interp[0] != '\0') {
  3179. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  3180. interp = full_interp;
  3181. }
  3182. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  3183. if (interp[0] != '\0') {
  3184. mg_snprintf(conn,
  3185. &truncated,
  3186. cmdline,
  3187. sizeof(cmdline),
  3188. "\"%s\" \"%s\\%s\"",
  3189. interp,
  3190. full_dir,
  3191. prog);
  3192. } else {
  3193. mg_snprintf(conn,
  3194. &truncated,
  3195. cmdline,
  3196. sizeof(cmdline),
  3197. "\"%s\\%s\"",
  3198. full_dir,
  3199. prog);
  3200. }
  3201. if (truncated) {
  3202. pi.hProcess = (pid_t)-1;
  3203. goto spawn_cleanup;
  3204. }
  3205. DEBUG_TRACE("Running [%s]", cmdline);
  3206. if (CreateProcessA(NULL,
  3207. cmdline,
  3208. NULL,
  3209. NULL,
  3210. TRUE,
  3211. CREATE_NEW_PROCESS_GROUP,
  3212. envblk,
  3213. NULL,
  3214. &si,
  3215. &pi) == 0) {
  3216. mg_cry(
  3217. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  3218. pi.hProcess = (pid_t)-1;
  3219. /* goto spawn_cleanup; */
  3220. }
  3221. spawn_cleanup:
  3222. (void)CloseHandle(si.hStdOutput);
  3223. (void)CloseHandle(si.hStdError);
  3224. (void)CloseHandle(si.hStdInput);
  3225. if (pi.hThread != NULL) {
  3226. (void)CloseHandle(pi.hThread);
  3227. }
  3228. return (pid_t)pi.hProcess;
  3229. }
  3230. #endif /* !NO_CGI */
  3231. static int
  3232. set_non_blocking_mode(SOCKET sock)
  3233. {
  3234. unsigned long on = 1;
  3235. return ioctlsocket(sock, (long)FIONBIO, &on);
  3236. }
  3237. #else
  3238. static int
  3239. mg_stat(struct mg_connection *conn, const char *path, struct file *filep)
  3240. {
  3241. struct stat st;
  3242. if (!filep) {
  3243. return 0;
  3244. }
  3245. memset(filep, 0, sizeof(*filep));
  3246. if (conn && is_file_in_memory(conn, path, filep)) {
  3247. return 1;
  3248. }
  3249. if (0 == stat(path, &st)) {
  3250. filep->size = (uint64_t)(st.st_size);
  3251. filep->last_modified = st.st_mtime;
  3252. filep->is_directory = S_ISDIR(st.st_mode);
  3253. return 1;
  3254. }
  3255. return 0;
  3256. }
  3257. static void
  3258. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  3259. {
  3260. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  3261. if (conn) {
  3262. mg_cry(conn,
  3263. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  3264. __func__,
  3265. strerror(ERRNO));
  3266. }
  3267. }
  3268. }
  3269. int
  3270. mg_start_thread(mg_thread_func_t func, void *param)
  3271. {
  3272. pthread_t thread_id;
  3273. pthread_attr_t attr;
  3274. int result;
  3275. (void)pthread_attr_init(&attr);
  3276. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  3277. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3278. /* Compile-time option to control stack size,
  3279. * e.g. -DUSE_STACK_SIZE=16384 */
  3280. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3281. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3282. result = pthread_create(&thread_id, &attr, func, param);
  3283. pthread_attr_destroy(&attr);
  3284. return result;
  3285. }
  3286. /* Start a thread storing the thread context. */
  3287. static int
  3288. mg_start_thread_with_id(mg_thread_func_t func,
  3289. void *param,
  3290. pthread_t *threadidptr)
  3291. {
  3292. pthread_t thread_id;
  3293. pthread_attr_t attr;
  3294. int result;
  3295. (void)pthread_attr_init(&attr);
  3296. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3297. /* Compile-time option to control stack size,
  3298. * e.g. -DUSE_STACK_SIZE=16384 */
  3299. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3300. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  3301. result = pthread_create(&thread_id, &attr, func, param);
  3302. pthread_attr_destroy(&attr);
  3303. if ((result == 0) && (threadidptr != NULL)) {
  3304. *threadidptr = thread_id;
  3305. }
  3306. return result;
  3307. }
  3308. /* Wait for a thread to finish. */
  3309. static int
  3310. mg_join_thread(pthread_t threadid)
  3311. {
  3312. int result;
  3313. result = pthread_join(threadid, NULL);
  3314. return result;
  3315. }
  3316. #ifndef NO_CGI
  3317. static pid_t
  3318. spawn_process(struct mg_connection *conn,
  3319. const char *prog,
  3320. char *envblk,
  3321. char *envp[],
  3322. int fdin[2],
  3323. int fdout[2],
  3324. int fderr[2],
  3325. const char *dir)
  3326. {
  3327. pid_t pid;
  3328. const char *interp;
  3329. (void)envblk;
  3330. if (conn == NULL) {
  3331. return 0;
  3332. }
  3333. if ((pid = fork()) == -1) {
  3334. /* Parent */
  3335. send_http_error(conn,
  3336. 500,
  3337. "Error: Creating CGI process\nfork(): %s",
  3338. strerror(ERRNO));
  3339. } else if (pid == 0) {
  3340. /* Child */
  3341. if (chdir(dir) != 0) {
  3342. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  3343. } else if (dup2(fdin[0], 0) == -1) {
  3344. mg_cry(conn,
  3345. "%s: dup2(%d, 0): %s",
  3346. __func__,
  3347. fdin[0],
  3348. strerror(ERRNO));
  3349. } else if (dup2(fdout[1], 1) == -1) {
  3350. mg_cry(conn,
  3351. "%s: dup2(%d, 1): %s",
  3352. __func__,
  3353. fdout[1],
  3354. strerror(ERRNO));
  3355. } else if (dup2(fderr[1], 2) == -1) {
  3356. mg_cry(conn,
  3357. "%s: dup2(%d, 2): %s",
  3358. __func__,
  3359. fderr[1],
  3360. strerror(ERRNO));
  3361. } else {
  3362. /* Keep stderr and stdout in two different pipes.
  3363. * Stdout will be sent back to the client,
  3364. * stderr should go into a server error log. */
  3365. (void)close(fdin[0]);
  3366. (void)close(fdout[1]);
  3367. (void)close(fderr[1]);
  3368. /* Close write end fdin and read end fdout and fderr */
  3369. (void)close(fdin[1]);
  3370. (void)close(fdout[0]);
  3371. (void)close(fderr[0]);
  3372. /* After exec, all signal handlers are restored to their default
  3373. * values, with one exception of SIGCHLD. According to
  3374. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler will
  3375. * leave unchanged after exec if it was set to be ignored. Restore
  3376. * it to default action. */
  3377. signal(SIGCHLD, SIG_DFL);
  3378. interp = conn->ctx->config[CGI_INTERPRETER];
  3379. if (interp == NULL) {
  3380. (void)execle(prog, prog, NULL, envp);
  3381. mg_cry(conn,
  3382. "%s: execle(%s): %s",
  3383. __func__,
  3384. prog,
  3385. strerror(ERRNO));
  3386. } else {
  3387. (void)execle(interp, interp, prog, NULL, envp);
  3388. mg_cry(conn,
  3389. "%s: execle(%s %s): %s",
  3390. __func__,
  3391. interp,
  3392. prog,
  3393. strerror(ERRNO));
  3394. }
  3395. }
  3396. exit(EXIT_FAILURE);
  3397. }
  3398. return pid;
  3399. }
  3400. #endif /* !NO_CGI */
  3401. static int
  3402. set_non_blocking_mode(SOCKET sock)
  3403. {
  3404. int flags;
  3405. flags = fcntl(sock, F_GETFL, 0);
  3406. (void)fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  3407. return 0;
  3408. }
  3409. #endif /* _WIN32 */
  3410. /* End of initial operating system specific define block. */
  3411. /* Get a random number (independent of C rand function) */
  3412. static uint64_t
  3413. get_random(void)
  3414. {
  3415. static uint64_t lfsr = 0; /* Linear feedback shift register */
  3416. static uint64_t lcg = 0; /* Linear congruential generator */
  3417. struct timespec now;
  3418. memset(&now, 0, sizeof(now));
  3419. clock_gettime(CLOCK_MONOTONIC, &now);
  3420. if (lfsr == 0) {
  3421. /* lfsr will be only 0 if has not been initialized,
  3422. * so this code is called only once. */
  3423. lfsr = (((uint64_t)now.tv_sec) << 21) ^ ((uint64_t)now.tv_nsec)
  3424. ^ ((uint64_t)(ptrdiff_t)&now) ^ (((uint64_t)time(NULL)) << 33);
  3425. lcg = (((uint64_t)now.tv_sec) << 25) + (uint64_t)now.tv_nsec
  3426. + (uint64_t)(ptrdiff_t)&now;
  3427. } else {
  3428. /* Get the next step of both random number generators. */
  3429. lfsr = (lfsr >> 1)
  3430. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  3431. << 63);
  3432. lcg = lcg * 6364136223846793005 + 1442695040888963407;
  3433. }
  3434. /* Combining two pseudo-random number generators and a high resolution part
  3435. * of the current server time will make it hard (impossible?) to guess the
  3436. * next number. */
  3437. return (lfsr ^ lcg ^ (uint64_t)now.tv_nsec);
  3438. }
  3439. /* Write data to the IO channel - opened file descriptor, socket or SSL
  3440. * descriptor. Return number of bytes written. */
  3441. static int
  3442. push(struct mg_context *ctx,
  3443. FILE *fp,
  3444. SOCKET sock,
  3445. SSL *ssl,
  3446. const char *buf,
  3447. int len,
  3448. double timeout)
  3449. {
  3450. struct timespec start, now;
  3451. int n, err;
  3452. #ifdef _WIN32
  3453. typedef int len_t;
  3454. #else
  3455. typedef size_t len_t;
  3456. #endif
  3457. if (timeout > 0) {
  3458. memset(&start, 0, sizeof(start));
  3459. memset(&now, 0, sizeof(now));
  3460. clock_gettime(CLOCK_MONOTONIC, &start);
  3461. }
  3462. if (ctx == NULL) {
  3463. return -1;
  3464. }
  3465. #ifdef NO_SSL
  3466. if (ssl) {
  3467. return -1;
  3468. }
  3469. #endif
  3470. do {
  3471. #ifndef NO_SSL
  3472. if (ssl != NULL) {
  3473. n = SSL_write(ssl, buf, len);
  3474. if (n <= 0) {
  3475. err = SSL_get_error(ssl, n);
  3476. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  3477. err = ERRNO;
  3478. } else if ((err == SSL_ERROR_WANT_READ)
  3479. || (err == SSL_ERROR_WANT_WRITE)) {
  3480. n = 0;
  3481. } else {
  3482. DEBUG_TRACE("SSL_write() failed, error %d", err);
  3483. return -1;
  3484. }
  3485. } else {
  3486. err = 0;
  3487. }
  3488. } else
  3489. #endif
  3490. if (fp != NULL) {
  3491. n = (int)fwrite(buf, 1, (size_t)len, fp);
  3492. if (ferror(fp)) {
  3493. n = -1;
  3494. err = ERRNO;
  3495. } else {
  3496. err = 0;
  3497. }
  3498. } else {
  3499. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  3500. err = (n < 0) ? ERRNO : 0;
  3501. if (n == 0) {
  3502. /* shutdown of the socket at client side */
  3503. return -1;
  3504. }
  3505. }
  3506. if (ctx->stop_flag) {
  3507. return -1;
  3508. }
  3509. if ((n > 0) || (n == 0 && len == 0)) {
  3510. /* some data has been read, or no data was requested */
  3511. return n;
  3512. }
  3513. if (n < 0) {
  3514. /* socket error - check errno */
  3515. DEBUG_TRACE("send() failed, error %d", err);
  3516. /* TODO: error handling depending on the error code.
  3517. * These codes are different between Windows and Linux.
  3518. */
  3519. return -1;
  3520. }
  3521. /* This code is not reached in the moment.
  3522. * ==> Fix the TODOs above first. */
  3523. if (timeout > 0) {
  3524. clock_gettime(CLOCK_MONOTONIC, &now);
  3525. }
  3526. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  3527. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  3528. used */
  3529. return -1;
  3530. }
  3531. static int64_t
  3532. push_all(struct mg_context *ctx,
  3533. FILE *fp,
  3534. SOCKET sock,
  3535. SSL *ssl,
  3536. const char *buf,
  3537. int64_t len)
  3538. {
  3539. double timeout = -1.0;
  3540. int64_t n, nwritten = 0;
  3541. if (ctx == NULL) {
  3542. return -1;
  3543. }
  3544. if (ctx->config[REQUEST_TIMEOUT]) {
  3545. timeout = atoi(ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  3546. }
  3547. while (len > 0 && ctx->stop_flag == 0) {
  3548. n = push(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  3549. if (n < 0) {
  3550. if (nwritten == 0) {
  3551. nwritten = n; /* Propagate the error */
  3552. }
  3553. break;
  3554. } else if (n == 0) {
  3555. break; /* No more data to write */
  3556. } else {
  3557. nwritten += n;
  3558. len -= n;
  3559. }
  3560. }
  3561. return nwritten;
  3562. }
  3563. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  3564. * Return negative value on error, or number of bytes read on success. */
  3565. static int
  3566. pull(FILE *fp, struct mg_connection *conn, char *buf, int len, double timeout)
  3567. {
  3568. int nread, err;
  3569. struct timespec start, now;
  3570. #ifdef _WIN32
  3571. typedef int len_t;
  3572. #else
  3573. typedef size_t len_t;
  3574. #endif
  3575. if (timeout > 0) {
  3576. memset(&start, 0, sizeof(start));
  3577. memset(&now, 0, sizeof(now));
  3578. clock_gettime(CLOCK_MONOTONIC, &start);
  3579. }
  3580. do {
  3581. if (fp != NULL) {
  3582. #if !defined(_WIN32_WCE)
  3583. /* Use read() instead of fread(), because if we're reading from the
  3584. * CGI pipe, fread() may block until IO buffer is filled up. We
  3585. * cannot afford to block and must pass all read bytes immediately
  3586. * to the client. */
  3587. nread = (int)read(fileno(fp), buf, (size_t)len);
  3588. #else
  3589. /* WinCE does not support CGI pipes */
  3590. nread = (int)fread(buf, 1, (size_t)len, fp);
  3591. #endif
  3592. err = (nread < 0) ? ERRNO : 0;
  3593. #ifndef NO_SSL
  3594. } else if (conn->ssl != NULL) {
  3595. nread = SSL_read(conn->ssl, buf, len);
  3596. if (nread <= 0) {
  3597. err = SSL_get_error(conn->ssl, nread);
  3598. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  3599. err = ERRNO;
  3600. } else if ((err == SSL_ERROR_WANT_READ)
  3601. || (err == SSL_ERROR_WANT_WRITE)) {
  3602. nread = 0;
  3603. } else {
  3604. DEBUG_TRACE("SSL_read() failed, error %d", err);
  3605. return -1;
  3606. }
  3607. } else {
  3608. err = 0;
  3609. }
  3610. #endif
  3611. } else {
  3612. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  3613. err = (nread < 0) ? ERRNO : 0;
  3614. if (nread == 0) {
  3615. /* shutdown of the socket at client side */
  3616. return -1;
  3617. }
  3618. }
  3619. if (conn->ctx->stop_flag) {
  3620. return -1;
  3621. }
  3622. if ((nread > 0) || (nread == 0 && len == 0)) {
  3623. /* some data has been read, or no data was requested */
  3624. return nread;
  3625. }
  3626. if (nread < 0) {
  3627. /* socket error - check errno */
  3628. #ifdef _WIN32
  3629. if (err == WSAEWOULDBLOCK) {
  3630. /* standard case if called from close_socket_gracefully */
  3631. return -1;
  3632. } else if (err == WSAETIMEDOUT) {
  3633. /* timeout is handled by the while loop */
  3634. } else {
  3635. DEBUG_TRACE("recv() failed, error %d", err);
  3636. return -1;
  3637. }
  3638. #else
  3639. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  3640. * if the timeout is reached and if the socket was set to non-
  3641. * blocking in close_socket_gracefully, so we can not distinguish
  3642. * here. We have to wait for the timeout in both cases for now.
  3643. */
  3644. if (err == EAGAIN || err == EWOULDBLOCK || err == EINTR) {
  3645. /* EAGAIN/EWOULDBLOCK:
  3646. * standard case if called from close_socket_gracefully
  3647. * => should return -1 */
  3648. /* or timeout occured
  3649. * => the code must stay in the while loop */
  3650. /* EINTR can be generated on a socket with a timeout set even
  3651. * when SA_RESTART is effective for all relevant signals
  3652. * (see signal(7)).
  3653. * => stay in the while loop */
  3654. } else {
  3655. DEBUG_TRACE("recv() failed, error %d", err);
  3656. return -1;
  3657. }
  3658. #endif
  3659. }
  3660. if (timeout > 0) {
  3661. clock_gettime(CLOCK_MONOTONIC, &now);
  3662. }
  3663. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  3664. /* Timeout occured, but no data available. */
  3665. return -1;
  3666. }
  3667. static int
  3668. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  3669. {
  3670. int n, nread = 0;
  3671. double timeout = -1.0;
  3672. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  3673. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  3674. }
  3675. while (len > 0 && conn->ctx->stop_flag == 0) {
  3676. n = pull(fp, conn, buf + nread, len, timeout);
  3677. if (n < 0) {
  3678. if (nread == 0) {
  3679. nread = n; /* Propagate the error */
  3680. }
  3681. break;
  3682. } else if (n == 0) {
  3683. break; /* No more data to read */
  3684. } else {
  3685. conn->consumed_content += n;
  3686. nread += n;
  3687. len -= n;
  3688. }
  3689. }
  3690. return nread;
  3691. }
  3692. static void
  3693. discard_unread_request_data(struct mg_connection *conn)
  3694. {
  3695. char buf[MG_BUF_LEN];
  3696. size_t to_read;
  3697. int nread;
  3698. if (conn == NULL) {
  3699. return;
  3700. }
  3701. to_read = sizeof(buf);
  3702. if (conn->is_chunked) {
  3703. /* Chunked encoding: 1=chunk not read completely, 2=chunk read
  3704. * completely */
  3705. while (conn->is_chunked == 1) {
  3706. nread = mg_read(conn, buf, to_read);
  3707. if (nread <= 0) {
  3708. break;
  3709. }
  3710. }
  3711. } else {
  3712. /* Not chunked: content length is known */
  3713. while (conn->consumed_content < conn->content_len) {
  3714. if (to_read
  3715. > (size_t)(conn->content_len - conn->consumed_content)) {
  3716. to_read = (size_t)(conn->content_len - conn->consumed_content);
  3717. }
  3718. nread = mg_read(conn, buf, to_read);
  3719. if (nread <= 0) {
  3720. break;
  3721. }
  3722. }
  3723. }
  3724. }
  3725. static int
  3726. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  3727. {
  3728. int64_t n, buffered_len, nread;
  3729. int64_t len64 =
  3730. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  3731. * int, we may not read more
  3732. * bytes */
  3733. const char *body;
  3734. if (conn == NULL) {
  3735. return 0;
  3736. }
  3737. /* If Content-Length is not set for a PUT or POST request, read until
  3738. * socket is closed */
  3739. if (conn->consumed_content == 0 && conn->content_len == -1) {
  3740. conn->content_len = INT64_MAX;
  3741. conn->must_close = 1;
  3742. }
  3743. nread = 0;
  3744. if (conn->consumed_content < conn->content_len) {
  3745. /* Adjust number of bytes to read. */
  3746. int64_t left_to_read = conn->content_len - conn->consumed_content;
  3747. if (left_to_read < len64) {
  3748. /* Do not read more than the total content length of the request.
  3749. */
  3750. len64 = left_to_read;
  3751. }
  3752. /* Return buffered data */
  3753. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  3754. - conn->consumed_content;
  3755. if (buffered_len > 0) {
  3756. if (len64 < buffered_len) {
  3757. buffered_len = len64;
  3758. }
  3759. body = conn->buf + conn->request_len + conn->consumed_content;
  3760. memcpy(buf, body, (size_t)buffered_len);
  3761. len64 -= buffered_len;
  3762. conn->consumed_content += buffered_len;
  3763. nread += buffered_len;
  3764. buf = (char *)buf + buffered_len;
  3765. }
  3766. /* We have returned all buffered data. Read new data from the remote
  3767. * socket.
  3768. */
  3769. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  3770. nread += n;
  3771. } else {
  3772. nread = ((nread > 0) ? nread : n);
  3773. }
  3774. }
  3775. return (int)nread;
  3776. }
  3777. static char
  3778. mg_getc(struct mg_connection *conn)
  3779. {
  3780. char c;
  3781. if (conn == NULL) {
  3782. return 0;
  3783. }
  3784. conn->content_len++;
  3785. if (mg_read_inner(conn, &c, 1) <= 0) {
  3786. return (char)0;
  3787. }
  3788. return c;
  3789. }
  3790. int
  3791. mg_read(struct mg_connection *conn, void *buf, size_t len)
  3792. {
  3793. if (len > INT_MAX) {
  3794. len = INT_MAX;
  3795. }
  3796. if (conn == NULL) {
  3797. return 0;
  3798. }
  3799. if (conn->is_chunked) {
  3800. size_t all_read = 0;
  3801. while (len > 0) {
  3802. if (conn->is_chunked == 2) {
  3803. /* No more data left to read */
  3804. return 0;
  3805. }
  3806. if (conn->chunk_remainder) {
  3807. /* copy from the remainder of the last received chunk */
  3808. long read_ret;
  3809. size_t read_now =
  3810. ((conn->chunk_remainder > len) ? (len)
  3811. : (conn->chunk_remainder));
  3812. conn->content_len += (int)read_now;
  3813. read_ret =
  3814. mg_read_inner(conn, (char *)buf + all_read, read_now);
  3815. all_read += (size_t)read_ret;
  3816. conn->chunk_remainder -= read_now;
  3817. len -= read_now;
  3818. if (conn->chunk_remainder == 0) {
  3819. /* the rest of the data in the current chunk has been read
  3820. */
  3821. if ((mg_getc(conn) != '\r') || (mg_getc(conn) != '\n')) {
  3822. /* Protocol violation */
  3823. return -1;
  3824. }
  3825. }
  3826. } else {
  3827. /* fetch a new chunk */
  3828. int i = 0;
  3829. char lenbuf[64];
  3830. char *end = 0;
  3831. unsigned long chunkSize = 0;
  3832. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  3833. lenbuf[i] = mg_getc(conn);
  3834. if (i > 0 && lenbuf[i] == '\r' && lenbuf[i - 1] != '\r') {
  3835. continue;
  3836. }
  3837. if (i > 1 && lenbuf[i] == '\n' && lenbuf[i - 1] == '\r') {
  3838. lenbuf[i + 1] = 0;
  3839. chunkSize = strtoul(lenbuf, &end, 16);
  3840. if (chunkSize == 0) {
  3841. /* regular end of content */
  3842. conn->is_chunked = 2;
  3843. }
  3844. break;
  3845. }
  3846. if (!isalnum(lenbuf[i])) {
  3847. /* illegal character for chunk length */
  3848. return -1;
  3849. }
  3850. }
  3851. if ((end == NULL) || (*end != '\r')) {
  3852. /* chunksize not set correctly */
  3853. return -1;
  3854. }
  3855. if (chunkSize == 0) {
  3856. break;
  3857. }
  3858. conn->chunk_remainder = chunkSize;
  3859. }
  3860. }
  3861. return (int)all_read;
  3862. }
  3863. return mg_read_inner(conn, buf, len);
  3864. }
  3865. int
  3866. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  3867. {
  3868. time_t now;
  3869. int64_t n, total, allowed;
  3870. if (conn == NULL) {
  3871. return 0;
  3872. }
  3873. if (conn->throttle > 0) {
  3874. if ((now = time(NULL)) != conn->last_throttle_time) {
  3875. conn->last_throttle_time = now;
  3876. conn->last_throttle_bytes = 0;
  3877. }
  3878. allowed = conn->throttle - conn->last_throttle_bytes;
  3879. if (allowed > (int64_t)len) {
  3880. allowed = (int64_t)len;
  3881. }
  3882. if ((total = push_all(conn->ctx,
  3883. NULL,
  3884. conn->client.sock,
  3885. conn->ssl,
  3886. (const char *)buf,
  3887. (int64_t)allowed)) == allowed) {
  3888. buf = (const char *)buf + total;
  3889. conn->last_throttle_bytes += total;
  3890. while (total < (int64_t)len && conn->ctx->stop_flag == 0) {
  3891. allowed = (conn->throttle > ((int64_t)len - total))
  3892. ? (int64_t)len - total
  3893. : conn->throttle;
  3894. if ((n = push_all(conn->ctx,
  3895. NULL,
  3896. conn->client.sock,
  3897. conn->ssl,
  3898. (const char *)buf,
  3899. (int64_t)allowed)) != allowed) {
  3900. break;
  3901. }
  3902. sleep(1);
  3903. conn->last_throttle_bytes = allowed;
  3904. conn->last_throttle_time = time(NULL);
  3905. buf = (const char *)buf + n;
  3906. total += n;
  3907. }
  3908. }
  3909. } else {
  3910. total = push_all(conn->ctx,
  3911. NULL,
  3912. conn->client.sock,
  3913. conn->ssl,
  3914. (const char *)buf,
  3915. (int64_t)len);
  3916. }
  3917. return (int)total;
  3918. }
  3919. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  3920. static int
  3921. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  3922. {
  3923. va_list ap_copy;
  3924. size_t size = MG_BUF_LEN / 4;
  3925. int len = -1;
  3926. *buf = NULL;
  3927. while (len < 0) {
  3928. if (*buf) {
  3929. mg_free(*buf);
  3930. }
  3931. size *= 4;
  3932. *buf = (char *)mg_malloc(size);
  3933. if (!*buf) {
  3934. break;
  3935. }
  3936. va_copy(ap_copy, ap);
  3937. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  3938. va_end(ap_copy);
  3939. (*buf)[size - 1] = 0;
  3940. }
  3941. return len;
  3942. }
  3943. /* Print message to buffer. If buffer is large enough to hold the message,
  3944. * return buffer. If buffer is to small, allocate large enough buffer on heap,
  3945. * and return allocated buffer. */
  3946. static int
  3947. alloc_vprintf(char **out_buf,
  3948. char *prealloc_buf,
  3949. size_t prealloc_size,
  3950. const char *fmt,
  3951. va_list ap)
  3952. {
  3953. va_list ap_copy;
  3954. int len;
  3955. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  3956. * buffer is too small. Also, older versions of msvcrt.dll do not have
  3957. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  3958. * Therefore, we make two passes: on first pass, get required message
  3959. * length.
  3960. * On second pass, actually print the message. */
  3961. va_copy(ap_copy, ap);
  3962. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  3963. va_end(ap_copy);
  3964. if (len < 0) {
  3965. /* C runtime is not standard compliant, vsnprintf() returned -1.
  3966. * Switch to alternative code path that uses incremental allocations.
  3967. */
  3968. va_copy(ap_copy, ap);
  3969. len = alloc_vprintf2(out_buf, fmt, ap);
  3970. va_end(ap_copy);
  3971. } else if ((size_t)(len) >= prealloc_size) {
  3972. /* The pre-allocated buffer not large enough. */
  3973. /* Allocate a new buffer. */
  3974. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  3975. if (!*out_buf) {
  3976. /* Allocation failed. Return -1 as "out of memory" error. */
  3977. return -1;
  3978. }
  3979. /* Buffer allocation successful. Store the string there. */
  3980. va_copy(ap_copy, ap);
  3981. IGNORE_UNUSED_RESULT(
  3982. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  3983. va_end(ap_copy);
  3984. } else {
  3985. /* The pre-allocated buffer is large enough.
  3986. * Use it to store the string and return the address. */
  3987. va_copy(ap_copy, ap);
  3988. IGNORE_UNUSED_RESULT(
  3989. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  3990. va_end(ap_copy);
  3991. *out_buf = prealloc_buf;
  3992. }
  3993. return len;
  3994. }
  3995. static int
  3996. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  3997. {
  3998. char mem[MG_BUF_LEN];
  3999. char *buf = NULL;
  4000. int len;
  4001. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  4002. len = mg_write(conn, buf, (size_t)len);
  4003. }
  4004. if (buf != mem && buf != NULL) {
  4005. mg_free(buf);
  4006. }
  4007. return len;
  4008. }
  4009. int
  4010. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  4011. {
  4012. va_list ap;
  4013. int result;
  4014. va_start(ap, fmt);
  4015. result = mg_vprintf(conn, fmt, ap);
  4016. va_end(ap);
  4017. return result;
  4018. }
  4019. int
  4020. mg_url_decode(const char *src,
  4021. int src_len,
  4022. char *dst,
  4023. int dst_len,
  4024. int is_form_url_encoded)
  4025. {
  4026. int i, j, a, b;
  4027. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  4028. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  4029. if (i < src_len - 2 && src[i] == '%'
  4030. && isxdigit(*(const unsigned char *)(src + i + 1))
  4031. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  4032. a = tolower(*(const unsigned char *)(src + i + 1));
  4033. b = tolower(*(const unsigned char *)(src + i + 2));
  4034. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  4035. i += 2;
  4036. } else if (is_form_url_encoded && src[i] == '+') {
  4037. dst[j] = ' ';
  4038. } else {
  4039. dst[j] = src[i];
  4040. }
  4041. }
  4042. dst[j] = '\0'; /* Null-terminate the destination */
  4043. return (i >= src_len) ? j : -1;
  4044. }
  4045. int
  4046. mg_get_var(const char *data,
  4047. size_t data_len,
  4048. const char *name,
  4049. char *dst,
  4050. size_t dst_len)
  4051. {
  4052. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  4053. }
  4054. int
  4055. mg_get_var2(const char *data,
  4056. size_t data_len,
  4057. const char *name,
  4058. char *dst,
  4059. size_t dst_len,
  4060. size_t occurrence)
  4061. {
  4062. const char *p, *e, *s;
  4063. size_t name_len;
  4064. int len;
  4065. if (dst == NULL || dst_len == 0) {
  4066. len = -2;
  4067. } else if (data == NULL || name == NULL || data_len == 0) {
  4068. len = -1;
  4069. dst[0] = '\0';
  4070. } else {
  4071. name_len = strlen(name);
  4072. e = data + data_len;
  4073. len = -1;
  4074. dst[0] = '\0';
  4075. /* data is "var1=val1&var2=val2...". Find variable first */
  4076. for (p = data; p + name_len < e; p++) {
  4077. if ((p == data || p[-1] == '&') && p[name_len] == '='
  4078. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  4079. /* Point p to variable value */
  4080. p += name_len + 1;
  4081. /* Point s to the end of the value */
  4082. s = (const char *)memchr(p, '&', (size_t)(e - p));
  4083. if (s == NULL) {
  4084. s = e;
  4085. }
  4086. /* assert(s >= p); */
  4087. if (s < p) {
  4088. return -3;
  4089. }
  4090. /* Decode variable into destination buffer */
  4091. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  4092. /* Redirect error code from -1 to -2 (destination buffer too
  4093. * small). */
  4094. if (len == -1) {
  4095. len = -2;
  4096. }
  4097. break;
  4098. }
  4099. }
  4100. }
  4101. return len;
  4102. }
  4103. /* HCP24: some changes to compare hole var_name */
  4104. int
  4105. mg_get_cookie(const char *cookie_header,
  4106. const char *var_name,
  4107. char *dst,
  4108. size_t dst_size)
  4109. {
  4110. const char *s, *p, *end;
  4111. int name_len, len = -1;
  4112. if (dst == NULL || dst_size == 0) {
  4113. return -2;
  4114. }
  4115. dst[0] = '\0';
  4116. if (var_name == NULL || (s = cookie_header) == NULL) {
  4117. return -1;
  4118. }
  4119. name_len = (int)strlen(var_name);
  4120. end = s + strlen(s);
  4121. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  4122. if (s[name_len] == '=') {
  4123. /* HCP24: now check is it a substring or a full cookie name */
  4124. if ((s == cookie_header) || (s[-1] == ' ')) {
  4125. s += name_len + 1;
  4126. if ((p = strchr(s, ' ')) == NULL) {
  4127. p = end;
  4128. }
  4129. if (p[-1] == ';') {
  4130. p--;
  4131. }
  4132. if (*s == '"' && p[-1] == '"' && p > s + 1) {
  4133. s++;
  4134. p--;
  4135. }
  4136. if ((size_t)(p - s) < dst_size) {
  4137. len = (int)(p - s);
  4138. mg_strlcpy(dst, s, (size_t)len + 1);
  4139. } else {
  4140. len = -3;
  4141. }
  4142. break;
  4143. }
  4144. }
  4145. }
  4146. return len;
  4147. }
  4148. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  4149. static void
  4150. base64_encode(const unsigned char *src, int src_len, char *dst)
  4151. {
  4152. static const char *b64 =
  4153. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  4154. int i, j, a, b, c;
  4155. for (i = j = 0; i < src_len; i += 3) {
  4156. a = src[i];
  4157. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  4158. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  4159. dst[j++] = b64[a >> 2];
  4160. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  4161. if (i + 1 < src_len) {
  4162. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  4163. }
  4164. if (i + 2 < src_len) {
  4165. dst[j++] = b64[c & 63];
  4166. }
  4167. }
  4168. while (j % 4 != 0) {
  4169. dst[j++] = '=';
  4170. }
  4171. dst[j++] = '\0';
  4172. }
  4173. #endif
  4174. #if defined(USE_LUA)
  4175. static unsigned char
  4176. b64reverse(char letter)
  4177. {
  4178. if (letter >= 'A' && letter <= 'Z') {
  4179. return letter - 'A';
  4180. }
  4181. if (letter >= 'a' && letter <= 'z') {
  4182. return letter - 'a' + 26;
  4183. }
  4184. if (letter >= '0' && letter <= '9') {
  4185. return letter - '0' + 52;
  4186. }
  4187. if (letter == '+') {
  4188. return 62;
  4189. }
  4190. if (letter == '/') {
  4191. return 63;
  4192. }
  4193. if (letter == '=') {
  4194. return 255; /* normal end */
  4195. }
  4196. return 254; /* error */
  4197. }
  4198. static int
  4199. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  4200. {
  4201. int i;
  4202. unsigned char a, b, c, d;
  4203. *dst_len = 0;
  4204. for (i = 0; i < src_len; i += 4) {
  4205. a = b64reverse(src[i]);
  4206. if (a >= 254) {
  4207. return i;
  4208. }
  4209. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  4210. if (b >= 254) {
  4211. return i + 1;
  4212. }
  4213. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  4214. if (c == 254) {
  4215. return i + 2;
  4216. }
  4217. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  4218. if (d == 254) {
  4219. return i + 3;
  4220. }
  4221. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  4222. if (c != 255) {
  4223. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  4224. if (d != 255) {
  4225. dst[(*dst_len)++] = (c << 6) + d;
  4226. }
  4227. }
  4228. }
  4229. return -1;
  4230. }
  4231. #endif
  4232. static int
  4233. is_put_or_delete_method(const struct mg_connection *conn)
  4234. {
  4235. if (conn) {
  4236. const char *s = conn->request_info.request_method;
  4237. return s != NULL && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  4238. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  4239. }
  4240. return 0;
  4241. }
  4242. static void
  4243. interpret_uri(struct mg_connection *conn, /* in: request (must be valid) */
  4244. char *filename, /* out: filename */
  4245. size_t filename_buf_len, /* in: size of filename buffer */
  4246. struct file *filep, /* out: file structure */
  4247. int *is_found, /* out: file is found (directly) */
  4248. int *is_script_resource, /* out: handled by a script? */
  4249. int *is_websocket_request, /* out: websocket connetion? */
  4250. int *is_put_or_delete_request /* out: put/delete a file? */
  4251. )
  4252. {
  4253. /* TODO (high): Restructure this function */
  4254. #if !defined(NO_FILES)
  4255. const char *uri = conn->request_info.local_uri;
  4256. const char *root = conn->ctx->config[DOCUMENT_ROOT];
  4257. const char *rewrite;
  4258. struct vec a, b;
  4259. int match_len;
  4260. char gz_path[PATH_MAX];
  4261. char const *accept_encoding;
  4262. int truncated;
  4263. #if !defined(NO_CGI) || defined(USE_LUA)
  4264. char *p;
  4265. #endif
  4266. #else
  4267. (void)filename_buf_len; /* unused if NO_FILES is defined */
  4268. #endif
  4269. memset(filep, 0, sizeof(*filep));
  4270. *filename = 0;
  4271. *is_found = 0;
  4272. *is_script_resource = 0;
  4273. *is_put_or_delete_request = is_put_or_delete_method(conn);
  4274. #if defined(USE_WEBSOCKET)
  4275. *is_websocket_request = is_websocket_protocol(conn);
  4276. #if !defined(NO_FILES)
  4277. if (*is_websocket_request && conn->ctx->config[WEBSOCKET_ROOT]) {
  4278. root = conn->ctx->config[WEBSOCKET_ROOT];
  4279. }
  4280. #endif /* !NO_FILES */
  4281. #else /* USE_WEBSOCKET */
  4282. *is_websocket_request = 0;
  4283. #endif /* USE_WEBSOCKET */
  4284. #if !defined(NO_FILES)
  4285. /* Note that root == NULL is a regular use case here. This occurs,
  4286. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  4287. * config is not required. */
  4288. if (root == NULL) {
  4289. /* all file related outputs have already been set to 0, just return
  4290. */
  4291. return;
  4292. }
  4293. /* Using buf_len - 1 because memmove() for PATH_INFO may shift part
  4294. * of the path one byte on the right.
  4295. * If document_root is NULL, leave the file empty. */
  4296. mg_snprintf(
  4297. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  4298. if (truncated) {
  4299. goto interpret_cleanup;
  4300. }
  4301. rewrite = conn->ctx->config[REWRITE];
  4302. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  4303. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  4304. mg_snprintf(conn,
  4305. &truncated,
  4306. filename,
  4307. filename_buf_len - 1,
  4308. "%.*s%s",
  4309. (int)b.len,
  4310. b.ptr,
  4311. uri + match_len);
  4312. break;
  4313. }
  4314. }
  4315. if (truncated) {
  4316. goto interpret_cleanup;
  4317. }
  4318. /* Local file path and name, corresponding to requested URI
  4319. * is now stored in "filename" variable. */
  4320. if (mg_stat(conn, filename, filep)) {
  4321. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  4322. /* File exists. Check if it is a script type. */
  4323. if (0
  4324. #if !defined(NO_CGI)
  4325. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  4326. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4327. filename) > 0
  4328. #endif
  4329. #if defined(USE_LUA)
  4330. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  4331. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  4332. filename) > 0
  4333. #endif
  4334. #if defined(USE_DUKTAPE)
  4335. || match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  4336. strlen(
  4337. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  4338. filename) > 0
  4339. #endif
  4340. ) {
  4341. /* The request addresses a CGI script or a Lua script. The URI
  4342. * corresponds to the script itself (like /path/script.cgi),
  4343. * and there is no additional resource path
  4344. * (like /path/script.cgi/something).
  4345. * Requests that modify (replace or delete) a resource, like
  4346. * PUT and DELETE requests, should replace/delete the script
  4347. * file.
  4348. * Requests that read or write from/to a resource, like GET and
  4349. * POST requests, should call the script and return the
  4350. * generated response. */
  4351. *is_script_resource = !*is_put_or_delete_request;
  4352. }
  4353. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  4354. *is_found = 1;
  4355. return;
  4356. }
  4357. /* If we can't find the actual file, look for the file
  4358. * with the same name but a .gz extension. If we find it,
  4359. * use that and set the gzipped flag in the file struct
  4360. * to indicate that the response need to have the content-
  4361. * encoding: gzip header.
  4362. * We can only do this if the browser declares support. */
  4363. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  4364. if (strstr(accept_encoding, "gzip") != NULL) {
  4365. mg_snprintf(
  4366. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  4367. if (truncated) {
  4368. goto interpret_cleanup;
  4369. }
  4370. if (mg_stat(conn, gz_path, filep)) {
  4371. if (filep) {
  4372. filep->gzipped = 1;
  4373. *is_found = 1;
  4374. }
  4375. /* Currently gz files can not be scripts. */
  4376. return;
  4377. }
  4378. }
  4379. }
  4380. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  4381. /* Support PATH_INFO for CGI scripts. */
  4382. for (p = filename + strlen(filename); p > filename + 1; p--) {
  4383. if (*p == '/') {
  4384. *p = '\0';
  4385. if ((0
  4386. #if !defined(NO_CGI)
  4387. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  4388. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4389. filename) > 0
  4390. #endif
  4391. #if defined(USE_LUA)
  4392. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  4393. strlen(
  4394. conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  4395. filename) > 0
  4396. #endif
  4397. #if defined(USE_DUKTAPE)
  4398. || match_prefix(
  4399. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  4400. strlen(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  4401. filename) > 0
  4402. #endif
  4403. ) && mg_stat(conn, filename, filep)) {
  4404. /* Shift PATH_INFO block one character right, e.g.
  4405. * "/x.cgi/foo/bar\x00" => "/x.cgi\x00/foo/bar\x00"
  4406. * conn->path_info is pointing to the local variable "path"
  4407. * declared in handle_request(), so PATH_INFO is not valid
  4408. * after handle_request returns. */
  4409. conn->path_info = p + 1;
  4410. memmove(p + 2, p + 1, strlen(p + 1) + 1); /* +1 is for
  4411. * trailing \0 */
  4412. p[1] = '/';
  4413. *is_script_resource = 1;
  4414. break;
  4415. } else {
  4416. *p = '/';
  4417. }
  4418. }
  4419. }
  4420. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  4421. #endif /* !defined(NO_FILES) */
  4422. return;
  4423. #if !defined(NO_FILES)
  4424. /* Reset all outputs */
  4425. interpret_cleanup:
  4426. memset(filep, 0, sizeof(*filep));
  4427. *filename = 0;
  4428. *is_found = 0;
  4429. *is_script_resource = 0;
  4430. *is_websocket_request = 0;
  4431. *is_put_or_delete_request = 0;
  4432. #endif /* !defined(NO_FILES) */
  4433. }
  4434. /* Check whether full request is buffered. Return:
  4435. * -1 if request is malformed
  4436. * 0 if request is not yet fully buffered
  4437. * >0 actual request length, including last \r\n\r\n */
  4438. static int
  4439. get_request_len(const char *buf, int buflen)
  4440. {
  4441. const char *s, *e;
  4442. int len = 0;
  4443. for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
  4444. /* Control characters are not allowed but >=128 is. */
  4445. if (!isprint(*(const unsigned char *)s) && *s != '\r' && *s != '\n'
  4446. && *(const unsigned char *)s < 128) {
  4447. len = -1;
  4448. break; /* [i_a] abort scan as soon as one malformed character is
  4449. * found; */
  4450. /* don't let subsequent \r\n\r\n win us over anyhow */
  4451. } else if (s[0] == '\n' && s[1] == '\n') {
  4452. len = (int)(s - buf) + 2;
  4453. } else if (s[0] == '\n' && &s[1] < e && s[1] == '\r' && s[2] == '\n') {
  4454. len = (int)(s - buf) + 3;
  4455. }
  4456. return len;
  4457. }
  4458. #if !defined(NO_CACHING)
  4459. /* Convert month to the month number. Return -1 on error, or month number */
  4460. static int
  4461. get_month_index(const char *s)
  4462. {
  4463. size_t i;
  4464. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  4465. if (!strcmp(s, month_names[i])) {
  4466. return (int)i;
  4467. }
  4468. }
  4469. return -1;
  4470. }
  4471. /* Parse UTC date-time string, and return the corresponding time_t value. */
  4472. static time_t
  4473. parse_date_string(const char *datetime)
  4474. {
  4475. char month_str[32] = {0};
  4476. int second, minute, hour, day, month, year;
  4477. time_t result = (time_t)0;
  4478. struct tm tm;
  4479. if ((sscanf(datetime,
  4480. "%d/%3s/%d %d:%d:%d",
  4481. &day,
  4482. month_str,
  4483. &year,
  4484. &hour,
  4485. &minute,
  4486. &second) == 6) || (sscanf(datetime,
  4487. "%d %3s %d %d:%d:%d",
  4488. &day,
  4489. month_str,
  4490. &year,
  4491. &hour,
  4492. &minute,
  4493. &second) == 6)
  4494. || (sscanf(datetime,
  4495. "%*3s, %d %3s %d %d:%d:%d",
  4496. &day,
  4497. month_str,
  4498. &year,
  4499. &hour,
  4500. &minute,
  4501. &second) == 6) || (sscanf(datetime,
  4502. "%d-%3s-%d %d:%d:%d",
  4503. &day,
  4504. month_str,
  4505. &year,
  4506. &hour,
  4507. &minute,
  4508. &second) == 6)) {
  4509. month = get_month_index(month_str);
  4510. if ((month >= 0) && (year >= 1970)) {
  4511. memset(&tm, 0, sizeof(tm));
  4512. tm.tm_year = year - 1900;
  4513. tm.tm_mon = month;
  4514. tm.tm_mday = day;
  4515. tm.tm_hour = hour;
  4516. tm.tm_min = minute;
  4517. tm.tm_sec = second;
  4518. result = timegm(&tm);
  4519. }
  4520. }
  4521. return result;
  4522. }
  4523. #endif /* !NO_CACHING */
  4524. /* Protect against directory disclosure attack by removing '..',
  4525. * excessive '/' and '\' characters */
  4526. static void
  4527. remove_double_dots_and_double_slashes(char *s)
  4528. {
  4529. char *p = s;
  4530. while ((s[0] == '.') && (s[1] == '.')) {
  4531. s++;
  4532. }
  4533. while (*s != '\0') {
  4534. *p++ = *s++;
  4535. if (s[-1] == '/' || s[-1] == '\\') {
  4536. /* Skip all following slashes, backslashes and double-dots */
  4537. while (s[0] != '\0') {
  4538. if (s[0] == '/' || s[0] == '\\') {
  4539. s++;
  4540. } else if (s[0] == '.' && s[1] == '.') {
  4541. s += 2;
  4542. } else {
  4543. break;
  4544. }
  4545. }
  4546. }
  4547. }
  4548. *p = '\0';
  4549. }
  4550. static const struct {
  4551. const char *extension;
  4552. size_t ext_len;
  4553. const char *mime_type;
  4554. } builtin_mime_types[] = {
  4555. /* IANA registered MIME types (http://www.iana.org/assignments/media-types)
  4556. * application types */
  4557. {".doc", 4, "application/msword"},
  4558. {".eps", 4, "application/postscript"},
  4559. {".exe", 4, "application/octet-stream"},
  4560. {".js", 3, "application/javascript"},
  4561. {".json", 5, "application/json"},
  4562. {".pdf", 4, "application/pdf"},
  4563. {".ps", 3, "application/postscript"},
  4564. {".rtf", 4, "application/rtf"},
  4565. {".xhtml", 6, "application/xhtml+xml"},
  4566. {".xsl", 4, "application/xml"},
  4567. {".xslt", 5, "application/xml"},
  4568. /* fonts */
  4569. {".ttf", 4, "application/font-sfnt"},
  4570. {".cff", 4, "application/font-sfnt"},
  4571. {".otf", 4, "application/font-sfnt"},
  4572. {".aat", 4, "application/font-sfnt"},
  4573. {".sil", 4, "application/font-sfnt"},
  4574. {".pfr", 4, "application/font-tdpfr"},
  4575. {".woff", 5, "application/font-woff"},
  4576. /* audio */
  4577. {".mp3", 4, "audio/mpeg"},
  4578. {".oga", 4, "audio/ogg"},
  4579. {".ogg", 4, "audio/ogg"},
  4580. /* image */
  4581. {".gif", 4, "image/gif"},
  4582. {".ief", 4, "image/ief"},
  4583. {".jpeg", 5, "image/jpeg"},
  4584. {".jpg", 4, "image/jpeg"},
  4585. {".jpm", 4, "image/jpm"},
  4586. {".jpx", 4, "image/jpx"},
  4587. {".png", 4, "image/png"},
  4588. {".svg", 4, "image/svg+xml"},
  4589. {".tif", 4, "image/tiff"},
  4590. {".tiff", 5, "image/tiff"},
  4591. /* model */
  4592. {".wrl", 4, "model/vrml"},
  4593. /* text */
  4594. {".css", 4, "text/css"},
  4595. {".csv", 4, "text/csv"},
  4596. {".htm", 4, "text/html"},
  4597. {".html", 5, "text/html"},
  4598. {".sgm", 4, "text/sgml"},
  4599. {".shtm", 5, "text/html"},
  4600. {".shtml", 6, "text/html"},
  4601. {".txt", 4, "text/plain"},
  4602. {".xml", 4, "text/xml"},
  4603. /* video */
  4604. {".mov", 4, "video/quicktime"},
  4605. {".mp4", 4, "video/mp4"},
  4606. {".mpeg", 5, "video/mpeg"},
  4607. {".mpg", 4, "video/mpeg"},
  4608. {".ogv", 4, "video/ogg"},
  4609. {".qt", 3, "video/quicktime"},
  4610. /* not registered types
  4611. * (http://reference.sitepoint.com/html/mime-types-full,
  4612. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  4613. {".arj", 4, "application/x-arj-compressed"},
  4614. {".gz", 3, "application/x-gunzip"},
  4615. {".rar", 4, "application/x-arj-compressed"},
  4616. {".swf", 4, "application/x-shockwave-flash"},
  4617. {".tar", 4, "application/x-tar"},
  4618. {".tgz", 4, "application/x-tar-gz"},
  4619. {".torrent", 8, "application/x-bittorrent"},
  4620. {".ppt", 4, "application/x-mspowerpoint"},
  4621. {".xls", 4, "application/x-msexcel"},
  4622. {".zip", 4, "application/x-zip-compressed"},
  4623. {".aac",
  4624. 4,
  4625. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  4626. {".aif", 4, "audio/x-aif"},
  4627. {".m3u", 4, "audio/x-mpegurl"},
  4628. {".mid", 4, "audio/x-midi"},
  4629. {".ra", 3, "audio/x-pn-realaudio"},
  4630. {".ram", 4, "audio/x-pn-realaudio"},
  4631. {".wav", 4, "audio/x-wav"},
  4632. {".bmp", 4, "image/bmp"},
  4633. {".ico", 4, "image/x-icon"},
  4634. {".pct", 4, "image/x-pct"},
  4635. {".pict", 5, "image/pict"},
  4636. {".rgb", 4, "image/x-rgb"},
  4637. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  4638. {".asf", 4, "video/x-ms-asf"},
  4639. {".avi", 4, "video/x-msvideo"},
  4640. {".m4v", 4, "video/x-m4v"},
  4641. {NULL, 0, NULL}};
  4642. const char *
  4643. mg_get_builtin_mime_type(const char *path)
  4644. {
  4645. const char *ext;
  4646. size_t i, path_len;
  4647. path_len = strlen(path);
  4648. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  4649. ext = path + (path_len - builtin_mime_types[i].ext_len);
  4650. if (path_len > builtin_mime_types[i].ext_len
  4651. && mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {
  4652. return builtin_mime_types[i].mime_type;
  4653. }
  4654. }
  4655. return "text/plain";
  4656. }
  4657. /* Look at the "path" extension and figure what mime type it has.
  4658. * Store mime type in the vector. */
  4659. static void
  4660. get_mime_type(struct mg_context *ctx, const char *path, struct vec *vec)
  4661. {
  4662. struct vec ext_vec, mime_vec;
  4663. const char *list, *ext;
  4664. size_t path_len;
  4665. path_len = strlen(path);
  4666. if (ctx == NULL || vec == NULL) {
  4667. return;
  4668. }
  4669. /* Scan user-defined mime types first, in case user wants to
  4670. * override default mime types. */
  4671. list = ctx->config[EXTRA_MIME_TYPES];
  4672. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  4673. /* ext now points to the path suffix */
  4674. ext = path + path_len - ext_vec.len;
  4675. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  4676. *vec = mime_vec;
  4677. return;
  4678. }
  4679. }
  4680. vec->ptr = mg_get_builtin_mime_type(path);
  4681. vec->len = strlen(vec->ptr);
  4682. }
  4683. /* Stringify binary data. Output buffer must be twice as big as input,
  4684. * because each byte takes 2 bytes in string representation */
  4685. static void
  4686. bin2str(char *to, const unsigned char *p, size_t len)
  4687. {
  4688. static const char *hex = "0123456789abcdef";
  4689. for (; len--; p++) {
  4690. *to++ = hex[p[0] >> 4];
  4691. *to++ = hex[p[0] & 0x0f];
  4692. }
  4693. *to = '\0';
  4694. }
  4695. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes. */
  4696. char *
  4697. mg_md5(char buf[33], ...)
  4698. {
  4699. md5_byte_t hash[16];
  4700. const char *p;
  4701. va_list ap;
  4702. md5_state_t ctx;
  4703. md5_init(&ctx);
  4704. va_start(ap, buf);
  4705. while ((p = va_arg(ap, const char *)) != NULL) {
  4706. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  4707. }
  4708. va_end(ap);
  4709. md5_finish(&ctx, hash);
  4710. bin2str(buf, hash, sizeof(hash));
  4711. return buf;
  4712. }
  4713. /* Check the user's password, return 1 if OK */
  4714. static int
  4715. check_password(const char *method,
  4716. const char *ha1,
  4717. const char *uri,
  4718. const char *nonce,
  4719. const char *nc,
  4720. const char *cnonce,
  4721. const char *qop,
  4722. const char *response)
  4723. {
  4724. char ha2[32 + 1], expected_response[32 + 1];
  4725. /* Some of the parameters may be NULL */
  4726. if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL
  4727. || qop == NULL
  4728. || response == NULL) {
  4729. return 0;
  4730. }
  4731. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  4732. if (strlen(response) != 32) {
  4733. return 0;
  4734. }
  4735. mg_md5(ha2, method, ":", uri, NULL);
  4736. mg_md5(expected_response,
  4737. ha1,
  4738. ":",
  4739. nonce,
  4740. ":",
  4741. nc,
  4742. ":",
  4743. cnonce,
  4744. ":",
  4745. qop,
  4746. ":",
  4747. ha2,
  4748. NULL);
  4749. return mg_strcasecmp(response, expected_response) == 0;
  4750. }
  4751. /* Use the global passwords file, if specified by auth_gpass option,
  4752. * or search for .htpasswd in the requested directory. */
  4753. static void
  4754. open_auth_file(struct mg_connection *conn, const char *path, struct file *filep)
  4755. {
  4756. if (conn != NULL && conn->ctx != NULL) {
  4757. char name[PATH_MAX];
  4758. const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
  4759. struct file file = STRUCT_FILE_INITIALIZER;
  4760. int truncated;
  4761. if (gpass != NULL) {
  4762. /* Use global passwords file */
  4763. if (!mg_fopen(conn, gpass, "r", filep)) {
  4764. #ifdef DEBUG
  4765. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  4766. #endif
  4767. }
  4768. /* Important: using local struct file to test path for is_directory
  4769. * flag. If filep is used, mg_stat() makes it appear as if auth file
  4770. * was opened. */
  4771. } else if (mg_stat(conn, path, &file) && file.is_directory) {
  4772. mg_snprintf(conn,
  4773. &truncated,
  4774. name,
  4775. sizeof(name),
  4776. "%s/%s",
  4777. path,
  4778. PASSWORDS_FILE_NAME);
  4779. if (truncated || !mg_fopen(conn, name, "r", filep)) {
  4780. #ifdef DEBUG
  4781. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  4782. #endif
  4783. }
  4784. } else {
  4785. /* Try to find .htpasswd in requested directory. */
  4786. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  4787. if (e[0] == '/') {
  4788. break;
  4789. }
  4790. }
  4791. mg_snprintf(conn,
  4792. &truncated,
  4793. name,
  4794. sizeof(name),
  4795. "%.*s/%s",
  4796. (int)(e - p),
  4797. p,
  4798. PASSWORDS_FILE_NAME);
  4799. if (truncated || !mg_fopen(conn, name, "r", filep)) {
  4800. #ifdef DEBUG
  4801. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  4802. #endif
  4803. }
  4804. }
  4805. }
  4806. }
  4807. /* Parsed Authorization header */
  4808. struct ah {
  4809. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  4810. };
  4811. /* Return 1 on success. Always initializes the ah structure. */
  4812. static int
  4813. parse_auth_header(struct mg_connection *conn,
  4814. char *buf,
  4815. size_t buf_size,
  4816. struct ah *ah)
  4817. {
  4818. char *name, *value, *s;
  4819. const char *auth_header;
  4820. uint64_t nonce;
  4821. if (!ah || !conn) {
  4822. return 0;
  4823. }
  4824. (void)memset(ah, 0, sizeof(*ah));
  4825. if ((auth_header = mg_get_header(conn, "Authorization")) == NULL
  4826. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  4827. return 0;
  4828. }
  4829. /* Make modifiable copy of the auth header */
  4830. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  4831. s = buf;
  4832. /* Parse authorization header */
  4833. for (;;) {
  4834. /* Gobble initial spaces */
  4835. while (isspace(*(unsigned char *)s)) {
  4836. s++;
  4837. }
  4838. name = skip_quoted(&s, "=", " ", 0);
  4839. /* Value is either quote-delimited, or ends at first comma or space. */
  4840. if (s[0] == '\"') {
  4841. s++;
  4842. value = skip_quoted(&s, "\"", " ", '\\');
  4843. if (s[0] == ',') {
  4844. s++;
  4845. }
  4846. } else {
  4847. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  4848. * spaces */
  4849. }
  4850. if (*name == '\0') {
  4851. break;
  4852. }
  4853. if (!strcmp(name, "username")) {
  4854. ah->user = value;
  4855. } else if (!strcmp(name, "cnonce")) {
  4856. ah->cnonce = value;
  4857. } else if (!strcmp(name, "response")) {
  4858. ah->response = value;
  4859. } else if (!strcmp(name, "uri")) {
  4860. ah->uri = value;
  4861. } else if (!strcmp(name, "qop")) {
  4862. ah->qop = value;
  4863. } else if (!strcmp(name, "nc")) {
  4864. ah->nc = value;
  4865. } else if (!strcmp(name, "nonce")) {
  4866. ah->nonce = value;
  4867. }
  4868. }
  4869. #ifndef NO_NONCE_CHECK
  4870. /* Read the nonce from the response. */
  4871. if (ah->nonce == NULL) {
  4872. return 0;
  4873. }
  4874. s = NULL;
  4875. nonce = strtoull(ah->nonce, &s, 10);
  4876. if ((s == NULL) || (*s != 0)) {
  4877. return 0;
  4878. }
  4879. /* Convert the nonce from the client to a number. */
  4880. nonce ^= conn->ctx->auth_nonce_mask;
  4881. /* The converted number corresponds to the time the nounce has been
  4882. * created. This should not be earlier than the server start. */
  4883. /* Server side nonce check is valuable in all situations but one:
  4884. * if the server restarts frequently, but the client should not see
  4885. * that, so the server should accept nonces from previous starts. */
  4886. /* However, the reasonable default is to not accept a nonce from a
  4887. * previous start, so if anyone changed the access rights between
  4888. * two restarts, a new login is required. */
  4889. if (nonce < (uint64_t)conn->ctx->start_time) {
  4890. /* nonce is from a previous start of the server and no longer valid
  4891. * (replay attack?) */
  4892. return 0;
  4893. }
  4894. /* Check if the nonce is too high, so it has not (yet) been used by the
  4895. * server. */
  4896. if (nonce >= ((uint64_t)conn->ctx->start_time + conn->ctx->nonce_count)) {
  4897. return 0;
  4898. }
  4899. #else
  4900. (void)nonce;
  4901. #endif
  4902. /* CGI needs it as REMOTE_USER */
  4903. if (ah->user != NULL) {
  4904. conn->request_info.remote_user = mg_strdup(ah->user);
  4905. } else {
  4906. return 0;
  4907. }
  4908. return 1;
  4909. }
  4910. static const char *
  4911. mg_fgets(char *buf, size_t size, struct file *filep, char **p)
  4912. {
  4913. const char *eof;
  4914. size_t len;
  4915. const char *memend;
  4916. if (!filep) {
  4917. return NULL;
  4918. }
  4919. if (filep->membuf != NULL && *p != NULL) {
  4920. memend = (const char *)&filep->membuf[filep->size];
  4921. /* Search for \n from p till the end of stream */
  4922. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  4923. if (eof != NULL) {
  4924. eof += 1; /* Include \n */
  4925. } else {
  4926. eof = memend; /* Copy remaining data */
  4927. }
  4928. len =
  4929. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  4930. memcpy(buf, *p, len);
  4931. buf[len] = '\0';
  4932. *p += len;
  4933. return len ? eof : NULL;
  4934. } else if (filep->fp != NULL) {
  4935. return fgets(buf, (int)size, filep->fp);
  4936. } else {
  4937. return NULL;
  4938. }
  4939. }
  4940. struct read_auth_file_struct {
  4941. struct mg_connection *conn;
  4942. struct ah ah;
  4943. char *domain;
  4944. char buf[256 + 256 + 40];
  4945. char *f_user;
  4946. char *f_domain;
  4947. char *f_ha1;
  4948. };
  4949. static int
  4950. read_auth_file(struct file *filep, struct read_auth_file_struct *workdata)
  4951. {
  4952. char *p;
  4953. int is_authorized = 0;
  4954. struct file fp;
  4955. size_t l;
  4956. if (!filep || !workdata) {
  4957. return 0;
  4958. }
  4959. /* Loop over passwords file */
  4960. p = (char *)filep->membuf;
  4961. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  4962. l = strlen(workdata->buf);
  4963. while (l > 0) {
  4964. if (isspace(workdata->buf[l - 1])
  4965. || iscntrl(workdata->buf[l - 1])) {
  4966. l--;
  4967. workdata->buf[l] = 0;
  4968. } else
  4969. break;
  4970. }
  4971. if (l < 1) {
  4972. continue;
  4973. }
  4974. workdata->f_user = workdata->buf;
  4975. if (workdata->f_user[0] == ':') {
  4976. /* user names may not contain a ':' and may not be empty,
  4977. * so lines starting with ':' may be used for a special purpose */
  4978. if (workdata->f_user[1] == '#') {
  4979. /* :# is a comment */
  4980. continue;
  4981. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  4982. if (mg_fopen(workdata->conn, workdata->f_user + 9, "r", &fp)) {
  4983. is_authorized = read_auth_file(&fp, workdata);
  4984. mg_fclose(&fp);
  4985. } else {
  4986. mg_cry(workdata->conn,
  4987. "%s: cannot open authorization file: %s",
  4988. __func__,
  4989. workdata->buf);
  4990. }
  4991. continue;
  4992. }
  4993. /* everything is invalid for the moment (might change in the
  4994. * future) */
  4995. mg_cry(workdata->conn,
  4996. "%s: syntax error in authorization file: %s",
  4997. __func__,
  4998. workdata->buf);
  4999. continue;
  5000. }
  5001. workdata->f_domain = strchr(workdata->f_user, ':');
  5002. if (workdata->f_domain == 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_domain) = 0;
  5010. (workdata->f_domain)++;
  5011. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  5012. if (workdata->f_ha1 == NULL) {
  5013. mg_cry(workdata->conn,
  5014. "%s: syntax error in authorization file: %s",
  5015. __func__,
  5016. workdata->buf);
  5017. continue;
  5018. }
  5019. *(workdata->f_ha1) = 0;
  5020. (workdata->f_ha1)++;
  5021. if (!strcmp(workdata->ah.user, workdata->f_user)
  5022. && !strcmp(workdata->domain, workdata->f_domain)) {
  5023. return check_password(workdata->conn->request_info.request_method,
  5024. workdata->f_ha1,
  5025. workdata->ah.uri,
  5026. workdata->ah.nonce,
  5027. workdata->ah.nc,
  5028. workdata->ah.cnonce,
  5029. workdata->ah.qop,
  5030. workdata->ah.response);
  5031. }
  5032. }
  5033. return is_authorized;
  5034. }
  5035. /* Authorize against the opened passwords file. Return 1 if authorized. */
  5036. static int
  5037. authorize(struct mg_connection *conn, struct file *filep)
  5038. {
  5039. struct read_auth_file_struct workdata;
  5040. char buf[MG_BUF_LEN];
  5041. if (!conn || !conn->ctx) {
  5042. return 0;
  5043. }
  5044. memset(&workdata, 0, sizeof(workdata));
  5045. workdata.conn = conn;
  5046. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  5047. return 0;
  5048. }
  5049. workdata.domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  5050. return read_auth_file(filep, &workdata);
  5051. }
  5052. /* Return 1 if request is authorised, 0 otherwise. */
  5053. static int
  5054. check_authorization(struct mg_connection *conn, const char *path)
  5055. {
  5056. char fname[PATH_MAX];
  5057. struct vec uri_vec, filename_vec;
  5058. const char *list;
  5059. struct file file = STRUCT_FILE_INITIALIZER;
  5060. int authorized = 1, truncated;
  5061. if (!conn || !conn->ctx) {
  5062. return 0;
  5063. }
  5064. list = conn->ctx->config[PROTECT_URI];
  5065. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  5066. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  5067. mg_snprintf(conn,
  5068. &truncated,
  5069. fname,
  5070. sizeof(fname),
  5071. "%.*s",
  5072. (int)filename_vec.len,
  5073. filename_vec.ptr);
  5074. if (truncated || !mg_fopen(conn, fname, "r", &file)) {
  5075. mg_cry(conn,
  5076. "%s: cannot open %s: %s",
  5077. __func__,
  5078. fname,
  5079. strerror(errno));
  5080. }
  5081. break;
  5082. }
  5083. }
  5084. if (!is_file_opened(&file)) {
  5085. open_auth_file(conn, path, &file);
  5086. }
  5087. if (is_file_opened(&file)) {
  5088. authorized = authorize(conn, &file);
  5089. mg_fclose(&file);
  5090. }
  5091. return authorized;
  5092. }
  5093. static void
  5094. send_authorization_request(struct mg_connection *conn)
  5095. {
  5096. char date[64];
  5097. time_t curtime = time(NULL);
  5098. if (conn && conn->ctx) {
  5099. uint64_t nonce = (uint64_t)(conn->ctx->start_time);
  5100. (void)pthread_mutex_lock(&conn->ctx->nonce_mutex);
  5101. nonce += conn->ctx->nonce_count;
  5102. ++conn->ctx->nonce_count;
  5103. (void)pthread_mutex_unlock(&conn->ctx->nonce_mutex);
  5104. nonce ^= conn->ctx->auth_nonce_mask;
  5105. conn->status_code = 401;
  5106. conn->must_close = 1;
  5107. gmt_time_string(date, sizeof(date), &curtime);
  5108. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  5109. send_no_cache_header(conn);
  5110. mg_printf(conn,
  5111. "Date: %s\r\n"
  5112. "Connection: %s\r\n"
  5113. "Content-Length: 0\r\n"
  5114. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  5115. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  5116. date,
  5117. suggest_connection_header(conn),
  5118. conn->ctx->config[AUTHENTICATION_DOMAIN],
  5119. nonce);
  5120. }
  5121. }
  5122. #if !defined(NO_FILES)
  5123. static int
  5124. is_authorized_for_put(struct mg_connection *conn)
  5125. {
  5126. if (conn) {
  5127. struct file file = STRUCT_FILE_INITIALIZER;
  5128. const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
  5129. int ret = 0;
  5130. if (passfile != NULL && mg_fopen(conn, passfile, "r", &file)) {
  5131. ret = authorize(conn, &file);
  5132. mg_fclose(&file);
  5133. }
  5134. return ret;
  5135. }
  5136. return 0;
  5137. }
  5138. #endif
  5139. int
  5140. mg_modify_passwords_file(const char *fname,
  5141. const char *domain,
  5142. const char *user,
  5143. const char *pass)
  5144. {
  5145. int found, i;
  5146. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  5147. FILE *fp, *fp2;
  5148. found = 0;
  5149. fp = fp2 = NULL;
  5150. /* Regard empty password as no password - remove user record. */
  5151. if (pass != NULL && pass[0] == '\0') {
  5152. pass = NULL;
  5153. }
  5154. /* Other arguments must not be empty */
  5155. if (fname == NULL || domain == NULL || user == NULL) {
  5156. return 0;
  5157. }
  5158. /* Using the given file format, user name and domain must not contain ':'
  5159. */
  5160. if (strchr(user, ':') != NULL) {
  5161. return 0;
  5162. }
  5163. if (strchr(domain, ':') != NULL) {
  5164. return 0;
  5165. }
  5166. /* Do not allow control characters like newline in user name and domain.
  5167. * Do not allow excessively long names either. */
  5168. for (i = 0; i < 255 && user[i] != 0; i++) {
  5169. if (iscntrl(user[i])) {
  5170. return 0;
  5171. }
  5172. }
  5173. if (user[i]) {
  5174. return 0;
  5175. }
  5176. for (i = 0; i < 255 && domain[i] != 0; i++) {
  5177. if (iscntrl(domain[i])) {
  5178. return 0;
  5179. }
  5180. }
  5181. if (domain[i]) {
  5182. return 0;
  5183. }
  5184. /* The maximum length of the path to the password file is limited */
  5185. if ((strlen(fname) + 4) >= PATH_MAX) {
  5186. return 0;
  5187. }
  5188. /* Create a temporary file name. Length has been checked before. */
  5189. strcpy(tmp, fname);
  5190. strcat(tmp, ".tmp");
  5191. /* Create the file if does not exist */
  5192. /* Use of fopen here is OK, since fname is only ASCII */
  5193. if ((fp = fopen(fname, "a+")) != NULL) {
  5194. (void)fclose(fp);
  5195. }
  5196. /* Open the given file and temporary file */
  5197. if ((fp = fopen(fname, "r")) == NULL) {
  5198. return 0;
  5199. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  5200. fclose(fp);
  5201. return 0;
  5202. }
  5203. /* Copy the stuff to temporary file */
  5204. while (fgets(line, sizeof(line), fp) != NULL) {
  5205. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  5206. continue;
  5207. }
  5208. u[255] = 0;
  5209. d[255] = 0;
  5210. if (!strcmp(u, user) && !strcmp(d, domain)) {
  5211. found++;
  5212. if (pass != NULL) {
  5213. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  5214. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  5215. }
  5216. } else {
  5217. fprintf(fp2, "%s", line);
  5218. }
  5219. }
  5220. /* If new user, just add it */
  5221. if (!found && pass != NULL) {
  5222. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  5223. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  5224. }
  5225. /* Close files */
  5226. fclose(fp);
  5227. fclose(fp2);
  5228. /* Put the temp file in place of real file */
  5229. IGNORE_UNUSED_RESULT(remove(fname));
  5230. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  5231. return 1;
  5232. }
  5233. static int
  5234. is_valid_port(unsigned long port)
  5235. {
  5236. return port < 0xffff;
  5237. }
  5238. static int
  5239. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  5240. {
  5241. struct addrinfo hints, *res, *ressave;
  5242. int func_ret = 0;
  5243. int gai_ret;
  5244. memset(&hints, 0, sizeof(struct addrinfo));
  5245. hints.ai_family = af;
  5246. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  5247. if (gai_ret != 0) {
  5248. /* gai_strerror could be used to convert gai_ret to a string */
  5249. /* POSIX return values: see
  5250. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  5251. */
  5252. /* Windows return values: see
  5253. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  5254. */
  5255. return 0;
  5256. }
  5257. ressave = res;
  5258. while (res) {
  5259. if (dstlen >= res->ai_addrlen) {
  5260. memcpy(dst, res->ai_addr, res->ai_addrlen);
  5261. func_ret = 1;
  5262. }
  5263. res = res->ai_next;
  5264. }
  5265. freeaddrinfo(ressave);
  5266. return func_ret;
  5267. }
  5268. static int
  5269. connect_socket(struct mg_context *ctx /* may be NULL */,
  5270. const char *host,
  5271. int port,
  5272. int use_ssl,
  5273. char *ebuf,
  5274. size_t ebuf_len,
  5275. SOCKET *sock /* output: socket, must not be NULL */,
  5276. union usa *sa /* output: socket address, must not be NULL */
  5277. )
  5278. {
  5279. int ip_ver = 0;
  5280. *sock = INVALID_SOCKET;
  5281. memset(sa, 0, sizeof(*sa));
  5282. if (ebuf_len > 0) {
  5283. *ebuf = 0;
  5284. }
  5285. if (host == NULL) {
  5286. mg_snprintf(NULL,
  5287. NULL, /* No truncation check for ebuf */
  5288. ebuf,
  5289. ebuf_len,
  5290. "%s",
  5291. "NULL host");
  5292. return 0;
  5293. }
  5294. if (port < 0 || !is_valid_port((unsigned)port)) {
  5295. mg_snprintf(NULL,
  5296. NULL, /* No truncation check for ebuf */
  5297. ebuf,
  5298. ebuf_len,
  5299. "%s",
  5300. "invalid port");
  5301. return 0;
  5302. }
  5303. #if !defined(NO_SSL)
  5304. if (use_ssl && (SSLv23_client_method == NULL)) {
  5305. mg_snprintf(NULL,
  5306. NULL, /* No truncation check for ebuf */
  5307. ebuf,
  5308. ebuf_len,
  5309. "%s",
  5310. "SSL is not initialized");
  5311. return 0;
  5312. }
  5313. #else
  5314. (void)use_ssl;
  5315. #endif
  5316. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  5317. sa->sin.sin_port = htons((uint16_t)port);
  5318. ip_ver = 4;
  5319. #ifdef USE_IPV6
  5320. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  5321. sa->sin6.sin6_port = htons((uint16_t)port);
  5322. ip_ver = 6;
  5323. } else if (host[0] == '[') {
  5324. /* While getaddrinfo on Windows will work with [::1],
  5325. * getaddrinfo on Linux only works with ::1 (without []). */
  5326. size_t l = strlen(host + 1);
  5327. char *h = (l > 1) ? mg_strdup(host + 1) : NULL;
  5328. if (h) {
  5329. h[l - 1] = 0;
  5330. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  5331. sa->sin6.sin6_port = htons((uint16_t)port);
  5332. ip_ver = 6;
  5333. }
  5334. mg_free(h);
  5335. }
  5336. #endif
  5337. }
  5338. if (ip_ver == 0) {
  5339. mg_snprintf(NULL,
  5340. NULL, /* No truncation check for ebuf */
  5341. ebuf,
  5342. ebuf_len,
  5343. "%s",
  5344. "host not found");
  5345. return 0;
  5346. }
  5347. if (ip_ver == 4) {
  5348. *sock = socket(PF_INET, SOCK_STREAM, 0);
  5349. }
  5350. #ifdef USE_IPV6
  5351. else if (ip_ver == 6) {
  5352. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  5353. }
  5354. #endif
  5355. if (*sock == INVALID_SOCKET) {
  5356. mg_snprintf(NULL,
  5357. NULL, /* No truncation check for ebuf */
  5358. ebuf,
  5359. ebuf_len,
  5360. "socket(): %s",
  5361. strerror(ERRNO));
  5362. return 0;
  5363. }
  5364. set_close_on_exec(*sock, fc(ctx));
  5365. if ((ip_ver == 4)
  5366. && (connect(*sock, (struct sockaddr *)&sa->sin, sizeof(sa->sin))
  5367. == 0)) {
  5368. /* connected with IPv4 */
  5369. return 1;
  5370. }
  5371. #ifdef USE_IPV6
  5372. if ((ip_ver == 6)
  5373. && (connect(*sock, (struct sockaddr *)&sa->sin6, sizeof(sa->sin6))
  5374. == 0)) {
  5375. /* connected with IPv6 */
  5376. return 1;
  5377. }
  5378. #endif
  5379. /* Not connected */
  5380. mg_snprintf(NULL,
  5381. NULL, /* No truncation check for ebuf */
  5382. ebuf,
  5383. ebuf_len,
  5384. "connect(%s:%d): %s",
  5385. host,
  5386. port,
  5387. strerror(ERRNO));
  5388. closesocket(*sock);
  5389. *sock = INVALID_SOCKET;
  5390. return 0;
  5391. }
  5392. int
  5393. mg_url_encode(const char *src, char *dst, size_t dst_len)
  5394. {
  5395. static const char *dont_escape = "._-$,;~()";
  5396. static const char *hex = "0123456789abcdef";
  5397. char *pos = dst;
  5398. const char *end = dst + dst_len - 1;
  5399. for (; *src != '\0' && pos < end; src++, pos++) {
  5400. if (isalnum(*(const unsigned char *)src)
  5401. || strchr(dont_escape, *(const unsigned char *)src) != NULL) {
  5402. *pos = *src;
  5403. } else if (pos + 2 < end) {
  5404. pos[0] = '%';
  5405. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  5406. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  5407. pos += 2;
  5408. } else {
  5409. break;
  5410. }
  5411. }
  5412. *pos = '\0';
  5413. return (*src == '\0') ? (int)(pos - dst) : -1;
  5414. }
  5415. static void
  5416. print_dir_entry(struct de *de)
  5417. {
  5418. char size[64], mod[64], href[PATH_MAX * 3 /* worst case */];
  5419. struct tm *tm;
  5420. if (de->file.is_directory) {
  5421. mg_snprintf(de->conn,
  5422. NULL, /* Buffer is big enough */
  5423. size,
  5424. sizeof(size),
  5425. "%s",
  5426. "[DIRECTORY]");
  5427. } else {
  5428. /* We use (signed) cast below because MSVC 6 compiler cannot
  5429. * convert unsigned __int64 to double. Sigh. */
  5430. if (de->file.size < 1024) {
  5431. mg_snprintf(de->conn,
  5432. NULL, /* Buffer is big enough */
  5433. size,
  5434. sizeof(size),
  5435. "%d",
  5436. (int)de->file.size);
  5437. } else if (de->file.size < 0x100000) {
  5438. mg_snprintf(de->conn,
  5439. NULL, /* Buffer is big enough */
  5440. size,
  5441. sizeof(size),
  5442. "%.1fk",
  5443. (double)de->file.size / 1024.0);
  5444. } else if (de->file.size < 0x40000000) {
  5445. mg_snprintf(de->conn,
  5446. NULL, /* Buffer is big enough */
  5447. size,
  5448. sizeof(size),
  5449. "%.1fM",
  5450. (double)de->file.size / 1048576);
  5451. } else {
  5452. mg_snprintf(de->conn,
  5453. NULL, /* Buffer is big enough */
  5454. size,
  5455. sizeof(size),
  5456. "%.1fG",
  5457. (double)de->file.size / 1073741824);
  5458. }
  5459. }
  5460. /* Note: mg_snprintf will not cause a buffer overflow above.
  5461. * So, string truncation checks are not required here. */
  5462. tm = localtime(&de->file.last_modified);
  5463. if (tm != NULL) {
  5464. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  5465. } else {
  5466. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  5467. mod[sizeof(mod) - 1] = '\0';
  5468. }
  5469. mg_url_encode(de->file_name, href, sizeof(href));
  5470. de->conn->num_bytes_sent +=
  5471. mg_printf(de->conn,
  5472. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  5473. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  5474. de->conn->request_info.local_uri,
  5475. href,
  5476. de->file.is_directory ? "/" : "",
  5477. de->file_name,
  5478. de->file.is_directory ? "/" : "",
  5479. mod,
  5480. size);
  5481. }
  5482. /* This function is called from send_directory() and used for
  5483. * sorting directory entries by size, or name, or modification time.
  5484. * On windows, __cdecl specification is needed in case if project is built
  5485. * with __stdcall convention. qsort always requires __cdels callback. */
  5486. static int WINCDECL
  5487. compare_dir_entries(const void *p1, const void *p2)
  5488. {
  5489. if (p1 && p2) {
  5490. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  5491. const char *query_string = a->conn->request_info.query_string;
  5492. int cmp_result = 0;
  5493. if (query_string == NULL) {
  5494. query_string = "na";
  5495. }
  5496. if (a->file.is_directory && !b->file.is_directory) {
  5497. return -1; /* Always put directories on top */
  5498. } else if (!a->file.is_directory && b->file.is_directory) {
  5499. return 1; /* Always put directories on top */
  5500. } else if (*query_string == 'n') {
  5501. cmp_result = strcmp(a->file_name, b->file_name);
  5502. } else if (*query_string == 's') {
  5503. cmp_result = (a->file.size == b->file.size)
  5504. ? 0
  5505. : ((a->file.size > b->file.size) ? 1 : -1);
  5506. } else if (*query_string == 'd') {
  5507. cmp_result =
  5508. (a->file.last_modified == b->file.last_modified)
  5509. ? 0
  5510. : ((a->file.last_modified > b->file.last_modified) ? 1
  5511. : -1);
  5512. }
  5513. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  5514. }
  5515. return 0;
  5516. }
  5517. static int
  5518. must_hide_file(struct mg_connection *conn, const char *path)
  5519. {
  5520. if (conn && conn->ctx) {
  5521. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  5522. const char *pattern = conn->ctx->config[HIDE_FILES];
  5523. return match_prefix(pw_pattern, strlen(pw_pattern), path) > 0
  5524. || (pattern != NULL
  5525. && match_prefix(pattern, strlen(pattern), path) > 0);
  5526. }
  5527. return 0;
  5528. }
  5529. static int
  5530. scan_directory(struct mg_connection *conn,
  5531. const char *dir,
  5532. void *data,
  5533. void (*cb)(struct de *, void *))
  5534. {
  5535. char path[PATH_MAX];
  5536. struct dirent *dp;
  5537. DIR *dirp;
  5538. struct de de;
  5539. int truncated;
  5540. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  5541. return 0;
  5542. } else {
  5543. de.conn = conn;
  5544. while ((dp = mg_readdir(dirp)) != NULL) {
  5545. /* Do not show current dir and hidden files */
  5546. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  5547. || must_hide_file(conn, dp->d_name)) {
  5548. continue;
  5549. }
  5550. mg_snprintf(
  5551. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  5552. /* If we don't memset stat structure to zero, mtime will have
  5553. * garbage and strftime() will segfault later on in
  5554. * print_dir_entry(). memset is required only if mg_stat()
  5555. * fails. For more details, see
  5556. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  5557. memset(&de.file, 0, sizeof(de.file));
  5558. if (truncated) {
  5559. /* If the path is not complete, skip processing. */
  5560. continue;
  5561. }
  5562. if (!mg_stat(conn, path, &de.file)) {
  5563. mg_cry(conn,
  5564. "%s: mg_stat(%s) failed: %s",
  5565. __func__,
  5566. path,
  5567. strerror(ERRNO));
  5568. }
  5569. de.file_name = dp->d_name;
  5570. cb(&de, data);
  5571. }
  5572. (void)mg_closedir(dirp);
  5573. }
  5574. return 1;
  5575. }
  5576. #if !defined(NO_FILES)
  5577. static int
  5578. remove_directory(struct mg_connection *conn, const char *dir)
  5579. {
  5580. char path[PATH_MAX];
  5581. struct dirent *dp;
  5582. DIR *dirp;
  5583. struct de de;
  5584. int truncated;
  5585. int ok = 1;
  5586. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  5587. return 0;
  5588. } else {
  5589. de.conn = conn;
  5590. while ((dp = mg_readdir(dirp)) != NULL) {
  5591. /* Do not show current dir (but show hidden files as they will
  5592. * also be removed) */
  5593. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  5594. continue;
  5595. }
  5596. mg_snprintf(
  5597. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  5598. /* If we don't memset stat structure to zero, mtime will have
  5599. * garbage and strftime() will segfault later on in
  5600. * print_dir_entry(). memset is required only if mg_stat()
  5601. * fails. For more details, see
  5602. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  5603. memset(&de.file, 0, sizeof(de.file));
  5604. if (truncated) {
  5605. /* Do not delete anything shorter */
  5606. ok = 0;
  5607. continue;
  5608. }
  5609. if (!mg_stat(conn, path, &de.file)) {
  5610. mg_cry(conn,
  5611. "%s: mg_stat(%s) failed: %s",
  5612. __func__,
  5613. path,
  5614. strerror(ERRNO));
  5615. ok = 0;
  5616. }
  5617. if (de.file.membuf == NULL) {
  5618. /* file is not in memory */
  5619. if (de.file.is_directory) {
  5620. if (remove_directory(conn, path) == 0) {
  5621. ok = 0;
  5622. }
  5623. } else {
  5624. if (mg_remove(conn, path) == 0) {
  5625. ok = 0;
  5626. }
  5627. }
  5628. } else {
  5629. /* file is in memory. It can not be deleted. */
  5630. ok = 0;
  5631. }
  5632. }
  5633. (void)mg_closedir(dirp);
  5634. IGNORE_UNUSED_RESULT(rmdir(dir));
  5635. }
  5636. return ok;
  5637. }
  5638. #endif
  5639. struct dir_scan_data {
  5640. struct de *entries;
  5641. unsigned int num_entries;
  5642. unsigned int arr_size;
  5643. };
  5644. /* Behaves like realloc(), but frees original pointer on failure */
  5645. static void *
  5646. realloc2(void *ptr, size_t size)
  5647. {
  5648. void *new_ptr = mg_realloc(ptr, size);
  5649. if (new_ptr == NULL) {
  5650. mg_free(ptr);
  5651. }
  5652. return new_ptr;
  5653. }
  5654. static void
  5655. dir_scan_callback(struct de *de, void *data)
  5656. {
  5657. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  5658. if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {
  5659. dsd->arr_size *= 2;
  5660. dsd->entries =
  5661. (struct de *)realloc2(dsd->entries,
  5662. dsd->arr_size * sizeof(dsd->entries[0]));
  5663. }
  5664. if (dsd->entries == NULL) {
  5665. /* TODO(lsm, low): propagate an error to the caller */
  5666. dsd->num_entries = 0;
  5667. } else {
  5668. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  5669. dsd->entries[dsd->num_entries].file = de->file;
  5670. dsd->entries[dsd->num_entries].conn = de->conn;
  5671. dsd->num_entries++;
  5672. }
  5673. }
  5674. static void
  5675. handle_directory_request(struct mg_connection *conn, const char *dir)
  5676. {
  5677. unsigned int i;
  5678. int sort_direction;
  5679. struct dir_scan_data data = {NULL, 0, 128};
  5680. char date[64];
  5681. time_t curtime = time(NULL);
  5682. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  5683. send_http_error(conn,
  5684. 500,
  5685. "Error: Cannot open directory\nopendir(%s): %s",
  5686. dir,
  5687. strerror(ERRNO));
  5688. return;
  5689. }
  5690. gmt_time_string(date, sizeof(date), &curtime);
  5691. if (!conn) {
  5692. return;
  5693. }
  5694. sort_direction = ((conn->request_info.query_string != NULL)
  5695. && (conn->request_info.query_string[1] == 'd'))
  5696. ? 'a'
  5697. : 'd';
  5698. conn->must_close = 1;
  5699. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  5700. send_static_cache_header(conn);
  5701. mg_printf(conn,
  5702. "Date: %s\r\n"
  5703. "Connection: close\r\n"
  5704. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  5705. date);
  5706. conn->num_bytes_sent +=
  5707. mg_printf(conn,
  5708. "<html><head><title>Index of %s</title>"
  5709. "<style>th {text-align: left;}</style></head>"
  5710. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  5711. "<tr><th><a href=\"?n%c\">Name</a></th>"
  5712. "<th><a href=\"?d%c\">Modified</a></th>"
  5713. "<th><a href=\"?s%c\">Size</a></th></tr>"
  5714. "<tr><td colspan=\"3\"><hr></td></tr>",
  5715. conn->request_info.local_uri,
  5716. conn->request_info.local_uri,
  5717. sort_direction,
  5718. sort_direction,
  5719. sort_direction);
  5720. /* Print first entry - link to a parent directory */
  5721. conn->num_bytes_sent +=
  5722. mg_printf(conn,
  5723. "<tr><td><a href=\"%s%s\">%s</a></td>"
  5724. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  5725. conn->request_info.local_uri,
  5726. "..",
  5727. "Parent directory",
  5728. "-",
  5729. "-");
  5730. /* Sort and print directory entries */
  5731. if (data.entries != NULL) {
  5732. qsort(data.entries,
  5733. (size_t)data.num_entries,
  5734. sizeof(data.entries[0]),
  5735. compare_dir_entries);
  5736. for (i = 0; i < data.num_entries; i++) {
  5737. print_dir_entry(&data.entries[i]);
  5738. mg_free(data.entries[i].file_name);
  5739. }
  5740. mg_free(data.entries);
  5741. }
  5742. conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");
  5743. conn->status_code = 200;
  5744. }
  5745. /* Send len bytes from the opened file to the client. */
  5746. static void
  5747. send_file_data(struct mg_connection *conn,
  5748. struct file *filep,
  5749. int64_t offset,
  5750. int64_t len)
  5751. {
  5752. char buf[MG_BUF_LEN];
  5753. int to_read, num_read, num_written;
  5754. int64_t size;
  5755. if (!filep || !conn) {
  5756. return;
  5757. }
  5758. /* Sanity check the offset */
  5759. size = (filep->size > INT64_MAX) ? INT64_MAX : (int64_t)(filep->size);
  5760. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  5761. if (len > 0 && filep->membuf != NULL && size > 0) {
  5762. /* file stored in memory */
  5763. if (len > size - offset) {
  5764. len = size - offset;
  5765. }
  5766. mg_write(conn, filep->membuf + offset, (size_t)len);
  5767. } else if (len > 0 && filep->fp != NULL) {
  5768. /* file stored on disk */
  5769. #if defined(__linux__)
  5770. /* sendfile is only available for Linux */
  5771. if (conn->throttle == 0 && conn->ssl == 0) {
  5772. off_t sf_offs = (off_t)offset;
  5773. ssize_t sf_sent;
  5774. int sf_file = fileno(filep->fp);
  5775. int loop_cnt = 0;
  5776. do {
  5777. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  5778. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  5779. size_t sf_tosend =
  5780. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  5781. sf_sent =
  5782. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  5783. if (sf_sent > 0) {
  5784. conn->num_bytes_sent += sf_sent;
  5785. len -= sf_sent;
  5786. offset += sf_sent;
  5787. } else if (loop_cnt == 0) {
  5788. /* This file can not be sent using sendfile.
  5789. * This might be the case for pseudo-files in the
  5790. * /sys/ and /proc/ file system.
  5791. * Use the regular user mode copy code instead. */
  5792. break;
  5793. } else if (sf_sent == 0) {
  5794. /* No error, but 0 bytes sent. May be EOF? */
  5795. return;
  5796. }
  5797. loop_cnt++;
  5798. } while ((len > 0) && (sf_sent >= 0));
  5799. if (sf_sent > 0) {
  5800. return; /* OK */
  5801. }
  5802. /* sf_sent<0 means error, thus fall back to the classic way */
  5803. /* This is always the case, if sf_file is not a "normal" file,
  5804. * e.g., for sending data from the output of a CGI process. */
  5805. offset = (int64_t)sf_offs;
  5806. }
  5807. #endif
  5808. if ((offset > 0) && (fseeko(filep->fp, offset, SEEK_SET) != 0)) {
  5809. mg_cry(conn, "%s: fseeko() failed: %s", __func__, strerror(ERRNO));
  5810. send_http_error(
  5811. conn,
  5812. 500,
  5813. "%s",
  5814. "Error: Unable to access file at requested position.");
  5815. } else {
  5816. while (len > 0) {
  5817. /* Calculate how much to read from the file in the buffer */
  5818. to_read = sizeof(buf);
  5819. if ((int64_t)to_read > len) {
  5820. to_read = (int)len;
  5821. }
  5822. /* Read from file, exit the loop on error */
  5823. if ((num_read = (int)fread(buf, 1, (size_t)to_read, filep->fp))
  5824. <= 0) {
  5825. break;
  5826. }
  5827. /* Send read bytes to the client, exit the loop on error */
  5828. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  5829. != num_read) {
  5830. break;
  5831. }
  5832. /* Both read and were successful, adjust counters */
  5833. conn->num_bytes_sent += num_written;
  5834. len -= num_written;
  5835. }
  5836. }
  5837. }
  5838. }
  5839. static int
  5840. parse_range_header(const char *header, int64_t *a, int64_t *b)
  5841. {
  5842. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  5843. }
  5844. static void
  5845. construct_etag(char *buf, size_t buf_len, const struct file *filep)
  5846. {
  5847. if (filep != NULL && buf != NULL) {
  5848. mg_snprintf(NULL,
  5849. NULL, /* All calls to construct_etag use 64 byte buffer */
  5850. buf,
  5851. buf_len,
  5852. "\"%lx.%" INT64_FMT "\"",
  5853. (unsigned long)filep->last_modified,
  5854. filep->size);
  5855. }
  5856. }
  5857. static void
  5858. fclose_on_exec(struct file *filep, struct mg_connection *conn)
  5859. {
  5860. if (filep != NULL && filep->fp != NULL) {
  5861. #ifdef _WIN32
  5862. (void)conn; /* Unused. */
  5863. #else
  5864. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  5865. mg_cry(conn,
  5866. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  5867. __func__,
  5868. strerror(ERRNO));
  5869. }
  5870. #endif
  5871. }
  5872. }
  5873. static void
  5874. handle_static_file_request(struct mg_connection *conn,
  5875. const char *path,
  5876. struct file *filep,
  5877. const char *mime_type)
  5878. {
  5879. char date[64], lm[64], etag[64];
  5880. char range[128]; /* large enough, so there will be no overflow */
  5881. const char *msg = "OK", *hdr;
  5882. time_t curtime = time(NULL);
  5883. int64_t cl, r1, r2;
  5884. struct vec mime_vec;
  5885. int n, truncated;
  5886. char gz_path[PATH_MAX];
  5887. const char *encoding = "";
  5888. const char *cors1, *cors2, *cors3;
  5889. if (conn == NULL || conn->ctx == NULL || filep == NULL) {
  5890. return;
  5891. }
  5892. if (mime_type == NULL) {
  5893. get_mime_type(conn->ctx, path, &mime_vec);
  5894. } else {
  5895. mime_vec.ptr = mime_type;
  5896. mime_vec.len = strlen(mime_type);
  5897. }
  5898. if (filep->size > INT64_MAX) {
  5899. send_http_error(conn,
  5900. 500,
  5901. "Error: File size is too large to send\n%" INT64_FMT,
  5902. filep->size);
  5903. }
  5904. cl = (int64_t)filep->size;
  5905. conn->status_code = 200;
  5906. range[0] = '\0';
  5907. /* if this file is in fact a pre-gzipped file, rewrite its filename
  5908. * it's important to rewrite the filename after resolving
  5909. * the mime type from it, to preserve the actual file's type */
  5910. if (filep->gzipped) {
  5911. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  5912. if (truncated) {
  5913. send_http_error(conn,
  5914. 500,
  5915. "Error: Path of zipped file too long (%s)",
  5916. path);
  5917. return;
  5918. }
  5919. path = gz_path;
  5920. encoding = "Content-Encoding: gzip\r\n";
  5921. }
  5922. if (!mg_fopen(conn, path, "rb", filep)) {
  5923. send_http_error(conn,
  5924. 500,
  5925. "Error: Cannot open file\nfopen(%s): %s",
  5926. path,
  5927. strerror(ERRNO));
  5928. return;
  5929. }
  5930. fclose_on_exec(filep, conn);
  5931. /* If Range: header specified, act accordingly */
  5932. r1 = r2 = 0;
  5933. hdr = mg_get_header(conn, "Range");
  5934. if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 && r1 >= 0
  5935. && r2 >= 0) {
  5936. /* actually, range requests don't play well with a pre-gzipped
  5937. * file (since the range is specified in the uncompressed space) */
  5938. if (filep->gzipped) {
  5939. send_http_error(
  5940. conn,
  5941. 501,
  5942. "%s",
  5943. "Error: Range requests in gzipped files are not supported");
  5944. mg_fclose(filep);
  5945. return;
  5946. }
  5947. conn->status_code = 206;
  5948. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  5949. mg_snprintf(conn,
  5950. NULL, /* range buffer is big enough */
  5951. range,
  5952. sizeof(range),
  5953. "Content-Range: bytes "
  5954. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  5955. r1,
  5956. r1 + cl - 1,
  5957. filep->size);
  5958. msg = "Partial Content";
  5959. }
  5960. hdr = mg_get_header(conn, "Origin");
  5961. if (hdr) {
  5962. /* Cross-origin resource sharing (CORS), see
  5963. * http://www.html5rocks.com/en/tutorials/cors/,
  5964. * http://www.html5rocks.com/static/images/cors_server_flowchart.png -
  5965. * preflight is not supported for files. */
  5966. cors1 = "Access-Control-Allow-Origin: ";
  5967. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  5968. cors3 = "\r\n";
  5969. } else {
  5970. cors1 = cors2 = cors3 = "";
  5971. }
  5972. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
  5973. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  5974. gmt_time_string(date, sizeof(date), &curtime);
  5975. gmt_time_string(lm, sizeof(lm), &filep->last_modified);
  5976. construct_etag(etag, sizeof(etag), filep);
  5977. (void)mg_printf(conn,
  5978. "HTTP/1.1 %d %s\r\n"
  5979. "%s%s%s"
  5980. "Date: %s\r\n",
  5981. conn->status_code,
  5982. msg,
  5983. cors1,
  5984. cors2,
  5985. cors3,
  5986. date);
  5987. send_static_cache_header(conn);
  5988. (void)mg_printf(conn,
  5989. "Last-Modified: %s\r\n"
  5990. "Etag: %s\r\n"
  5991. "Content-Type: %.*s\r\n"
  5992. "Content-Length: %" INT64_FMT "\r\n"
  5993. "Connection: %s\r\n"
  5994. "Accept-Ranges: bytes\r\n"
  5995. "%s%s\r\n",
  5996. lm,
  5997. etag,
  5998. (int)mime_vec.len,
  5999. mime_vec.ptr,
  6000. cl,
  6001. suggest_connection_header(conn),
  6002. range,
  6003. encoding);
  6004. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  6005. send_file_data(conn, filep, r1, cl);
  6006. }
  6007. mg_fclose(filep);
  6008. }
  6009. #if !defined(NO_CACHING)
  6010. static void
  6011. handle_not_modified_static_file_request(struct mg_connection *conn,
  6012. struct file *filep)
  6013. {
  6014. char date[64], lm[64], etag[64];
  6015. time_t curtime = time(NULL);
  6016. if (conn == NULL || filep == NULL) {
  6017. return;
  6018. }
  6019. conn->status_code = 304;
  6020. gmt_time_string(date, sizeof(date), &curtime);
  6021. gmt_time_string(lm, sizeof(lm), &filep->last_modified);
  6022. construct_etag(etag, sizeof(etag), filep);
  6023. (void)mg_printf(conn,
  6024. "HTTP/1.1 %d %s\r\n"
  6025. "Date: %s\r\n",
  6026. conn->status_code,
  6027. mg_get_response_code_text(conn, conn->status_code),
  6028. date);
  6029. send_static_cache_header(conn);
  6030. (void)mg_printf(conn,
  6031. "Last-Modified: %s\r\n"
  6032. "Etag: %s\r\n"
  6033. "Connection: %s\r\n"
  6034. "\r\n",
  6035. lm,
  6036. etag,
  6037. suggest_connection_header(conn));
  6038. }
  6039. #endif
  6040. void
  6041. mg_send_file(struct mg_connection *conn, const char *path)
  6042. {
  6043. mg_send_mime_file(conn, path, NULL);
  6044. }
  6045. void
  6046. mg_send_mime_file(struct mg_connection *conn,
  6047. const char *path,
  6048. const char *mime_type)
  6049. {
  6050. struct file file = STRUCT_FILE_INITIALIZER;
  6051. if (mg_stat(conn, path, &file)) {
  6052. if (file.is_directory) {
  6053. if (!conn) {
  6054. return;
  6055. }
  6056. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  6057. "yes")) {
  6058. handle_directory_request(conn, path);
  6059. } else {
  6060. send_http_error(conn,
  6061. 403,
  6062. "%s",
  6063. "Error: Directory listing denied");
  6064. }
  6065. } else {
  6066. handle_static_file_request(conn, path, &file, mime_type);
  6067. }
  6068. } else {
  6069. send_http_error(conn, 404, "%s", "Error: File not found");
  6070. }
  6071. }
  6072. /* For a given PUT path, create all intermediate subdirectories.
  6073. * Return 0 if the path itself is a directory.
  6074. * Return 1 if the path leads to a file.
  6075. * Return -1 for if the path is too long.
  6076. * Return -2 if path can not be created.
  6077. */
  6078. static int
  6079. put_dir(struct mg_connection *conn, const char *path)
  6080. {
  6081. char buf[PATH_MAX];
  6082. const char *s, *p;
  6083. struct file file = STRUCT_FILE_INITIALIZER;
  6084. size_t len;
  6085. int res = 1;
  6086. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  6087. len = (size_t)(p - path);
  6088. if (len >= sizeof(buf)) {
  6089. /* path too long */
  6090. res = -1;
  6091. break;
  6092. }
  6093. memcpy(buf, path, len);
  6094. buf[len] = '\0';
  6095. /* Try to create intermediate directory */
  6096. DEBUG_TRACE("mkdir(%s)", buf);
  6097. if (!mg_stat(conn, buf, &file) && mg_mkdir(conn, buf, 0755) != 0) {
  6098. /* path does not exixt and can not be created */
  6099. res = -2;
  6100. break;
  6101. }
  6102. /* Is path itself a directory? */
  6103. if (p[1] == '\0') {
  6104. res = 0;
  6105. }
  6106. }
  6107. return res;
  6108. }
  6109. static void
  6110. remove_bad_file(const struct mg_connection *conn, const char *path)
  6111. {
  6112. int r = mg_remove(conn, path);
  6113. if (r != 0) {
  6114. mg_cry(conn, "%s: Cannot remove invalid file %s", __func__, path);
  6115. }
  6116. }
  6117. long long
  6118. mg_store_body(struct mg_connection *conn, const char *path)
  6119. {
  6120. char buf[MG_BUF_LEN];
  6121. long long len = 0;
  6122. int ret, n;
  6123. struct file fi;
  6124. if (conn->consumed_content != 0) {
  6125. mg_cry(conn, "%s: Contents already consumed", __func__);
  6126. return -11;
  6127. }
  6128. ret = put_dir(conn, path);
  6129. if (ret < 0) {
  6130. /* -1 for path too long,
  6131. * -2 for path can not be created. */
  6132. return ret;
  6133. }
  6134. if (ret != 1) {
  6135. /* Return 0 means, path itself is a directory. */
  6136. return 0;
  6137. }
  6138. if (mg_fopen(conn, path, "w", &fi) == 0) {
  6139. return -12;
  6140. }
  6141. ret = mg_read(conn, buf, sizeof(buf));
  6142. while (ret > 0) {
  6143. n = (int)fwrite(buf, 1, (size_t)ret, fi.fp);
  6144. if (n != ret) {
  6145. mg_fclose(&fi);
  6146. remove_bad_file(conn, path);
  6147. return -13;
  6148. }
  6149. ret = mg_read(conn, buf, sizeof(buf));
  6150. }
  6151. /* TODO: mg_fclose should return an error,
  6152. * and every caller should check and handle it. */
  6153. if (fclose(fi.fp) != 0) {
  6154. remove_bad_file(conn, path);
  6155. return -14;
  6156. }
  6157. return len;
  6158. }
  6159. /* Parse HTTP headers from the given buffer, advance buf pointer
  6160. * to the point where parsing stopped.
  6161. * All parameters must be valid pointers (not NULL).
  6162. * Return <0 on error. */
  6163. static int
  6164. parse_http_headers(char **buf, struct mg_request_info *ri)
  6165. {
  6166. int i;
  6167. ri->num_headers = 0;
  6168. for (i = 0; i < (int)ARRAY_SIZE(ri->http_headers); i++) {
  6169. char *dp = *buf;
  6170. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  6171. dp++;
  6172. }
  6173. if (dp == *buf) {
  6174. /* End of headers reached. */
  6175. break;
  6176. }
  6177. if (*dp != ':') {
  6178. /* This is not a valid field. */
  6179. return -1;
  6180. }
  6181. /* End of header key (*dp == ':') */
  6182. /* Truncate here and set the key name */
  6183. *dp = 0;
  6184. ri->http_headers[i].name = *buf;
  6185. do {
  6186. dp++;
  6187. } while (*dp == ' ');
  6188. /* The rest of the line is the value */
  6189. ri->http_headers[i].value = dp;
  6190. *buf = dp + strcspn(dp, "\r\n");
  6191. if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) {
  6192. *buf = NULL;
  6193. }
  6194. ri->num_headers = i + 1;
  6195. if (*buf) {
  6196. (*buf)[0] = 0;
  6197. (*buf)[1] = 0;
  6198. *buf += 2;
  6199. } else {
  6200. *buf = dp;
  6201. break;
  6202. }
  6203. if ((*buf)[0] == '\r') {
  6204. /* This is the end of the header */
  6205. break;
  6206. }
  6207. }
  6208. return ri->num_headers;
  6209. }
  6210. static int
  6211. is_valid_http_method(const char *method)
  6212. {
  6213. return !strcmp(method, "GET") /* HTTP (RFC 2616) */
  6214. || !strcmp(method, "POST") /* HTTP (RFC 2616) */
  6215. || !strcmp(method, "HEAD") /* HTTP (RFC 2616) */
  6216. || !strcmp(method, "PUT") /* HTTP (RFC 2616) */
  6217. || !strcmp(method, "DELETE") /* HTTP (RFC 2616) */
  6218. || !strcmp(method, "OPTIONS") /* HTTP (RFC 2616) */
  6219. /* TRACE method (RFC 2616) is not supported for security reasons */
  6220. || !strcmp(method, "CONNECT") /* HTTP (RFC 2616) */
  6221. || !strcmp(method, "PROPFIND") /* WEBDAV (RFC 2518) */
  6222. || !strcmp(method, "MKCOL") /* WEBDAV (RFC 2518) */
  6223. /* Unsupported WEBDAV Methods: */
  6224. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  6225. /* + 11 methods from RFC 3253 */
  6226. /* ORDERPATCH (RFC 3648) */
  6227. /* ACL (RFC 3744) */
  6228. /* SEARCH (RFC 5323) */
  6229. /* + MicroSoft extensions
  6230. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  6231. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  6232. || !strcmp(method, "PATCH"); /* PATCH method (RFC 5789) */
  6233. }
  6234. /* Parse HTTP request, fill in mg_request_info structure.
  6235. * This function modifies the buffer by NUL-terminating
  6236. * HTTP request components, header names and header values.
  6237. * Parameters:
  6238. * buf (in/out): pointer to the HTTP header to parse and split
  6239. * len (in): length of HTTP header buffer
  6240. * re (out): parsed header as mg_request_info
  6241. * buf and ri must be valid pointers (not NULL), len>0.
  6242. * Returns <0 on error. */
  6243. static int
  6244. parse_http_message(char *buf, int len, struct mg_request_info *ri)
  6245. {
  6246. int is_request, request_length;
  6247. char *start_line;
  6248. request_length = get_request_len(buf, len);
  6249. if (request_length > 0) {
  6250. /* Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_addr,
  6251. * remote_port */
  6252. ri->remote_user = ri->request_method = ri->request_uri =
  6253. ri->http_version = NULL;
  6254. ri->num_headers = 0;
  6255. buf[request_length - 1] = '\0';
  6256. /* RFC says that all initial whitespaces should be ingored */
  6257. while (*buf != '\0' && isspace(*(unsigned char *)buf)) {
  6258. buf++;
  6259. }
  6260. start_line = skip(&buf, "\r\n");
  6261. ri->request_method = skip(&start_line, " ");
  6262. ri->request_uri = skip(&start_line, " ");
  6263. ri->http_version = start_line;
  6264. /* HTTP message could be either HTTP request:
  6265. * "GET / HTTP/1.0 ..."
  6266. * or a HTTP response:
  6267. * "HTTP/1.0 200 OK ..."
  6268. * otherwise it is invalid.
  6269. */
  6270. is_request = is_valid_http_method(ri->request_method);
  6271. if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0)
  6272. || (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
  6273. /* Not a valid request or response: invalid */
  6274. return -1;
  6275. }
  6276. if (is_request) {
  6277. ri->http_version += 5;
  6278. }
  6279. if (parse_http_headers(&buf, ri) < 0) {
  6280. /* Error while parsing headers */
  6281. return -1;
  6282. }
  6283. }
  6284. return request_length;
  6285. }
  6286. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  6287. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  6288. * buffer (which marks the end of HTTP request). Buffer buf may already
  6289. * have some data. The length of the data is stored in nread.
  6290. * Upon every read operation, increase nread by the number of bytes read. */
  6291. static int
  6292. read_request(FILE *fp,
  6293. struct mg_connection *conn,
  6294. char *buf,
  6295. int bufsiz,
  6296. int *nread)
  6297. {
  6298. int request_len, n = 0;
  6299. struct timespec last_action_time;
  6300. double request_timeout;
  6301. if (!conn) {
  6302. return 0;
  6303. }
  6304. memset(&last_action_time, 0, sizeof(last_action_time));
  6305. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  6306. /* value of request_timeout is in seconds, config in milliseconds */
  6307. request_timeout = atof(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  6308. } else {
  6309. request_timeout = -1.0;
  6310. }
  6311. request_len = get_request_len(buf, *nread);
  6312. /* first time reading from this connection */
  6313. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  6314. while (
  6315. (conn->ctx->stop_flag == 0) && (*nread < bufsiz) && (request_len == 0)
  6316. && ((mg_difftimespec(&last_action_time, &(conn->req_time))
  6317. <= request_timeout) || (request_timeout < 0))
  6318. && ((n = pull(fp, conn, buf + *nread, bufsiz - *nread, request_timeout))
  6319. > 0)) {
  6320. *nread += n;
  6321. /* assert(*nread <= bufsiz); */
  6322. if (*nread > bufsiz) {
  6323. return -2;
  6324. }
  6325. request_len = get_request_len(buf, *nread);
  6326. if (request_timeout > 0.0) {
  6327. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  6328. }
  6329. }
  6330. return ((request_len <= 0) && (n <= 0)) ? -1 : request_len;
  6331. }
  6332. #if !defined(NO_FILES)
  6333. /* For given directory path, substitute it to valid index file.
  6334. * Return 1 if index file has been found, 0 if not found.
  6335. * If the file is found, it's stats is returned in stp. */
  6336. static int
  6337. substitute_index_file(struct mg_connection *conn,
  6338. char *path,
  6339. size_t path_len,
  6340. struct file *filep)
  6341. {
  6342. if (conn && conn->ctx) {
  6343. const char *list = conn->ctx->config[INDEX_FILES];
  6344. struct file file = STRUCT_FILE_INITIALIZER;
  6345. struct vec filename_vec;
  6346. size_t n = strlen(path);
  6347. int found = 0;
  6348. /* The 'path' given to us points to the directory. Remove all trailing
  6349. * directory separator characters from the end of the path, and
  6350. * then append single directory separator character. */
  6351. while (n > 0 && path[n - 1] == '/') {
  6352. n--;
  6353. }
  6354. path[n] = '/';
  6355. /* Traverse index files list. For each entry, append it to the given
  6356. * path and see if the file exists. If it exists, break the loop */
  6357. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6358. /* Ignore too long entries that may overflow path buffer */
  6359. if (filename_vec.len > path_len - (n + 2)) {
  6360. continue;
  6361. }
  6362. /* Prepare full path to the index file */
  6363. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6364. /* Does it exist? */
  6365. if (mg_stat(conn, path, &file)) {
  6366. /* Yes it does, break the loop */
  6367. *filep = file;
  6368. found = 1;
  6369. break;
  6370. }
  6371. }
  6372. /* If no index file exists, restore directory path */
  6373. if (!found) {
  6374. path[n] = '\0';
  6375. }
  6376. return found;
  6377. }
  6378. return 0;
  6379. }
  6380. #endif
  6381. #if !defined(NO_CACHING)
  6382. /* Return True if we should reply 304 Not Modified. */
  6383. static int
  6384. is_not_modified(const struct mg_connection *conn, const struct file *filep)
  6385. {
  6386. char etag[64];
  6387. const char *ims = mg_get_header(conn, "If-Modified-Since");
  6388. const char *inm = mg_get_header(conn, "If-None-Match");
  6389. construct_etag(etag, sizeof(etag), filep);
  6390. if (!filep) {
  6391. return 0;
  6392. }
  6393. return (inm != NULL && !mg_strcasecmp(etag, inm))
  6394. || (ims != NULL && (filep->last_modified <= parse_date_string(ims)));
  6395. }
  6396. #endif /* !NO_CACHING */
  6397. #if !defined(NO_CGI) || !defined(NO_FILES)
  6398. static int
  6399. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  6400. {
  6401. const char *expect, *body;
  6402. char buf[MG_BUF_LEN];
  6403. int to_read, nread, success = 0;
  6404. int64_t buffered_len;
  6405. double timeout = -1.0;
  6406. if (!conn) {
  6407. return 0;
  6408. }
  6409. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  6410. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  6411. }
  6412. expect = mg_get_header(conn, "Expect");
  6413. /* assert(fp != NULL); */
  6414. if (!fp) {
  6415. send_http_error(conn, 500, "%s", "Error: NULL File");
  6416. return 0;
  6417. }
  6418. if (conn->content_len == -1 && !conn->is_chunked) {
  6419. /* Content length is not specified by the client. */
  6420. send_http_error(conn,
  6421. 411,
  6422. "%s",
  6423. "Error: Client did not specify content length");
  6424. } else if ((expect != NULL)
  6425. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  6426. /* Client sent an "Expect: xyz" header and xyz is not 100-continue. */
  6427. send_http_error(conn,
  6428. 417,
  6429. "Error: Can not fulfill expectation %s",
  6430. expect);
  6431. } else {
  6432. if (expect != NULL) {
  6433. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  6434. conn->status_code = 100;
  6435. } else {
  6436. conn->status_code = 200;
  6437. }
  6438. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  6439. - conn->consumed_content;
  6440. /* assert(buffered_len >= 0); */
  6441. /* assert(conn->consumed_content == 0); */
  6442. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  6443. send_http_error(conn, 500, "%s", "Error: Size mismatch");
  6444. return 0;
  6445. }
  6446. if (buffered_len > 0) {
  6447. if ((int64_t)buffered_len > conn->content_len) {
  6448. buffered_len = (int)conn->content_len;
  6449. }
  6450. body = conn->buf + conn->request_len + conn->consumed_content;
  6451. push_all(conn->ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  6452. conn->consumed_content += buffered_len;
  6453. }
  6454. nread = 0;
  6455. while (conn->consumed_content < conn->content_len) {
  6456. to_read = sizeof(buf);
  6457. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  6458. to_read = (int)(conn->content_len - conn->consumed_content);
  6459. }
  6460. nread = pull(NULL, conn, buf, to_read, timeout);
  6461. if (nread <= 0
  6462. || push_all(conn->ctx, fp, sock, ssl, buf, nread) != nread) {
  6463. break;
  6464. }
  6465. conn->consumed_content += nread;
  6466. }
  6467. if (conn->consumed_content == conn->content_len) {
  6468. success = (nread >= 0);
  6469. }
  6470. /* Each error code path in this function must send an error */
  6471. if (!success) {
  6472. /* NOTE: Maybe some data has already been sent. */
  6473. /* TODO (low): If some data has been sent, a correct error
  6474. * reply can no longer be sent, so just close the connection */
  6475. send_http_error(conn, 500, "%s", "");
  6476. }
  6477. }
  6478. return success;
  6479. }
  6480. #endif
  6481. #if !defined(NO_CGI)
  6482. /* This structure helps to create an environment for the spawned CGI program.
  6483. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  6484. * last element must be NULL.
  6485. * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  6486. * strings must reside in a contiguous buffer. The end of the buffer is
  6487. * marked by two '\0' characters.
  6488. * We satisfy both worlds: we create an envp array (which is vars), all
  6489. * entries are actually pointers inside buf. */
  6490. struct cgi_environment {
  6491. struct mg_connection *conn;
  6492. /* Data block */
  6493. char *buf; /* Environment buffer */
  6494. size_t buflen; /* Space available in buf */
  6495. size_t bufused; /* Space taken in buf */
  6496. /* Index block */
  6497. char **var; /* char **envp */
  6498. size_t varlen; /* Number of variables available in var */
  6499. size_t varused; /* Number of variables stored in var */
  6500. };
  6501. static void addenv(struct cgi_environment *env,
  6502. PRINTF_FORMAT_STRING(const char *fmt),
  6503. ...) PRINTF_ARGS(2, 3);
  6504. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  6505. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  6506. static void
  6507. addenv(struct cgi_environment *env, const char *fmt, ...)
  6508. {
  6509. size_t n, space;
  6510. int truncated;
  6511. char *added;
  6512. va_list ap;
  6513. /* Calculate how much space is left in the buffer */
  6514. space = (env->buflen - env->bufused);
  6515. /* Calculate an estimate for the required space */
  6516. n = strlen(fmt) + 2 + 128;
  6517. do {
  6518. if (space <= n) {
  6519. /* Allocate new buffer */
  6520. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  6521. added = (char *)mg_realloc(env->buf, n);
  6522. if (!added) {
  6523. /* Out of memory */
  6524. mg_cry(env->conn,
  6525. "%s: Cannot allocate memory for CGI variable [%s]",
  6526. __func__,
  6527. fmt);
  6528. return;
  6529. }
  6530. env->buf = added;
  6531. env->buflen = n;
  6532. space = (env->buflen - env->bufused);
  6533. }
  6534. /* Make a pointer to the free space int the buffer */
  6535. added = env->buf + env->bufused;
  6536. /* Copy VARIABLE=VALUE\0 string into the free space */
  6537. va_start(ap, fmt);
  6538. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  6539. va_end(ap);
  6540. /* Do not add truncated strings to the environment */
  6541. if (truncated) {
  6542. /* Reallocate the buffer */
  6543. space = 0;
  6544. n = 1;
  6545. }
  6546. } while (truncated);
  6547. /* Calculate number of bytes added to the environment */
  6548. n = strlen(added) + 1;
  6549. env->bufused += n;
  6550. /* Now update the variable index */
  6551. space = (env->varlen - env->varused);
  6552. if (space < 2) {
  6553. mg_cry(env->conn,
  6554. "%s: Cannot register CGI variable [%s]",
  6555. __func__,
  6556. fmt);
  6557. return;
  6558. }
  6559. /* Append a pointer to the added string into the envp array */
  6560. env->var[env->varused] = added;
  6561. env->varused++;
  6562. }
  6563. static void
  6564. prepare_cgi_environment(struct mg_connection *conn,
  6565. const char *prog,
  6566. struct cgi_environment *env)
  6567. {
  6568. const char *s;
  6569. struct vec var_vec;
  6570. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  6571. int i, truncated;
  6572. if (conn == NULL || prog == NULL || env == NULL) {
  6573. return;
  6574. }
  6575. env->conn = conn;
  6576. env->buflen = CGI_ENVIRONMENT_SIZE;
  6577. env->bufused = 0;
  6578. env->buf = (char *)mg_malloc(env->buflen);
  6579. env->varlen = MAX_CGI_ENVIR_VARS;
  6580. env->varused = 0;
  6581. env->var = (char **)mg_malloc(env->buflen * sizeof(char *));
  6582. addenv(env, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  6583. addenv(env, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6584. addenv(env, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6585. addenv(env, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  6586. /* Prepare the environment block */
  6587. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  6588. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  6589. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  6590. #if defined(USE_IPV6)
  6591. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  6592. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  6593. } else
  6594. #endif
  6595. {
  6596. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  6597. }
  6598. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  6599. addenv(env, "REMOTE_ADDR=%s", src_addr);
  6600. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  6601. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  6602. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  6603. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  6604. /* SCRIPT_NAME */
  6605. addenv(env,
  6606. "SCRIPT_NAME=%.*s",
  6607. (int)strlen(conn->request_info.local_uri)
  6608. - ((conn->path_info == NULL) ? 0 : (int)strlen(conn->path_info)),
  6609. conn->request_info.local_uri);
  6610. addenv(env, "SCRIPT_FILENAME=%s", prog);
  6611. if (conn->path_info == NULL) {
  6612. addenv(env, "PATH_TRANSLATED=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6613. } else {
  6614. addenv(env,
  6615. "PATH_TRANSLATED=%s%s",
  6616. conn->ctx->config[DOCUMENT_ROOT],
  6617. conn->path_info);
  6618. }
  6619. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  6620. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  6621. addenv(env, "CONTENT_TYPE=%s", s);
  6622. }
  6623. if (conn->request_info.query_string != NULL) {
  6624. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  6625. }
  6626. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  6627. addenv(env, "CONTENT_LENGTH=%s", s);
  6628. }
  6629. if ((s = getenv("PATH")) != NULL) {
  6630. addenv(env, "PATH=%s", s);
  6631. }
  6632. if (conn->path_info != NULL) {
  6633. addenv(env, "PATH_INFO=%s", conn->path_info);
  6634. }
  6635. if (conn->status_code > 0) {
  6636. /* CGI error handler should show the status code */
  6637. addenv(env, "STATUS=%d", conn->status_code);
  6638. }
  6639. #if defined(_WIN32)
  6640. if ((s = getenv("COMSPEC")) != NULL) {
  6641. addenv(env, "COMSPEC=%s", s);
  6642. }
  6643. if ((s = getenv("SYSTEMROOT")) != NULL) {
  6644. addenv(env, "SYSTEMROOT=%s", s);
  6645. }
  6646. if ((s = getenv("SystemDrive")) != NULL) {
  6647. addenv(env, "SystemDrive=%s", s);
  6648. }
  6649. if ((s = getenv("ProgramFiles")) != NULL) {
  6650. addenv(env, "ProgramFiles=%s", s);
  6651. }
  6652. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  6653. addenv(env, "ProgramFiles(x86)=%s", s);
  6654. }
  6655. #else
  6656. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  6657. addenv(env, "LD_LIBRARY_PATH=%s", s);
  6658. }
  6659. #endif /* _WIN32 */
  6660. if ((s = getenv("PERLLIB")) != NULL) {
  6661. addenv(env, "PERLLIB=%s", s);
  6662. }
  6663. if (conn->request_info.remote_user != NULL) {
  6664. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  6665. addenv(env, "%s", "AUTH_TYPE=Digest");
  6666. }
  6667. /* Add all headers as HTTP_* variables */
  6668. for (i = 0; i < conn->request_info.num_headers; i++) {
  6669. (void)mg_snprintf(conn,
  6670. &truncated,
  6671. http_var_name,
  6672. sizeof(http_var_name),
  6673. "HTTP_%s",
  6674. conn->request_info.http_headers[i].name);
  6675. if (truncated) {
  6676. mg_cry(conn,
  6677. "%s: HTTP header variable too long [%s]",
  6678. __func__,
  6679. conn->request_info.http_headers[i].name);
  6680. continue;
  6681. }
  6682. /* Convert variable name into uppercase, and change - to _ */
  6683. for (p = http_var_name; *p != '\0'; p++) {
  6684. if (*p == '-') {
  6685. *p = '_';
  6686. }
  6687. *p = (char)toupper(*(unsigned char *)p);
  6688. }
  6689. addenv(env,
  6690. "%s=%s",
  6691. http_var_name,
  6692. conn->request_info.http_headers[i].value);
  6693. }
  6694. /* Add user-specified variables */
  6695. s = conn->ctx->config[CGI_ENVIRONMENT];
  6696. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  6697. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  6698. }
  6699. env->var[env->varused] = NULL;
  6700. env->buf[env->bufused] = '\0';
  6701. }
  6702. static void
  6703. handle_cgi_request(struct mg_connection *conn, const char *prog)
  6704. {
  6705. char *buf;
  6706. size_t buflen;
  6707. int headers_len, data_len, i, truncated;
  6708. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  6709. const char *status, *status_text, *connection_state;
  6710. char *pbuf, dir[PATH_MAX], *p;
  6711. struct mg_request_info ri;
  6712. struct cgi_environment blk;
  6713. FILE *in = NULL, *out = NULL, *err = NULL;
  6714. struct file fout = STRUCT_FILE_INITIALIZER;
  6715. pid_t pid = (pid_t)-1;
  6716. if (conn == NULL) {
  6717. return;
  6718. }
  6719. buf = NULL;
  6720. buflen = 16384;
  6721. prepare_cgi_environment(conn, prog, &blk);
  6722. /* CGI must be executed in its own directory. 'dir' must point to the
  6723. * directory containing executable program, 'p' must point to the
  6724. * executable program name relative to 'dir'. */
  6725. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  6726. if (truncated) {
  6727. mg_cry(conn, "Error: CGI program \"%s\": Path too long", prog);
  6728. send_http_error(conn, 500, "Error: %s", "CGI path too long");
  6729. goto done;
  6730. }
  6731. if ((p = strrchr(dir, '/')) != NULL) {
  6732. *p++ = '\0';
  6733. } else {
  6734. dir[0] = '.', dir[1] = '\0';
  6735. p = (char *)prog;
  6736. }
  6737. if (pipe(fdin) != 0 || pipe(fdout) != 0 || pipe(fderr) != 0) {
  6738. status = strerror(ERRNO);
  6739. mg_cry(conn,
  6740. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  6741. prog,
  6742. status);
  6743. send_http_error(conn, 500, "Error: Cannot create CGI pipe: %s", status);
  6744. goto done;
  6745. }
  6746. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  6747. if (pid == (pid_t)-1) {
  6748. status = strerror(ERRNO);
  6749. mg_cry(conn,
  6750. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  6751. prog,
  6752. status);
  6753. send_http_error(conn,
  6754. 500,
  6755. "Error: Cannot spawn CGI process [%s]: %s",
  6756. prog,
  6757. status);
  6758. goto done;
  6759. }
  6760. /* Make sure child closes all pipe descriptors. It must dup them to 0,1 */
  6761. set_close_on_exec((SOCKET)fdin[0], conn); /* stdin read */
  6762. set_close_on_exec((SOCKET)fdout[1], conn); /* stdout write */
  6763. set_close_on_exec((SOCKET)fderr[1], conn); /* stderr write */
  6764. set_close_on_exec((SOCKET)fdin[1], conn); /* stdin write */
  6765. set_close_on_exec((SOCKET)fdout[0], conn); /* stdout read */
  6766. set_close_on_exec((SOCKET)fderr[0], conn); /* stderr read */
  6767. /* Parent closes only one side of the pipes.
  6768. * If we don't mark them as closed, close() attempt before
  6769. * return from this function throws an exception on Windows.
  6770. * Windows does not like when closed descriptor is closed again. */
  6771. (void)close(fdin[0]);
  6772. (void)close(fdout[1]);
  6773. (void)close(fderr[1]);
  6774. fdin[0] = fdout[1] = fderr[1] = -1;
  6775. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  6776. status = strerror(ERRNO);
  6777. mg_cry(conn,
  6778. "Error: CGI program \"%s\": Can not open stdin: %s",
  6779. prog,
  6780. status);
  6781. send_http_error(conn,
  6782. 500,
  6783. "Error: CGI can not open fdin\nfopen: %s",
  6784. status);
  6785. goto done;
  6786. }
  6787. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  6788. status = strerror(ERRNO);
  6789. mg_cry(conn,
  6790. "Error: CGI program \"%s\": Can not open stdout: %s",
  6791. prog,
  6792. status);
  6793. send_http_error(conn,
  6794. 500,
  6795. "Error: CGI can not open fdout\nfopen: %s",
  6796. status);
  6797. goto done;
  6798. }
  6799. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  6800. status = strerror(ERRNO);
  6801. mg_cry(conn,
  6802. "Error: CGI program \"%s\": Can not open stderr: %s",
  6803. prog,
  6804. status);
  6805. send_http_error(conn,
  6806. 500,
  6807. "Error: CGI can not open fdout\nfopen: %s",
  6808. status);
  6809. goto done;
  6810. }
  6811. setbuf(in, NULL);
  6812. setbuf(out, NULL);
  6813. setbuf(err, NULL);
  6814. fout.fp = out;
  6815. if ((conn->request_info.content_length > 0) || conn->is_chunked) {
  6816. /* This is a POST/PUT request, or another request with body data. */
  6817. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  6818. /* Error sending the body data */
  6819. mg_cry(conn,
  6820. "Error: CGI program \"%s\": Forward body data failed",
  6821. prog);
  6822. goto done;
  6823. }
  6824. }
  6825. /* Close so child gets an EOF. */
  6826. fclose(in);
  6827. in = NULL;
  6828. fdin[1] = -1;
  6829. /* Now read CGI reply into a buffer. We need to set correct
  6830. * status code, thus we need to see all HTTP headers first.
  6831. * Do not send anything back to client, until we buffer in all
  6832. * HTTP headers. */
  6833. data_len = 0;
  6834. buf = (char *)mg_malloc(buflen);
  6835. if (buf == NULL) {
  6836. send_http_error(conn,
  6837. 500,
  6838. "Error: Not enough memory for CGI buffer (%u bytes)",
  6839. (unsigned int)buflen);
  6840. mg_cry(conn,
  6841. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  6842. "bytes)",
  6843. prog,
  6844. (unsigned int)buflen);
  6845. goto done;
  6846. }
  6847. headers_len = read_request(out, conn, buf, (int)buflen, &data_len);
  6848. if (headers_len <= 0) {
  6849. /* Could not parse the CGI response. Check if some error message on
  6850. * stderr. */
  6851. i = pull_all(err, conn, buf, (int)buflen);
  6852. if (i > 0) {
  6853. mg_cry(conn,
  6854. "Error: CGI program \"%s\" sent error "
  6855. "message: [%.*s]",
  6856. prog,
  6857. i,
  6858. buf);
  6859. send_http_error(conn,
  6860. 500,
  6861. "Error: CGI program \"%s\" sent error "
  6862. "message: [%.*s]",
  6863. prog,
  6864. i,
  6865. buf);
  6866. } else {
  6867. mg_cry(conn,
  6868. "Error: CGI program sent malformed or too big "
  6869. "(>%u bytes) HTTP headers: [%.*s]",
  6870. (unsigned)buflen,
  6871. data_len,
  6872. buf);
  6873. send_http_error(conn,
  6874. 500,
  6875. "Error: CGI program sent malformed or too big "
  6876. "(>%u bytes) HTTP headers: [%.*s]",
  6877. (unsigned)buflen,
  6878. data_len,
  6879. buf);
  6880. }
  6881. goto done;
  6882. }
  6883. pbuf = buf;
  6884. buf[headers_len - 1] = '\0';
  6885. parse_http_headers(&pbuf, &ri);
  6886. /* Make up and send the status line */
  6887. status_text = "OK";
  6888. if ((status = get_header(&ri, "Status")) != NULL) {
  6889. conn->status_code = atoi(status);
  6890. status_text = status;
  6891. while (isdigit(*(const unsigned char *)status_text)
  6892. || *status_text == ' ') {
  6893. status_text++;
  6894. }
  6895. } else if (get_header(&ri, "Location") != NULL) {
  6896. conn->status_code = 302;
  6897. } else {
  6898. conn->status_code = 200;
  6899. }
  6900. connection_state = get_header(&ri, "Connection");
  6901. if (!header_has_option(connection_state, "keep-alive")) {
  6902. conn->must_close = 1;
  6903. }
  6904. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  6905. /* Send headers */
  6906. for (i = 0; i < ri.num_headers; i++) {
  6907. mg_printf(conn,
  6908. "%s: %s\r\n",
  6909. ri.http_headers[i].name,
  6910. ri.http_headers[i].value);
  6911. }
  6912. mg_write(conn, "\r\n", 2);
  6913. /* Send chunk of data that may have been read after the headers */
  6914. conn->num_bytes_sent +=
  6915. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  6916. /* Read the rest of CGI output and send to the client */
  6917. send_file_data(conn, &fout, 0, INT64_MAX);
  6918. done:
  6919. mg_free(blk.var);
  6920. mg_free(blk.buf);
  6921. if (pid != (pid_t)-1) {
  6922. kill(pid, SIGKILL);
  6923. #if !defined(_WIN32)
  6924. {
  6925. int st;
  6926. while (waitpid(pid, &st, 0) != -1)
  6927. ; /* clean zombies */
  6928. }
  6929. #endif
  6930. }
  6931. if (fdin[0] != -1) {
  6932. close(fdin[0]);
  6933. }
  6934. if (fdout[1] != -1) {
  6935. close(fdout[1]);
  6936. }
  6937. if (in != NULL) {
  6938. fclose(in);
  6939. } else if (fdin[1] != -1) {
  6940. close(fdin[1]);
  6941. }
  6942. if (out != NULL) {
  6943. fclose(out);
  6944. } else if (fdout[0] != -1) {
  6945. close(fdout[0]);
  6946. }
  6947. if (err != NULL) {
  6948. fclose(err);
  6949. } else if (fderr[0] != -1) {
  6950. close(fderr[0]);
  6951. }
  6952. if (buf != NULL) {
  6953. mg_free(buf);
  6954. }
  6955. }
  6956. #endif /* !NO_CGI */
  6957. #if !defined(NO_FILES)
  6958. static void
  6959. mkcol(struct mg_connection *conn, const char *path)
  6960. {
  6961. int rc, body_len;
  6962. struct de de;
  6963. char date[64];
  6964. time_t curtime = time(NULL);
  6965. if (conn == NULL) {
  6966. return;
  6967. }
  6968. /* TODO (mid): Check the send_http_error situations in this function */
  6969. memset(&de.file, 0, sizeof(de.file));
  6970. if (!mg_stat(conn, path, &de.file)) {
  6971. mg_cry(conn,
  6972. "%s: mg_stat(%s) failed: %s",
  6973. __func__,
  6974. path,
  6975. strerror(ERRNO));
  6976. }
  6977. if (de.file.last_modified) {
  6978. /* TODO (high): This check does not seem to make any sense ! */
  6979. send_http_error(
  6980. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6981. return;
  6982. }
  6983. body_len = conn->data_len - conn->request_len;
  6984. if (body_len > 0) {
  6985. send_http_error(
  6986. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6987. return;
  6988. }
  6989. rc = mg_mkdir(conn, path, 0755);
  6990. if (rc == 0) {
  6991. conn->status_code = 201;
  6992. gmt_time_string(date, sizeof(date), &curtime);
  6993. mg_printf(conn,
  6994. "HTTP/1.1 %d Created\r\n"
  6995. "Date: %s\r\n",
  6996. conn->status_code,
  6997. date);
  6998. send_static_cache_header(conn);
  6999. mg_printf(conn,
  7000. "Content-Length: 0\r\n"
  7001. "Connection: %s\r\n\r\n",
  7002. suggest_connection_header(conn));
  7003. } else if (rc == -1) {
  7004. if (errno == EEXIST) {
  7005. send_http_error(
  7006. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7007. } else if (errno == EACCES) {
  7008. send_http_error(
  7009. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7010. } else if (errno == ENOENT) {
  7011. send_http_error(
  7012. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7013. } else {
  7014. send_http_error(conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  7015. }
  7016. }
  7017. }
  7018. static void
  7019. put_file(struct mg_connection *conn, const char *path)
  7020. {
  7021. struct file file = STRUCT_FILE_INITIALIZER;
  7022. const char *range;
  7023. int64_t r1, r2;
  7024. int rc;
  7025. char date[64];
  7026. time_t curtime = time(NULL);
  7027. if (conn == NULL) {
  7028. return;
  7029. }
  7030. if (mg_stat(conn, path, &file)) {
  7031. /* File already exists */
  7032. conn->status_code = 200;
  7033. if (file.is_directory) {
  7034. /* This is an already existing directory,
  7035. * so there is nothing to do for the server. */
  7036. rc = 0;
  7037. } else {
  7038. /* File exists and is not a directory. */
  7039. /* Can it be replaced? */
  7040. if (file.membuf != NULL) {
  7041. /* This is an "in-memory" file, that can not be replaced */
  7042. send_http_error(
  7043. conn,
  7044. 405,
  7045. "Error: Put not possible\nReplacing %s is not supported",
  7046. path);
  7047. return;
  7048. }
  7049. /* Check if the server may write this file */
  7050. if (access(path, W_OK) == 0) {
  7051. /* Access granted */
  7052. conn->status_code = 200;
  7053. rc = 1;
  7054. } else {
  7055. send_http_error(
  7056. conn,
  7057. 403,
  7058. "Error: Put not possible\nReplacing %s is not allowed",
  7059. path);
  7060. return;
  7061. }
  7062. }
  7063. } else {
  7064. /* File should be created */
  7065. conn->status_code = 201;
  7066. rc = put_dir(conn, path);
  7067. }
  7068. if (rc == 0) {
  7069. /* put_dir returns 0 if path is a directory */
  7070. gmt_time_string(date, sizeof(date), &curtime);
  7071. mg_printf(conn,
  7072. "HTTP/1.1 %d %s\r\n",
  7073. conn->status_code,
  7074. mg_get_response_code_text(NULL, conn->status_code));
  7075. send_no_cache_header(conn);
  7076. mg_printf(conn,
  7077. "Date: %s\r\n"
  7078. "Content-Length: 0\r\n"
  7079. "Connection: %s\r\n\r\n",
  7080. date,
  7081. suggest_connection_header(conn));
  7082. /* Request to create a directory has been fulfilled successfully.
  7083. * No need to put a file. */
  7084. return;
  7085. }
  7086. if (rc == -1) {
  7087. /* put_dir returns -1 if the path is too long */
  7088. send_http_error(conn,
  7089. 414,
  7090. "Error: Path too long\nput_dir(%s): %s",
  7091. path,
  7092. strerror(ERRNO));
  7093. return;
  7094. }
  7095. if (rc == -2) {
  7096. /* put_dir returns -2 if the directory can not be created */
  7097. send_http_error(conn,
  7098. 500,
  7099. "Error: Can not create directory\nput_dir(%s): %s",
  7100. path,
  7101. strerror(ERRNO));
  7102. return;
  7103. }
  7104. /* A file should be created or overwritten. */
  7105. if (!mg_fopen(conn, path, "wb+", &file) || file.fp == NULL) {
  7106. mg_fclose(&file);
  7107. send_http_error(conn,
  7108. 500,
  7109. "Error: Can not create file\nfopen(%s): %s",
  7110. path,
  7111. strerror(ERRNO));
  7112. return;
  7113. }
  7114. fclose_on_exec(&file, conn);
  7115. range = mg_get_header(conn, "Content-Range");
  7116. r1 = r2 = 0;
  7117. if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
  7118. conn->status_code = 206; /* Partial content */
  7119. fseeko(file.fp, r1, SEEK_SET);
  7120. }
  7121. if (!forward_body_data(conn, file.fp, INVALID_SOCKET, NULL)) {
  7122. /* forward_body_data failed.
  7123. * The error code has already been sent to the client,
  7124. * and conn->status_code is already set. */
  7125. mg_fclose(&file);
  7126. return;
  7127. }
  7128. gmt_time_string(date, sizeof(date), &curtime);
  7129. mg_printf(conn,
  7130. "HTTP/1.1 %d %s\r\n",
  7131. conn->status_code,
  7132. mg_get_response_code_text(NULL, conn->status_code));
  7133. send_no_cache_header(conn);
  7134. mg_printf(conn,
  7135. "Date: %s\r\n"
  7136. "Content-Length: 0\r\n"
  7137. "Connection: %s\r\n\r\n",
  7138. date,
  7139. suggest_connection_header(conn));
  7140. mg_fclose(&file);
  7141. }
  7142. static void
  7143. delete_file(struct mg_connection *conn, const char *path)
  7144. {
  7145. struct de de;
  7146. memset(&de.file, 0, sizeof(de.file));
  7147. if (!mg_stat(conn, path, &de.file)) {
  7148. /* mg_stat returns 0 if the file does not exist */
  7149. send_http_error(conn,
  7150. 404,
  7151. "Error: Cannot delete file\nFile %s not found",
  7152. path);
  7153. return;
  7154. }
  7155. if (de.file.membuf != NULL) {
  7156. /* the file is cached in memory */
  7157. send_http_error(
  7158. conn,
  7159. 405,
  7160. "Error: Delete not possible\nDeleting %s is not supported",
  7161. path);
  7162. return;
  7163. }
  7164. if (de.file.is_directory) {
  7165. if (remove_directory(conn, path)) {
  7166. /* Delete is successful: Return 204 without content. */
  7167. send_http_error(conn, 204, "%s", "");
  7168. } else {
  7169. /* Delete is not successful: Return 500 (Server error). */
  7170. send_http_error(conn, 500, "Error: Could not delete %s", path);
  7171. }
  7172. return;
  7173. }
  7174. /* This is an existing file (not a directory).
  7175. * Check if write permission is granted. */
  7176. if (access(path, W_OK) != 0) {
  7177. /* File is read only */
  7178. send_http_error(
  7179. conn,
  7180. 403,
  7181. "Error: Delete not possible\nDeleting %s is not allowed",
  7182. path);
  7183. return;
  7184. }
  7185. /* Try to delete it. */
  7186. if (mg_remove(conn, path) == 0) {
  7187. /* Delete was successful: Return 204 without content. */
  7188. send_http_error(conn, 204, "%s", "");
  7189. } else {
  7190. /* Delete not successful (file locked). */
  7191. send_http_error(conn,
  7192. 423,
  7193. "Error: Cannot delete file\nremove(%s): %s",
  7194. path,
  7195. strerror(ERRNO));
  7196. }
  7197. }
  7198. #endif /* !NO_FILES */
  7199. static void
  7200. send_ssi_file(struct mg_connection *, const char *, struct file *, int);
  7201. static void
  7202. do_ssi_include(struct mg_connection *conn,
  7203. const char *ssi,
  7204. char *tag,
  7205. int include_level)
  7206. {
  7207. char file_name[MG_BUF_LEN], path[512], *p;
  7208. struct file file = STRUCT_FILE_INITIALIZER;
  7209. size_t len;
  7210. int truncated = 0;
  7211. if (conn == NULL) {
  7212. return;
  7213. }
  7214. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  7215. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  7216. * always < MG_BUF_LEN. */
  7217. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  7218. /* File name is relative to the webserver root */
  7219. file_name[511] = 0;
  7220. (void)mg_snprintf(conn,
  7221. &truncated,
  7222. path,
  7223. sizeof(path),
  7224. "%s/%s",
  7225. conn->ctx->config[DOCUMENT_ROOT],
  7226. file_name);
  7227. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  7228. /* File name is relative to the webserver working directory
  7229. * or it is absolute system path */
  7230. file_name[511] = 0;
  7231. (void)
  7232. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  7233. } else if (sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1
  7234. || sscanf(tag, " \"%511[^\"]\"", file_name) == 1) {
  7235. /* File name is relative to the currect document */
  7236. file_name[511] = 0;
  7237. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  7238. if (!truncated) {
  7239. if ((p = strrchr(path, '/')) != NULL) {
  7240. p[1] = '\0';
  7241. }
  7242. len = strlen(path);
  7243. (void)mg_snprintf(conn,
  7244. &truncated,
  7245. path + len,
  7246. sizeof(path) - len,
  7247. "%s",
  7248. file_name);
  7249. }
  7250. } else {
  7251. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  7252. return;
  7253. }
  7254. if (truncated) {
  7255. mg_cry(conn, "SSI #include path length overflow: [%s]", tag);
  7256. return;
  7257. }
  7258. if (!mg_fopen(conn, path, "rb", &file)) {
  7259. mg_cry(conn,
  7260. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  7261. tag,
  7262. path,
  7263. strerror(ERRNO));
  7264. } else {
  7265. fclose_on_exec(&file, conn);
  7266. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  7267. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  7268. path) > 0) {
  7269. send_ssi_file(conn, path, &file, include_level + 1);
  7270. } else {
  7271. send_file_data(conn, &file, 0, INT64_MAX);
  7272. }
  7273. mg_fclose(&file);
  7274. }
  7275. }
  7276. #if !defined(NO_POPEN)
  7277. static void
  7278. do_ssi_exec(struct mg_connection *conn, char *tag)
  7279. {
  7280. char cmd[1024] = "";
  7281. struct file file = STRUCT_FILE_INITIALIZER;
  7282. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  7283. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  7284. } else {
  7285. cmd[1023] = 0;
  7286. if ((file.fp = popen(cmd, "r")) == NULL) {
  7287. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  7288. } else {
  7289. send_file_data(conn, &file, 0, INT64_MAX);
  7290. pclose(file.fp);
  7291. }
  7292. }
  7293. }
  7294. #endif /* !NO_POPEN */
  7295. static int
  7296. mg_fgetc(struct file *filep, int offset)
  7297. {
  7298. if (filep == NULL) {
  7299. return EOF;
  7300. }
  7301. if (filep->membuf != NULL && offset >= 0
  7302. && ((unsigned int)(offset)) < filep->size) {
  7303. return ((const unsigned char *)filep->membuf)[offset];
  7304. } else if (filep->fp != NULL) {
  7305. return fgetc(filep->fp);
  7306. } else {
  7307. return EOF;
  7308. }
  7309. }
  7310. static void
  7311. send_ssi_file(struct mg_connection *conn,
  7312. const char *path,
  7313. struct file *filep,
  7314. int include_level)
  7315. {
  7316. char buf[MG_BUF_LEN];
  7317. int ch, offset, len, in_ssi_tag;
  7318. if (include_level > 10) {
  7319. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  7320. return;
  7321. }
  7322. in_ssi_tag = len = offset = 0;
  7323. while ((ch = mg_fgetc(filep, offset)) != EOF) {
  7324. if (in_ssi_tag && ch == '>') {
  7325. in_ssi_tag = 0;
  7326. buf[len++] = (char)ch;
  7327. buf[len] = '\0';
  7328. /* assert(len <= (int) sizeof(buf)); */
  7329. if (len > (int)sizeof(buf)) {
  7330. break;
  7331. }
  7332. if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
  7333. /* Not an SSI tag, pass it */
  7334. (void)mg_write(conn, buf, (size_t)len);
  7335. } else {
  7336. if (!memcmp(buf + 5, "include", 7)) {
  7337. do_ssi_include(conn, path, buf + 12, include_level);
  7338. #if !defined(NO_POPEN)
  7339. } else if (!memcmp(buf + 5, "exec", 4)) {
  7340. do_ssi_exec(conn, buf + 9);
  7341. #endif /* !NO_POPEN */
  7342. } else {
  7343. mg_cry(conn,
  7344. "%s: unknown SSI "
  7345. "command: \"%s\"",
  7346. path,
  7347. buf);
  7348. }
  7349. }
  7350. len = 0;
  7351. } else if (in_ssi_tag) {
  7352. if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
  7353. /* Not an SSI tag */
  7354. in_ssi_tag = 0;
  7355. } else if (len == (int)sizeof(buf) - 2) {
  7356. mg_cry(conn, "%s: SSI tag is too large", path);
  7357. len = 0;
  7358. }
  7359. buf[len++] = (char)(ch & 0xff);
  7360. } else if (ch == '<') {
  7361. in_ssi_tag = 1;
  7362. if (len > 0) {
  7363. mg_write(conn, buf, (size_t)len);
  7364. }
  7365. len = 0;
  7366. buf[len++] = (char)(ch & 0xff);
  7367. } else {
  7368. buf[len++] = (char)(ch & 0xff);
  7369. if (len == (int)sizeof(buf)) {
  7370. mg_write(conn, buf, (size_t)len);
  7371. len = 0;
  7372. }
  7373. }
  7374. }
  7375. /* Send the rest of buffered data */
  7376. if (len > 0) {
  7377. mg_write(conn, buf, (size_t)len);
  7378. }
  7379. }
  7380. static void
  7381. handle_ssi_file_request(struct mg_connection *conn,
  7382. const char *path,
  7383. struct file *filep)
  7384. {
  7385. char date[64];
  7386. time_t curtime = time(NULL);
  7387. const char *cors1, *cors2, *cors3;
  7388. if (conn == NULL || path == NULL || filep == NULL) {
  7389. return;
  7390. }
  7391. if (mg_get_header(conn, "Origin")) {
  7392. /* Cross-origin resource sharing (CORS). */
  7393. cors1 = "Access-Control-Allow-Origin: ";
  7394. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  7395. cors3 = "\r\n";
  7396. } else {
  7397. cors1 = cors2 = cors3 = "";
  7398. }
  7399. if (!mg_fopen(conn, path, "rb", filep)) {
  7400. /* File exists (precondition for calling this function),
  7401. * but can not be opened by the server. */
  7402. send_http_error(conn,
  7403. 500,
  7404. "Error: Cannot read file\nfopen(%s): %s",
  7405. path,
  7406. strerror(ERRNO));
  7407. } else {
  7408. conn->must_close = 1;
  7409. gmt_time_string(date, sizeof(date), &curtime);
  7410. fclose_on_exec(filep, conn);
  7411. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  7412. send_no_cache_header(conn);
  7413. mg_printf(conn,
  7414. "%s%s%s"
  7415. "Date: %s\r\n"
  7416. "Content-Type: text/html\r\n"
  7417. "Connection: %s\r\n\r\n",
  7418. cors1,
  7419. cors2,
  7420. cors3,
  7421. date,
  7422. suggest_connection_header(conn));
  7423. send_ssi_file(conn, path, filep, 0);
  7424. mg_fclose(filep);
  7425. }
  7426. }
  7427. #if !defined(NO_FILES)
  7428. static void
  7429. send_options(struct mg_connection *conn)
  7430. {
  7431. char date[64];
  7432. time_t curtime = time(NULL);
  7433. if (!conn) {
  7434. return;
  7435. }
  7436. conn->status_code = 200;
  7437. conn->must_close = 1;
  7438. gmt_time_string(date, sizeof(date), &curtime);
  7439. mg_printf(conn,
  7440. "HTTP/1.1 200 OK\r\n"
  7441. "Date: %s\r\n"
  7442. /* TODO: "Cache-Control" (?) */
  7443. "Connection: %s\r\n"
  7444. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  7445. "PROPFIND, MKCOL\r\n"
  7446. "DAV: 1\r\n\r\n",
  7447. date,
  7448. suggest_connection_header(conn));
  7449. }
  7450. /* Writes PROPFIND properties for a collection element */
  7451. static void
  7452. print_props(struct mg_connection *conn, const char *uri, struct file *filep)
  7453. {
  7454. char mtime[64];
  7455. if (conn == NULL || uri == NULL || filep == NULL) {
  7456. return;
  7457. }
  7458. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  7459. conn->num_bytes_sent +=
  7460. mg_printf(conn,
  7461. "<d:response>"
  7462. "<d:href>%s</d:href>"
  7463. "<d:propstat>"
  7464. "<d:prop>"
  7465. "<d:resourcetype>%s</d:resourcetype>"
  7466. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  7467. "<d:getlastmodified>%s</d:getlastmodified>"
  7468. "</d:prop>"
  7469. "<d:status>HTTP/1.1 200 OK</d:status>"
  7470. "</d:propstat>"
  7471. "</d:response>\n",
  7472. uri,
  7473. filep->is_directory ? "<d:collection/>" : "",
  7474. filep->size,
  7475. mtime);
  7476. }
  7477. static void
  7478. print_dav_dir_entry(struct de *de, void *data)
  7479. {
  7480. char href[PATH_MAX];
  7481. char href_encoded[PATH_MAX * 3 /* worst case */];
  7482. int truncated;
  7483. struct mg_connection *conn = (struct mg_connection *)data;
  7484. if (!de || !conn) {
  7485. return;
  7486. }
  7487. mg_snprintf(conn,
  7488. &truncated,
  7489. href,
  7490. sizeof(href),
  7491. "%s%s",
  7492. conn->request_info.local_uri,
  7493. de->file_name);
  7494. if (!truncated) {
  7495. mg_url_encode(href, href_encoded, PATH_MAX * 3);
  7496. print_props(conn, href_encoded, &de->file);
  7497. }
  7498. }
  7499. static void
  7500. handle_propfind(struct mg_connection *conn,
  7501. const char *path,
  7502. struct file *filep)
  7503. {
  7504. const char *depth = mg_get_header(conn, "Depth");
  7505. char date[64];
  7506. time_t curtime = time(NULL);
  7507. gmt_time_string(date, sizeof(date), &curtime);
  7508. if (!conn || !path || !filep || !conn->ctx) {
  7509. return;
  7510. }
  7511. conn->must_close = 1;
  7512. conn->status_code = 207;
  7513. mg_printf(conn,
  7514. "HTTP/1.1 207 Multi-Status\r\n"
  7515. "Date: %s\r\n",
  7516. date);
  7517. send_static_cache_header(conn);
  7518. mg_printf(conn,
  7519. "Connection: %s\r\n"
  7520. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  7521. suggest_connection_header(conn));
  7522. conn->num_bytes_sent +=
  7523. mg_printf(conn,
  7524. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  7525. "<d:multistatus xmlns:d='DAV:'>\n");
  7526. /* Print properties for the requested resource itself */
  7527. print_props(conn, conn->request_info.local_uri, filep);
  7528. /* If it is a directory, print directory entries too if Depth is not 0 */
  7529. if (filep && filep->is_directory
  7530. && !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")
  7531. && (depth == NULL || strcmp(depth, "0") != 0)) {
  7532. scan_directory(conn, path, conn, &print_dav_dir_entry);
  7533. }
  7534. conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");
  7535. }
  7536. #endif
  7537. void
  7538. mg_lock_connection(struct mg_connection *conn)
  7539. {
  7540. if (conn) {
  7541. (void)pthread_mutex_lock(&conn->mutex);
  7542. }
  7543. }
  7544. void
  7545. mg_unlock_connection(struct mg_connection *conn)
  7546. {
  7547. if (conn) {
  7548. (void)pthread_mutex_unlock(&conn->mutex);
  7549. }
  7550. }
  7551. void
  7552. mg_lock_context(struct mg_context *ctx)
  7553. {
  7554. if (ctx) {
  7555. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  7556. }
  7557. }
  7558. void
  7559. mg_unlock_context(struct mg_context *ctx)
  7560. {
  7561. if (ctx) {
  7562. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  7563. }
  7564. }
  7565. #if defined(USE_TIMERS)
  7566. #include "timer.inl"
  7567. #endif /* USE_TIMERS */
  7568. #ifdef USE_LUA
  7569. #include "mod_lua.inl"
  7570. #endif /* USE_LUA */
  7571. #ifdef USE_DUKTAPE
  7572. #include "mod_duktape.inl"
  7573. #endif /* USE_DUKTAPE */
  7574. #if defined(USE_WEBSOCKET)
  7575. /* START OF SHA-1 code
  7576. * Copyright(c) By Steve Reid <steve@edmweb.com> */
  7577. #define SHA1HANDSOFF
  7578. /* According to current tests (May 2015), the <solarisfixes.h> is not required.
  7579. *
  7580. * #if defined(__sun)
  7581. * #include "solarisfixes.h"
  7582. * #endif
  7583. */
  7584. static int
  7585. is_big_endian(void)
  7586. {
  7587. static const int n = 1;
  7588. return ((char *)&n)[0] == 0;
  7589. }
  7590. union char64long16 {
  7591. unsigned char c[64];
  7592. uint32_t l[16];
  7593. };
  7594. #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
  7595. static uint32_t
  7596. blk0(union char64long16 *block, int i)
  7597. {
  7598. /* Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN */
  7599. if (!is_big_endian()) {
  7600. block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00)
  7601. | (rol(block->l[i], 8) & 0x00FF00FF);
  7602. }
  7603. return block->l[i];
  7604. }
  7605. #define blk(i) \
  7606. (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] \
  7607. ^ block->l[(i + 2) & 15] ^ block->l[i & 15], \
  7608. 1))
  7609. #define R0(v, w, x, y, z, i) \
  7610. z += ((w & (x ^ y)) ^ y) + blk0(block, i) + 0x5A827999 + rol(v, 5); \
  7611. w = rol(w, 30);
  7612. #define R1(v, w, x, y, z, i) \
  7613. z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \
  7614. w = rol(w, 30);
  7615. #define R2(v, w, x, y, z, i) \
  7616. z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \
  7617. w = rol(w, 30);
  7618. #define R3(v, w, x, y, z, i) \
  7619. z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \
  7620. w = rol(w, 30);
  7621. #define R4(v, w, x, y, z, i) \
  7622. z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \
  7623. w = rol(w, 30);
  7624. typedef struct {
  7625. uint32_t state[5];
  7626. uint32_t count[2];
  7627. unsigned char buffer[64];
  7628. } SHA1_CTX;
  7629. static void
  7630. SHA1Transform(uint32_t state[5], const unsigned char buffer[64])
  7631. {
  7632. uint32_t a, b, c, d, e;
  7633. union char64long16 block[1];
  7634. memcpy(block, buffer, 64);
  7635. a = state[0];
  7636. b = state[1];
  7637. c = state[2];
  7638. d = state[3];
  7639. e = state[4];
  7640. R0(a, b, c, d, e, 0);
  7641. R0(e, a, b, c, d, 1);
  7642. R0(d, e, a, b, c, 2);
  7643. R0(c, d, e, a, b, 3);
  7644. R0(b, c, d, e, a, 4);
  7645. R0(a, b, c, d, e, 5);
  7646. R0(e, a, b, c, d, 6);
  7647. R0(d, e, a, b, c, 7);
  7648. R0(c, d, e, a, b, 8);
  7649. R0(b, c, d, e, a, 9);
  7650. R0(a, b, c, d, e, 10);
  7651. R0(e, a, b, c, d, 11);
  7652. R0(d, e, a, b, c, 12);
  7653. R0(c, d, e, a, b, 13);
  7654. R0(b, c, d, e, a, 14);
  7655. R0(a, b, c, d, e, 15);
  7656. R1(e, a, b, c, d, 16);
  7657. R1(d, e, a, b, c, 17);
  7658. R1(c, d, e, a, b, 18);
  7659. R1(b, c, d, e, a, 19);
  7660. R2(a, b, c, d, e, 20);
  7661. R2(e, a, b, c, d, 21);
  7662. R2(d, e, a, b, c, 22);
  7663. R2(c, d, e, a, b, 23);
  7664. R2(b, c, d, e, a, 24);
  7665. R2(a, b, c, d, e, 25);
  7666. R2(e, a, b, c, d, 26);
  7667. R2(d, e, a, b, c, 27);
  7668. R2(c, d, e, a, b, 28);
  7669. R2(b, c, d, e, a, 29);
  7670. R2(a, b, c, d, e, 30);
  7671. R2(e, a, b, c, d, 31);
  7672. R2(d, e, a, b, c, 32);
  7673. R2(c, d, e, a, b, 33);
  7674. R2(b, c, d, e, a, 34);
  7675. R2(a, b, c, d, e, 35);
  7676. R2(e, a, b, c, d, 36);
  7677. R2(d, e, a, b, c, 37);
  7678. R2(c, d, e, a, b, 38);
  7679. R2(b, c, d, e, a, 39);
  7680. R3(a, b, c, d, e, 40);
  7681. R3(e, a, b, c, d, 41);
  7682. R3(d, e, a, b, c, 42);
  7683. R3(c, d, e, a, b, 43);
  7684. R3(b, c, d, e, a, 44);
  7685. R3(a, b, c, d, e, 45);
  7686. R3(e, a, b, c, d, 46);
  7687. R3(d, e, a, b, c, 47);
  7688. R3(c, d, e, a, b, 48);
  7689. R3(b, c, d, e, a, 49);
  7690. R3(a, b, c, d, e, 50);
  7691. R3(e, a, b, c, d, 51);
  7692. R3(d, e, a, b, c, 52);
  7693. R3(c, d, e, a, b, 53);
  7694. R3(b, c, d, e, a, 54);
  7695. R3(a, b, c, d, e, 55);
  7696. R3(e, a, b, c, d, 56);
  7697. R3(d, e, a, b, c, 57);
  7698. R3(c, d, e, a, b, 58);
  7699. R3(b, c, d, e, a, 59);
  7700. R4(a, b, c, d, e, 60);
  7701. R4(e, a, b, c, d, 61);
  7702. R4(d, e, a, b, c, 62);
  7703. R4(c, d, e, a, b, 63);
  7704. R4(b, c, d, e, a, 64);
  7705. R4(a, b, c, d, e, 65);
  7706. R4(e, a, b, c, d, 66);
  7707. R4(d, e, a, b, c, 67);
  7708. R4(c, d, e, a, b, 68);
  7709. R4(b, c, d, e, a, 69);
  7710. R4(a, b, c, d, e, 70);
  7711. R4(e, a, b, c, d, 71);
  7712. R4(d, e, a, b, c, 72);
  7713. R4(c, d, e, a, b, 73);
  7714. R4(b, c, d, e, a, 74);
  7715. R4(a, b, c, d, e, 75);
  7716. R4(e, a, b, c, d, 76);
  7717. R4(d, e, a, b, c, 77);
  7718. R4(c, d, e, a, b, 78);
  7719. R4(b, c, d, e, a, 79);
  7720. state[0] += a;
  7721. state[1] += b;
  7722. state[2] += c;
  7723. state[3] += d;
  7724. state[4] += e;
  7725. a = b = c = d = e = 0;
  7726. memset(block, '\0', sizeof(block));
  7727. }
  7728. static void
  7729. SHA1Init(SHA1_CTX *context)
  7730. {
  7731. context->state[0] = 0x67452301;
  7732. context->state[1] = 0xEFCDAB89;
  7733. context->state[2] = 0x98BADCFE;
  7734. context->state[3] = 0x10325476;
  7735. context->state[4] = 0xC3D2E1F0;
  7736. context->count[0] = context->count[1] = 0;
  7737. }
  7738. static void
  7739. SHA1Update(SHA1_CTX *context, const unsigned char *data, uint32_t len)
  7740. {
  7741. uint32_t i, j;
  7742. j = context->count[0];
  7743. if ((context->count[0] += len << 3) < j) {
  7744. context->count[1]++;
  7745. }
  7746. context->count[1] += (len >> 29);
  7747. j = (j >> 3) & 63;
  7748. if ((j + len) > 63) {
  7749. memcpy(&context->buffer[j], data, (i = 64 - j));
  7750. SHA1Transform(context->state, context->buffer);
  7751. for (; i + 63 < len; i += 64) {
  7752. SHA1Transform(context->state, &data[i]);
  7753. }
  7754. j = 0;
  7755. } else
  7756. i = 0;
  7757. memcpy(&context->buffer[j], &data[i], len - i);
  7758. }
  7759. static void
  7760. SHA1Final(unsigned char digest[20], SHA1_CTX *context)
  7761. {
  7762. unsigned i;
  7763. unsigned char finalcount[8], c;
  7764. for (i = 0; i < 8; i++) {
  7765. finalcount[i] = (unsigned char)((context->count[(i >= 4) ? 0 : 1]
  7766. >> ((3 - (i & 3)) * 8)) & 255);
  7767. }
  7768. c = 0200;
  7769. SHA1Update(context, &c, 1);
  7770. while ((context->count[0] & 504) != 448) {
  7771. c = 0000;
  7772. SHA1Update(context, &c, 1);
  7773. }
  7774. SHA1Update(context, finalcount, 8);
  7775. for (i = 0; i < 20; i++) {
  7776. digest[i] = (unsigned char)((context->state[i >> 2]
  7777. >> ((3 - (i & 3)) * 8)) & 255);
  7778. }
  7779. memset(context, '\0', sizeof(*context));
  7780. memset(&finalcount, '\0', sizeof(finalcount));
  7781. }
  7782. /* END OF SHA1 CODE */
  7783. static int
  7784. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  7785. {
  7786. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  7787. const char *protocol = NULL;
  7788. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  7789. SHA1_CTX sha_ctx;
  7790. int truncated;
  7791. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  7792. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  7793. if (truncated) {
  7794. conn->must_close = 1;
  7795. return 0;
  7796. }
  7797. SHA1Init(&sha_ctx);
  7798. SHA1Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  7799. SHA1Final((unsigned char *)sha, &sha_ctx);
  7800. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  7801. mg_printf(conn,
  7802. "HTTP/1.1 101 Switching Protocols\r\n"
  7803. "Upgrade: websocket\r\n"
  7804. "Connection: Upgrade\r\n"
  7805. "Sec-WebSocket-Accept: %s\r\n",
  7806. b64_sha);
  7807. protocol = mg_get_header(conn, "Sec-WebSocket-Protocol");
  7808. if (protocol) {
  7809. /* The protocol is a comma seperated list of names. */
  7810. /* The server must only return one value from this list. */
  7811. /* First check if it is a list or just a single value. */
  7812. const char *sep = strchr(protocol, ',');
  7813. if (sep == NULL) {
  7814. /* Just a single protocol -> accept it. */
  7815. mg_printf(conn, "Sec-WebSocket-Protocol: %s\r\n\r\n", protocol);
  7816. } else {
  7817. /* Multiple protocols -> accept the first one. */
  7818. /* This is just a quick fix if the client offers multiple
  7819. * protocols. In order to get the behavior intended by
  7820. * RFC 6455 (https://tools.ietf.org/rfc/rfc6455.txt), it is
  7821. * required to have a list of websocket subprotocols accepted
  7822. * by the server. Then the server must either select a subprotocol
  7823. * supported by client and server, or the server has to abort the
  7824. * handshake by not returning a Sec-Websocket-Protocol header if
  7825. * no subprotocol is acceptable.
  7826. */
  7827. mg_printf(conn,
  7828. "Sec-WebSocket-Protocol: %.*s\r\n\r\n",
  7829. (int)(sep - protocol),
  7830. protocol);
  7831. }
  7832. /* TODO: Real subprotocol negotiation instead of just taking the first
  7833. * websocket subprotocol suggested by the client. */
  7834. } else {
  7835. mg_printf(conn, "%s", "\r\n");
  7836. }
  7837. return 1;
  7838. }
  7839. static void
  7840. read_websocket(struct mg_connection *conn,
  7841. mg_websocket_data_handler ws_data_handler,
  7842. void *callback_data)
  7843. {
  7844. /* Pointer to the beginning of the portion of the incoming websocket
  7845. * message queue.
  7846. * The original websocket upgrade request is never removed, so the queue
  7847. * begins after it. */
  7848. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  7849. int n, error, exit_by_callback;
  7850. /* body_len is the length of the entire queue in bytes
  7851. * len is the length of the current message
  7852. * data_len is the length of the current message's data payload
  7853. * header_len is the length of the current message's header */
  7854. size_t i, len, mask_len = 0, data_len = 0, header_len, body_len;
  7855. /* "The masking key is a 32-bit value chosen at random by the client."
  7856. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  7857. */
  7858. unsigned char mask[4];
  7859. /* data points to the place where the message is stored when passed to
  7860. * the
  7861. * websocket_data callback. This is either mem on the stack, or a
  7862. * dynamically allocated buffer if it is too large. */
  7863. char mem[4096];
  7864. char *data = mem;
  7865. unsigned char mop; /* mask flag and opcode */
  7866. double timeout = -1.0;
  7867. if (conn->ctx->config[WEBSOCKET_TIMEOUT]) {
  7868. timeout = atoi(conn->ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  7869. }
  7870. if ((timeout <= 0.0) && (conn->ctx->config[REQUEST_TIMEOUT])) {
  7871. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  7872. }
  7873. mg_set_thread_name("wsock");
  7874. /* Loop continuously, reading messages from the socket, invoking the
  7875. * callback, and waiting repeatedly until an error occurs. */
  7876. while (!conn->ctx->stop_flag) {
  7877. header_len = 0;
  7878. assert(conn->data_len >= conn->request_len);
  7879. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  7880. len = buf[1] & 127;
  7881. mask_len = (buf[1] & 128) ? 4 : 0;
  7882. if ((len < 126) && (body_len >= mask_len)) {
  7883. data_len = len;
  7884. header_len = 2 + mask_len;
  7885. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  7886. header_len = 4 + mask_len;
  7887. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  7888. } else if (body_len >= (10 + mask_len)) {
  7889. header_len = 10 + mask_len;
  7890. data_len = (((uint64_t)ntohl(*(uint32_t *)(void *)&buf[2]))
  7891. << 32) + ntohl(*(uint32_t *)(void *)&buf[6]);
  7892. }
  7893. }
  7894. if (header_len > 0 && body_len >= header_len) {
  7895. /* Allocate space to hold websocket payload */
  7896. data = mem;
  7897. if (data_len > sizeof(mem)) {
  7898. data = (char *)mg_malloc(data_len);
  7899. if (data == NULL) {
  7900. /* Allocation failed, exit the loop and then close the
  7901. * connection */
  7902. mg_cry(conn, "websocket out of memory; closing connection");
  7903. break;
  7904. }
  7905. }
  7906. /* Copy the mask before we shift the queue and destroy it */
  7907. if (mask_len > 0) {
  7908. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  7909. } else {
  7910. memset(mask, 0, sizeof(mask));
  7911. }
  7912. /* Read frame payload from the first message in the queue into
  7913. * data and advance the queue by moving the memory in place. */
  7914. assert(body_len >= header_len);
  7915. if (data_len + header_len > body_len) {
  7916. mop = buf[0]; /* current mask and opcode */
  7917. /* Overflow case */
  7918. len = body_len - header_len;
  7919. memcpy(data, buf + header_len, len);
  7920. error = 0;
  7921. while (len < data_len) {
  7922. n = pull(
  7923. NULL, conn, data + len, (int)(data_len - len), timeout);
  7924. if (n <= 0) {
  7925. error = 1;
  7926. break;
  7927. }
  7928. len += (size_t)n;
  7929. }
  7930. if (error) {
  7931. mg_cry(conn, "Websocket pull failed; closing connection");
  7932. break;
  7933. }
  7934. conn->data_len = conn->request_len;
  7935. } else {
  7936. mop = buf[0]; /* current mask and opcode, overwritten by
  7937. * memmove() */
  7938. /* Length of the message being read at the front of the
  7939. * queue */
  7940. len = data_len + header_len;
  7941. /* Copy the data payload into the data pointer for the
  7942. * callback */
  7943. memcpy(data, buf + header_len, data_len);
  7944. /* Move the queue forward len bytes */
  7945. memmove(buf, buf + len, body_len - len);
  7946. /* Mark the queue as advanced */
  7947. conn->data_len -= (int)len;
  7948. }
  7949. /* Apply mask if necessary */
  7950. if (mask_len > 0) {
  7951. for (i = 0; i < data_len; ++i) {
  7952. data[i] ^= mask[i & 3];
  7953. }
  7954. }
  7955. /* Exit the loop if callback signals to exit (server side),
  7956. * or "connection close" opcode received (client side). */
  7957. exit_by_callback = 0;
  7958. if ((ws_data_handler != NULL)
  7959. && !ws_data_handler(conn, mop, data, data_len, callback_data)) {
  7960. exit_by_callback = 1;
  7961. }
  7962. if (data != mem) {
  7963. mg_free(data);
  7964. }
  7965. if (exit_by_callback
  7966. || ((mop & 0xf) == WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  7967. /* Opcode == 8, connection close */
  7968. break;
  7969. }
  7970. /* Not breaking the loop, process next websocket frame. */
  7971. } else {
  7972. /* Read from the socket into the next available location in the
  7973. * message queue. */
  7974. if ((n = pull(NULL,
  7975. conn,
  7976. conn->buf + conn->data_len,
  7977. conn->buf_size - conn->data_len,
  7978. timeout)) <= 0) {
  7979. /* Error, no bytes read */
  7980. break;
  7981. }
  7982. conn->data_len += n;
  7983. }
  7984. }
  7985. mg_set_thread_name("worker");
  7986. }
  7987. static int
  7988. mg_websocket_write_exec(struct mg_connection *conn,
  7989. int opcode,
  7990. const char *data,
  7991. size_t dataLen,
  7992. uint32_t masking_key)
  7993. {
  7994. unsigned char header[14];
  7995. size_t headerLen = 1;
  7996. int retval = -1;
  7997. header[0] = 0x80 + (opcode & 0xF);
  7998. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  7999. if (dataLen < 126) {
  8000. /* inline 7-bit length field */
  8001. header[1] = (unsigned char)dataLen;
  8002. headerLen = 2;
  8003. } else if (dataLen <= 0xFFFF) {
  8004. /* 16-bit length field */
  8005. uint16_t len = htons((uint16_t)dataLen);
  8006. header[1] = 126;
  8007. memcpy(header + 2, &len, 2);
  8008. headerLen = 4;
  8009. } else {
  8010. /* 64-bit length field */
  8011. uint32_t len1 = htonl((uint64_t)dataLen >> 32);
  8012. uint32_t len2 = htonl(dataLen & 0xFFFFFFFF);
  8013. header[1] = 127;
  8014. memcpy(header + 2, &len1, 4);
  8015. memcpy(header + 6, &len2, 4);
  8016. headerLen = 10;
  8017. }
  8018. if (masking_key) {
  8019. /* add mask */
  8020. header[1] |= 0x80;
  8021. memcpy(header + headerLen, &masking_key, 4);
  8022. headerLen += 4;
  8023. }
  8024. /* Note that POSIX/Winsock's send() is threadsafe
  8025. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  8026. * but mongoose's mg_printf/mg_write is not (because of the loop in
  8027. * push(), although that is only a problem if the packet is large or
  8028. * outgoing buffer is full). */
  8029. (void)mg_lock_connection(conn);
  8030. retval = mg_write(conn, header, headerLen);
  8031. if (dataLen > 0) {
  8032. retval = mg_write(conn, data, dataLen);
  8033. }
  8034. mg_unlock_connection(conn);
  8035. return retval;
  8036. }
  8037. int
  8038. mg_websocket_write(struct mg_connection *conn,
  8039. int opcode,
  8040. const char *data,
  8041. size_t dataLen)
  8042. {
  8043. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  8044. }
  8045. static void
  8046. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  8047. {
  8048. size_t i = 0;
  8049. i = 0;
  8050. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  8051. /* Convert in 32 bit words, if data is 4 byte aligned */
  8052. while (i < (in_len - 3)) {
  8053. *(uint32_t *)(void *)(out + i) =
  8054. *(uint32_t *)(void *)(in + i) ^ masking_key;
  8055. i += 4;
  8056. }
  8057. }
  8058. if (i != in_len) {
  8059. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  8060. while (i < in_len) {
  8061. *(uint8_t *)(void *)(out + i) =
  8062. *(uint8_t *)(void *)(in + i)
  8063. ^ *(((uint8_t *)&masking_key) + (i % 4));
  8064. i++;
  8065. }
  8066. }
  8067. }
  8068. int
  8069. mg_websocket_client_write(struct mg_connection *conn,
  8070. int opcode,
  8071. const char *data,
  8072. size_t dataLen)
  8073. {
  8074. int retval = -1;
  8075. char *masked_data = (char *)mg_malloc(((dataLen + 7) / 4) * 4);
  8076. uint32_t masking_key = (uint32_t)get_random();
  8077. if (masked_data == NULL) {
  8078. /* Return -1 in an error case */
  8079. mg_cry(conn,
  8080. "Cannot allocate buffer for masked websocket response: "
  8081. "Out of memory");
  8082. return -1;
  8083. }
  8084. mask_data(data, dataLen, masking_key, masked_data);
  8085. retval = mg_websocket_write_exec(
  8086. conn, opcode, masked_data, dataLen, masking_key);
  8087. mg_free(masked_data);
  8088. return retval;
  8089. }
  8090. static void
  8091. handle_websocket_request(struct mg_connection *conn,
  8092. const char *path,
  8093. int is_callback_resource,
  8094. mg_websocket_connect_handler ws_connect_handler,
  8095. mg_websocket_ready_handler ws_ready_handler,
  8096. mg_websocket_data_handler ws_data_handler,
  8097. mg_websocket_close_handler ws_close_handler,
  8098. void *cbData)
  8099. {
  8100. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  8101. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  8102. int lua_websock = 0;
  8103. #if !defined(USE_LUA)
  8104. (void)path;
  8105. #endif
  8106. /* Step 1: Check websocket protocol version. */
  8107. /* Step 1.1: Check Sec-WebSocket-Key. */
  8108. if (!websock_key) {
  8109. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  8110. * requires a Sec-WebSocket-Key header.
  8111. */
  8112. /* It could be the hixie draft version
  8113. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  8114. */
  8115. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  8116. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  8117. char key3[8];
  8118. if ((key1 != NULL) && (key2 != NULL)) {
  8119. /* This version uses 8 byte body data in a GET request */
  8120. conn->content_len = 8;
  8121. if (8 == mg_read(conn, key3, 8)) {
  8122. /* This is the hixie version */
  8123. send_http_error(conn,
  8124. 426,
  8125. "%s",
  8126. "Protocol upgrade to RFC 6455 required");
  8127. return;
  8128. }
  8129. }
  8130. /* This is an unknown version */
  8131. send_http_error(conn, 400, "%s", "Malformed websocket request");
  8132. return;
  8133. }
  8134. /* Step 1.2: Check websocket protocol version. */
  8135. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  8136. if (version == NULL || strcmp(version, "13") != 0) {
  8137. /* Reject wrong versions */
  8138. send_http_error(conn, 426, "%s", "Protocol upgrade required");
  8139. return;
  8140. }
  8141. /* Step 1.3: Could check for "Host", but we do not really nead this
  8142. * value for anything, so just ignore it. */
  8143. /* Step 2: If a callback is responsible, call it. */
  8144. if (is_callback_resource) {
  8145. if (ws_connect_handler != NULL
  8146. && ws_connect_handler(conn, cbData) != 0) {
  8147. /* C callback has returned non-zero, do not proceed with
  8148. * handshake.
  8149. */
  8150. /* Note that C callbacks are no longer called when Lua is
  8151. * responsible, so C can no longer filter callbacks for Lua. */
  8152. return;
  8153. }
  8154. }
  8155. #if defined(USE_LUA)
  8156. /* Step 3: No callback. Check if Lua is responsible. */
  8157. else {
  8158. /* Step 3.1: Check if Lua is responsible. */
  8159. if (conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  8160. lua_websock =
  8161. match_prefix(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  8162. strlen(
  8163. conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  8164. path);
  8165. }
  8166. if (lua_websock) {
  8167. /* Step 3.2: Lua is responsible: call it. */
  8168. conn->lua_websocket_state = lua_websocket_new(path, conn);
  8169. if (!conn->lua_websocket_state) {
  8170. /* Lua rejected the new client */
  8171. return;
  8172. }
  8173. }
  8174. }
  8175. #endif
  8176. /* Step 4: Check if there is a responsible websocket handler. */
  8177. if (!is_callback_resource && !lua_websock) {
  8178. /* There is no callback, an Lua is not responsible either. */
  8179. /* Reply with a 404 Not Found or with nothing at all?
  8180. * TODO (mid): check the websocket standards, how to reply to
  8181. * requests to invalid websocket addresses. */
  8182. send_http_error(conn, 404, "%s", "Not found");
  8183. return;
  8184. }
  8185. /* Step 5: The websocket connection has been accepted */
  8186. if (!send_websocket_handshake(conn, websock_key)) {
  8187. send_http_error(conn, 500, "%s", "Websocket handshake failed");
  8188. return;
  8189. }
  8190. /* Step 6: Call the ready handler */
  8191. if (is_callback_resource) {
  8192. if (ws_ready_handler != NULL) {
  8193. ws_ready_handler(conn, cbData);
  8194. }
  8195. #if defined(USE_LUA)
  8196. } else if (lua_websock) {
  8197. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  8198. /* the ready handler returned false */
  8199. return;
  8200. }
  8201. #endif
  8202. }
  8203. /* Step 7: Enter the read loop */
  8204. if (is_callback_resource) {
  8205. read_websocket(conn, ws_data_handler, cbData);
  8206. #if defined(USE_LUA)
  8207. } else if (lua_websock) {
  8208. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  8209. #endif
  8210. }
  8211. /* Step 8: Call the close handler */
  8212. if (ws_close_handler) {
  8213. ws_close_handler(conn, cbData);
  8214. }
  8215. }
  8216. static int
  8217. is_websocket_protocol(const struct mg_connection *conn)
  8218. {
  8219. const char *upgrade, *connection;
  8220. /* A websocket protocoll has the following HTTP headers:
  8221. *
  8222. * Connection: Upgrade
  8223. * Upgrade: Websocket
  8224. */
  8225. upgrade = mg_get_header(conn, "Upgrade");
  8226. if (upgrade == NULL) {
  8227. return 0; /* fail early, don't waste time checking other header
  8228. * fields
  8229. */
  8230. }
  8231. if (!mg_strcasestr(upgrade, "websocket")) {
  8232. return 0;
  8233. }
  8234. connection = mg_get_header(conn, "Connection");
  8235. if (connection == NULL) {
  8236. return 0;
  8237. }
  8238. if (!mg_strcasestr(connection, "upgrade")) {
  8239. return 0;
  8240. }
  8241. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  8242. * "Sec-WebSocket-Version" are also required.
  8243. * Don't check them here, since even an unsupported websocket protocol
  8244. * request still IS a websocket request (in contrast to a standard HTTP
  8245. * request). It will fail later in handle_websocket_request.
  8246. */
  8247. return 1;
  8248. }
  8249. #endif /* !USE_WEBSOCKET */
  8250. static int
  8251. isbyte(int n)
  8252. {
  8253. return n >= 0 && n <= 255;
  8254. }
  8255. static int
  8256. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  8257. {
  8258. int n, a, b, c, d, slash = 32, len = 0;
  8259. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5
  8260. || sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) && isbyte(a)
  8261. && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0
  8262. && slash < 33) {
  8263. len = n;
  8264. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  8265. | (uint32_t)d;
  8266. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  8267. }
  8268. return len;
  8269. }
  8270. static int
  8271. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  8272. {
  8273. int throttle = 0;
  8274. struct vec vec, val;
  8275. uint32_t net, mask;
  8276. char mult;
  8277. double v;
  8278. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  8279. mult = ',';
  8280. if (sscanf(val.ptr, "%lf%c", &v, &mult) < 1 || v < 0
  8281. || (lowercase(&mult) != 'k' && lowercase(&mult) != 'm'
  8282. && mult != ',')) {
  8283. continue;
  8284. }
  8285. v *= (lowercase(&mult) == 'k')
  8286. ? 1024
  8287. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  8288. if (vec.len == 1 && vec.ptr[0] == '*') {
  8289. throttle = (int)v;
  8290. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  8291. if ((remote_ip & mask) == net) {
  8292. throttle = (int)v;
  8293. }
  8294. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  8295. throttle = (int)v;
  8296. }
  8297. }
  8298. return throttle;
  8299. }
  8300. static uint32_t
  8301. get_remote_ip(const struct mg_connection *conn)
  8302. {
  8303. if (!conn) {
  8304. return 0;
  8305. }
  8306. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  8307. }
  8308. /* The mg_upload function is superseeded by mg_handle_form_request. */
  8309. #include "handle_form.inl"
  8310. #if defined(MG_LEGACY_INTERFACE)
  8311. /* Implement the deprecated mg_upload function by calling the new
  8312. * mg_handle_form_request function. While mg_upload could only handle
  8313. * HTML forms sent as POST request in multipart/form-data format
  8314. * containing only file input elements, mg_handle_form_request can
  8315. * handle all form input elements and all standard request methods. */
  8316. struct mg_upload_user_data {
  8317. struct mg_connection *conn;
  8318. const char *destination_dir;
  8319. int num_uploaded_files;
  8320. };
  8321. /* Helper function for deprecated mg_upload. */
  8322. static int
  8323. mg_upload_field_found(const char *key,
  8324. const char *filename,
  8325. char *path,
  8326. size_t pathlen,
  8327. void *user_data)
  8328. {
  8329. int truncated = 0;
  8330. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  8331. (void)key;
  8332. if (!filename) {
  8333. mg_cry(fud->conn, "%s: No filename set", __func__);
  8334. return FORM_FIELD_STORAGE_ABORT;
  8335. }
  8336. mg_snprintf(fud->conn,
  8337. &truncated,
  8338. path,
  8339. pathlen - 1,
  8340. "%s/%s",
  8341. fud->destination_dir,
  8342. filename);
  8343. if (!truncated) {
  8344. mg_cry(fud->conn, "%s: File path too long", __func__);
  8345. return FORM_FIELD_STORAGE_ABORT;
  8346. }
  8347. return FORM_FIELD_STORAGE_STORE;
  8348. }
  8349. /* Helper function for deprecated mg_upload. */
  8350. static int
  8351. mg_upload_field_get(const char *key,
  8352. const char *value,
  8353. size_t value_size,
  8354. void *user_data)
  8355. {
  8356. /* Function should never be called */
  8357. (void)key;
  8358. (void)value;
  8359. (void)value_size;
  8360. (void)user_data;
  8361. return 0;
  8362. }
  8363. /* Helper function for deprecated mg_upload. */
  8364. static int
  8365. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  8366. {
  8367. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  8368. (void)file_size;
  8369. fud->num_uploaded_files++;
  8370. fud->conn->ctx->callbacks.upload(fud->conn, path);
  8371. return 0;
  8372. }
  8373. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  8374. int
  8375. mg_upload(struct mg_connection *conn, const char *destination_dir)
  8376. {
  8377. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  8378. struct mg_form_data_handler fdh = {mg_upload_field_found,
  8379. mg_upload_field_get,
  8380. mg_upload_field_stored,
  8381. 0};
  8382. int ret;
  8383. fdh.user_data = (void *)&fud;
  8384. ret = mg_handle_form_request(conn, &fdh);
  8385. if (ret < 0) {
  8386. mg_cry(conn, "%s: Error while parsing the request", __func__);
  8387. }
  8388. return fud.num_uploaded_files;
  8389. }
  8390. #endif
  8391. static int
  8392. get_first_ssl_listener_index(const struct mg_context *ctx)
  8393. {
  8394. unsigned int i;
  8395. int idx = -1;
  8396. if (ctx) {
  8397. for (i = 0; idx == -1 && i < ctx->num_listening_sockets; i++) {
  8398. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  8399. }
  8400. }
  8401. return idx;
  8402. }
  8403. static void
  8404. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  8405. {
  8406. char host[1025];
  8407. const char *host_header;
  8408. size_t hostlen;
  8409. host_header = mg_get_header(conn, "Host");
  8410. hostlen = sizeof(host);
  8411. if (host_header != NULL) {
  8412. char *pos;
  8413. mg_strlcpy(host, host_header, hostlen);
  8414. host[hostlen - 1] = '\0';
  8415. pos = strchr(host, ':');
  8416. if (pos != NULL) {
  8417. *pos = '\0';
  8418. }
  8419. } else {
  8420. /* Cannot get host from the Host: header.
  8421. * Fallback to our IP address. */
  8422. if (conn) {
  8423. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  8424. }
  8425. }
  8426. /* Send host, port, uri and (if it exists) ?query_string */
  8427. if (conn) {
  8428. mg_printf(conn,
  8429. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  8430. host,
  8431. #if defined(USE_IPV6)
  8432. (conn->ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  8433. == AF_INET6)
  8434. ? (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  8435. .lsa.sin6.sin6_port)
  8436. :
  8437. #endif
  8438. (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  8439. .lsa.sin.sin_port),
  8440. conn->request_info.local_uri,
  8441. (conn->request_info.query_string == NULL) ? "" : "?",
  8442. (conn->request_info.query_string == NULL)
  8443. ? ""
  8444. : conn->request_info.query_string);
  8445. }
  8446. }
  8447. static void
  8448. mg_set_handler_type(struct mg_context *ctx,
  8449. const char *uri,
  8450. int handler_type,
  8451. int is_delete_request,
  8452. mg_request_handler handler,
  8453. mg_websocket_connect_handler connect_handler,
  8454. mg_websocket_ready_handler ready_handler,
  8455. mg_websocket_data_handler data_handler,
  8456. mg_websocket_close_handler close_handler,
  8457. mg_authorization_handler auth_handler,
  8458. void *cbdata)
  8459. {
  8460. struct mg_handler_info *tmp_rh, **lastref;
  8461. size_t urilen = strlen(uri);
  8462. if (handler_type == WEBSOCKET_HANDLER) {
  8463. /* assert(handler == NULL); */
  8464. /* assert(is_delete_request || connect_handler!=NULL ||
  8465. * ready_handler!=NULL || data_handler!=NULL ||
  8466. * close_handler!=NULL);
  8467. */
  8468. /* assert(auth_handler == NULL); */
  8469. if (handler != NULL) {
  8470. return;
  8471. }
  8472. if (!is_delete_request && connect_handler == NULL
  8473. && ready_handler == NULL
  8474. && data_handler == NULL
  8475. && close_handler == NULL) {
  8476. return;
  8477. }
  8478. if (auth_handler != NULL) {
  8479. return;
  8480. }
  8481. } else if (handler_type == REQUEST_HANDLER) {
  8482. /* assert(connect_handler==NULL && ready_handler==NULL &&
  8483. * data_handler==NULL && close_handler==NULL); */
  8484. /* assert(is_delete_request || (handler!=NULL));
  8485. */
  8486. /* assert(auth_handler == NULL); */
  8487. if (connect_handler != NULL || ready_handler != NULL
  8488. || data_handler != NULL
  8489. || close_handler != NULL) {
  8490. return;
  8491. }
  8492. if (!is_delete_request && (handler == NULL)) {
  8493. return;
  8494. }
  8495. if (auth_handler != NULL) {
  8496. return;
  8497. }
  8498. } else { /* AUTH_HANDLER */
  8499. /* assert(handler == NULL); */
  8500. /* assert(connect_handler==NULL && ready_handler==NULL &&
  8501. * data_handler==NULL && close_handler==NULL); */
  8502. /* assert(auth_handler != NULL); */
  8503. if (handler != NULL) {
  8504. return;
  8505. }
  8506. if (connect_handler != NULL || ready_handler != NULL
  8507. || data_handler != NULL
  8508. || close_handler != NULL) {
  8509. return;
  8510. }
  8511. if (!is_delete_request && (auth_handler == NULL)) {
  8512. return;
  8513. }
  8514. }
  8515. if (!ctx) {
  8516. return;
  8517. }
  8518. mg_lock_context(ctx);
  8519. /* first try to find an existing handler */
  8520. lastref = &(ctx->handlers);
  8521. for (tmp_rh = ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  8522. if (tmp_rh->handler_type == handler_type) {
  8523. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  8524. if (!is_delete_request) {
  8525. /* update existing handler */
  8526. if (handler_type == REQUEST_HANDLER) {
  8527. tmp_rh->handler = handler;
  8528. } else if (handler_type == WEBSOCKET_HANDLER) {
  8529. tmp_rh->connect_handler = connect_handler;
  8530. tmp_rh->ready_handler = ready_handler;
  8531. tmp_rh->data_handler = data_handler;
  8532. tmp_rh->close_handler = close_handler;
  8533. } else { /* AUTH_HANDLER */
  8534. tmp_rh->auth_handler = auth_handler;
  8535. }
  8536. tmp_rh->cbdata = cbdata;
  8537. } else {
  8538. /* remove existing handler */
  8539. *lastref = tmp_rh->next;
  8540. mg_free(tmp_rh->uri);
  8541. mg_free(tmp_rh);
  8542. }
  8543. mg_unlock_context(ctx);
  8544. return;
  8545. }
  8546. }
  8547. lastref = &(tmp_rh->next);
  8548. }
  8549. if (is_delete_request) {
  8550. /* no handler to set, this was a remove request to a non-existing
  8551. * handler */
  8552. mg_unlock_context(ctx);
  8553. return;
  8554. }
  8555. tmp_rh =
  8556. (struct mg_handler_info *)mg_calloc(sizeof(struct mg_handler_info), 1);
  8557. if (tmp_rh == NULL) {
  8558. mg_unlock_context(ctx);
  8559. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  8560. return;
  8561. }
  8562. tmp_rh->uri = mg_strdup(uri);
  8563. if (!tmp_rh->uri) {
  8564. mg_unlock_context(ctx);
  8565. mg_free(tmp_rh);
  8566. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  8567. return;
  8568. }
  8569. tmp_rh->uri_len = urilen;
  8570. if (handler_type == REQUEST_HANDLER) {
  8571. tmp_rh->handler = handler;
  8572. } else if (handler_type == WEBSOCKET_HANDLER) {
  8573. tmp_rh->connect_handler = connect_handler;
  8574. tmp_rh->ready_handler = ready_handler;
  8575. tmp_rh->data_handler = data_handler;
  8576. tmp_rh->close_handler = close_handler;
  8577. } else { /* AUTH_HANDLER */
  8578. tmp_rh->auth_handler = auth_handler;
  8579. }
  8580. tmp_rh->cbdata = cbdata;
  8581. tmp_rh->handler_type = handler_type;
  8582. tmp_rh->next = NULL;
  8583. *lastref = tmp_rh;
  8584. mg_unlock_context(ctx);
  8585. }
  8586. void
  8587. mg_set_request_handler(struct mg_context *ctx,
  8588. const char *uri,
  8589. mg_request_handler handler,
  8590. void *cbdata)
  8591. {
  8592. mg_set_handler_type(ctx,
  8593. uri,
  8594. REQUEST_HANDLER,
  8595. handler == NULL,
  8596. handler,
  8597. NULL,
  8598. NULL,
  8599. NULL,
  8600. NULL,
  8601. NULL,
  8602. cbdata);
  8603. }
  8604. void
  8605. mg_set_websocket_handler(struct mg_context *ctx,
  8606. const char *uri,
  8607. mg_websocket_connect_handler connect_handler,
  8608. mg_websocket_ready_handler ready_handler,
  8609. mg_websocket_data_handler data_handler,
  8610. mg_websocket_close_handler close_handler,
  8611. void *cbdata)
  8612. {
  8613. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  8614. && (data_handler == NULL)
  8615. && (close_handler == NULL);
  8616. mg_set_handler_type(ctx,
  8617. uri,
  8618. WEBSOCKET_HANDLER,
  8619. is_delete_request,
  8620. NULL,
  8621. connect_handler,
  8622. ready_handler,
  8623. data_handler,
  8624. close_handler,
  8625. NULL,
  8626. cbdata);
  8627. }
  8628. void
  8629. mg_set_auth_handler(struct mg_context *ctx,
  8630. const char *uri,
  8631. mg_request_handler handler,
  8632. void *cbdata)
  8633. {
  8634. mg_set_handler_type(ctx,
  8635. uri,
  8636. AUTH_HANDLER,
  8637. handler == NULL,
  8638. NULL,
  8639. NULL,
  8640. NULL,
  8641. NULL,
  8642. NULL,
  8643. handler,
  8644. cbdata);
  8645. }
  8646. static int
  8647. get_request_handler(struct mg_connection *conn,
  8648. int handler_type,
  8649. mg_request_handler *handler,
  8650. mg_websocket_connect_handler *connect_handler,
  8651. mg_websocket_ready_handler *ready_handler,
  8652. mg_websocket_data_handler *data_handler,
  8653. mg_websocket_close_handler *close_handler,
  8654. mg_authorization_handler *auth_handler,
  8655. void **cbdata)
  8656. {
  8657. const struct mg_request_info *request_info = mg_get_request_info(conn);
  8658. if (request_info) {
  8659. const char *uri = request_info->local_uri;
  8660. size_t urilen = strlen(uri);
  8661. struct mg_handler_info *tmp_rh;
  8662. if (!conn || !conn->ctx) {
  8663. return 0;
  8664. }
  8665. mg_lock_context(conn->ctx);
  8666. /* first try for an exact match */
  8667. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8668. tmp_rh = tmp_rh->next) {
  8669. if (tmp_rh->handler_type == handler_type) {
  8670. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  8671. if (handler_type == WEBSOCKET_HANDLER) {
  8672. *connect_handler = tmp_rh->connect_handler;
  8673. *ready_handler = tmp_rh->ready_handler;
  8674. *data_handler = tmp_rh->data_handler;
  8675. *close_handler = tmp_rh->close_handler;
  8676. } else if (handler_type == REQUEST_HANDLER) {
  8677. *handler = tmp_rh->handler;
  8678. } else { /* AUTH_HANDLER */
  8679. *auth_handler = tmp_rh->auth_handler;
  8680. }
  8681. *cbdata = tmp_rh->cbdata;
  8682. mg_unlock_context(conn->ctx);
  8683. return 1;
  8684. }
  8685. }
  8686. }
  8687. /* next try for a partial match, we will accept uri/something */
  8688. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8689. tmp_rh = tmp_rh->next) {
  8690. if (tmp_rh->handler_type == handler_type) {
  8691. if (tmp_rh->uri_len < urilen && uri[tmp_rh->uri_len] == '/'
  8692. && memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0) {
  8693. if (handler_type == WEBSOCKET_HANDLER) {
  8694. *connect_handler = tmp_rh->connect_handler;
  8695. *ready_handler = tmp_rh->ready_handler;
  8696. *data_handler = tmp_rh->data_handler;
  8697. *close_handler = tmp_rh->close_handler;
  8698. } else if (handler_type == REQUEST_HANDLER) {
  8699. *handler = tmp_rh->handler;
  8700. } else { /* AUTH_HANDLER */
  8701. *auth_handler = tmp_rh->auth_handler;
  8702. }
  8703. *cbdata = tmp_rh->cbdata;
  8704. mg_unlock_context(conn->ctx);
  8705. return 1;
  8706. }
  8707. }
  8708. }
  8709. /* finally try for pattern match */
  8710. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8711. tmp_rh = tmp_rh->next) {
  8712. if (tmp_rh->handler_type == handler_type) {
  8713. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  8714. if (handler_type == WEBSOCKET_HANDLER) {
  8715. *connect_handler = tmp_rh->connect_handler;
  8716. *ready_handler = tmp_rh->ready_handler;
  8717. *data_handler = tmp_rh->data_handler;
  8718. *close_handler = tmp_rh->close_handler;
  8719. } else if (handler_type == REQUEST_HANDLER) {
  8720. *handler = tmp_rh->handler;
  8721. } else { /* AUTH_HANDLER */
  8722. *auth_handler = tmp_rh->auth_handler;
  8723. }
  8724. *cbdata = tmp_rh->cbdata;
  8725. mg_unlock_context(conn->ctx);
  8726. return 1;
  8727. }
  8728. }
  8729. }
  8730. mg_unlock_context(conn->ctx);
  8731. }
  8732. return 0; /* none found */
  8733. }
  8734. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  8735. static int
  8736. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  8737. void *cbdata)
  8738. {
  8739. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  8740. if (pcallbacks->websocket_connect) {
  8741. return pcallbacks->websocket_connect(conn);
  8742. }
  8743. /* No handler set - assume "OK" */
  8744. return 0;
  8745. }
  8746. static void
  8747. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  8748. {
  8749. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  8750. if (pcallbacks->websocket_ready) {
  8751. pcallbacks->websocket_ready(conn);
  8752. }
  8753. }
  8754. static int
  8755. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  8756. int bits,
  8757. char *data,
  8758. size_t len,
  8759. void *cbdata)
  8760. {
  8761. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  8762. if (pcallbacks->websocket_data) {
  8763. return pcallbacks->websocket_data(conn, bits, data, len);
  8764. }
  8765. /* No handler set - assume "OK" */
  8766. return 1;
  8767. }
  8768. #endif
  8769. /* This is the heart of the Civetweb's logic.
  8770. * This function is called when the request is read, parsed and validated,
  8771. * and Civetweb must decide what action to take: serve a file, or
  8772. * a directory, or call embedded function, etcetera. */
  8773. static void
  8774. handle_request(struct mg_connection *conn)
  8775. {
  8776. if (conn) {
  8777. struct mg_request_info *ri = &conn->request_info;
  8778. char path[PATH_MAX];
  8779. int uri_len, ssl_index;
  8780. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  8781. is_put_or_delete_request = 0, is_callback_resource = 0;
  8782. int i;
  8783. struct file file = STRUCT_FILE_INITIALIZER;
  8784. mg_request_handler callback_handler = NULL;
  8785. mg_websocket_connect_handler ws_connect_handler = NULL;
  8786. mg_websocket_ready_handler ws_ready_handler = NULL;
  8787. mg_websocket_data_handler ws_data_handler = NULL;
  8788. mg_websocket_close_handler ws_close_handler = NULL;
  8789. void *callback_data = NULL;
  8790. mg_authorization_handler auth_handler = NULL;
  8791. void *auth_callback_data = NULL;
  8792. #if !defined(NO_FILES)
  8793. time_t curtime = time(NULL);
  8794. char date[64];
  8795. #endif
  8796. path[0] = 0;
  8797. if (!ri) {
  8798. return;
  8799. }
  8800. /* 1. get the request url */
  8801. /* 1.1. split into url and query string */
  8802. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  8803. != NULL) {
  8804. *((char *)conn->request_info.query_string++) = '\0';
  8805. }
  8806. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  8807. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  8808. ssl_index = get_first_ssl_listener_index(conn->ctx);
  8809. if (ssl_index >= 0) {
  8810. redirect_to_https_port(conn, ssl_index);
  8811. } else {
  8812. /* A http to https forward port has been specified,
  8813. * but no https port to forward to. */
  8814. send_http_error(conn,
  8815. 503,
  8816. "%s",
  8817. "Error: SSL forward not configured properly");
  8818. mg_cry(conn, "Can not redirect to SSL, no SSL port available");
  8819. }
  8820. return;
  8821. }
  8822. uri_len = (int)strlen(ri->local_uri);
  8823. /* 1.3. decode url (if config says so) */
  8824. if (should_decode_url(conn)) {
  8825. mg_url_decode(
  8826. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  8827. }
  8828. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  8829. * not possible */
  8830. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  8831. /* step 1. completed, the url is known now */
  8832. uri_len = (int)strlen(ri->local_uri);
  8833. DEBUG_TRACE("URL: %s", ri->local_uri);
  8834. /* 3. if this ip has limited speed, set it for this connection */
  8835. conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
  8836. get_remote_ip(conn),
  8837. ri->local_uri);
  8838. /* 4. call a "handle everything" callback, if registered */
  8839. if (conn->ctx->callbacks.begin_request != NULL) {
  8840. /* Note that since V1.7 the "begin_request" function is called
  8841. * before an authorization check. If an authorization check is
  8842. * required, use a request_handler instead. */
  8843. i = conn->ctx->callbacks.begin_request(conn);
  8844. if (i > 0) {
  8845. /* callback already processed the request. Store the
  8846. return value as a status code for the access log. */
  8847. conn->status_code = i;
  8848. return;
  8849. } else if (i == 0) {
  8850. /* civetweb should process the request */
  8851. } else {
  8852. /* unspecified - may change with the next version */
  8853. return;
  8854. }
  8855. }
  8856. /* request not yet handled by a handler or redirect, so the request
  8857. * is processed here */
  8858. /* 5. interpret the url to find out how the request must be handled
  8859. */
  8860. /* 5.1. first test, if the request targets the regular http(s)://
  8861. * protocol namespace or the websocket ws(s):// protocol namespace.
  8862. */
  8863. is_websocket_request = is_websocket_protocol(conn);
  8864. /* 5.2. check if the request will be handled by a callback */
  8865. if (get_request_handler(conn,
  8866. is_websocket_request ? WEBSOCKET_HANDLER
  8867. : REQUEST_HANDLER,
  8868. &callback_handler,
  8869. &ws_connect_handler,
  8870. &ws_ready_handler,
  8871. &ws_data_handler,
  8872. &ws_close_handler,
  8873. NULL,
  8874. &callback_data)) {
  8875. /* 5.2.1. A callback will handle this request. All requests
  8876. * handled
  8877. * by a callback have to be considered as requests to a script
  8878. * resource. */
  8879. is_callback_resource = 1;
  8880. is_script_resource = 1;
  8881. is_put_or_delete_request = is_put_or_delete_method(conn);
  8882. } else {
  8883. no_callback_resource:
  8884. /* 5.2.2. No callback is responsible for this request. The URI
  8885. * addresses a file based resource (static content or Lua/cgi
  8886. * scripts in the file system). */
  8887. is_callback_resource = 0;
  8888. interpret_uri(conn,
  8889. path,
  8890. sizeof(path),
  8891. &file,
  8892. &is_found,
  8893. &is_script_resource,
  8894. &is_websocket_request,
  8895. &is_put_or_delete_request);
  8896. }
  8897. /* 6. authorization check */
  8898. /* 6.1. a custom authorization handler is installed */
  8899. if (get_request_handler(conn,
  8900. AUTH_HANDLER,
  8901. NULL,
  8902. NULL,
  8903. NULL,
  8904. NULL,
  8905. NULL,
  8906. &auth_handler,
  8907. &auth_callback_data)) {
  8908. if (!auth_handler(conn, auth_callback_data)) {
  8909. return;
  8910. }
  8911. } else if (is_put_or_delete_request && !is_script_resource
  8912. && !is_callback_resource) {
  8913. /* 6.2. this request is a PUT/DELETE to a real file */
  8914. /* 6.2.1. thus, the server must have real files */
  8915. #if defined(NO_FILES)
  8916. if (1) {
  8917. #else
  8918. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  8919. #endif
  8920. /* This server does not have any real files, thus the
  8921. * PUT/DELETE methods are not valid. */
  8922. send_http_error(conn,
  8923. 405,
  8924. "%s method not allowed",
  8925. conn->request_info.request_method);
  8926. return;
  8927. }
  8928. #if !defined(NO_FILES)
  8929. /* 6.2.2. Check if put authorization for static files is
  8930. * available.
  8931. */
  8932. if (!is_authorized_for_put(conn)) {
  8933. send_authorization_request(conn);
  8934. return;
  8935. }
  8936. #endif
  8937. } else {
  8938. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  8939. * or it is a PUT or DELETE request to a resource that does not
  8940. * correspond to a file. Check authorization. */
  8941. if (!check_authorization(conn, path)) {
  8942. send_authorization_request(conn);
  8943. return;
  8944. }
  8945. }
  8946. /* request is authorized or does not need authorization */
  8947. /* 7. check if there are request handlers for this uri */
  8948. if (is_callback_resource) {
  8949. if (!is_websocket_request) {
  8950. i = callback_handler(conn, callback_data);
  8951. if (i > 0) {
  8952. /* Do nothing, callback has served the request. Store
  8953. * the
  8954. * return value as status code for the log and discard
  8955. * all
  8956. * data from the client not used by the callback. */
  8957. conn->status_code = i;
  8958. discard_unread_request_data(conn);
  8959. } else {
  8960. /* TODO (high): what if the handler did NOT handle the
  8961. * request */
  8962. /* The last version did handle this as a file request,
  8963. * but
  8964. * since a file request is not always a script resource,
  8965. * the authorization check might be different */
  8966. interpret_uri(conn,
  8967. path,
  8968. sizeof(path),
  8969. &file,
  8970. &is_found,
  8971. &is_script_resource,
  8972. &is_websocket_request,
  8973. &is_put_or_delete_request);
  8974. callback_handler = NULL;
  8975. /* TODO (very low): goto is deprecated but for the
  8976. * moment,
  8977. * a goto is simpler than some curious loop. */
  8978. /* The situation "callback does not handle the request"
  8979. * needs to be reconsidered anyway. */
  8980. goto no_callback_resource;
  8981. }
  8982. } else {
  8983. #if defined(USE_WEBSOCKET)
  8984. handle_websocket_request(conn,
  8985. path,
  8986. is_callback_resource,
  8987. ws_connect_handler,
  8988. ws_ready_handler,
  8989. ws_data_handler,
  8990. ws_close_handler,
  8991. callback_data);
  8992. #endif
  8993. }
  8994. return;
  8995. }
  8996. /* 8. handle websocket requests */
  8997. #if defined(USE_WEBSOCKET)
  8998. if (is_websocket_request) {
  8999. if (is_script_resource) {
  9000. /* Websocket Lua script */
  9001. handle_websocket_request(conn,
  9002. path,
  9003. 0 /* Lua Script */,
  9004. NULL,
  9005. NULL,
  9006. NULL,
  9007. NULL,
  9008. &conn->ctx->callbacks);
  9009. } else {
  9010. #if defined(MG_LEGACY_INTERFACE)
  9011. handle_websocket_request(
  9012. conn,
  9013. path,
  9014. !is_script_resource /* could be deprecated global callback */,
  9015. deprecated_websocket_connect_wrapper,
  9016. deprecated_websocket_ready_wrapper,
  9017. deprecated_websocket_data_wrapper,
  9018. NULL,
  9019. &conn->ctx->callbacks);
  9020. #else
  9021. send_http_error(conn, 404, "%s", "Not found");
  9022. #endif
  9023. }
  9024. return;
  9025. } else
  9026. #endif
  9027. #if defined(NO_FILES)
  9028. /* 9a. In case the server uses only callbacks, this uri is
  9029. * unknown.
  9030. * Then, all request handling ends here. */
  9031. send_http_error(conn, 404, "%s", "Not Found");
  9032. #else
  9033. /* 9b. This request is either for a static file or resource handled
  9034. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  9035. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  9036. send_http_error(conn, 404, "%s", "Not Found");
  9037. return;
  9038. }
  9039. /* 10. File is handled by a script. */
  9040. if (is_script_resource) {
  9041. handle_file_based_request(conn, path, &file);
  9042. return;
  9043. }
  9044. /* 11. Handle put/delete/mkcol requests */
  9045. if (is_put_or_delete_request) {
  9046. /* 11.1. PUT method */
  9047. if (!strcmp(ri->request_method, "PUT")) {
  9048. put_file(conn, path);
  9049. return;
  9050. }
  9051. /* 11.2. DELETE method */
  9052. if (!strcmp(ri->request_method, "DELETE")) {
  9053. delete_file(conn, path);
  9054. return;
  9055. }
  9056. /* 11.3. MKCOL method */
  9057. if (!strcmp(ri->request_method, "MKCOL")) {
  9058. mkcol(conn, path);
  9059. return;
  9060. }
  9061. /* 11.4. PATCH method
  9062. * This method is not supported for static resources,
  9063. * only for scripts (Lua, CGI) and callbacks. */
  9064. send_http_error(conn,
  9065. 405,
  9066. "%s method not allowed",
  9067. conn->request_info.request_method);
  9068. return;
  9069. }
  9070. /* 11. File does not exist, or it was configured that it should be
  9071. * hidden */
  9072. if (!is_found || (must_hide_file(conn, path))) {
  9073. send_http_error(conn, 404, "%s", "Not found");
  9074. return;
  9075. }
  9076. /* 12. Directory uris should end with a slash */
  9077. if (file.is_directory && (uri_len > 0)
  9078. && (ri->local_uri[uri_len - 1] != '/')) {
  9079. gmt_time_string(date, sizeof(date), &curtime);
  9080. mg_printf(conn,
  9081. "HTTP/1.1 301 Moved Permanently\r\n"
  9082. "Location: %s/\r\n"
  9083. "Date: %s\r\n"
  9084. /* "Cache-Control: private\r\n" (= default) */
  9085. "Content-Length: 0\r\n"
  9086. "Connection: %s\r\n\r\n",
  9087. ri->request_uri,
  9088. date,
  9089. suggest_connection_header(conn));
  9090. return;
  9091. }
  9092. /* 13. Handle other methods than GET/HEAD */
  9093. /* 13.1. Handle PROPFIND */
  9094. if (!strcmp(ri->request_method, "PROPFIND")) {
  9095. handle_propfind(conn, path, &file);
  9096. return;
  9097. }
  9098. /* 13.2. Handle OPTIONS for files */
  9099. if (!strcmp(ri->request_method, "OPTIONS")) {
  9100. /* This standard handler is only used for real files.
  9101. * Scripts should support the OPTIONS method themselves, to allow a
  9102. * maximum flexibility.
  9103. * Lua and CGI scripts may fully support CORS this way (including
  9104. * preflights). */
  9105. send_options(conn);
  9106. return;
  9107. }
  9108. /* 13.3. everything but GET and HEAD (e.g. POST) */
  9109. if (0 != strcmp(ri->request_method, "GET")
  9110. && 0 != strcmp(ri->request_method, "HEAD")) {
  9111. send_http_error(conn,
  9112. 405,
  9113. "%s method not allowed",
  9114. conn->request_info.request_method);
  9115. return;
  9116. }
  9117. /* 14. directories */
  9118. if (file.is_directory) {
  9119. if (substitute_index_file(conn, path, sizeof(path), &file)) {
  9120. /* 14.1. use a substitute file */
  9121. /* TODO (high): substitute index may be a script resource.
  9122. * define what should be possible in this case. */
  9123. } else {
  9124. /* 14.2. no substitute file */
  9125. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  9126. "yes")) {
  9127. handle_directory_request(conn, path);
  9128. } else {
  9129. send_http_error(conn,
  9130. 403,
  9131. "%s",
  9132. "Error: Directory listing denied");
  9133. }
  9134. return;
  9135. }
  9136. }
  9137. handle_file_based_request(conn, path, &file);
  9138. #endif /* !defined(NO_FILES) */
  9139. #if 0
  9140. /* Perform redirect and auth checks before calling begin_request()
  9141. * handler.
  9142. * Otherwise, begin_request() would need to perform auth checks and
  9143. * redirects. */
  9144. #endif
  9145. }
  9146. return;
  9147. }
  9148. static void
  9149. handle_file_based_request(struct mg_connection *conn,
  9150. const char *path,
  9151. struct file *file)
  9152. {
  9153. if (!conn || !conn->ctx) {
  9154. return;
  9155. }
  9156. if (0) {
  9157. #ifdef USE_LUA
  9158. } else if (match_prefix(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  9159. strlen(
  9160. conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  9161. path) > 0) {
  9162. /* Lua server page: an SSI like page containing mostly plain html
  9163. * code
  9164. * plus some tags with server generated contents. */
  9165. handle_lsp_request(conn, path, file, NULL);
  9166. } else if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  9167. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  9168. path) > 0) {
  9169. /* Lua in-server module script: a CGI like script used to generate
  9170. * the
  9171. * entire reply. */
  9172. mg_exec_lua_script(conn, path, NULL);
  9173. #endif
  9174. #if defined(USE_DUKTAPE)
  9175. } else if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  9176. strlen(
  9177. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  9178. path) > 0) {
  9179. /* Call duktape to generate the page */
  9180. mg_exec_duktape_script(conn, path);
  9181. #endif
  9182. #if !defined(NO_CGI)
  9183. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  9184. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  9185. path) > 0) {
  9186. /* CGI scripts may support all HTTP methods */
  9187. handle_cgi_request(conn, path);
  9188. #endif /* !NO_CGI */
  9189. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  9190. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  9191. path) > 0) {
  9192. handle_ssi_file_request(conn, path, file);
  9193. #if !defined(NO_CACHING)
  9194. } else if ((!conn->in_error_handler) && is_not_modified(conn, file)) {
  9195. /* Send 304 "Not Modified" - this must not send any body data */
  9196. handle_not_modified_static_file_request(conn, file);
  9197. #endif /* !NO_CACHING */
  9198. } else {
  9199. handle_static_file_request(conn, path, file, NULL);
  9200. }
  9201. }
  9202. static void
  9203. close_all_listening_sockets(struct mg_context *ctx)
  9204. {
  9205. unsigned int i;
  9206. if (!ctx) {
  9207. return;
  9208. }
  9209. for (i = 0; i < ctx->num_listening_sockets; i++) {
  9210. closesocket(ctx->listening_sockets[i].sock);
  9211. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  9212. }
  9213. mg_free(ctx->listening_sockets);
  9214. ctx->listening_sockets = NULL;
  9215. mg_free(ctx->listening_socket_fds);
  9216. ctx->listening_socket_fds = NULL;
  9217. }
  9218. /* Valid listening port specification is: [ip_address:]port[s]
  9219. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 1.2.3.4:8080s
  9220. * Examples for IPv6: [::]:80, [::1]:80,
  9221. * [FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:443s
  9222. * see https://tools.ietf.org/html/rfc3513#section-2.2 */
  9223. static int
  9224. parse_port_string(const struct vec *vec, struct socket *so)
  9225. {
  9226. unsigned int a, b, c, d, port;
  9227. int ch, len;
  9228. #if defined(USE_IPV6)
  9229. char buf[100] = {0};
  9230. #endif
  9231. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  9232. * Also, all-zeroes in the socket address means binding to all addresses
  9233. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  9234. memset(so, 0, sizeof(*so));
  9235. so->lsa.sin.sin_family = AF_INET;
  9236. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  9237. == 5) {
  9238. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  9239. so->lsa.sin.sin_addr.s_addr =
  9240. htonl((a << 24) | (b << 16) | (c << 8) | d);
  9241. so->lsa.sin.sin_port = htons((uint16_t)port);
  9242. #if defined(USE_IPV6)
  9243. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  9244. && mg_inet_pton(
  9245. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  9246. /* IPv6 address, examples: see above */
  9247. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  9248. */
  9249. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  9250. #endif
  9251. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  9252. /* If only port is specified, bind to IPv4, INADDR_ANY */
  9253. so->lsa.sin.sin_port = htons((uint16_t)port);
  9254. } else {
  9255. /* Parsing failure. Make port invalid. */
  9256. port = 0;
  9257. len = 0;
  9258. }
  9259. /* sscanf and the option splitting code ensure the following condition
  9260. */
  9261. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  9262. return 0;
  9263. }
  9264. ch = vec->ptr[len]; /* Next character after the port number */
  9265. so->is_ssl = (ch == 's');
  9266. so->ssl_redir = (ch == 'r');
  9267. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  9268. return is_valid_port(port)
  9269. && (ch == '\0' || ch == 's' || ch == 'r' || ch == ',');
  9270. }
  9271. static int
  9272. set_ports_option(struct mg_context *ctx)
  9273. {
  9274. const char *list;
  9275. int on = 1;
  9276. #if defined(USE_IPV6)
  9277. int off = 0;
  9278. #endif
  9279. struct vec vec;
  9280. struct socket so, *ptr;
  9281. struct pollfd *pfd;
  9282. union usa usa;
  9283. socklen_t len;
  9284. int portsTotal = 0;
  9285. int portsOk = 0;
  9286. if (!ctx) {
  9287. return 0;
  9288. }
  9289. memset(&so, 0, sizeof(so));
  9290. memset(&usa, 0, sizeof(usa));
  9291. len = sizeof(usa);
  9292. list = ctx->config[LISTENING_PORTS];
  9293. while ((list = next_option(list, &vec, NULL)) != NULL) {
  9294. portsTotal++;
  9295. if (!parse_port_string(&vec, &so)) {
  9296. mg_cry(fc(ctx),
  9297. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  9298. (int)vec.len,
  9299. vec.ptr,
  9300. portsTotal,
  9301. "[IP_ADDRESS:]PORT[s|r]");
  9302. continue;
  9303. }
  9304. #if !defined(NO_SSL)
  9305. if (so.is_ssl && ctx->ssl_ctx == NULL) {
  9306. mg_cry(fc(ctx),
  9307. "Cannot add SSL socket (entry %i). Is -ssl_certificate "
  9308. "option set?",
  9309. portsTotal);
  9310. continue;
  9311. }
  9312. #endif
  9313. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  9314. == INVALID_SOCKET) {
  9315. mg_cry(fc(ctx), "cannot create socket (entry %i)", portsTotal);
  9316. continue;
  9317. }
  9318. #ifdef _WIN32
  9319. /* Windows SO_REUSEADDR lets many procs binds to a
  9320. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  9321. * if someone already has the socket -- DTL */
  9322. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  9323. * Windows might need a few seconds before
  9324. * the same port can be used again in the
  9325. * same process, so a short Sleep may be
  9326. * required between mg_stop and mg_start.
  9327. */
  9328. if (setsockopt(so.sock,
  9329. SOL_SOCKET,
  9330. SO_EXCLUSIVEADDRUSE,
  9331. (SOCK_OPT_TYPE)&on,
  9332. sizeof(on)) != 0) {
  9333. mg_cry(fc(ctx),
  9334. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  9335. portsTotal);
  9336. }
  9337. #else
  9338. if (setsockopt(so.sock,
  9339. SOL_SOCKET,
  9340. SO_REUSEADDR,
  9341. (SOCK_OPT_TYPE)&on,
  9342. sizeof(on)) != 0) {
  9343. mg_cry(fc(ctx),
  9344. "cannot set socket option SO_REUSEADDR (entry %i)",
  9345. portsTotal);
  9346. }
  9347. #endif
  9348. #if defined(USE_IPV6)
  9349. if (so.lsa.sa.sa_family == AF_INET6
  9350. && setsockopt(so.sock,
  9351. IPPROTO_IPV6,
  9352. IPV6_V6ONLY,
  9353. (void *)&off,
  9354. sizeof(off)) != 0) {
  9355. mg_cry(fc(ctx),
  9356. "cannot set socket option IPV6_V6ONLY (entry %i)",
  9357. portsTotal);
  9358. }
  9359. #endif
  9360. if (so.lsa.sa.sa_family == AF_INET) {
  9361. len = sizeof(so.lsa.sin);
  9362. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  9363. mg_cry(fc(ctx),
  9364. "cannot bind to %.*s: %d (%s)",
  9365. (int)vec.len,
  9366. vec.ptr,
  9367. (int)ERRNO,
  9368. strerror(errno));
  9369. closesocket(so.sock);
  9370. so.sock = INVALID_SOCKET;
  9371. continue;
  9372. }
  9373. }
  9374. #if defined(USE_IPV6)
  9375. else if (so.lsa.sa.sa_family == AF_INET6) {
  9376. len = sizeof(so.lsa.sin6);
  9377. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  9378. mg_cry(fc(ctx),
  9379. "cannot bind to IPv6 %.*s: %d (%s)",
  9380. (int)vec.len,
  9381. vec.ptr,
  9382. (int)ERRNO,
  9383. strerror(errno));
  9384. closesocket(so.sock);
  9385. so.sock = INVALID_SOCKET;
  9386. continue;
  9387. }
  9388. }
  9389. #endif
  9390. else {
  9391. mg_cry(fc(ctx),
  9392. "cannot bind: address family not supported (entry %i)",
  9393. portsTotal);
  9394. continue;
  9395. }
  9396. if (listen(so.sock, SOMAXCONN) != 0) {
  9397. mg_cry(fc(ctx),
  9398. "cannot listen to %.*s: %d (%s)",
  9399. (int)vec.len,
  9400. vec.ptr,
  9401. (int)ERRNO,
  9402. strerror(errno));
  9403. closesocket(so.sock);
  9404. so.sock = INVALID_SOCKET;
  9405. continue;
  9406. }
  9407. if (getsockname(so.sock, &(usa.sa), &len) != 0
  9408. || usa.sa.sa_family != so.lsa.sa.sa_family) {
  9409. int err = (int)ERRNO;
  9410. mg_cry(fc(ctx),
  9411. "call to getsockname failed %.*s: %d (%s)",
  9412. (int)vec.len,
  9413. vec.ptr,
  9414. err,
  9415. strerror(errno));
  9416. closesocket(so.sock);
  9417. so.sock = INVALID_SOCKET;
  9418. continue;
  9419. }
  9420. /* Update lsa port in case of random free ports */
  9421. #if defined(USE_IPV6)
  9422. if (so.lsa.sa.sa_family == AF_INET6) {
  9423. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  9424. } else
  9425. #endif
  9426. {
  9427. so.lsa.sin.sin_port = usa.sin.sin_port;
  9428. }
  9429. if ((ptr = (struct socket *)
  9430. mg_realloc(ctx->listening_sockets,
  9431. (ctx->num_listening_sockets + 1)
  9432. * sizeof(ctx->listening_sockets[0]))) == NULL) {
  9433. mg_cry(fc(ctx), "%s", "Out of memory");
  9434. closesocket(so.sock);
  9435. so.sock = INVALID_SOCKET;
  9436. continue;
  9437. }
  9438. if ((pfd = (struct pollfd *)mg_realloc(
  9439. ctx->listening_socket_fds,
  9440. (ctx->num_listening_sockets + 1)
  9441. * sizeof(ctx->listening_socket_fds[0]))) == NULL) {
  9442. mg_cry(fc(ctx), "%s", "Out of memory");
  9443. closesocket(so.sock);
  9444. so.sock = INVALID_SOCKET;
  9445. mg_free(ptr);
  9446. continue;
  9447. }
  9448. set_close_on_exec(so.sock, fc(ctx));
  9449. ctx->listening_sockets = ptr;
  9450. ctx->listening_sockets[ctx->num_listening_sockets] = so;
  9451. ctx->listening_socket_fds = pfd;
  9452. ctx->num_listening_sockets++;
  9453. portsOk++;
  9454. }
  9455. if (portsOk != portsTotal) {
  9456. close_all_listening_sockets(ctx);
  9457. portsOk = 0;
  9458. }
  9459. return portsOk;
  9460. }
  9461. static const char *
  9462. header_val(const struct mg_connection *conn, const char *header)
  9463. {
  9464. const char *header_value;
  9465. if ((header_value = mg_get_header(conn, header)) == NULL) {
  9466. return "-";
  9467. } else {
  9468. return header_value;
  9469. }
  9470. }
  9471. static void
  9472. log_access(const struct mg_connection *conn)
  9473. {
  9474. const struct mg_request_info *ri;
  9475. struct file fi;
  9476. char date[64], src_addr[IP_ADDR_STR_LEN];
  9477. struct tm *tm;
  9478. const char *referer;
  9479. const char *user_agent;
  9480. char buf[4096];
  9481. if (!conn || !conn->ctx) {
  9482. return;
  9483. }
  9484. if (conn->ctx->config[ACCESS_LOG_FILE] != NULL) {
  9485. if (mg_fopen(conn, conn->ctx->config[ACCESS_LOG_FILE], "a+", &fi)
  9486. == 0) {
  9487. fi.fp = NULL;
  9488. }
  9489. } else {
  9490. fi.fp = NULL;
  9491. }
  9492. /* Log is written to a file and/or a callback. If both are not set,
  9493. * executing the rest of the function is pointless. */
  9494. if ((fi.fp == NULL) && (conn->ctx->callbacks.log_access == NULL)) {
  9495. return;
  9496. }
  9497. tm = localtime(&conn->conn_birth_time);
  9498. if (tm != NULL) {
  9499. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  9500. } else {
  9501. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  9502. date[sizeof(date) - 1] = '\0';
  9503. }
  9504. ri = &conn->request_info;
  9505. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9506. referer = header_val(conn, "Referer");
  9507. user_agent = header_val(conn, "User-Agent");
  9508. mg_snprintf(conn,
  9509. NULL, /* Ignore truncation in access log */
  9510. buf,
  9511. sizeof(buf),
  9512. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  9513. src_addr,
  9514. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  9515. date,
  9516. ri->request_method ? ri->request_method : "-",
  9517. ri->request_uri ? ri->request_uri : "-",
  9518. ri->query_string ? "?" : "",
  9519. ri->query_string ? ri->query_string : "",
  9520. ri->http_version,
  9521. conn->status_code,
  9522. conn->num_bytes_sent,
  9523. referer,
  9524. user_agent);
  9525. if (conn->ctx->callbacks.log_access) {
  9526. conn->ctx->callbacks.log_access(conn, buf);
  9527. }
  9528. if (fi.fp) {
  9529. flockfile(fi.fp);
  9530. fprintf(fi.fp, "%s\n", buf);
  9531. fflush(fi.fp);
  9532. funlockfile(fi.fp);
  9533. mg_fclose(&fi);
  9534. }
  9535. }
  9536. /* Verify given socket address against the ACL.
  9537. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  9538. */
  9539. static int
  9540. check_acl(struct mg_context *ctx, uint32_t remote_ip)
  9541. {
  9542. int allowed, flag;
  9543. uint32_t net, mask;
  9544. struct vec vec;
  9545. if (ctx) {
  9546. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  9547. /* If any ACL is set, deny by default */
  9548. allowed = (list == NULL) ? '+' : '-';
  9549. while ((list = next_option(list, &vec, NULL)) != NULL) {
  9550. flag = vec.ptr[0];
  9551. if ((flag != '+' && flag != '-')
  9552. || parse_net(&vec.ptr[1], &net, &mask) == 0) {
  9553. mg_cry(fc(ctx),
  9554. "%s: subnet must be [+|-]x.x.x.x[/x]",
  9555. __func__);
  9556. return -1;
  9557. }
  9558. if (net == (remote_ip & mask)) {
  9559. allowed = flag;
  9560. }
  9561. }
  9562. return allowed == '+';
  9563. }
  9564. return -1;
  9565. }
  9566. #if !defined(_WIN32)
  9567. static int
  9568. set_uid_option(struct mg_context *ctx)
  9569. {
  9570. struct passwd *pw;
  9571. if (ctx) {
  9572. const char *uid = ctx->config[RUN_AS_USER];
  9573. int success = 0;
  9574. if (uid == NULL) {
  9575. success = 1;
  9576. } else {
  9577. if ((pw = getpwnam(uid)) == NULL) {
  9578. mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  9579. } else if (setgid(pw->pw_gid) == -1) {
  9580. mg_cry(fc(ctx),
  9581. "%s: setgid(%s): %s",
  9582. __func__,
  9583. uid,
  9584. strerror(errno));
  9585. } else if (setgroups(0, NULL)) {
  9586. mg_cry(fc(ctx),
  9587. "%s: setgroups(): %s",
  9588. __func__,
  9589. strerror(errno));
  9590. } else if (setuid(pw->pw_uid) == -1) {
  9591. mg_cry(fc(ctx),
  9592. "%s: setuid(%s): %s",
  9593. __func__,
  9594. uid,
  9595. strerror(errno));
  9596. } else {
  9597. success = 1;
  9598. }
  9599. }
  9600. return success;
  9601. }
  9602. return 0;
  9603. }
  9604. #endif /* !_WIN32 */
  9605. static void
  9606. tls_dtor(void *key)
  9607. {
  9608. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  9609. /* key == pthread_getspecific(sTlsKey); */
  9610. if (tls) {
  9611. if (tls->is_master == 2) {
  9612. tls->is_master = -3; /* Mark memory as dead */
  9613. mg_free(tls);
  9614. }
  9615. }
  9616. pthread_setspecific(sTlsKey, NULL);
  9617. }
  9618. #if !defined(NO_SSL)
  9619. /* Must be set if sizeof(pthread_t) > sizeof(unsigned long) */
  9620. static unsigned long
  9621. ssl_id_callback(void)
  9622. {
  9623. #ifdef _WIN32
  9624. return GetCurrentThreadId();
  9625. #else
  9626. #ifdef __clang__
  9627. #pragma clang diagnostic push
  9628. #pragma clang diagnostic ignored "-Wunreachable-code"
  9629. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  9630. * or not, so one of the two conditions will be unreachable by construction.
  9631. * Unfortunately the C standard does not define a way to check this at
  9632. * compile time, since the #if preprocessor conditions can not use the sizeof
  9633. * operator as an argument. */
  9634. #endif
  9635. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  9636. /* This is the problematic case for CRYPTO_set_id_callback:
  9637. * The OS pthread_t can not be cast to unsigned long. */
  9638. struct mg_workerTLS *tls =
  9639. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  9640. if (tls == NULL) {
  9641. /* SSL called from an unknown thread: Create some thread index.
  9642. */
  9643. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  9644. tls->is_master = -2; /* -2 means "3rd party thread" */
  9645. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  9646. pthread_setspecific(sTlsKey, tls);
  9647. }
  9648. return tls->thread_idx;
  9649. } else {
  9650. /* pthread_t may be any data type, so a simple cast to unsigned long
  9651. * can rise a warning/error, depending on the platform.
  9652. * Here memcpy is used as an anything-to-anything cast. */
  9653. unsigned long ret = 0;
  9654. pthread_t t = pthread_self();
  9655. memcpy(&ret, &t, sizeof(pthread_t));
  9656. return ret;
  9657. }
  9658. #ifdef __clang__
  9659. #pragma clang diagnostic pop
  9660. #endif
  9661. #endif
  9662. }
  9663. static int ssl_use_pem_file(struct mg_context *ctx, const char *pem);
  9664. static const char *ssl_error(void);
  9665. static int
  9666. refresh_trust(struct mg_connection *conn)
  9667. {
  9668. static int reload_lock = 0;
  9669. static long int data_check = 0;
  9670. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  9671. struct stat cert_buf;
  9672. long int t;
  9673. char *pem;
  9674. int should_verify_peer;
  9675. if ((pem = conn->ctx->config[SSL_CERTIFICATE]) == NULL
  9676. && conn->ctx->callbacks.init_ssl == NULL) {
  9677. return 0;
  9678. }
  9679. t = data_check;
  9680. if (stat(pem, &cert_buf) != -1) {
  9681. t = (long int)cert_buf.st_mtime;
  9682. }
  9683. if (data_check != t) {
  9684. data_check = t;
  9685. should_verify_peer =
  9686. (conn->ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  9687. && (mg_strcasecmp(conn->ctx->config[SSL_DO_VERIFY_PEER], "yes")
  9688. == 0);
  9689. if (should_verify_peer) {
  9690. char *ca_path = conn->ctx->config[SSL_CA_PATH];
  9691. char *ca_file = conn->ctx->config[SSL_CA_FILE];
  9692. if (SSL_CTX_load_verify_locations(conn->ctx->ssl_ctx,
  9693. ca_file,
  9694. ca_path) != 1) {
  9695. mg_cry(fc(conn->ctx),
  9696. "SSL_CTX_load_verify_locations error: %s "
  9697. "ssl_verify_peer requires setting "
  9698. "either ssl_ca_path or ssl_ca_file. Is any of them "
  9699. "present in "
  9700. "the .conf file?",
  9701. ssl_error());
  9702. return 0;
  9703. }
  9704. }
  9705. if (1 == mg_atomic_inc(p_reload_lock)) {
  9706. if (ssl_use_pem_file(conn->ctx, pem) == 0) {
  9707. return 0;
  9708. }
  9709. *p_reload_lock = 0;
  9710. }
  9711. }
  9712. /* lock while cert is reloading */
  9713. while (*p_reload_lock) {
  9714. sleep(1);
  9715. }
  9716. return 1;
  9717. }
  9718. static pthread_mutex_t *ssl_mutexes;
  9719. static int
  9720. sslize(struct mg_connection *conn, SSL_CTX *s, int (*func)(SSL *))
  9721. {
  9722. int ret, err;
  9723. int short_trust;
  9724. unsigned i;
  9725. if (!conn) {
  9726. return 0;
  9727. }
  9728. short_trust =
  9729. (conn->ctx->config[SSL_SHORT_TRUST] != NULL)
  9730. && (mg_strcasecmp(conn->ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  9731. if (short_trust) {
  9732. int trust_ret = refresh_trust(conn);
  9733. if (!trust_ret) {
  9734. return trust_ret;
  9735. }
  9736. }
  9737. conn->ssl = SSL_new(s);
  9738. if (conn->ssl == NULL) {
  9739. return 0;
  9740. }
  9741. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  9742. if (ret != 1) {
  9743. err = SSL_get_error(conn->ssl, ret);
  9744. (void)err; /* TODO: set some error message */
  9745. SSL_free(conn->ssl);
  9746. conn->ssl = NULL;
  9747. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  9748. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  9749. ERR_remove_state(0);
  9750. return 0;
  9751. }
  9752. /* SSL functions may fail and require to be called again:
  9753. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  9754. * Here "func" could be SSL_connect or SSL_accept. */
  9755. for (i = 0; i <= 16; i *= 2) {
  9756. ret = func(conn->ssl);
  9757. if (ret != 1) {
  9758. err = SSL_get_error(conn->ssl, ret);
  9759. if ((err == SSL_ERROR_WANT_CONNECT)
  9760. || (err == SSL_ERROR_WANT_ACCEPT)) {
  9761. /* Retry */
  9762. mg_sleep(i);
  9763. } else {
  9764. /* This is an error */
  9765. /* TODO: set some error message */
  9766. break;
  9767. }
  9768. } else {
  9769. /* success */
  9770. break;
  9771. }
  9772. }
  9773. if (ret != 1) {
  9774. SSL_free(conn->ssl);
  9775. conn->ssl = NULL;
  9776. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  9777. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  9778. ERR_remove_state(0);
  9779. return 0;
  9780. }
  9781. return 1;
  9782. }
  9783. /* Return OpenSSL error message (from CRYPTO lib) */
  9784. static const char *
  9785. ssl_error(void)
  9786. {
  9787. unsigned long err;
  9788. err = ERR_get_error();
  9789. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  9790. }
  9791. static int
  9792. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  9793. {
  9794. int i;
  9795. const char hexdigit[] = "0123456789abcdef";
  9796. if (memlen <= 0 || buflen <= 0) {
  9797. return 0;
  9798. }
  9799. if (buflen < (3 * memlen)) {
  9800. return 0;
  9801. }
  9802. for (i = 0; i < memlen; i++) {
  9803. if (i > 0) {
  9804. buf[3 * i - 1] = ' ';
  9805. }
  9806. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  9807. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  9808. }
  9809. buf[3 * memlen - 1] = 0;
  9810. return 1;
  9811. }
  9812. static void
  9813. ssl_get_client_cert_info(struct mg_connection *conn)
  9814. {
  9815. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  9816. if (cert) {
  9817. char str_subject[1024];
  9818. char str_issuer[1024];
  9819. char str_serial[1024];
  9820. char str_finger[1024];
  9821. unsigned char buf[256];
  9822. int len;
  9823. unsigned int ulen;
  9824. /* Handle to algorithm used for fingerprint */
  9825. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  9826. /* Get Subject and issuer */
  9827. X509_NAME *subj = X509_get_subject_name(cert);
  9828. X509_NAME *iss = X509_get_issuer_name(cert);
  9829. /* Get serial number */
  9830. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  9831. /* Translate subject and issuer to a string */
  9832. (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
  9833. (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
  9834. /* Translate serial number to a hex string */
  9835. len = i2c_ASN1_INTEGER(serial, NULL);
  9836. if ((len > 0) && ((unsigned)len < (unsigned)sizeof(buf))) {
  9837. unsigned char *pbuf = buf;
  9838. int len2 = i2c_ASN1_INTEGER(serial, &pbuf);
  9839. if (!hexdump2string(
  9840. buf, len2, str_serial, (int)sizeof(str_serial))) {
  9841. *str_serial = 0;
  9842. }
  9843. } else {
  9844. *str_serial = 0;
  9845. }
  9846. /* Calculate SHA1 fingerprint and store as a hex string */
  9847. ulen = 0;
  9848. ASN1_digest((int (*)())i2d_X509, digest, (char *)cert, buf, &ulen);
  9849. if (!hexdump2string(
  9850. buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
  9851. *str_finger = 0;
  9852. }
  9853. conn->request_info.client_cert =
  9854. (struct client_cert *)mg_malloc(sizeof(struct client_cert));
  9855. if (conn->request_info.client_cert) {
  9856. conn->request_info.client_cert->subject = mg_strdup(str_subject);
  9857. conn->request_info.client_cert->issuer = mg_strdup(str_issuer);
  9858. conn->request_info.client_cert->serial = mg_strdup(str_serial);
  9859. conn->request_info.client_cert->finger = mg_strdup(str_finger);
  9860. } else {
  9861. /* TODO: write some OOM message */
  9862. }
  9863. X509_free(cert);
  9864. }
  9865. }
  9866. static void
  9867. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  9868. {
  9869. (void)line;
  9870. (void)file;
  9871. if (mode & 1) {
  9872. /* 1 is CRYPTO_LOCK */
  9873. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  9874. } else {
  9875. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  9876. }
  9877. }
  9878. #if !defined(NO_SSL_DL)
  9879. static void *
  9880. load_dll(struct mg_context *ctx, const char *dll_name, struct ssl_func *sw)
  9881. {
  9882. union {
  9883. void *p;
  9884. void (*fp)(void);
  9885. } u;
  9886. void *dll_handle;
  9887. struct ssl_func *fp;
  9888. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  9889. mg_cry(fc(ctx), "%s: cannot load %s", __func__, dll_name);
  9890. return NULL;
  9891. }
  9892. for (fp = sw; fp->name != NULL; fp++) {
  9893. #ifdef _WIN32
  9894. /* GetProcAddress() returns pointer to function */
  9895. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  9896. #else
  9897. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  9898. * pointers to function pointers. We need to use a union to make a
  9899. * cast. */
  9900. u.p = dlsym(dll_handle, fp->name);
  9901. #endif /* _WIN32 */
  9902. if (u.fp == NULL) {
  9903. mg_cry(fc(ctx),
  9904. "%s: %s: cannot find %s",
  9905. __func__,
  9906. dll_name,
  9907. fp->name);
  9908. dlclose(dll_handle);
  9909. return NULL;
  9910. } else {
  9911. fp->ptr = u.fp;
  9912. }
  9913. }
  9914. return dll_handle;
  9915. }
  9916. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  9917. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  9918. #endif /* NO_SSL_DL */
  9919. #if defined(SSL_ALREADY_INITIALIZED)
  9920. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  9921. #else
  9922. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  9923. #endif
  9924. static int
  9925. initialize_ssl(struct mg_context *ctx)
  9926. {
  9927. int i;
  9928. size_t size;
  9929. #if !defined(NO_SSL_DL)
  9930. if (!cryptolib_dll_handle) {
  9931. cryptolib_dll_handle = load_dll(ctx, CRYPTO_LIB, crypto_sw);
  9932. if (!cryptolib_dll_handle) {
  9933. return 0;
  9934. }
  9935. }
  9936. #endif /* NO_SSL_DL */
  9937. if (mg_atomic_inc(&cryptolib_users) > 1) {
  9938. return 1;
  9939. }
  9940. /* Initialize locking callbacks, needed for thread safety.
  9941. * http://www.openssl.org/support/faq.html#PROG1
  9942. */
  9943. i = CRYPTO_num_locks();
  9944. if (i < 0) {
  9945. i = 0;
  9946. }
  9947. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  9948. if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  9949. mg_cry(fc(ctx),
  9950. "%s: cannot allocate mutexes: %s",
  9951. __func__,
  9952. ssl_error());
  9953. return 0;
  9954. }
  9955. for (i = 0; i < CRYPTO_num_locks(); i++) {
  9956. pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr);
  9957. }
  9958. CRYPTO_set_locking_callback(&ssl_locking_callback);
  9959. CRYPTO_set_id_callback(&ssl_id_callback);
  9960. return 1;
  9961. }
  9962. static int
  9963. ssl_use_pem_file(struct mg_context *ctx, const char *pem)
  9964. {
  9965. if (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0) {
  9966. mg_cry(fc(ctx),
  9967. "%s: cannot open certificate file %s: %s",
  9968. __func__,
  9969. pem,
  9970. ssl_error());
  9971. return 0;
  9972. }
  9973. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  9974. if (SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0) {
  9975. mg_cry(fc(ctx),
  9976. "%s: cannot open private key file %s: %s",
  9977. __func__,
  9978. pem,
  9979. ssl_error());
  9980. return 0;
  9981. }
  9982. if (SSL_CTX_check_private_key(ctx->ssl_ctx) == 0) {
  9983. mg_cry(fc(ctx),
  9984. "%s: certificate and private key do not match: %s",
  9985. __func__,
  9986. pem);
  9987. return 0;
  9988. }
  9989. if (SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem) == 0) {
  9990. mg_cry(fc(ctx),
  9991. "%s: cannot use certificate chain file %s: %s",
  9992. __func__,
  9993. pem,
  9994. ssl_error());
  9995. return 0;
  9996. }
  9997. return 1;
  9998. }
  9999. static long
  10000. ssl_get_protocol(int version_id)
  10001. {
  10002. long ret = SSL_OP_ALL;
  10003. if (version_id > 0)
  10004. ret |= SSL_OP_NO_SSLv2;
  10005. if (version_id > 1)
  10006. ret |= SSL_OP_NO_SSLv3;
  10007. if (version_id > 2)
  10008. ret |= SSL_OP_NO_TLSv1;
  10009. if (version_id > 3)
  10010. ret |= SSL_OP_NO_TLSv1_1;
  10011. return ret;
  10012. }
  10013. /* Dynamically load SSL library. Set up ctx->ssl_ctx pointer. */
  10014. static int
  10015. set_ssl_option(struct mg_context *ctx)
  10016. {
  10017. const char *pem;
  10018. int callback_ret;
  10019. int should_verify_peer;
  10020. const char *ca_path;
  10021. const char *ca_file;
  10022. int use_default_verify_paths;
  10023. int verify_depth;
  10024. time_t now_rt = time(NULL);
  10025. struct timespec now_mt;
  10026. md5_byte_t ssl_context_id[16];
  10027. md5_state_t md5state;
  10028. int protocol_ver;
  10029. /* If PEM file is not specified and the init_ssl callback
  10030. * is not specified, skip SSL initialization. */
  10031. if (!ctx) {
  10032. return 0;
  10033. }
  10034. if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL
  10035. && ctx->callbacks.init_ssl == NULL) {
  10036. return 1;
  10037. }
  10038. if (!initialize_ssl(ctx)) {
  10039. return 0;
  10040. }
  10041. #if !defined(NO_SSL_DL)
  10042. if (!ssllib_dll_handle) {
  10043. ssllib_dll_handle = load_dll(ctx, SSL_LIB, ssl_sw);
  10044. if (!ssllib_dll_handle) {
  10045. return 0;
  10046. }
  10047. }
  10048. #endif /* NO_SSL_DL */
  10049. /* Initialize SSL library */
  10050. SSL_library_init();
  10051. SSL_load_error_strings();
  10052. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  10053. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  10054. return 0;
  10055. }
  10056. SSL_CTX_clear_options(ctx->ssl_ctx,
  10057. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  10058. | SSL_OP_NO_TLSv1_1);
  10059. protocol_ver = atoi(ctx->config[SSL_PROTOCOL_VERSION]);
  10060. SSL_CTX_set_options(ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  10061. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  10062. SSL_CTX_set_ecdh_auto(ctx->ssl_ctx, 1);
  10063. /* If a callback has been specified, call it. */
  10064. callback_ret =
  10065. (ctx->callbacks.init_ssl == NULL)
  10066. ? 0
  10067. : (ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data));
  10068. /* If callback returns 0, civetweb sets up the SSL certificate.
  10069. * If it returns 1, civetweb assumes the calback already did this.
  10070. * If it returns -1, initializing ssl fails. */
  10071. if (callback_ret < 0) {
  10072. mg_cry(fc(ctx), "SSL callback returned error: %i", callback_ret);
  10073. return 0;
  10074. }
  10075. if (callback_ret > 0) {
  10076. if (pem != NULL) {
  10077. (void)SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
  10078. }
  10079. return 1;
  10080. }
  10081. /* Use some UID as session context ID. */
  10082. md5_init(&md5state);
  10083. md5_append(&md5state, (const md5_byte_t *)&now_rt, sizeof(now_rt));
  10084. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  10085. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  10086. md5_append(&md5state,
  10087. (const md5_byte_t *)ctx->config[LISTENING_PORTS],
  10088. strlen(ctx->config[LISTENING_PORTS]));
  10089. md5_append(&md5state, (const md5_byte_t *)ctx, sizeof(*ctx));
  10090. md5_finish(&md5state, ssl_context_id);
  10091. SSL_CTX_set_session_id_context(ctx->ssl_ctx,
  10092. (const unsigned char *)&ssl_context_id,
  10093. sizeof(ssl_context_id));
  10094. if (pem != NULL) {
  10095. if (!ssl_use_pem_file(ctx, pem)) {
  10096. return 0;
  10097. }
  10098. }
  10099. should_verify_peer =
  10100. (ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  10101. && (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0);
  10102. use_default_verify_paths =
  10103. (ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  10104. && (mg_strcasecmp(ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes") == 0);
  10105. if (should_verify_peer) {
  10106. ca_path = ctx->config[SSL_CA_PATH];
  10107. ca_file = ctx->config[SSL_CA_FILE];
  10108. if (SSL_CTX_load_verify_locations(ctx->ssl_ctx, ca_file, ca_path)
  10109. != 1) {
  10110. mg_cry(fc(ctx),
  10111. "SSL_CTX_load_verify_locations error: %s "
  10112. "ssl_verify_peer requires setting "
  10113. "either ssl_ca_path or ssl_ca_file. Is any of them "
  10114. "present in "
  10115. "the .conf file?",
  10116. ssl_error());
  10117. return 0;
  10118. }
  10119. SSL_CTX_set_verify(ctx->ssl_ctx,
  10120. SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  10121. NULL);
  10122. if (use_default_verify_paths
  10123. && SSL_CTX_set_default_verify_paths(ctx->ssl_ctx) != 1) {
  10124. mg_cry(fc(ctx),
  10125. "SSL_CTX_set_default_verify_paths error: %s",
  10126. ssl_error());
  10127. return 0;
  10128. }
  10129. if (ctx->config[SSL_VERIFY_DEPTH]) {
  10130. verify_depth = atoi(ctx->config[SSL_VERIFY_DEPTH]);
  10131. SSL_CTX_set_verify_depth(ctx->ssl_ctx, verify_depth);
  10132. }
  10133. }
  10134. if (ctx->config[SSL_CIPHER_LIST] != NULL) {
  10135. if (SSL_CTX_set_cipher_list(ctx->ssl_ctx, ctx->config[SSL_CIPHER_LIST])
  10136. != 1) {
  10137. mg_cry(fc(ctx), "SSL_CTX_set_cipher_list error: %s", ssl_error());
  10138. }
  10139. }
  10140. return 1;
  10141. }
  10142. static void
  10143. uninitialize_ssl(struct mg_context *ctx)
  10144. {
  10145. int i;
  10146. (void)ctx;
  10147. if (mg_atomic_dec(&cryptolib_users) == 0) {
  10148. /* Shutdown according to
  10149. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  10150. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  10151. */
  10152. CRYPTO_set_locking_callback(NULL);
  10153. CRYPTO_set_id_callback(NULL);
  10154. ENGINE_cleanup();
  10155. CONF_modules_unload(1);
  10156. ERR_free_strings();
  10157. EVP_cleanup();
  10158. CRYPTO_cleanup_all_ex_data();
  10159. ERR_remove_state(0);
  10160. for (i = 0; i < CRYPTO_num_locks(); i++) {
  10161. pthread_mutex_destroy(&ssl_mutexes[i]);
  10162. }
  10163. mg_free(ssl_mutexes);
  10164. ssl_mutexes = NULL;
  10165. }
  10166. }
  10167. #endif /* !NO_SSL */
  10168. static int
  10169. set_gpass_option(struct mg_context *ctx)
  10170. {
  10171. if (ctx) {
  10172. struct file file = STRUCT_FILE_INITIALIZER;
  10173. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  10174. if (path != NULL && !mg_stat(fc(ctx), path, &file)) {
  10175. mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  10176. return 0;
  10177. }
  10178. return 1;
  10179. }
  10180. return 0;
  10181. }
  10182. static int
  10183. set_acl_option(struct mg_context *ctx)
  10184. {
  10185. return check_acl(ctx, (uint32_t)0x7f000001UL) != -1;
  10186. }
  10187. static void
  10188. reset_per_request_attributes(struct mg_connection *conn)
  10189. {
  10190. if (!conn) {
  10191. return;
  10192. }
  10193. conn->path_info = NULL;
  10194. conn->num_bytes_sent = conn->consumed_content = 0;
  10195. conn->status_code = -1;
  10196. conn->is_chunked = 0;
  10197. conn->must_close = conn->request_len = conn->throttle = 0;
  10198. conn->request_info.content_length = -1;
  10199. conn->request_info.remote_user = NULL;
  10200. conn->request_info.request_method = NULL;
  10201. conn->request_info.request_uri = NULL;
  10202. conn->request_info.local_uri = NULL;
  10203. conn->request_info.uri = NULL; /* TODO: cleanup uri,
  10204. * local_uri and request_uri */
  10205. conn->request_info.http_version = NULL;
  10206. conn->request_info.num_headers = 0;
  10207. conn->data_len = 0;
  10208. conn->chunk_remainder = 0;
  10209. conn->internal_error = 0;
  10210. }
  10211. static int
  10212. set_sock_timeout(SOCKET sock, int milliseconds)
  10213. {
  10214. int r0 = 0, r1, r2;
  10215. #ifdef _WIN32
  10216. /* Windows specific */
  10217. DWORD tv = (DWORD)milliseconds;
  10218. #else
  10219. /* Linux, ... (not Windows) */
  10220. struct timeval tv;
  10221. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  10222. * max. time waiting for the acknowledged of TCP data before the connection
  10223. * will be forcefully closed and ETIMEDOUT is returned to the application.
  10224. * If this option is not set, the default timeout of 20-30 minutes is used.
  10225. */
  10226. /* #define TCP_USER_TIMEOUT (18) */
  10227. #if defined(TCP_USER_TIMEOUT)
  10228. unsigned int uto = (unsigned int)milliseconds;
  10229. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  10230. #endif
  10231. memset(&tv, 0, sizeof(tv));
  10232. tv.tv_sec = milliseconds / 1000;
  10233. tv.tv_usec = (milliseconds * 1000) % 1000000;
  10234. #endif /* _WIN32 */
  10235. r1 = setsockopt(
  10236. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  10237. r2 = setsockopt(
  10238. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  10239. return r0 || r1 || r2;
  10240. }
  10241. static int
  10242. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  10243. {
  10244. if (setsockopt(sock,
  10245. IPPROTO_TCP,
  10246. TCP_NODELAY,
  10247. (SOCK_OPT_TYPE)&nodelay_on,
  10248. sizeof(nodelay_on)) != 0) {
  10249. /* Error */
  10250. return 1;
  10251. }
  10252. /* OK */
  10253. return 0;
  10254. }
  10255. static void
  10256. close_socket_gracefully(struct mg_connection *conn)
  10257. {
  10258. #if defined(_WIN32)
  10259. char buf[MG_BUF_LEN];
  10260. int n;
  10261. #endif
  10262. struct linger linger;
  10263. if (!conn) {
  10264. return;
  10265. }
  10266. /* Set linger option to avoid socket hanging out after close. This
  10267. * prevent
  10268. * ephemeral port exhaust problem under high QPS. */
  10269. linger.l_onoff = 1;
  10270. linger.l_linger = 1;
  10271. if (setsockopt(conn->client.sock,
  10272. SOL_SOCKET,
  10273. SO_LINGER,
  10274. (char *)&linger,
  10275. sizeof(linger)) != 0) {
  10276. mg_cry(conn,
  10277. "%s: setsockopt(SOL_SOCKET SO_LINGER) failed: %s",
  10278. __func__,
  10279. strerror(ERRNO));
  10280. }
  10281. /* Send FIN to the client */
  10282. shutdown(conn->client.sock, SHUTDOWN_WR);
  10283. set_non_blocking_mode(conn->client.sock);
  10284. #if defined(_WIN32)
  10285. /* Read and discard pending incoming data. If we do not do that and
  10286. * close
  10287. * the socket, the data in the send buffer may be discarded. This
  10288. * behaviour is seen on Windows, when client keeps sending data
  10289. * when server decides to close the connection; then when client
  10290. * does recv() it gets no data back. */
  10291. do {
  10292. n = pull(
  10293. NULL, conn, buf, sizeof(buf), 1E-10 /* TODO: allow 0 as timeout */);
  10294. } while (n > 0);
  10295. #endif
  10296. /* Now we know that our FIN is ACK-ed, safe to close */
  10297. closesocket(conn->client.sock);
  10298. conn->client.sock = INVALID_SOCKET;
  10299. }
  10300. static void
  10301. close_connection(struct mg_connection *conn)
  10302. {
  10303. if (!conn || !conn->ctx) {
  10304. return;
  10305. }
  10306. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  10307. if (conn->lua_websocket_state) {
  10308. lua_websocket_close(conn, conn->lua_websocket_state);
  10309. conn->lua_websocket_state = NULL;
  10310. }
  10311. #endif
  10312. /* call the connection_close callback if assigned */
  10313. if ((conn->ctx->callbacks.connection_close != NULL)
  10314. && (conn->ctx->context_type == 1)) {
  10315. conn->ctx->callbacks.connection_close(conn);
  10316. }
  10317. mg_lock_connection(conn);
  10318. conn->must_close = 1;
  10319. #ifndef NO_SSL
  10320. if (conn->ssl != NULL) {
  10321. /* Run SSL_shutdown twice to ensure completly close SSL connection
  10322. */
  10323. SSL_shutdown(conn->ssl);
  10324. SSL_free(conn->ssl);
  10325. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  10326. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  10327. ERR_remove_state(0);
  10328. conn->ssl = NULL;
  10329. }
  10330. #endif
  10331. if (conn->client.sock != INVALID_SOCKET) {
  10332. close_socket_gracefully(conn);
  10333. conn->client.sock = INVALID_SOCKET;
  10334. }
  10335. mg_unlock_connection(conn);
  10336. }
  10337. void
  10338. mg_close_connection(struct mg_connection *conn)
  10339. {
  10340. struct mg_context *client_ctx = NULL;
  10341. unsigned int i;
  10342. if (conn == NULL) {
  10343. return;
  10344. }
  10345. if (conn->ctx->context_type == 2) {
  10346. client_ctx = conn->ctx;
  10347. /* client context: loops must end */
  10348. conn->ctx->stop_flag = 1;
  10349. }
  10350. #ifndef NO_SSL
  10351. if (conn->client_ssl_ctx != NULL) {
  10352. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  10353. }
  10354. #endif
  10355. close_connection(conn);
  10356. if (client_ctx != NULL) {
  10357. /* join worker thread and free context */
  10358. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  10359. if (client_ctx->workerthreadids[i] != 0) {
  10360. mg_join_thread(client_ctx->workerthreadids[i]);
  10361. }
  10362. }
  10363. mg_free(client_ctx->workerthreadids);
  10364. mg_free(client_ctx);
  10365. (void)pthread_mutex_destroy(&conn->mutex);
  10366. mg_free(conn);
  10367. }
  10368. }
  10369. static struct mg_connection *
  10370. mg_connect_client_impl(const struct mg_client_options *client_options,
  10371. int use_ssl,
  10372. char *ebuf,
  10373. size_t ebuf_len)
  10374. {
  10375. static struct mg_context fake_ctx;
  10376. struct mg_connection *conn = NULL;
  10377. SOCKET sock;
  10378. union usa sa;
  10379. if (!connect_socket(&fake_ctx,
  10380. client_options->host,
  10381. client_options->port,
  10382. use_ssl,
  10383. ebuf,
  10384. ebuf_len,
  10385. &sock,
  10386. &sa)) {
  10387. ;
  10388. } else if ((conn = (struct mg_connection *)
  10389. mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) {
  10390. mg_snprintf(NULL,
  10391. NULL, /* No truncation check for ebuf */
  10392. ebuf,
  10393. ebuf_len,
  10394. "calloc(): %s",
  10395. strerror(ERRNO));
  10396. closesocket(sock);
  10397. #ifndef NO_SSL
  10398. } else if (use_ssl
  10399. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  10400. == NULL) {
  10401. mg_snprintf(NULL,
  10402. NULL, /* No truncation check for ebuf */
  10403. ebuf,
  10404. ebuf_len,
  10405. "SSL_CTX_new error");
  10406. closesocket(sock);
  10407. mg_free(conn);
  10408. conn = NULL;
  10409. #endif /* NO_SSL */
  10410. } else {
  10411. #ifdef USE_IPV6
  10412. socklen_t len = (sa.sa.sa_family == AF_INET)
  10413. ? sizeof(conn->client.rsa.sin)
  10414. : sizeof(conn->client.rsa.sin6);
  10415. struct sockaddr *psa =
  10416. (sa.sa.sa_family == AF_INET)
  10417. ? (struct sockaddr *)&(conn->client.rsa.sin)
  10418. : (struct sockaddr *)&(conn->client.rsa.sin6);
  10419. #else
  10420. socklen_t len = sizeof(conn->client.rsa.sin);
  10421. struct sockaddr *psa = (struct sockaddr *)&(conn->client.rsa.sin);
  10422. #endif
  10423. conn->buf_size = MAX_REQUEST_SIZE;
  10424. conn->buf = (char *)(conn + 1);
  10425. conn->ctx = &fake_ctx;
  10426. conn->client.sock = sock;
  10427. conn->client.lsa = sa;
  10428. if (getsockname(sock, psa, &len) != 0) {
  10429. mg_cry(conn,
  10430. "%s: getsockname() failed: %s",
  10431. __func__,
  10432. strerror(ERRNO));
  10433. }
  10434. conn->client.is_ssl = use_ssl ? 1 : 0;
  10435. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  10436. #ifndef NO_SSL
  10437. if (use_ssl) {
  10438. fake_ctx.ssl_ctx = conn->client_ssl_ctx;
  10439. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  10440. * SSL_CTX_set_verify call is needed to switch off server
  10441. * certificate checking, which is off by default in OpenSSL and
  10442. * on in yaSSL. */
  10443. /* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  10444. * SSL_VERIFY_PEER, verify_ssl_server); */
  10445. if (client_options->client_cert) {
  10446. if (!ssl_use_pem_file(&fake_ctx, client_options->client_cert)) {
  10447. mg_snprintf(NULL,
  10448. NULL, /* No truncation check for ebuf */
  10449. ebuf,
  10450. ebuf_len,
  10451. "Can not use SSL client certificate");
  10452. SSL_CTX_free(conn->client_ssl_ctx);
  10453. closesocket(sock);
  10454. mg_free(conn);
  10455. conn = NULL;
  10456. }
  10457. }
  10458. if (client_options->server_cert) {
  10459. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  10460. client_options->server_cert,
  10461. NULL);
  10462. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  10463. } else {
  10464. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  10465. }
  10466. if (!sslize(conn, conn->client_ssl_ctx, SSL_connect)) {
  10467. mg_snprintf(NULL,
  10468. NULL, /* No truncation check for ebuf */
  10469. ebuf,
  10470. ebuf_len,
  10471. "SSL connection error");
  10472. SSL_CTX_free(conn->client_ssl_ctx);
  10473. closesocket(sock);
  10474. mg_free(conn);
  10475. conn = NULL;
  10476. }
  10477. }
  10478. #endif
  10479. }
  10480. return conn;
  10481. }
  10482. CIVETWEB_API struct mg_connection *
  10483. mg_connect_client_secure(const struct mg_client_options *client_options,
  10484. char *error_buffer,
  10485. size_t error_buffer_size)
  10486. {
  10487. return mg_connect_client_impl(client_options,
  10488. 1,
  10489. error_buffer,
  10490. error_buffer_size);
  10491. }
  10492. struct mg_connection *
  10493. mg_connect_client(const char *host,
  10494. int port,
  10495. int use_ssl,
  10496. char *error_buffer,
  10497. size_t error_buffer_size)
  10498. {
  10499. struct mg_client_options opts;
  10500. memset(&opts, 0, sizeof(opts));
  10501. opts.host = host;
  10502. opts.port = port;
  10503. return mg_connect_client_impl(&opts,
  10504. use_ssl,
  10505. error_buffer,
  10506. error_buffer_size);
  10507. }
  10508. static const struct {
  10509. const char *proto;
  10510. size_t proto_len;
  10511. unsigned default_port;
  10512. } abs_uri_protocols[] = {{"http://", 7, 80},
  10513. {"https://", 8, 443},
  10514. {"ws://", 5, 80},
  10515. {"wss://", 6, 443},
  10516. {NULL, 0, 0}};
  10517. /* Check if the uri is valid.
  10518. * return 0 for invalid uri,
  10519. * return 1 for *,
  10520. * return 2 for relative uri,
  10521. * return 3 for absolute uri without port,
  10522. * return 4 for absolute uri with port */
  10523. static int
  10524. get_uri_type(const char *uri)
  10525. {
  10526. int i;
  10527. char *hostend, *portbegin, *portend;
  10528. unsigned long port;
  10529. /* According to the HTTP standard
  10530. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  10531. * URI can be an asterisk (*) or should start with slash (relative uri),
  10532. * or it should start with the protocol (absolute uri). */
  10533. if (uri[0] == '*' && uri[1] == '\0') {
  10534. /* asterisk */
  10535. return 1;
  10536. }
  10537. /* Valid URIs according to RFC 3986
  10538. * (https://www.ietf.org/rfc/rfc3986.txt)
  10539. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  10540. * and unreserved characters A-Z a-z 0-9 and -._~
  10541. * and % encoded symbols.
  10542. */
  10543. for (i = 0; uri[i] != 0; i++) {
  10544. if (uri[i] < 33) {
  10545. /* control characters and spaces are invalid */
  10546. return 0;
  10547. }
  10548. if (uri[i] > 126) {
  10549. /* non-ascii characters must be % encoded */
  10550. return 0;
  10551. } else {
  10552. switch (uri[i]) {
  10553. case '"': /* 34 */
  10554. case '<': /* 60 */
  10555. case '>': /* 62 */
  10556. case '\\': /* 92 */
  10557. case '^': /* 94 */
  10558. case '`': /* 96 */
  10559. case '{': /* 123 */
  10560. case '|': /* 124 */
  10561. case '}': /* 125 */
  10562. return 0;
  10563. default:
  10564. /* character is ok */
  10565. break;
  10566. }
  10567. }
  10568. }
  10569. /* A relative uri starts with a / character */
  10570. if (uri[0] == '/') {
  10571. /* relative uri */
  10572. return 2;
  10573. }
  10574. /* It could be an absolute uri: */
  10575. /* This function only checks if the uri is valid, not if it is
  10576. * addressing the current server. So civetweb can also be used
  10577. * as a proxy server. */
  10578. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  10579. if (mg_strncasecmp(uri,
  10580. abs_uri_protocols[i].proto,
  10581. abs_uri_protocols[i].proto_len) == 0) {
  10582. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  10583. if (!hostend) {
  10584. return 0;
  10585. }
  10586. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  10587. if (!portbegin) {
  10588. return 3;
  10589. }
  10590. port = strtoul(portbegin + 1, &portend, 10);
  10591. if ((portend != hostend) || !port || !is_valid_port(port)) {
  10592. return 0;
  10593. }
  10594. return 4;
  10595. }
  10596. }
  10597. return 0;
  10598. }
  10599. /* Return NULL or the relative uri at the current server */
  10600. static const char *
  10601. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  10602. {
  10603. const char *server_domain;
  10604. size_t server_domain_len;
  10605. size_t request_domain_len = 0;
  10606. unsigned long port = 0;
  10607. int i;
  10608. const char *hostbegin = NULL;
  10609. const char *hostend = NULL;
  10610. const char *portbegin;
  10611. char *portend;
  10612. /* DNS is case insensitive, so use case insensitive string compare here
  10613. */
  10614. server_domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  10615. if (!server_domain) {
  10616. return 0;
  10617. }
  10618. server_domain_len = strlen(server_domain);
  10619. if (!server_domain_len) {
  10620. return 0;
  10621. }
  10622. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  10623. if (mg_strncasecmp(uri,
  10624. abs_uri_protocols[i].proto,
  10625. abs_uri_protocols[i].proto_len) == 0) {
  10626. hostbegin = uri + abs_uri_protocols[i].proto_len;
  10627. hostend = strchr(hostbegin, '/');
  10628. if (!hostend) {
  10629. return 0;
  10630. }
  10631. portbegin = strchr(hostbegin, ':');
  10632. if ((!portbegin) || (portbegin > hostend)) {
  10633. port = abs_uri_protocols[i].default_port;
  10634. request_domain_len = (size_t)(hostend - hostbegin);
  10635. } else {
  10636. port = strtoul(portbegin + 1, &portend, 10);
  10637. if ((portend != hostend) || !port || !is_valid_port(port)) {
  10638. return 0;
  10639. }
  10640. request_domain_len = (size_t)(portbegin - hostbegin);
  10641. }
  10642. /* protocol found, port set */
  10643. break;
  10644. }
  10645. }
  10646. if (!port) {
  10647. /* port remains 0 if the protocol is not found */
  10648. return 0;
  10649. }
  10650. #if defined(USE_IPV6)
  10651. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  10652. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  10653. /* Request is directed to a different port */
  10654. return 0;
  10655. }
  10656. } else
  10657. #endif
  10658. {
  10659. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  10660. /* Request is directed to a different port */
  10661. return 0;
  10662. }
  10663. }
  10664. if ((request_domain_len != server_domain_len)
  10665. || (0 != memcmp(server_domain, hostbegin, server_domain_len))) {
  10666. /* Request is directed to another server */
  10667. return 0;
  10668. }
  10669. return hostend;
  10670. }
  10671. static int
  10672. getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  10673. {
  10674. const char *cl;
  10675. if (ebuf_len > 0) {
  10676. ebuf[0] = '\0';
  10677. }
  10678. *err = 0;
  10679. reset_per_request_attributes(conn);
  10680. if (!conn) {
  10681. mg_snprintf(conn,
  10682. NULL, /* No truncation check for ebuf */
  10683. ebuf,
  10684. ebuf_len,
  10685. "%s",
  10686. "Internal error");
  10687. *err = 500;
  10688. return 0;
  10689. }
  10690. /* Set the time the request was received. This value should be used for
  10691. * timeouts. */
  10692. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  10693. conn->request_len =
  10694. read_request(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  10695. /* assert(conn->request_len < 0 || conn->data_len >= conn->request_len);
  10696. */
  10697. if (conn->request_len >= 0 && conn->data_len < conn->request_len) {
  10698. mg_snprintf(conn,
  10699. NULL, /* No truncation check for ebuf */
  10700. ebuf,
  10701. ebuf_len,
  10702. "%s",
  10703. "Invalid request size");
  10704. *err = 500;
  10705. return 0;
  10706. }
  10707. if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
  10708. mg_snprintf(conn,
  10709. NULL, /* No truncation check for ebuf */
  10710. ebuf,
  10711. ebuf_len,
  10712. "%s",
  10713. "Request Too Large");
  10714. *err = 413;
  10715. return 0;
  10716. } else if (conn->request_len <= 0) {
  10717. if (conn->data_len > 0) {
  10718. mg_snprintf(conn,
  10719. NULL, /* No truncation check for ebuf */
  10720. ebuf,
  10721. ebuf_len,
  10722. "%s",
  10723. "Client sent malformed request");
  10724. *err = 400;
  10725. } else {
  10726. /* Server did not send anything -> just close the connection */
  10727. conn->must_close = 1;
  10728. mg_snprintf(conn,
  10729. NULL, /* No truncation check for ebuf */
  10730. ebuf,
  10731. ebuf_len,
  10732. "%s",
  10733. "Client did not send a request");
  10734. *err = 0;
  10735. }
  10736. return 0;
  10737. } else if (parse_http_message(conn->buf,
  10738. conn->buf_size,
  10739. &conn->request_info) <= 0) {
  10740. mg_snprintf(conn,
  10741. NULL, /* No truncation check for ebuf */
  10742. ebuf,
  10743. ebuf_len,
  10744. "%s",
  10745. "Bad Request");
  10746. *err = 400;
  10747. return 0;
  10748. } else {
  10749. /* Message is a valid request or response */
  10750. if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) {
  10751. /* Request/response has content length set */
  10752. char *endptr = NULL;
  10753. conn->content_len = strtoll(cl, &endptr, 10);
  10754. if (endptr == cl) {
  10755. mg_snprintf(conn,
  10756. NULL, /* No truncation check for ebuf */
  10757. ebuf,
  10758. ebuf_len,
  10759. "%s",
  10760. "Bad Request");
  10761. *err = 411;
  10762. return 0;
  10763. }
  10764. /* Publish the content length back to the request info. */
  10765. conn->request_info.content_length = conn->content_len;
  10766. } else if ((cl = get_header(&conn->request_info, "Transfer-Encoding"))
  10767. != NULL
  10768. && !mg_strcasecmp(cl, "chunked")) {
  10769. conn->is_chunked = 1;
  10770. } else if (!mg_strcasecmp(conn->request_info.request_method, "POST")
  10771. || !mg_strcasecmp(conn->request_info.request_method,
  10772. "PUT")) {
  10773. /* POST or PUT request without content length set */
  10774. conn->content_len = -1;
  10775. } else if (!mg_strncasecmp(conn->request_info.request_method,
  10776. "HTTP/",
  10777. 5)) {
  10778. /* Response without content length set */
  10779. conn->content_len = -1;
  10780. } else {
  10781. /* Other request */
  10782. conn->content_len = 0;
  10783. }
  10784. }
  10785. return 1;
  10786. }
  10787. int
  10788. mg_get_response(struct mg_connection *conn,
  10789. char *ebuf,
  10790. size_t ebuf_len,
  10791. int timeout)
  10792. {
  10793. if (conn) {
  10794. /* Implementation of API function for HTTP clients */
  10795. int err, ret;
  10796. struct mg_context *octx = conn->ctx;
  10797. struct mg_context rctx = *(conn->ctx);
  10798. char txt[32]; /* will not overflow */
  10799. if (timeout >= 0) {
  10800. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  10801. rctx.config[REQUEST_TIMEOUT] = txt;
  10802. set_sock_timeout(conn->client.sock, timeout);
  10803. } else {
  10804. rctx.config[REQUEST_TIMEOUT] = NULL;
  10805. }
  10806. conn->ctx = &rctx;
  10807. ret = getreq(conn, ebuf, ebuf_len, &err);
  10808. conn->ctx = octx;
  10809. /* TODO: 1) uri is deprecated;
  10810. * 2) here, ri.uri is the http response code */
  10811. conn->request_info.uri = conn->request_info.request_uri;
  10812. /* TODO (mid): Define proper return values - maybe return length?
  10813. * For the first test use <0 for error and >0 for OK */
  10814. return (ret == 0) ? -1 : +1;
  10815. }
  10816. return -1;
  10817. }
  10818. struct mg_connection *
  10819. mg_download(const char *host,
  10820. int port,
  10821. int use_ssl,
  10822. char *ebuf,
  10823. size_t ebuf_len,
  10824. const char *fmt,
  10825. ...)
  10826. {
  10827. struct mg_connection *conn;
  10828. va_list ap;
  10829. int i;
  10830. int reqerr;
  10831. va_start(ap, fmt);
  10832. ebuf[0] = '\0';
  10833. /* open a connection */
  10834. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  10835. if (conn != NULL) {
  10836. i = mg_vprintf(conn, fmt, ap);
  10837. if (i <= 0) {
  10838. mg_snprintf(conn,
  10839. NULL, /* No truncation check for ebuf */
  10840. ebuf,
  10841. ebuf_len,
  10842. "%s",
  10843. "Error sending request");
  10844. } else {
  10845. getreq(conn, ebuf, ebuf_len, &reqerr);
  10846. /* TODO: 1) uri is deprecated;
  10847. * 2) here, ri.uri is the http response code */
  10848. conn->request_info.uri = conn->request_info.request_uri;
  10849. }
  10850. }
  10851. /* if an error occured, close the connection */
  10852. if (ebuf[0] != '\0' && conn != NULL) {
  10853. mg_close_connection(conn);
  10854. conn = NULL;
  10855. }
  10856. va_end(ap);
  10857. return conn;
  10858. }
  10859. struct websocket_client_thread_data {
  10860. struct mg_connection *conn;
  10861. mg_websocket_data_handler data_handler;
  10862. mg_websocket_close_handler close_handler;
  10863. void *callback_data;
  10864. };
  10865. #if defined(USE_WEBSOCKET)
  10866. #ifdef _WIN32
  10867. static unsigned __stdcall websocket_client_thread(void *data)
  10868. #else
  10869. static void *
  10870. websocket_client_thread(void *data)
  10871. #endif
  10872. {
  10873. struct websocket_client_thread_data *cdata =
  10874. (struct websocket_client_thread_data *)data;
  10875. mg_set_thread_name("ws-client");
  10876. if (cdata->conn->ctx) {
  10877. if (cdata->conn->ctx->callbacks.init_thread) {
  10878. /* 3 indicates a websocket client thread */
  10879. /* TODO: check if conn->ctx can be set */
  10880. cdata->conn->ctx->callbacks.init_thread(cdata->conn->ctx, 3);
  10881. }
  10882. }
  10883. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  10884. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  10885. if (cdata->close_handler != NULL) {
  10886. cdata->close_handler(cdata->conn, cdata->callback_data);
  10887. }
  10888. mg_free((void *)cdata);
  10889. #ifdef _WIN32
  10890. return 0;
  10891. #else
  10892. return NULL;
  10893. #endif
  10894. }
  10895. #endif
  10896. struct mg_connection *
  10897. mg_connect_websocket_client(const char *host,
  10898. int port,
  10899. int use_ssl,
  10900. char *error_buffer,
  10901. size_t error_buffer_size,
  10902. const char *path,
  10903. const char *origin,
  10904. mg_websocket_data_handler data_func,
  10905. mg_websocket_close_handler close_func,
  10906. void *user_data)
  10907. {
  10908. struct mg_connection *conn = NULL;
  10909. #if defined(USE_WEBSOCKET)
  10910. struct mg_context *newctx = NULL;
  10911. struct websocket_client_thread_data *thread_data;
  10912. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  10913. static const char *handshake_req;
  10914. if (origin != NULL) {
  10915. handshake_req = "GET %s HTTP/1.1\r\n"
  10916. "Host: %s\r\n"
  10917. "Upgrade: websocket\r\n"
  10918. "Connection: Upgrade\r\n"
  10919. "Sec-WebSocket-Key: %s\r\n"
  10920. "Sec-WebSocket-Version: 13\r\n"
  10921. "Origin: %s\r\n"
  10922. "\r\n";
  10923. } else {
  10924. handshake_req = "GET %s HTTP/1.1\r\n"
  10925. "Host: %s\r\n"
  10926. "Upgrade: websocket\r\n"
  10927. "Connection: Upgrade\r\n"
  10928. "Sec-WebSocket-Key: %s\r\n"
  10929. "Sec-WebSocket-Version: 13\r\n"
  10930. "\r\n";
  10931. }
  10932. /* Establish the client connection and request upgrade */
  10933. conn = mg_download(host,
  10934. port,
  10935. use_ssl,
  10936. error_buffer,
  10937. error_buffer_size,
  10938. handshake_req,
  10939. path,
  10940. host,
  10941. magic,
  10942. origin);
  10943. /* Connection object will be null if something goes wrong */
  10944. if (conn == NULL || (strcmp(conn->request_info.request_uri, "101") != 0)) {
  10945. if (!*error_buffer) {
  10946. /* if there is a connection, but it did not return 101,
  10947. * error_buffer is not yet set */
  10948. mg_snprintf(conn,
  10949. NULL, /* No truncation check for ebuf */
  10950. error_buffer,
  10951. error_buffer_size,
  10952. "Unexpected server reply");
  10953. }
  10954. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  10955. if (conn != NULL) {
  10956. mg_free(conn);
  10957. conn = NULL;
  10958. }
  10959. return conn;
  10960. }
  10961. /* For client connections, mg_context is fake. Since we need to set a
  10962. * callback function, we need to create a copy and modify it. */
  10963. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  10964. memcpy(newctx, conn->ctx, sizeof(struct mg_context));
  10965. newctx->user_data = user_data;
  10966. newctx->context_type = 2; /* client context type */
  10967. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  10968. newctx->workerthreadids =
  10969. (pthread_t *)mg_calloc(newctx->cfg_worker_threads, sizeof(pthread_t));
  10970. conn->ctx = newctx;
  10971. thread_data = (struct websocket_client_thread_data *)
  10972. mg_calloc(sizeof(struct websocket_client_thread_data), 1);
  10973. thread_data->conn = conn;
  10974. thread_data->data_handler = data_func;
  10975. thread_data->close_handler = close_func;
  10976. thread_data->callback_data = NULL;
  10977. /* Start a thread to read the websocket client connection
  10978. * This thread will automatically stop when mg_disconnect is
  10979. * called on the client connection */
  10980. if (mg_start_thread_with_id(websocket_client_thread,
  10981. (void *)thread_data,
  10982. newctx->workerthreadids) != 0) {
  10983. mg_free((void *)thread_data);
  10984. mg_free((void *)newctx->workerthreadids);
  10985. mg_free((void *)newctx);
  10986. mg_free((void *)conn);
  10987. conn = NULL;
  10988. DEBUG_TRACE("%s",
  10989. "Websocket client connect thread could not be started\r\n");
  10990. }
  10991. #else
  10992. /* Appease "unused parameter" warnings */
  10993. (void)host;
  10994. (void)port;
  10995. (void)use_ssl;
  10996. (void)error_buffer;
  10997. (void)error_buffer_size;
  10998. (void)path;
  10999. (void)origin;
  11000. (void)user_data;
  11001. (void)data_func;
  11002. (void)close_func;
  11003. #endif
  11004. return conn;
  11005. }
  11006. static void
  11007. process_new_connection(struct mg_connection *conn)
  11008. {
  11009. if (conn && conn->ctx) {
  11010. struct mg_request_info *ri = &conn->request_info;
  11011. int keep_alive_enabled, keep_alive, discard_len;
  11012. char ebuf[100];
  11013. const char *hostend;
  11014. int reqerr, uri_type;
  11015. keep_alive_enabled =
  11016. !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  11017. /* Important: on new connection, reset the receiving buffer. Credit
  11018. * goes to crule42. */
  11019. conn->data_len = 0;
  11020. do {
  11021. if (!getreq(conn, ebuf, sizeof(ebuf), &reqerr)) {
  11022. /* The request sent by the client could not be understood by
  11023. * the server, or it was incomplete or a timeout. Send an
  11024. * error message and close the connection. */
  11025. if (reqerr > 0) {
  11026. /*assert(ebuf[0] != '\0');*/
  11027. send_http_error(conn, reqerr, "%s", ebuf);
  11028. }
  11029. } else if (strcmp(ri->http_version, "1.0")
  11030. && strcmp(ri->http_version, "1.1")) {
  11031. mg_snprintf(conn,
  11032. NULL, /* No truncation check for ebuf */
  11033. ebuf,
  11034. sizeof(ebuf),
  11035. "Bad HTTP version: [%s]",
  11036. ri->http_version);
  11037. send_http_error(conn, 505, "%s", ebuf);
  11038. }
  11039. if (ebuf[0] == '\0') {
  11040. uri_type = get_uri_type(conn->request_info.request_uri);
  11041. switch (uri_type) {
  11042. case 1:
  11043. /* Asterisk */
  11044. conn->request_info.local_uri = NULL;
  11045. break;
  11046. case 2:
  11047. /* relative uri */
  11048. conn->request_info.local_uri =
  11049. conn->request_info.request_uri;
  11050. break;
  11051. case 3:
  11052. case 4:
  11053. /* absolute uri (with/without port) */
  11054. hostend = get_rel_url_at_current_server(
  11055. conn->request_info.request_uri, conn);
  11056. if (hostend) {
  11057. conn->request_info.local_uri = hostend;
  11058. } else {
  11059. conn->request_info.local_uri = NULL;
  11060. }
  11061. break;
  11062. default:
  11063. mg_snprintf(conn,
  11064. NULL, /* No truncation check for ebuf */
  11065. ebuf,
  11066. sizeof(ebuf),
  11067. "Invalid URI");
  11068. send_http_error(conn, 400, "%s", ebuf);
  11069. conn->request_info.local_uri = NULL;
  11070. break;
  11071. }
  11072. /* TODO: cleanup uri, local_uri and request_uri */
  11073. conn->request_info.uri = conn->request_info.local_uri;
  11074. }
  11075. if (ebuf[0] == '\0') {
  11076. if (conn->request_info.local_uri) {
  11077. /* handle request to local server */
  11078. handle_request(conn);
  11079. if (conn->ctx->callbacks.end_request != NULL) {
  11080. conn->ctx->callbacks.end_request(conn,
  11081. conn->status_code);
  11082. }
  11083. log_access(conn);
  11084. } else {
  11085. /* TODO: handle non-local request (PROXY) */
  11086. conn->must_close = 1;
  11087. }
  11088. } else {
  11089. conn->must_close = 1;
  11090. }
  11091. if (ri->remote_user != NULL) {
  11092. mg_free((void *)ri->remote_user);
  11093. /* Important! When having connections with and without auth
  11094. * would cause double free and then crash */
  11095. ri->remote_user = NULL;
  11096. }
  11097. /* NOTE(lsm): order is important here. should_keep_alive() call
  11098. * is
  11099. * using parsed request, which will be invalid after memmove's
  11100. * below.
  11101. * Therefore, memorize should_keep_alive() result now for later
  11102. * use
  11103. * in loop exit condition. */
  11104. keep_alive = conn->ctx->stop_flag == 0 && keep_alive_enabled
  11105. && conn->content_len >= 0 && should_keep_alive(conn);
  11106. /* Discard all buffered data for this request */
  11107. discard_len = ((conn->content_len >= 0) && (conn->request_len > 0)
  11108. && ((conn->request_len + conn->content_len)
  11109. < (int64_t)conn->data_len))
  11110. ? (int)(conn->request_len + conn->content_len)
  11111. : conn->data_len;
  11112. /*assert(discard_len >= 0);*/
  11113. if (discard_len < 0)
  11114. break;
  11115. conn->data_len -= discard_len;
  11116. if (conn->data_len > 0) {
  11117. memmove(conn->buf,
  11118. conn->buf + discard_len,
  11119. (size_t)conn->data_len);
  11120. }
  11121. /* assert(conn->data_len >= 0); */
  11122. /* assert(conn->data_len <= conn->buf_size); */
  11123. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  11124. break;
  11125. }
  11126. } while (keep_alive);
  11127. }
  11128. }
  11129. #if defined(ALTERNATIVE_QUEUE)
  11130. static void
  11131. produce_socket(struct mg_context *ctx, const struct socket *sp)
  11132. {
  11133. unsigned int i;
  11134. for (;;) {
  11135. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  11136. /* find a free worker slot and signal it */
  11137. if (ctx->client_socks[i].in_use == 0) {
  11138. ctx->client_socks[i] = *sp;
  11139. ctx->client_socks[i].in_use = 1;
  11140. event_signal(ctx->client_wait_events[i]);
  11141. return;
  11142. }
  11143. }
  11144. /* queue is full */
  11145. mg_sleep(1);
  11146. }
  11147. }
  11148. static int
  11149. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  11150. {
  11151. ctx->client_socks[thread_index].in_use = 0;
  11152. event_wait(ctx->client_wait_events[thread_index]);
  11153. *sp = ctx->client_socks[thread_index];
  11154. return !ctx->stop_flag;
  11155. }
  11156. #else /* ALTERNATIVE_QUEUE */
  11157. /* Worker threads take accepted socket from the queue */
  11158. static int
  11159. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  11160. {
  11161. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  11162. (void)thread_index;
  11163. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11164. DEBUG_TRACE("%s", "going idle");
  11165. /* If the queue is empty, wait. We're idle at this point. */
  11166. while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
  11167. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  11168. }
  11169. /* If we're stopping, sq_head may be equal to sq_tail. */
  11170. if (ctx->sq_head > ctx->sq_tail) {
  11171. /* Copy socket from the queue and increment tail */
  11172. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  11173. ctx->sq_tail++;
  11174. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  11175. /* Wrap pointers if needed */
  11176. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  11177. ctx->sq_tail -= QUEUE_SIZE(ctx);
  11178. ctx->sq_head -= QUEUE_SIZE(ctx);
  11179. }
  11180. }
  11181. (void)pthread_cond_signal(&ctx->sq_empty);
  11182. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11183. return !ctx->stop_flag;
  11184. #undef QUEUE_SIZE
  11185. }
  11186. /* Master thread adds accepted socket to a queue */
  11187. static void
  11188. produce_socket(struct mg_context *ctx, const struct socket *sp)
  11189. {
  11190. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  11191. if (!ctx) {
  11192. return;
  11193. }
  11194. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11195. /* If the queue is full, wait */
  11196. while (ctx->stop_flag == 0
  11197. && ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx)) {
  11198. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  11199. }
  11200. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  11201. /* Copy socket to the queue and increment head */
  11202. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  11203. ctx->sq_head++;
  11204. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  11205. }
  11206. (void)pthread_cond_signal(&ctx->sq_full);
  11207. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11208. #undef QUEUE_SIZE
  11209. }
  11210. #endif /* ALTERNATIVE_QUEUE */
  11211. struct worker_thread_args {
  11212. struct mg_context *ctx;
  11213. int index;
  11214. };
  11215. static void *
  11216. worker_thread_run(struct worker_thread_args *thread_args)
  11217. {
  11218. struct mg_context *ctx = thread_args->ctx;
  11219. struct mg_connection *conn;
  11220. struct mg_workerTLS tls;
  11221. #if defined(MG_LEGACY_INTERFACE)
  11222. uint32_t addr;
  11223. #endif
  11224. mg_set_thread_name("worker");
  11225. tls.is_master = 0;
  11226. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  11227. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11228. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  11229. #endif
  11230. if (ctx->callbacks.init_thread) {
  11231. /* call init_thread for a worker thread (type 1) */
  11232. ctx->callbacks.init_thread(ctx, 1);
  11233. }
  11234. conn =
  11235. (struct mg_connection *)mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE);
  11236. if (conn == NULL) {
  11237. mg_cry(fc(ctx), "%s", "Cannot create new connection struct, OOM");
  11238. } else {
  11239. pthread_setspecific(sTlsKey, &tls);
  11240. conn->buf_size = MAX_REQUEST_SIZE;
  11241. conn->buf = (char *)(conn + 1);
  11242. conn->ctx = ctx;
  11243. conn->thread_index = thread_args->index;
  11244. conn->request_info.user_data = ctx->user_data;
  11245. /* Allocate a mutex for this connection to allow communication both
  11246. * within the request handler and from elsewhere in the application
  11247. */
  11248. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  11249. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  11250. * signal sq_empty condvar to wake up the master waiting in
  11251. * produce_socket() */
  11252. while (consume_socket(ctx, &conn->client, conn->thread_index)) {
  11253. conn->conn_birth_time = time(NULL);
  11254. /* Fill in IP, port info early so even if SSL setup below fails,
  11255. * error handler would have the corresponding info.
  11256. * Thanks to Johannes Winkelmann for the patch.
  11257. */
  11258. #if defined(USE_IPV6)
  11259. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  11260. conn->request_info.remote_port =
  11261. ntohs(conn->client.rsa.sin6.sin6_port);
  11262. } else
  11263. #endif
  11264. {
  11265. conn->request_info.remote_port =
  11266. ntohs(conn->client.rsa.sin.sin_port);
  11267. }
  11268. sockaddr_to_string(conn->request_info.remote_addr,
  11269. sizeof(conn->request_info.remote_addr),
  11270. &conn->client.rsa);
  11271. #if defined(MG_LEGACY_INTERFACE)
  11272. /* This legacy interface only works for the IPv4 case */
  11273. addr = ntohl(conn->client.rsa.sin.sin_addr.s_addr);
  11274. memcpy(&conn->request_info.remote_ip, &addr, 4);
  11275. #endif
  11276. conn->request_info.is_ssl = conn->client.is_ssl;
  11277. if (conn->client.is_ssl) {
  11278. #ifndef NO_SSL
  11279. /* HTTPS connection */
  11280. if (sslize(conn, conn->ctx->ssl_ctx, SSL_accept)) {
  11281. /* Get SSL client certificate information (if set) */
  11282. ssl_get_client_cert_info(conn);
  11283. /* process HTTPS connection */
  11284. process_new_connection(conn);
  11285. /* Free client certificate info */
  11286. if (conn->request_info.client_cert) {
  11287. mg_free(
  11288. (void *)(conn->request_info.client_cert->subject));
  11289. mg_free(
  11290. (void *)(conn->request_info.client_cert->issuer));
  11291. mg_free(
  11292. (void *)(conn->request_info.client_cert->serial));
  11293. mg_free(
  11294. (void *)(conn->request_info.client_cert->finger));
  11295. conn->request_info.client_cert->subject = 0;
  11296. conn->request_info.client_cert->issuer = 0;
  11297. conn->request_info.client_cert->serial = 0;
  11298. conn->request_info.client_cert->finger = 0;
  11299. mg_free(conn->request_info.client_cert);
  11300. conn->request_info.client_cert = 0;
  11301. }
  11302. }
  11303. #endif
  11304. } else {
  11305. /* process HTTP connection */
  11306. process_new_connection(conn);
  11307. }
  11308. close_connection(conn);
  11309. }
  11310. }
  11311. pthread_setspecific(sTlsKey, NULL);
  11312. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11313. CloseHandle(tls.pthread_cond_helper_mutex);
  11314. #endif
  11315. pthread_mutex_destroy(&conn->mutex);
  11316. mg_free(conn);
  11317. DEBUG_TRACE("%s", "exiting");
  11318. return NULL;
  11319. }
  11320. /* Threads have different return types on Windows and Unix. */
  11321. #ifdef _WIN32
  11322. static unsigned __stdcall worker_thread(void *thread_func_param)
  11323. {
  11324. struct worker_thread_args *pwta =
  11325. (struct worker_thread_args *)thread_func_param;
  11326. worker_thread_run(pwta);
  11327. mg_free(thread_func_param);
  11328. return 0;
  11329. }
  11330. #else
  11331. static void *
  11332. worker_thread(void *thread_func_param)
  11333. {
  11334. struct worker_thread_args *pwta =
  11335. (struct worker_thread_args *)thread_func_param;
  11336. worker_thread_run(pwta);
  11337. mg_free(thread_func_param);
  11338. return NULL;
  11339. }
  11340. #endif /* _WIN32 */
  11341. static void
  11342. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  11343. {
  11344. struct socket so;
  11345. char src_addr[IP_ADDR_STR_LEN];
  11346. socklen_t len = sizeof(so.rsa);
  11347. int on = 1;
  11348. int timeout;
  11349. if (!listener) {
  11350. return;
  11351. }
  11352. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  11353. == INVALID_SOCKET) {
  11354. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  11355. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  11356. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  11357. closesocket(so.sock);
  11358. so.sock = INVALID_SOCKET;
  11359. } else {
  11360. /* Put so socket structure into the queue */
  11361. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  11362. set_close_on_exec(so.sock, fc(ctx));
  11363. so.is_ssl = listener->is_ssl;
  11364. so.ssl_redir = listener->ssl_redir;
  11365. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  11366. mg_cry(fc(ctx),
  11367. "%s: getsockname() failed: %s",
  11368. __func__,
  11369. strerror(ERRNO));
  11370. }
  11371. /* Set TCP keep-alive. This is needed because if HTTP-level
  11372. * keep-alive
  11373. * is enabled, and client resets the connection, server won't get
  11374. * TCP FIN or RST and will keep the connection open forever. With
  11375. * TCP keep-alive, next keep-alive handshake will figure out that
  11376. * the client is down and will close the server end.
  11377. * Thanks to Igor Klopov who suggested the patch. */
  11378. if (setsockopt(so.sock,
  11379. SOL_SOCKET,
  11380. SO_KEEPALIVE,
  11381. (SOCK_OPT_TYPE)&on,
  11382. sizeof(on)) != 0) {
  11383. mg_cry(fc(ctx),
  11384. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  11385. __func__,
  11386. strerror(ERRNO));
  11387. }
  11388. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  11389. * to effectively fill up the underlying IP packet payload and
  11390. * reduce the overhead of sending lots of small buffers. However
  11391. * this hurts the server's throughput (ie. operations per second)
  11392. * when HTTP 1.1 persistent connections are used and the responses
  11393. * are relatively small (eg. less than 1400 bytes).
  11394. */
  11395. if ((ctx != NULL) && (ctx->config[CONFIG_TCP_NODELAY] != NULL)
  11396. && (!strcmp(ctx->config[CONFIG_TCP_NODELAY], "1"))) {
  11397. if (set_tcp_nodelay(so.sock, 1) != 0) {
  11398. mg_cry(fc(ctx),
  11399. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  11400. __func__,
  11401. strerror(ERRNO));
  11402. }
  11403. }
  11404. if (ctx && ctx->config[REQUEST_TIMEOUT]) {
  11405. timeout = atoi(ctx->config[REQUEST_TIMEOUT]);
  11406. } else {
  11407. timeout = -1;
  11408. }
  11409. if (timeout > 0) {
  11410. set_sock_timeout(so.sock, timeout);
  11411. }
  11412. produce_socket(ctx, &so);
  11413. }
  11414. }
  11415. static void
  11416. master_thread_run(void *thread_func_param)
  11417. {
  11418. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  11419. struct mg_workerTLS tls;
  11420. struct pollfd *pfd;
  11421. unsigned int i;
  11422. unsigned int workerthreadcount;
  11423. if (!ctx) {
  11424. return;
  11425. }
  11426. mg_set_thread_name("master");
  11427. /* Increase priority of the master thread */
  11428. #if defined(_WIN32)
  11429. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  11430. #elif defined(USE_MASTER_THREAD_PRIORITY)
  11431. int min_prio = sched_get_priority_min(SCHED_RR);
  11432. int max_prio = sched_get_priority_max(SCHED_RR);
  11433. if ((min_prio >= 0) && (max_prio >= 0)
  11434. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  11435. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  11436. struct sched_param sched_param = {0};
  11437. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  11438. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  11439. }
  11440. #endif
  11441. /* Initialize thread local storage */
  11442. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11443. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  11444. #endif
  11445. tls.is_master = 1;
  11446. pthread_setspecific(sTlsKey, &tls);
  11447. if (ctx->callbacks.init_thread) {
  11448. /* Callback for the master thread (type 0) */
  11449. ctx->callbacks.init_thread(ctx, 0);
  11450. }
  11451. /* Server starts *now* */
  11452. ctx->start_time = time(NULL);
  11453. /* Start the server */
  11454. pfd = ctx->listening_socket_fds;
  11455. while (ctx->stop_flag == 0) {
  11456. for (i = 0; i < ctx->num_listening_sockets; i++) {
  11457. pfd[i].fd = ctx->listening_sockets[i].sock;
  11458. pfd[i].events = POLLIN;
  11459. }
  11460. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  11461. for (i = 0; i < ctx->num_listening_sockets; i++) {
  11462. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  11463. * successful poll, and POLLIN is defined as
  11464. * (POLLRDNORM | POLLRDBAND)
  11465. * Therefore, we're checking pfd[i].revents & POLLIN, not
  11466. * pfd[i].revents == POLLIN. */
  11467. if (ctx->stop_flag == 0 && (pfd[i].revents & POLLIN)) {
  11468. accept_new_connection(&ctx->listening_sockets[i], ctx);
  11469. }
  11470. }
  11471. }
  11472. }
  11473. /* Here stop_flag is 1 - Initiate shutdown. */
  11474. DEBUG_TRACE("%s", "stopping workers");
  11475. /* Stop signal received: somebody called mg_stop. Quit. */
  11476. close_all_listening_sockets(ctx);
  11477. /* Wakeup workers that are waiting for connections to handle. */
  11478. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11479. #if defined(ALTERNATIVE_QUEUE)
  11480. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  11481. event_signal(ctx->client_wait_events[i]);
  11482. /* Since we know all sockets, we can shutdown the connections. */
  11483. if (ctx->client_socks[i].in_use) {
  11484. shutdown(ctx->client_socks[i].sock, SHUTDOWN_BOTH);
  11485. }
  11486. }
  11487. #else
  11488. pthread_cond_broadcast(&ctx->sq_full);
  11489. #endif
  11490. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11491. /* Join all worker threads to avoid leaking threads. */
  11492. workerthreadcount = ctx->cfg_worker_threads;
  11493. for (i = 0; i < workerthreadcount; i++) {
  11494. if (ctx->workerthreadids[i] != 0) {
  11495. mg_join_thread(ctx->workerthreadids[i]);
  11496. }
  11497. }
  11498. #if !defined(NO_SSL)
  11499. if (ctx->ssl_ctx != NULL) {
  11500. uninitialize_ssl(ctx);
  11501. }
  11502. #endif
  11503. DEBUG_TRACE("%s", "exiting");
  11504. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11505. CloseHandle(tls.pthread_cond_helper_mutex);
  11506. #endif
  11507. pthread_setspecific(sTlsKey, NULL);
  11508. /* Signal mg_stop() that we're done.
  11509. * WARNING: This must be the very last thing this
  11510. * thread does, as ctx becomes invalid after this line. */
  11511. ctx->stop_flag = 2;
  11512. }
  11513. /* Threads have different return types on Windows and Unix. */
  11514. #ifdef _WIN32
  11515. static unsigned __stdcall master_thread(void *thread_func_param)
  11516. {
  11517. master_thread_run(thread_func_param);
  11518. return 0;
  11519. }
  11520. #else
  11521. static void *
  11522. master_thread(void *thread_func_param)
  11523. {
  11524. master_thread_run(thread_func_param);
  11525. return NULL;
  11526. }
  11527. #endif /* _WIN32 */
  11528. static void
  11529. free_context(struct mg_context *ctx)
  11530. {
  11531. int i;
  11532. struct mg_handler_info *tmp_rh;
  11533. if (ctx == NULL) {
  11534. return;
  11535. }
  11536. if (ctx->callbacks.exit_context) {
  11537. ctx->callbacks.exit_context(ctx);
  11538. }
  11539. /* All threads exited, no sync is needed. Destroy thread mutex and
  11540. * condvars
  11541. */
  11542. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  11543. #if defined(ALTERNATIVE_QUEUE)
  11544. mg_free(ctx->client_socks);
  11545. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  11546. event_destroy(ctx->client_wait_events[i]);
  11547. }
  11548. mg_free(ctx->client_wait_events);
  11549. #else
  11550. (void)pthread_cond_destroy(&ctx->sq_empty);
  11551. (void)pthread_cond_destroy(&ctx->sq_full);
  11552. #endif
  11553. /* Destroy other context global data structures mutex */
  11554. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  11555. #if defined(USE_TIMERS)
  11556. timers_exit(ctx);
  11557. #endif
  11558. /* Deallocate config parameters */
  11559. for (i = 0; i < NUM_OPTIONS; i++) {
  11560. if (ctx->config[i] != NULL) {
  11561. #if defined(_MSC_VER)
  11562. #pragma warning(suppress : 6001)
  11563. #endif
  11564. mg_free(ctx->config[i]);
  11565. }
  11566. }
  11567. /* Deallocate request handlers */
  11568. while (ctx->handlers) {
  11569. tmp_rh = ctx->handlers;
  11570. ctx->handlers = tmp_rh->next;
  11571. mg_free(tmp_rh->uri);
  11572. mg_free(tmp_rh);
  11573. }
  11574. #ifndef NO_SSL
  11575. /* Deallocate SSL context */
  11576. if (ctx->ssl_ctx != NULL) {
  11577. SSL_CTX_free(ctx->ssl_ctx);
  11578. }
  11579. #endif /* !NO_SSL */
  11580. /* Deallocate worker thread ID array */
  11581. if (ctx->workerthreadids != NULL) {
  11582. mg_free(ctx->workerthreadids);
  11583. }
  11584. /* Deallocate the tls variable */
  11585. if (mg_atomic_dec(&sTlsInit) == 0) {
  11586. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11587. DeleteCriticalSection(&global_log_file_lock);
  11588. #endif /* _WIN32 && !__SYMBIAN32__ */
  11589. #if !defined(_WIN32)
  11590. pthread_mutexattr_destroy(&pthread_mutex_attr);
  11591. #endif
  11592. pthread_key_delete(sTlsKey);
  11593. }
  11594. /* deallocate system name string */
  11595. mg_free(ctx->systemName);
  11596. /* Deallocate context itself */
  11597. mg_free(ctx);
  11598. }
  11599. void
  11600. mg_stop(struct mg_context *ctx)
  11601. {
  11602. pthread_t mt;
  11603. if (!ctx) {
  11604. return;
  11605. }
  11606. /* We don't use a lock here. Calling mg_stop with the same ctx from
  11607. * two threads is not allowed. */
  11608. mt = ctx->masterthreadid;
  11609. if (mt == 0) {
  11610. return;
  11611. }
  11612. ctx->masterthreadid = 0;
  11613. /* Set stop flag, so all threads know they have to exit. */
  11614. ctx->stop_flag = 1;
  11615. /* Wait until everything has stopped. */
  11616. while (ctx->stop_flag != 2) {
  11617. (void)mg_sleep(10);
  11618. }
  11619. mg_join_thread(mt);
  11620. free_context(ctx);
  11621. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11622. (void)WSACleanup();
  11623. #endif /* _WIN32 && !__SYMBIAN32__ */
  11624. }
  11625. static void
  11626. get_system_name(char **sysName)
  11627. {
  11628. #if defined(_WIN32)
  11629. #if !defined(__SYMBIAN32__)
  11630. #if defined(_WIN32_WCE)
  11631. *sysName = mg_strdup("WinCE");
  11632. #else
  11633. char name[128];
  11634. DWORD dwVersion = 0;
  11635. DWORD dwMajorVersion = 0;
  11636. DWORD dwMinorVersion = 0;
  11637. DWORD dwBuild = 0;
  11638. #ifdef _MSC_VER
  11639. #pragma warning(push)
  11640. // GetVersion was declared deprecated
  11641. #pragma warning(disable : 4996)
  11642. #endif
  11643. dwVersion = GetVersion();
  11644. #ifdef _MSC_VER
  11645. #pragma warning(pop)
  11646. #endif
  11647. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  11648. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  11649. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  11650. (void)dwBuild;
  11651. sprintf(name,
  11652. "Windows %u.%u",
  11653. (unsigned)dwMajorVersion,
  11654. (unsigned)dwMinorVersion);
  11655. *sysName = mg_strdup(name);
  11656. #endif
  11657. #else
  11658. *sysName = mg_strdup("Symbian");
  11659. #endif
  11660. #else
  11661. struct utsname name;
  11662. memset(&name, 0, sizeof(name));
  11663. uname(&name);
  11664. *sysName = mg_strdup(name.sysname);
  11665. #endif
  11666. }
  11667. struct mg_context *
  11668. mg_start(const struct mg_callbacks *callbacks,
  11669. void *user_data,
  11670. const char **options)
  11671. {
  11672. struct mg_context *ctx;
  11673. const char *name, *value, *default_value;
  11674. int idx, ok, workerthreadcount;
  11675. unsigned int i;
  11676. void (*exit_callback)(const struct mg_context *ctx) = 0;
  11677. struct mg_workerTLS tls;
  11678. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11679. WSADATA data;
  11680. WSAStartup(MAKEWORD(2, 2), &data);
  11681. #endif /* _WIN32 && !__SYMBIAN32__ */
  11682. /* Allocate context and initialize reasonable general case defaults. */
  11683. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  11684. return NULL;
  11685. }
  11686. /* Random number generator will initialize at the first call */
  11687. ctx->auth_nonce_mask =
  11688. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  11689. if (mg_atomic_inc(&sTlsInit) == 1) {
  11690. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11691. InitializeCriticalSection(&global_log_file_lock);
  11692. #endif /* _WIN32 && !__SYMBIAN32__ */
  11693. #if !defined(_WIN32)
  11694. pthread_mutexattr_init(&pthread_mutex_attr);
  11695. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  11696. #endif
  11697. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  11698. /* Fatal error - abort start. However, this situation should
  11699. * never
  11700. * occur in practice. */
  11701. mg_atomic_dec(&sTlsInit);
  11702. mg_cry(fc(ctx), "Cannot initialize thread local storage");
  11703. mg_free(ctx);
  11704. return NULL;
  11705. }
  11706. } else {
  11707. /* TODO (low): istead of sleeping, check if sTlsKey is already
  11708. * initialized. */
  11709. mg_sleep(1);
  11710. }
  11711. tls.is_master = -1;
  11712. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  11713. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11714. tls.pthread_cond_helper_mutex = NULL;
  11715. #endif
  11716. pthread_setspecific(sTlsKey, &tls);
  11717. #if defined(USE_LUA)
  11718. lua_init_optional_libraries();
  11719. #endif
  11720. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr);
  11721. #if !defined(ALTERNATIVE_QUEUE)
  11722. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  11723. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  11724. #endif
  11725. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr);
  11726. if (!ok) {
  11727. /* Fatal error - abort start. However, this situation should never
  11728. * occur in practice. */
  11729. mg_cry(fc(ctx), "Cannot initialize thread synchronization objects");
  11730. mg_free(ctx);
  11731. pthread_setspecific(sTlsKey, NULL);
  11732. return NULL;
  11733. }
  11734. if (callbacks) {
  11735. ctx->callbacks = *callbacks;
  11736. exit_callback = callbacks->exit_context;
  11737. ctx->callbacks.exit_context = 0;
  11738. }
  11739. ctx->user_data = user_data;
  11740. ctx->handlers = NULL;
  11741. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  11742. ctx->shared_lua_websockets = 0;
  11743. #endif
  11744. while (options && (name = *options++) != NULL) {
  11745. if ((idx = get_option_index(name)) == -1) {
  11746. mg_cry(fc(ctx), "Invalid option: %s", name);
  11747. free_context(ctx);
  11748. pthread_setspecific(sTlsKey, NULL);
  11749. return NULL;
  11750. } else if ((value = *options++) == NULL) {
  11751. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  11752. free_context(ctx);
  11753. pthread_setspecific(sTlsKey, NULL);
  11754. return NULL;
  11755. }
  11756. if (ctx->config[idx] != NULL) {
  11757. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  11758. mg_free(ctx->config[idx]);
  11759. }
  11760. ctx->config[idx] = mg_strdup(value);
  11761. DEBUG_TRACE("[%s] -> [%s]", name, value);
  11762. }
  11763. /* Set default value if needed */
  11764. for (i = 0; config_options[i].name != NULL; i++) {
  11765. default_value = config_options[i].default_value;
  11766. if (ctx->config[i] == NULL && default_value != NULL) {
  11767. ctx->config[i] = mg_strdup(default_value);
  11768. }
  11769. }
  11770. #if defined(NO_FILES)
  11771. if (ctx->config[DOCUMENT_ROOT] != NULL) {
  11772. mg_cry(fc(ctx), "%s", "Document root must not be set");
  11773. free_context(ctx);
  11774. pthread_setspecific(sTlsKey, NULL);
  11775. return NULL;
  11776. }
  11777. #endif
  11778. get_system_name(&ctx->systemName);
  11779. /* NOTE(lsm): order is important here. SSL certificates must
  11780. * be initialized before listening ports. UID must be set last. */
  11781. if (!set_gpass_option(ctx) ||
  11782. #if !defined(NO_SSL)
  11783. !set_ssl_option(ctx) ||
  11784. #endif
  11785. !set_ports_option(ctx) ||
  11786. #if !defined(_WIN32)
  11787. !set_uid_option(ctx) ||
  11788. #endif
  11789. !set_acl_option(ctx)) {
  11790. free_context(ctx);
  11791. pthread_setspecific(sTlsKey, NULL);
  11792. return NULL;
  11793. }
  11794. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  11795. /* Ignore SIGPIPE signal, so if browser cancels the request, it
  11796. * won't kill the whole process. */
  11797. (void)signal(SIGPIPE, SIG_IGN);
  11798. #endif /* !_WIN32 && !__SYMBIAN32__ */
  11799. workerthreadcount = atoi(ctx->config[NUM_THREADS]);
  11800. if (workerthreadcount > MAX_WORKER_THREADS) {
  11801. mg_cry(fc(ctx), "Too many worker threads");
  11802. free_context(ctx);
  11803. pthread_setspecific(sTlsKey, NULL);
  11804. return NULL;
  11805. }
  11806. if (workerthreadcount > 0) {
  11807. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  11808. ctx->workerthreadids =
  11809. (pthread_t *)mg_calloc(ctx->cfg_worker_threads, sizeof(pthread_t));
  11810. if (ctx->workerthreadids == NULL) {
  11811. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  11812. free_context(ctx);
  11813. pthread_setspecific(sTlsKey, NULL);
  11814. return NULL;
  11815. }
  11816. #if defined(ALTERNATIVE_QUEUE)
  11817. ctx->client_wait_events = mg_calloc(sizeof(ctx->client_wait_events[0]),
  11818. ctx->cfg_worker_threads);
  11819. if (ctx->client_wait_events == NULL) {
  11820. mg_cry(fc(ctx), "Not enough memory for worker event array");
  11821. mg_free(ctx->workerthreadids);
  11822. free_context(ctx);
  11823. pthread_setspecific(sTlsKey, NULL);
  11824. return NULL;
  11825. }
  11826. ctx->client_socks =
  11827. mg_calloc(sizeof(ctx->client_socks[0]), ctx->cfg_worker_threads);
  11828. if (ctx->client_wait_events == NULL) {
  11829. mg_cry(fc(ctx), "Not enough memory for worker socket array");
  11830. mg_free(ctx->client_socks);
  11831. mg_free(ctx->workerthreadids);
  11832. free_context(ctx);
  11833. pthread_setspecific(sTlsKey, NULL);
  11834. return NULL;
  11835. }
  11836. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  11837. ctx->client_wait_events[i] = event_create();
  11838. if (ctx->client_wait_events[i] == 0) {
  11839. mg_cry(fc(ctx), "Error creating worker event %i", i);
  11840. /* TODO: clean all and exit */
  11841. }
  11842. }
  11843. #endif
  11844. }
  11845. #if defined(USE_TIMERS)
  11846. if (timers_init(ctx) != 0) {
  11847. mg_cry(fc(ctx), "Error creating timers");
  11848. free_context(ctx);
  11849. pthread_setspecific(sTlsKey, NULL);
  11850. return NULL;
  11851. }
  11852. #endif
  11853. /* Context has been created - init user libraries */
  11854. if (ctx->callbacks.init_context) {
  11855. ctx->callbacks.init_context(ctx);
  11856. }
  11857. ctx->callbacks.exit_context = exit_callback;
  11858. ctx->context_type = 1; /* server context */
  11859. /* Start master (listening) thread */
  11860. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  11861. /* Start worker threads */
  11862. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  11863. struct worker_thread_args *wta =
  11864. mg_malloc(sizeof(struct worker_thread_args));
  11865. if (wta) {
  11866. wta->ctx = ctx;
  11867. wta->index = (int)i;
  11868. }
  11869. if ((wta == NULL)
  11870. || (mg_start_thread_with_id(worker_thread,
  11871. wta,
  11872. &ctx->workerthreadids[i]) != 0)) {
  11873. /* thread was not created */
  11874. if (wta != NULL) {
  11875. mg_free(wta);
  11876. }
  11877. if (i > 0) {
  11878. mg_cry(fc(ctx),
  11879. "Cannot start worker thread %i: error %ld",
  11880. i + 1,
  11881. (long)ERRNO);
  11882. } else {
  11883. mg_cry(fc(ctx),
  11884. "Cannot create threads: error %ld",
  11885. (long)ERRNO);
  11886. free_context(ctx);
  11887. pthread_setspecific(sTlsKey, NULL);
  11888. return NULL;
  11889. }
  11890. break;
  11891. }
  11892. }
  11893. pthread_setspecific(sTlsKey, NULL);
  11894. return ctx;
  11895. }
  11896. /* Feature check API function */
  11897. unsigned
  11898. mg_check_feature(unsigned feature)
  11899. {
  11900. static const unsigned feature_set = 0
  11901. /* Set bits for available features according to API documentation.
  11902. * This bit mask is created at compile time, according to the active
  11903. * preprocessor defines. It is a single const value at runtime. */
  11904. #if !defined(NO_FILES)
  11905. | 0x0001u
  11906. #endif
  11907. #if !defined(NO_SSL)
  11908. | 0x0002u
  11909. #endif
  11910. #if !defined(NO_CGI)
  11911. | 0x0004u
  11912. #endif
  11913. #if defined(USE_IPV6)
  11914. | 0x0008u
  11915. #endif
  11916. #if defined(USE_WEBSOCKET)
  11917. | 0x0010u
  11918. #endif
  11919. #if defined(USE_LUA)
  11920. | 0x0020u
  11921. #endif
  11922. #if defined(USE_DUKTAPE)
  11923. | 0x0040u
  11924. #endif
  11925. #if !defined(NO_CACHING)
  11926. | 0x0080u
  11927. #endif
  11928. /* Set some extra bits not defined in the API documentation.
  11929. * These bits may change without further notice. */
  11930. #if defined(MG_LEGACY_INTERFACE)
  11931. | 0x8000u
  11932. #endif
  11933. #if defined(MEMORY_DEBUGGING)
  11934. | 0x0100u
  11935. #endif
  11936. #if defined(USE_TIMERS)
  11937. | 0x0200u
  11938. #endif
  11939. #if !defined(NO_NONCE_CHECK)
  11940. | 0x0400u
  11941. #endif
  11942. #if !defined(NO_POPEN)
  11943. | 0x0800u
  11944. #endif
  11945. ;
  11946. return (feature & feature_set);
  11947. }