civetweb.c 363 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983
  1. /* Copyright (c) 2013-2016 the Civetweb developers
  2. * Copyright (c) 2004-2013 Sergey Lyubka
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. * THE SOFTWARE.
  21. */
  22. #if defined(_WIN32)
  23. #if !defined(_CRT_SECURE_NO_WARNINGS)
  24. #define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */
  25. #endif
  26. #ifndef _WIN32_WINNT /* defined for tdm-gcc so we can use getnameinfo */
  27. #define _WIN32_WINNT 0x0501
  28. #endif
  29. #else
  30. #if defined(__GNUC__) && !defined(_GNU_SOURCE)
  31. #define _GNU_SOURCE /* for setgroups() */
  32. #endif
  33. #if defined(__linux__) && !defined(_XOPEN_SOURCE)
  34. #define _XOPEN_SOURCE 600 /* For flockfile() on Linux */
  35. #endif
  36. #ifndef _LARGEFILE_SOURCE
  37. #define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
  38. #endif
  39. #ifndef _FILE_OFFSET_BITS
  40. #define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
  41. #endif
  42. #ifndef __STDC_FORMAT_MACROS
  43. #define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
  44. #endif
  45. #ifndef __STDC_LIMIT_MACROS
  46. #define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
  47. #endif
  48. #ifdef __sun
  49. #define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */
  50. #define __inline inline /* not recognized on older compiler versions */
  51. #endif
  52. #endif
  53. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  54. #define USE_TIMERS
  55. #endif
  56. #if defined(_MSC_VER)
  57. /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
  58. #pragma warning(disable : 4306)
  59. /* conditional expression is constant: introduced by FD_SET(..) */
  60. #pragma warning(disable : 4127)
  61. /* non-constant aggregate initializer: issued due to missing C99 support */
  62. #pragma warning(disable : 4204)
  63. /* padding added after data member */
  64. #pragma warning(disable : 4820)
  65. /* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
  66. #pragma warning(disable : 4668)
  67. /* no function prototype given: converting '()' to '(void)' */
  68. #pragma warning(disable : 4255)
  69. /* function has been selected for automatic inline expansion */
  70. #pragma warning(disable : 4711)
  71. #endif
  72. /* This code uses static_assert to check some conditions.
  73. * Unfortunately some compilers still do not support it, so we have a
  74. * replacement function here. */
  75. #if defined(_MSC_VER) && (_MSC_VER >= 1600)
  76. #define mg_static_assert static_assert
  77. #elif defined(__cplusplus) && (__cplusplus >= 201103L)
  78. #define mg_static_assert static_assert
  79. #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)
  80. #define mg_static_assert _Static_assert
  81. #else
  82. char static_assert_replacement[1];
  83. #define mg_static_assert(cond, txt) \
  84. extern char static_assert_replacement[(cond) ? 1 : -1]
  85. #endif
  86. mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
  87. "int data type size check");
  88. mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
  89. "pointer data type size check");
  90. mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
  91. /* DTL -- including winsock2.h works better if lean and mean */
  92. #ifndef WIN32_LEAN_AND_MEAN
  93. #define WIN32_LEAN_AND_MEAN
  94. #endif
  95. #if defined(__SYMBIAN32__)
  96. #define NO_SSL /* SSL is not supported */
  97. #define NO_CGI /* CGI is not supported */
  98. #define PATH_MAX FILENAME_MAX
  99. #endif /* __SYMBIAN32__ */
  100. /* Include the header file here, so the CivetWeb interface is defined for the
  101. * entire implementation, including the following forward definitions. */
  102. #include "civetweb.h"
  103. #ifndef IGNORE_UNUSED_RESULT
  104. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  105. #endif
  106. #ifndef _WIN32_WCE /* Some ANSI #includes are not available on Windows CE */
  107. #include <sys/types.h>
  108. #include <sys/stat.h>
  109. #include <errno.h>
  110. #include <signal.h>
  111. #include <fcntl.h>
  112. #endif /* !_WIN32_WCE */
  113. #ifdef __clang__
  114. /* When using -Weverything, clang does not accept it's own headers
  115. * in a release build configuration. Disable what is too much in
  116. * -Weverything. */
  117. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  118. #endif
  119. #ifdef __MACH__ /* Apple OSX section */
  120. #ifdef __clang__
  121. /* Avoid warnings for Xopen 7.00 and higher */
  122. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  123. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  124. #endif
  125. #define CLOCK_MONOTONIC (1)
  126. #define CLOCK_REALTIME (2)
  127. #include <sys/errno.h>
  128. #include <sys/time.h>
  129. #include <mach/clock.h>
  130. #include <mach/mach.h>
  131. #include <mach/mach_time.h>
  132. #include <assert.h>
  133. /* clock_gettime is not implemented on OSX prior to 10.12 */
  134. int _civet_clock_gettime(int clk_id, struct timespec *t);
  135. int
  136. _civet_clock_gettime(int clk_id, struct timespec *t)
  137. {
  138. memset(t, 0, sizeof(*t));
  139. if (clk_id == CLOCK_REALTIME) {
  140. struct timeval now;
  141. int rv = gettimeofday(&now, NULL);
  142. if (rv) {
  143. return rv;
  144. }
  145. t->tv_sec = now.tv_sec;
  146. t->tv_nsec = now.tv_usec * 1000;
  147. return 0;
  148. } else if (clk_id == CLOCK_MONOTONIC) {
  149. static uint64_t clock_start_time = 0;
  150. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  151. uint64_t now = mach_absolute_time();
  152. if (clock_start_time == 0) {
  153. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  154. #if defined(DEBUG)
  155. assert(mach_status == KERN_SUCCESS);
  156. #else
  157. /* appease "unused variable" warning for release builds */
  158. (void)mach_status;
  159. #endif
  160. clock_start_time = now;
  161. }
  162. now = (uint64_t)((double)(now - clock_start_time)
  163. * (double)timebase_ifo.numer
  164. / (double)timebase_ifo.denom);
  165. t->tv_sec = now / 1000000000;
  166. t->tv_nsec = now % 1000000000;
  167. return 0;
  168. }
  169. return -1; /* EINVAL - Clock ID is unknown */
  170. }
  171. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  172. #ifdef __CLOCK_AVAILABILITY
  173. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  174. * declared
  175. * but it may be NULL at runtime. So we need to check before using it. */
  176. int _civet_safe_clock_gettime(int clk_id, struct timespec *t);
  177. int
  178. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  179. {
  180. if (clock_gettime) {
  181. return clock_gettime(clk_id, t);
  182. }
  183. return _civet_clock_gettime(clk_id, t);
  184. }
  185. #define clock_gettime _civet_safe_clock_gettime
  186. #else
  187. #define clock_gettime _civet_clock_gettime
  188. #endif
  189. #endif
  190. #include <time.h>
  191. #include <stdlib.h>
  192. #include <stdarg.h>
  193. #include <assert.h>
  194. #include <string.h>
  195. #include <ctype.h>
  196. #include <limits.h>
  197. #include <stddef.h>
  198. #include <stdio.h>
  199. #ifndef MAX_WORKER_THREADS
  200. #define MAX_WORKER_THREADS (1024 * 64)
  201. #endif
  202. #define SHUTDOWN_RD (0)
  203. #define SHUTDOWN_WR (1)
  204. #define SHUTDOWN_BOTH (2)
  205. mg_static_assert(MAX_WORKER_THREADS >= 1,
  206. "worker threads must be a positive number");
  207. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  208. "size_t data type size check");
  209. #if defined(_WIN32) \
  210. && !defined(__SYMBIAN32__) /* WINDOWS / UNIX include block */
  211. #include <windows.h>
  212. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  213. #include <ws2tcpip.h>
  214. typedef const char *SOCK_OPT_TYPE;
  215. #if !defined(PATH_MAX)
  216. #define PATH_MAX (MAX_PATH)
  217. #endif
  218. #if !defined(PATH_MAX)
  219. #define PATH_MAX (4096)
  220. #endif
  221. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  222. #ifndef _IN_PORT_T
  223. #ifndef in_port_t
  224. #define in_port_t u_short
  225. #endif
  226. #endif
  227. #ifndef _WIN32_WCE
  228. #include <process.h>
  229. #include <direct.h>
  230. #include <io.h>
  231. #else /* _WIN32_WCE */
  232. #define NO_CGI /* WinCE has no pipes */
  233. #define NO_POPEN /* WinCE has no popen */
  234. typedef long off_t;
  235. #define errno ((int)(GetLastError()))
  236. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  237. #endif /* _WIN32_WCE */
  238. #define MAKEUQUAD(lo, hi) \
  239. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  240. #define RATE_DIFF (10000000) /* 100 nsecs */
  241. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  242. #define SYS2UNIX_TIME(lo, hi) \
  243. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  244. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  245. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  246. * Also use _strtoui64 on modern M$ compilers */
  247. #if defined(_MSC_VER)
  248. #if (_MSC_VER < 1300)
  249. #define STRX(x) #x
  250. #define STR(x) STRX(x)
  251. #define __func__ __FILE__ ":" STR(__LINE__)
  252. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  253. #define strtoll(x, y, z) (_atoi64(x))
  254. #else
  255. #define __func__ __FUNCTION__
  256. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  257. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  258. #endif
  259. #endif /* _MSC_VER */
  260. #define ERRNO ((int)(GetLastError()))
  261. #define NO_SOCKLEN_T
  262. #if defined(_WIN64) || defined(__MINGW64__)
  263. #define SSL_LIB "ssleay64.dll"
  264. #define CRYPTO_LIB "libeay64.dll"
  265. #else
  266. #define SSL_LIB "ssleay32.dll"
  267. #define CRYPTO_LIB "libeay32.dll"
  268. #endif
  269. #define O_NONBLOCK (0)
  270. #ifndef W_OK
  271. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  272. #endif
  273. #if !defined(EWOULDBLOCK)
  274. #define EWOULDBLOCK WSAEWOULDBLOCK
  275. #endif /* !EWOULDBLOCK */
  276. #define _POSIX_
  277. #define INT64_FMT "I64d"
  278. #define UINT64_FMT "I64u"
  279. #define WINCDECL __cdecl
  280. #define vsnprintf_impl _vsnprintf
  281. #define access _access
  282. #define mg_sleep(x) (Sleep(x))
  283. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  284. #ifndef popen
  285. #define popen(x, y) (_popen(x, y))
  286. #endif
  287. #ifndef pclose
  288. #define pclose(x) (_pclose(x))
  289. #endif
  290. #define close(x) (_close(x))
  291. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  292. #define RTLD_LAZY (0)
  293. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  294. #define fdopen(x, y) (_fdopen((x), (y)))
  295. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  296. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  297. #define flockfile(x) (EnterCriticalSection(&global_log_file_lock))
  298. #define funlockfile(x) (LeaveCriticalSection(&global_log_file_lock))
  299. #define sleep(x) (Sleep((x)*1000))
  300. #define rmdir(x) (_rmdir(x))
  301. #define timegm(x) (_mkgmtime(x))
  302. #if !defined(fileno)
  303. #define fileno(x) (_fileno(x))
  304. #endif /* !fileno MINGW #defines fileno */
  305. typedef HANDLE pthread_mutex_t;
  306. typedef DWORD pthread_key_t;
  307. typedef HANDLE pthread_t;
  308. typedef struct {
  309. CRITICAL_SECTION threadIdSec;
  310. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  311. } pthread_cond_t;
  312. #ifndef __clockid_t_defined
  313. typedef DWORD clockid_t;
  314. #endif
  315. #ifndef CLOCK_MONOTONIC
  316. #define CLOCK_MONOTONIC (1)
  317. #endif
  318. #ifndef CLOCK_REALTIME
  319. #define CLOCK_REALTIME (2)
  320. #endif
  321. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  322. #define _TIMESPEC_DEFINED
  323. #endif
  324. #ifndef _TIMESPEC_DEFINED
  325. struct timespec {
  326. time_t tv_sec; /* seconds */
  327. long tv_nsec; /* nanoseconds */
  328. };
  329. #endif
  330. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  331. static int pthread_mutex_lock(pthread_mutex_t *);
  332. static int pthread_mutex_unlock(pthread_mutex_t *);
  333. static void path_to_unicode(const struct mg_connection *conn,
  334. const char *path,
  335. wchar_t *wbuf,
  336. size_t wbuf_len);
  337. struct file;
  338. static const char *
  339. mg_fgets(char *buf, size_t size, struct file *filep, char **p);
  340. #if defined(HAVE_STDINT)
  341. #include <stdint.h>
  342. #else
  343. typedef unsigned char uint8_t;
  344. typedef unsigned short uint16_t;
  345. typedef unsigned int uint32_t;
  346. typedef unsigned __int64 uint64_t;
  347. typedef __int64 int64_t;
  348. #ifndef INT64_MAX
  349. #define INT64_MAX (9223372036854775807)
  350. #endif
  351. #endif /* HAVE_STDINT */
  352. /* POSIX dirent interface */
  353. struct dirent {
  354. char d_name[PATH_MAX];
  355. };
  356. typedef struct DIR {
  357. HANDLE handle;
  358. WIN32_FIND_DATAW info;
  359. struct dirent result;
  360. } DIR;
  361. #if defined(_WIN32) && !defined(POLLIN)
  362. #ifndef HAVE_POLL
  363. struct pollfd {
  364. SOCKET fd;
  365. short events;
  366. short revents;
  367. };
  368. #define POLLIN (0x0300)
  369. #endif
  370. #endif
  371. /* Mark required libraries */
  372. #if defined(_MSC_VER)
  373. #pragma comment(lib, "Ws2_32.lib")
  374. #endif
  375. #else /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  376. WINDOWS / UNIX include block */
  377. #include <sys/wait.h>
  378. #include <sys/socket.h>
  379. #include <sys/poll.h>
  380. #include <netinet/in.h>
  381. #include <arpa/inet.h>
  382. #include <sys/time.h>
  383. #include <sys/utsname.h>
  384. #include <stdint.h>
  385. #include <inttypes.h>
  386. #include <netdb.h>
  387. #include <netinet/tcp.h>
  388. typedef const void *SOCK_OPT_TYPE;
  389. #if defined(ANDROID)
  390. typedef unsigned short int in_port_t;
  391. #endif
  392. #include <pwd.h>
  393. #include <unistd.h>
  394. #include <grp.h>
  395. #include <dirent.h>
  396. #define vsnprintf_impl vsnprintf
  397. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  398. #include <dlfcn.h>
  399. #endif
  400. #include <pthread.h>
  401. #if defined(__MACH__)
  402. #define SSL_LIB "libssl.dylib"
  403. #define CRYPTO_LIB "libcrypto.dylib"
  404. #else
  405. #if !defined(SSL_LIB)
  406. #define SSL_LIB "libssl.so"
  407. #endif
  408. #if !defined(CRYPTO_LIB)
  409. #define CRYPTO_LIB "libcrypto.so"
  410. #endif
  411. #endif
  412. #ifndef O_BINARY
  413. #define O_BINARY (0)
  414. #endif /* O_BINARY */
  415. #define closesocket(a) (close(a))
  416. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  417. #define mg_remove(conn, x) (remove(x))
  418. #define mg_sleep(x) (usleep((x)*1000))
  419. #define mg_opendir(conn, x) (opendir(x))
  420. #define mg_closedir(x) (closedir(x))
  421. #define mg_readdir(x) (readdir(x))
  422. #define ERRNO (errno)
  423. #define INVALID_SOCKET (-1)
  424. #define INT64_FMT PRId64
  425. #define UINT64_FMT PRIu64
  426. typedef int SOCKET;
  427. #define WINCDECL
  428. #if defined(__hpux)
  429. /* HPUX 11 does not have monotonic, fall back to realtime */
  430. #ifndef CLOCK_MONOTONIC
  431. #define CLOCK_MONOTONIC CLOCK_REALTIME
  432. #endif
  433. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  434. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  435. * the prototypes use int* rather than socklen_t* which matches the
  436. * actual library expectation. When called with the wrong size arg
  437. * accept() returns a zero client inet addr and check_acl() always
  438. * fails. Since socklen_t is widely used below, just force replace
  439. * their typedef with int. - DTL
  440. */
  441. #define socklen_t int
  442. #endif /* hpux */
  443. #endif /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  444. WINDOWS / UNIX include block */
  445. /* va_copy should always be a macro, C99 and C++11 - DTL */
  446. #ifndef va_copy
  447. #define va_copy(x, y) ((x) = (y))
  448. #endif
  449. #ifdef _WIN32
  450. /* Create substitutes for POSIX functions in Win32. */
  451. #if defined(__MINGW32__)
  452. /* Show no warning in case system functions are not used. */
  453. #pragma GCC diagnostic push
  454. #pragma GCC diagnostic ignored "-Wunused-function"
  455. #endif
  456. static CRITICAL_SECTION global_log_file_lock;
  457. static DWORD
  458. pthread_self(void)
  459. {
  460. return GetCurrentThreadId();
  461. }
  462. static int
  463. pthread_key_create(
  464. pthread_key_t *key,
  465. void (*_ignored)(void *) /* destructor not supported for Windows */
  466. )
  467. {
  468. (void)_ignored;
  469. if ((key != 0)) {
  470. *key = TlsAlloc();
  471. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  472. }
  473. return -2;
  474. }
  475. static int
  476. pthread_key_delete(pthread_key_t key)
  477. {
  478. return TlsFree(key) ? 0 : 1;
  479. }
  480. static int
  481. pthread_setspecific(pthread_key_t key, void *value)
  482. {
  483. return TlsSetValue(key, value) ? 0 : 1;
  484. }
  485. static void *
  486. pthread_getspecific(pthread_key_t key)
  487. {
  488. return TlsGetValue(key);
  489. }
  490. #if defined(__MINGW32__)
  491. /* Enable unused function warning again */
  492. #pragma GCC diagnostic pop
  493. #endif
  494. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  495. #else
  496. static pthread_mutexattr_t pthread_mutex_attr;
  497. #endif /* _WIN32 */
  498. #define PASSWORDS_FILE_NAME ".htpasswd"
  499. #define CGI_ENVIRONMENT_SIZE (4096)
  500. #define MAX_CGI_ENVIR_VARS (256)
  501. #define MG_BUF_LEN (8192)
  502. #ifndef MAX_REQUEST_SIZE
  503. #define MAX_REQUEST_SIZE (16384)
  504. #endif
  505. mg_static_assert(MAX_REQUEST_SIZE >= 256,
  506. "request size length must be a positive number");
  507. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  508. #if !defined(DEBUG_TRACE)
  509. #if defined(DEBUG)
  510. #if defined(_WIN32_WCE)
  511. /* Create substitutes for POSIX functions in Win32. */
  512. #if defined(__MINGW32__)
  513. /* Show no warning in case system functions are not used. */
  514. #pragma GCC diagnostic push
  515. #pragma GCC diagnostic ignored "-Wunused-function"
  516. #endif
  517. static time_t
  518. time(time_t *ptime)
  519. {
  520. time_t t;
  521. SYSTEMTIME st;
  522. FILETIME ft;
  523. GetSystemTime(&st);
  524. SystemTimeToFileTime(&st, &ft);
  525. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  526. if (ptime != NULL) {
  527. *ptime = t;
  528. }
  529. return t;
  530. }
  531. static struct tm *
  532. localtime_s(const time_t *ptime, struct tm *ptm)
  533. {
  534. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  535. FILETIME ft, lft;
  536. SYSTEMTIME st;
  537. TIME_ZONE_INFORMATION tzinfo;
  538. if (ptm == NULL) {
  539. return NULL;
  540. }
  541. *(int64_t *)&ft = t;
  542. FileTimeToLocalFileTime(&ft, &lft);
  543. FileTimeToSystemTime(&lft, &st);
  544. ptm->tm_year = st.wYear - 1900;
  545. ptm->tm_mon = st.wMonth - 1;
  546. ptm->tm_wday = st.wDayOfWeek;
  547. ptm->tm_mday = st.wDay;
  548. ptm->tm_hour = st.wHour;
  549. ptm->tm_min = st.wMinute;
  550. ptm->tm_sec = st.wSecond;
  551. ptm->tm_yday = 0; /* hope nobody uses this */
  552. ptm->tm_isdst =
  553. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  554. return ptm;
  555. }
  556. static struct tm *
  557. gmtime_s(const time_t *ptime, struct tm *ptm)
  558. {
  559. /* FIXME(lsm): fix this. */
  560. return localtime_s(ptime, ptm);
  561. }
  562. static int mg_atomic_inc(volatile int *addr);
  563. static struct tm tm_array[MAX_WORKER_THREADS];
  564. static int tm_index = 0;
  565. static struct tm *
  566. localtime(const time_t *ptime)
  567. {
  568. int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0]));
  569. return localtime_s(ptime, tm_array + i);
  570. }
  571. static struct tm *
  572. gmtime(const time_t *ptime)
  573. {
  574. int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  575. return gmtime_s(ptime, tm_array + i);
  576. }
  577. static size_t
  578. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  579. {
  580. /* TODO */ //(void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  581. // for WinCE");
  582. return 0;
  583. }
  584. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  585. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  586. #define remove(f) mg_remove(NULL, f)
  587. static int
  588. rename(const char *a, const char *b)
  589. {
  590. wchar_t wa[PATH_MAX];
  591. wchar_t wb[PATH_MAX];
  592. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  593. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  594. return MoveFileW(wa, wb) ? 0 : -1;
  595. }
  596. struct stat {
  597. int64_t st_size;
  598. time_t st_mtime;
  599. };
  600. static int
  601. stat(const char *name, struct stat *st)
  602. {
  603. wchar_t wbuf[PATH_MAX];
  604. WIN32_FILE_ATTRIBUTE_DATA attr;
  605. time_t creation_time, write_time;
  606. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  607. memset(&attr, 0, sizeof(attr));
  608. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  609. st->st_size =
  610. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  611. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  612. attr.ftLastWriteTime.dwHighDateTime);
  613. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  614. attr.ftCreationTime.dwHighDateTime);
  615. if (creation_time > write_time) {
  616. st->st_mtime = creation_time;
  617. } else {
  618. st->st_mtime = write_time;
  619. }
  620. return 0;
  621. }
  622. #define access(x, a) 1 /* not required anyway */
  623. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  624. #define EEXIST 1 /* TODO: See Windows error codes */
  625. #define EACCES 2 /* TODO: See Windows error codes */
  626. #define ENOENT 3 /* TODO: See Windows Error codes */
  627. #if defined(__MINGW32__)
  628. /* Enable unused function warning again */
  629. #pragma GCC diagnostic pop
  630. #endif
  631. #endif /* defined(_WIN32_WCE) */
  632. static void DEBUG_TRACE_FUNC(const char *func,
  633. unsigned line,
  634. PRINTF_FORMAT_STRING(const char *fmt),
  635. ...) PRINTF_ARGS(3, 4);
  636. static void
  637. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  638. {
  639. va_list args;
  640. flockfile(stdout);
  641. printf("*** %lu.%p.%s.%u: ",
  642. (unsigned long)time(NULL),
  643. (void *)pthread_self(),
  644. func,
  645. line);
  646. va_start(args, fmt);
  647. vprintf(fmt, args);
  648. va_end(args);
  649. putchar('\n');
  650. fflush(stdout);
  651. funlockfile(stdout);
  652. }
  653. #define DEBUG_TRACE(fmt, ...) \
  654. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  655. #else
  656. #define DEBUG_TRACE(fmt, ...) \
  657. do { \
  658. } while (0)
  659. #endif /* DEBUG */
  660. #endif /* DEBUG_TRACE */
  661. #if defined(MEMORY_DEBUGGING)
  662. unsigned long mg_memory_debug_blockCount = 0;
  663. unsigned long mg_memory_debug_totalMemUsed = 0;
  664. static void *
  665. mg_malloc_ex(size_t size, const char *file, unsigned line)
  666. {
  667. void *data = malloc(size + sizeof(size_t));
  668. void *memory = 0;
  669. char mallocStr[256];
  670. if (data) {
  671. *(size_t *)data = size;
  672. mg_memory_debug_totalMemUsed += size;
  673. mg_memory_debug_blockCount++;
  674. memory = (void *)(((char *)data) + sizeof(size_t));
  675. }
  676. sprintf(mallocStr,
  677. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  678. memory,
  679. (unsigned long)size,
  680. mg_memory_debug_totalMemUsed,
  681. mg_memory_debug_blockCount,
  682. file,
  683. line);
  684. #if defined(_WIN32)
  685. OutputDebugStringA(mallocStr);
  686. #else
  687. DEBUG_TRACE("%s", mallocStr);
  688. #endif
  689. return memory;
  690. }
  691. static void *
  692. mg_calloc_ex(size_t count, size_t size, const char *file, unsigned line)
  693. {
  694. void *data = mg_malloc_ex(size * count, file, line);
  695. if (data) {
  696. memset(data, 0, size * count);
  697. }
  698. return data;
  699. }
  700. static void
  701. mg_free_ex(void *memory, const char *file, unsigned line)
  702. {
  703. char mallocStr[256];
  704. void *data = (void *)(((char *)memory) - sizeof(size_t));
  705. size_t size;
  706. if (memory) {
  707. size = *(size_t *)data;
  708. mg_memory_debug_totalMemUsed -= size;
  709. mg_memory_debug_blockCount--;
  710. sprintf(mallocStr,
  711. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  712. memory,
  713. (unsigned long)size,
  714. mg_memory_debug_totalMemUsed,
  715. mg_memory_debug_blockCount,
  716. file,
  717. line);
  718. #if defined(_WIN32)
  719. OutputDebugStringA(mallocStr);
  720. #else
  721. DEBUG_TRACE("%s", mallocStr);
  722. #endif
  723. free(data);
  724. }
  725. }
  726. static void *
  727. mg_realloc_ex(void *memory, size_t newsize, const char *file, unsigned line)
  728. {
  729. char mallocStr[256];
  730. void *data;
  731. void *_realloc;
  732. size_t oldsize;
  733. if (newsize) {
  734. if (memory) {
  735. data = (void *)(((char *)memory) - sizeof(size_t));
  736. oldsize = *(size_t *)data;
  737. _realloc = realloc(data, newsize + sizeof(size_t));
  738. if (_realloc) {
  739. data = _realloc;
  740. mg_memory_debug_totalMemUsed -= oldsize;
  741. sprintf(mallocStr,
  742. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  743. memory,
  744. (unsigned long)oldsize,
  745. mg_memory_debug_totalMemUsed,
  746. mg_memory_debug_blockCount,
  747. file,
  748. line);
  749. #if defined(_WIN32)
  750. OutputDebugStringA(mallocStr);
  751. #else
  752. DEBUG_TRACE("%s", mallocStr);
  753. #endif
  754. mg_memory_debug_totalMemUsed += newsize;
  755. sprintf(mallocStr,
  756. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  757. memory,
  758. (unsigned long)newsize,
  759. mg_memory_debug_totalMemUsed,
  760. mg_memory_debug_blockCount,
  761. file,
  762. line);
  763. #if defined(_WIN32)
  764. OutputDebugStringA(mallocStr);
  765. #else
  766. DEBUG_TRACE("%s", mallocStr);
  767. #endif
  768. *(size_t *)data = newsize;
  769. data = (void *)(((char *)data) + sizeof(size_t));
  770. } else {
  771. #if defined(_WIN32)
  772. OutputDebugStringA("MEM: realloc failed\n");
  773. #else
  774. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  775. #endif
  776. return _realloc;
  777. }
  778. } else {
  779. data = mg_malloc_ex(newsize, file, line);
  780. }
  781. } else {
  782. data = 0;
  783. mg_free_ex(memory, file, line);
  784. }
  785. return data;
  786. }
  787. #define mg_malloc(a) mg_malloc_ex(a, __FILE__, __LINE__)
  788. #define mg_calloc(a, b) mg_calloc_ex(a, b, __FILE__, __LINE__)
  789. #define mg_realloc(a, b) mg_realloc_ex(a, b, __FILE__, __LINE__)
  790. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  791. #else
  792. static __inline void *
  793. mg_malloc(size_t a)
  794. {
  795. return malloc(a);
  796. }
  797. static __inline void *
  798. mg_calloc(size_t a, size_t b)
  799. {
  800. return calloc(a, b);
  801. }
  802. static __inline void *
  803. mg_realloc(void *a, size_t b)
  804. {
  805. return realloc(a, b);
  806. }
  807. static __inline void
  808. mg_free(void *a)
  809. {
  810. free(a);
  811. }
  812. #endif
  813. static void mg_vsnprintf(const struct mg_connection *conn,
  814. int *truncated,
  815. char *buf,
  816. size_t buflen,
  817. const char *fmt,
  818. va_list ap);
  819. static void mg_snprintf(const struct mg_connection *conn,
  820. int *truncated,
  821. char *buf,
  822. size_t buflen,
  823. PRINTF_FORMAT_STRING(const char *fmt),
  824. ...) PRINTF_ARGS(5, 6);
  825. /* This following lines are just meant as a reminder to use the mg-functions
  826. * for memory management */
  827. #ifdef malloc
  828. #undef malloc
  829. #endif
  830. #ifdef calloc
  831. #undef calloc
  832. #endif
  833. #ifdef realloc
  834. #undef realloc
  835. #endif
  836. #ifdef free
  837. #undef free
  838. #endif
  839. #ifdef snprintf
  840. #undef snprintf
  841. #endif
  842. #ifdef vsnprintf
  843. #undef vsnprintf
  844. #endif
  845. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  846. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  847. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  848. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  849. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  850. #ifdef _WIN32 /* vsnprintf must not be used in any system, * \ \ \ \
  851. * but this define only works well for Windows. */
  852. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  853. #endif
  854. #define MD5_STATIC static
  855. #include "md5.inl"
  856. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  857. #ifdef NO_SOCKLEN_T
  858. typedef int socklen_t;
  859. #endif /* NO_SOCKLEN_T */
  860. #define _DARWIN_UNLIMITED_SELECT
  861. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  862. #if !defined(MSG_NOSIGNAL)
  863. #define MSG_NOSIGNAL (0)
  864. #endif
  865. #if !defined(SOMAXCONN)
  866. #define SOMAXCONN (100)
  867. #endif
  868. /* Size of the accepted socket queue */
  869. #if !defined(MGSQLEN)
  870. #define MGSQLEN (20)
  871. #endif
  872. #if defined(NO_SSL)
  873. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  874. typedef struct SSL_CTX SSL_CTX;
  875. #else
  876. #if defined(NO_SSL_DL)
  877. #include <openssl/ssl.h>
  878. #include <openssl/err.h>
  879. #include <openssl/crypto.h>
  880. #include <openssl/x509.h>
  881. #include <openssl/pem.h>
  882. #include <openssl/engine.h>
  883. #include <openssl/conf.h>
  884. #include <openssl/dh.h>
  885. #else
  886. /* SSL loaded dynamically from DLL.
  887. * I put the prototypes here to be independent from OpenSSL source
  888. * installation. */
  889. typedef struct ssl_st SSL;
  890. typedef struct ssl_method_st SSL_METHOD;
  891. typedef struct ssl_ctx_st SSL_CTX;
  892. typedef struct x509_store_ctx_st X509_STORE_CTX;
  893. typedef struct x509_name X509_NAME;
  894. typedef struct asn1_integer ASN1_INTEGER;
  895. typedef struct evp_md EVP_MD;
  896. typedef struct x509 X509;
  897. #define SSL_CTRL_OPTIONS (32)
  898. #define SSL_CTRL_CLEAR_OPTIONS (77)
  899. #define SSL_CTRL_SET_ECDH_AUTO (94)
  900. #define SSL_VERIFY_NONE (0)
  901. #define SSL_VERIFY_PEER (1)
  902. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  903. #define SSL_VERIFY_CLIENT_ONCE (4)
  904. #define SSL_OP_ALL ((long)(0x80000BFFUL))
  905. #define SSL_OP_NO_SSLv2 (0x01000000L)
  906. #define SSL_OP_NO_SSLv3 (0x02000000L)
  907. #define SSL_OP_NO_TLSv1 (0x04000000L)
  908. #define SSL_OP_NO_TLSv1_2 (0x08000000L)
  909. #define SSL_OP_NO_TLSv1_1 (0x10000000L)
  910. #define SSL_OP_SINGLE_DH_USE (0x00100000L)
  911. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000L)
  912. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000L)
  913. #define SSL_ERROR_NONE (0)
  914. #define SSL_ERROR_SSL (1)
  915. #define SSL_ERROR_WANT_READ (2)
  916. #define SSL_ERROR_WANT_WRITE (3)
  917. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  918. #define SSL_ERROR_SYSCALL (5) /* see errno */
  919. #define SSL_ERROR_ZERO_RETURN (6)
  920. #define SSL_ERROR_WANT_CONNECT (7)
  921. #define SSL_ERROR_WANT_ACCEPT (8)
  922. struct ssl_func {
  923. const char *name; /* SSL function name */
  924. void (*ptr)(void); /* Function pointer */
  925. };
  926. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  927. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  928. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  929. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  930. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  931. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  932. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  933. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  934. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  935. #define SSLv23_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  936. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  937. #define SSL_CTX_use_PrivateKey_file \
  938. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  939. #define SSL_CTX_use_certificate_file \
  940. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  941. #define SSL_CTX_set_default_passwd_cb \
  942. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  943. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  944. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  945. #define SSL_CTX_use_certificate_chain_file \
  946. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  947. #define SSLv23_client_method (*(SSL_METHOD * (*)(void))ssl_sw[17].ptr)
  948. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  949. #define SSL_CTX_set_verify \
  950. (*(void (*)(SSL_CTX *, \
  951. int, \
  952. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19].ptr)
  953. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  954. #define SSL_CTX_load_verify_locations \
  955. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  956. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  957. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  958. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[24].ptr)
  959. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  960. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[26].ptr)
  961. #define SSL_CIPHER_get_name \
  962. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  963. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  964. #define SSL_CTX_set_session_id_context \
  965. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  966. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  967. #define SSL_CTX_set_cipher_list \
  968. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  969. #define SSL_CTX_set_options(ctx, op) \
  970. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  971. #define SSL_CTX_clear_options(ctx, op) \
  972. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  973. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  974. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  975. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  976. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  977. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  978. #define CRYPTO_set_locking_callback \
  979. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  980. #define CRYPTO_set_id_callback \
  981. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  982. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  983. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  984. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  985. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  986. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  987. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  988. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  989. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  990. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  991. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[12].ptr)
  992. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[13].ptr)
  993. #define X509_NAME_oneline \
  994. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  995. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[15].ptr)
  996. #define i2c_ASN1_INTEGER \
  997. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  998. #define EVP_get_digestbyname \
  999. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1000. #define ASN1_digest \
  1001. (*(int (*)(int (*)(), \
  1002. const EVP_MD *, \
  1003. char *, \
  1004. unsigned char *, \
  1005. unsigned int *))crypto_sw[18].ptr)
  1006. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1007. /* set_ssl_option() function updates this array.
  1008. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1009. * of respective functions. The macros above (like SSL_connect()) are really
  1010. * just calling these functions indirectly via the pointer. */
  1011. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1012. {"SSL_accept", NULL},
  1013. {"SSL_connect", NULL},
  1014. {"SSL_read", NULL},
  1015. {"SSL_write", NULL},
  1016. {"SSL_get_error", NULL},
  1017. {"SSL_set_fd", NULL},
  1018. {"SSL_new", NULL},
  1019. {"SSL_CTX_new", NULL},
  1020. {"SSLv23_server_method", NULL},
  1021. {"SSL_library_init", NULL},
  1022. {"SSL_CTX_use_PrivateKey_file", NULL},
  1023. {"SSL_CTX_use_certificate_file", NULL},
  1024. {"SSL_CTX_set_default_passwd_cb", NULL},
  1025. {"SSL_CTX_free", NULL},
  1026. {"SSL_load_error_strings", NULL},
  1027. {"SSL_CTX_use_certificate_chain_file", NULL},
  1028. {"SSLv23_client_method", NULL},
  1029. {"SSL_pending", NULL},
  1030. {"SSL_CTX_set_verify", NULL},
  1031. {"SSL_shutdown", NULL},
  1032. {"SSL_CTX_load_verify_locations", NULL},
  1033. {"SSL_CTX_set_default_verify_paths", NULL},
  1034. {"SSL_CTX_set_verify_depth", NULL},
  1035. {"SSL_get_peer_certificate", NULL},
  1036. {"SSL_get_version", NULL},
  1037. {"SSL_get_current_cipher", NULL},
  1038. {"SSL_CIPHER_get_name", NULL},
  1039. {"SSL_CTX_check_private_key", NULL},
  1040. {"SSL_CTX_set_session_id_context", NULL},
  1041. {"SSL_CTX_ctrl", NULL},
  1042. {"SSL_CTX_set_cipher_list", NULL},
  1043. {NULL, NULL}};
  1044. /* Similar array as ssl_sw. These functions could be located in different
  1045. * lib. */
  1046. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  1047. {"CRYPTO_set_locking_callback", NULL},
  1048. {"CRYPTO_set_id_callback", NULL},
  1049. {"ERR_get_error", NULL},
  1050. {"ERR_error_string", NULL},
  1051. {"ERR_remove_state", NULL},
  1052. {"ERR_free_strings", NULL},
  1053. {"ENGINE_cleanup", NULL},
  1054. {"CONF_modules_unload", NULL},
  1055. {"CRYPTO_cleanup_all_ex_data", NULL},
  1056. {"EVP_cleanup", NULL},
  1057. {"X509_free", NULL},
  1058. {"X509_get_subject_name", NULL},
  1059. {"X509_get_issuer_name", NULL},
  1060. {"X509_NAME_oneline", NULL},
  1061. {"X509_get_serialNumber", NULL},
  1062. {"i2c_ASN1_INTEGER", NULL},
  1063. {"EVP_get_digestbyname", NULL},
  1064. {"ASN1_digest", NULL},
  1065. {"i2d_X509", NULL},
  1066. {NULL, NULL}};
  1067. #endif /* NO_SSL_DL */
  1068. #endif /* NO_SSL */
  1069. #if !defined(NO_CACHING)
  1070. static const char *month_names[] = {"Jan",
  1071. "Feb",
  1072. "Mar",
  1073. "Apr",
  1074. "May",
  1075. "Jun",
  1076. "Jul",
  1077. "Aug",
  1078. "Sep",
  1079. "Oct",
  1080. "Nov",
  1081. "Dec"};
  1082. #endif /* !NO_CACHING */
  1083. /* Unified socket address. For IPv6 support, add IPv6 address structure in the
  1084. * union u. */
  1085. union usa {
  1086. struct sockaddr sa;
  1087. struct sockaddr_in sin;
  1088. #if defined(USE_IPV6)
  1089. struct sockaddr_in6 sin6;
  1090. #endif
  1091. };
  1092. /* Describes a string (chunk of memory). */
  1093. struct vec {
  1094. const char *ptr;
  1095. size_t len;
  1096. };
  1097. struct file {
  1098. uint64_t size;
  1099. time_t last_modified;
  1100. FILE *fp;
  1101. const char *membuf; /* Non-NULL if file data is in memory */
  1102. int is_directory;
  1103. int gzipped; /* set to 1 if the content is gzipped
  1104. * in which case we need a content-encoding: gzip header */
  1105. };
  1106. #define STRUCT_FILE_INITIALIZER \
  1107. { \
  1108. (uint64_t)0, (time_t)0, (FILE *)NULL, (const char *)NULL, 0, 0 \
  1109. }
  1110. /* Describes listening socket, or socket which was accept()-ed by the master
  1111. * thread and queued for future handling by the worker thread. */
  1112. struct socket {
  1113. SOCKET sock; /* Listening socket */
  1114. union usa lsa; /* Local socket address */
  1115. union usa rsa; /* Remote socket address */
  1116. unsigned char is_ssl; /* Is port SSL-ed */
  1117. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1118. * port */
  1119. unsigned char in_use; /* Is valid */
  1120. };
  1121. /* NOTE(lsm): this enum shoulds be in sync with the config_options below. */
  1122. enum {
  1123. CGI_EXTENSIONS,
  1124. CGI_ENVIRONMENT,
  1125. PUT_DELETE_PASSWORDS_FILE,
  1126. CGI_INTERPRETER,
  1127. PROTECT_URI,
  1128. AUTHENTICATION_DOMAIN,
  1129. SSI_EXTENSIONS,
  1130. THROTTLE,
  1131. ACCESS_LOG_FILE,
  1132. ENABLE_DIRECTORY_LISTING,
  1133. ERROR_LOG_FILE,
  1134. GLOBAL_PASSWORDS_FILE,
  1135. INDEX_FILES,
  1136. ENABLE_KEEP_ALIVE,
  1137. ACCESS_CONTROL_LIST,
  1138. EXTRA_MIME_TYPES,
  1139. LISTENING_PORTS,
  1140. DOCUMENT_ROOT,
  1141. SSL_CERTIFICATE,
  1142. NUM_THREADS,
  1143. RUN_AS_USER,
  1144. REWRITE,
  1145. HIDE_FILES,
  1146. REQUEST_TIMEOUT,
  1147. SSL_DO_VERIFY_PEER,
  1148. SSL_CA_PATH,
  1149. SSL_CA_FILE,
  1150. SSL_VERIFY_DEPTH,
  1151. SSL_DEFAULT_VERIFY_PATHS,
  1152. SSL_CIPHER_LIST,
  1153. SSL_PROTOCOL_VERSION,
  1154. SSL_SHORT_TRUST,
  1155. #if defined(USE_WEBSOCKET)
  1156. WEBSOCKET_TIMEOUT,
  1157. #endif
  1158. DECODE_URL,
  1159. #if defined(USE_LUA)
  1160. LUA_PRELOAD_FILE,
  1161. LUA_SCRIPT_EXTENSIONS,
  1162. LUA_SERVER_PAGE_EXTENSIONS,
  1163. #endif
  1164. #if defined(USE_DUKTAPE)
  1165. DUKTAPE_SCRIPT_EXTENSIONS,
  1166. #endif
  1167. #if defined(USE_WEBSOCKET)
  1168. WEBSOCKET_ROOT,
  1169. #endif
  1170. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1171. LUA_WEBSOCKET_EXTENSIONS,
  1172. #endif
  1173. ACCESS_CONTROL_ALLOW_ORIGIN,
  1174. ERROR_PAGES,
  1175. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1176. * socket option typedef TCP_NODELAY. */
  1177. #if !defined(NO_CACHING)
  1178. STATIC_FILE_MAX_AGE,
  1179. #endif
  1180. #if defined(__linux__)
  1181. ALLOW_SENDFILE_CALL,
  1182. #endif
  1183. #if defined(_WIN32)
  1184. CASE_SENSITIVE_FILES,
  1185. #endif
  1186. NUM_OPTIONS
  1187. };
  1188. /* Config option name, config types, default value */
  1189. static struct mg_option config_options[] = {
  1190. {"cgi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1191. {"cgi_environment", CONFIG_TYPE_STRING, NULL},
  1192. {"put_delete_auth_file", CONFIG_TYPE_FILE, NULL},
  1193. {"cgi_interpreter", CONFIG_TYPE_FILE, NULL},
  1194. {"protect_uri", CONFIG_TYPE_STRING, NULL},
  1195. {"authentication_domain", CONFIG_TYPE_STRING, "mydomain.com"},
  1196. {"ssi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1197. {"throttle", CONFIG_TYPE_STRING, NULL},
  1198. {"access_log_file", CONFIG_TYPE_FILE, NULL},
  1199. {"enable_directory_listing", CONFIG_TYPE_BOOLEAN, "yes"},
  1200. {"error_log_file", CONFIG_TYPE_FILE, NULL},
  1201. {"global_auth_file", CONFIG_TYPE_FILE, NULL},
  1202. {"index_files",
  1203. CONFIG_TYPE_STRING,
  1204. #ifdef USE_LUA
  1205. "index.xhtml,index.html,index.htm,index.lp,index.lsp,index.lua,index.cgi,"
  1206. "index.shtml,index.php"},
  1207. #else
  1208. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1209. #endif
  1210. {"enable_keep_alive", CONFIG_TYPE_BOOLEAN, "no"},
  1211. {"access_control_list", CONFIG_TYPE_STRING, NULL},
  1212. {"extra_mime_types", CONFIG_TYPE_STRING, NULL},
  1213. {"listening_ports", CONFIG_TYPE_STRING, "8080"},
  1214. {"document_root", CONFIG_TYPE_DIRECTORY, NULL},
  1215. {"ssl_certificate", CONFIG_TYPE_FILE, NULL},
  1216. {"num_threads", CONFIG_TYPE_NUMBER, "50"},
  1217. {"run_as_user", CONFIG_TYPE_STRING, NULL},
  1218. {"url_rewrite_patterns", CONFIG_TYPE_STRING, NULL},
  1219. {"hide_files_patterns", CONFIG_TYPE_EXT_PATTERN, NULL},
  1220. {"request_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1221. {"ssl_verify_peer", CONFIG_TYPE_BOOLEAN, "no"},
  1222. {"ssl_ca_path", CONFIG_TYPE_DIRECTORY, NULL},
  1223. {"ssl_ca_file", CONFIG_TYPE_FILE, NULL},
  1224. {"ssl_verify_depth", CONFIG_TYPE_NUMBER, "9"},
  1225. {"ssl_default_verify_paths", CONFIG_TYPE_BOOLEAN, "yes"},
  1226. {"ssl_cipher_list", CONFIG_TYPE_STRING, NULL},
  1227. {"ssl_protocol_version", CONFIG_TYPE_NUMBER, "0"},
  1228. {"ssl_short_trust", CONFIG_TYPE_BOOLEAN, "no"},
  1229. #if defined(USE_WEBSOCKET)
  1230. {"websocket_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1231. #endif
  1232. {"decode_url", CONFIG_TYPE_BOOLEAN, "yes"},
  1233. #if defined(USE_LUA)
  1234. {"lua_preload_file", CONFIG_TYPE_FILE, NULL},
  1235. {"lua_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1236. {"lua_server_page_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1237. #endif
  1238. #if defined(USE_DUKTAPE)
  1239. /* The support for duktape is still in alpha version state.
  1240. * The name of this config option might change. */
  1241. {"duktape_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1242. #endif
  1243. #if defined(USE_WEBSOCKET)
  1244. {"websocket_root", CONFIG_TYPE_DIRECTORY, NULL},
  1245. #endif
  1246. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1247. {"lua_websocket_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1248. #endif
  1249. {"access_control_allow_origin", CONFIG_TYPE_STRING, "*"},
  1250. {"error_pages", CONFIG_TYPE_DIRECTORY, NULL},
  1251. {"tcp_nodelay", CONFIG_TYPE_NUMBER, "0"},
  1252. #if !defined(NO_CACHING)
  1253. {"static_file_max_age", CONFIG_TYPE_NUMBER, "3600"},
  1254. #endif
  1255. #if defined(__linux__)
  1256. {"allow_sendfile_call", CONFIG_TYPE_BOOLEAN, "yes"},
  1257. #endif
  1258. #if defined(_WIN32)
  1259. {"case_sensitive", CONFIG_TYPE_BOOLEAN, "no"},
  1260. #endif
  1261. {NULL, CONFIG_TYPE_UNKNOWN, NULL}};
  1262. /* Check if the config_options and the corresponding enum have compatible
  1263. * sizes. */
  1264. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1265. == (NUM_OPTIONS + 1),
  1266. "config_options and enum not sync");
  1267. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1268. struct mg_handler_info {
  1269. /* Name/Pattern of the URI. */
  1270. char *uri;
  1271. size_t uri_len;
  1272. /* handler type */
  1273. int handler_type;
  1274. /* Handler for http/https or authorization requests. */
  1275. mg_request_handler handler;
  1276. /* Handler for ws/wss (websocket) requests. */
  1277. mg_websocket_connect_handler connect_handler;
  1278. mg_websocket_ready_handler ready_handler;
  1279. mg_websocket_data_handler data_handler;
  1280. mg_websocket_close_handler close_handler;
  1281. /* Handler for authorization requests */
  1282. mg_authorization_handler auth_handler;
  1283. /* User supplied argument for the handler function. */
  1284. void *cbdata;
  1285. /* next handler in a linked list */
  1286. struct mg_handler_info *next;
  1287. };
  1288. struct mg_context {
  1289. volatile int stop_flag; /* Should we stop event loop */
  1290. SSL_CTX *ssl_ctx; /* SSL context */
  1291. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1292. struct mg_callbacks callbacks; /* User-defined callback function */
  1293. void *user_data; /* User-defined data */
  1294. int context_type; /* 1 = server context, 2 = client context */
  1295. struct socket *listening_sockets;
  1296. struct pollfd *listening_socket_fds;
  1297. unsigned int num_listening_sockets;
  1298. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  1299. #ifdef ALTERNATIVE_QUEUE
  1300. struct socket *client_socks;
  1301. void **client_wait_events;
  1302. #else
  1303. struct socket queue[MGSQLEN]; /* Accepted sockets */
  1304. volatile int sq_head; /* Head of the socket queue */
  1305. volatile int sq_tail; /* Tail of the socket queue */
  1306. pthread_cond_t sq_full; /* Signaled when socket is produced */
  1307. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  1308. #endif
  1309. pthread_t masterthreadid; /* The master thread ID */
  1310. unsigned int
  1311. cfg_worker_threads; /* The number of configured worker threads. */
  1312. pthread_t *workerthreadids; /* The worker thread IDs */
  1313. time_t start_time; /* Server start time, used for authentication */
  1314. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1315. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  1316. unsigned long nonce_count; /* Used nonces, used for authentication */
  1317. char *systemName; /* What operating system is running */
  1318. /* linked list of uri handlers */
  1319. struct mg_handler_info *handlers;
  1320. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1321. /* linked list of shared lua websockets */
  1322. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1323. #endif
  1324. #ifdef USE_TIMERS
  1325. struct ttimers *timers;
  1326. #endif
  1327. };
  1328. struct mg_connection {
  1329. struct mg_request_info request_info;
  1330. struct mg_context *ctx;
  1331. SSL *ssl; /* SSL descriptor */
  1332. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  1333. struct socket client; /* Connected client */
  1334. time_t conn_birth_time; /* Time (wall clock) when connection was
  1335. * established */
  1336. struct timespec req_time; /* Time (since system start) when the request
  1337. * was received */
  1338. int64_t num_bytes_sent; /* Total bytes sent to client */
  1339. int64_t content_len; /* Content-Length header value */
  1340. int64_t consumed_content; /* How many bytes of content have been read */
  1341. int is_chunked; /* Transfer-Encoding is chunked: 0=no, 1=yes:
  1342. * data available, 2: all data read */
  1343. size_t chunk_remainder; /* Unread data from the last chunk */
  1344. char *buf; /* Buffer for received data */
  1345. char *path_info; /* PATH_INFO part of the URL */
  1346. int must_close; /* 1 if connection must be closed */
  1347. int in_error_handler; /* 1 if in handler for user defined error
  1348. * pages */
  1349. int internal_error; /* 1 if an error occured while processing the
  1350. * request */
  1351. int buf_size; /* Buffer size */
  1352. int request_len; /* Size of the request + headers in a buffer */
  1353. int data_len; /* Total size of data in a buffer */
  1354. int status_code; /* HTTP reply status code, e.g. 200 */
  1355. int throttle; /* Throttling, bytes/sec. <= 0 means no
  1356. * throttle */
  1357. time_t last_throttle_time; /* Last time throttled data was sent */
  1358. int64_t last_throttle_bytes; /* Bytes sent this second */
  1359. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  1360. * atomic transmissions for websockets */
  1361. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1362. void *lua_websocket_state; /* Lua_State for a websocket connection */
  1363. #endif
  1364. int thread_index; /* Thread index within ctx */
  1365. };
  1366. static pthread_key_t sTlsKey; /* Thread local storage index */
  1367. static int sTlsInit = 0;
  1368. static int thread_idx_max = 0;
  1369. struct mg_workerTLS {
  1370. int is_master;
  1371. unsigned long thread_idx;
  1372. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1373. HANDLE pthread_cond_helper_mutex;
  1374. struct mg_workerTLS *next_waiting_thread;
  1375. #endif
  1376. };
  1377. /* Directory entry */
  1378. struct de {
  1379. struct mg_connection *conn;
  1380. char *file_name;
  1381. struct file file;
  1382. };
  1383. #if defined(USE_WEBSOCKET)
  1384. static int is_websocket_protocol(const struct mg_connection *conn);
  1385. #else
  1386. #define is_websocket_protocol(conn) (0)
  1387. #endif
  1388. static int
  1389. mg_atomic_inc(volatile int *addr)
  1390. {
  1391. int ret;
  1392. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1393. /* Depending on the SDK, this function uses either
  1394. * (volatile unsigned int *) or (volatile LONG *),
  1395. * so whatever you use, the other SDK is likely to raise a warning. */
  1396. ret = InterlockedIncrement((volatile long *)addr);
  1397. #elif defined(__GNUC__) \
  1398. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  1399. ret = __sync_add_and_fetch(addr, 1);
  1400. #else
  1401. ret = (++(*addr));
  1402. #endif
  1403. return ret;
  1404. }
  1405. static int
  1406. mg_atomic_dec(volatile int *addr)
  1407. {
  1408. int ret;
  1409. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1410. /* Depending on the SDK, this function uses either
  1411. * (volatile unsigned int *) or (volatile LONG *),
  1412. * so whatever you use, the other SDK is likely to raise a warning. */
  1413. ret = InterlockedDecrement((volatile long *)addr);
  1414. #elif defined(__GNUC__) \
  1415. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  1416. ret = __sync_sub_and_fetch(addr, 1);
  1417. #else
  1418. ret = (--(*addr));
  1419. #endif
  1420. return ret;
  1421. }
  1422. #if !defined(NO_THREAD_NAME)
  1423. #if defined(_WIN32) && defined(_MSC_VER)
  1424. /* Set the thread name for debugging purposes in Visual Studio
  1425. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  1426. */
  1427. #pragma pack(push, 8)
  1428. typedef struct tagTHREADNAME_INFO {
  1429. DWORD dwType; /* Must be 0x1000. */
  1430. LPCSTR szName; /* Pointer to name (in user addr space). */
  1431. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  1432. DWORD dwFlags; /* Reserved for future use, must be zero. */
  1433. } THREADNAME_INFO;
  1434. #pragma pack(pop)
  1435. #elif defined(__linux__)
  1436. #include <sys/prctl.h>
  1437. #include <sys/sendfile.h>
  1438. #include <sys/eventfd.h>
  1439. #if defined(ALTERNATIVE_QUEUE)
  1440. static void *
  1441. event_create(void)
  1442. {
  1443. int ret = eventfd(0, EFD_CLOEXEC);
  1444. if (ret == -1) {
  1445. /* Linux uses -1 on error, Windows NULL. */
  1446. /* However, Linux does not return 0 on success either. */
  1447. return 0;
  1448. }
  1449. return (void *)ret;
  1450. }
  1451. static int
  1452. event_wait(void *eventhdl)
  1453. {
  1454. uint64_t u;
  1455. int s = (int)read((int)eventhdl, &u, sizeof(u));
  1456. if (s != sizeof(uint64_t)) {
  1457. /* error */
  1458. return 0;
  1459. }
  1460. (void)u; /* the value is not required */
  1461. return 1;
  1462. }
  1463. static int
  1464. event_signal(void *eventhdl)
  1465. {
  1466. uint64_t u = 1;
  1467. int s = (int)write((int)eventhdl, &u, sizeof(u));
  1468. if (s != sizeof(uint64_t)) {
  1469. /* error */
  1470. return 0;
  1471. }
  1472. return 1;
  1473. }
  1474. static void
  1475. event_destroy(void *eventhdl)
  1476. {
  1477. close((int)eventhdl);
  1478. }
  1479. #endif
  1480. #endif
  1481. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  1482. struct posix_event {
  1483. pthread_mutex_t mutex;
  1484. pthread_cond_t cond;
  1485. };
  1486. static void *
  1487. event_create(void)
  1488. {
  1489. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  1490. if (ret == 0) {
  1491. /* out of memory */
  1492. return 0;
  1493. }
  1494. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  1495. /* pthread mutex not available */
  1496. mg_free(ret);
  1497. return 0;
  1498. }
  1499. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  1500. /* pthread cond not available */
  1501. pthread_mutex_destroy(&(ret->mutex));
  1502. mg_free(ret);
  1503. return 0;
  1504. }
  1505. return (void *)ret;
  1506. }
  1507. static int
  1508. event_wait(void *eventhdl)
  1509. {
  1510. struct posix_event *ev = (struct posix_event *)eventhdl;
  1511. pthread_mutex_lock(&(ev->mutex));
  1512. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  1513. pthread_mutex_unlock(&(ev->mutex));
  1514. return 1;
  1515. }
  1516. static int
  1517. event_signal(void *eventhdl)
  1518. {
  1519. struct posix_event *ev = (struct posix_event *)eventhdl;
  1520. pthread_mutex_lock(&(ev->mutex));
  1521. pthread_cond_signal(&(ev->cond));
  1522. pthread_mutex_unlock(&(ev->mutex));
  1523. return 1;
  1524. }
  1525. static void
  1526. event_destroy(void *eventhdl)
  1527. {
  1528. struct posix_event *ev = (struct posix_event *)eventhdl;
  1529. pthread_cond_destroy(&(ev->cond));
  1530. pthread_mutex_destroy(&(ev->mutex));
  1531. mg_free(ev);
  1532. }
  1533. #endif
  1534. static void
  1535. mg_set_thread_name(const char *name)
  1536. {
  1537. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  1538. mg_snprintf(
  1539. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  1540. #if defined(_WIN32)
  1541. #if defined(_MSC_VER)
  1542. /* Windows and Visual Studio Compiler */
  1543. __try
  1544. {
  1545. THREADNAME_INFO info;
  1546. info.dwType = 0x1000;
  1547. info.szName = threadName;
  1548. info.dwThreadID = ~0U;
  1549. info.dwFlags = 0;
  1550. RaiseException(0x406D1388,
  1551. 0,
  1552. sizeof(info) / sizeof(ULONG_PTR),
  1553. (ULONG_PTR *)&info);
  1554. }
  1555. __except(EXCEPTION_EXECUTE_HANDLER)
  1556. {
  1557. }
  1558. #elif defined(__MINGW32__)
  1559. /* No option known to set thread name for MinGW */
  1560. #endif
  1561. #elif defined(__GLIBC__) \
  1562. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  1563. /* pthread_setname_np first appeared in glibc in version 2.12*/
  1564. (void)pthread_setname_np(pthread_self(), threadName);
  1565. #elif defined(__linux__)
  1566. /* on linux we can use the old prctl function */
  1567. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  1568. #endif
  1569. }
  1570. #else /* !defined(NO_THREAD_NAME) */
  1571. void
  1572. mg_set_thread_name(const char *threadName)
  1573. {
  1574. }
  1575. #endif
  1576. #if defined(MG_LEGACY_INTERFACE)
  1577. const char **
  1578. mg_get_valid_option_names(void)
  1579. {
  1580. /* This function is deprecated. Use mg_get_valid_options instead. */
  1581. static const char *
  1582. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  1583. int i;
  1584. for (i = 0; config_options[i].name != NULL; i++) {
  1585. data[i * 2] = config_options[i].name;
  1586. data[i * 2 + 1] = config_options[i].default_value;
  1587. }
  1588. return data;
  1589. }
  1590. #endif
  1591. const struct mg_option *
  1592. mg_get_valid_options(void)
  1593. {
  1594. return config_options;
  1595. }
  1596. static int
  1597. is_file_in_memory(const struct mg_connection *conn,
  1598. const char *path,
  1599. struct file *filep)
  1600. {
  1601. size_t size = 0;
  1602. if (!conn || !filep) {
  1603. return 0;
  1604. }
  1605. if (conn->ctx->callbacks.open_file) {
  1606. filep->membuf = conn->ctx->callbacks.open_file(conn, path, &size);
  1607. if (filep->membuf != NULL) {
  1608. /* NOTE: override filep->size only on success. Otherwise, it might
  1609. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  1610. filep->size = size;
  1611. }
  1612. }
  1613. return filep->membuf != NULL;
  1614. }
  1615. static int
  1616. is_file_opened(const struct file *filep)
  1617. {
  1618. if (!filep) {
  1619. return 0;
  1620. }
  1621. return filep->membuf != NULL || filep->fp != NULL;
  1622. }
  1623. /* mg_fopen will open a file either in memory or on the disk.
  1624. * The input parameter path is a string in UTF-8 encoding.
  1625. * The input parameter mode is the same as for fopen.
  1626. * Either fp or membuf will be set in the output struct filep.
  1627. * The function returns 1 on success, 0 on error. */
  1628. static int
  1629. mg_fopen(const struct mg_connection *conn,
  1630. const char *path,
  1631. const char *mode,
  1632. struct file *filep)
  1633. {
  1634. struct stat st;
  1635. if (!filep) {
  1636. return 0;
  1637. }
  1638. /* TODO (high): mg_fopen should only open a file, while mg_stat should
  1639. * only get the file status. They should not work on different members of
  1640. * the same structure (bad cohesion). */
  1641. memset(filep, 0, sizeof(*filep));
  1642. if (stat(path, &st) == 0) {
  1643. filep->size = (uint64_t)(st.st_size);
  1644. }
  1645. if (!is_file_in_memory(conn, path, filep)) {
  1646. #ifdef _WIN32
  1647. wchar_t wbuf[PATH_MAX], wmode[20];
  1648. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  1649. MultiByteToWideChar(CP_UTF8, 0, mode, -1, wmode, ARRAY_SIZE(wmode));
  1650. filep->fp = _wfopen(wbuf, wmode);
  1651. #else
  1652. /* Linux et al already use unicode. No need to convert. */
  1653. filep->fp = fopen(path, mode);
  1654. #endif
  1655. }
  1656. return is_file_opened(filep);
  1657. }
  1658. static void
  1659. mg_fclose(struct file *filep)
  1660. {
  1661. if (filep != NULL && filep->fp != NULL) {
  1662. fclose(filep->fp);
  1663. }
  1664. }
  1665. static void
  1666. mg_strlcpy(register char *dst, register const char *src, size_t n)
  1667. {
  1668. for (; *src != '\0' && n > 1; n--) {
  1669. *dst++ = *src++;
  1670. }
  1671. *dst = '\0';
  1672. }
  1673. static int
  1674. lowercase(const char *s)
  1675. {
  1676. return tolower(*(const unsigned char *)s);
  1677. }
  1678. int
  1679. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  1680. {
  1681. int diff = 0;
  1682. if (len > 0) {
  1683. do {
  1684. diff = lowercase(s1++) - lowercase(s2++);
  1685. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  1686. }
  1687. return diff;
  1688. }
  1689. int
  1690. mg_strcasecmp(const char *s1, const char *s2)
  1691. {
  1692. int diff;
  1693. do {
  1694. diff = lowercase(s1++) - lowercase(s2++);
  1695. } while (diff == 0 && s1[-1] != '\0');
  1696. return diff;
  1697. }
  1698. static char *
  1699. mg_strndup(const char *ptr, size_t len)
  1700. {
  1701. char *p;
  1702. if ((p = (char *)mg_malloc(len + 1)) != NULL) {
  1703. mg_strlcpy(p, ptr, len + 1);
  1704. }
  1705. return p;
  1706. }
  1707. static char *
  1708. mg_strdup(const char *str)
  1709. {
  1710. return mg_strndup(str, strlen(str));
  1711. }
  1712. static const char *
  1713. mg_strcasestr(const char *big_str, const char *small_str)
  1714. {
  1715. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  1716. if (big_len >= small_len) {
  1717. for (i = 0; i <= (big_len - small_len); i++) {
  1718. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  1719. return big_str + i;
  1720. }
  1721. }
  1722. }
  1723. return NULL;
  1724. }
  1725. /* Return null terminated string of given maximum length.
  1726. * Report errors if length is exceeded. */
  1727. static void
  1728. mg_vsnprintf(const struct mg_connection *conn,
  1729. int *truncated,
  1730. char *buf,
  1731. size_t buflen,
  1732. const char *fmt,
  1733. va_list ap)
  1734. {
  1735. int n, ok;
  1736. if (buflen == 0) {
  1737. return;
  1738. }
  1739. #ifdef __clang__
  1740. #pragma clang diagnostic push
  1741. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  1742. /* Using fmt as a non-literal is intended here, since it is mostly called
  1743. * indirectly by mg_snprintf */
  1744. #endif
  1745. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  1746. ok = (n >= 0) && ((size_t)n < buflen);
  1747. #ifdef __clang__
  1748. #pragma clang diagnostic pop
  1749. #endif
  1750. if (ok) {
  1751. if (truncated) {
  1752. *truncated = 0;
  1753. }
  1754. } else {
  1755. if (truncated) {
  1756. *truncated = 1;
  1757. }
  1758. mg_cry(conn,
  1759. "truncating vsnprintf buffer: [%.*s]",
  1760. (int)((buflen > 200) ? 200 : (buflen - 1)),
  1761. buf);
  1762. n = (int)buflen - 1;
  1763. }
  1764. buf[n] = '\0';
  1765. }
  1766. static void
  1767. mg_snprintf(const struct mg_connection *conn,
  1768. int *truncated,
  1769. char *buf,
  1770. size_t buflen,
  1771. const char *fmt,
  1772. ...)
  1773. {
  1774. va_list ap;
  1775. va_start(ap, fmt);
  1776. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  1777. va_end(ap);
  1778. }
  1779. static int
  1780. get_option_index(const char *name)
  1781. {
  1782. int i;
  1783. for (i = 0; config_options[i].name != NULL; i++) {
  1784. if (strcmp(config_options[i].name, name) == 0) {
  1785. return i;
  1786. }
  1787. }
  1788. return -1;
  1789. }
  1790. const char *
  1791. mg_get_option(const struct mg_context *ctx, const char *name)
  1792. {
  1793. int i;
  1794. if ((i = get_option_index(name)) == -1) {
  1795. return NULL;
  1796. } else if (!ctx || ctx->config[i] == NULL) {
  1797. return "";
  1798. } else {
  1799. return ctx->config[i];
  1800. }
  1801. }
  1802. struct mg_context *
  1803. mg_get_context(const struct mg_connection *conn)
  1804. {
  1805. return (conn == NULL) ? (struct mg_context *)NULL : (conn->ctx);
  1806. }
  1807. void *
  1808. mg_get_user_data(const struct mg_context *ctx)
  1809. {
  1810. return (ctx == NULL) ? NULL : ctx->user_data;
  1811. }
  1812. void
  1813. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  1814. {
  1815. if (conn != NULL) {
  1816. conn->request_info.conn_data = data;
  1817. }
  1818. }
  1819. void *
  1820. mg_get_user_connection_data(const struct mg_connection *conn)
  1821. {
  1822. if (conn != NULL) {
  1823. return conn->request_info.conn_data;
  1824. }
  1825. return NULL;
  1826. }
  1827. size_t
  1828. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  1829. {
  1830. size_t i;
  1831. if (!ctx) {
  1832. return 0;
  1833. }
  1834. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  1835. ssl[i] = ctx->listening_sockets[i].is_ssl;
  1836. ports[i] =
  1837. #if defined(USE_IPV6)
  1838. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  1839. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  1840. :
  1841. #endif
  1842. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  1843. }
  1844. return i;
  1845. }
  1846. int
  1847. mg_get_server_ports(const struct mg_context *ctx,
  1848. int size,
  1849. struct mg_server_ports *ports)
  1850. {
  1851. int i, cnt = 0;
  1852. if (size <= 0) {
  1853. return -1;
  1854. }
  1855. memset(ports, 0, sizeof(*ports) * (size_t)size);
  1856. if (!ctx) {
  1857. return -1;
  1858. }
  1859. if (!ctx->listening_sockets) {
  1860. return -1;
  1861. }
  1862. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  1863. ports[cnt].port =
  1864. #if defined(USE_IPV6)
  1865. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  1866. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  1867. :
  1868. #endif
  1869. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  1870. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  1871. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  1872. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  1873. /* IPv4 */
  1874. ports[cnt].protocol = 1;
  1875. cnt++;
  1876. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  1877. /* IPv6 */
  1878. ports[cnt].protocol = 3;
  1879. cnt++;
  1880. }
  1881. }
  1882. return cnt;
  1883. }
  1884. static void
  1885. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  1886. {
  1887. buf[0] = '\0';
  1888. if (!usa) {
  1889. return;
  1890. }
  1891. if (usa->sa.sa_family == AF_INET) {
  1892. getnameinfo(&usa->sa,
  1893. sizeof(usa->sin),
  1894. buf,
  1895. (unsigned)len,
  1896. NULL,
  1897. 0,
  1898. NI_NUMERICHOST);
  1899. }
  1900. #if defined(USE_IPV6)
  1901. else if (usa->sa.sa_family == AF_INET6) {
  1902. getnameinfo(&usa->sa,
  1903. sizeof(usa->sin6),
  1904. buf,
  1905. (unsigned)len,
  1906. NULL,
  1907. 0,
  1908. NI_NUMERICHOST);
  1909. }
  1910. #endif
  1911. }
  1912. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  1913. * included in all responses other than 100, 101, 5xx. */
  1914. static void
  1915. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  1916. {
  1917. struct tm *tm;
  1918. tm = ((t != NULL) ? gmtime(t) : NULL);
  1919. if (tm != NULL) {
  1920. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  1921. } else {
  1922. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  1923. buf[buf_len - 1] = '\0';
  1924. }
  1925. }
  1926. /* difftime for struct timespec. Return value is in seconds. */
  1927. static double
  1928. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  1929. {
  1930. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  1931. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  1932. }
  1933. /* Print error message to the opened error log stream. */
  1934. void
  1935. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  1936. {
  1937. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  1938. va_list ap;
  1939. struct file fi;
  1940. time_t timestamp;
  1941. va_start(ap, fmt);
  1942. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  1943. va_end(ap);
  1944. buf[sizeof(buf) - 1] = 0;
  1945. if (!conn) {
  1946. puts(buf);
  1947. return;
  1948. }
  1949. /* Do not lock when getting the callback value, here and below.
  1950. * I suppose this is fine, since function cannot disappear in the
  1951. * same way string option can. */
  1952. if ((conn->ctx->callbacks.log_message == NULL)
  1953. || (conn->ctx->callbacks.log_message(conn, buf) == 0)) {
  1954. if (conn->ctx->config[ERROR_LOG_FILE] != NULL) {
  1955. if (mg_fopen(conn, conn->ctx->config[ERROR_LOG_FILE], "a+", &fi)
  1956. == 0) {
  1957. fi.fp = NULL;
  1958. }
  1959. } else {
  1960. fi.fp = NULL;
  1961. }
  1962. if (fi.fp != NULL) {
  1963. flockfile(fi.fp);
  1964. timestamp = time(NULL);
  1965. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  1966. fprintf(fi.fp,
  1967. "[%010lu] [error] [client %s] ",
  1968. (unsigned long)timestamp,
  1969. src_addr);
  1970. if (conn->request_info.request_method != NULL) {
  1971. fprintf(fi.fp,
  1972. "%s %s: ",
  1973. conn->request_info.request_method,
  1974. conn->request_info.request_uri);
  1975. }
  1976. fprintf(fi.fp, "%s", buf);
  1977. fputc('\n', fi.fp);
  1978. fflush(fi.fp);
  1979. funlockfile(fi.fp);
  1980. mg_fclose(&fi);
  1981. }
  1982. }
  1983. }
  1984. /* Return fake connection structure. Used for logging, if connection
  1985. * is not applicable at the moment of logging. */
  1986. static struct mg_connection *
  1987. fc(struct mg_context *ctx)
  1988. {
  1989. static struct mg_connection fake_connection;
  1990. fake_connection.ctx = ctx;
  1991. return &fake_connection;
  1992. }
  1993. const char *
  1994. mg_version(void)
  1995. {
  1996. return CIVETWEB_VERSION;
  1997. }
  1998. const struct mg_request_info *
  1999. mg_get_request_info(const struct mg_connection *conn)
  2000. {
  2001. if (!conn) {
  2002. return NULL;
  2003. }
  2004. return &conn->request_info;
  2005. }
  2006. /* Skip the characters until one of the delimiters characters found.
  2007. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  2008. * Advance pointer to buffer to the next word. Return found 0-terminated word.
  2009. * Delimiters can be quoted with quotechar. */
  2010. static char *
  2011. skip_quoted(char **buf,
  2012. const char *delimiters,
  2013. const char *whitespace,
  2014. char quotechar)
  2015. {
  2016. char *p, *begin_word, *end_word, *end_whitespace;
  2017. begin_word = *buf;
  2018. end_word = begin_word + strcspn(begin_word, delimiters);
  2019. /* Check for quotechar */
  2020. if (end_word > begin_word) {
  2021. p = end_word - 1;
  2022. while (*p == quotechar) {
  2023. /* While the delimiter is quoted, look for the next delimiter. */
  2024. /* This happens, e.g., in calls from parse_auth_header,
  2025. * if the user name contains a " character. */
  2026. /* If there is anything beyond end_word, copy it. */
  2027. if (*end_word != '\0') {
  2028. size_t end_off = strcspn(end_word + 1, delimiters);
  2029. memmove(p, end_word, end_off + 1);
  2030. p += end_off; /* p must correspond to end_word - 1 */
  2031. end_word += end_off + 1;
  2032. } else {
  2033. *p = '\0';
  2034. break;
  2035. }
  2036. }
  2037. for (p++; p < end_word; p++) {
  2038. *p = '\0';
  2039. }
  2040. }
  2041. if (*end_word == '\0') {
  2042. *buf = end_word;
  2043. } else {
  2044. end_whitespace =
  2045. end_word + ((unsigned int)strspn(end_word + 1, whitespace) + 1u);
  2046. for (p = end_word; p < end_whitespace; p++) {
  2047. *p = '\0';
  2048. }
  2049. *buf = end_whitespace;
  2050. }
  2051. return begin_word;
  2052. }
  2053. /* Simplified version of skip_quoted without quote char
  2054. * and whitespace == delimiters */
  2055. static char *
  2056. skip(char **buf, const char *delimiters)
  2057. {
  2058. return skip_quoted(buf, delimiters, delimiters, 0);
  2059. }
  2060. /* Return HTTP header value, or NULL if not found. */
  2061. static const char *
  2062. get_header(const struct mg_request_info *ri, const char *name)
  2063. {
  2064. int i;
  2065. if (ri) {
  2066. for (i = 0; i < ri->num_headers; i++) {
  2067. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  2068. return ri->http_headers[i].value;
  2069. }
  2070. }
  2071. }
  2072. return NULL;
  2073. }
  2074. const char *
  2075. mg_get_header(const struct mg_connection *conn, const char *name)
  2076. {
  2077. if (!conn) {
  2078. return NULL;
  2079. }
  2080. return get_header(&conn->request_info, name);
  2081. }
  2082. /* A helper function for traversing a comma separated list of values.
  2083. * It returns a list pointer shifted to the next value, or NULL if the end
  2084. * of the list found.
  2085. * Value is stored in val vector. If value has form "x=y", then eq_val
  2086. * vector is initialized to point to the "y" part, and val vector length
  2087. * is adjusted to point only to "x". */
  2088. static const char *
  2089. next_option(const char *list, struct vec *val, struct vec *eq_val)
  2090. {
  2091. int end;
  2092. reparse:
  2093. if (val == NULL || list == NULL || *list == '\0') {
  2094. /* End of the list */
  2095. list = NULL;
  2096. } else {
  2097. /* Skip over leading LWS */
  2098. while (*list == ' ' || *list == '\t')
  2099. list++;
  2100. val->ptr = list;
  2101. if ((list = strchr(val->ptr, ',')) != NULL) {
  2102. /* Comma found. Store length and shift the list ptr */
  2103. val->len = ((size_t)(list - val->ptr));
  2104. list++;
  2105. } else {
  2106. /* This value is the last one */
  2107. list = val->ptr + strlen(val->ptr);
  2108. val->len = ((size_t)(list - val->ptr));
  2109. }
  2110. /* Adjust length for trailing LWS */
  2111. end = (int)val->len - 1;
  2112. while (end >= 0 && (val->ptr[end] == ' ' || val->ptr[end] == '\t'))
  2113. end--;
  2114. val->len = (size_t)(end + 1);
  2115. if (val->len == 0) {
  2116. /* Ignore any empty entries. */
  2117. goto reparse;
  2118. }
  2119. if (eq_val != NULL) {
  2120. /* Value has form "x=y", adjust pointers and lengths
  2121. * so that val points to "x", and eq_val points to "y". */
  2122. eq_val->len = 0;
  2123. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  2124. if (eq_val->ptr != NULL) {
  2125. eq_val->ptr++; /* Skip over '=' character */
  2126. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  2127. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  2128. }
  2129. }
  2130. }
  2131. return list;
  2132. }
  2133. /* A helper function for checking if a comma separated list of values contains
  2134. * the given option (case insensitvely).
  2135. * 'header' can be NULL, in which case false is returned. */
  2136. static int
  2137. header_has_option(const char *header, const char *option)
  2138. {
  2139. struct vec opt_vec;
  2140. struct vec eq_vec;
  2141. assert(option != NULL);
  2142. assert(option[0] != '\0');
  2143. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  2144. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  2145. return 1;
  2146. }
  2147. return 0;
  2148. }
  2149. /* Perform case-insensitive match of string against pattern */
  2150. static int
  2151. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  2152. {
  2153. const char *or_str;
  2154. size_t i;
  2155. int j, len, res;
  2156. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  2157. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  2158. return (res > 0) ? res : match_prefix(or_str + 1,
  2159. (size_t)((pattern + pattern_len)
  2160. - (or_str + 1)),
  2161. str);
  2162. }
  2163. for (i = 0, j = 0; i < pattern_len; i++, j++) {
  2164. if (pattern[i] == '?' && str[j] != '\0') {
  2165. continue;
  2166. } else if (pattern[i] == '$') {
  2167. return (str[j] == '\0') ? j : -1;
  2168. } else if (pattern[i] == '*') {
  2169. i++;
  2170. if (pattern[i] == '*') {
  2171. i++;
  2172. len = (int)strlen(str + j);
  2173. } else {
  2174. len = (int)strcspn(str + j, "/");
  2175. }
  2176. if (i == pattern_len) {
  2177. return j + len;
  2178. }
  2179. do {
  2180. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  2181. } while (res == -1 && len-- > 0);
  2182. return (res == -1) ? -1 : j + res + len;
  2183. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  2184. return -1;
  2185. }
  2186. }
  2187. return j;
  2188. }
  2189. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  2190. * This function must tolerate situations when connection info is not
  2191. * set up, for example if request parsing failed. */
  2192. static int
  2193. should_keep_alive(const struct mg_connection *conn)
  2194. {
  2195. if (conn != NULL) {
  2196. const char *http_version = conn->request_info.http_version;
  2197. const char *header = mg_get_header(conn, "Connection");
  2198. if (conn->must_close || conn->internal_error || conn->status_code == 401
  2199. || mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0
  2200. || (header != NULL && !header_has_option(header, "keep-alive"))
  2201. || (header == NULL && http_version
  2202. && 0 != strcmp(http_version, "1.1"))) {
  2203. return 0;
  2204. }
  2205. return 1;
  2206. }
  2207. return 0;
  2208. }
  2209. static int
  2210. should_decode_url(const struct mg_connection *conn)
  2211. {
  2212. if (!conn || !conn->ctx) {
  2213. return 0;
  2214. }
  2215. return (mg_strcasecmp(conn->ctx->config[DECODE_URL], "yes") == 0);
  2216. }
  2217. static const char *
  2218. suggest_connection_header(const struct mg_connection *conn)
  2219. {
  2220. return should_keep_alive(conn) ? "keep-alive" : "close";
  2221. }
  2222. static int
  2223. send_no_cache_header(struct mg_connection *conn)
  2224. {
  2225. /* Send all current and obsolete cache opt-out directives. */
  2226. return mg_printf(conn,
  2227. "Cache-Control: no-cache, no-store, "
  2228. "must-revalidate, private, max-age=0\r\n"
  2229. "Pragma: no-cache\r\n"
  2230. "Expires: 0\r\n");
  2231. }
  2232. static int
  2233. send_static_cache_header(struct mg_connection *conn)
  2234. {
  2235. #if !defined(NO_CACHING)
  2236. /* Read the server config to check how long a file may be cached.
  2237. * The configuration is in seconds. */
  2238. int max_age = atoi(conn->ctx->config[STATIC_FILE_MAX_AGE]);
  2239. if (max_age <= 0) {
  2240. /* 0 means "do not cache". All values <0 are reserved
  2241. * and may be used differently in the future. */
  2242. /* If a file should not be cached, do not only send
  2243. * max-age=0, but also pragmas and Expires headers. */
  2244. return send_no_cache_header(conn);
  2245. }
  2246. /* Use "Cache-Control: max-age" instead of "Expires" header.
  2247. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  2248. /* See also https://www.mnot.net/cache_docs/ */
  2249. /* According to RFC 2616, Section 14.21, caching times should not exceed
  2250. * one year. A year with 365 days corresponds to 31536000 seconds, a leap
  2251. * year to 31622400 seconds. For the moment, we just send whatever has
  2252. * been configured, still the behavior for >1 year should be considered
  2253. * as undefined. */
  2254. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  2255. #else /* NO_CACHING */
  2256. return send_no_cache_header(conn);
  2257. #endif /* !NO_CACHING */
  2258. }
  2259. static void handle_file_based_request(struct mg_connection *conn,
  2260. const char *path,
  2261. struct file *filep);
  2262. static int
  2263. mg_stat(struct mg_connection *conn, const char *path, struct file *filep);
  2264. const char *
  2265. mg_get_response_code_text(struct mg_connection *conn, int response_code)
  2266. {
  2267. /* See IANA HTTP status code assignment:
  2268. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  2269. */
  2270. switch (response_code) {
  2271. /* RFC2616 Section 10.1 - Informational 1xx */
  2272. case 100:
  2273. return "Continue"; /* RFC2616 Section 10.1.1 */
  2274. case 101:
  2275. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  2276. case 102:
  2277. return "Processing"; /* RFC2518 Section 10.1 */
  2278. /* RFC2616 Section 10.2 - Successful 2xx */
  2279. case 200:
  2280. return "OK"; /* RFC2616 Section 10.2.1 */
  2281. case 201:
  2282. return "Created"; /* RFC2616 Section 10.2.2 */
  2283. case 202:
  2284. return "Accepted"; /* RFC2616 Section 10.2.3 */
  2285. case 203:
  2286. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  2287. case 204:
  2288. return "No Content"; /* RFC2616 Section 10.2.5 */
  2289. case 205:
  2290. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  2291. case 206:
  2292. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  2293. case 207:
  2294. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1 */
  2295. case 208:
  2296. return "Already Reported"; /* RFC5842 Section 7.1 */
  2297. case 226:
  2298. return "IM used"; /* RFC3229 Section 10.4.1 */
  2299. /* RFC2616 Section 10.3 - Redirection 3xx */
  2300. case 300:
  2301. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  2302. case 301:
  2303. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  2304. case 302:
  2305. return "Found"; /* RFC2616 Section 10.3.3 */
  2306. case 303:
  2307. return "See Other"; /* RFC2616 Section 10.3.4 */
  2308. case 304:
  2309. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  2310. case 305:
  2311. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  2312. case 307:
  2313. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  2314. case 308:
  2315. return "Permanent Redirect"; /* RFC7238 Section 3 */
  2316. /* RFC2616 Section 10.4 - Client Error 4xx */
  2317. case 400:
  2318. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  2319. case 401:
  2320. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  2321. case 402:
  2322. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  2323. case 403:
  2324. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  2325. case 404:
  2326. return "Not Found"; /* RFC2616 Section 10.4.5 */
  2327. case 405:
  2328. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  2329. case 406:
  2330. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  2331. case 407:
  2332. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  2333. case 408:
  2334. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  2335. case 409:
  2336. return "Conflict"; /* RFC2616 Section 10.4.10 */
  2337. case 410:
  2338. return "Gone"; /* RFC2616 Section 10.4.11 */
  2339. case 411:
  2340. return "Length Required"; /* RFC2616 Section 10.4.12 */
  2341. case 412:
  2342. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  2343. case 413:
  2344. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  2345. case 414:
  2346. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  2347. case 415:
  2348. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  2349. case 416:
  2350. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17 */
  2351. case 417:
  2352. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  2353. case 421:
  2354. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  2355. case 422:
  2356. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  2357. * Section 11.2 */
  2358. case 423:
  2359. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  2360. case 424:
  2361. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  2362. * Section 11.4 */
  2363. case 426:
  2364. return "Upgrade Required"; /* RFC 2817 Section 4 */
  2365. case 428:
  2366. return "Precondition Required"; /* RFC 6585, Section 3 */
  2367. case 429:
  2368. return "Too Many Requests"; /* RFC 6585, Section 4 */
  2369. case 431:
  2370. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  2371. case 451:
  2372. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  2373. * Section 3 */
  2374. /* RFC2616 Section 10.5 - Server Error 5xx */
  2375. case 500:
  2376. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  2377. case 501:
  2378. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  2379. case 502:
  2380. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  2381. case 503:
  2382. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  2383. case 504:
  2384. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  2385. case 505:
  2386. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  2387. case 506:
  2388. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  2389. case 507:
  2390. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  2391. * Section 11.5 */
  2392. case 508:
  2393. return "Loop Detected"; /* RFC5842 Section 7.1 */
  2394. case 510:
  2395. return "Not Extended"; /* RFC 2774, Section 7 */
  2396. case 511:
  2397. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  2398. /* Other status codes, not shown in the IANA HTTP status code assignment.
  2399. * E.g., "de facto" standards due to common use, ... */
  2400. case 418:
  2401. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  2402. case 419:
  2403. return "Authentication Timeout"; /* common use */
  2404. case 420:
  2405. return "Enhance Your Calm"; /* common use */
  2406. case 440:
  2407. return "Login Timeout"; /* common use */
  2408. case 509:
  2409. return "Bandwidth Limit Exceeded"; /* common use */
  2410. default:
  2411. /* This error code is unknown. This should not happen. */
  2412. if (conn) {
  2413. mg_cry(conn, "Unknown HTTP response code: %u", response_code);
  2414. }
  2415. /* Return at least a category according to RFC 2616 Section 10. */
  2416. if (response_code >= 100 && response_code < 200) {
  2417. /* Unknown informational status code */
  2418. return "Information";
  2419. }
  2420. if (response_code >= 200 && response_code < 300) {
  2421. /* Unknown success code */
  2422. return "Success";
  2423. }
  2424. if (response_code >= 300 && response_code < 400) {
  2425. /* Unknown redirection code */
  2426. return "Redirection";
  2427. }
  2428. if (response_code >= 400 && response_code < 500) {
  2429. /* Unknown request error code */
  2430. return "Client Error";
  2431. }
  2432. if (response_code >= 500 && response_code < 600) {
  2433. /* Unknown server error code */
  2434. return "Server Error";
  2435. }
  2436. /* Response code not even within reasonable range */
  2437. return "";
  2438. }
  2439. }
  2440. static void send_http_error(struct mg_connection *,
  2441. int,
  2442. PRINTF_FORMAT_STRING(const char *fmt),
  2443. ...) PRINTF_ARGS(3, 4);
  2444. static void
  2445. send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  2446. {
  2447. char buf[MG_BUF_LEN];
  2448. va_list ap;
  2449. int len, i, page_handler_found, scope, truncated, has_body;
  2450. char date[64];
  2451. time_t curtime = time(NULL);
  2452. const char *error_handler = NULL;
  2453. struct file error_page_file = STRUCT_FILE_INITIALIZER;
  2454. const char *error_page_file_ext, *tstr;
  2455. const char *status_text = mg_get_response_code_text(conn, status);
  2456. if (conn == NULL) {
  2457. return;
  2458. }
  2459. conn->status_code = status;
  2460. if (conn->in_error_handler || conn->ctx->callbacks.http_error == NULL
  2461. || conn->ctx->callbacks.http_error(conn, status)) {
  2462. if (!conn->in_error_handler) {
  2463. /* Send user defined error pages, if defined */
  2464. error_handler = conn->ctx->config[ERROR_PAGES];
  2465. error_page_file_ext = conn->ctx->config[INDEX_FILES];
  2466. page_handler_found = 0;
  2467. if (error_handler != NULL) {
  2468. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  2469. switch (scope) {
  2470. case 1: /* Handler for specific error, e.g. 404 error */
  2471. mg_snprintf(conn,
  2472. &truncated,
  2473. buf,
  2474. sizeof(buf) - 32,
  2475. "%serror%03u.",
  2476. error_handler,
  2477. status);
  2478. break;
  2479. case 2: /* Handler for error group, e.g., 5xx error handler
  2480. * for all server errors (500-599) */
  2481. mg_snprintf(conn,
  2482. &truncated,
  2483. buf,
  2484. sizeof(buf) - 32,
  2485. "%serror%01uxx.",
  2486. error_handler,
  2487. status / 100);
  2488. break;
  2489. default: /* Handler for all errors */
  2490. mg_snprintf(conn,
  2491. &truncated,
  2492. buf,
  2493. sizeof(buf) - 32,
  2494. "%serror.",
  2495. error_handler);
  2496. break;
  2497. }
  2498. /* String truncation in buf may only occur if error_handler
  2499. * is too long. This string is from the config, not from a
  2500. * client. */
  2501. (void)truncated;
  2502. len = (int)strlen(buf);
  2503. tstr = strchr(error_page_file_ext, '.');
  2504. while (tstr) {
  2505. for (i = 1; i < 32 && tstr[i] != 0 && tstr[i] != ',';
  2506. i++)
  2507. buf[len + i - 1] = tstr[i];
  2508. buf[len + i - 1] = 0;
  2509. if (mg_stat(conn, buf, &error_page_file)) {
  2510. page_handler_found = 1;
  2511. break;
  2512. }
  2513. tstr = strchr(tstr + i, '.');
  2514. }
  2515. }
  2516. }
  2517. if (page_handler_found) {
  2518. conn->in_error_handler = 1;
  2519. handle_file_based_request(conn, buf, &error_page_file);
  2520. conn->in_error_handler = 0;
  2521. return;
  2522. }
  2523. }
  2524. /* No custom error page. Send default error page. */
  2525. gmt_time_string(date, sizeof(date), &curtime);
  2526. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  2527. has_body = (status > 199 && status != 204 && status != 304);
  2528. conn->must_close = 1;
  2529. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  2530. send_no_cache_header(conn);
  2531. if (has_body) {
  2532. mg_printf(conn,
  2533. "%s",
  2534. "Content-Type: text/plain; charset=utf-8\r\n");
  2535. }
  2536. mg_printf(conn,
  2537. "Date: %s\r\n"
  2538. "Connection: close\r\n\r\n",
  2539. date);
  2540. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  2541. if (has_body) {
  2542. mg_printf(conn, "Error %d: %s\n", status, status_text);
  2543. if (fmt != NULL) {
  2544. va_start(ap, fmt);
  2545. mg_vsnprintf(conn, NULL, buf, sizeof(buf), fmt, ap);
  2546. va_end(ap);
  2547. mg_write(conn, buf, strlen(buf));
  2548. DEBUG_TRACE("Error %i - [%s]", status, buf);
  2549. }
  2550. } else {
  2551. /* No body allowed. Close the connection. */
  2552. DEBUG_TRACE("Error %i", status);
  2553. }
  2554. }
  2555. }
  2556. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  2557. /* Create substitutes for POSIX functions in Win32. */
  2558. #if defined(__MINGW32__)
  2559. /* Show no warning in case system functions are not used. */
  2560. #pragma GCC diagnostic push
  2561. #pragma GCC diagnostic ignored "-Wunused-function"
  2562. #endif
  2563. static int
  2564. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  2565. {
  2566. (void)unused;
  2567. *mutex = CreateMutex(NULL, FALSE, NULL);
  2568. return (*mutex == NULL) ? -1 : 0;
  2569. }
  2570. static int
  2571. pthread_mutex_destroy(pthread_mutex_t *mutex)
  2572. {
  2573. return (CloseHandle(*mutex) == 0) ? -1 : 0;
  2574. }
  2575. static int
  2576. pthread_mutex_lock(pthread_mutex_t *mutex)
  2577. {
  2578. return (WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0) ? 0 : -1;
  2579. }
  2580. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  2581. static int
  2582. pthread_mutex_trylock(pthread_mutex_t *mutex)
  2583. {
  2584. switch (WaitForSingleObject(*mutex, 0)) {
  2585. case WAIT_OBJECT_0:
  2586. return 0;
  2587. case WAIT_TIMEOUT:
  2588. return -2; /* EBUSY */
  2589. }
  2590. return -1;
  2591. }
  2592. #endif
  2593. static int
  2594. pthread_mutex_unlock(pthread_mutex_t *mutex)
  2595. {
  2596. return (ReleaseMutex(*mutex) == 0) ? -1 : 0;
  2597. }
  2598. #ifndef WIN_PTHREADS_TIME_H
  2599. static int
  2600. clock_gettime(clockid_t clk_id, struct timespec *tp)
  2601. {
  2602. FILETIME ft;
  2603. ULARGE_INTEGER li;
  2604. BOOL ok = FALSE;
  2605. double d;
  2606. static double perfcnt_per_sec = 0.0;
  2607. if (tp) {
  2608. memset(tp, 0, sizeof(*tp));
  2609. if (clk_id == CLOCK_REALTIME) {
  2610. GetSystemTimeAsFileTime(&ft);
  2611. li.LowPart = ft.dwLowDateTime;
  2612. li.HighPart = ft.dwHighDateTime;
  2613. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  2614. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  2615. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  2616. ok = TRUE;
  2617. } else if (clk_id == CLOCK_MONOTONIC) {
  2618. if (perfcnt_per_sec == 0.0) {
  2619. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  2620. perfcnt_per_sec = 1.0 / li.QuadPart;
  2621. }
  2622. if (perfcnt_per_sec != 0.0) {
  2623. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  2624. d = li.QuadPart * perfcnt_per_sec;
  2625. tp->tv_sec = (time_t)d;
  2626. d -= tp->tv_sec;
  2627. tp->tv_nsec = (long)(d * 1.0E9);
  2628. ok = TRUE;
  2629. }
  2630. }
  2631. }
  2632. return ok ? 0 : -1;
  2633. }
  2634. #endif
  2635. static int
  2636. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  2637. {
  2638. (void)unused;
  2639. InitializeCriticalSection(&cv->threadIdSec);
  2640. cv->waiting_thread = NULL;
  2641. return 0;
  2642. }
  2643. static int
  2644. pthread_cond_timedwait(pthread_cond_t *cv,
  2645. pthread_mutex_t *mutex,
  2646. const struct timespec *abstime)
  2647. {
  2648. struct mg_workerTLS **ptls,
  2649. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2650. int ok;
  2651. struct timespec tsnow;
  2652. int64_t nsnow, nswaitabs, nswaitrel;
  2653. DWORD mswaitrel;
  2654. EnterCriticalSection(&cv->threadIdSec);
  2655. /* Add this thread to cv's waiting list */
  2656. ptls = &cv->waiting_thread;
  2657. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  2658. ;
  2659. tls->next_waiting_thread = NULL;
  2660. *ptls = tls;
  2661. LeaveCriticalSection(&cv->threadIdSec);
  2662. if (abstime) {
  2663. clock_gettime(CLOCK_REALTIME, &tsnow);
  2664. nsnow = (((int64_t)tsnow.tv_sec) * 1000000000) + tsnow.tv_nsec;
  2665. nswaitabs =
  2666. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  2667. nswaitrel = nswaitabs - nsnow;
  2668. if (nswaitrel < 0) {
  2669. nswaitrel = 0;
  2670. }
  2671. mswaitrel = (DWORD)(nswaitrel / 1000000);
  2672. } else {
  2673. mswaitrel = INFINITE;
  2674. }
  2675. pthread_mutex_unlock(mutex);
  2676. ok = (WAIT_OBJECT_0
  2677. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  2678. if (!ok) {
  2679. ok = 1;
  2680. EnterCriticalSection(&cv->threadIdSec);
  2681. ptls = &cv->waiting_thread;
  2682. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  2683. if (*ptls == tls) {
  2684. *ptls = tls->next_waiting_thread;
  2685. ok = 0;
  2686. break;
  2687. }
  2688. }
  2689. LeaveCriticalSection(&cv->threadIdSec);
  2690. if (ok) {
  2691. WaitForSingleObject(tls->pthread_cond_helper_mutex, INFINITE);
  2692. }
  2693. }
  2694. /* This thread has been removed from cv's waiting list */
  2695. pthread_mutex_lock(mutex);
  2696. return ok ? 0 : -1;
  2697. }
  2698. static int
  2699. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  2700. {
  2701. return pthread_cond_timedwait(cv, mutex, NULL);
  2702. }
  2703. static int
  2704. pthread_cond_signal(pthread_cond_t *cv)
  2705. {
  2706. HANDLE wkup = NULL;
  2707. BOOL ok = FALSE;
  2708. EnterCriticalSection(&cv->threadIdSec);
  2709. if (cv->waiting_thread) {
  2710. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  2711. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  2712. ok = SetEvent(wkup);
  2713. assert(ok);
  2714. }
  2715. LeaveCriticalSection(&cv->threadIdSec);
  2716. return ok ? 0 : 1;
  2717. }
  2718. static int
  2719. pthread_cond_broadcast(pthread_cond_t *cv)
  2720. {
  2721. EnterCriticalSection(&cv->threadIdSec);
  2722. while (cv->waiting_thread) {
  2723. pthread_cond_signal(cv);
  2724. }
  2725. LeaveCriticalSection(&cv->threadIdSec);
  2726. return 0;
  2727. }
  2728. static int
  2729. pthread_cond_destroy(pthread_cond_t *cv)
  2730. {
  2731. EnterCriticalSection(&cv->threadIdSec);
  2732. assert(cv->waiting_thread == NULL);
  2733. LeaveCriticalSection(&cv->threadIdSec);
  2734. DeleteCriticalSection(&cv->threadIdSec);
  2735. return 0;
  2736. }
  2737. #ifdef ALTERNATIVE_QUEUE
  2738. static void *
  2739. event_create(void)
  2740. {
  2741. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  2742. }
  2743. static int
  2744. event_wait(void *eventhdl)
  2745. {
  2746. int res = WaitForSingleObject((HANDLE)eventhdl, INFINITE);
  2747. return (res == WAIT_OBJECT_0);
  2748. }
  2749. static int
  2750. event_signal(void *eventhdl)
  2751. {
  2752. return (int)SetEvent((HANDLE)eventhdl);
  2753. }
  2754. static void
  2755. event_destroy(void *eventhdl)
  2756. {
  2757. CloseHandle((HANDLE)eventhdl);
  2758. }
  2759. #endif
  2760. #if defined(__MINGW32__)
  2761. /* Enable unused function warning again */
  2762. #pragma GCC diagnostic pop
  2763. #endif
  2764. /* For Windows, change all slashes to backslashes in path names. */
  2765. static void
  2766. change_slashes_to_backslashes(char *path)
  2767. {
  2768. int i;
  2769. for (i = 0; path[i] != '\0'; i++) {
  2770. if (path[i] == '/') {
  2771. path[i] = '\\';
  2772. }
  2773. /* remove double backslash (check i > 0 to preserve UNC paths,
  2774. * like \\server\file.txt) */
  2775. if ((path[i] == '\\') && (i > 0)) {
  2776. while (path[i + 1] == '\\' || path[i + 1] == '/') {
  2777. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  2778. }
  2779. }
  2780. }
  2781. }
  2782. static int
  2783. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  2784. {
  2785. int diff;
  2786. do {
  2787. diff = tolower(*s1) - tolower(*s2);
  2788. s1++;
  2789. s2++;
  2790. } while (diff == 0 && s1[-1] != '\0');
  2791. return diff;
  2792. }
  2793. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  2794. * wbuf and wbuf_len is a target buffer and its length. */
  2795. static void
  2796. path_to_unicode(const struct mg_connection *conn,
  2797. const char *path,
  2798. wchar_t *wbuf,
  2799. size_t wbuf_len)
  2800. {
  2801. char buf[PATH_MAX], buf2[PATH_MAX];
  2802. wchar_t wbuf2[MAX_PATH + 1];
  2803. DWORD long_len, err;
  2804. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  2805. mg_strlcpy(buf, path, sizeof(buf));
  2806. change_slashes_to_backslashes(buf);
  2807. /* Convert to Unicode and back. If doubly-converted string does not
  2808. * match the original, something is fishy, reject. */
  2809. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  2810. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  2811. WideCharToMultiByte(
  2812. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  2813. if (strcmp(buf, buf2) != 0) {
  2814. wbuf[0] = L'\0';
  2815. }
  2816. /* Windows file systems are not case sensitive, but you can still use
  2817. * uppercase and lowercase letters (on all modern file systems).
  2818. * The server can check if the URI uses the same upper/lowercase
  2819. * letters an the file system, effectively making Windows servers
  2820. * case sensitive (like Linux servers are). It is still not possible
  2821. * to use two files with the same name in different cases on Windows
  2822. * (like /a and /A) - this would be possible in Linux.
  2823. * As a default, Windows is not case sensitive, but the case sensitive
  2824. * file name check can be activated by an additional configuration. */
  2825. if (conn) {
  2826. if (conn->ctx->config[CASE_SENSITIVE_FILES]
  2827. && !mg_strcasecmp(conn->ctx->config[CASE_SENSITIVE_FILES], "yes")) {
  2828. /* Use case sensitive compare function */
  2829. fcompare = wcscmp;
  2830. }
  2831. }
  2832. (void)conn; /* conn is currently unused */
  2833. #if !defined(_WIN32_WCE)
  2834. /* Only accept a full file path, not a Windows short (8.3) path. */
  2835. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  2836. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  2837. if (long_len == 0) {
  2838. err = GetLastError();
  2839. if (err == ERROR_FILE_NOT_FOUND) {
  2840. /* File does not exist. This is not always a problem here. */
  2841. return;
  2842. }
  2843. }
  2844. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  2845. /* Short name is used. */
  2846. wbuf[0] = L'\0';
  2847. }
  2848. #else
  2849. (void)long_len;
  2850. (void)wbuf2;
  2851. (void)err;
  2852. if (strchr(path, '~')) {
  2853. wbuf[0] = L'\0';
  2854. }
  2855. #endif
  2856. }
  2857. /* Windows happily opens files with some garbage at the end of file name.
  2858. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  2859. * "a.cgi", despite one would expect an error back.
  2860. * This function returns non-0 if path ends with some garbage. */
  2861. static int
  2862. path_cannot_disclose_cgi(const char *path)
  2863. {
  2864. static const char *allowed_last_characters = "_-";
  2865. int last = path[strlen(path) - 1];
  2866. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  2867. }
  2868. static int
  2869. mg_stat(struct mg_connection *conn, const char *path, struct file *filep)
  2870. {
  2871. wchar_t wbuf[PATH_MAX];
  2872. WIN32_FILE_ATTRIBUTE_DATA info;
  2873. time_t creation_time;
  2874. if (!filep) {
  2875. return 0;
  2876. }
  2877. memset(filep, 0, sizeof(*filep));
  2878. if (conn && is_file_in_memory(conn, path, filep)) {
  2879. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  2880. * memset */
  2881. filep->last_modified = time(NULL);
  2882. /* last_modified = now ... assumes the file may change during runtime,
  2883. * so every mg_fopen call may return different data */
  2884. /* last_modified = conn->ctx.start_time;
  2885. * May be used it the data does not change during runtime. This allows
  2886. * browser caching. Since we do not know, we have to assume the file
  2887. * in memory may change. */
  2888. return 1;
  2889. }
  2890. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2891. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  2892. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  2893. filep->last_modified =
  2894. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  2895. info.ftLastWriteTime.dwHighDateTime);
  2896. /* On Windows, the file creation time can be higher than the
  2897. * modification time, e.g. when a file is copied.
  2898. * Since the Last-Modified timestamp is used for caching
  2899. * it should be based on the most recent timestamp. */
  2900. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  2901. info.ftCreationTime.dwHighDateTime);
  2902. if (creation_time > filep->last_modified) {
  2903. filep->last_modified = creation_time;
  2904. }
  2905. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  2906. /* If file name is fishy, reset the file structure and return
  2907. * error.
  2908. * Note it is important to reset, not just return the error, cause
  2909. * functions like is_file_opened() check the struct. */
  2910. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  2911. memset(filep, 0, sizeof(*filep));
  2912. return 0;
  2913. }
  2914. return 1;
  2915. }
  2916. return 0;
  2917. }
  2918. static int
  2919. mg_remove(const struct mg_connection *conn, const char *path)
  2920. {
  2921. wchar_t wbuf[PATH_MAX];
  2922. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2923. return DeleteFileW(wbuf) ? 0 : -1;
  2924. }
  2925. static int
  2926. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  2927. {
  2928. wchar_t wbuf[PATH_MAX];
  2929. (void)mode;
  2930. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2931. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  2932. }
  2933. /* Create substitutes for POSIX functions in Win32. */
  2934. #if defined(__MINGW32__)
  2935. /* Show no warning in case system functions are not used. */
  2936. #pragma GCC diagnostic push
  2937. #pragma GCC diagnostic ignored "-Wunused-function"
  2938. #endif
  2939. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  2940. static DIR *
  2941. mg_opendir(const struct mg_connection *conn, const char *name)
  2942. {
  2943. DIR *dir = NULL;
  2944. wchar_t wpath[PATH_MAX];
  2945. DWORD attrs;
  2946. if (name == NULL) {
  2947. SetLastError(ERROR_BAD_ARGUMENTS);
  2948. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  2949. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  2950. } else {
  2951. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  2952. attrs = GetFileAttributesW(wpath);
  2953. if (attrs != 0xFFFFFFFF && ((attrs & FILE_ATTRIBUTE_DIRECTORY)
  2954. == FILE_ATTRIBUTE_DIRECTORY)) {
  2955. (void)wcscat(wpath, L"\\*");
  2956. dir->handle = FindFirstFileW(wpath, &dir->info);
  2957. dir->result.d_name[0] = '\0';
  2958. } else {
  2959. mg_free(dir);
  2960. dir = NULL;
  2961. }
  2962. }
  2963. return dir;
  2964. }
  2965. static int
  2966. mg_closedir(DIR *dir)
  2967. {
  2968. int result = 0;
  2969. if (dir != NULL) {
  2970. if (dir->handle != INVALID_HANDLE_VALUE)
  2971. result = FindClose(dir->handle) ? 0 : -1;
  2972. mg_free(dir);
  2973. } else {
  2974. result = -1;
  2975. SetLastError(ERROR_BAD_ARGUMENTS);
  2976. }
  2977. return result;
  2978. }
  2979. static struct dirent *
  2980. mg_readdir(DIR *dir)
  2981. {
  2982. struct dirent *result = 0;
  2983. if (dir) {
  2984. if (dir->handle != INVALID_HANDLE_VALUE) {
  2985. result = &dir->result;
  2986. (void)WideCharToMultiByte(CP_UTF8,
  2987. 0,
  2988. dir->info.cFileName,
  2989. -1,
  2990. result->d_name,
  2991. sizeof(result->d_name),
  2992. NULL,
  2993. NULL);
  2994. if (!FindNextFileW(dir->handle, &dir->info)) {
  2995. (void)FindClose(dir->handle);
  2996. dir->handle = INVALID_HANDLE_VALUE;
  2997. }
  2998. } else {
  2999. SetLastError(ERROR_FILE_NOT_FOUND);
  3000. }
  3001. } else {
  3002. SetLastError(ERROR_BAD_ARGUMENTS);
  3003. }
  3004. return result;
  3005. }
  3006. #ifndef HAVE_POLL
  3007. static int
  3008. poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  3009. {
  3010. struct timeval tv;
  3011. fd_set set;
  3012. unsigned int i;
  3013. int result;
  3014. SOCKET maxfd = 0;
  3015. memset(&tv, 0, sizeof(tv));
  3016. tv.tv_sec = milliseconds / 1000;
  3017. tv.tv_usec = (milliseconds % 1000) * 1000;
  3018. FD_ZERO(&set);
  3019. for (i = 0; i < n; i++) {
  3020. FD_SET((SOCKET)pfd[i].fd, &set);
  3021. pfd[i].revents = 0;
  3022. if (pfd[i].fd > maxfd) {
  3023. maxfd = pfd[i].fd;
  3024. }
  3025. }
  3026. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  3027. for (i = 0; i < n; i++) {
  3028. if (FD_ISSET(pfd[i].fd, &set)) {
  3029. pfd[i].revents = POLLIN;
  3030. }
  3031. }
  3032. }
  3033. return result;
  3034. }
  3035. #endif /* HAVE_POLL */
  3036. #if defined(__MINGW32__)
  3037. /* Enable unused function warning again */
  3038. #pragma GCC diagnostic pop
  3039. #endif
  3040. static void
  3041. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  3042. {
  3043. (void)conn; /* Unused. */
  3044. #if defined(_WIN32_WCE)
  3045. (void)sock;
  3046. #else
  3047. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  3048. #endif
  3049. }
  3050. int
  3051. mg_start_thread(mg_thread_func_t f, void *p)
  3052. {
  3053. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3054. /* Compile-time option to control stack size, e.g. -DUSE_STACK_SIZE=16384
  3055. */
  3056. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  3057. == ((uintptr_t)(-1L)))
  3058. ? -1
  3059. : 0);
  3060. #else
  3061. return (
  3062. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  3063. ? -1
  3064. : 0);
  3065. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3066. }
  3067. /* Start a thread storing the thread context. */
  3068. static int
  3069. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  3070. void *p,
  3071. pthread_t *threadidptr)
  3072. {
  3073. uintptr_t uip;
  3074. HANDLE threadhandle;
  3075. int result = -1;
  3076. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  3077. threadhandle = (HANDLE)uip;
  3078. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  3079. *threadidptr = threadhandle;
  3080. result = 0;
  3081. }
  3082. return result;
  3083. }
  3084. /* Wait for a thread to finish. */
  3085. static int
  3086. mg_join_thread(pthread_t threadid)
  3087. {
  3088. int result;
  3089. DWORD dwevent;
  3090. result = -1;
  3091. dwevent = WaitForSingleObject(threadid, INFINITE);
  3092. if (dwevent == WAIT_FAILED) {
  3093. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  3094. } else {
  3095. if (dwevent == WAIT_OBJECT_0) {
  3096. CloseHandle(threadid);
  3097. result = 0;
  3098. }
  3099. }
  3100. return result;
  3101. }
  3102. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  3103. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  3104. /* Create substitutes for POSIX functions in Win32. */
  3105. #if defined(__MINGW32__)
  3106. /* Show no warning in case system functions are not used. */
  3107. #pragma GCC diagnostic push
  3108. #pragma GCC diagnostic ignored "-Wunused-function"
  3109. #endif
  3110. static HANDLE
  3111. dlopen(const char *dll_name, int flags)
  3112. {
  3113. wchar_t wbuf[PATH_MAX];
  3114. (void)flags;
  3115. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  3116. return LoadLibraryW(wbuf);
  3117. }
  3118. static int
  3119. dlclose(void *handle)
  3120. {
  3121. int result;
  3122. if (FreeLibrary((HMODULE)handle) != 0) {
  3123. result = 0;
  3124. } else {
  3125. result = -1;
  3126. }
  3127. return result;
  3128. }
  3129. #if defined(__MINGW32__)
  3130. /* Enable unused function warning again */
  3131. #pragma GCC diagnostic pop
  3132. #endif
  3133. #endif
  3134. #if !defined(NO_CGI)
  3135. #define SIGKILL (0)
  3136. static int
  3137. kill(pid_t pid, int sig_num)
  3138. {
  3139. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  3140. (void)CloseHandle((HANDLE)pid);
  3141. return 0;
  3142. }
  3143. static void
  3144. trim_trailing_whitespaces(char *s)
  3145. {
  3146. char *e = s + strlen(s) - 1;
  3147. while (e > s && isspace(*(unsigned char *)e)) {
  3148. *e-- = '\0';
  3149. }
  3150. }
  3151. static pid_t
  3152. spawn_process(struct mg_connection *conn,
  3153. const char *prog,
  3154. char *envblk,
  3155. char *envp[],
  3156. int fdin[2],
  3157. int fdout[2],
  3158. int fderr[2],
  3159. const char *dir)
  3160. {
  3161. HANDLE me;
  3162. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  3163. cmdline[PATH_MAX], buf[PATH_MAX];
  3164. int truncated;
  3165. struct file file = STRUCT_FILE_INITIALIZER;
  3166. STARTUPINFOA si;
  3167. PROCESS_INFORMATION pi = {0};
  3168. (void)envp;
  3169. memset(&si, 0, sizeof(si));
  3170. si.cb = sizeof(si);
  3171. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  3172. si.wShowWindow = SW_HIDE;
  3173. me = GetCurrentProcess();
  3174. DuplicateHandle(me,
  3175. (HANDLE)_get_osfhandle(fdin[0]),
  3176. me,
  3177. &si.hStdInput,
  3178. 0,
  3179. TRUE,
  3180. DUPLICATE_SAME_ACCESS);
  3181. DuplicateHandle(me,
  3182. (HANDLE)_get_osfhandle(fdout[1]),
  3183. me,
  3184. &si.hStdOutput,
  3185. 0,
  3186. TRUE,
  3187. DUPLICATE_SAME_ACCESS);
  3188. DuplicateHandle(me,
  3189. (HANDLE)_get_osfhandle(fderr[1]),
  3190. me,
  3191. &si.hStdError,
  3192. 0,
  3193. TRUE,
  3194. DUPLICATE_SAME_ACCESS);
  3195. /* Mark handles that should not be inherited. See
  3196. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  3197. */
  3198. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  3199. HANDLE_FLAG_INHERIT,
  3200. 0);
  3201. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  3202. HANDLE_FLAG_INHERIT,
  3203. 0);
  3204. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  3205. HANDLE_FLAG_INHERIT,
  3206. 0);
  3207. /* If CGI file is a script, try to read the interpreter line */
  3208. interp = conn->ctx->config[CGI_INTERPRETER];
  3209. if (interp == NULL) {
  3210. buf[0] = buf[1] = '\0';
  3211. /* Read the first line of the script into the buffer */
  3212. mg_snprintf(
  3213. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  3214. if (truncated) {
  3215. pi.hProcess = (pid_t)-1;
  3216. goto spawn_cleanup;
  3217. }
  3218. if (mg_fopen(conn, cmdline, "r", &file)) {
  3219. p = (char *)file.membuf;
  3220. mg_fgets(buf, sizeof(buf), &file, &p);
  3221. mg_fclose(&file);
  3222. buf[sizeof(buf) - 1] = '\0';
  3223. }
  3224. if (buf[0] == '#' && buf[1] == '!') {
  3225. trim_trailing_whitespaces(buf + 2);
  3226. } else {
  3227. buf[2] = '\0';
  3228. }
  3229. interp = buf + 2;
  3230. }
  3231. if (interp[0] != '\0') {
  3232. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  3233. interp = full_interp;
  3234. }
  3235. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  3236. if (interp[0] != '\0') {
  3237. mg_snprintf(conn,
  3238. &truncated,
  3239. cmdline,
  3240. sizeof(cmdline),
  3241. "\"%s\" \"%s\\%s\"",
  3242. interp,
  3243. full_dir,
  3244. prog);
  3245. } else {
  3246. mg_snprintf(conn,
  3247. &truncated,
  3248. cmdline,
  3249. sizeof(cmdline),
  3250. "\"%s\\%s\"",
  3251. full_dir,
  3252. prog);
  3253. }
  3254. if (truncated) {
  3255. pi.hProcess = (pid_t)-1;
  3256. goto spawn_cleanup;
  3257. }
  3258. DEBUG_TRACE("Running [%s]", cmdline);
  3259. if (CreateProcessA(NULL,
  3260. cmdline,
  3261. NULL,
  3262. NULL,
  3263. TRUE,
  3264. CREATE_NEW_PROCESS_GROUP,
  3265. envblk,
  3266. NULL,
  3267. &si,
  3268. &pi) == 0) {
  3269. mg_cry(
  3270. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  3271. pi.hProcess = (pid_t)-1;
  3272. /* goto spawn_cleanup; */
  3273. }
  3274. spawn_cleanup:
  3275. (void)CloseHandle(si.hStdOutput);
  3276. (void)CloseHandle(si.hStdError);
  3277. (void)CloseHandle(si.hStdInput);
  3278. if (pi.hThread != NULL) {
  3279. (void)CloseHandle(pi.hThread);
  3280. }
  3281. return (pid_t)pi.hProcess;
  3282. }
  3283. #endif /* !NO_CGI */
  3284. static int
  3285. set_non_blocking_mode(SOCKET sock)
  3286. {
  3287. unsigned long on = 1;
  3288. return ioctlsocket(sock, (long)FIONBIO, &on);
  3289. }
  3290. #else
  3291. static int
  3292. mg_stat(struct mg_connection *conn, const char *path, struct file *filep)
  3293. {
  3294. struct stat st;
  3295. if (!filep) {
  3296. return 0;
  3297. }
  3298. memset(filep, 0, sizeof(*filep));
  3299. if (conn && is_file_in_memory(conn, path, filep)) {
  3300. return 1;
  3301. }
  3302. if (0 == stat(path, &st)) {
  3303. filep->size = (uint64_t)(st.st_size);
  3304. filep->last_modified = st.st_mtime;
  3305. filep->is_directory = S_ISDIR(st.st_mode);
  3306. return 1;
  3307. }
  3308. return 0;
  3309. }
  3310. static void
  3311. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  3312. {
  3313. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  3314. if (conn) {
  3315. mg_cry(conn,
  3316. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  3317. __func__,
  3318. strerror(ERRNO));
  3319. }
  3320. }
  3321. }
  3322. int
  3323. mg_start_thread(mg_thread_func_t func, void *param)
  3324. {
  3325. pthread_t thread_id;
  3326. pthread_attr_t attr;
  3327. int result;
  3328. (void)pthread_attr_init(&attr);
  3329. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  3330. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3331. /* Compile-time option to control stack size,
  3332. * e.g. -DUSE_STACK_SIZE=16384 */
  3333. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3334. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3335. result = pthread_create(&thread_id, &attr, func, param);
  3336. pthread_attr_destroy(&attr);
  3337. return result;
  3338. }
  3339. /* Start a thread storing the thread context. */
  3340. static int
  3341. mg_start_thread_with_id(mg_thread_func_t func,
  3342. void *param,
  3343. pthread_t *threadidptr)
  3344. {
  3345. pthread_t thread_id;
  3346. pthread_attr_t attr;
  3347. int result;
  3348. (void)pthread_attr_init(&attr);
  3349. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3350. /* Compile-time option to control stack size,
  3351. * e.g. -DUSE_STACK_SIZE=16384 */
  3352. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3353. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  3354. result = pthread_create(&thread_id, &attr, func, param);
  3355. pthread_attr_destroy(&attr);
  3356. if ((result == 0) && (threadidptr != NULL)) {
  3357. *threadidptr = thread_id;
  3358. }
  3359. return result;
  3360. }
  3361. /* Wait for a thread to finish. */
  3362. static int
  3363. mg_join_thread(pthread_t threadid)
  3364. {
  3365. int result;
  3366. result = pthread_join(threadid, NULL);
  3367. return result;
  3368. }
  3369. #ifndef NO_CGI
  3370. static pid_t
  3371. spawn_process(struct mg_connection *conn,
  3372. const char *prog,
  3373. char *envblk,
  3374. char *envp[],
  3375. int fdin[2],
  3376. int fdout[2],
  3377. int fderr[2],
  3378. const char *dir)
  3379. {
  3380. pid_t pid;
  3381. const char *interp;
  3382. (void)envblk;
  3383. if (conn == NULL) {
  3384. return 0;
  3385. }
  3386. if ((pid = fork()) == -1) {
  3387. /* Parent */
  3388. send_http_error(conn,
  3389. 500,
  3390. "Error: Creating CGI process\nfork(): %s",
  3391. strerror(ERRNO));
  3392. } else if (pid == 0) {
  3393. /* Child */
  3394. if (chdir(dir) != 0) {
  3395. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  3396. } else if (dup2(fdin[0], 0) == -1) {
  3397. mg_cry(conn,
  3398. "%s: dup2(%d, 0): %s",
  3399. __func__,
  3400. fdin[0],
  3401. strerror(ERRNO));
  3402. } else if (dup2(fdout[1], 1) == -1) {
  3403. mg_cry(conn,
  3404. "%s: dup2(%d, 1): %s",
  3405. __func__,
  3406. fdout[1],
  3407. strerror(ERRNO));
  3408. } else if (dup2(fderr[1], 2) == -1) {
  3409. mg_cry(conn,
  3410. "%s: dup2(%d, 2): %s",
  3411. __func__,
  3412. fderr[1],
  3413. strerror(ERRNO));
  3414. } else {
  3415. /* Keep stderr and stdout in two different pipes.
  3416. * Stdout will be sent back to the client,
  3417. * stderr should go into a server error log. */
  3418. (void)close(fdin[0]);
  3419. (void)close(fdout[1]);
  3420. (void)close(fderr[1]);
  3421. /* Close write end fdin and read end fdout and fderr */
  3422. (void)close(fdin[1]);
  3423. (void)close(fdout[0]);
  3424. (void)close(fderr[0]);
  3425. /* After exec, all signal handlers are restored to their default
  3426. * values, with one exception of SIGCHLD. According to
  3427. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler will
  3428. * leave unchanged after exec if it was set to be ignored. Restore
  3429. * it to default action. */
  3430. signal(SIGCHLD, SIG_DFL);
  3431. interp = conn->ctx->config[CGI_INTERPRETER];
  3432. if (interp == NULL) {
  3433. (void)execle(prog, prog, NULL, envp);
  3434. mg_cry(conn,
  3435. "%s: execle(%s): %s",
  3436. __func__,
  3437. prog,
  3438. strerror(ERRNO));
  3439. } else {
  3440. (void)execle(interp, interp, prog, NULL, envp);
  3441. mg_cry(conn,
  3442. "%s: execle(%s %s): %s",
  3443. __func__,
  3444. interp,
  3445. prog,
  3446. strerror(ERRNO));
  3447. }
  3448. }
  3449. exit(EXIT_FAILURE);
  3450. }
  3451. return pid;
  3452. }
  3453. #endif /* !NO_CGI */
  3454. static int
  3455. set_non_blocking_mode(SOCKET sock)
  3456. {
  3457. int flags;
  3458. flags = fcntl(sock, F_GETFL, 0);
  3459. (void)fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  3460. return 0;
  3461. }
  3462. #endif /* _WIN32 */
  3463. /* End of initial operating system specific define block. */
  3464. /* Get a random number (independent of C rand function) */
  3465. static uint64_t
  3466. get_random(void)
  3467. {
  3468. static uint64_t lfsr = 0; /* Linear feedback shift register */
  3469. static uint64_t lcg = 0; /* Linear congruential generator */
  3470. struct timespec now;
  3471. memset(&now, 0, sizeof(now));
  3472. clock_gettime(CLOCK_MONOTONIC, &now);
  3473. if (lfsr == 0) {
  3474. /* lfsr will be only 0 if has not been initialized,
  3475. * so this code is called only once. */
  3476. lfsr = (((uint64_t)now.tv_sec) << 21) ^ ((uint64_t)now.tv_nsec)
  3477. ^ ((uint64_t)(ptrdiff_t)&now) ^ (((uint64_t)time(NULL)) << 33);
  3478. lcg = (((uint64_t)now.tv_sec) << 25) + (uint64_t)now.tv_nsec
  3479. + (uint64_t)(ptrdiff_t)&now;
  3480. } else {
  3481. /* Get the next step of both random number generators. */
  3482. lfsr = (lfsr >> 1)
  3483. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  3484. << 63);
  3485. lcg = lcg * 6364136223846793005 + 1442695040888963407;
  3486. }
  3487. /* Combining two pseudo-random number generators and a high resolution part
  3488. * of the current server time will make it hard (impossible?) to guess the
  3489. * next number. */
  3490. return (lfsr ^ lcg ^ (uint64_t)now.tv_nsec);
  3491. }
  3492. /* Write data to the IO channel - opened file descriptor, socket or SSL
  3493. * descriptor. Return number of bytes written. */
  3494. static int
  3495. push(struct mg_context *ctx,
  3496. FILE *fp,
  3497. SOCKET sock,
  3498. SSL *ssl,
  3499. const char *buf,
  3500. int len,
  3501. double timeout)
  3502. {
  3503. struct timespec start, now;
  3504. int n, err;
  3505. #ifdef _WIN32
  3506. typedef int len_t;
  3507. #else
  3508. typedef size_t len_t;
  3509. #endif
  3510. if (timeout > 0) {
  3511. memset(&start, 0, sizeof(start));
  3512. memset(&now, 0, sizeof(now));
  3513. clock_gettime(CLOCK_MONOTONIC, &start);
  3514. }
  3515. if (ctx == NULL) {
  3516. return -1;
  3517. }
  3518. #ifdef NO_SSL
  3519. if (ssl) {
  3520. return -1;
  3521. }
  3522. #endif
  3523. do {
  3524. #ifndef NO_SSL
  3525. if (ssl != NULL) {
  3526. n = SSL_write(ssl, buf, len);
  3527. if (n <= 0) {
  3528. err = SSL_get_error(ssl, n);
  3529. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  3530. err = ERRNO;
  3531. } else if ((err == SSL_ERROR_WANT_READ)
  3532. || (err == SSL_ERROR_WANT_WRITE)) {
  3533. n = 0;
  3534. } else {
  3535. DEBUG_TRACE("SSL_write() failed, error %d", err);
  3536. return -1;
  3537. }
  3538. } else {
  3539. err = 0;
  3540. }
  3541. } else
  3542. #endif
  3543. if (fp != NULL) {
  3544. n = (int)fwrite(buf, 1, (size_t)len, fp);
  3545. if (ferror(fp)) {
  3546. n = -1;
  3547. err = ERRNO;
  3548. } else {
  3549. err = 0;
  3550. }
  3551. } else {
  3552. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  3553. err = (n < 0) ? ERRNO : 0;
  3554. if (n == 0) {
  3555. /* shutdown of the socket at client side */
  3556. return -1;
  3557. }
  3558. }
  3559. if (ctx->stop_flag) {
  3560. return -1;
  3561. }
  3562. if ((n > 0) || (n == 0 && len == 0)) {
  3563. /* some data has been read, or no data was requested */
  3564. return n;
  3565. }
  3566. if (n < 0) {
  3567. /* socket error - check errno */
  3568. DEBUG_TRACE("send() failed, error %d", err);
  3569. /* TODO: error handling depending on the error code.
  3570. * These codes are different between Windows and Linux.
  3571. */
  3572. return -1;
  3573. }
  3574. /* This code is not reached in the moment.
  3575. * ==> Fix the TODOs above first. */
  3576. if (timeout > 0) {
  3577. clock_gettime(CLOCK_MONOTONIC, &now);
  3578. }
  3579. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  3580. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  3581. used */
  3582. return -1;
  3583. }
  3584. static int64_t
  3585. push_all(struct mg_context *ctx,
  3586. FILE *fp,
  3587. SOCKET sock,
  3588. SSL *ssl,
  3589. const char *buf,
  3590. int64_t len)
  3591. {
  3592. double timeout = -1.0;
  3593. int64_t n, nwritten = 0;
  3594. if (ctx == NULL) {
  3595. return -1;
  3596. }
  3597. if (ctx->config[REQUEST_TIMEOUT]) {
  3598. timeout = atoi(ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  3599. }
  3600. while (len > 0 && ctx->stop_flag == 0) {
  3601. n = push(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  3602. if (n < 0) {
  3603. if (nwritten == 0) {
  3604. nwritten = n; /* Propagate the error */
  3605. }
  3606. break;
  3607. } else if (n == 0) {
  3608. break; /* No more data to write */
  3609. } else {
  3610. nwritten += n;
  3611. len -= n;
  3612. }
  3613. }
  3614. return nwritten;
  3615. }
  3616. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  3617. * Return negative value on error, or number of bytes read on success. */
  3618. static int
  3619. pull(FILE *fp, struct mg_connection *conn, char *buf, int len, double timeout)
  3620. {
  3621. int nread, err;
  3622. struct timespec start, now;
  3623. #ifdef _WIN32
  3624. typedef int len_t;
  3625. #else
  3626. typedef size_t len_t;
  3627. #endif
  3628. if (timeout > 0) {
  3629. memset(&start, 0, sizeof(start));
  3630. memset(&now, 0, sizeof(now));
  3631. clock_gettime(CLOCK_MONOTONIC, &start);
  3632. }
  3633. do {
  3634. if (fp != NULL) {
  3635. #if !defined(_WIN32_WCE)
  3636. /* Use read() instead of fread(), because if we're reading from the
  3637. * CGI pipe, fread() may block until IO buffer is filled up. We
  3638. * cannot afford to block and must pass all read bytes immediately
  3639. * to the client. */
  3640. nread = (int)read(fileno(fp), buf, (size_t)len);
  3641. #else
  3642. /* WinCE does not support CGI pipes */
  3643. nread = (int)fread(buf, 1, (size_t)len, fp);
  3644. #endif
  3645. err = (nread < 0) ? ERRNO : 0;
  3646. #ifndef NO_SSL
  3647. } else if (conn->ssl != NULL) {
  3648. nread = SSL_read(conn->ssl, buf, len);
  3649. if (nread <= 0) {
  3650. err = SSL_get_error(conn->ssl, nread);
  3651. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  3652. err = ERRNO;
  3653. } else if ((err == SSL_ERROR_WANT_READ)
  3654. || (err == SSL_ERROR_WANT_WRITE)) {
  3655. nread = 0;
  3656. } else {
  3657. DEBUG_TRACE("SSL_read() failed, error %d", err);
  3658. return -1;
  3659. }
  3660. } else {
  3661. err = 0;
  3662. }
  3663. #endif
  3664. } else {
  3665. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  3666. err = (nread < 0) ? ERRNO : 0;
  3667. if (nread == 0) {
  3668. /* shutdown of the socket at client side */
  3669. return -1;
  3670. }
  3671. }
  3672. if (conn->ctx->stop_flag) {
  3673. return -1;
  3674. }
  3675. if ((nread > 0) || (nread == 0 && len == 0)) {
  3676. /* some data has been read, or no data was requested */
  3677. return nread;
  3678. }
  3679. if (nread < 0) {
  3680. /* socket error - check errno */
  3681. #ifdef _WIN32
  3682. if (err == WSAEWOULDBLOCK) {
  3683. /* standard case if called from close_socket_gracefully */
  3684. return -1;
  3685. } else if (err == WSAETIMEDOUT) {
  3686. /* timeout is handled by the while loop */
  3687. } else {
  3688. DEBUG_TRACE("recv() failed, error %d", err);
  3689. return -1;
  3690. }
  3691. #else
  3692. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  3693. * if the timeout is reached and if the socket was set to non-
  3694. * blocking in close_socket_gracefully, so we can not distinguish
  3695. * here. We have to wait for the timeout in both cases for now.
  3696. */
  3697. if (err == EAGAIN || err == EWOULDBLOCK || err == EINTR) {
  3698. /* EAGAIN/EWOULDBLOCK:
  3699. * standard case if called from close_socket_gracefully
  3700. * => should return -1 */
  3701. /* or timeout occured
  3702. * => the code must stay in the while loop */
  3703. /* EINTR can be generated on a socket with a timeout set even
  3704. * when SA_RESTART is effective for all relevant signals
  3705. * (see signal(7)).
  3706. * => stay in the while loop */
  3707. } else {
  3708. DEBUG_TRACE("recv() failed, error %d", err);
  3709. return -1;
  3710. }
  3711. #endif
  3712. }
  3713. if (timeout > 0) {
  3714. clock_gettime(CLOCK_MONOTONIC, &now);
  3715. }
  3716. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  3717. /* Timeout occured, but no data available. */
  3718. return -1;
  3719. }
  3720. static int
  3721. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  3722. {
  3723. int n, nread = 0;
  3724. double timeout = -1.0;
  3725. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  3726. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  3727. }
  3728. while (len > 0 && conn->ctx->stop_flag == 0) {
  3729. n = pull(fp, conn, buf + nread, len, timeout);
  3730. if (n < 0) {
  3731. if (nread == 0) {
  3732. nread = n; /* Propagate the error */
  3733. }
  3734. break;
  3735. } else if (n == 0) {
  3736. break; /* No more data to read */
  3737. } else {
  3738. conn->consumed_content += n;
  3739. nread += n;
  3740. len -= n;
  3741. }
  3742. }
  3743. return nread;
  3744. }
  3745. static void
  3746. discard_unread_request_data(struct mg_connection *conn)
  3747. {
  3748. char buf[MG_BUF_LEN];
  3749. size_t to_read;
  3750. int nread;
  3751. if (conn == NULL) {
  3752. return;
  3753. }
  3754. to_read = sizeof(buf);
  3755. if (conn->is_chunked) {
  3756. /* Chunked encoding: 1=chunk not read completely, 2=chunk read
  3757. * completely */
  3758. while (conn->is_chunked == 1) {
  3759. nread = mg_read(conn, buf, to_read);
  3760. if (nread <= 0) {
  3761. break;
  3762. }
  3763. }
  3764. } else {
  3765. /* Not chunked: content length is known */
  3766. while (conn->consumed_content < conn->content_len) {
  3767. if (to_read
  3768. > (size_t)(conn->content_len - conn->consumed_content)) {
  3769. to_read = (size_t)(conn->content_len - conn->consumed_content);
  3770. }
  3771. nread = mg_read(conn, buf, to_read);
  3772. if (nread <= 0) {
  3773. break;
  3774. }
  3775. }
  3776. }
  3777. }
  3778. static int
  3779. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  3780. {
  3781. int64_t n, buffered_len, nread;
  3782. int64_t len64 =
  3783. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  3784. * int, we may not read more
  3785. * bytes */
  3786. const char *body;
  3787. if (conn == NULL) {
  3788. return 0;
  3789. }
  3790. /* If Content-Length is not set for a PUT or POST request, read until
  3791. * socket is closed */
  3792. if (conn->consumed_content == 0 && conn->content_len == -1) {
  3793. conn->content_len = INT64_MAX;
  3794. conn->must_close = 1;
  3795. }
  3796. nread = 0;
  3797. if (conn->consumed_content < conn->content_len) {
  3798. /* Adjust number of bytes to read. */
  3799. int64_t left_to_read = conn->content_len - conn->consumed_content;
  3800. if (left_to_read < len64) {
  3801. /* Do not read more than the total content length of the request.
  3802. */
  3803. len64 = left_to_read;
  3804. }
  3805. /* Return buffered data */
  3806. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  3807. - conn->consumed_content;
  3808. if (buffered_len > 0) {
  3809. if (len64 < buffered_len) {
  3810. buffered_len = len64;
  3811. }
  3812. body = conn->buf + conn->request_len + conn->consumed_content;
  3813. memcpy(buf, body, (size_t)buffered_len);
  3814. len64 -= buffered_len;
  3815. conn->consumed_content += buffered_len;
  3816. nread += buffered_len;
  3817. buf = (char *)buf + buffered_len;
  3818. }
  3819. /* We have returned all buffered data. Read new data from the remote
  3820. * socket.
  3821. */
  3822. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  3823. nread += n;
  3824. } else {
  3825. nread = ((nread > 0) ? nread : n);
  3826. }
  3827. }
  3828. return (int)nread;
  3829. }
  3830. static char
  3831. mg_getc(struct mg_connection *conn)
  3832. {
  3833. char c;
  3834. if (conn == NULL) {
  3835. return 0;
  3836. }
  3837. conn->content_len++;
  3838. if (mg_read_inner(conn, &c, 1) <= 0) {
  3839. return (char)0;
  3840. }
  3841. return c;
  3842. }
  3843. int
  3844. mg_read(struct mg_connection *conn, void *buf, size_t len)
  3845. {
  3846. if (len > INT_MAX) {
  3847. len = INT_MAX;
  3848. }
  3849. if (conn == NULL) {
  3850. return 0;
  3851. }
  3852. if (conn->is_chunked) {
  3853. size_t all_read = 0;
  3854. while (len > 0) {
  3855. if (conn->is_chunked == 2) {
  3856. /* No more data left to read */
  3857. return 0;
  3858. }
  3859. if (conn->chunk_remainder) {
  3860. /* copy from the remainder of the last received chunk */
  3861. long read_ret;
  3862. size_t read_now =
  3863. ((conn->chunk_remainder > len) ? (len)
  3864. : (conn->chunk_remainder));
  3865. conn->content_len += (int)read_now;
  3866. read_ret =
  3867. mg_read_inner(conn, (char *)buf + all_read, read_now);
  3868. all_read += (size_t)read_ret;
  3869. conn->chunk_remainder -= read_now;
  3870. len -= read_now;
  3871. if (conn->chunk_remainder == 0) {
  3872. /* the rest of the data in the current chunk has been read
  3873. */
  3874. if ((mg_getc(conn) != '\r') || (mg_getc(conn) != '\n')) {
  3875. /* Protocol violation */
  3876. return -1;
  3877. }
  3878. }
  3879. } else {
  3880. /* fetch a new chunk */
  3881. int i = 0;
  3882. char lenbuf[64];
  3883. char *end = 0;
  3884. unsigned long chunkSize = 0;
  3885. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  3886. lenbuf[i] = mg_getc(conn);
  3887. if (i > 0 && lenbuf[i] == '\r' && lenbuf[i - 1] != '\r') {
  3888. continue;
  3889. }
  3890. if (i > 1 && lenbuf[i] == '\n' && lenbuf[i - 1] == '\r') {
  3891. lenbuf[i + 1] = 0;
  3892. chunkSize = strtoul(lenbuf, &end, 16);
  3893. if (chunkSize == 0) {
  3894. /* regular end of content */
  3895. conn->is_chunked = 2;
  3896. }
  3897. break;
  3898. }
  3899. if (!isalnum(lenbuf[i])) {
  3900. /* illegal character for chunk length */
  3901. return -1;
  3902. }
  3903. }
  3904. if ((end == NULL) || (*end != '\r')) {
  3905. /* chunksize not set correctly */
  3906. return -1;
  3907. }
  3908. if (chunkSize == 0) {
  3909. break;
  3910. }
  3911. conn->chunk_remainder = chunkSize;
  3912. }
  3913. }
  3914. return (int)all_read;
  3915. }
  3916. return mg_read_inner(conn, buf, len);
  3917. }
  3918. int
  3919. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  3920. {
  3921. time_t now;
  3922. int64_t n, total, allowed;
  3923. if (conn == NULL) {
  3924. return 0;
  3925. }
  3926. if (conn->throttle > 0) {
  3927. if ((now = time(NULL)) != conn->last_throttle_time) {
  3928. conn->last_throttle_time = now;
  3929. conn->last_throttle_bytes = 0;
  3930. }
  3931. allowed = conn->throttle - conn->last_throttle_bytes;
  3932. if (allowed > (int64_t)len) {
  3933. allowed = (int64_t)len;
  3934. }
  3935. if ((total = push_all(conn->ctx,
  3936. NULL,
  3937. conn->client.sock,
  3938. conn->ssl,
  3939. (const char *)buf,
  3940. (int64_t)allowed)) == allowed) {
  3941. buf = (const char *)buf + total;
  3942. conn->last_throttle_bytes += total;
  3943. while (total < (int64_t)len && conn->ctx->stop_flag == 0) {
  3944. allowed = (conn->throttle > ((int64_t)len - total))
  3945. ? (int64_t)len - total
  3946. : conn->throttle;
  3947. if ((n = push_all(conn->ctx,
  3948. NULL,
  3949. conn->client.sock,
  3950. conn->ssl,
  3951. (const char *)buf,
  3952. (int64_t)allowed)) != allowed) {
  3953. break;
  3954. }
  3955. sleep(1);
  3956. conn->last_throttle_bytes = allowed;
  3957. conn->last_throttle_time = time(NULL);
  3958. buf = (const char *)buf + n;
  3959. total += n;
  3960. }
  3961. }
  3962. } else {
  3963. total = push_all(conn->ctx,
  3964. NULL,
  3965. conn->client.sock,
  3966. conn->ssl,
  3967. (const char *)buf,
  3968. (int64_t)len);
  3969. }
  3970. return (int)total;
  3971. }
  3972. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  3973. static int
  3974. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  3975. {
  3976. va_list ap_copy;
  3977. size_t size = MG_BUF_LEN / 4;
  3978. int len = -1;
  3979. *buf = NULL;
  3980. while (len < 0) {
  3981. if (*buf) {
  3982. mg_free(*buf);
  3983. }
  3984. size *= 4;
  3985. *buf = (char *)mg_malloc(size);
  3986. if (!*buf) {
  3987. break;
  3988. }
  3989. va_copy(ap_copy, ap);
  3990. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  3991. va_end(ap_copy);
  3992. (*buf)[size - 1] = 0;
  3993. }
  3994. return len;
  3995. }
  3996. /* Print message to buffer. If buffer is large enough to hold the message,
  3997. * return buffer. If buffer is to small, allocate large enough buffer on heap,
  3998. * and return allocated buffer. */
  3999. static int
  4000. alloc_vprintf(char **out_buf,
  4001. char *prealloc_buf,
  4002. size_t prealloc_size,
  4003. const char *fmt,
  4004. va_list ap)
  4005. {
  4006. va_list ap_copy;
  4007. int len;
  4008. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  4009. * buffer is too small. Also, older versions of msvcrt.dll do not have
  4010. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  4011. * Therefore, we make two passes: on first pass, get required message
  4012. * length.
  4013. * On second pass, actually print the message. */
  4014. va_copy(ap_copy, ap);
  4015. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  4016. va_end(ap_copy);
  4017. if (len < 0) {
  4018. /* C runtime is not standard compliant, vsnprintf() returned -1.
  4019. * Switch to alternative code path that uses incremental allocations.
  4020. */
  4021. va_copy(ap_copy, ap);
  4022. len = alloc_vprintf2(out_buf, fmt, ap);
  4023. va_end(ap_copy);
  4024. } else if ((size_t)(len) >= prealloc_size) {
  4025. /* The pre-allocated buffer not large enough. */
  4026. /* Allocate a new buffer. */
  4027. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  4028. if (!*out_buf) {
  4029. /* Allocation failed. Return -1 as "out of memory" error. */
  4030. return -1;
  4031. }
  4032. /* Buffer allocation successful. Store the string there. */
  4033. va_copy(ap_copy, ap);
  4034. IGNORE_UNUSED_RESULT(
  4035. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  4036. va_end(ap_copy);
  4037. } else {
  4038. /* The pre-allocated buffer is large enough.
  4039. * Use it to store the string and return the address. */
  4040. va_copy(ap_copy, ap);
  4041. IGNORE_UNUSED_RESULT(
  4042. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  4043. va_end(ap_copy);
  4044. *out_buf = prealloc_buf;
  4045. }
  4046. return len;
  4047. }
  4048. static int
  4049. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  4050. {
  4051. char mem[MG_BUF_LEN];
  4052. char *buf = NULL;
  4053. int len;
  4054. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  4055. len = mg_write(conn, buf, (size_t)len);
  4056. }
  4057. if (buf != mem && buf != NULL) {
  4058. mg_free(buf);
  4059. }
  4060. return len;
  4061. }
  4062. int
  4063. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  4064. {
  4065. va_list ap;
  4066. int result;
  4067. va_start(ap, fmt);
  4068. result = mg_vprintf(conn, fmt, ap);
  4069. va_end(ap);
  4070. return result;
  4071. }
  4072. int
  4073. mg_url_decode(const char *src,
  4074. int src_len,
  4075. char *dst,
  4076. int dst_len,
  4077. int is_form_url_encoded)
  4078. {
  4079. int i, j, a, b;
  4080. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  4081. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  4082. if (i < src_len - 2 && src[i] == '%'
  4083. && isxdigit(*(const unsigned char *)(src + i + 1))
  4084. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  4085. a = tolower(*(const unsigned char *)(src + i + 1));
  4086. b = tolower(*(const unsigned char *)(src + i + 2));
  4087. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  4088. i += 2;
  4089. } else if (is_form_url_encoded && src[i] == '+') {
  4090. dst[j] = ' ';
  4091. } else {
  4092. dst[j] = src[i];
  4093. }
  4094. }
  4095. dst[j] = '\0'; /* Null-terminate the destination */
  4096. return (i >= src_len) ? j : -1;
  4097. }
  4098. int
  4099. mg_get_var(const char *data,
  4100. size_t data_len,
  4101. const char *name,
  4102. char *dst,
  4103. size_t dst_len)
  4104. {
  4105. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  4106. }
  4107. int
  4108. mg_get_var2(const char *data,
  4109. size_t data_len,
  4110. const char *name,
  4111. char *dst,
  4112. size_t dst_len,
  4113. size_t occurrence)
  4114. {
  4115. const char *p, *e, *s;
  4116. size_t name_len;
  4117. int len;
  4118. if (dst == NULL || dst_len == 0) {
  4119. len = -2;
  4120. } else if (data == NULL || name == NULL || data_len == 0) {
  4121. len = -1;
  4122. dst[0] = '\0';
  4123. } else {
  4124. name_len = strlen(name);
  4125. e = data + data_len;
  4126. len = -1;
  4127. dst[0] = '\0';
  4128. /* data is "var1=val1&var2=val2...". Find variable first */
  4129. for (p = data; p + name_len < e; p++) {
  4130. if ((p == data || p[-1] == '&') && p[name_len] == '='
  4131. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  4132. /* Point p to variable value */
  4133. p += name_len + 1;
  4134. /* Point s to the end of the value */
  4135. s = (const char *)memchr(p, '&', (size_t)(e - p));
  4136. if (s == NULL) {
  4137. s = e;
  4138. }
  4139. /* assert(s >= p); */
  4140. if (s < p) {
  4141. return -3;
  4142. }
  4143. /* Decode variable into destination buffer */
  4144. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  4145. /* Redirect error code from -1 to -2 (destination buffer too
  4146. * small). */
  4147. if (len == -1) {
  4148. len = -2;
  4149. }
  4150. break;
  4151. }
  4152. }
  4153. }
  4154. return len;
  4155. }
  4156. /* HCP24: some changes to compare hole var_name */
  4157. int
  4158. mg_get_cookie(const char *cookie_header,
  4159. const char *var_name,
  4160. char *dst,
  4161. size_t dst_size)
  4162. {
  4163. const char *s, *p, *end;
  4164. int name_len, len = -1;
  4165. if (dst == NULL || dst_size == 0) {
  4166. return -2;
  4167. }
  4168. dst[0] = '\0';
  4169. if (var_name == NULL || (s = cookie_header) == NULL) {
  4170. return -1;
  4171. }
  4172. name_len = (int)strlen(var_name);
  4173. end = s + strlen(s);
  4174. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  4175. if (s[name_len] == '=') {
  4176. /* HCP24: now check is it a substring or a full cookie name */
  4177. if ((s == cookie_header) || (s[-1] == ' ')) {
  4178. s += name_len + 1;
  4179. if ((p = strchr(s, ' ')) == NULL) {
  4180. p = end;
  4181. }
  4182. if (p[-1] == ';') {
  4183. p--;
  4184. }
  4185. if (*s == '"' && p[-1] == '"' && p > s + 1) {
  4186. s++;
  4187. p--;
  4188. }
  4189. if ((size_t)(p - s) < dst_size) {
  4190. len = (int)(p - s);
  4191. mg_strlcpy(dst, s, (size_t)len + 1);
  4192. } else {
  4193. len = -3;
  4194. }
  4195. break;
  4196. }
  4197. }
  4198. }
  4199. return len;
  4200. }
  4201. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  4202. static void
  4203. base64_encode(const unsigned char *src, int src_len, char *dst)
  4204. {
  4205. static const char *b64 =
  4206. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  4207. int i, j, a, b, c;
  4208. for (i = j = 0; i < src_len; i += 3) {
  4209. a = src[i];
  4210. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  4211. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  4212. dst[j++] = b64[a >> 2];
  4213. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  4214. if (i + 1 < src_len) {
  4215. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  4216. }
  4217. if (i + 2 < src_len) {
  4218. dst[j++] = b64[c & 63];
  4219. }
  4220. }
  4221. while (j % 4 != 0) {
  4222. dst[j++] = '=';
  4223. }
  4224. dst[j++] = '\0';
  4225. }
  4226. #endif
  4227. #if defined(USE_LUA)
  4228. static unsigned char
  4229. b64reverse(char letter)
  4230. {
  4231. if (letter >= 'A' && letter <= 'Z') {
  4232. return letter - 'A';
  4233. }
  4234. if (letter >= 'a' && letter <= 'z') {
  4235. return letter - 'a' + 26;
  4236. }
  4237. if (letter >= '0' && letter <= '9') {
  4238. return letter - '0' + 52;
  4239. }
  4240. if (letter == '+') {
  4241. return 62;
  4242. }
  4243. if (letter == '/') {
  4244. return 63;
  4245. }
  4246. if (letter == '=') {
  4247. return 255; /* normal end */
  4248. }
  4249. return 254; /* error */
  4250. }
  4251. static int
  4252. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  4253. {
  4254. int i;
  4255. unsigned char a, b, c, d;
  4256. *dst_len = 0;
  4257. for (i = 0; i < src_len; i += 4) {
  4258. a = b64reverse(src[i]);
  4259. if (a >= 254) {
  4260. return i;
  4261. }
  4262. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  4263. if (b >= 254) {
  4264. return i + 1;
  4265. }
  4266. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  4267. if (c == 254) {
  4268. return i + 2;
  4269. }
  4270. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  4271. if (d == 254) {
  4272. return i + 3;
  4273. }
  4274. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  4275. if (c != 255) {
  4276. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  4277. if (d != 255) {
  4278. dst[(*dst_len)++] = (c << 6) + d;
  4279. }
  4280. }
  4281. }
  4282. return -1;
  4283. }
  4284. #endif
  4285. static int
  4286. is_put_or_delete_method(const struct mg_connection *conn)
  4287. {
  4288. if (conn) {
  4289. const char *s = conn->request_info.request_method;
  4290. return s != NULL && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  4291. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  4292. }
  4293. return 0;
  4294. }
  4295. static void
  4296. interpret_uri(struct mg_connection *conn, /* in: request (must be valid) */
  4297. char *filename, /* out: filename */
  4298. size_t filename_buf_len, /* in: size of filename buffer */
  4299. struct file *filep, /* out: file structure */
  4300. int *is_found, /* out: file is found (directly) */
  4301. int *is_script_resource, /* out: handled by a script? */
  4302. int *is_websocket_request, /* out: websocket connetion? */
  4303. int *is_put_or_delete_request /* out: put/delete a file? */
  4304. )
  4305. {
  4306. /* TODO (high): Restructure this function */
  4307. #if !defined(NO_FILES)
  4308. const char *uri = conn->request_info.local_uri;
  4309. const char *root = conn->ctx->config[DOCUMENT_ROOT];
  4310. const char *rewrite;
  4311. struct vec a, b;
  4312. int match_len;
  4313. char gz_path[PATH_MAX];
  4314. char const *accept_encoding;
  4315. int truncated;
  4316. #if !defined(NO_CGI) || defined(USE_LUA)
  4317. char *p;
  4318. #endif
  4319. #else
  4320. (void)filename_buf_len; /* unused if NO_FILES is defined */
  4321. #endif
  4322. memset(filep, 0, sizeof(*filep));
  4323. *filename = 0;
  4324. *is_found = 0;
  4325. *is_script_resource = 0;
  4326. *is_put_or_delete_request = is_put_or_delete_method(conn);
  4327. #if defined(USE_WEBSOCKET)
  4328. *is_websocket_request = is_websocket_protocol(conn);
  4329. #if !defined(NO_FILES)
  4330. if (*is_websocket_request && conn->ctx->config[WEBSOCKET_ROOT]) {
  4331. root = conn->ctx->config[WEBSOCKET_ROOT];
  4332. }
  4333. #endif /* !NO_FILES */
  4334. #else /* USE_WEBSOCKET */
  4335. *is_websocket_request = 0;
  4336. #endif /* USE_WEBSOCKET */
  4337. #if !defined(NO_FILES)
  4338. /* Note that root == NULL is a regular use case here. This occurs,
  4339. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  4340. * config is not required. */
  4341. if (root == NULL) {
  4342. /* all file related outputs have already been set to 0, just return
  4343. */
  4344. return;
  4345. }
  4346. /* Using buf_len - 1 because memmove() for PATH_INFO may shift part
  4347. * of the path one byte on the right.
  4348. * If document_root is NULL, leave the file empty. */
  4349. mg_snprintf(
  4350. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  4351. if (truncated) {
  4352. goto interpret_cleanup;
  4353. }
  4354. rewrite = conn->ctx->config[REWRITE];
  4355. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  4356. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  4357. mg_snprintf(conn,
  4358. &truncated,
  4359. filename,
  4360. filename_buf_len - 1,
  4361. "%.*s%s",
  4362. (int)b.len,
  4363. b.ptr,
  4364. uri + match_len);
  4365. break;
  4366. }
  4367. }
  4368. if (truncated) {
  4369. goto interpret_cleanup;
  4370. }
  4371. /* Local file path and name, corresponding to requested URI
  4372. * is now stored in "filename" variable. */
  4373. if (mg_stat(conn, filename, filep)) {
  4374. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  4375. /* File exists. Check if it is a script type. */
  4376. if (0
  4377. #if !defined(NO_CGI)
  4378. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  4379. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4380. filename) > 0
  4381. #endif
  4382. #if defined(USE_LUA)
  4383. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  4384. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  4385. filename) > 0
  4386. #endif
  4387. #if defined(USE_DUKTAPE)
  4388. || match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  4389. strlen(
  4390. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  4391. filename) > 0
  4392. #endif
  4393. ) {
  4394. /* The request addresses a CGI script or a Lua script. The URI
  4395. * corresponds to the script itself (like /path/script.cgi),
  4396. * and there is no additional resource path
  4397. * (like /path/script.cgi/something).
  4398. * Requests that modify (replace or delete) a resource, like
  4399. * PUT and DELETE requests, should replace/delete the script
  4400. * file.
  4401. * Requests that read or write from/to a resource, like GET and
  4402. * POST requests, should call the script and return the
  4403. * generated response. */
  4404. *is_script_resource = !*is_put_or_delete_request;
  4405. }
  4406. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  4407. *is_found = 1;
  4408. return;
  4409. }
  4410. /* If we can't find the actual file, look for the file
  4411. * with the same name but a .gz extension. If we find it,
  4412. * use that and set the gzipped flag in the file struct
  4413. * to indicate that the response need to have the content-
  4414. * encoding: gzip header.
  4415. * We can only do this if the browser declares support. */
  4416. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  4417. if (strstr(accept_encoding, "gzip") != NULL) {
  4418. mg_snprintf(
  4419. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  4420. if (truncated) {
  4421. goto interpret_cleanup;
  4422. }
  4423. if (mg_stat(conn, gz_path, filep)) {
  4424. if (filep) {
  4425. filep->gzipped = 1;
  4426. *is_found = 1;
  4427. }
  4428. /* Currently gz files can not be scripts. */
  4429. return;
  4430. }
  4431. }
  4432. }
  4433. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  4434. /* Support PATH_INFO for CGI scripts. */
  4435. for (p = filename + strlen(filename); p > filename + 1; p--) {
  4436. if (*p == '/') {
  4437. *p = '\0';
  4438. if ((0
  4439. #if !defined(NO_CGI)
  4440. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  4441. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4442. filename) > 0
  4443. #endif
  4444. #if defined(USE_LUA)
  4445. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  4446. strlen(
  4447. conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  4448. filename) > 0
  4449. #endif
  4450. #if defined(USE_DUKTAPE)
  4451. || match_prefix(
  4452. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  4453. strlen(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  4454. filename) > 0
  4455. #endif
  4456. ) && mg_stat(conn, filename, filep)) {
  4457. /* Shift PATH_INFO block one character right, e.g.
  4458. * "/x.cgi/foo/bar\x00" => "/x.cgi\x00/foo/bar\x00"
  4459. * conn->path_info is pointing to the local variable "path"
  4460. * declared in handle_request(), so PATH_INFO is not valid
  4461. * after handle_request returns. */
  4462. conn->path_info = p + 1;
  4463. memmove(p + 2, p + 1, strlen(p + 1) + 1); /* +1 is for
  4464. * trailing \0 */
  4465. p[1] = '/';
  4466. *is_script_resource = 1;
  4467. break;
  4468. } else {
  4469. *p = '/';
  4470. }
  4471. }
  4472. }
  4473. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  4474. #endif /* !defined(NO_FILES) */
  4475. return;
  4476. #if !defined(NO_FILES)
  4477. /* Reset all outputs */
  4478. interpret_cleanup:
  4479. memset(filep, 0, sizeof(*filep));
  4480. *filename = 0;
  4481. *is_found = 0;
  4482. *is_script_resource = 0;
  4483. *is_websocket_request = 0;
  4484. *is_put_or_delete_request = 0;
  4485. #endif /* !defined(NO_FILES) */
  4486. }
  4487. /* Check whether full request is buffered. Return:
  4488. * -1 if request is malformed
  4489. * 0 if request is not yet fully buffered
  4490. * >0 actual request length, including last \r\n\r\n */
  4491. static int
  4492. get_request_len(const char *buf, int buflen)
  4493. {
  4494. const char *s, *e;
  4495. int len = 0;
  4496. for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
  4497. /* Control characters are not allowed but >=128 is. */
  4498. if (!isprint(*(const unsigned char *)s) && *s != '\r' && *s != '\n'
  4499. && *(const unsigned char *)s < 128) {
  4500. len = -1;
  4501. break; /* [i_a] abort scan as soon as one malformed character is
  4502. * found; */
  4503. /* don't let subsequent \r\n\r\n win us over anyhow */
  4504. } else if (s[0] == '\n' && s[1] == '\n') {
  4505. len = (int)(s - buf) + 2;
  4506. } else if (s[0] == '\n' && &s[1] < e && s[1] == '\r' && s[2] == '\n') {
  4507. len = (int)(s - buf) + 3;
  4508. }
  4509. return len;
  4510. }
  4511. #if !defined(NO_CACHING)
  4512. /* Convert month to the month number. Return -1 on error, or month number */
  4513. static int
  4514. get_month_index(const char *s)
  4515. {
  4516. size_t i;
  4517. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  4518. if (!strcmp(s, month_names[i])) {
  4519. return (int)i;
  4520. }
  4521. }
  4522. return -1;
  4523. }
  4524. /* Parse UTC date-time string, and return the corresponding time_t value. */
  4525. static time_t
  4526. parse_date_string(const char *datetime)
  4527. {
  4528. char month_str[32] = {0};
  4529. int second, minute, hour, day, month, year;
  4530. time_t result = (time_t)0;
  4531. struct tm tm;
  4532. if ((sscanf(datetime,
  4533. "%d/%3s/%d %d:%d:%d",
  4534. &day,
  4535. month_str,
  4536. &year,
  4537. &hour,
  4538. &minute,
  4539. &second) == 6) || (sscanf(datetime,
  4540. "%d %3s %d %d:%d:%d",
  4541. &day,
  4542. month_str,
  4543. &year,
  4544. &hour,
  4545. &minute,
  4546. &second) == 6)
  4547. || (sscanf(datetime,
  4548. "%*3s, %d %3s %d %d:%d:%d",
  4549. &day,
  4550. month_str,
  4551. &year,
  4552. &hour,
  4553. &minute,
  4554. &second) == 6) || (sscanf(datetime,
  4555. "%d-%3s-%d %d:%d:%d",
  4556. &day,
  4557. month_str,
  4558. &year,
  4559. &hour,
  4560. &minute,
  4561. &second) == 6)) {
  4562. month = get_month_index(month_str);
  4563. if ((month >= 0) && (year >= 1970)) {
  4564. memset(&tm, 0, sizeof(tm));
  4565. tm.tm_year = year - 1900;
  4566. tm.tm_mon = month;
  4567. tm.tm_mday = day;
  4568. tm.tm_hour = hour;
  4569. tm.tm_min = minute;
  4570. tm.tm_sec = second;
  4571. result = timegm(&tm);
  4572. }
  4573. }
  4574. return result;
  4575. }
  4576. #endif /* !NO_CACHING */
  4577. /* Protect against directory disclosure attack by removing '..',
  4578. * excessive '/' and '\' characters */
  4579. static void
  4580. remove_double_dots_and_double_slashes(char *s)
  4581. {
  4582. char *p = s;
  4583. while ((s[0] == '.') && (s[1] == '.')) {
  4584. s++;
  4585. }
  4586. while (*s != '\0') {
  4587. *p++ = *s++;
  4588. if (s[-1] == '/' || s[-1] == '\\') {
  4589. /* Skip all following slashes, backslashes and double-dots */
  4590. while (s[0] != '\0') {
  4591. if (s[0] == '/' || s[0] == '\\') {
  4592. s++;
  4593. } else if (s[0] == '.' && s[1] == '.') {
  4594. s += 2;
  4595. } else {
  4596. break;
  4597. }
  4598. }
  4599. }
  4600. }
  4601. *p = '\0';
  4602. }
  4603. static const struct {
  4604. const char *extension;
  4605. size_t ext_len;
  4606. const char *mime_type;
  4607. } builtin_mime_types[] = {
  4608. /* IANA registered MIME types (http://www.iana.org/assignments/media-types)
  4609. * application types */
  4610. {".doc", 4, "application/msword"},
  4611. {".eps", 4, "application/postscript"},
  4612. {".exe", 4, "application/octet-stream"},
  4613. {".js", 3, "application/javascript"},
  4614. {".json", 5, "application/json"},
  4615. {".pdf", 4, "application/pdf"},
  4616. {".ps", 3, "application/postscript"},
  4617. {".rtf", 4, "application/rtf"},
  4618. {".xhtml", 6, "application/xhtml+xml"},
  4619. {".xsl", 4, "application/xml"},
  4620. {".xslt", 5, "application/xml"},
  4621. /* fonts */
  4622. {".ttf", 4, "application/font-sfnt"},
  4623. {".cff", 4, "application/font-sfnt"},
  4624. {".otf", 4, "application/font-sfnt"},
  4625. {".aat", 4, "application/font-sfnt"},
  4626. {".sil", 4, "application/font-sfnt"},
  4627. {".pfr", 4, "application/font-tdpfr"},
  4628. {".woff", 5, "application/font-woff"},
  4629. /* audio */
  4630. {".mp3", 4, "audio/mpeg"},
  4631. {".oga", 4, "audio/ogg"},
  4632. {".ogg", 4, "audio/ogg"},
  4633. /* image */
  4634. {".gif", 4, "image/gif"},
  4635. {".ief", 4, "image/ief"},
  4636. {".jpeg", 5, "image/jpeg"},
  4637. {".jpg", 4, "image/jpeg"},
  4638. {".jpm", 4, "image/jpm"},
  4639. {".jpx", 4, "image/jpx"},
  4640. {".png", 4, "image/png"},
  4641. {".svg", 4, "image/svg+xml"},
  4642. {".tif", 4, "image/tiff"},
  4643. {".tiff", 5, "image/tiff"},
  4644. /* model */
  4645. {".wrl", 4, "model/vrml"},
  4646. /* text */
  4647. {".css", 4, "text/css"},
  4648. {".csv", 4, "text/csv"},
  4649. {".htm", 4, "text/html"},
  4650. {".html", 5, "text/html"},
  4651. {".sgm", 4, "text/sgml"},
  4652. {".shtm", 5, "text/html"},
  4653. {".shtml", 6, "text/html"},
  4654. {".txt", 4, "text/plain"},
  4655. {".xml", 4, "text/xml"},
  4656. /* video */
  4657. {".mov", 4, "video/quicktime"},
  4658. {".mp4", 4, "video/mp4"},
  4659. {".mpeg", 5, "video/mpeg"},
  4660. {".mpg", 4, "video/mpeg"},
  4661. {".ogv", 4, "video/ogg"},
  4662. {".qt", 3, "video/quicktime"},
  4663. /* not registered types
  4664. * (http://reference.sitepoint.com/html/mime-types-full,
  4665. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  4666. {".arj", 4, "application/x-arj-compressed"},
  4667. {".gz", 3, "application/x-gunzip"},
  4668. {".rar", 4, "application/x-arj-compressed"},
  4669. {".swf", 4, "application/x-shockwave-flash"},
  4670. {".tar", 4, "application/x-tar"},
  4671. {".tgz", 4, "application/x-tar-gz"},
  4672. {".torrent", 8, "application/x-bittorrent"},
  4673. {".ppt", 4, "application/x-mspowerpoint"},
  4674. {".xls", 4, "application/x-msexcel"},
  4675. {".zip", 4, "application/x-zip-compressed"},
  4676. {".aac",
  4677. 4,
  4678. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  4679. {".aif", 4, "audio/x-aif"},
  4680. {".m3u", 4, "audio/x-mpegurl"},
  4681. {".mid", 4, "audio/x-midi"},
  4682. {".ra", 3, "audio/x-pn-realaudio"},
  4683. {".ram", 4, "audio/x-pn-realaudio"},
  4684. {".wav", 4, "audio/x-wav"},
  4685. {".bmp", 4, "image/bmp"},
  4686. {".ico", 4, "image/x-icon"},
  4687. {".pct", 4, "image/x-pct"},
  4688. {".pict", 5, "image/pict"},
  4689. {".rgb", 4, "image/x-rgb"},
  4690. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  4691. {".asf", 4, "video/x-ms-asf"},
  4692. {".avi", 4, "video/x-msvideo"},
  4693. {".m4v", 4, "video/x-m4v"},
  4694. {NULL, 0, NULL}};
  4695. const char *
  4696. mg_get_builtin_mime_type(const char *path)
  4697. {
  4698. const char *ext;
  4699. size_t i, path_len;
  4700. path_len = strlen(path);
  4701. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  4702. ext = path + (path_len - builtin_mime_types[i].ext_len);
  4703. if (path_len > builtin_mime_types[i].ext_len
  4704. && mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {
  4705. return builtin_mime_types[i].mime_type;
  4706. }
  4707. }
  4708. return "text/plain";
  4709. }
  4710. /* Look at the "path" extension and figure what mime type it has.
  4711. * Store mime type in the vector. */
  4712. static void
  4713. get_mime_type(struct mg_context *ctx, const char *path, struct vec *vec)
  4714. {
  4715. struct vec ext_vec, mime_vec;
  4716. const char *list, *ext;
  4717. size_t path_len;
  4718. path_len = strlen(path);
  4719. if (ctx == NULL || vec == NULL) {
  4720. return;
  4721. }
  4722. /* Scan user-defined mime types first, in case user wants to
  4723. * override default mime types. */
  4724. list = ctx->config[EXTRA_MIME_TYPES];
  4725. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  4726. /* ext now points to the path suffix */
  4727. ext = path + path_len - ext_vec.len;
  4728. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  4729. *vec = mime_vec;
  4730. return;
  4731. }
  4732. }
  4733. vec->ptr = mg_get_builtin_mime_type(path);
  4734. vec->len = strlen(vec->ptr);
  4735. }
  4736. /* Stringify binary data. Output buffer must be twice as big as input,
  4737. * because each byte takes 2 bytes in string representation */
  4738. static void
  4739. bin2str(char *to, const unsigned char *p, size_t len)
  4740. {
  4741. static const char *hex = "0123456789abcdef";
  4742. for (; len--; p++) {
  4743. *to++ = hex[p[0] >> 4];
  4744. *to++ = hex[p[0] & 0x0f];
  4745. }
  4746. *to = '\0';
  4747. }
  4748. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes. */
  4749. char *
  4750. mg_md5(char buf[33], ...)
  4751. {
  4752. md5_byte_t hash[16];
  4753. const char *p;
  4754. va_list ap;
  4755. md5_state_t ctx;
  4756. md5_init(&ctx);
  4757. va_start(ap, buf);
  4758. while ((p = va_arg(ap, const char *)) != NULL) {
  4759. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  4760. }
  4761. va_end(ap);
  4762. md5_finish(&ctx, hash);
  4763. bin2str(buf, hash, sizeof(hash));
  4764. return buf;
  4765. }
  4766. /* Check the user's password, return 1 if OK */
  4767. static int
  4768. check_password(const char *method,
  4769. const char *ha1,
  4770. const char *uri,
  4771. const char *nonce,
  4772. const char *nc,
  4773. const char *cnonce,
  4774. const char *qop,
  4775. const char *response)
  4776. {
  4777. char ha2[32 + 1], expected_response[32 + 1];
  4778. /* Some of the parameters may be NULL */
  4779. if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL
  4780. || qop == NULL
  4781. || response == NULL) {
  4782. return 0;
  4783. }
  4784. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  4785. if (strlen(response) != 32) {
  4786. return 0;
  4787. }
  4788. mg_md5(ha2, method, ":", uri, NULL);
  4789. mg_md5(expected_response,
  4790. ha1,
  4791. ":",
  4792. nonce,
  4793. ":",
  4794. nc,
  4795. ":",
  4796. cnonce,
  4797. ":",
  4798. qop,
  4799. ":",
  4800. ha2,
  4801. NULL);
  4802. return mg_strcasecmp(response, expected_response) == 0;
  4803. }
  4804. /* Use the global passwords file, if specified by auth_gpass option,
  4805. * or search for .htpasswd in the requested directory. */
  4806. static void
  4807. open_auth_file(struct mg_connection *conn, const char *path, struct file *filep)
  4808. {
  4809. if (conn != NULL && conn->ctx != NULL) {
  4810. char name[PATH_MAX];
  4811. const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
  4812. struct file file = STRUCT_FILE_INITIALIZER;
  4813. int truncated;
  4814. if (gpass != NULL) {
  4815. /* Use global passwords file */
  4816. if (!mg_fopen(conn, gpass, "r", filep)) {
  4817. #ifdef DEBUG
  4818. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  4819. #endif
  4820. }
  4821. /* Important: using local struct file to test path for is_directory
  4822. * flag. If filep is used, mg_stat() makes it appear as if auth file
  4823. * was opened. */
  4824. } else if (mg_stat(conn, path, &file) && file.is_directory) {
  4825. mg_snprintf(conn,
  4826. &truncated,
  4827. name,
  4828. sizeof(name),
  4829. "%s/%s",
  4830. path,
  4831. PASSWORDS_FILE_NAME);
  4832. if (truncated || !mg_fopen(conn, name, "r", filep)) {
  4833. #ifdef DEBUG
  4834. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  4835. #endif
  4836. }
  4837. } else {
  4838. /* Try to find .htpasswd in requested directory. */
  4839. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  4840. if (e[0] == '/') {
  4841. break;
  4842. }
  4843. }
  4844. mg_snprintf(conn,
  4845. &truncated,
  4846. name,
  4847. sizeof(name),
  4848. "%.*s/%s",
  4849. (int)(e - p),
  4850. p,
  4851. PASSWORDS_FILE_NAME);
  4852. if (truncated || !mg_fopen(conn, name, "r", filep)) {
  4853. #ifdef DEBUG
  4854. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  4855. #endif
  4856. }
  4857. }
  4858. }
  4859. }
  4860. /* Parsed Authorization header */
  4861. struct ah {
  4862. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  4863. };
  4864. /* Return 1 on success. Always initializes the ah structure. */
  4865. static int
  4866. parse_auth_header(struct mg_connection *conn,
  4867. char *buf,
  4868. size_t buf_size,
  4869. struct ah *ah)
  4870. {
  4871. char *name, *value, *s;
  4872. const char *auth_header;
  4873. uint64_t nonce;
  4874. if (!ah || !conn) {
  4875. return 0;
  4876. }
  4877. (void)memset(ah, 0, sizeof(*ah));
  4878. if ((auth_header = mg_get_header(conn, "Authorization")) == NULL
  4879. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  4880. return 0;
  4881. }
  4882. /* Make modifiable copy of the auth header */
  4883. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  4884. s = buf;
  4885. /* Parse authorization header */
  4886. for (;;) {
  4887. /* Gobble initial spaces */
  4888. while (isspace(*(unsigned char *)s)) {
  4889. s++;
  4890. }
  4891. name = skip_quoted(&s, "=", " ", 0);
  4892. /* Value is either quote-delimited, or ends at first comma or space. */
  4893. if (s[0] == '\"') {
  4894. s++;
  4895. value = skip_quoted(&s, "\"", " ", '\\');
  4896. if (s[0] == ',') {
  4897. s++;
  4898. }
  4899. } else {
  4900. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  4901. * spaces */
  4902. }
  4903. if (*name == '\0') {
  4904. break;
  4905. }
  4906. if (!strcmp(name, "username")) {
  4907. ah->user = value;
  4908. } else if (!strcmp(name, "cnonce")) {
  4909. ah->cnonce = value;
  4910. } else if (!strcmp(name, "response")) {
  4911. ah->response = value;
  4912. } else if (!strcmp(name, "uri")) {
  4913. ah->uri = value;
  4914. } else if (!strcmp(name, "qop")) {
  4915. ah->qop = value;
  4916. } else if (!strcmp(name, "nc")) {
  4917. ah->nc = value;
  4918. } else if (!strcmp(name, "nonce")) {
  4919. ah->nonce = value;
  4920. }
  4921. }
  4922. #ifndef NO_NONCE_CHECK
  4923. /* Read the nonce from the response. */
  4924. if (ah->nonce == NULL) {
  4925. return 0;
  4926. }
  4927. s = NULL;
  4928. nonce = strtoull(ah->nonce, &s, 10);
  4929. if ((s == NULL) || (*s != 0)) {
  4930. return 0;
  4931. }
  4932. /* Convert the nonce from the client to a number. */
  4933. nonce ^= conn->ctx->auth_nonce_mask;
  4934. /* The converted number corresponds to the time the nounce has been
  4935. * created. This should not be earlier than the server start. */
  4936. /* Server side nonce check is valuable in all situations but one:
  4937. * if the server restarts frequently, but the client should not see
  4938. * that, so the server should accept nonces from previous starts. */
  4939. /* However, the reasonable default is to not accept a nonce from a
  4940. * previous start, so if anyone changed the access rights between
  4941. * two restarts, a new login is required. */
  4942. if (nonce < (uint64_t)conn->ctx->start_time) {
  4943. /* nonce is from a previous start of the server and no longer valid
  4944. * (replay attack?) */
  4945. return 0;
  4946. }
  4947. /* Check if the nonce is too high, so it has not (yet) been used by the
  4948. * server. */
  4949. if (nonce >= ((uint64_t)conn->ctx->start_time + conn->ctx->nonce_count)) {
  4950. return 0;
  4951. }
  4952. #else
  4953. (void)nonce;
  4954. #endif
  4955. /* CGI needs it as REMOTE_USER */
  4956. if (ah->user != NULL) {
  4957. conn->request_info.remote_user = mg_strdup(ah->user);
  4958. } else {
  4959. return 0;
  4960. }
  4961. return 1;
  4962. }
  4963. static const char *
  4964. mg_fgets(char *buf, size_t size, struct file *filep, char **p)
  4965. {
  4966. const char *eof;
  4967. size_t len;
  4968. const char *memend;
  4969. if (!filep) {
  4970. return NULL;
  4971. }
  4972. if (filep->membuf != NULL && *p != NULL) {
  4973. memend = (const char *)&filep->membuf[filep->size];
  4974. /* Search for \n from p till the end of stream */
  4975. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  4976. if (eof != NULL) {
  4977. eof += 1; /* Include \n */
  4978. } else {
  4979. eof = memend; /* Copy remaining data */
  4980. }
  4981. len =
  4982. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  4983. memcpy(buf, *p, len);
  4984. buf[len] = '\0';
  4985. *p += len;
  4986. return len ? eof : NULL;
  4987. } else if (filep->fp != NULL) {
  4988. return fgets(buf, (int)size, filep->fp);
  4989. } else {
  4990. return NULL;
  4991. }
  4992. }
  4993. struct read_auth_file_struct {
  4994. struct mg_connection *conn;
  4995. struct ah ah;
  4996. char *domain;
  4997. char buf[256 + 256 + 40];
  4998. char *f_user;
  4999. char *f_domain;
  5000. char *f_ha1;
  5001. };
  5002. static int
  5003. read_auth_file(struct file *filep, struct read_auth_file_struct *workdata)
  5004. {
  5005. char *p;
  5006. int is_authorized = 0;
  5007. struct file fp;
  5008. size_t l;
  5009. if (!filep || !workdata) {
  5010. return 0;
  5011. }
  5012. /* Loop over passwords file */
  5013. p = (char *)filep->membuf;
  5014. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  5015. l = strlen(workdata->buf);
  5016. while (l > 0) {
  5017. if (isspace(workdata->buf[l - 1])
  5018. || iscntrl(workdata->buf[l - 1])) {
  5019. l--;
  5020. workdata->buf[l] = 0;
  5021. } else
  5022. break;
  5023. }
  5024. if (l < 1) {
  5025. continue;
  5026. }
  5027. workdata->f_user = workdata->buf;
  5028. if (workdata->f_user[0] == ':') {
  5029. /* user names may not contain a ':' and may not be empty,
  5030. * so lines starting with ':' may be used for a special purpose */
  5031. if (workdata->f_user[1] == '#') {
  5032. /* :# is a comment */
  5033. continue;
  5034. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  5035. if (mg_fopen(workdata->conn, workdata->f_user + 9, "r", &fp)) {
  5036. is_authorized = read_auth_file(&fp, workdata);
  5037. mg_fclose(&fp);
  5038. } else {
  5039. mg_cry(workdata->conn,
  5040. "%s: cannot open authorization file: %s",
  5041. __func__,
  5042. workdata->buf);
  5043. }
  5044. continue;
  5045. }
  5046. /* everything is invalid for the moment (might change in the
  5047. * future) */
  5048. mg_cry(workdata->conn,
  5049. "%s: syntax error in authorization file: %s",
  5050. __func__,
  5051. workdata->buf);
  5052. continue;
  5053. }
  5054. workdata->f_domain = strchr(workdata->f_user, ':');
  5055. if (workdata->f_domain == NULL) {
  5056. mg_cry(workdata->conn,
  5057. "%s: syntax error in authorization file: %s",
  5058. __func__,
  5059. workdata->buf);
  5060. continue;
  5061. }
  5062. *(workdata->f_domain) = 0;
  5063. (workdata->f_domain)++;
  5064. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  5065. if (workdata->f_ha1 == NULL) {
  5066. mg_cry(workdata->conn,
  5067. "%s: syntax error in authorization file: %s",
  5068. __func__,
  5069. workdata->buf);
  5070. continue;
  5071. }
  5072. *(workdata->f_ha1) = 0;
  5073. (workdata->f_ha1)++;
  5074. if (!strcmp(workdata->ah.user, workdata->f_user)
  5075. && !strcmp(workdata->domain, workdata->f_domain)) {
  5076. return check_password(workdata->conn->request_info.request_method,
  5077. workdata->f_ha1,
  5078. workdata->ah.uri,
  5079. workdata->ah.nonce,
  5080. workdata->ah.nc,
  5081. workdata->ah.cnonce,
  5082. workdata->ah.qop,
  5083. workdata->ah.response);
  5084. }
  5085. }
  5086. return is_authorized;
  5087. }
  5088. /* Authorize against the opened passwords file. Return 1 if authorized. */
  5089. static int
  5090. authorize(struct mg_connection *conn, struct file *filep)
  5091. {
  5092. struct read_auth_file_struct workdata;
  5093. char buf[MG_BUF_LEN];
  5094. if (!conn || !conn->ctx) {
  5095. return 0;
  5096. }
  5097. memset(&workdata, 0, sizeof(workdata));
  5098. workdata.conn = conn;
  5099. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  5100. return 0;
  5101. }
  5102. workdata.domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  5103. return read_auth_file(filep, &workdata);
  5104. }
  5105. /* Return 1 if request is authorised, 0 otherwise. */
  5106. static int
  5107. check_authorization(struct mg_connection *conn, const char *path)
  5108. {
  5109. char fname[PATH_MAX];
  5110. struct vec uri_vec, filename_vec;
  5111. const char *list;
  5112. struct file file = STRUCT_FILE_INITIALIZER;
  5113. int authorized = 1, truncated;
  5114. if (!conn || !conn->ctx) {
  5115. return 0;
  5116. }
  5117. list = conn->ctx->config[PROTECT_URI];
  5118. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  5119. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  5120. mg_snprintf(conn,
  5121. &truncated,
  5122. fname,
  5123. sizeof(fname),
  5124. "%.*s",
  5125. (int)filename_vec.len,
  5126. filename_vec.ptr);
  5127. if (truncated || !mg_fopen(conn, fname, "r", &file)) {
  5128. mg_cry(conn,
  5129. "%s: cannot open %s: %s",
  5130. __func__,
  5131. fname,
  5132. strerror(errno));
  5133. }
  5134. break;
  5135. }
  5136. }
  5137. if (!is_file_opened(&file)) {
  5138. open_auth_file(conn, path, &file);
  5139. }
  5140. if (is_file_opened(&file)) {
  5141. authorized = authorize(conn, &file);
  5142. mg_fclose(&file);
  5143. }
  5144. return authorized;
  5145. }
  5146. static void
  5147. send_authorization_request(struct mg_connection *conn)
  5148. {
  5149. char date[64];
  5150. time_t curtime = time(NULL);
  5151. if (conn && conn->ctx) {
  5152. uint64_t nonce = (uint64_t)(conn->ctx->start_time);
  5153. (void)pthread_mutex_lock(&conn->ctx->nonce_mutex);
  5154. nonce += conn->ctx->nonce_count;
  5155. ++conn->ctx->nonce_count;
  5156. (void)pthread_mutex_unlock(&conn->ctx->nonce_mutex);
  5157. nonce ^= conn->ctx->auth_nonce_mask;
  5158. conn->status_code = 401;
  5159. conn->must_close = 1;
  5160. gmt_time_string(date, sizeof(date), &curtime);
  5161. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  5162. send_no_cache_header(conn);
  5163. mg_printf(conn,
  5164. "Date: %s\r\n"
  5165. "Connection: %s\r\n"
  5166. "Content-Length: 0\r\n"
  5167. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  5168. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  5169. date,
  5170. suggest_connection_header(conn),
  5171. conn->ctx->config[AUTHENTICATION_DOMAIN],
  5172. nonce);
  5173. }
  5174. }
  5175. #if !defined(NO_FILES)
  5176. static int
  5177. is_authorized_for_put(struct mg_connection *conn)
  5178. {
  5179. if (conn) {
  5180. struct file file = STRUCT_FILE_INITIALIZER;
  5181. const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
  5182. int ret = 0;
  5183. if (passfile != NULL && mg_fopen(conn, passfile, "r", &file)) {
  5184. ret = authorize(conn, &file);
  5185. mg_fclose(&file);
  5186. }
  5187. return ret;
  5188. }
  5189. return 0;
  5190. }
  5191. #endif
  5192. int
  5193. mg_modify_passwords_file(const char *fname,
  5194. const char *domain,
  5195. const char *user,
  5196. const char *pass)
  5197. {
  5198. int found, i;
  5199. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  5200. FILE *fp, *fp2;
  5201. found = 0;
  5202. fp = fp2 = NULL;
  5203. /* Regard empty password as no password - remove user record. */
  5204. if (pass != NULL && pass[0] == '\0') {
  5205. pass = NULL;
  5206. }
  5207. /* Other arguments must not be empty */
  5208. if (fname == NULL || domain == NULL || user == NULL) {
  5209. return 0;
  5210. }
  5211. /* Using the given file format, user name and domain must not contain ':'
  5212. */
  5213. if (strchr(user, ':') != NULL) {
  5214. return 0;
  5215. }
  5216. if (strchr(domain, ':') != NULL) {
  5217. return 0;
  5218. }
  5219. /* Do not allow control characters like newline in user name and domain.
  5220. * Do not allow excessively long names either. */
  5221. for (i = 0; i < 255 && user[i] != 0; i++) {
  5222. if (iscntrl(user[i])) {
  5223. return 0;
  5224. }
  5225. }
  5226. if (user[i]) {
  5227. return 0;
  5228. }
  5229. for (i = 0; i < 255 && domain[i] != 0; i++) {
  5230. if (iscntrl(domain[i])) {
  5231. return 0;
  5232. }
  5233. }
  5234. if (domain[i]) {
  5235. return 0;
  5236. }
  5237. /* The maximum length of the path to the password file is limited */
  5238. if ((strlen(fname) + 4) >= PATH_MAX) {
  5239. return 0;
  5240. }
  5241. /* Create a temporary file name. Length has been checked before. */
  5242. strcpy(tmp, fname);
  5243. strcat(tmp, ".tmp");
  5244. /* Create the file if does not exist */
  5245. /* Use of fopen here is OK, since fname is only ASCII */
  5246. if ((fp = fopen(fname, "a+")) != NULL) {
  5247. (void)fclose(fp);
  5248. }
  5249. /* Open the given file and temporary file */
  5250. if ((fp = fopen(fname, "r")) == NULL) {
  5251. return 0;
  5252. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  5253. fclose(fp);
  5254. return 0;
  5255. }
  5256. /* Copy the stuff to temporary file */
  5257. while (fgets(line, sizeof(line), fp) != NULL) {
  5258. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  5259. continue;
  5260. }
  5261. u[255] = 0;
  5262. d[255] = 0;
  5263. if (!strcmp(u, user) && !strcmp(d, domain)) {
  5264. found++;
  5265. if (pass != NULL) {
  5266. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  5267. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  5268. }
  5269. } else {
  5270. fprintf(fp2, "%s", line);
  5271. }
  5272. }
  5273. /* If new user, just add it */
  5274. if (!found && pass != NULL) {
  5275. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  5276. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  5277. }
  5278. /* Close files */
  5279. fclose(fp);
  5280. fclose(fp2);
  5281. /* Put the temp file in place of real file */
  5282. IGNORE_UNUSED_RESULT(remove(fname));
  5283. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  5284. return 1;
  5285. }
  5286. static int
  5287. is_valid_port(unsigned long port)
  5288. {
  5289. return port < 0xffff;
  5290. }
  5291. static int
  5292. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  5293. {
  5294. struct addrinfo hints, *res, *ressave;
  5295. int func_ret = 0;
  5296. int gai_ret;
  5297. memset(&hints, 0, sizeof(struct addrinfo));
  5298. hints.ai_family = af;
  5299. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  5300. if (gai_ret != 0) {
  5301. /* gai_strerror could be used to convert gai_ret to a string */
  5302. /* POSIX return values: see
  5303. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  5304. */
  5305. /* Windows return values: see
  5306. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  5307. */
  5308. return 0;
  5309. }
  5310. ressave = res;
  5311. while (res) {
  5312. if (dstlen >= res->ai_addrlen) {
  5313. memcpy(dst, res->ai_addr, res->ai_addrlen);
  5314. func_ret = 1;
  5315. }
  5316. res = res->ai_next;
  5317. }
  5318. freeaddrinfo(ressave);
  5319. return func_ret;
  5320. }
  5321. static int
  5322. connect_socket(struct mg_context *ctx /* may be NULL */,
  5323. const char *host,
  5324. int port,
  5325. int use_ssl,
  5326. char *ebuf,
  5327. size_t ebuf_len,
  5328. SOCKET *sock /* output: socket, must not be NULL */,
  5329. union usa *sa /* output: socket address, must not be NULL */
  5330. )
  5331. {
  5332. int ip_ver = 0;
  5333. *sock = INVALID_SOCKET;
  5334. memset(sa, 0, sizeof(*sa));
  5335. if (ebuf_len > 0) {
  5336. *ebuf = 0;
  5337. }
  5338. if (host == NULL) {
  5339. mg_snprintf(NULL,
  5340. NULL, /* No truncation check for ebuf */
  5341. ebuf,
  5342. ebuf_len,
  5343. "%s",
  5344. "NULL host");
  5345. return 0;
  5346. }
  5347. if (port < 0 || !is_valid_port((unsigned)port)) {
  5348. mg_snprintf(NULL,
  5349. NULL, /* No truncation check for ebuf */
  5350. ebuf,
  5351. ebuf_len,
  5352. "%s",
  5353. "invalid port");
  5354. return 0;
  5355. }
  5356. #if !defined(NO_SSL)
  5357. if (use_ssl && (SSLv23_client_method == NULL)) {
  5358. mg_snprintf(NULL,
  5359. NULL, /* No truncation check for ebuf */
  5360. ebuf,
  5361. ebuf_len,
  5362. "%s",
  5363. "SSL is not initialized");
  5364. return 0;
  5365. }
  5366. #else
  5367. (void)use_ssl;
  5368. #endif
  5369. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  5370. sa->sin.sin_port = htons((uint16_t)port);
  5371. ip_ver = 4;
  5372. #ifdef USE_IPV6
  5373. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  5374. sa->sin6.sin6_port = htons((uint16_t)port);
  5375. ip_ver = 6;
  5376. } else if (host[0] == '[') {
  5377. /* While getaddrinfo on Windows will work with [::1],
  5378. * getaddrinfo on Linux only works with ::1 (without []). */
  5379. size_t l = strlen(host + 1);
  5380. char *h = (l > 1) ? mg_strdup(host + 1) : NULL;
  5381. if (h) {
  5382. h[l - 1] = 0;
  5383. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  5384. sa->sin6.sin6_port = htons((uint16_t)port);
  5385. ip_ver = 6;
  5386. }
  5387. mg_free(h);
  5388. }
  5389. #endif
  5390. }
  5391. if (ip_ver == 0) {
  5392. mg_snprintf(NULL,
  5393. NULL, /* No truncation check for ebuf */
  5394. ebuf,
  5395. ebuf_len,
  5396. "%s",
  5397. "host not found");
  5398. return 0;
  5399. }
  5400. if (ip_ver == 4) {
  5401. *sock = socket(PF_INET, SOCK_STREAM, 0);
  5402. }
  5403. #ifdef USE_IPV6
  5404. else if (ip_ver == 6) {
  5405. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  5406. }
  5407. #endif
  5408. if (*sock == INVALID_SOCKET) {
  5409. mg_snprintf(NULL,
  5410. NULL, /* No truncation check for ebuf */
  5411. ebuf,
  5412. ebuf_len,
  5413. "socket(): %s",
  5414. strerror(ERRNO));
  5415. return 0;
  5416. }
  5417. set_close_on_exec(*sock, fc(ctx));
  5418. if ((ip_ver == 4)
  5419. && (connect(*sock, (struct sockaddr *)&sa->sin, sizeof(sa->sin))
  5420. == 0)) {
  5421. /* connected with IPv4 */
  5422. return 1;
  5423. }
  5424. #ifdef USE_IPV6
  5425. if ((ip_ver == 6)
  5426. && (connect(*sock, (struct sockaddr *)&sa->sin6, sizeof(sa->sin6))
  5427. == 0)) {
  5428. /* connected with IPv6 */
  5429. return 1;
  5430. }
  5431. #endif
  5432. /* Not connected */
  5433. mg_snprintf(NULL,
  5434. NULL, /* No truncation check for ebuf */
  5435. ebuf,
  5436. ebuf_len,
  5437. "connect(%s:%d): %s",
  5438. host,
  5439. port,
  5440. strerror(ERRNO));
  5441. closesocket(*sock);
  5442. *sock = INVALID_SOCKET;
  5443. return 0;
  5444. }
  5445. int
  5446. mg_url_encode(const char *src, char *dst, size_t dst_len)
  5447. {
  5448. static const char *dont_escape = "._-$,;~()";
  5449. static const char *hex = "0123456789abcdef";
  5450. char *pos = dst;
  5451. const char *end = dst + dst_len - 1;
  5452. for (; *src != '\0' && pos < end; src++, pos++) {
  5453. if (isalnum(*(const unsigned char *)src)
  5454. || strchr(dont_escape, *(const unsigned char *)src) != NULL) {
  5455. *pos = *src;
  5456. } else if (pos + 2 < end) {
  5457. pos[0] = '%';
  5458. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  5459. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  5460. pos += 2;
  5461. } else {
  5462. break;
  5463. }
  5464. }
  5465. *pos = '\0';
  5466. return (*src == '\0') ? (int)(pos - dst) : -1;
  5467. }
  5468. static void
  5469. print_dir_entry(struct de *de)
  5470. {
  5471. char size[64], mod[64], href[PATH_MAX * 3 /* worst case */];
  5472. struct tm *tm;
  5473. if (de->file.is_directory) {
  5474. mg_snprintf(de->conn,
  5475. NULL, /* Buffer is big enough */
  5476. size,
  5477. sizeof(size),
  5478. "%s",
  5479. "[DIRECTORY]");
  5480. } else {
  5481. /* We use (signed) cast below because MSVC 6 compiler cannot
  5482. * convert unsigned __int64 to double. Sigh. */
  5483. if (de->file.size < 1024) {
  5484. mg_snprintf(de->conn,
  5485. NULL, /* Buffer is big enough */
  5486. size,
  5487. sizeof(size),
  5488. "%d",
  5489. (int)de->file.size);
  5490. } else if (de->file.size < 0x100000) {
  5491. mg_snprintf(de->conn,
  5492. NULL, /* Buffer is big enough */
  5493. size,
  5494. sizeof(size),
  5495. "%.1fk",
  5496. (double)de->file.size / 1024.0);
  5497. } else if (de->file.size < 0x40000000) {
  5498. mg_snprintf(de->conn,
  5499. NULL, /* Buffer is big enough */
  5500. size,
  5501. sizeof(size),
  5502. "%.1fM",
  5503. (double)de->file.size / 1048576);
  5504. } else {
  5505. mg_snprintf(de->conn,
  5506. NULL, /* Buffer is big enough */
  5507. size,
  5508. sizeof(size),
  5509. "%.1fG",
  5510. (double)de->file.size / 1073741824);
  5511. }
  5512. }
  5513. /* Note: mg_snprintf will not cause a buffer overflow above.
  5514. * So, string truncation checks are not required here. */
  5515. tm = localtime(&de->file.last_modified);
  5516. if (tm != NULL) {
  5517. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  5518. } else {
  5519. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  5520. mod[sizeof(mod) - 1] = '\0';
  5521. }
  5522. mg_url_encode(de->file_name, href, sizeof(href));
  5523. de->conn->num_bytes_sent +=
  5524. mg_printf(de->conn,
  5525. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  5526. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  5527. de->conn->request_info.local_uri,
  5528. href,
  5529. de->file.is_directory ? "/" : "",
  5530. de->file_name,
  5531. de->file.is_directory ? "/" : "",
  5532. mod,
  5533. size);
  5534. }
  5535. /* This function is called from send_directory() and used for
  5536. * sorting directory entries by size, or name, or modification time.
  5537. * On windows, __cdecl specification is needed in case if project is built
  5538. * with __stdcall convention. qsort always requires __cdels callback. */
  5539. static int WINCDECL
  5540. compare_dir_entries(const void *p1, const void *p2)
  5541. {
  5542. if (p1 && p2) {
  5543. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  5544. const char *query_string = a->conn->request_info.query_string;
  5545. int cmp_result = 0;
  5546. if (query_string == NULL) {
  5547. query_string = "na";
  5548. }
  5549. if (a->file.is_directory && !b->file.is_directory) {
  5550. return -1; /* Always put directories on top */
  5551. } else if (!a->file.is_directory && b->file.is_directory) {
  5552. return 1; /* Always put directories on top */
  5553. } else if (*query_string == 'n') {
  5554. cmp_result = strcmp(a->file_name, b->file_name);
  5555. } else if (*query_string == 's') {
  5556. cmp_result = (a->file.size == b->file.size)
  5557. ? 0
  5558. : ((a->file.size > b->file.size) ? 1 : -1);
  5559. } else if (*query_string == 'd') {
  5560. cmp_result =
  5561. (a->file.last_modified == b->file.last_modified)
  5562. ? 0
  5563. : ((a->file.last_modified > b->file.last_modified) ? 1
  5564. : -1);
  5565. }
  5566. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  5567. }
  5568. return 0;
  5569. }
  5570. static int
  5571. must_hide_file(struct mg_connection *conn, const char *path)
  5572. {
  5573. if (conn && conn->ctx) {
  5574. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  5575. const char *pattern = conn->ctx->config[HIDE_FILES];
  5576. return match_prefix(pw_pattern, strlen(pw_pattern), path) > 0
  5577. || (pattern != NULL
  5578. && match_prefix(pattern, strlen(pattern), path) > 0);
  5579. }
  5580. return 0;
  5581. }
  5582. static int
  5583. scan_directory(struct mg_connection *conn,
  5584. const char *dir,
  5585. void *data,
  5586. void (*cb)(struct de *, void *))
  5587. {
  5588. char path[PATH_MAX];
  5589. struct dirent *dp;
  5590. DIR *dirp;
  5591. struct de de;
  5592. int truncated;
  5593. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  5594. return 0;
  5595. } else {
  5596. de.conn = conn;
  5597. while ((dp = mg_readdir(dirp)) != NULL) {
  5598. /* Do not show current dir and hidden files */
  5599. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  5600. || must_hide_file(conn, dp->d_name)) {
  5601. continue;
  5602. }
  5603. mg_snprintf(
  5604. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  5605. /* If we don't memset stat structure to zero, mtime will have
  5606. * garbage and strftime() will segfault later on in
  5607. * print_dir_entry(). memset is required only if mg_stat()
  5608. * fails. For more details, see
  5609. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  5610. memset(&de.file, 0, sizeof(de.file));
  5611. if (truncated) {
  5612. /* If the path is not complete, skip processing. */
  5613. continue;
  5614. }
  5615. if (!mg_stat(conn, path, &de.file)) {
  5616. mg_cry(conn,
  5617. "%s: mg_stat(%s) failed: %s",
  5618. __func__,
  5619. path,
  5620. strerror(ERRNO));
  5621. }
  5622. de.file_name = dp->d_name;
  5623. cb(&de, data);
  5624. }
  5625. (void)mg_closedir(dirp);
  5626. }
  5627. return 1;
  5628. }
  5629. #if !defined(NO_FILES)
  5630. static int
  5631. remove_directory(struct mg_connection *conn, const char *dir)
  5632. {
  5633. char path[PATH_MAX];
  5634. struct dirent *dp;
  5635. DIR *dirp;
  5636. struct de de;
  5637. int truncated;
  5638. int ok = 1;
  5639. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  5640. return 0;
  5641. } else {
  5642. de.conn = conn;
  5643. while ((dp = mg_readdir(dirp)) != NULL) {
  5644. /* Do not show current dir (but show hidden files as they will
  5645. * also be removed) */
  5646. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  5647. continue;
  5648. }
  5649. mg_snprintf(
  5650. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  5651. /* If we don't memset stat structure to zero, mtime will have
  5652. * garbage and strftime() will segfault later on in
  5653. * print_dir_entry(). memset is required only if mg_stat()
  5654. * fails. For more details, see
  5655. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  5656. memset(&de.file, 0, sizeof(de.file));
  5657. if (truncated) {
  5658. /* Do not delete anything shorter */
  5659. ok = 0;
  5660. continue;
  5661. }
  5662. if (!mg_stat(conn, path, &de.file)) {
  5663. mg_cry(conn,
  5664. "%s: mg_stat(%s) failed: %s",
  5665. __func__,
  5666. path,
  5667. strerror(ERRNO));
  5668. ok = 0;
  5669. }
  5670. if (de.file.membuf == NULL) {
  5671. /* file is not in memory */
  5672. if (de.file.is_directory) {
  5673. if (remove_directory(conn, path) == 0) {
  5674. ok = 0;
  5675. }
  5676. } else {
  5677. if (mg_remove(conn, path) == 0) {
  5678. ok = 0;
  5679. }
  5680. }
  5681. } else {
  5682. /* file is in memory. It can not be deleted. */
  5683. ok = 0;
  5684. }
  5685. }
  5686. (void)mg_closedir(dirp);
  5687. IGNORE_UNUSED_RESULT(rmdir(dir));
  5688. }
  5689. return ok;
  5690. }
  5691. #endif
  5692. struct dir_scan_data {
  5693. struct de *entries;
  5694. unsigned int num_entries;
  5695. unsigned int arr_size;
  5696. };
  5697. /* Behaves like realloc(), but frees original pointer on failure */
  5698. static void *
  5699. realloc2(void *ptr, size_t size)
  5700. {
  5701. void *new_ptr = mg_realloc(ptr, size);
  5702. if (new_ptr == NULL) {
  5703. mg_free(ptr);
  5704. }
  5705. return new_ptr;
  5706. }
  5707. static void
  5708. dir_scan_callback(struct de *de, void *data)
  5709. {
  5710. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  5711. if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {
  5712. dsd->arr_size *= 2;
  5713. dsd->entries =
  5714. (struct de *)realloc2(dsd->entries,
  5715. dsd->arr_size * sizeof(dsd->entries[0]));
  5716. }
  5717. if (dsd->entries == NULL) {
  5718. /* TODO(lsm, low): propagate an error to the caller */
  5719. dsd->num_entries = 0;
  5720. } else {
  5721. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  5722. dsd->entries[dsd->num_entries].file = de->file;
  5723. dsd->entries[dsd->num_entries].conn = de->conn;
  5724. dsd->num_entries++;
  5725. }
  5726. }
  5727. static void
  5728. handle_directory_request(struct mg_connection *conn, const char *dir)
  5729. {
  5730. unsigned int i;
  5731. int sort_direction;
  5732. struct dir_scan_data data = {NULL, 0, 128};
  5733. char date[64];
  5734. time_t curtime = time(NULL);
  5735. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  5736. send_http_error(conn,
  5737. 500,
  5738. "Error: Cannot open directory\nopendir(%s): %s",
  5739. dir,
  5740. strerror(ERRNO));
  5741. return;
  5742. }
  5743. gmt_time_string(date, sizeof(date), &curtime);
  5744. if (!conn) {
  5745. return;
  5746. }
  5747. sort_direction = ((conn->request_info.query_string != NULL)
  5748. && (conn->request_info.query_string[1] == 'd'))
  5749. ? 'a'
  5750. : 'd';
  5751. conn->must_close = 1;
  5752. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  5753. send_static_cache_header(conn);
  5754. mg_printf(conn,
  5755. "Date: %s\r\n"
  5756. "Connection: close\r\n"
  5757. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  5758. date);
  5759. conn->num_bytes_sent +=
  5760. mg_printf(conn,
  5761. "<html><head><title>Index of %s</title>"
  5762. "<style>th {text-align: left;}</style></head>"
  5763. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  5764. "<tr><th><a href=\"?n%c\">Name</a></th>"
  5765. "<th><a href=\"?d%c\">Modified</a></th>"
  5766. "<th><a href=\"?s%c\">Size</a></th></tr>"
  5767. "<tr><td colspan=\"3\"><hr></td></tr>",
  5768. conn->request_info.local_uri,
  5769. conn->request_info.local_uri,
  5770. sort_direction,
  5771. sort_direction,
  5772. sort_direction);
  5773. /* Print first entry - link to a parent directory */
  5774. conn->num_bytes_sent +=
  5775. mg_printf(conn,
  5776. "<tr><td><a href=\"%s%s\">%s</a></td>"
  5777. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  5778. conn->request_info.local_uri,
  5779. "..",
  5780. "Parent directory",
  5781. "-",
  5782. "-");
  5783. /* Sort and print directory entries */
  5784. if (data.entries != NULL) {
  5785. qsort(data.entries,
  5786. (size_t)data.num_entries,
  5787. sizeof(data.entries[0]),
  5788. compare_dir_entries);
  5789. for (i = 0; i < data.num_entries; i++) {
  5790. print_dir_entry(&data.entries[i]);
  5791. mg_free(data.entries[i].file_name);
  5792. }
  5793. mg_free(data.entries);
  5794. }
  5795. conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");
  5796. conn->status_code = 200;
  5797. }
  5798. /* Send len bytes from the opened file to the client. */
  5799. static void
  5800. send_file_data(struct mg_connection *conn,
  5801. struct file *filep,
  5802. int64_t offset,
  5803. int64_t len)
  5804. {
  5805. char buf[MG_BUF_LEN];
  5806. int to_read, num_read, num_written;
  5807. int64_t size;
  5808. if (!filep || !conn) {
  5809. return;
  5810. }
  5811. /* Sanity check the offset */
  5812. size = (filep->size > INT64_MAX) ? INT64_MAX : (int64_t)(filep->size);
  5813. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  5814. if (len > 0 && filep->membuf != NULL && size > 0) {
  5815. /* file stored in memory */
  5816. if (len > size - offset) {
  5817. len = size - offset;
  5818. }
  5819. mg_write(conn, filep->membuf + offset, (size_t)len);
  5820. } else if (len > 0 && filep->fp != NULL) {
  5821. /* file stored on disk */
  5822. #if defined(__linux__)
  5823. /* sendfile is only available for Linux */
  5824. if ((conn->ssl == 0) && (conn->throttle == 0)
  5825. && (!mg_strcasecmp(conn->ctx->config[ALLOW_SENDFILE_CALL],
  5826. "yes"))) {
  5827. off_t sf_offs = (off_t)offset;
  5828. ssize_t sf_sent;
  5829. int sf_file = fileno(filep->fp);
  5830. int loop_cnt = 0;
  5831. do {
  5832. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  5833. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  5834. size_t sf_tosend =
  5835. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  5836. sf_sent =
  5837. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  5838. if (sf_sent > 0) {
  5839. conn->num_bytes_sent += sf_sent;
  5840. len -= sf_sent;
  5841. offset += sf_sent;
  5842. } else if (loop_cnt == 0) {
  5843. /* This file can not be sent using sendfile.
  5844. * This might be the case for pseudo-files in the
  5845. * /sys/ and /proc/ file system.
  5846. * Use the regular user mode copy code instead. */
  5847. break;
  5848. } else if (sf_sent == 0) {
  5849. /* No error, but 0 bytes sent. May be EOF? */
  5850. return;
  5851. }
  5852. loop_cnt++;
  5853. } while ((len > 0) && (sf_sent >= 0));
  5854. if (sf_sent > 0) {
  5855. return; /* OK */
  5856. }
  5857. /* sf_sent<0 means error, thus fall back to the classic way */
  5858. /* This is always the case, if sf_file is not a "normal" file,
  5859. * e.g., for sending data from the output of a CGI process. */
  5860. offset = (int64_t)sf_offs;
  5861. }
  5862. #endif
  5863. if ((offset > 0) && (fseeko(filep->fp, offset, SEEK_SET) != 0)) {
  5864. mg_cry(conn, "%s: fseeko() failed: %s", __func__, strerror(ERRNO));
  5865. send_http_error(
  5866. conn,
  5867. 500,
  5868. "%s",
  5869. "Error: Unable to access file at requested position.");
  5870. } else {
  5871. while (len > 0) {
  5872. /* Calculate how much to read from the file in the buffer */
  5873. to_read = sizeof(buf);
  5874. if ((int64_t)to_read > len) {
  5875. to_read = (int)len;
  5876. }
  5877. /* Read from file, exit the loop on error */
  5878. if ((num_read = (int)fread(buf, 1, (size_t)to_read, filep->fp))
  5879. <= 0) {
  5880. break;
  5881. }
  5882. /* Send read bytes to the client, exit the loop on error */
  5883. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  5884. != num_read) {
  5885. break;
  5886. }
  5887. /* Both read and were successful, adjust counters */
  5888. conn->num_bytes_sent += num_written;
  5889. len -= num_written;
  5890. }
  5891. }
  5892. }
  5893. }
  5894. static int
  5895. parse_range_header(const char *header, int64_t *a, int64_t *b)
  5896. {
  5897. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  5898. }
  5899. static void
  5900. construct_etag(char *buf, size_t buf_len, const struct file *filep)
  5901. {
  5902. if (filep != NULL && buf != NULL) {
  5903. mg_snprintf(NULL,
  5904. NULL, /* All calls to construct_etag use 64 byte buffer */
  5905. buf,
  5906. buf_len,
  5907. "\"%lx.%" INT64_FMT "\"",
  5908. (unsigned long)filep->last_modified,
  5909. filep->size);
  5910. }
  5911. }
  5912. static void
  5913. fclose_on_exec(struct file *filep, struct mg_connection *conn)
  5914. {
  5915. if (filep != NULL && filep->fp != NULL) {
  5916. #ifdef _WIN32
  5917. (void)conn; /* Unused. */
  5918. #else
  5919. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  5920. mg_cry(conn,
  5921. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  5922. __func__,
  5923. strerror(ERRNO));
  5924. }
  5925. #endif
  5926. }
  5927. }
  5928. static void
  5929. handle_static_file_request(struct mg_connection *conn,
  5930. const char *path,
  5931. struct file *filep,
  5932. const char *mime_type,
  5933. const char *additional_headers)
  5934. {
  5935. char date[64], lm[64], etag[64];
  5936. char range[128]; /* large enough, so there will be no overflow */
  5937. const char *msg = "OK", *hdr;
  5938. time_t curtime = time(NULL);
  5939. int64_t cl, r1, r2;
  5940. struct vec mime_vec;
  5941. int n, truncated;
  5942. char gz_path[PATH_MAX];
  5943. const char *encoding = "";
  5944. const char *cors1, *cors2, *cors3;
  5945. if (conn == NULL || conn->ctx == NULL || filep == NULL) {
  5946. return;
  5947. }
  5948. if (mime_type == NULL) {
  5949. get_mime_type(conn->ctx, path, &mime_vec);
  5950. } else {
  5951. mime_vec.ptr = mime_type;
  5952. mime_vec.len = strlen(mime_type);
  5953. }
  5954. if (filep->size > INT64_MAX) {
  5955. send_http_error(conn,
  5956. 500,
  5957. "Error: File size is too large to send\n%" INT64_FMT,
  5958. filep->size);
  5959. }
  5960. cl = (int64_t)filep->size;
  5961. conn->status_code = 200;
  5962. range[0] = '\0';
  5963. /* if this file is in fact a pre-gzipped file, rewrite its filename
  5964. * it's important to rewrite the filename after resolving
  5965. * the mime type from it, to preserve the actual file's type */
  5966. if (filep->gzipped) {
  5967. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  5968. if (truncated) {
  5969. send_http_error(conn,
  5970. 500,
  5971. "Error: Path of zipped file too long (%s)",
  5972. path);
  5973. return;
  5974. }
  5975. path = gz_path;
  5976. encoding = "Content-Encoding: gzip\r\n";
  5977. }
  5978. if (!mg_fopen(conn, path, "rb", filep)) {
  5979. send_http_error(conn,
  5980. 500,
  5981. "Error: Cannot open file\nfopen(%s): %s",
  5982. path,
  5983. strerror(ERRNO));
  5984. return;
  5985. }
  5986. fclose_on_exec(filep, conn);
  5987. /* If Range: header specified, act accordingly */
  5988. r1 = r2 = 0;
  5989. hdr = mg_get_header(conn, "Range");
  5990. if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 && r1 >= 0
  5991. && r2 >= 0) {
  5992. /* actually, range requests don't play well with a pre-gzipped
  5993. * file (since the range is specified in the uncompressed space) */
  5994. if (filep->gzipped) {
  5995. send_http_error(
  5996. conn,
  5997. 501,
  5998. "%s",
  5999. "Error: Range requests in gzipped files are not supported");
  6000. mg_fclose(filep);
  6001. return;
  6002. }
  6003. conn->status_code = 206;
  6004. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  6005. mg_snprintf(conn,
  6006. NULL, /* range buffer is big enough */
  6007. range,
  6008. sizeof(range),
  6009. "Content-Range: bytes "
  6010. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  6011. r1,
  6012. r1 + cl - 1,
  6013. filep->size);
  6014. msg = "Partial Content";
  6015. }
  6016. hdr = mg_get_header(conn, "Origin");
  6017. if (hdr) {
  6018. /* Cross-origin resource sharing (CORS), see
  6019. * http://www.html5rocks.com/en/tutorials/cors/,
  6020. * http://www.html5rocks.com/static/images/cors_server_flowchart.png -
  6021. * preflight is not supported for files. */
  6022. cors1 = "Access-Control-Allow-Origin: ";
  6023. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  6024. cors3 = "\r\n";
  6025. } else {
  6026. cors1 = cors2 = cors3 = "";
  6027. }
  6028. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
  6029. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  6030. gmt_time_string(date, sizeof(date), &curtime);
  6031. gmt_time_string(lm, sizeof(lm), &filep->last_modified);
  6032. construct_etag(etag, sizeof(etag), filep);
  6033. (void)mg_printf(conn,
  6034. "HTTP/1.1 %d %s\r\n"
  6035. "%s%s%s"
  6036. "Date: %s\r\n",
  6037. conn->status_code,
  6038. msg,
  6039. cors1,
  6040. cors2,
  6041. cors3,
  6042. date);
  6043. send_static_cache_header(conn);
  6044. (void)mg_printf(conn,
  6045. "Last-Modified: %s\r\n"
  6046. "Etag: %s\r\n"
  6047. "Content-Type: %.*s\r\n"
  6048. "Content-Length: %" INT64_FMT "\r\n"
  6049. "Connection: %s\r\n"
  6050. "Accept-Ranges: bytes\r\n"
  6051. "%s%s",
  6052. lm,
  6053. etag,
  6054. (int)mime_vec.len,
  6055. mime_vec.ptr,
  6056. cl,
  6057. suggest_connection_header(conn),
  6058. range,
  6059. encoding);
  6060. /* The previous code must not add any header starting with X- to make
  6061. * sure no one of the additional_headers is included twice */
  6062. if (additional_headers != NULL) {
  6063. (void)mg_printf(conn,
  6064. "%.*s\r\n\r\n",
  6065. (int)strlen(additional_headers),
  6066. additional_headers);
  6067. } else {
  6068. (void)mg_printf(conn, "\r\n");
  6069. }
  6070. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  6071. send_file_data(conn, filep, r1, cl);
  6072. }
  6073. mg_fclose(filep);
  6074. }
  6075. #if !defined(NO_CACHING)
  6076. static void
  6077. handle_not_modified_static_file_request(struct mg_connection *conn,
  6078. struct file *filep)
  6079. {
  6080. char date[64], lm[64], etag[64];
  6081. time_t curtime = time(NULL);
  6082. if (conn == NULL || filep == NULL) {
  6083. return;
  6084. }
  6085. conn->status_code = 304;
  6086. gmt_time_string(date, sizeof(date), &curtime);
  6087. gmt_time_string(lm, sizeof(lm), &filep->last_modified);
  6088. construct_etag(etag, sizeof(etag), filep);
  6089. (void)mg_printf(conn,
  6090. "HTTP/1.1 %d %s\r\n"
  6091. "Date: %s\r\n",
  6092. conn->status_code,
  6093. mg_get_response_code_text(conn, conn->status_code),
  6094. date);
  6095. send_static_cache_header(conn);
  6096. (void)mg_printf(conn,
  6097. "Last-Modified: %s\r\n"
  6098. "Etag: %s\r\n"
  6099. "Connection: %s\r\n"
  6100. "\r\n",
  6101. lm,
  6102. etag,
  6103. suggest_connection_header(conn));
  6104. }
  6105. #endif
  6106. void
  6107. mg_send_file(struct mg_connection *conn, const char *path)
  6108. {
  6109. mg_send_mime_file(conn, path, NULL);
  6110. }
  6111. void
  6112. mg_send_mime_file(struct mg_connection *conn,
  6113. const char *path,
  6114. const char *mime_type)
  6115. {
  6116. mg_send_mime_file2(conn, path, mime_type, NULL);
  6117. }
  6118. void
  6119. mg_send_mime_file2(struct mg_connection *conn,
  6120. const char *path,
  6121. const char *mime_type,
  6122. const char *additional_headers)
  6123. {
  6124. struct file file = STRUCT_FILE_INITIALIZER;
  6125. if (mg_stat(conn, path, &file)) {
  6126. if (file.is_directory) {
  6127. if (!conn) {
  6128. return;
  6129. }
  6130. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  6131. "yes")) {
  6132. handle_directory_request(conn, path);
  6133. } else {
  6134. send_http_error(conn,
  6135. 403,
  6136. "%s",
  6137. "Error: Directory listing denied");
  6138. }
  6139. } else {
  6140. handle_static_file_request(
  6141. conn, path, &file, mime_type, additional_headers);
  6142. }
  6143. } else {
  6144. send_http_error(conn, 404, "%s", "Error: File not found");
  6145. }
  6146. }
  6147. /* For a given PUT path, create all intermediate subdirectories.
  6148. * Return 0 if the path itself is a directory.
  6149. * Return 1 if the path leads to a file.
  6150. * Return -1 for if the path is too long.
  6151. * Return -2 if path can not be created.
  6152. */
  6153. static int
  6154. put_dir(struct mg_connection *conn, const char *path)
  6155. {
  6156. char buf[PATH_MAX];
  6157. const char *s, *p;
  6158. struct file file = STRUCT_FILE_INITIALIZER;
  6159. size_t len;
  6160. int res = 1;
  6161. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  6162. len = (size_t)(p - path);
  6163. if (len >= sizeof(buf)) {
  6164. /* path too long */
  6165. res = -1;
  6166. break;
  6167. }
  6168. memcpy(buf, path, len);
  6169. buf[len] = '\0';
  6170. /* Try to create intermediate directory */
  6171. DEBUG_TRACE("mkdir(%s)", buf);
  6172. if (!mg_stat(conn, buf, &file) && mg_mkdir(conn, buf, 0755) != 0) {
  6173. /* path does not exixt and can not be created */
  6174. res = -2;
  6175. break;
  6176. }
  6177. /* Is path itself a directory? */
  6178. if (p[1] == '\0') {
  6179. res = 0;
  6180. }
  6181. }
  6182. return res;
  6183. }
  6184. static void
  6185. remove_bad_file(const struct mg_connection *conn, const char *path)
  6186. {
  6187. int r = mg_remove(conn, path);
  6188. if (r != 0) {
  6189. mg_cry(conn, "%s: Cannot remove invalid file %s", __func__, path);
  6190. }
  6191. }
  6192. long long
  6193. mg_store_body(struct mg_connection *conn, const char *path)
  6194. {
  6195. char buf[MG_BUF_LEN];
  6196. long long len = 0;
  6197. int ret, n;
  6198. struct file fi;
  6199. if (conn->consumed_content != 0) {
  6200. mg_cry(conn, "%s: Contents already consumed", __func__);
  6201. return -11;
  6202. }
  6203. ret = put_dir(conn, path);
  6204. if (ret < 0) {
  6205. /* -1 for path too long,
  6206. * -2 for path can not be created. */
  6207. return ret;
  6208. }
  6209. if (ret != 1) {
  6210. /* Return 0 means, path itself is a directory. */
  6211. return 0;
  6212. }
  6213. if (mg_fopen(conn, path, "w", &fi) == 0) {
  6214. return -12;
  6215. }
  6216. ret = mg_read(conn, buf, sizeof(buf));
  6217. while (ret > 0) {
  6218. n = (int)fwrite(buf, 1, (size_t)ret, fi.fp);
  6219. if (n != ret) {
  6220. mg_fclose(&fi);
  6221. remove_bad_file(conn, path);
  6222. return -13;
  6223. }
  6224. ret = mg_read(conn, buf, sizeof(buf));
  6225. }
  6226. /* TODO: mg_fclose should return an error,
  6227. * and every caller should check and handle it. */
  6228. if (fclose(fi.fp) != 0) {
  6229. remove_bad_file(conn, path);
  6230. return -14;
  6231. }
  6232. return len;
  6233. }
  6234. /* Parse HTTP headers from the given buffer, advance buf pointer
  6235. * to the point where parsing stopped.
  6236. * All parameters must be valid pointers (not NULL).
  6237. * Return <0 on error. */
  6238. static int
  6239. parse_http_headers(char **buf, struct mg_request_info *ri)
  6240. {
  6241. int i;
  6242. ri->num_headers = 0;
  6243. for (i = 0; i < (int)ARRAY_SIZE(ri->http_headers); i++) {
  6244. char *dp = *buf;
  6245. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  6246. dp++;
  6247. }
  6248. if (dp == *buf) {
  6249. /* End of headers reached. */
  6250. break;
  6251. }
  6252. if (*dp != ':') {
  6253. /* This is not a valid field. */
  6254. return -1;
  6255. }
  6256. /* End of header key (*dp == ':') */
  6257. /* Truncate here and set the key name */
  6258. *dp = 0;
  6259. ri->http_headers[i].name = *buf;
  6260. do {
  6261. dp++;
  6262. } while (*dp == ' ');
  6263. /* The rest of the line is the value */
  6264. ri->http_headers[i].value = dp;
  6265. *buf = dp + strcspn(dp, "\r\n");
  6266. if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) {
  6267. *buf = NULL;
  6268. }
  6269. ri->num_headers = i + 1;
  6270. if (*buf) {
  6271. (*buf)[0] = 0;
  6272. (*buf)[1] = 0;
  6273. *buf += 2;
  6274. } else {
  6275. *buf = dp;
  6276. break;
  6277. }
  6278. if ((*buf)[0] == '\r') {
  6279. /* This is the end of the header */
  6280. break;
  6281. }
  6282. }
  6283. return ri->num_headers;
  6284. }
  6285. static int
  6286. is_valid_http_method(const char *method)
  6287. {
  6288. return !strcmp(method, "GET") /* HTTP (RFC 2616) */
  6289. || !strcmp(method, "POST") /* HTTP (RFC 2616) */
  6290. || !strcmp(method, "HEAD") /* HTTP (RFC 2616) */
  6291. || !strcmp(method, "PUT") /* HTTP (RFC 2616) */
  6292. || !strcmp(method, "DELETE") /* HTTP (RFC 2616) */
  6293. || !strcmp(method, "OPTIONS") /* HTTP (RFC 2616) */
  6294. /* TRACE method (RFC 2616) is not supported for security reasons */
  6295. || !strcmp(method, "CONNECT") /* HTTP (RFC 2616) */
  6296. || !strcmp(method, "PROPFIND") /* WEBDAV (RFC 2518) */
  6297. || !strcmp(method, "MKCOL") /* WEBDAV (RFC 2518) */
  6298. /* Unsupported WEBDAV Methods: */
  6299. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  6300. /* + 11 methods from RFC 3253 */
  6301. /* ORDERPATCH (RFC 3648) */
  6302. /* ACL (RFC 3744) */
  6303. /* SEARCH (RFC 5323) */
  6304. /* + MicroSoft extensions
  6305. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  6306. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  6307. || !strcmp(method, "PATCH"); /* PATCH method (RFC 5789) */
  6308. }
  6309. /* Parse HTTP request, fill in mg_request_info structure.
  6310. * This function modifies the buffer by NUL-terminating
  6311. * HTTP request components, header names and header values.
  6312. * Parameters:
  6313. * buf (in/out): pointer to the HTTP header to parse and split
  6314. * len (in): length of HTTP header buffer
  6315. * re (out): parsed header as mg_request_info
  6316. * buf and ri must be valid pointers (not NULL), len>0.
  6317. * Returns <0 on error. */
  6318. static int
  6319. parse_http_message(char *buf, int len, struct mg_request_info *ri)
  6320. {
  6321. int is_request, request_length;
  6322. char *start_line;
  6323. request_length = get_request_len(buf, len);
  6324. if (request_length > 0) {
  6325. /* Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_addr,
  6326. * remote_port */
  6327. ri->remote_user = ri->request_method = ri->request_uri =
  6328. ri->http_version = NULL;
  6329. ri->num_headers = 0;
  6330. buf[request_length - 1] = '\0';
  6331. /* RFC says that all initial whitespaces should be ingored */
  6332. while (*buf != '\0' && isspace(*(unsigned char *)buf)) {
  6333. buf++;
  6334. }
  6335. start_line = skip(&buf, "\r\n");
  6336. ri->request_method = skip(&start_line, " ");
  6337. ri->request_uri = skip(&start_line, " ");
  6338. ri->http_version = start_line;
  6339. /* HTTP message could be either HTTP request:
  6340. * "GET / HTTP/1.0 ..."
  6341. * or a HTTP response:
  6342. * "HTTP/1.0 200 OK ..."
  6343. * otherwise it is invalid.
  6344. */
  6345. is_request = is_valid_http_method(ri->request_method);
  6346. if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0)
  6347. || (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
  6348. /* Not a valid request or response: invalid */
  6349. return -1;
  6350. }
  6351. if (is_request) {
  6352. ri->http_version += 5;
  6353. }
  6354. if (parse_http_headers(&buf, ri) < 0) {
  6355. /* Error while parsing headers */
  6356. return -1;
  6357. }
  6358. }
  6359. return request_length;
  6360. }
  6361. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  6362. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  6363. * buffer (which marks the end of HTTP request). Buffer buf may already
  6364. * have some data. The length of the data is stored in nread.
  6365. * Upon every read operation, increase nread by the number of bytes read. */
  6366. static int
  6367. read_request(FILE *fp,
  6368. struct mg_connection *conn,
  6369. char *buf,
  6370. int bufsiz,
  6371. int *nread)
  6372. {
  6373. int request_len, n = 0;
  6374. struct timespec last_action_time;
  6375. double request_timeout;
  6376. if (!conn) {
  6377. return 0;
  6378. }
  6379. memset(&last_action_time, 0, sizeof(last_action_time));
  6380. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  6381. /* value of request_timeout is in seconds, config in milliseconds */
  6382. request_timeout = atof(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  6383. } else {
  6384. request_timeout = -1.0;
  6385. }
  6386. request_len = get_request_len(buf, *nread);
  6387. /* first time reading from this connection */
  6388. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  6389. while (
  6390. (conn->ctx->stop_flag == 0) && (*nread < bufsiz) && (request_len == 0)
  6391. && ((mg_difftimespec(&last_action_time, &(conn->req_time))
  6392. <= request_timeout) || (request_timeout < 0))
  6393. && ((n = pull(fp, conn, buf + *nread, bufsiz - *nread, request_timeout))
  6394. > 0)) {
  6395. *nread += n;
  6396. /* assert(*nread <= bufsiz); */
  6397. if (*nread > bufsiz) {
  6398. return -2;
  6399. }
  6400. request_len = get_request_len(buf, *nread);
  6401. if (request_timeout > 0.0) {
  6402. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  6403. }
  6404. }
  6405. return ((request_len <= 0) && (n <= 0)) ? -1 : request_len;
  6406. }
  6407. #if !defined(NO_FILES)
  6408. /* For given directory path, substitute it to valid index file.
  6409. * Return 1 if index file has been found, 0 if not found.
  6410. * If the file is found, it's stats is returned in stp. */
  6411. static int
  6412. substitute_index_file(struct mg_connection *conn,
  6413. char *path,
  6414. size_t path_len,
  6415. struct file *filep)
  6416. {
  6417. if (conn && conn->ctx) {
  6418. const char *list = conn->ctx->config[INDEX_FILES];
  6419. struct file file = STRUCT_FILE_INITIALIZER;
  6420. struct vec filename_vec;
  6421. size_t n = strlen(path);
  6422. int found = 0;
  6423. /* The 'path' given to us points to the directory. Remove all trailing
  6424. * directory separator characters from the end of the path, and
  6425. * then append single directory separator character. */
  6426. while (n > 0 && path[n - 1] == '/') {
  6427. n--;
  6428. }
  6429. path[n] = '/';
  6430. /* Traverse index files list. For each entry, append it to the given
  6431. * path and see if the file exists. If it exists, break the loop */
  6432. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6433. /* Ignore too long entries that may overflow path buffer */
  6434. if (filename_vec.len > path_len - (n + 2)) {
  6435. continue;
  6436. }
  6437. /* Prepare full path to the index file */
  6438. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6439. /* Does it exist? */
  6440. if (mg_stat(conn, path, &file)) {
  6441. /* Yes it does, break the loop */
  6442. *filep = file;
  6443. found = 1;
  6444. break;
  6445. }
  6446. }
  6447. /* If no index file exists, restore directory path */
  6448. if (!found) {
  6449. path[n] = '\0';
  6450. }
  6451. return found;
  6452. }
  6453. return 0;
  6454. }
  6455. #endif
  6456. #if !defined(NO_CACHING)
  6457. /* Return True if we should reply 304 Not Modified. */
  6458. static int
  6459. is_not_modified(const struct mg_connection *conn, const struct file *filep)
  6460. {
  6461. char etag[64];
  6462. const char *ims = mg_get_header(conn, "If-Modified-Since");
  6463. const char *inm = mg_get_header(conn, "If-None-Match");
  6464. construct_etag(etag, sizeof(etag), filep);
  6465. if (!filep) {
  6466. return 0;
  6467. }
  6468. return (inm != NULL && !mg_strcasecmp(etag, inm))
  6469. || (ims != NULL && (filep->last_modified <= parse_date_string(ims)));
  6470. }
  6471. #endif /* !NO_CACHING */
  6472. #if !defined(NO_CGI) || !defined(NO_FILES)
  6473. static int
  6474. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  6475. {
  6476. const char *expect, *body;
  6477. char buf[MG_BUF_LEN];
  6478. int to_read, nread, success = 0;
  6479. int64_t buffered_len;
  6480. double timeout = -1.0;
  6481. if (!conn) {
  6482. return 0;
  6483. }
  6484. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  6485. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  6486. }
  6487. expect = mg_get_header(conn, "Expect");
  6488. /* assert(fp != NULL); */
  6489. if (!fp) {
  6490. send_http_error(conn, 500, "%s", "Error: NULL File");
  6491. return 0;
  6492. }
  6493. if (conn->content_len == -1 && !conn->is_chunked) {
  6494. /* Content length is not specified by the client. */
  6495. send_http_error(conn,
  6496. 411,
  6497. "%s",
  6498. "Error: Client did not specify content length");
  6499. } else if ((expect != NULL)
  6500. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  6501. /* Client sent an "Expect: xyz" header and xyz is not 100-continue. */
  6502. send_http_error(conn,
  6503. 417,
  6504. "Error: Can not fulfill expectation %s",
  6505. expect);
  6506. } else {
  6507. if (expect != NULL) {
  6508. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  6509. conn->status_code = 100;
  6510. } else {
  6511. conn->status_code = 200;
  6512. }
  6513. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  6514. - conn->consumed_content;
  6515. /* assert(buffered_len >= 0); */
  6516. /* assert(conn->consumed_content == 0); */
  6517. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  6518. send_http_error(conn, 500, "%s", "Error: Size mismatch");
  6519. return 0;
  6520. }
  6521. if (buffered_len > 0) {
  6522. if ((int64_t)buffered_len > conn->content_len) {
  6523. buffered_len = (int)conn->content_len;
  6524. }
  6525. body = conn->buf + conn->request_len + conn->consumed_content;
  6526. push_all(conn->ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  6527. conn->consumed_content += buffered_len;
  6528. }
  6529. nread = 0;
  6530. while (conn->consumed_content < conn->content_len) {
  6531. to_read = sizeof(buf);
  6532. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  6533. to_read = (int)(conn->content_len - conn->consumed_content);
  6534. }
  6535. nread = pull(NULL, conn, buf, to_read, timeout);
  6536. if (nread <= 0
  6537. || push_all(conn->ctx, fp, sock, ssl, buf, nread) != nread) {
  6538. break;
  6539. }
  6540. conn->consumed_content += nread;
  6541. }
  6542. if (conn->consumed_content == conn->content_len) {
  6543. success = (nread >= 0);
  6544. }
  6545. /* Each error code path in this function must send an error */
  6546. if (!success) {
  6547. /* NOTE: Maybe some data has already been sent. */
  6548. /* TODO (low): If some data has been sent, a correct error
  6549. * reply can no longer be sent, so just close the connection */
  6550. send_http_error(conn, 500, "%s", "");
  6551. }
  6552. }
  6553. return success;
  6554. }
  6555. #endif
  6556. #if !defined(NO_CGI)
  6557. /* This structure helps to create an environment for the spawned CGI program.
  6558. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  6559. * last element must be NULL.
  6560. * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  6561. * strings must reside in a contiguous buffer. The end of the buffer is
  6562. * marked by two '\0' characters.
  6563. * We satisfy both worlds: we create an envp array (which is vars), all
  6564. * entries are actually pointers inside buf. */
  6565. struct cgi_environment {
  6566. struct mg_connection *conn;
  6567. /* Data block */
  6568. char *buf; /* Environment buffer */
  6569. size_t buflen; /* Space available in buf */
  6570. size_t bufused; /* Space taken in buf */
  6571. /* Index block */
  6572. char **var; /* char **envp */
  6573. size_t varlen; /* Number of variables available in var */
  6574. size_t varused; /* Number of variables stored in var */
  6575. };
  6576. static void addenv(struct cgi_environment *env,
  6577. PRINTF_FORMAT_STRING(const char *fmt),
  6578. ...) PRINTF_ARGS(2, 3);
  6579. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  6580. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  6581. static void
  6582. addenv(struct cgi_environment *env, const char *fmt, ...)
  6583. {
  6584. size_t n, space;
  6585. int truncated;
  6586. char *added;
  6587. va_list ap;
  6588. /* Calculate how much space is left in the buffer */
  6589. space = (env->buflen - env->bufused);
  6590. /* Calculate an estimate for the required space */
  6591. n = strlen(fmt) + 2 + 128;
  6592. do {
  6593. if (space <= n) {
  6594. /* Allocate new buffer */
  6595. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  6596. added = (char *)mg_realloc(env->buf, n);
  6597. if (!added) {
  6598. /* Out of memory */
  6599. mg_cry(env->conn,
  6600. "%s: Cannot allocate memory for CGI variable [%s]",
  6601. __func__,
  6602. fmt);
  6603. return;
  6604. }
  6605. env->buf = added;
  6606. env->buflen = n;
  6607. space = (env->buflen - env->bufused);
  6608. }
  6609. /* Make a pointer to the free space int the buffer */
  6610. added = env->buf + env->bufused;
  6611. /* Copy VARIABLE=VALUE\0 string into the free space */
  6612. va_start(ap, fmt);
  6613. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  6614. va_end(ap);
  6615. /* Do not add truncated strings to the environment */
  6616. if (truncated) {
  6617. /* Reallocate the buffer */
  6618. space = 0;
  6619. n = 1;
  6620. }
  6621. } while (truncated);
  6622. /* Calculate number of bytes added to the environment */
  6623. n = strlen(added) + 1;
  6624. env->bufused += n;
  6625. /* Now update the variable index */
  6626. space = (env->varlen - env->varused);
  6627. if (space < 2) {
  6628. mg_cry(env->conn,
  6629. "%s: Cannot register CGI variable [%s]",
  6630. __func__,
  6631. fmt);
  6632. return;
  6633. }
  6634. /* Append a pointer to the added string into the envp array */
  6635. env->var[env->varused] = added;
  6636. env->varused++;
  6637. }
  6638. static void
  6639. prepare_cgi_environment(struct mg_connection *conn,
  6640. const char *prog,
  6641. struct cgi_environment *env)
  6642. {
  6643. const char *s;
  6644. struct vec var_vec;
  6645. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  6646. int i, truncated;
  6647. if (conn == NULL || prog == NULL || env == NULL) {
  6648. return;
  6649. }
  6650. env->conn = conn;
  6651. env->buflen = CGI_ENVIRONMENT_SIZE;
  6652. env->bufused = 0;
  6653. env->buf = (char *)mg_malloc(env->buflen);
  6654. env->varlen = MAX_CGI_ENVIR_VARS;
  6655. env->varused = 0;
  6656. env->var = (char **)mg_malloc(env->buflen * sizeof(char *));
  6657. addenv(env, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  6658. addenv(env, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6659. addenv(env, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6660. addenv(env, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  6661. /* Prepare the environment block */
  6662. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  6663. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  6664. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  6665. #if defined(USE_IPV6)
  6666. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  6667. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  6668. } else
  6669. #endif
  6670. {
  6671. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  6672. }
  6673. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  6674. addenv(env, "REMOTE_ADDR=%s", src_addr);
  6675. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  6676. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  6677. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  6678. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  6679. /* SCRIPT_NAME */
  6680. addenv(env,
  6681. "SCRIPT_NAME=%.*s",
  6682. (int)strlen(conn->request_info.local_uri)
  6683. - ((conn->path_info == NULL) ? 0 : (int)strlen(conn->path_info)),
  6684. conn->request_info.local_uri);
  6685. addenv(env, "SCRIPT_FILENAME=%s", prog);
  6686. if (conn->path_info == NULL) {
  6687. addenv(env, "PATH_TRANSLATED=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6688. } else {
  6689. addenv(env,
  6690. "PATH_TRANSLATED=%s%s",
  6691. conn->ctx->config[DOCUMENT_ROOT],
  6692. conn->path_info);
  6693. }
  6694. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  6695. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  6696. addenv(env, "CONTENT_TYPE=%s", s);
  6697. }
  6698. if (conn->request_info.query_string != NULL) {
  6699. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  6700. }
  6701. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  6702. addenv(env, "CONTENT_LENGTH=%s", s);
  6703. }
  6704. if ((s = getenv("PATH")) != NULL) {
  6705. addenv(env, "PATH=%s", s);
  6706. }
  6707. if (conn->path_info != NULL) {
  6708. addenv(env, "PATH_INFO=%s", conn->path_info);
  6709. }
  6710. if (conn->status_code > 0) {
  6711. /* CGI error handler should show the status code */
  6712. addenv(env, "STATUS=%d", conn->status_code);
  6713. }
  6714. #if defined(_WIN32)
  6715. if ((s = getenv("COMSPEC")) != NULL) {
  6716. addenv(env, "COMSPEC=%s", s);
  6717. }
  6718. if ((s = getenv("SYSTEMROOT")) != NULL) {
  6719. addenv(env, "SYSTEMROOT=%s", s);
  6720. }
  6721. if ((s = getenv("SystemDrive")) != NULL) {
  6722. addenv(env, "SystemDrive=%s", s);
  6723. }
  6724. if ((s = getenv("ProgramFiles")) != NULL) {
  6725. addenv(env, "ProgramFiles=%s", s);
  6726. }
  6727. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  6728. addenv(env, "ProgramFiles(x86)=%s", s);
  6729. }
  6730. #else
  6731. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  6732. addenv(env, "LD_LIBRARY_PATH=%s", s);
  6733. }
  6734. #endif /* _WIN32 */
  6735. if ((s = getenv("PERLLIB")) != NULL) {
  6736. addenv(env, "PERLLIB=%s", s);
  6737. }
  6738. if (conn->request_info.remote_user != NULL) {
  6739. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  6740. addenv(env, "%s", "AUTH_TYPE=Digest");
  6741. }
  6742. /* Add all headers as HTTP_* variables */
  6743. for (i = 0; i < conn->request_info.num_headers; i++) {
  6744. (void)mg_snprintf(conn,
  6745. &truncated,
  6746. http_var_name,
  6747. sizeof(http_var_name),
  6748. "HTTP_%s",
  6749. conn->request_info.http_headers[i].name);
  6750. if (truncated) {
  6751. mg_cry(conn,
  6752. "%s: HTTP header variable too long [%s]",
  6753. __func__,
  6754. conn->request_info.http_headers[i].name);
  6755. continue;
  6756. }
  6757. /* Convert variable name into uppercase, and change - to _ */
  6758. for (p = http_var_name; *p != '\0'; p++) {
  6759. if (*p == '-') {
  6760. *p = '_';
  6761. }
  6762. *p = (char)toupper(*(unsigned char *)p);
  6763. }
  6764. addenv(env,
  6765. "%s=%s",
  6766. http_var_name,
  6767. conn->request_info.http_headers[i].value);
  6768. }
  6769. /* Add user-specified variables */
  6770. s = conn->ctx->config[CGI_ENVIRONMENT];
  6771. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  6772. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  6773. }
  6774. env->var[env->varused] = NULL;
  6775. env->buf[env->bufused] = '\0';
  6776. }
  6777. static void
  6778. handle_cgi_request(struct mg_connection *conn, const char *prog)
  6779. {
  6780. char *buf;
  6781. size_t buflen;
  6782. int headers_len, data_len, i, truncated;
  6783. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  6784. const char *status, *status_text, *connection_state;
  6785. char *pbuf, dir[PATH_MAX], *p;
  6786. struct mg_request_info ri;
  6787. struct cgi_environment blk;
  6788. FILE *in = NULL, *out = NULL, *err = NULL;
  6789. struct file fout = STRUCT_FILE_INITIALIZER;
  6790. pid_t pid = (pid_t)-1;
  6791. if (conn == NULL) {
  6792. return;
  6793. }
  6794. buf = NULL;
  6795. buflen = 16384;
  6796. prepare_cgi_environment(conn, prog, &blk);
  6797. /* CGI must be executed in its own directory. 'dir' must point to the
  6798. * directory containing executable program, 'p' must point to the
  6799. * executable program name relative to 'dir'. */
  6800. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  6801. if (truncated) {
  6802. mg_cry(conn, "Error: CGI program \"%s\": Path too long", prog);
  6803. send_http_error(conn, 500, "Error: %s", "CGI path too long");
  6804. goto done;
  6805. }
  6806. if ((p = strrchr(dir, '/')) != NULL) {
  6807. *p++ = '\0';
  6808. } else {
  6809. dir[0] = '.', dir[1] = '\0';
  6810. p = (char *)prog;
  6811. }
  6812. if (pipe(fdin) != 0 || pipe(fdout) != 0 || pipe(fderr) != 0) {
  6813. status = strerror(ERRNO);
  6814. mg_cry(conn,
  6815. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  6816. prog,
  6817. status);
  6818. send_http_error(conn, 500, "Error: Cannot create CGI pipe: %s", status);
  6819. goto done;
  6820. }
  6821. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  6822. if (pid == (pid_t)-1) {
  6823. status = strerror(ERRNO);
  6824. mg_cry(conn,
  6825. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  6826. prog,
  6827. status);
  6828. send_http_error(conn,
  6829. 500,
  6830. "Error: Cannot spawn CGI process [%s]: %s",
  6831. prog,
  6832. status);
  6833. goto done;
  6834. }
  6835. /* Make sure child closes all pipe descriptors. It must dup them to 0,1 */
  6836. set_close_on_exec((SOCKET)fdin[0], conn); /* stdin read */
  6837. set_close_on_exec((SOCKET)fdout[1], conn); /* stdout write */
  6838. set_close_on_exec((SOCKET)fderr[1], conn); /* stderr write */
  6839. set_close_on_exec((SOCKET)fdin[1], conn); /* stdin write */
  6840. set_close_on_exec((SOCKET)fdout[0], conn); /* stdout read */
  6841. set_close_on_exec((SOCKET)fderr[0], conn); /* stderr read */
  6842. /* Parent closes only one side of the pipes.
  6843. * If we don't mark them as closed, close() attempt before
  6844. * return from this function throws an exception on Windows.
  6845. * Windows does not like when closed descriptor is closed again. */
  6846. (void)close(fdin[0]);
  6847. (void)close(fdout[1]);
  6848. (void)close(fderr[1]);
  6849. fdin[0] = fdout[1] = fderr[1] = -1;
  6850. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  6851. status = strerror(ERRNO);
  6852. mg_cry(conn,
  6853. "Error: CGI program \"%s\": Can not open stdin: %s",
  6854. prog,
  6855. status);
  6856. send_http_error(conn,
  6857. 500,
  6858. "Error: CGI can not open fdin\nfopen: %s",
  6859. status);
  6860. goto done;
  6861. }
  6862. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  6863. status = strerror(ERRNO);
  6864. mg_cry(conn,
  6865. "Error: CGI program \"%s\": Can not open stdout: %s",
  6866. prog,
  6867. status);
  6868. send_http_error(conn,
  6869. 500,
  6870. "Error: CGI can not open fdout\nfopen: %s",
  6871. status);
  6872. goto done;
  6873. }
  6874. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  6875. status = strerror(ERRNO);
  6876. mg_cry(conn,
  6877. "Error: CGI program \"%s\": Can not open stderr: %s",
  6878. prog,
  6879. status);
  6880. send_http_error(conn,
  6881. 500,
  6882. "Error: CGI can not open fdout\nfopen: %s",
  6883. status);
  6884. goto done;
  6885. }
  6886. setbuf(in, NULL);
  6887. setbuf(out, NULL);
  6888. setbuf(err, NULL);
  6889. fout.fp = out;
  6890. if ((conn->request_info.content_length > 0) || conn->is_chunked) {
  6891. /* This is a POST/PUT request, or another request with body data. */
  6892. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  6893. /* Error sending the body data */
  6894. mg_cry(conn,
  6895. "Error: CGI program \"%s\": Forward body data failed",
  6896. prog);
  6897. goto done;
  6898. }
  6899. }
  6900. /* Close so child gets an EOF. */
  6901. fclose(in);
  6902. in = NULL;
  6903. fdin[1] = -1;
  6904. /* Now read CGI reply into a buffer. We need to set correct
  6905. * status code, thus we need to see all HTTP headers first.
  6906. * Do not send anything back to client, until we buffer in all
  6907. * HTTP headers. */
  6908. data_len = 0;
  6909. buf = (char *)mg_malloc(buflen);
  6910. if (buf == NULL) {
  6911. send_http_error(conn,
  6912. 500,
  6913. "Error: Not enough memory for CGI buffer (%u bytes)",
  6914. (unsigned int)buflen);
  6915. mg_cry(conn,
  6916. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  6917. "bytes)",
  6918. prog,
  6919. (unsigned int)buflen);
  6920. goto done;
  6921. }
  6922. headers_len = read_request(out, conn, buf, (int)buflen, &data_len);
  6923. if (headers_len <= 0) {
  6924. /* Could not parse the CGI response. Check if some error message on
  6925. * stderr. */
  6926. i = pull_all(err, conn, buf, (int)buflen);
  6927. if (i > 0) {
  6928. mg_cry(conn,
  6929. "Error: CGI program \"%s\" sent error "
  6930. "message: [%.*s]",
  6931. prog,
  6932. i,
  6933. buf);
  6934. send_http_error(conn,
  6935. 500,
  6936. "Error: CGI program \"%s\" sent error "
  6937. "message: [%.*s]",
  6938. prog,
  6939. i,
  6940. buf);
  6941. } else {
  6942. mg_cry(conn,
  6943. "Error: CGI program sent malformed or too big "
  6944. "(>%u bytes) HTTP headers: [%.*s]",
  6945. (unsigned)buflen,
  6946. data_len,
  6947. buf);
  6948. send_http_error(conn,
  6949. 500,
  6950. "Error: CGI program sent malformed or too big "
  6951. "(>%u bytes) HTTP headers: [%.*s]",
  6952. (unsigned)buflen,
  6953. data_len,
  6954. buf);
  6955. }
  6956. goto done;
  6957. }
  6958. pbuf = buf;
  6959. buf[headers_len - 1] = '\0';
  6960. parse_http_headers(&pbuf, &ri);
  6961. /* Make up and send the status line */
  6962. status_text = "OK";
  6963. if ((status = get_header(&ri, "Status")) != NULL) {
  6964. conn->status_code = atoi(status);
  6965. status_text = status;
  6966. while (isdigit(*(const unsigned char *)status_text)
  6967. || *status_text == ' ') {
  6968. status_text++;
  6969. }
  6970. } else if (get_header(&ri, "Location") != NULL) {
  6971. conn->status_code = 302;
  6972. } else {
  6973. conn->status_code = 200;
  6974. }
  6975. connection_state = get_header(&ri, "Connection");
  6976. if (!header_has_option(connection_state, "keep-alive")) {
  6977. conn->must_close = 1;
  6978. }
  6979. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  6980. /* Send headers */
  6981. for (i = 0; i < ri.num_headers; i++) {
  6982. mg_printf(conn,
  6983. "%s: %s\r\n",
  6984. ri.http_headers[i].name,
  6985. ri.http_headers[i].value);
  6986. }
  6987. mg_write(conn, "\r\n", 2);
  6988. /* Send chunk of data that may have been read after the headers */
  6989. conn->num_bytes_sent +=
  6990. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  6991. /* Read the rest of CGI output and send to the client */
  6992. send_file_data(conn, &fout, 0, INT64_MAX);
  6993. done:
  6994. mg_free(blk.var);
  6995. mg_free(blk.buf);
  6996. if (pid != (pid_t)-1) {
  6997. kill(pid, SIGKILL);
  6998. #if !defined(_WIN32)
  6999. {
  7000. int st;
  7001. while (waitpid(pid, &st, 0) != -1)
  7002. ; /* clean zombies */
  7003. }
  7004. #endif
  7005. }
  7006. if (fdin[0] != -1) {
  7007. close(fdin[0]);
  7008. }
  7009. if (fdout[1] != -1) {
  7010. close(fdout[1]);
  7011. }
  7012. if (in != NULL) {
  7013. fclose(in);
  7014. } else if (fdin[1] != -1) {
  7015. close(fdin[1]);
  7016. }
  7017. if (out != NULL) {
  7018. fclose(out);
  7019. } else if (fdout[0] != -1) {
  7020. close(fdout[0]);
  7021. }
  7022. if (err != NULL) {
  7023. fclose(err);
  7024. } else if (fderr[0] != -1) {
  7025. close(fderr[0]);
  7026. }
  7027. if (buf != NULL) {
  7028. mg_free(buf);
  7029. }
  7030. }
  7031. #endif /* !NO_CGI */
  7032. #if !defined(NO_FILES)
  7033. static void
  7034. mkcol(struct mg_connection *conn, const char *path)
  7035. {
  7036. int rc, body_len;
  7037. struct de de;
  7038. char date[64];
  7039. time_t curtime = time(NULL);
  7040. if (conn == NULL) {
  7041. return;
  7042. }
  7043. /* TODO (mid): Check the send_http_error situations in this function */
  7044. memset(&de.file, 0, sizeof(de.file));
  7045. if (!mg_stat(conn, path, &de.file)) {
  7046. mg_cry(conn,
  7047. "%s: mg_stat(%s) failed: %s",
  7048. __func__,
  7049. path,
  7050. strerror(ERRNO));
  7051. }
  7052. if (de.file.last_modified) {
  7053. /* TODO (high): This check does not seem to make any sense ! */
  7054. send_http_error(
  7055. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7056. return;
  7057. }
  7058. body_len = conn->data_len - conn->request_len;
  7059. if (body_len > 0) {
  7060. send_http_error(
  7061. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7062. return;
  7063. }
  7064. rc = mg_mkdir(conn, path, 0755);
  7065. if (rc == 0) {
  7066. conn->status_code = 201;
  7067. gmt_time_string(date, sizeof(date), &curtime);
  7068. mg_printf(conn,
  7069. "HTTP/1.1 %d Created\r\n"
  7070. "Date: %s\r\n",
  7071. conn->status_code,
  7072. date);
  7073. send_static_cache_header(conn);
  7074. mg_printf(conn,
  7075. "Content-Length: 0\r\n"
  7076. "Connection: %s\r\n\r\n",
  7077. suggest_connection_header(conn));
  7078. } else if (rc == -1) {
  7079. if (errno == EEXIST) {
  7080. send_http_error(
  7081. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7082. } else if (errno == EACCES) {
  7083. send_http_error(
  7084. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7085. } else if (errno == ENOENT) {
  7086. send_http_error(
  7087. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7088. } else {
  7089. send_http_error(conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  7090. }
  7091. }
  7092. }
  7093. static void
  7094. put_file(struct mg_connection *conn, const char *path)
  7095. {
  7096. struct file file = STRUCT_FILE_INITIALIZER;
  7097. const char *range;
  7098. int64_t r1, r2;
  7099. int rc;
  7100. char date[64];
  7101. time_t curtime = time(NULL);
  7102. if (conn == NULL) {
  7103. return;
  7104. }
  7105. if (mg_stat(conn, path, &file)) {
  7106. /* File already exists */
  7107. conn->status_code = 200;
  7108. if (file.is_directory) {
  7109. /* This is an already existing directory,
  7110. * so there is nothing to do for the server. */
  7111. rc = 0;
  7112. } else {
  7113. /* File exists and is not a directory. */
  7114. /* Can it be replaced? */
  7115. if (file.membuf != NULL) {
  7116. /* This is an "in-memory" file, that can not be replaced */
  7117. send_http_error(
  7118. conn,
  7119. 405,
  7120. "Error: Put not possible\nReplacing %s is not supported",
  7121. path);
  7122. return;
  7123. }
  7124. /* Check if the server may write this file */
  7125. if (access(path, W_OK) == 0) {
  7126. /* Access granted */
  7127. conn->status_code = 200;
  7128. rc = 1;
  7129. } else {
  7130. send_http_error(
  7131. conn,
  7132. 403,
  7133. "Error: Put not possible\nReplacing %s is not allowed",
  7134. path);
  7135. return;
  7136. }
  7137. }
  7138. } else {
  7139. /* File should be created */
  7140. conn->status_code = 201;
  7141. rc = put_dir(conn, path);
  7142. }
  7143. if (rc == 0) {
  7144. /* put_dir returns 0 if path is a directory */
  7145. gmt_time_string(date, sizeof(date), &curtime);
  7146. mg_printf(conn,
  7147. "HTTP/1.1 %d %s\r\n",
  7148. conn->status_code,
  7149. mg_get_response_code_text(NULL, conn->status_code));
  7150. send_no_cache_header(conn);
  7151. mg_printf(conn,
  7152. "Date: %s\r\n"
  7153. "Content-Length: 0\r\n"
  7154. "Connection: %s\r\n\r\n",
  7155. date,
  7156. suggest_connection_header(conn));
  7157. /* Request to create a directory has been fulfilled successfully.
  7158. * No need to put a file. */
  7159. return;
  7160. }
  7161. if (rc == -1) {
  7162. /* put_dir returns -1 if the path is too long */
  7163. send_http_error(conn,
  7164. 414,
  7165. "Error: Path too long\nput_dir(%s): %s",
  7166. path,
  7167. strerror(ERRNO));
  7168. return;
  7169. }
  7170. if (rc == -2) {
  7171. /* put_dir returns -2 if the directory can not be created */
  7172. send_http_error(conn,
  7173. 500,
  7174. "Error: Can not create directory\nput_dir(%s): %s",
  7175. path,
  7176. strerror(ERRNO));
  7177. return;
  7178. }
  7179. /* A file should be created or overwritten. */
  7180. if (!mg_fopen(conn, path, "wb+", &file) || file.fp == NULL) {
  7181. mg_fclose(&file);
  7182. send_http_error(conn,
  7183. 500,
  7184. "Error: Can not create file\nfopen(%s): %s",
  7185. path,
  7186. strerror(ERRNO));
  7187. return;
  7188. }
  7189. fclose_on_exec(&file, conn);
  7190. range = mg_get_header(conn, "Content-Range");
  7191. r1 = r2 = 0;
  7192. if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
  7193. conn->status_code = 206; /* Partial content */
  7194. fseeko(file.fp, r1, SEEK_SET);
  7195. }
  7196. if (!forward_body_data(conn, file.fp, INVALID_SOCKET, NULL)) {
  7197. /* forward_body_data failed.
  7198. * The error code has already been sent to the client,
  7199. * and conn->status_code is already set. */
  7200. mg_fclose(&file);
  7201. return;
  7202. }
  7203. gmt_time_string(date, sizeof(date), &curtime);
  7204. mg_printf(conn,
  7205. "HTTP/1.1 %d %s\r\n",
  7206. conn->status_code,
  7207. mg_get_response_code_text(NULL, conn->status_code));
  7208. send_no_cache_header(conn);
  7209. mg_printf(conn,
  7210. "Date: %s\r\n"
  7211. "Content-Length: 0\r\n"
  7212. "Connection: %s\r\n\r\n",
  7213. date,
  7214. suggest_connection_header(conn));
  7215. mg_fclose(&file);
  7216. }
  7217. static void
  7218. delete_file(struct mg_connection *conn, const char *path)
  7219. {
  7220. struct de de;
  7221. memset(&de.file, 0, sizeof(de.file));
  7222. if (!mg_stat(conn, path, &de.file)) {
  7223. /* mg_stat returns 0 if the file does not exist */
  7224. send_http_error(conn,
  7225. 404,
  7226. "Error: Cannot delete file\nFile %s not found",
  7227. path);
  7228. return;
  7229. }
  7230. if (de.file.membuf != NULL) {
  7231. /* the file is cached in memory */
  7232. send_http_error(
  7233. conn,
  7234. 405,
  7235. "Error: Delete not possible\nDeleting %s is not supported",
  7236. path);
  7237. return;
  7238. }
  7239. if (de.file.is_directory) {
  7240. if (remove_directory(conn, path)) {
  7241. /* Delete is successful: Return 204 without content. */
  7242. send_http_error(conn, 204, "%s", "");
  7243. } else {
  7244. /* Delete is not successful: Return 500 (Server error). */
  7245. send_http_error(conn, 500, "Error: Could not delete %s", path);
  7246. }
  7247. return;
  7248. }
  7249. /* This is an existing file (not a directory).
  7250. * Check if write permission is granted. */
  7251. if (access(path, W_OK) != 0) {
  7252. /* File is read only */
  7253. send_http_error(
  7254. conn,
  7255. 403,
  7256. "Error: Delete not possible\nDeleting %s is not allowed",
  7257. path);
  7258. return;
  7259. }
  7260. /* Try to delete it. */
  7261. if (mg_remove(conn, path) == 0) {
  7262. /* Delete was successful: Return 204 without content. */
  7263. send_http_error(conn, 204, "%s", "");
  7264. } else {
  7265. /* Delete not successful (file locked). */
  7266. send_http_error(conn,
  7267. 423,
  7268. "Error: Cannot delete file\nremove(%s): %s",
  7269. path,
  7270. strerror(ERRNO));
  7271. }
  7272. }
  7273. #endif /* !NO_FILES */
  7274. static void
  7275. send_ssi_file(struct mg_connection *, const char *, struct file *, int);
  7276. static void
  7277. do_ssi_include(struct mg_connection *conn,
  7278. const char *ssi,
  7279. char *tag,
  7280. int include_level)
  7281. {
  7282. char file_name[MG_BUF_LEN], path[512], *p;
  7283. struct file file = STRUCT_FILE_INITIALIZER;
  7284. size_t len;
  7285. int truncated = 0;
  7286. if (conn == NULL) {
  7287. return;
  7288. }
  7289. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  7290. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  7291. * always < MG_BUF_LEN. */
  7292. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  7293. /* File name is relative to the webserver root */
  7294. file_name[511] = 0;
  7295. (void)mg_snprintf(conn,
  7296. &truncated,
  7297. path,
  7298. sizeof(path),
  7299. "%s/%s",
  7300. conn->ctx->config[DOCUMENT_ROOT],
  7301. file_name);
  7302. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  7303. /* File name is relative to the webserver working directory
  7304. * or it is absolute system path */
  7305. file_name[511] = 0;
  7306. (void)
  7307. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  7308. } else if (sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1
  7309. || sscanf(tag, " \"%511[^\"]\"", file_name) == 1) {
  7310. /* File name is relative to the currect document */
  7311. file_name[511] = 0;
  7312. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  7313. if (!truncated) {
  7314. if ((p = strrchr(path, '/')) != NULL) {
  7315. p[1] = '\0';
  7316. }
  7317. len = strlen(path);
  7318. (void)mg_snprintf(conn,
  7319. &truncated,
  7320. path + len,
  7321. sizeof(path) - len,
  7322. "%s",
  7323. file_name);
  7324. }
  7325. } else {
  7326. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  7327. return;
  7328. }
  7329. if (truncated) {
  7330. mg_cry(conn, "SSI #include path length overflow: [%s]", tag);
  7331. return;
  7332. }
  7333. if (!mg_fopen(conn, path, "rb", &file)) {
  7334. mg_cry(conn,
  7335. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  7336. tag,
  7337. path,
  7338. strerror(ERRNO));
  7339. } else {
  7340. fclose_on_exec(&file, conn);
  7341. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  7342. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  7343. path) > 0) {
  7344. send_ssi_file(conn, path, &file, include_level + 1);
  7345. } else {
  7346. send_file_data(conn, &file, 0, INT64_MAX);
  7347. }
  7348. mg_fclose(&file);
  7349. }
  7350. }
  7351. #if !defined(NO_POPEN)
  7352. static void
  7353. do_ssi_exec(struct mg_connection *conn, char *tag)
  7354. {
  7355. char cmd[1024] = "";
  7356. struct file file = STRUCT_FILE_INITIALIZER;
  7357. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  7358. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  7359. } else {
  7360. cmd[1023] = 0;
  7361. if ((file.fp = popen(cmd, "r")) == NULL) {
  7362. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  7363. } else {
  7364. send_file_data(conn, &file, 0, INT64_MAX);
  7365. pclose(file.fp);
  7366. }
  7367. }
  7368. }
  7369. #endif /* !NO_POPEN */
  7370. static int
  7371. mg_fgetc(struct file *filep, int offset)
  7372. {
  7373. if (filep == NULL) {
  7374. return EOF;
  7375. }
  7376. if (filep->membuf != NULL && offset >= 0
  7377. && ((unsigned int)(offset)) < filep->size) {
  7378. return ((const unsigned char *)filep->membuf)[offset];
  7379. } else if (filep->fp != NULL) {
  7380. return fgetc(filep->fp);
  7381. } else {
  7382. return EOF;
  7383. }
  7384. }
  7385. static void
  7386. send_ssi_file(struct mg_connection *conn,
  7387. const char *path,
  7388. struct file *filep,
  7389. int include_level)
  7390. {
  7391. char buf[MG_BUF_LEN];
  7392. int ch, offset, len, in_ssi_tag;
  7393. if (include_level > 10) {
  7394. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  7395. return;
  7396. }
  7397. in_ssi_tag = len = offset = 0;
  7398. while ((ch = mg_fgetc(filep, offset)) != EOF) {
  7399. if (in_ssi_tag && ch == '>') {
  7400. in_ssi_tag = 0;
  7401. buf[len++] = (char)ch;
  7402. buf[len] = '\0';
  7403. /* assert(len <= (int) sizeof(buf)); */
  7404. if (len > (int)sizeof(buf)) {
  7405. break;
  7406. }
  7407. if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
  7408. /* Not an SSI tag, pass it */
  7409. (void)mg_write(conn, buf, (size_t)len);
  7410. } else {
  7411. if (!memcmp(buf + 5, "include", 7)) {
  7412. do_ssi_include(conn, path, buf + 12, include_level);
  7413. #if !defined(NO_POPEN)
  7414. } else if (!memcmp(buf + 5, "exec", 4)) {
  7415. do_ssi_exec(conn, buf + 9);
  7416. #endif /* !NO_POPEN */
  7417. } else {
  7418. mg_cry(conn,
  7419. "%s: unknown SSI "
  7420. "command: \"%s\"",
  7421. path,
  7422. buf);
  7423. }
  7424. }
  7425. len = 0;
  7426. } else if (in_ssi_tag) {
  7427. if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
  7428. /* Not an SSI tag */
  7429. in_ssi_tag = 0;
  7430. } else if (len == (int)sizeof(buf) - 2) {
  7431. mg_cry(conn, "%s: SSI tag is too large", path);
  7432. len = 0;
  7433. }
  7434. buf[len++] = (char)(ch & 0xff);
  7435. } else if (ch == '<') {
  7436. in_ssi_tag = 1;
  7437. if (len > 0) {
  7438. mg_write(conn, buf, (size_t)len);
  7439. }
  7440. len = 0;
  7441. buf[len++] = (char)(ch & 0xff);
  7442. } else {
  7443. buf[len++] = (char)(ch & 0xff);
  7444. if (len == (int)sizeof(buf)) {
  7445. mg_write(conn, buf, (size_t)len);
  7446. len = 0;
  7447. }
  7448. }
  7449. }
  7450. /* Send the rest of buffered data */
  7451. if (len > 0) {
  7452. mg_write(conn, buf, (size_t)len);
  7453. }
  7454. }
  7455. static void
  7456. handle_ssi_file_request(struct mg_connection *conn,
  7457. const char *path,
  7458. struct file *filep)
  7459. {
  7460. char date[64];
  7461. time_t curtime = time(NULL);
  7462. const char *cors1, *cors2, *cors3;
  7463. if (conn == NULL || path == NULL || filep == NULL) {
  7464. return;
  7465. }
  7466. if (mg_get_header(conn, "Origin")) {
  7467. /* Cross-origin resource sharing (CORS). */
  7468. cors1 = "Access-Control-Allow-Origin: ";
  7469. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  7470. cors3 = "\r\n";
  7471. } else {
  7472. cors1 = cors2 = cors3 = "";
  7473. }
  7474. if (!mg_fopen(conn, path, "rb", filep)) {
  7475. /* File exists (precondition for calling this function),
  7476. * but can not be opened by the server. */
  7477. send_http_error(conn,
  7478. 500,
  7479. "Error: Cannot read file\nfopen(%s): %s",
  7480. path,
  7481. strerror(ERRNO));
  7482. } else {
  7483. conn->must_close = 1;
  7484. gmt_time_string(date, sizeof(date), &curtime);
  7485. fclose_on_exec(filep, conn);
  7486. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  7487. send_no_cache_header(conn);
  7488. mg_printf(conn,
  7489. "%s%s%s"
  7490. "Date: %s\r\n"
  7491. "Content-Type: text/html\r\n"
  7492. "Connection: %s\r\n\r\n",
  7493. cors1,
  7494. cors2,
  7495. cors3,
  7496. date,
  7497. suggest_connection_header(conn));
  7498. send_ssi_file(conn, path, filep, 0);
  7499. mg_fclose(filep);
  7500. }
  7501. }
  7502. #if !defined(NO_FILES)
  7503. static void
  7504. send_options(struct mg_connection *conn)
  7505. {
  7506. char date[64];
  7507. time_t curtime = time(NULL);
  7508. if (!conn) {
  7509. return;
  7510. }
  7511. conn->status_code = 200;
  7512. conn->must_close = 1;
  7513. gmt_time_string(date, sizeof(date), &curtime);
  7514. mg_printf(conn,
  7515. "HTTP/1.1 200 OK\r\n"
  7516. "Date: %s\r\n"
  7517. /* TODO: "Cache-Control" (?) */
  7518. "Connection: %s\r\n"
  7519. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  7520. "PROPFIND, MKCOL\r\n"
  7521. "DAV: 1\r\n\r\n",
  7522. date,
  7523. suggest_connection_header(conn));
  7524. }
  7525. /* Writes PROPFIND properties for a collection element */
  7526. static void
  7527. print_props(struct mg_connection *conn, const char *uri, struct file *filep)
  7528. {
  7529. char mtime[64];
  7530. if (conn == NULL || uri == NULL || filep == NULL) {
  7531. return;
  7532. }
  7533. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  7534. conn->num_bytes_sent +=
  7535. mg_printf(conn,
  7536. "<d:response>"
  7537. "<d:href>%s</d:href>"
  7538. "<d:propstat>"
  7539. "<d:prop>"
  7540. "<d:resourcetype>%s</d:resourcetype>"
  7541. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  7542. "<d:getlastmodified>%s</d:getlastmodified>"
  7543. "</d:prop>"
  7544. "<d:status>HTTP/1.1 200 OK</d:status>"
  7545. "</d:propstat>"
  7546. "</d:response>\n",
  7547. uri,
  7548. filep->is_directory ? "<d:collection/>" : "",
  7549. filep->size,
  7550. mtime);
  7551. }
  7552. static void
  7553. print_dav_dir_entry(struct de *de, void *data)
  7554. {
  7555. char href[PATH_MAX];
  7556. char href_encoded[PATH_MAX * 3 /* worst case */];
  7557. int truncated;
  7558. struct mg_connection *conn = (struct mg_connection *)data;
  7559. if (!de || !conn) {
  7560. return;
  7561. }
  7562. mg_snprintf(conn,
  7563. &truncated,
  7564. href,
  7565. sizeof(href),
  7566. "%s%s",
  7567. conn->request_info.local_uri,
  7568. de->file_name);
  7569. if (!truncated) {
  7570. mg_url_encode(href, href_encoded, PATH_MAX * 3);
  7571. print_props(conn, href_encoded, &de->file);
  7572. }
  7573. }
  7574. static void
  7575. handle_propfind(struct mg_connection *conn,
  7576. const char *path,
  7577. struct file *filep)
  7578. {
  7579. const char *depth = mg_get_header(conn, "Depth");
  7580. char date[64];
  7581. time_t curtime = time(NULL);
  7582. gmt_time_string(date, sizeof(date), &curtime);
  7583. if (!conn || !path || !filep || !conn->ctx) {
  7584. return;
  7585. }
  7586. conn->must_close = 1;
  7587. conn->status_code = 207;
  7588. mg_printf(conn,
  7589. "HTTP/1.1 207 Multi-Status\r\n"
  7590. "Date: %s\r\n",
  7591. date);
  7592. send_static_cache_header(conn);
  7593. mg_printf(conn,
  7594. "Connection: %s\r\n"
  7595. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  7596. suggest_connection_header(conn));
  7597. conn->num_bytes_sent +=
  7598. mg_printf(conn,
  7599. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  7600. "<d:multistatus xmlns:d='DAV:'>\n");
  7601. /* Print properties for the requested resource itself */
  7602. print_props(conn, conn->request_info.local_uri, filep);
  7603. /* If it is a directory, print directory entries too if Depth is not 0 */
  7604. if (filep && filep->is_directory
  7605. && !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")
  7606. && (depth == NULL || strcmp(depth, "0") != 0)) {
  7607. scan_directory(conn, path, conn, &print_dav_dir_entry);
  7608. }
  7609. conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");
  7610. }
  7611. #endif
  7612. void
  7613. mg_lock_connection(struct mg_connection *conn)
  7614. {
  7615. if (conn) {
  7616. (void)pthread_mutex_lock(&conn->mutex);
  7617. }
  7618. }
  7619. void
  7620. mg_unlock_connection(struct mg_connection *conn)
  7621. {
  7622. if (conn) {
  7623. (void)pthread_mutex_unlock(&conn->mutex);
  7624. }
  7625. }
  7626. void
  7627. mg_lock_context(struct mg_context *ctx)
  7628. {
  7629. if (ctx) {
  7630. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  7631. }
  7632. }
  7633. void
  7634. mg_unlock_context(struct mg_context *ctx)
  7635. {
  7636. if (ctx) {
  7637. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  7638. }
  7639. }
  7640. #if defined(USE_TIMERS)
  7641. #include "timer.inl"
  7642. #endif /* USE_TIMERS */
  7643. #ifdef USE_LUA
  7644. #include "mod_lua.inl"
  7645. #endif /* USE_LUA */
  7646. #ifdef USE_DUKTAPE
  7647. #include "mod_duktape.inl"
  7648. #endif /* USE_DUKTAPE */
  7649. #if defined(USE_WEBSOCKET)
  7650. /* START OF SHA-1 code
  7651. * Copyright(c) By Steve Reid <steve@edmweb.com> */
  7652. #define SHA1HANDSOFF
  7653. /* According to current tests (May 2015), the <solarisfixes.h> is not required.
  7654. *
  7655. * #if defined(__sun)
  7656. * #include "solarisfixes.h"
  7657. * #endif
  7658. */
  7659. static int
  7660. is_big_endian(void)
  7661. {
  7662. static const int n = 1;
  7663. return ((char *)&n)[0] == 0;
  7664. }
  7665. union char64long16 {
  7666. unsigned char c[64];
  7667. uint32_t l[16];
  7668. };
  7669. #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
  7670. static uint32_t
  7671. blk0(union char64long16 *block, int i)
  7672. {
  7673. /* Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN */
  7674. if (!is_big_endian()) {
  7675. block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00)
  7676. | (rol(block->l[i], 8) & 0x00FF00FF);
  7677. }
  7678. return block->l[i];
  7679. }
  7680. #define blk(i) \
  7681. (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] \
  7682. ^ block->l[(i + 2) & 15] ^ block->l[i & 15], \
  7683. 1))
  7684. #define R0(v, w, x, y, z, i) \
  7685. z += ((w & (x ^ y)) ^ y) + blk0(block, i) + 0x5A827999 + rol(v, 5); \
  7686. w = rol(w, 30);
  7687. #define R1(v, w, x, y, z, i) \
  7688. z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \
  7689. w = rol(w, 30);
  7690. #define R2(v, w, x, y, z, i) \
  7691. z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \
  7692. w = rol(w, 30);
  7693. #define R3(v, w, x, y, z, i) \
  7694. z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \
  7695. w = rol(w, 30);
  7696. #define R4(v, w, x, y, z, i) \
  7697. z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \
  7698. w = rol(w, 30);
  7699. typedef struct {
  7700. uint32_t state[5];
  7701. uint32_t count[2];
  7702. unsigned char buffer[64];
  7703. } SHA1_CTX;
  7704. static void
  7705. SHA1Transform(uint32_t state[5], const unsigned char buffer[64])
  7706. {
  7707. uint32_t a, b, c, d, e;
  7708. union char64long16 block[1];
  7709. memcpy(block, buffer, 64);
  7710. a = state[0];
  7711. b = state[1];
  7712. c = state[2];
  7713. d = state[3];
  7714. e = state[4];
  7715. R0(a, b, c, d, e, 0);
  7716. R0(e, a, b, c, d, 1);
  7717. R0(d, e, a, b, c, 2);
  7718. R0(c, d, e, a, b, 3);
  7719. R0(b, c, d, e, a, 4);
  7720. R0(a, b, c, d, e, 5);
  7721. R0(e, a, b, c, d, 6);
  7722. R0(d, e, a, b, c, 7);
  7723. R0(c, d, e, a, b, 8);
  7724. R0(b, c, d, e, a, 9);
  7725. R0(a, b, c, d, e, 10);
  7726. R0(e, a, b, c, d, 11);
  7727. R0(d, e, a, b, c, 12);
  7728. R0(c, d, e, a, b, 13);
  7729. R0(b, c, d, e, a, 14);
  7730. R0(a, b, c, d, e, 15);
  7731. R1(e, a, b, c, d, 16);
  7732. R1(d, e, a, b, c, 17);
  7733. R1(c, d, e, a, b, 18);
  7734. R1(b, c, d, e, a, 19);
  7735. R2(a, b, c, d, e, 20);
  7736. R2(e, a, b, c, d, 21);
  7737. R2(d, e, a, b, c, 22);
  7738. R2(c, d, e, a, b, 23);
  7739. R2(b, c, d, e, a, 24);
  7740. R2(a, b, c, d, e, 25);
  7741. R2(e, a, b, c, d, 26);
  7742. R2(d, e, a, b, c, 27);
  7743. R2(c, d, e, a, b, 28);
  7744. R2(b, c, d, e, a, 29);
  7745. R2(a, b, c, d, e, 30);
  7746. R2(e, a, b, c, d, 31);
  7747. R2(d, e, a, b, c, 32);
  7748. R2(c, d, e, a, b, 33);
  7749. R2(b, c, d, e, a, 34);
  7750. R2(a, b, c, d, e, 35);
  7751. R2(e, a, b, c, d, 36);
  7752. R2(d, e, a, b, c, 37);
  7753. R2(c, d, e, a, b, 38);
  7754. R2(b, c, d, e, a, 39);
  7755. R3(a, b, c, d, e, 40);
  7756. R3(e, a, b, c, d, 41);
  7757. R3(d, e, a, b, c, 42);
  7758. R3(c, d, e, a, b, 43);
  7759. R3(b, c, d, e, a, 44);
  7760. R3(a, b, c, d, e, 45);
  7761. R3(e, a, b, c, d, 46);
  7762. R3(d, e, a, b, c, 47);
  7763. R3(c, d, e, a, b, 48);
  7764. R3(b, c, d, e, a, 49);
  7765. R3(a, b, c, d, e, 50);
  7766. R3(e, a, b, c, d, 51);
  7767. R3(d, e, a, b, c, 52);
  7768. R3(c, d, e, a, b, 53);
  7769. R3(b, c, d, e, a, 54);
  7770. R3(a, b, c, d, e, 55);
  7771. R3(e, a, b, c, d, 56);
  7772. R3(d, e, a, b, c, 57);
  7773. R3(c, d, e, a, b, 58);
  7774. R3(b, c, d, e, a, 59);
  7775. R4(a, b, c, d, e, 60);
  7776. R4(e, a, b, c, d, 61);
  7777. R4(d, e, a, b, c, 62);
  7778. R4(c, d, e, a, b, 63);
  7779. R4(b, c, d, e, a, 64);
  7780. R4(a, b, c, d, e, 65);
  7781. R4(e, a, b, c, d, 66);
  7782. R4(d, e, a, b, c, 67);
  7783. R4(c, d, e, a, b, 68);
  7784. R4(b, c, d, e, a, 69);
  7785. R4(a, b, c, d, e, 70);
  7786. R4(e, a, b, c, d, 71);
  7787. R4(d, e, a, b, c, 72);
  7788. R4(c, d, e, a, b, 73);
  7789. R4(b, c, d, e, a, 74);
  7790. R4(a, b, c, d, e, 75);
  7791. R4(e, a, b, c, d, 76);
  7792. R4(d, e, a, b, c, 77);
  7793. R4(c, d, e, a, b, 78);
  7794. R4(b, c, d, e, a, 79);
  7795. state[0] += a;
  7796. state[1] += b;
  7797. state[2] += c;
  7798. state[3] += d;
  7799. state[4] += e;
  7800. a = b = c = d = e = 0;
  7801. memset(block, '\0', sizeof(block));
  7802. }
  7803. static void
  7804. SHA1Init(SHA1_CTX *context)
  7805. {
  7806. context->state[0] = 0x67452301;
  7807. context->state[1] = 0xEFCDAB89;
  7808. context->state[2] = 0x98BADCFE;
  7809. context->state[3] = 0x10325476;
  7810. context->state[4] = 0xC3D2E1F0;
  7811. context->count[0] = context->count[1] = 0;
  7812. }
  7813. static void
  7814. SHA1Update(SHA1_CTX *context, const unsigned char *data, uint32_t len)
  7815. {
  7816. uint32_t i, j;
  7817. j = context->count[0];
  7818. if ((context->count[0] += len << 3) < j) {
  7819. context->count[1]++;
  7820. }
  7821. context->count[1] += (len >> 29);
  7822. j = (j >> 3) & 63;
  7823. if ((j + len) > 63) {
  7824. memcpy(&context->buffer[j], data, (i = 64 - j));
  7825. SHA1Transform(context->state, context->buffer);
  7826. for (; i + 63 < len; i += 64) {
  7827. SHA1Transform(context->state, &data[i]);
  7828. }
  7829. j = 0;
  7830. } else
  7831. i = 0;
  7832. memcpy(&context->buffer[j], &data[i], len - i);
  7833. }
  7834. static void
  7835. SHA1Final(unsigned char digest[20], SHA1_CTX *context)
  7836. {
  7837. unsigned i;
  7838. unsigned char finalcount[8], c;
  7839. for (i = 0; i < 8; i++) {
  7840. finalcount[i] = (unsigned char)((context->count[(i >= 4) ? 0 : 1]
  7841. >> ((3 - (i & 3)) * 8)) & 255);
  7842. }
  7843. c = 0200;
  7844. SHA1Update(context, &c, 1);
  7845. while ((context->count[0] & 504) != 448) {
  7846. c = 0000;
  7847. SHA1Update(context, &c, 1);
  7848. }
  7849. SHA1Update(context, finalcount, 8);
  7850. for (i = 0; i < 20; i++) {
  7851. digest[i] = (unsigned char)((context->state[i >> 2]
  7852. >> ((3 - (i & 3)) * 8)) & 255);
  7853. }
  7854. memset(context, '\0', sizeof(*context));
  7855. memset(&finalcount, '\0', sizeof(finalcount));
  7856. }
  7857. /* END OF SHA1 CODE */
  7858. static int
  7859. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  7860. {
  7861. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  7862. const char *protocol = NULL;
  7863. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  7864. SHA1_CTX sha_ctx;
  7865. int truncated;
  7866. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  7867. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  7868. if (truncated) {
  7869. conn->must_close = 1;
  7870. return 0;
  7871. }
  7872. SHA1Init(&sha_ctx);
  7873. SHA1Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  7874. SHA1Final((unsigned char *)sha, &sha_ctx);
  7875. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  7876. mg_printf(conn,
  7877. "HTTP/1.1 101 Switching Protocols\r\n"
  7878. "Upgrade: websocket\r\n"
  7879. "Connection: Upgrade\r\n"
  7880. "Sec-WebSocket-Accept: %s\r\n",
  7881. b64_sha);
  7882. protocol = mg_get_header(conn, "Sec-WebSocket-Protocol");
  7883. if (protocol) {
  7884. /* The protocol is a comma seperated list of names. */
  7885. /* The server must only return one value from this list. */
  7886. /* First check if it is a list or just a single value. */
  7887. const char *sep = strchr(protocol, ',');
  7888. if (sep == NULL) {
  7889. /* Just a single protocol -> accept it. */
  7890. mg_printf(conn, "Sec-WebSocket-Protocol: %s\r\n\r\n", protocol);
  7891. } else {
  7892. /* Multiple protocols -> accept the first one. */
  7893. /* This is just a quick fix if the client offers multiple
  7894. * protocols. In order to get the behavior intended by
  7895. * RFC 6455 (https://tools.ietf.org/rfc/rfc6455.txt), it is
  7896. * required to have a list of websocket subprotocols accepted
  7897. * by the server. Then the server must either select a subprotocol
  7898. * supported by client and server, or the server has to abort the
  7899. * handshake by not returning a Sec-Websocket-Protocol header if
  7900. * no subprotocol is acceptable.
  7901. */
  7902. mg_printf(conn,
  7903. "Sec-WebSocket-Protocol: %.*s\r\n\r\n",
  7904. (int)(sep - protocol),
  7905. protocol);
  7906. }
  7907. /* TODO: Real subprotocol negotiation instead of just taking the first
  7908. * websocket subprotocol suggested by the client. */
  7909. } else {
  7910. mg_printf(conn, "%s", "\r\n");
  7911. }
  7912. return 1;
  7913. }
  7914. static void
  7915. read_websocket(struct mg_connection *conn,
  7916. mg_websocket_data_handler ws_data_handler,
  7917. void *callback_data)
  7918. {
  7919. /* Pointer to the beginning of the portion of the incoming websocket
  7920. * message queue.
  7921. * The original websocket upgrade request is never removed, so the queue
  7922. * begins after it. */
  7923. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  7924. int n, error, exit_by_callback;
  7925. /* body_len is the length of the entire queue in bytes
  7926. * len is the length of the current message
  7927. * data_len is the length of the current message's data payload
  7928. * header_len is the length of the current message's header */
  7929. size_t i, len, mask_len = 0, data_len = 0, header_len, body_len;
  7930. /* "The masking key is a 32-bit value chosen at random by the client."
  7931. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  7932. */
  7933. unsigned char mask[4];
  7934. /* data points to the place where the message is stored when passed to
  7935. * the
  7936. * websocket_data callback. This is either mem on the stack, or a
  7937. * dynamically allocated buffer if it is too large. */
  7938. char mem[4096];
  7939. char *data = mem;
  7940. unsigned char mop; /* mask flag and opcode */
  7941. double timeout = -1.0;
  7942. if (conn->ctx->config[WEBSOCKET_TIMEOUT]) {
  7943. timeout = atoi(conn->ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  7944. }
  7945. if ((timeout <= 0.0) && (conn->ctx->config[REQUEST_TIMEOUT])) {
  7946. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  7947. }
  7948. mg_set_thread_name("wsock");
  7949. /* Loop continuously, reading messages from the socket, invoking the
  7950. * callback, and waiting repeatedly until an error occurs. */
  7951. while (!conn->ctx->stop_flag) {
  7952. header_len = 0;
  7953. assert(conn->data_len >= conn->request_len);
  7954. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  7955. len = buf[1] & 127;
  7956. mask_len = (buf[1] & 128) ? 4 : 0;
  7957. if ((len < 126) && (body_len >= mask_len)) {
  7958. data_len = len;
  7959. header_len = 2 + mask_len;
  7960. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  7961. header_len = 4 + mask_len;
  7962. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  7963. } else if (body_len >= (10 + mask_len)) {
  7964. header_len = 10 + mask_len;
  7965. data_len = (((uint64_t)ntohl(*(uint32_t *)(void *)&buf[2]))
  7966. << 32) + ntohl(*(uint32_t *)(void *)&buf[6]);
  7967. }
  7968. }
  7969. if (header_len > 0 && body_len >= header_len) {
  7970. /* Allocate space to hold websocket payload */
  7971. data = mem;
  7972. if (data_len > sizeof(mem)) {
  7973. data = (char *)mg_malloc(data_len);
  7974. if (data == NULL) {
  7975. /* Allocation failed, exit the loop and then close the
  7976. * connection */
  7977. mg_cry(conn, "websocket out of memory; closing connection");
  7978. break;
  7979. }
  7980. }
  7981. /* Copy the mask before we shift the queue and destroy it */
  7982. if (mask_len > 0) {
  7983. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  7984. } else {
  7985. memset(mask, 0, sizeof(mask));
  7986. }
  7987. /* Read frame payload from the first message in the queue into
  7988. * data and advance the queue by moving the memory in place. */
  7989. assert(body_len >= header_len);
  7990. if (data_len + header_len > body_len) {
  7991. mop = buf[0]; /* current mask and opcode */
  7992. /* Overflow case */
  7993. len = body_len - header_len;
  7994. memcpy(data, buf + header_len, len);
  7995. error = 0;
  7996. while (len < data_len) {
  7997. n = pull(
  7998. NULL, conn, data + len, (int)(data_len - len), timeout);
  7999. if (n <= 0) {
  8000. error = 1;
  8001. break;
  8002. }
  8003. len += (size_t)n;
  8004. }
  8005. if (error) {
  8006. mg_cry(conn, "Websocket pull failed; closing connection");
  8007. break;
  8008. }
  8009. conn->data_len = conn->request_len;
  8010. } else {
  8011. mop = buf[0]; /* current mask and opcode, overwritten by
  8012. * memmove() */
  8013. /* Length of the message being read at the front of the
  8014. * queue */
  8015. len = data_len + header_len;
  8016. /* Copy the data payload into the data pointer for the
  8017. * callback */
  8018. memcpy(data, buf + header_len, data_len);
  8019. /* Move the queue forward len bytes */
  8020. memmove(buf, buf + len, body_len - len);
  8021. /* Mark the queue as advanced */
  8022. conn->data_len -= (int)len;
  8023. }
  8024. /* Apply mask if necessary */
  8025. if (mask_len > 0) {
  8026. for (i = 0; i < data_len; ++i) {
  8027. data[i] ^= mask[i & 3];
  8028. }
  8029. }
  8030. /* Exit the loop if callback signals to exit (server side),
  8031. * or "connection close" opcode received (client side). */
  8032. exit_by_callback = 0;
  8033. if ((ws_data_handler != NULL)
  8034. && !ws_data_handler(conn, mop, data, data_len, callback_data)) {
  8035. exit_by_callback = 1;
  8036. }
  8037. if (data != mem) {
  8038. mg_free(data);
  8039. }
  8040. if (exit_by_callback
  8041. || ((mop & 0xf) == WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  8042. /* Opcode == 8, connection close */
  8043. break;
  8044. }
  8045. /* Not breaking the loop, process next websocket frame. */
  8046. } else {
  8047. /* Read from the socket into the next available location in the
  8048. * message queue. */
  8049. if ((n = pull(NULL,
  8050. conn,
  8051. conn->buf + conn->data_len,
  8052. conn->buf_size - conn->data_len,
  8053. timeout)) <= 0) {
  8054. /* Error, no bytes read */
  8055. break;
  8056. }
  8057. conn->data_len += n;
  8058. }
  8059. }
  8060. mg_set_thread_name("worker");
  8061. }
  8062. static int
  8063. mg_websocket_write_exec(struct mg_connection *conn,
  8064. int opcode,
  8065. const char *data,
  8066. size_t dataLen,
  8067. uint32_t masking_key)
  8068. {
  8069. unsigned char header[14];
  8070. size_t headerLen = 1;
  8071. int retval = -1;
  8072. header[0] = 0x80 + (opcode & 0xF);
  8073. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  8074. if (dataLen < 126) {
  8075. /* inline 7-bit length field */
  8076. header[1] = (unsigned char)dataLen;
  8077. headerLen = 2;
  8078. } else if (dataLen <= 0xFFFF) {
  8079. /* 16-bit length field */
  8080. uint16_t len = htons((uint16_t)dataLen);
  8081. header[1] = 126;
  8082. memcpy(header + 2, &len, 2);
  8083. headerLen = 4;
  8084. } else {
  8085. /* 64-bit length field */
  8086. uint32_t len1 = htonl((uint64_t)dataLen >> 32);
  8087. uint32_t len2 = htonl(dataLen & 0xFFFFFFFF);
  8088. header[1] = 127;
  8089. memcpy(header + 2, &len1, 4);
  8090. memcpy(header + 6, &len2, 4);
  8091. headerLen = 10;
  8092. }
  8093. if (masking_key) {
  8094. /* add mask */
  8095. header[1] |= 0x80;
  8096. memcpy(header + headerLen, &masking_key, 4);
  8097. headerLen += 4;
  8098. }
  8099. /* Note that POSIX/Winsock's send() is threadsafe
  8100. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  8101. * but mongoose's mg_printf/mg_write is not (because of the loop in
  8102. * push(), although that is only a problem if the packet is large or
  8103. * outgoing buffer is full). */
  8104. (void)mg_lock_connection(conn);
  8105. retval = mg_write(conn, header, headerLen);
  8106. if (dataLen > 0) {
  8107. retval = mg_write(conn, data, dataLen);
  8108. }
  8109. mg_unlock_connection(conn);
  8110. return retval;
  8111. }
  8112. int
  8113. mg_websocket_write(struct mg_connection *conn,
  8114. int opcode,
  8115. const char *data,
  8116. size_t dataLen)
  8117. {
  8118. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  8119. }
  8120. static void
  8121. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  8122. {
  8123. size_t i = 0;
  8124. i = 0;
  8125. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  8126. /* Convert in 32 bit words, if data is 4 byte aligned */
  8127. while (i < (in_len - 3)) {
  8128. *(uint32_t *)(void *)(out + i) =
  8129. *(uint32_t *)(void *)(in + i) ^ masking_key;
  8130. i += 4;
  8131. }
  8132. }
  8133. if (i != in_len) {
  8134. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  8135. while (i < in_len) {
  8136. *(uint8_t *)(void *)(out + i) =
  8137. *(uint8_t *)(void *)(in + i)
  8138. ^ *(((uint8_t *)&masking_key) + (i % 4));
  8139. i++;
  8140. }
  8141. }
  8142. }
  8143. int
  8144. mg_websocket_client_write(struct mg_connection *conn,
  8145. int opcode,
  8146. const char *data,
  8147. size_t dataLen)
  8148. {
  8149. int retval = -1;
  8150. char *masked_data = (char *)mg_malloc(((dataLen + 7) / 4) * 4);
  8151. uint32_t masking_key = (uint32_t)get_random();
  8152. if (masked_data == NULL) {
  8153. /* Return -1 in an error case */
  8154. mg_cry(conn,
  8155. "Cannot allocate buffer for masked websocket response: "
  8156. "Out of memory");
  8157. return -1;
  8158. }
  8159. mask_data(data, dataLen, masking_key, masked_data);
  8160. retval = mg_websocket_write_exec(
  8161. conn, opcode, masked_data, dataLen, masking_key);
  8162. mg_free(masked_data);
  8163. return retval;
  8164. }
  8165. static void
  8166. handle_websocket_request(struct mg_connection *conn,
  8167. const char *path,
  8168. int is_callback_resource,
  8169. mg_websocket_connect_handler ws_connect_handler,
  8170. mg_websocket_ready_handler ws_ready_handler,
  8171. mg_websocket_data_handler ws_data_handler,
  8172. mg_websocket_close_handler ws_close_handler,
  8173. void *cbData)
  8174. {
  8175. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  8176. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  8177. int lua_websock = 0;
  8178. #if !defined(USE_LUA)
  8179. (void)path;
  8180. #endif
  8181. /* Step 1: Check websocket protocol version. */
  8182. /* Step 1.1: Check Sec-WebSocket-Key. */
  8183. if (!websock_key) {
  8184. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  8185. * requires a Sec-WebSocket-Key header.
  8186. */
  8187. /* It could be the hixie draft version
  8188. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  8189. */
  8190. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  8191. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  8192. char key3[8];
  8193. if ((key1 != NULL) && (key2 != NULL)) {
  8194. /* This version uses 8 byte body data in a GET request */
  8195. conn->content_len = 8;
  8196. if (8 == mg_read(conn, key3, 8)) {
  8197. /* This is the hixie version */
  8198. send_http_error(conn,
  8199. 426,
  8200. "%s",
  8201. "Protocol upgrade to RFC 6455 required");
  8202. return;
  8203. }
  8204. }
  8205. /* This is an unknown version */
  8206. send_http_error(conn, 400, "%s", "Malformed websocket request");
  8207. return;
  8208. }
  8209. /* Step 1.2: Check websocket protocol version. */
  8210. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  8211. if (version == NULL || strcmp(version, "13") != 0) {
  8212. /* Reject wrong versions */
  8213. send_http_error(conn, 426, "%s", "Protocol upgrade required");
  8214. return;
  8215. }
  8216. /* Step 1.3: Could check for "Host", but we do not really nead this
  8217. * value for anything, so just ignore it. */
  8218. /* Step 2: If a callback is responsible, call it. */
  8219. if (is_callback_resource) {
  8220. if (ws_connect_handler != NULL
  8221. && ws_connect_handler(conn, cbData) != 0) {
  8222. /* C callback has returned non-zero, do not proceed with
  8223. * handshake.
  8224. */
  8225. /* Note that C callbacks are no longer called when Lua is
  8226. * responsible, so C can no longer filter callbacks for Lua. */
  8227. return;
  8228. }
  8229. }
  8230. #if defined(USE_LUA)
  8231. /* Step 3: No callback. Check if Lua is responsible. */
  8232. else {
  8233. /* Step 3.1: Check if Lua is responsible. */
  8234. if (conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  8235. lua_websock =
  8236. match_prefix(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  8237. strlen(
  8238. conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  8239. path);
  8240. }
  8241. if (lua_websock) {
  8242. /* Step 3.2: Lua is responsible: call it. */
  8243. conn->lua_websocket_state = lua_websocket_new(path, conn);
  8244. if (!conn->lua_websocket_state) {
  8245. /* Lua rejected the new client */
  8246. return;
  8247. }
  8248. }
  8249. }
  8250. #endif
  8251. /* Step 4: Check if there is a responsible websocket handler. */
  8252. if (!is_callback_resource && !lua_websock) {
  8253. /* There is no callback, an Lua is not responsible either. */
  8254. /* Reply with a 404 Not Found or with nothing at all?
  8255. * TODO (mid): check the websocket standards, how to reply to
  8256. * requests to invalid websocket addresses. */
  8257. send_http_error(conn, 404, "%s", "Not found");
  8258. return;
  8259. }
  8260. /* Step 5: The websocket connection has been accepted */
  8261. if (!send_websocket_handshake(conn, websock_key)) {
  8262. send_http_error(conn, 500, "%s", "Websocket handshake failed");
  8263. return;
  8264. }
  8265. /* Step 6: Call the ready handler */
  8266. if (is_callback_resource) {
  8267. if (ws_ready_handler != NULL) {
  8268. ws_ready_handler(conn, cbData);
  8269. }
  8270. #if defined(USE_LUA)
  8271. } else if (lua_websock) {
  8272. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  8273. /* the ready handler returned false */
  8274. return;
  8275. }
  8276. #endif
  8277. }
  8278. /* Step 7: Enter the read loop */
  8279. if (is_callback_resource) {
  8280. read_websocket(conn, ws_data_handler, cbData);
  8281. #if defined(USE_LUA)
  8282. } else if (lua_websock) {
  8283. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  8284. #endif
  8285. }
  8286. /* Step 8: Call the close handler */
  8287. if (ws_close_handler) {
  8288. ws_close_handler(conn, cbData);
  8289. }
  8290. }
  8291. static int
  8292. is_websocket_protocol(const struct mg_connection *conn)
  8293. {
  8294. const char *upgrade, *connection;
  8295. /* A websocket protocoll has the following HTTP headers:
  8296. *
  8297. * Connection: Upgrade
  8298. * Upgrade: Websocket
  8299. */
  8300. upgrade = mg_get_header(conn, "Upgrade");
  8301. if (upgrade == NULL) {
  8302. return 0; /* fail early, don't waste time checking other header
  8303. * fields
  8304. */
  8305. }
  8306. if (!mg_strcasestr(upgrade, "websocket")) {
  8307. return 0;
  8308. }
  8309. connection = mg_get_header(conn, "Connection");
  8310. if (connection == NULL) {
  8311. return 0;
  8312. }
  8313. if (!mg_strcasestr(connection, "upgrade")) {
  8314. return 0;
  8315. }
  8316. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  8317. * "Sec-WebSocket-Version" are also required.
  8318. * Don't check them here, since even an unsupported websocket protocol
  8319. * request still IS a websocket request (in contrast to a standard HTTP
  8320. * request). It will fail later in handle_websocket_request.
  8321. */
  8322. return 1;
  8323. }
  8324. #endif /* !USE_WEBSOCKET */
  8325. static int
  8326. isbyte(int n)
  8327. {
  8328. return n >= 0 && n <= 255;
  8329. }
  8330. static int
  8331. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  8332. {
  8333. int n, a, b, c, d, slash = 32, len = 0;
  8334. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5
  8335. || sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) && isbyte(a)
  8336. && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0
  8337. && slash < 33) {
  8338. len = n;
  8339. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  8340. | (uint32_t)d;
  8341. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  8342. }
  8343. return len;
  8344. }
  8345. static int
  8346. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  8347. {
  8348. int throttle = 0;
  8349. struct vec vec, val;
  8350. uint32_t net, mask;
  8351. char mult;
  8352. double v;
  8353. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  8354. mult = ',';
  8355. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  8356. || (v < 0) || ((lowercase(&mult) != 'k')
  8357. && (lowercase(&mult) != 'm') && (mult != ','))) {
  8358. continue;
  8359. }
  8360. v *= (lowercase(&mult) == 'k')
  8361. ? 1024
  8362. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  8363. if (vec.len == 1 && vec.ptr[0] == '*') {
  8364. throttle = (int)v;
  8365. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  8366. if ((remote_ip & mask) == net) {
  8367. throttle = (int)v;
  8368. }
  8369. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  8370. throttle = (int)v;
  8371. }
  8372. }
  8373. return throttle;
  8374. }
  8375. static uint32_t
  8376. get_remote_ip(const struct mg_connection *conn)
  8377. {
  8378. if (!conn) {
  8379. return 0;
  8380. }
  8381. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  8382. }
  8383. /* The mg_upload function is superseeded by mg_handle_form_request. */
  8384. #include "handle_form.inl"
  8385. #if defined(MG_LEGACY_INTERFACE)
  8386. /* Implement the deprecated mg_upload function by calling the new
  8387. * mg_handle_form_request function. While mg_upload could only handle
  8388. * HTML forms sent as POST request in multipart/form-data format
  8389. * containing only file input elements, mg_handle_form_request can
  8390. * handle all form input elements and all standard request methods. */
  8391. struct mg_upload_user_data {
  8392. struct mg_connection *conn;
  8393. const char *destination_dir;
  8394. int num_uploaded_files;
  8395. };
  8396. /* Helper function for deprecated mg_upload. */
  8397. static int
  8398. mg_upload_field_found(const char *key,
  8399. const char *filename,
  8400. char *path,
  8401. size_t pathlen,
  8402. void *user_data)
  8403. {
  8404. int truncated = 0;
  8405. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  8406. (void)key;
  8407. if (!filename) {
  8408. mg_cry(fud->conn, "%s: No filename set", __func__);
  8409. return FORM_FIELD_STORAGE_ABORT;
  8410. }
  8411. mg_snprintf(fud->conn,
  8412. &truncated,
  8413. path,
  8414. pathlen - 1,
  8415. "%s/%s",
  8416. fud->destination_dir,
  8417. filename);
  8418. if (!truncated) {
  8419. mg_cry(fud->conn, "%s: File path too long", __func__);
  8420. return FORM_FIELD_STORAGE_ABORT;
  8421. }
  8422. return FORM_FIELD_STORAGE_STORE;
  8423. }
  8424. /* Helper function for deprecated mg_upload. */
  8425. static int
  8426. mg_upload_field_get(const char *key,
  8427. const char *value,
  8428. size_t value_size,
  8429. void *user_data)
  8430. {
  8431. /* Function should never be called */
  8432. (void)key;
  8433. (void)value;
  8434. (void)value_size;
  8435. (void)user_data;
  8436. return 0;
  8437. }
  8438. /* Helper function for deprecated mg_upload. */
  8439. static int
  8440. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  8441. {
  8442. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  8443. (void)file_size;
  8444. fud->num_uploaded_files++;
  8445. fud->conn->ctx->callbacks.upload(fud->conn, path);
  8446. return 0;
  8447. }
  8448. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  8449. int
  8450. mg_upload(struct mg_connection *conn, const char *destination_dir)
  8451. {
  8452. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  8453. struct mg_form_data_handler fdh = {mg_upload_field_found,
  8454. mg_upload_field_get,
  8455. mg_upload_field_stored,
  8456. 0};
  8457. int ret;
  8458. fdh.user_data = (void *)&fud;
  8459. ret = mg_handle_form_request(conn, &fdh);
  8460. if (ret < 0) {
  8461. mg_cry(conn, "%s: Error while parsing the request", __func__);
  8462. }
  8463. return fud.num_uploaded_files;
  8464. }
  8465. #endif
  8466. static int
  8467. get_first_ssl_listener_index(const struct mg_context *ctx)
  8468. {
  8469. unsigned int i;
  8470. int idx = -1;
  8471. if (ctx) {
  8472. for (i = 0; idx == -1 && i < ctx->num_listening_sockets; i++) {
  8473. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  8474. }
  8475. }
  8476. return idx;
  8477. }
  8478. static void
  8479. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  8480. {
  8481. char host[1025];
  8482. const char *host_header;
  8483. size_t hostlen;
  8484. host_header = mg_get_header(conn, "Host");
  8485. hostlen = sizeof(host);
  8486. if (host_header != NULL) {
  8487. char *pos;
  8488. mg_strlcpy(host, host_header, hostlen);
  8489. host[hostlen - 1] = '\0';
  8490. pos = strchr(host, ':');
  8491. if (pos != NULL) {
  8492. *pos = '\0';
  8493. }
  8494. } else {
  8495. /* Cannot get host from the Host: header.
  8496. * Fallback to our IP address. */
  8497. if (conn) {
  8498. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  8499. }
  8500. }
  8501. /* Send host, port, uri and (if it exists) ?query_string */
  8502. if (conn) {
  8503. mg_printf(conn,
  8504. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  8505. host,
  8506. #if defined(USE_IPV6)
  8507. (conn->ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  8508. == AF_INET6)
  8509. ? (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  8510. .lsa.sin6.sin6_port)
  8511. :
  8512. #endif
  8513. (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  8514. .lsa.sin.sin_port),
  8515. conn->request_info.local_uri,
  8516. (conn->request_info.query_string == NULL) ? "" : "?",
  8517. (conn->request_info.query_string == NULL)
  8518. ? ""
  8519. : conn->request_info.query_string);
  8520. }
  8521. }
  8522. static void
  8523. mg_set_handler_type(struct mg_context *ctx,
  8524. const char *uri,
  8525. int handler_type,
  8526. int is_delete_request,
  8527. mg_request_handler handler,
  8528. mg_websocket_connect_handler connect_handler,
  8529. mg_websocket_ready_handler ready_handler,
  8530. mg_websocket_data_handler data_handler,
  8531. mg_websocket_close_handler close_handler,
  8532. mg_authorization_handler auth_handler,
  8533. void *cbdata)
  8534. {
  8535. struct mg_handler_info *tmp_rh, **lastref;
  8536. size_t urilen = strlen(uri);
  8537. if (handler_type == WEBSOCKET_HANDLER) {
  8538. /* assert(handler == NULL); */
  8539. /* assert(is_delete_request || connect_handler!=NULL ||
  8540. * ready_handler!=NULL || data_handler!=NULL ||
  8541. * close_handler!=NULL);
  8542. */
  8543. /* assert(auth_handler == NULL); */
  8544. if (handler != NULL) {
  8545. return;
  8546. }
  8547. if (!is_delete_request && connect_handler == NULL
  8548. && ready_handler == NULL
  8549. && data_handler == NULL
  8550. && close_handler == NULL) {
  8551. return;
  8552. }
  8553. if (auth_handler != NULL) {
  8554. return;
  8555. }
  8556. } else if (handler_type == REQUEST_HANDLER) {
  8557. /* assert(connect_handler==NULL && ready_handler==NULL &&
  8558. * data_handler==NULL && close_handler==NULL); */
  8559. /* assert(is_delete_request || (handler!=NULL));
  8560. */
  8561. /* assert(auth_handler == NULL); */
  8562. if (connect_handler != NULL || ready_handler != NULL
  8563. || data_handler != NULL
  8564. || close_handler != NULL) {
  8565. return;
  8566. }
  8567. if (!is_delete_request && (handler == NULL)) {
  8568. return;
  8569. }
  8570. if (auth_handler != NULL) {
  8571. return;
  8572. }
  8573. } else { /* AUTH_HANDLER */
  8574. /* assert(handler == NULL); */
  8575. /* assert(connect_handler==NULL && ready_handler==NULL &&
  8576. * data_handler==NULL && close_handler==NULL); */
  8577. /* assert(auth_handler != NULL); */
  8578. if (handler != NULL) {
  8579. return;
  8580. }
  8581. if (connect_handler != NULL || ready_handler != NULL
  8582. || data_handler != NULL
  8583. || close_handler != NULL) {
  8584. return;
  8585. }
  8586. if (!is_delete_request && (auth_handler == NULL)) {
  8587. return;
  8588. }
  8589. }
  8590. if (!ctx) {
  8591. return;
  8592. }
  8593. mg_lock_context(ctx);
  8594. /* first try to find an existing handler */
  8595. lastref = &(ctx->handlers);
  8596. for (tmp_rh = ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  8597. if (tmp_rh->handler_type == handler_type) {
  8598. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  8599. if (!is_delete_request) {
  8600. /* update existing handler */
  8601. if (handler_type == REQUEST_HANDLER) {
  8602. tmp_rh->handler = handler;
  8603. } else if (handler_type == WEBSOCKET_HANDLER) {
  8604. tmp_rh->connect_handler = connect_handler;
  8605. tmp_rh->ready_handler = ready_handler;
  8606. tmp_rh->data_handler = data_handler;
  8607. tmp_rh->close_handler = close_handler;
  8608. } else { /* AUTH_HANDLER */
  8609. tmp_rh->auth_handler = auth_handler;
  8610. }
  8611. tmp_rh->cbdata = cbdata;
  8612. } else {
  8613. /* remove existing handler */
  8614. *lastref = tmp_rh->next;
  8615. mg_free(tmp_rh->uri);
  8616. mg_free(tmp_rh);
  8617. }
  8618. mg_unlock_context(ctx);
  8619. return;
  8620. }
  8621. }
  8622. lastref = &(tmp_rh->next);
  8623. }
  8624. if (is_delete_request) {
  8625. /* no handler to set, this was a remove request to a non-existing
  8626. * handler */
  8627. mg_unlock_context(ctx);
  8628. return;
  8629. }
  8630. tmp_rh =
  8631. (struct mg_handler_info *)mg_calloc(sizeof(struct mg_handler_info), 1);
  8632. if (tmp_rh == NULL) {
  8633. mg_unlock_context(ctx);
  8634. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  8635. return;
  8636. }
  8637. tmp_rh->uri = mg_strdup(uri);
  8638. if (!tmp_rh->uri) {
  8639. mg_unlock_context(ctx);
  8640. mg_free(tmp_rh);
  8641. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  8642. return;
  8643. }
  8644. tmp_rh->uri_len = urilen;
  8645. if (handler_type == REQUEST_HANDLER) {
  8646. tmp_rh->handler = handler;
  8647. } else if (handler_type == WEBSOCKET_HANDLER) {
  8648. tmp_rh->connect_handler = connect_handler;
  8649. tmp_rh->ready_handler = ready_handler;
  8650. tmp_rh->data_handler = data_handler;
  8651. tmp_rh->close_handler = close_handler;
  8652. } else { /* AUTH_HANDLER */
  8653. tmp_rh->auth_handler = auth_handler;
  8654. }
  8655. tmp_rh->cbdata = cbdata;
  8656. tmp_rh->handler_type = handler_type;
  8657. tmp_rh->next = NULL;
  8658. *lastref = tmp_rh;
  8659. mg_unlock_context(ctx);
  8660. }
  8661. void
  8662. mg_set_request_handler(struct mg_context *ctx,
  8663. const char *uri,
  8664. mg_request_handler handler,
  8665. void *cbdata)
  8666. {
  8667. mg_set_handler_type(ctx,
  8668. uri,
  8669. REQUEST_HANDLER,
  8670. handler == NULL,
  8671. handler,
  8672. NULL,
  8673. NULL,
  8674. NULL,
  8675. NULL,
  8676. NULL,
  8677. cbdata);
  8678. }
  8679. void
  8680. mg_set_websocket_handler(struct mg_context *ctx,
  8681. const char *uri,
  8682. mg_websocket_connect_handler connect_handler,
  8683. mg_websocket_ready_handler ready_handler,
  8684. mg_websocket_data_handler data_handler,
  8685. mg_websocket_close_handler close_handler,
  8686. void *cbdata)
  8687. {
  8688. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  8689. && (data_handler == NULL)
  8690. && (close_handler == NULL);
  8691. mg_set_handler_type(ctx,
  8692. uri,
  8693. WEBSOCKET_HANDLER,
  8694. is_delete_request,
  8695. NULL,
  8696. connect_handler,
  8697. ready_handler,
  8698. data_handler,
  8699. close_handler,
  8700. NULL,
  8701. cbdata);
  8702. }
  8703. void
  8704. mg_set_auth_handler(struct mg_context *ctx,
  8705. const char *uri,
  8706. mg_request_handler handler,
  8707. void *cbdata)
  8708. {
  8709. mg_set_handler_type(ctx,
  8710. uri,
  8711. AUTH_HANDLER,
  8712. handler == NULL,
  8713. NULL,
  8714. NULL,
  8715. NULL,
  8716. NULL,
  8717. NULL,
  8718. handler,
  8719. cbdata);
  8720. }
  8721. static int
  8722. get_request_handler(struct mg_connection *conn,
  8723. int handler_type,
  8724. mg_request_handler *handler,
  8725. mg_websocket_connect_handler *connect_handler,
  8726. mg_websocket_ready_handler *ready_handler,
  8727. mg_websocket_data_handler *data_handler,
  8728. mg_websocket_close_handler *close_handler,
  8729. mg_authorization_handler *auth_handler,
  8730. void **cbdata)
  8731. {
  8732. const struct mg_request_info *request_info = mg_get_request_info(conn);
  8733. if (request_info) {
  8734. const char *uri = request_info->local_uri;
  8735. size_t urilen = strlen(uri);
  8736. struct mg_handler_info *tmp_rh;
  8737. if (!conn || !conn->ctx) {
  8738. return 0;
  8739. }
  8740. mg_lock_context(conn->ctx);
  8741. /* first try for an exact match */
  8742. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8743. tmp_rh = tmp_rh->next) {
  8744. if (tmp_rh->handler_type == handler_type) {
  8745. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  8746. if (handler_type == WEBSOCKET_HANDLER) {
  8747. *connect_handler = tmp_rh->connect_handler;
  8748. *ready_handler = tmp_rh->ready_handler;
  8749. *data_handler = tmp_rh->data_handler;
  8750. *close_handler = tmp_rh->close_handler;
  8751. } else if (handler_type == REQUEST_HANDLER) {
  8752. *handler = tmp_rh->handler;
  8753. } else { /* AUTH_HANDLER */
  8754. *auth_handler = tmp_rh->auth_handler;
  8755. }
  8756. *cbdata = tmp_rh->cbdata;
  8757. mg_unlock_context(conn->ctx);
  8758. return 1;
  8759. }
  8760. }
  8761. }
  8762. /* next try for a partial match, we will accept uri/something */
  8763. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8764. tmp_rh = tmp_rh->next) {
  8765. if (tmp_rh->handler_type == handler_type) {
  8766. if (tmp_rh->uri_len < urilen && uri[tmp_rh->uri_len] == '/'
  8767. && memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0) {
  8768. if (handler_type == WEBSOCKET_HANDLER) {
  8769. *connect_handler = tmp_rh->connect_handler;
  8770. *ready_handler = tmp_rh->ready_handler;
  8771. *data_handler = tmp_rh->data_handler;
  8772. *close_handler = tmp_rh->close_handler;
  8773. } else if (handler_type == REQUEST_HANDLER) {
  8774. *handler = tmp_rh->handler;
  8775. } else { /* AUTH_HANDLER */
  8776. *auth_handler = tmp_rh->auth_handler;
  8777. }
  8778. *cbdata = tmp_rh->cbdata;
  8779. mg_unlock_context(conn->ctx);
  8780. return 1;
  8781. }
  8782. }
  8783. }
  8784. /* finally try for pattern match */
  8785. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8786. tmp_rh = tmp_rh->next) {
  8787. if (tmp_rh->handler_type == handler_type) {
  8788. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  8789. if (handler_type == WEBSOCKET_HANDLER) {
  8790. *connect_handler = tmp_rh->connect_handler;
  8791. *ready_handler = tmp_rh->ready_handler;
  8792. *data_handler = tmp_rh->data_handler;
  8793. *close_handler = tmp_rh->close_handler;
  8794. } else if (handler_type == REQUEST_HANDLER) {
  8795. *handler = tmp_rh->handler;
  8796. } else { /* AUTH_HANDLER */
  8797. *auth_handler = tmp_rh->auth_handler;
  8798. }
  8799. *cbdata = tmp_rh->cbdata;
  8800. mg_unlock_context(conn->ctx);
  8801. return 1;
  8802. }
  8803. }
  8804. }
  8805. mg_unlock_context(conn->ctx);
  8806. }
  8807. return 0; /* none found */
  8808. }
  8809. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  8810. static int
  8811. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  8812. void *cbdata)
  8813. {
  8814. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  8815. if (pcallbacks->websocket_connect) {
  8816. return pcallbacks->websocket_connect(conn);
  8817. }
  8818. /* No handler set - assume "OK" */
  8819. return 0;
  8820. }
  8821. static void
  8822. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  8823. {
  8824. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  8825. if (pcallbacks->websocket_ready) {
  8826. pcallbacks->websocket_ready(conn);
  8827. }
  8828. }
  8829. static int
  8830. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  8831. int bits,
  8832. char *data,
  8833. size_t len,
  8834. void *cbdata)
  8835. {
  8836. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  8837. if (pcallbacks->websocket_data) {
  8838. return pcallbacks->websocket_data(conn, bits, data, len);
  8839. }
  8840. /* No handler set - assume "OK" */
  8841. return 1;
  8842. }
  8843. #endif
  8844. /* This is the heart of the Civetweb's logic.
  8845. * This function is called when the request is read, parsed and validated,
  8846. * and Civetweb must decide what action to take: serve a file, or
  8847. * a directory, or call embedded function, etcetera. */
  8848. static void
  8849. handle_request(struct mg_connection *conn)
  8850. {
  8851. if (conn) {
  8852. struct mg_request_info *ri = &conn->request_info;
  8853. char path[PATH_MAX];
  8854. int uri_len, ssl_index;
  8855. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  8856. is_put_or_delete_request = 0, is_callback_resource = 0;
  8857. int i;
  8858. struct file file = STRUCT_FILE_INITIALIZER;
  8859. mg_request_handler callback_handler = NULL;
  8860. mg_websocket_connect_handler ws_connect_handler = NULL;
  8861. mg_websocket_ready_handler ws_ready_handler = NULL;
  8862. mg_websocket_data_handler ws_data_handler = NULL;
  8863. mg_websocket_close_handler ws_close_handler = NULL;
  8864. void *callback_data = NULL;
  8865. mg_authorization_handler auth_handler = NULL;
  8866. void *auth_callback_data = NULL;
  8867. #if !defined(NO_FILES)
  8868. time_t curtime = time(NULL);
  8869. char date[64];
  8870. #endif
  8871. path[0] = 0;
  8872. if (!ri) {
  8873. return;
  8874. }
  8875. /* 1. get the request url */
  8876. /* 1.1. split into url and query string */
  8877. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  8878. != NULL) {
  8879. *((char *)conn->request_info.query_string++) = '\0';
  8880. }
  8881. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  8882. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  8883. ssl_index = get_first_ssl_listener_index(conn->ctx);
  8884. if (ssl_index >= 0) {
  8885. redirect_to_https_port(conn, ssl_index);
  8886. } else {
  8887. /* A http to https forward port has been specified,
  8888. * but no https port to forward to. */
  8889. send_http_error(conn,
  8890. 503,
  8891. "%s",
  8892. "Error: SSL forward not configured properly");
  8893. mg_cry(conn, "Can not redirect to SSL, no SSL port available");
  8894. }
  8895. return;
  8896. }
  8897. uri_len = (int)strlen(ri->local_uri);
  8898. /* 1.3. decode url (if config says so) */
  8899. if (should_decode_url(conn)) {
  8900. mg_url_decode(
  8901. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  8902. }
  8903. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  8904. * not possible */
  8905. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  8906. /* step 1. completed, the url is known now */
  8907. uri_len = (int)strlen(ri->local_uri);
  8908. DEBUG_TRACE("URL: %s", ri->local_uri);
  8909. /* 3. if this ip has limited speed, set it for this connection */
  8910. conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
  8911. get_remote_ip(conn),
  8912. ri->local_uri);
  8913. /* 4. call a "handle everything" callback, if registered */
  8914. if (conn->ctx->callbacks.begin_request != NULL) {
  8915. /* Note that since V1.7 the "begin_request" function is called
  8916. * before an authorization check. If an authorization check is
  8917. * required, use a request_handler instead. */
  8918. i = conn->ctx->callbacks.begin_request(conn);
  8919. if (i > 0) {
  8920. /* callback already processed the request. Store the
  8921. return value as a status code for the access log. */
  8922. conn->status_code = i;
  8923. discard_unread_request_data(conn);
  8924. return;
  8925. } else if (i == 0) {
  8926. /* civetweb should process the request */
  8927. } else {
  8928. /* unspecified - may change with the next version */
  8929. return;
  8930. }
  8931. }
  8932. /* request not yet handled by a handler or redirect, so the request
  8933. * is processed here */
  8934. /* 5. interpret the url to find out how the request must be handled
  8935. */
  8936. /* 5.1. first test, if the request targets the regular http(s)://
  8937. * protocol namespace or the websocket ws(s):// protocol namespace.
  8938. */
  8939. is_websocket_request = is_websocket_protocol(conn);
  8940. /* 5.2. check if the request will be handled by a callback */
  8941. if (get_request_handler(conn,
  8942. is_websocket_request ? WEBSOCKET_HANDLER
  8943. : REQUEST_HANDLER,
  8944. &callback_handler,
  8945. &ws_connect_handler,
  8946. &ws_ready_handler,
  8947. &ws_data_handler,
  8948. &ws_close_handler,
  8949. NULL,
  8950. &callback_data)) {
  8951. /* 5.2.1. A callback will handle this request. All requests
  8952. * handled
  8953. * by a callback have to be considered as requests to a script
  8954. * resource. */
  8955. is_callback_resource = 1;
  8956. is_script_resource = 1;
  8957. is_put_or_delete_request = is_put_or_delete_method(conn);
  8958. } else {
  8959. no_callback_resource:
  8960. /* 5.2.2. No callback is responsible for this request. The URI
  8961. * addresses a file based resource (static content or Lua/cgi
  8962. * scripts in the file system). */
  8963. is_callback_resource = 0;
  8964. interpret_uri(conn,
  8965. path,
  8966. sizeof(path),
  8967. &file,
  8968. &is_found,
  8969. &is_script_resource,
  8970. &is_websocket_request,
  8971. &is_put_or_delete_request);
  8972. }
  8973. /* 6. authorization check */
  8974. /* 6.1. a custom authorization handler is installed */
  8975. if (get_request_handler(conn,
  8976. AUTH_HANDLER,
  8977. NULL,
  8978. NULL,
  8979. NULL,
  8980. NULL,
  8981. NULL,
  8982. &auth_handler,
  8983. &auth_callback_data)) {
  8984. if (!auth_handler(conn, auth_callback_data)) {
  8985. return;
  8986. }
  8987. } else if (is_put_or_delete_request && !is_script_resource
  8988. && !is_callback_resource) {
  8989. /* 6.2. this request is a PUT/DELETE to a real file */
  8990. /* 6.2.1. thus, the server must have real files */
  8991. #if defined(NO_FILES)
  8992. if (1) {
  8993. #else
  8994. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  8995. #endif
  8996. /* This server does not have any real files, thus the
  8997. * PUT/DELETE methods are not valid. */
  8998. send_http_error(conn,
  8999. 405,
  9000. "%s method not allowed",
  9001. conn->request_info.request_method);
  9002. return;
  9003. }
  9004. #if !defined(NO_FILES)
  9005. /* 6.2.2. Check if put authorization for static files is
  9006. * available.
  9007. */
  9008. if (!is_authorized_for_put(conn)) {
  9009. send_authorization_request(conn);
  9010. return;
  9011. }
  9012. #endif
  9013. } else {
  9014. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  9015. * or it is a PUT or DELETE request to a resource that does not
  9016. * correspond to a file. Check authorization. */
  9017. if (!check_authorization(conn, path)) {
  9018. send_authorization_request(conn);
  9019. return;
  9020. }
  9021. }
  9022. /* request is authorized or does not need authorization */
  9023. /* 7. check if there are request handlers for this uri */
  9024. if (is_callback_resource) {
  9025. if (!is_websocket_request) {
  9026. i = callback_handler(conn, callback_data);
  9027. if (i > 0) {
  9028. /* Do nothing, callback has served the request. Store
  9029. * the
  9030. * return value as status code for the log and discard
  9031. * all
  9032. * data from the client not used by the callback. */
  9033. conn->status_code = i;
  9034. discard_unread_request_data(conn);
  9035. } else {
  9036. /* TODO (high): what if the handler did NOT handle the
  9037. * request */
  9038. /* The last version did handle this as a file request,
  9039. * but
  9040. * since a file request is not always a script resource,
  9041. * the authorization check might be different */
  9042. interpret_uri(conn,
  9043. path,
  9044. sizeof(path),
  9045. &file,
  9046. &is_found,
  9047. &is_script_resource,
  9048. &is_websocket_request,
  9049. &is_put_or_delete_request);
  9050. callback_handler = NULL;
  9051. /* TODO (very low): goto is deprecated but for the
  9052. * moment,
  9053. * a goto is simpler than some curious loop. */
  9054. /* The situation "callback does not handle the request"
  9055. * needs to be reconsidered anyway. */
  9056. goto no_callback_resource;
  9057. }
  9058. } else {
  9059. #if defined(USE_WEBSOCKET)
  9060. handle_websocket_request(conn,
  9061. path,
  9062. is_callback_resource,
  9063. ws_connect_handler,
  9064. ws_ready_handler,
  9065. ws_data_handler,
  9066. ws_close_handler,
  9067. callback_data);
  9068. #endif
  9069. }
  9070. return;
  9071. }
  9072. /* 8. handle websocket requests */
  9073. #if defined(USE_WEBSOCKET)
  9074. if (is_websocket_request) {
  9075. if (is_script_resource) {
  9076. /* Websocket Lua script */
  9077. handle_websocket_request(conn,
  9078. path,
  9079. 0 /* Lua Script */,
  9080. NULL,
  9081. NULL,
  9082. NULL,
  9083. NULL,
  9084. &conn->ctx->callbacks);
  9085. } else {
  9086. #if defined(MG_LEGACY_INTERFACE)
  9087. handle_websocket_request(
  9088. conn,
  9089. path,
  9090. !is_script_resource /* could be deprecated global callback */,
  9091. deprecated_websocket_connect_wrapper,
  9092. deprecated_websocket_ready_wrapper,
  9093. deprecated_websocket_data_wrapper,
  9094. NULL,
  9095. &conn->ctx->callbacks);
  9096. #else
  9097. send_http_error(conn, 404, "%s", "Not found");
  9098. #endif
  9099. }
  9100. return;
  9101. } else
  9102. #endif
  9103. #if defined(NO_FILES)
  9104. /* 9a. In case the server uses only callbacks, this uri is
  9105. * unknown.
  9106. * Then, all request handling ends here. */
  9107. send_http_error(conn, 404, "%s", "Not Found");
  9108. #else
  9109. /* 9b. This request is either for a static file or resource handled
  9110. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  9111. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  9112. send_http_error(conn, 404, "%s", "Not Found");
  9113. return;
  9114. }
  9115. /* 10. File is handled by a script. */
  9116. if (is_script_resource) {
  9117. handle_file_based_request(conn, path, &file);
  9118. return;
  9119. }
  9120. /* 11. Handle put/delete/mkcol requests */
  9121. if (is_put_or_delete_request) {
  9122. /* 11.1. PUT method */
  9123. if (!strcmp(ri->request_method, "PUT")) {
  9124. put_file(conn, path);
  9125. return;
  9126. }
  9127. /* 11.2. DELETE method */
  9128. if (!strcmp(ri->request_method, "DELETE")) {
  9129. delete_file(conn, path);
  9130. return;
  9131. }
  9132. /* 11.3. MKCOL method */
  9133. if (!strcmp(ri->request_method, "MKCOL")) {
  9134. mkcol(conn, path);
  9135. return;
  9136. }
  9137. /* 11.4. PATCH method
  9138. * This method is not supported for static resources,
  9139. * only for scripts (Lua, CGI) and callbacks. */
  9140. send_http_error(conn,
  9141. 405,
  9142. "%s method not allowed",
  9143. conn->request_info.request_method);
  9144. return;
  9145. }
  9146. /* 11. File does not exist, or it was configured that it should be
  9147. * hidden */
  9148. if (!is_found || (must_hide_file(conn, path))) {
  9149. send_http_error(conn, 404, "%s", "Not found");
  9150. return;
  9151. }
  9152. /* 12. Directory uris should end with a slash */
  9153. if (file.is_directory && (uri_len > 0)
  9154. && (ri->local_uri[uri_len - 1] != '/')) {
  9155. gmt_time_string(date, sizeof(date), &curtime);
  9156. mg_printf(conn,
  9157. "HTTP/1.1 301 Moved Permanently\r\n"
  9158. "Location: %s/\r\n"
  9159. "Date: %s\r\n"
  9160. /* "Cache-Control: private\r\n" (= default) */
  9161. "Content-Length: 0\r\n"
  9162. "Connection: %s\r\n\r\n",
  9163. ri->request_uri,
  9164. date,
  9165. suggest_connection_header(conn));
  9166. return;
  9167. }
  9168. /* 13. Handle other methods than GET/HEAD */
  9169. /* 13.1. Handle PROPFIND */
  9170. if (!strcmp(ri->request_method, "PROPFIND")) {
  9171. handle_propfind(conn, path, &file);
  9172. return;
  9173. }
  9174. /* 13.2. Handle OPTIONS for files */
  9175. if (!strcmp(ri->request_method, "OPTIONS")) {
  9176. /* This standard handler is only used for real files.
  9177. * Scripts should support the OPTIONS method themselves, to allow a
  9178. * maximum flexibility.
  9179. * Lua and CGI scripts may fully support CORS this way (including
  9180. * preflights). */
  9181. send_options(conn);
  9182. return;
  9183. }
  9184. /* 13.3. everything but GET and HEAD (e.g. POST) */
  9185. if (0 != strcmp(ri->request_method, "GET")
  9186. && 0 != strcmp(ri->request_method, "HEAD")) {
  9187. send_http_error(conn,
  9188. 405,
  9189. "%s method not allowed",
  9190. conn->request_info.request_method);
  9191. return;
  9192. }
  9193. /* 14. directories */
  9194. if (file.is_directory) {
  9195. if (substitute_index_file(conn, path, sizeof(path), &file)) {
  9196. /* 14.1. use a substitute file */
  9197. /* TODO (high): substitute index may be a script resource.
  9198. * define what should be possible in this case. */
  9199. } else {
  9200. /* 14.2. no substitute file */
  9201. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  9202. "yes")) {
  9203. handle_directory_request(conn, path);
  9204. } else {
  9205. send_http_error(conn,
  9206. 403,
  9207. "%s",
  9208. "Error: Directory listing denied");
  9209. }
  9210. return;
  9211. }
  9212. }
  9213. handle_file_based_request(conn, path, &file);
  9214. #endif /* !defined(NO_FILES) */
  9215. #if 0
  9216. /* Perform redirect and auth checks before calling begin_request()
  9217. * handler.
  9218. * Otherwise, begin_request() would need to perform auth checks and
  9219. * redirects. */
  9220. #endif
  9221. }
  9222. return;
  9223. }
  9224. static void
  9225. handle_file_based_request(struct mg_connection *conn,
  9226. const char *path,
  9227. struct file *file)
  9228. {
  9229. if (!conn || !conn->ctx) {
  9230. return;
  9231. }
  9232. if (0) {
  9233. #ifdef USE_LUA
  9234. } else if (match_prefix(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  9235. strlen(
  9236. conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  9237. path) > 0) {
  9238. /* Lua server page: an SSI like page containing mostly plain html
  9239. * code
  9240. * plus some tags with server generated contents. */
  9241. handle_lsp_request(conn, path, file, NULL);
  9242. } else if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  9243. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  9244. path) > 0) {
  9245. /* Lua in-server module script: a CGI like script used to generate
  9246. * the
  9247. * entire reply. */
  9248. mg_exec_lua_script(conn, path, NULL);
  9249. #endif
  9250. #if defined(USE_DUKTAPE)
  9251. } else if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  9252. strlen(
  9253. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  9254. path) > 0) {
  9255. /* Call duktape to generate the page */
  9256. mg_exec_duktape_script(conn, path);
  9257. #endif
  9258. #if !defined(NO_CGI)
  9259. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  9260. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  9261. path) > 0) {
  9262. /* CGI scripts may support all HTTP methods */
  9263. handle_cgi_request(conn, path);
  9264. #endif /* !NO_CGI */
  9265. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  9266. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  9267. path) > 0) {
  9268. handle_ssi_file_request(conn, path, file);
  9269. #if !defined(NO_CACHING)
  9270. } else if ((!conn->in_error_handler) && is_not_modified(conn, file)) {
  9271. /* Send 304 "Not Modified" - this must not send any body data */
  9272. handle_not_modified_static_file_request(conn, file);
  9273. #endif /* !NO_CACHING */
  9274. } else {
  9275. handle_static_file_request(conn, path, file, NULL, NULL);
  9276. }
  9277. }
  9278. static void
  9279. close_all_listening_sockets(struct mg_context *ctx)
  9280. {
  9281. unsigned int i;
  9282. if (!ctx) {
  9283. return;
  9284. }
  9285. for (i = 0; i < ctx->num_listening_sockets; i++) {
  9286. closesocket(ctx->listening_sockets[i].sock);
  9287. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  9288. }
  9289. mg_free(ctx->listening_sockets);
  9290. ctx->listening_sockets = NULL;
  9291. mg_free(ctx->listening_socket_fds);
  9292. ctx->listening_socket_fds = NULL;
  9293. }
  9294. /* Valid listening port specification is: [ip_address:]port[s]
  9295. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  9296. * Examples for IPv6: [::]:80, [::1]:80,
  9297. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  9298. * see https://tools.ietf.org/html/rfc3513#section-2.2
  9299. * In order to bind to both, IPv4 and IPv6, you can either add
  9300. * both ports using 8080,[::]:8080, or the short form +8080.
  9301. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  9302. * one only accepting IPv4 the other only IPv6. +8080 creates
  9303. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  9304. * environment, they might work differently, or might not work
  9305. * at all - it must be tested what options work best in the
  9306. * relevant network environment.
  9307. */
  9308. static int
  9309. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  9310. {
  9311. unsigned int a, b, c, d, port;
  9312. int ch, len;
  9313. #if defined(USE_IPV6)
  9314. char buf[100] = {0};
  9315. #endif
  9316. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  9317. * Also, all-zeroes in the socket address means binding to all addresses
  9318. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  9319. memset(so, 0, sizeof(*so));
  9320. so->lsa.sin.sin_family = AF_INET;
  9321. *ip_version = 0;
  9322. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  9323. == 5) {
  9324. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  9325. so->lsa.sin.sin_addr.s_addr =
  9326. htonl((a << 24) | (b << 16) | (c << 8) | d);
  9327. so->lsa.sin.sin_port = htons((uint16_t)port);
  9328. *ip_version = 4;
  9329. #if defined(USE_IPV6)
  9330. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  9331. && mg_inet_pton(
  9332. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  9333. /* IPv6 address, examples: see above */
  9334. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  9335. */
  9336. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  9337. *ip_version = 6;
  9338. #endif
  9339. } else if ((vec->ptr[0] == '+')
  9340. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  9341. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  9342. /* Add 1 to len for the + character we skipped before */
  9343. len++;
  9344. #if defined(USE_IPV6)
  9345. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  9346. so->lsa.sin6.sin6_family = AF_INET6;
  9347. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  9348. *ip_version = 4 + 6;
  9349. #else
  9350. /* Bind to IPv4 only, since IPv6 is not built in. */
  9351. so->lsa.sin.sin_port = htons((uint16_t)port);
  9352. *ip_version = 4;
  9353. #endif
  9354. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  9355. /* If only port is specified, bind to IPv4, INADDR_ANY */
  9356. so->lsa.sin.sin_port = htons((uint16_t)port);
  9357. *ip_version = 4;
  9358. } else {
  9359. /* Parsing failure. Make port invalid. */
  9360. port = 0;
  9361. len = 0;
  9362. }
  9363. /* sscanf and the option splitting code ensure the following condition
  9364. */
  9365. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  9366. *ip_version = 0;
  9367. return 0;
  9368. }
  9369. ch = vec->ptr[len]; /* Next character after the port number */
  9370. so->is_ssl = (ch == 's');
  9371. so->ssl_redir = (ch == 'r');
  9372. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  9373. if (is_valid_port(port)
  9374. && (ch == '\0' || ch == 's' || ch == 'r' || ch == ',')) {
  9375. return 1;
  9376. }
  9377. /* Reset ip_version to 0 of there is an error */
  9378. *ip_version = 0;
  9379. return 0;
  9380. }
  9381. static int
  9382. set_ports_option(struct mg_context *ctx)
  9383. {
  9384. const char *list;
  9385. int on = 1;
  9386. #if defined(USE_IPV6)
  9387. int off = 0;
  9388. #endif
  9389. struct vec vec;
  9390. struct socket so, *ptr;
  9391. struct pollfd *pfd;
  9392. union usa usa;
  9393. socklen_t len;
  9394. int ip_version;
  9395. int portsTotal = 0;
  9396. int portsOk = 0;
  9397. if (!ctx) {
  9398. return 0;
  9399. }
  9400. memset(&so, 0, sizeof(so));
  9401. memset(&usa, 0, sizeof(usa));
  9402. len = sizeof(usa);
  9403. list = ctx->config[LISTENING_PORTS];
  9404. while ((list = next_option(list, &vec, NULL)) != NULL) {
  9405. portsTotal++;
  9406. if (!parse_port_string(&vec, &so, &ip_version)) {
  9407. mg_cry(fc(ctx),
  9408. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  9409. (int)vec.len,
  9410. vec.ptr,
  9411. portsTotal,
  9412. "[IP_ADDRESS:]PORT[s|r]");
  9413. continue;
  9414. }
  9415. #if !defined(NO_SSL)
  9416. if (so.is_ssl && ctx->ssl_ctx == NULL) {
  9417. mg_cry(fc(ctx),
  9418. "Cannot add SSL socket (entry %i). Is -ssl_certificate "
  9419. "option set?",
  9420. portsTotal);
  9421. continue;
  9422. }
  9423. #endif
  9424. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  9425. == INVALID_SOCKET) {
  9426. mg_cry(fc(ctx), "cannot create socket (entry %i)", portsTotal);
  9427. continue;
  9428. }
  9429. #ifdef _WIN32
  9430. /* Windows SO_REUSEADDR lets many procs binds to a
  9431. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  9432. * if someone already has the socket -- DTL */
  9433. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  9434. * Windows might need a few seconds before
  9435. * the same port can be used again in the
  9436. * same process, so a short Sleep may be
  9437. * required between mg_stop and mg_start.
  9438. */
  9439. if (setsockopt(so.sock,
  9440. SOL_SOCKET,
  9441. SO_EXCLUSIVEADDRUSE,
  9442. (SOCK_OPT_TYPE)&on,
  9443. sizeof(on)) != 0) {
  9444. /* Set reuse option, but don't abort on errors. */
  9445. mg_cry(fc(ctx),
  9446. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  9447. portsTotal);
  9448. }
  9449. #else
  9450. if (setsockopt(so.sock,
  9451. SOL_SOCKET,
  9452. SO_REUSEADDR,
  9453. (SOCK_OPT_TYPE)&on,
  9454. sizeof(on)) != 0) {
  9455. /* Set reuse option, but don't abort on errors. */
  9456. mg_cry(fc(ctx),
  9457. "cannot set socket option SO_REUSEADDR (entry %i)",
  9458. portsTotal);
  9459. }
  9460. #endif
  9461. if (ip_version > 4) {
  9462. #if defined(USE_IPV6)
  9463. if (ip_version == 6) {
  9464. if (so.lsa.sa.sa_family == AF_INET6
  9465. && setsockopt(so.sock,
  9466. IPPROTO_IPV6,
  9467. IPV6_V6ONLY,
  9468. (void *)&off,
  9469. sizeof(off)) != 0) {
  9470. /* Set IPv6 only option, but don't abort on errors. */
  9471. mg_cry(fc(ctx),
  9472. "cannot set socket option IPV6_V6ONLY (entry %i)",
  9473. portsTotal);
  9474. }
  9475. }
  9476. #else
  9477. mg_cry(fc(ctx), "IPv6 not available");
  9478. closesocket(so.sock);
  9479. so.sock = INVALID_SOCKET;
  9480. continue;
  9481. #endif
  9482. }
  9483. if (so.lsa.sa.sa_family == AF_INET) {
  9484. len = sizeof(so.lsa.sin);
  9485. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  9486. mg_cry(fc(ctx),
  9487. "cannot bind to %.*s: %d (%s)",
  9488. (int)vec.len,
  9489. vec.ptr,
  9490. (int)ERRNO,
  9491. strerror(errno));
  9492. closesocket(so.sock);
  9493. so.sock = INVALID_SOCKET;
  9494. continue;
  9495. }
  9496. }
  9497. #if defined(USE_IPV6)
  9498. else if (so.lsa.sa.sa_family == AF_INET6) {
  9499. len = sizeof(so.lsa.sin6);
  9500. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  9501. mg_cry(fc(ctx),
  9502. "cannot bind to IPv6 %.*s: %d (%s)",
  9503. (int)vec.len,
  9504. vec.ptr,
  9505. (int)ERRNO,
  9506. strerror(errno));
  9507. closesocket(so.sock);
  9508. so.sock = INVALID_SOCKET;
  9509. continue;
  9510. }
  9511. }
  9512. #endif
  9513. else {
  9514. mg_cry(fc(ctx),
  9515. "cannot bind: address family not supported (entry %i)",
  9516. portsTotal);
  9517. continue;
  9518. }
  9519. if (listen(so.sock, SOMAXCONN) != 0) {
  9520. mg_cry(fc(ctx),
  9521. "cannot listen to %.*s: %d (%s)",
  9522. (int)vec.len,
  9523. vec.ptr,
  9524. (int)ERRNO,
  9525. strerror(errno));
  9526. closesocket(so.sock);
  9527. so.sock = INVALID_SOCKET;
  9528. continue;
  9529. }
  9530. if (getsockname(so.sock, &(usa.sa), &len) != 0
  9531. || usa.sa.sa_family != so.lsa.sa.sa_family) {
  9532. int err = (int)ERRNO;
  9533. mg_cry(fc(ctx),
  9534. "call to getsockname failed %.*s: %d (%s)",
  9535. (int)vec.len,
  9536. vec.ptr,
  9537. err,
  9538. strerror(errno));
  9539. closesocket(so.sock);
  9540. so.sock = INVALID_SOCKET;
  9541. continue;
  9542. }
  9543. /* Update lsa port in case of random free ports */
  9544. #if defined(USE_IPV6)
  9545. if (so.lsa.sa.sa_family == AF_INET6) {
  9546. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  9547. } else
  9548. #endif
  9549. {
  9550. so.lsa.sin.sin_port = usa.sin.sin_port;
  9551. }
  9552. if ((ptr = (struct socket *)
  9553. mg_realloc(ctx->listening_sockets,
  9554. (ctx->num_listening_sockets + 1)
  9555. * sizeof(ctx->listening_sockets[0]))) == NULL) {
  9556. mg_cry(fc(ctx), "%s", "Out of memory");
  9557. closesocket(so.sock);
  9558. so.sock = INVALID_SOCKET;
  9559. continue;
  9560. }
  9561. if ((pfd = (struct pollfd *)mg_realloc(
  9562. ctx->listening_socket_fds,
  9563. (ctx->num_listening_sockets + 1)
  9564. * sizeof(ctx->listening_socket_fds[0]))) == NULL) {
  9565. mg_cry(fc(ctx), "%s", "Out of memory");
  9566. closesocket(so.sock);
  9567. so.sock = INVALID_SOCKET;
  9568. mg_free(ptr);
  9569. continue;
  9570. }
  9571. set_close_on_exec(so.sock, fc(ctx));
  9572. ctx->listening_sockets = ptr;
  9573. ctx->listening_sockets[ctx->num_listening_sockets] = so;
  9574. ctx->listening_socket_fds = pfd;
  9575. ctx->num_listening_sockets++;
  9576. portsOk++;
  9577. }
  9578. if (portsOk != portsTotal) {
  9579. close_all_listening_sockets(ctx);
  9580. portsOk = 0;
  9581. }
  9582. return portsOk;
  9583. }
  9584. static const char *
  9585. header_val(const struct mg_connection *conn, const char *header)
  9586. {
  9587. const char *header_value;
  9588. if ((header_value = mg_get_header(conn, header)) == NULL) {
  9589. return "-";
  9590. } else {
  9591. return header_value;
  9592. }
  9593. }
  9594. static void
  9595. log_access(const struct mg_connection *conn)
  9596. {
  9597. const struct mg_request_info *ri;
  9598. struct file fi;
  9599. char date[64], src_addr[IP_ADDR_STR_LEN];
  9600. struct tm *tm;
  9601. const char *referer;
  9602. const char *user_agent;
  9603. char buf[4096];
  9604. if (!conn || !conn->ctx) {
  9605. return;
  9606. }
  9607. if (conn->ctx->config[ACCESS_LOG_FILE] != NULL) {
  9608. if (mg_fopen(conn, conn->ctx->config[ACCESS_LOG_FILE], "a+", &fi)
  9609. == 0) {
  9610. fi.fp = NULL;
  9611. }
  9612. } else {
  9613. fi.fp = NULL;
  9614. }
  9615. /* Log is written to a file and/or a callback. If both are not set,
  9616. * executing the rest of the function is pointless. */
  9617. if ((fi.fp == NULL) && (conn->ctx->callbacks.log_access == NULL)) {
  9618. return;
  9619. }
  9620. tm = localtime(&conn->conn_birth_time);
  9621. if (tm != NULL) {
  9622. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  9623. } else {
  9624. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  9625. date[sizeof(date) - 1] = '\0';
  9626. }
  9627. ri = &conn->request_info;
  9628. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9629. referer = header_val(conn, "Referer");
  9630. user_agent = header_val(conn, "User-Agent");
  9631. mg_snprintf(conn,
  9632. NULL, /* Ignore truncation in access log */
  9633. buf,
  9634. sizeof(buf),
  9635. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  9636. src_addr,
  9637. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  9638. date,
  9639. ri->request_method ? ri->request_method : "-",
  9640. ri->request_uri ? ri->request_uri : "-",
  9641. ri->query_string ? "?" : "",
  9642. ri->query_string ? ri->query_string : "",
  9643. ri->http_version,
  9644. conn->status_code,
  9645. conn->num_bytes_sent,
  9646. referer,
  9647. user_agent);
  9648. if (conn->ctx->callbacks.log_access) {
  9649. conn->ctx->callbacks.log_access(conn, buf);
  9650. }
  9651. if (fi.fp) {
  9652. flockfile(fi.fp);
  9653. fprintf(fi.fp, "%s\n", buf);
  9654. fflush(fi.fp);
  9655. funlockfile(fi.fp);
  9656. mg_fclose(&fi);
  9657. }
  9658. }
  9659. /* Verify given socket address against the ACL.
  9660. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  9661. */
  9662. static int
  9663. check_acl(struct mg_context *ctx, uint32_t remote_ip)
  9664. {
  9665. int allowed, flag;
  9666. uint32_t net, mask;
  9667. struct vec vec;
  9668. if (ctx) {
  9669. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  9670. /* If any ACL is set, deny by default */
  9671. allowed = (list == NULL) ? '+' : '-';
  9672. while ((list = next_option(list, &vec, NULL)) != NULL) {
  9673. flag = vec.ptr[0];
  9674. if ((flag != '+' && flag != '-')
  9675. || parse_net(&vec.ptr[1], &net, &mask) == 0) {
  9676. mg_cry(fc(ctx),
  9677. "%s: subnet must be [+|-]x.x.x.x[/x]",
  9678. __func__);
  9679. return -1;
  9680. }
  9681. if (net == (remote_ip & mask)) {
  9682. allowed = flag;
  9683. }
  9684. }
  9685. return allowed == '+';
  9686. }
  9687. return -1;
  9688. }
  9689. #if !defined(_WIN32)
  9690. static int
  9691. set_uid_option(struct mg_context *ctx)
  9692. {
  9693. struct passwd *pw;
  9694. if (ctx) {
  9695. const char *uid = ctx->config[RUN_AS_USER];
  9696. int success = 0;
  9697. if (uid == NULL) {
  9698. success = 1;
  9699. } else {
  9700. if ((pw = getpwnam(uid)) == NULL) {
  9701. mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  9702. } else if (setgid(pw->pw_gid) == -1) {
  9703. mg_cry(fc(ctx),
  9704. "%s: setgid(%s): %s",
  9705. __func__,
  9706. uid,
  9707. strerror(errno));
  9708. } else if (setgroups(0, NULL)) {
  9709. mg_cry(fc(ctx),
  9710. "%s: setgroups(): %s",
  9711. __func__,
  9712. strerror(errno));
  9713. } else if (setuid(pw->pw_uid) == -1) {
  9714. mg_cry(fc(ctx),
  9715. "%s: setuid(%s): %s",
  9716. __func__,
  9717. uid,
  9718. strerror(errno));
  9719. } else {
  9720. success = 1;
  9721. }
  9722. }
  9723. return success;
  9724. }
  9725. return 0;
  9726. }
  9727. #endif /* !_WIN32 */
  9728. static void
  9729. tls_dtor(void *key)
  9730. {
  9731. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  9732. /* key == pthread_getspecific(sTlsKey); */
  9733. if (tls) {
  9734. if (tls->is_master == 2) {
  9735. tls->is_master = -3; /* Mark memory as dead */
  9736. mg_free(tls);
  9737. }
  9738. }
  9739. pthread_setspecific(sTlsKey, NULL);
  9740. }
  9741. #if !defined(NO_SSL)
  9742. /* Must be set if sizeof(pthread_t) > sizeof(unsigned long) */
  9743. static unsigned long
  9744. ssl_id_callback(void)
  9745. {
  9746. #ifdef _WIN32
  9747. return GetCurrentThreadId();
  9748. #else
  9749. #ifdef __clang__
  9750. #pragma clang diagnostic push
  9751. #pragma clang diagnostic ignored "-Wunreachable-code"
  9752. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  9753. * or not, so one of the two conditions will be unreachable by construction.
  9754. * Unfortunately the C standard does not define a way to check this at
  9755. * compile time, since the #if preprocessor conditions can not use the sizeof
  9756. * operator as an argument. */
  9757. #endif
  9758. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  9759. /* This is the problematic case for CRYPTO_set_id_callback:
  9760. * The OS pthread_t can not be cast to unsigned long. */
  9761. struct mg_workerTLS *tls =
  9762. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  9763. if (tls == NULL) {
  9764. /* SSL called from an unknown thread: Create some thread index.
  9765. */
  9766. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  9767. tls->is_master = -2; /* -2 means "3rd party thread" */
  9768. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  9769. pthread_setspecific(sTlsKey, tls);
  9770. }
  9771. return tls->thread_idx;
  9772. } else {
  9773. /* pthread_t may be any data type, so a simple cast to unsigned long
  9774. * can rise a warning/error, depending on the platform.
  9775. * Here memcpy is used as an anything-to-anything cast. */
  9776. unsigned long ret = 0;
  9777. pthread_t t = pthread_self();
  9778. memcpy(&ret, &t, sizeof(pthread_t));
  9779. return ret;
  9780. }
  9781. #ifdef __clang__
  9782. #pragma clang diagnostic pop
  9783. #endif
  9784. #endif
  9785. }
  9786. static int ssl_use_pem_file(struct mg_context *ctx, const char *pem);
  9787. static const char *ssl_error(void);
  9788. static int
  9789. refresh_trust(struct mg_connection *conn)
  9790. {
  9791. static int reload_lock = 0;
  9792. static long int data_check = 0;
  9793. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  9794. struct stat cert_buf;
  9795. long int t;
  9796. char *pem;
  9797. int should_verify_peer;
  9798. if ((pem = conn->ctx->config[SSL_CERTIFICATE]) == NULL
  9799. && conn->ctx->callbacks.init_ssl == NULL) {
  9800. return 0;
  9801. }
  9802. t = data_check;
  9803. if (stat(pem, &cert_buf) != -1) {
  9804. t = (long int)cert_buf.st_mtime;
  9805. }
  9806. if (data_check != t) {
  9807. data_check = t;
  9808. should_verify_peer =
  9809. (conn->ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  9810. && (mg_strcasecmp(conn->ctx->config[SSL_DO_VERIFY_PEER], "yes")
  9811. == 0);
  9812. if (should_verify_peer) {
  9813. char *ca_path = conn->ctx->config[SSL_CA_PATH];
  9814. char *ca_file = conn->ctx->config[SSL_CA_FILE];
  9815. if (SSL_CTX_load_verify_locations(conn->ctx->ssl_ctx,
  9816. ca_file,
  9817. ca_path) != 1) {
  9818. mg_cry(fc(conn->ctx),
  9819. "SSL_CTX_load_verify_locations error: %s "
  9820. "ssl_verify_peer requires setting "
  9821. "either ssl_ca_path or ssl_ca_file. Is any of them "
  9822. "present in "
  9823. "the .conf file?",
  9824. ssl_error());
  9825. return 0;
  9826. }
  9827. }
  9828. if (1 == mg_atomic_inc(p_reload_lock)) {
  9829. if (ssl_use_pem_file(conn->ctx, pem) == 0) {
  9830. return 0;
  9831. }
  9832. *p_reload_lock = 0;
  9833. }
  9834. }
  9835. /* lock while cert is reloading */
  9836. while (*p_reload_lock) {
  9837. sleep(1);
  9838. }
  9839. return 1;
  9840. }
  9841. static pthread_mutex_t *ssl_mutexes;
  9842. static int
  9843. sslize(struct mg_connection *conn, SSL_CTX *s, int (*func)(SSL *))
  9844. {
  9845. int ret, err;
  9846. int short_trust;
  9847. unsigned i;
  9848. if (!conn) {
  9849. return 0;
  9850. }
  9851. short_trust =
  9852. (conn->ctx->config[SSL_SHORT_TRUST] != NULL)
  9853. && (mg_strcasecmp(conn->ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  9854. if (short_trust) {
  9855. int trust_ret = refresh_trust(conn);
  9856. if (!trust_ret) {
  9857. return trust_ret;
  9858. }
  9859. }
  9860. conn->ssl = SSL_new(s);
  9861. if (conn->ssl == NULL) {
  9862. return 0;
  9863. }
  9864. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  9865. if (ret != 1) {
  9866. err = SSL_get_error(conn->ssl, ret);
  9867. (void)err; /* TODO: set some error message */
  9868. SSL_free(conn->ssl);
  9869. conn->ssl = NULL;
  9870. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  9871. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  9872. ERR_remove_state(0);
  9873. return 0;
  9874. }
  9875. /* SSL functions may fail and require to be called again:
  9876. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  9877. * Here "func" could be SSL_connect or SSL_accept. */
  9878. for (i = 1; i <= 16; i *= 2) {
  9879. ret = func(conn->ssl);
  9880. if (ret != 1) {
  9881. err = SSL_get_error(conn->ssl, ret);
  9882. if ((err == SSL_ERROR_WANT_CONNECT)
  9883. || (err == SSL_ERROR_WANT_ACCEPT)) {
  9884. /* Retry */
  9885. mg_sleep(i);
  9886. } else {
  9887. /* This is an error */
  9888. /* TODO: set some error message */
  9889. break;
  9890. }
  9891. } else {
  9892. /* success */
  9893. break;
  9894. }
  9895. }
  9896. if (ret != 1) {
  9897. SSL_free(conn->ssl);
  9898. conn->ssl = NULL;
  9899. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  9900. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  9901. ERR_remove_state(0);
  9902. return 0;
  9903. }
  9904. return 1;
  9905. }
  9906. /* Return OpenSSL error message (from CRYPTO lib) */
  9907. static const char *
  9908. ssl_error(void)
  9909. {
  9910. unsigned long err;
  9911. err = ERR_get_error();
  9912. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  9913. }
  9914. static int
  9915. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  9916. {
  9917. int i;
  9918. const char hexdigit[] = "0123456789abcdef";
  9919. if (memlen <= 0 || buflen <= 0) {
  9920. return 0;
  9921. }
  9922. if (buflen < (3 * memlen)) {
  9923. return 0;
  9924. }
  9925. for (i = 0; i < memlen; i++) {
  9926. if (i > 0) {
  9927. buf[3 * i - 1] = ' ';
  9928. }
  9929. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  9930. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  9931. }
  9932. buf[3 * memlen - 1] = 0;
  9933. return 1;
  9934. }
  9935. static void
  9936. ssl_get_client_cert_info(struct mg_connection *conn)
  9937. {
  9938. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  9939. if (cert) {
  9940. char str_subject[1024];
  9941. char str_issuer[1024];
  9942. char str_serial[1024];
  9943. char str_finger[1024];
  9944. unsigned char buf[256];
  9945. int len;
  9946. unsigned int ulen;
  9947. /* Handle to algorithm used for fingerprint */
  9948. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  9949. /* Get Subject and issuer */
  9950. X509_NAME *subj = X509_get_subject_name(cert);
  9951. X509_NAME *iss = X509_get_issuer_name(cert);
  9952. /* Get serial number */
  9953. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  9954. /* Translate subject and issuer to a string */
  9955. (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
  9956. (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
  9957. /* Translate serial number to a hex string */
  9958. len = i2c_ASN1_INTEGER(serial, NULL);
  9959. if ((len > 0) && ((unsigned)len < (unsigned)sizeof(buf))) {
  9960. unsigned char *pbuf = buf;
  9961. int len2 = i2c_ASN1_INTEGER(serial, &pbuf);
  9962. if (!hexdump2string(
  9963. buf, len2, str_serial, (int)sizeof(str_serial))) {
  9964. *str_serial = 0;
  9965. }
  9966. } else {
  9967. *str_serial = 0;
  9968. }
  9969. /* Calculate SHA1 fingerprint and store as a hex string */
  9970. ulen = 0;
  9971. ASN1_digest((int (*)())i2d_X509, digest, (char *)cert, buf, &ulen);
  9972. if (!hexdump2string(
  9973. buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
  9974. *str_finger = 0;
  9975. }
  9976. conn->request_info.client_cert =
  9977. (struct client_cert *)mg_malloc(sizeof(struct client_cert));
  9978. if (conn->request_info.client_cert) {
  9979. conn->request_info.client_cert->subject = mg_strdup(str_subject);
  9980. conn->request_info.client_cert->issuer = mg_strdup(str_issuer);
  9981. conn->request_info.client_cert->serial = mg_strdup(str_serial);
  9982. conn->request_info.client_cert->finger = mg_strdup(str_finger);
  9983. } else {
  9984. /* TODO: write some OOM message */
  9985. }
  9986. X509_free(cert);
  9987. }
  9988. }
  9989. static void
  9990. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  9991. {
  9992. (void)line;
  9993. (void)file;
  9994. if (mode & 1) {
  9995. /* 1 is CRYPTO_LOCK */
  9996. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  9997. } else {
  9998. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  9999. }
  10000. }
  10001. #if !defined(NO_SSL_DL)
  10002. static void *
  10003. load_dll(struct mg_context *ctx, const char *dll_name, struct ssl_func *sw)
  10004. {
  10005. union {
  10006. void *p;
  10007. void (*fp)(void);
  10008. } u;
  10009. void *dll_handle;
  10010. struct ssl_func *fp;
  10011. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  10012. mg_cry(fc(ctx), "%s: cannot load %s", __func__, dll_name);
  10013. return NULL;
  10014. }
  10015. for (fp = sw; fp->name != NULL; fp++) {
  10016. #ifdef _WIN32
  10017. /* GetProcAddress() returns pointer to function */
  10018. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  10019. #else
  10020. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  10021. * pointers to function pointers. We need to use a union to make a
  10022. * cast. */
  10023. u.p = dlsym(dll_handle, fp->name);
  10024. #endif /* _WIN32 */
  10025. if (u.fp == NULL) {
  10026. mg_cry(fc(ctx),
  10027. "%s: %s: cannot find %s",
  10028. __func__,
  10029. dll_name,
  10030. fp->name);
  10031. dlclose(dll_handle);
  10032. return NULL;
  10033. } else {
  10034. fp->ptr = u.fp;
  10035. }
  10036. }
  10037. return dll_handle;
  10038. }
  10039. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  10040. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  10041. #endif /* NO_SSL_DL */
  10042. #if defined(SSL_ALREADY_INITIALIZED)
  10043. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  10044. #else
  10045. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  10046. #endif
  10047. static int
  10048. initialize_ssl(struct mg_context *ctx)
  10049. {
  10050. int i;
  10051. size_t size;
  10052. #if !defined(NO_SSL_DL)
  10053. if (!cryptolib_dll_handle) {
  10054. cryptolib_dll_handle = load_dll(ctx, CRYPTO_LIB, crypto_sw);
  10055. if (!cryptolib_dll_handle) {
  10056. return 0;
  10057. }
  10058. }
  10059. #endif /* NO_SSL_DL */
  10060. if (mg_atomic_inc(&cryptolib_users) > 1) {
  10061. return 1;
  10062. }
  10063. /* Initialize locking callbacks, needed for thread safety.
  10064. * http://www.openssl.org/support/faq.html#PROG1
  10065. */
  10066. i = CRYPTO_num_locks();
  10067. if (i < 0) {
  10068. i = 0;
  10069. }
  10070. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  10071. if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  10072. mg_cry(fc(ctx),
  10073. "%s: cannot allocate mutexes: %s",
  10074. __func__,
  10075. ssl_error());
  10076. return 0;
  10077. }
  10078. for (i = 0; i < CRYPTO_num_locks(); i++) {
  10079. pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr);
  10080. }
  10081. CRYPTO_set_locking_callback(&ssl_locking_callback);
  10082. CRYPTO_set_id_callback(&ssl_id_callback);
  10083. return 1;
  10084. }
  10085. static int
  10086. ssl_use_pem_file(struct mg_context *ctx, const char *pem)
  10087. {
  10088. if (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0) {
  10089. mg_cry(fc(ctx),
  10090. "%s: cannot open certificate file %s: %s",
  10091. __func__,
  10092. pem,
  10093. ssl_error());
  10094. return 0;
  10095. }
  10096. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  10097. if (SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0) {
  10098. mg_cry(fc(ctx),
  10099. "%s: cannot open private key file %s: %s",
  10100. __func__,
  10101. pem,
  10102. ssl_error());
  10103. return 0;
  10104. }
  10105. if (SSL_CTX_check_private_key(ctx->ssl_ctx) == 0) {
  10106. mg_cry(fc(ctx),
  10107. "%s: certificate and private key do not match: %s",
  10108. __func__,
  10109. pem);
  10110. return 0;
  10111. }
  10112. if (SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem) == 0) {
  10113. mg_cry(fc(ctx),
  10114. "%s: cannot use certificate chain file %s: %s",
  10115. __func__,
  10116. pem,
  10117. ssl_error());
  10118. return 0;
  10119. }
  10120. return 1;
  10121. }
  10122. static long
  10123. ssl_get_protocol(int version_id)
  10124. {
  10125. long ret = SSL_OP_ALL;
  10126. if (version_id > 0)
  10127. ret |= SSL_OP_NO_SSLv2;
  10128. if (version_id > 1)
  10129. ret |= SSL_OP_NO_SSLv3;
  10130. if (version_id > 2)
  10131. ret |= SSL_OP_NO_TLSv1;
  10132. if (version_id > 3)
  10133. ret |= SSL_OP_NO_TLSv1_1;
  10134. return ret;
  10135. }
  10136. /* Dynamically load SSL library. Set up ctx->ssl_ctx pointer. */
  10137. static int
  10138. set_ssl_option(struct mg_context *ctx)
  10139. {
  10140. const char *pem;
  10141. int callback_ret;
  10142. int should_verify_peer;
  10143. const char *ca_path;
  10144. const char *ca_file;
  10145. int use_default_verify_paths;
  10146. int verify_depth;
  10147. time_t now_rt = time(NULL);
  10148. struct timespec now_mt;
  10149. md5_byte_t ssl_context_id[16];
  10150. md5_state_t md5state;
  10151. int protocol_ver;
  10152. /* If PEM file is not specified and the init_ssl callback
  10153. * is not specified, skip SSL initialization. */
  10154. if (!ctx) {
  10155. return 0;
  10156. }
  10157. if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL
  10158. && ctx->callbacks.init_ssl == NULL) {
  10159. return 1;
  10160. }
  10161. if (!initialize_ssl(ctx)) {
  10162. return 0;
  10163. }
  10164. #if !defined(NO_SSL_DL)
  10165. if (!ssllib_dll_handle) {
  10166. ssllib_dll_handle = load_dll(ctx, SSL_LIB, ssl_sw);
  10167. if (!ssllib_dll_handle) {
  10168. return 0;
  10169. }
  10170. }
  10171. #endif /* NO_SSL_DL */
  10172. /* Initialize SSL library */
  10173. SSL_library_init();
  10174. SSL_load_error_strings();
  10175. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  10176. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  10177. return 0;
  10178. }
  10179. SSL_CTX_clear_options(ctx->ssl_ctx,
  10180. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  10181. | SSL_OP_NO_TLSv1_1);
  10182. protocol_ver = atoi(ctx->config[SSL_PROTOCOL_VERSION]);
  10183. SSL_CTX_set_options(ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  10184. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  10185. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  10186. SSL_CTX_set_ecdh_auto(ctx->ssl_ctx, 1);
  10187. /* If a callback has been specified, call it. */
  10188. callback_ret =
  10189. (ctx->callbacks.init_ssl == NULL)
  10190. ? 0
  10191. : (ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data));
  10192. /* If callback returns 0, civetweb sets up the SSL certificate.
  10193. * If it returns 1, civetweb assumes the calback already did this.
  10194. * If it returns -1, initializing ssl fails. */
  10195. if (callback_ret < 0) {
  10196. mg_cry(fc(ctx), "SSL callback returned error: %i", callback_ret);
  10197. return 0;
  10198. }
  10199. if (callback_ret > 0) {
  10200. if (pem != NULL) {
  10201. (void)SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
  10202. }
  10203. return 1;
  10204. }
  10205. /* Use some UID as session context ID. */
  10206. md5_init(&md5state);
  10207. md5_append(&md5state, (const md5_byte_t *)&now_rt, sizeof(now_rt));
  10208. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  10209. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  10210. md5_append(&md5state,
  10211. (const md5_byte_t *)ctx->config[LISTENING_PORTS],
  10212. strlen(ctx->config[LISTENING_PORTS]));
  10213. md5_append(&md5state, (const md5_byte_t *)ctx, sizeof(*ctx));
  10214. md5_finish(&md5state, ssl_context_id);
  10215. SSL_CTX_set_session_id_context(ctx->ssl_ctx,
  10216. (const unsigned char *)&ssl_context_id,
  10217. sizeof(ssl_context_id));
  10218. if (pem != NULL) {
  10219. if (!ssl_use_pem_file(ctx, pem)) {
  10220. return 0;
  10221. }
  10222. }
  10223. should_verify_peer =
  10224. (ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  10225. && (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0);
  10226. use_default_verify_paths =
  10227. (ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  10228. && (mg_strcasecmp(ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes") == 0);
  10229. if (should_verify_peer) {
  10230. ca_path = ctx->config[SSL_CA_PATH];
  10231. ca_file = ctx->config[SSL_CA_FILE];
  10232. if (SSL_CTX_load_verify_locations(ctx->ssl_ctx, ca_file, ca_path)
  10233. != 1) {
  10234. mg_cry(fc(ctx),
  10235. "SSL_CTX_load_verify_locations error: %s "
  10236. "ssl_verify_peer requires setting "
  10237. "either ssl_ca_path or ssl_ca_file. Is any of them "
  10238. "present in "
  10239. "the .conf file?",
  10240. ssl_error());
  10241. return 0;
  10242. }
  10243. SSL_CTX_set_verify(ctx->ssl_ctx,
  10244. SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  10245. NULL);
  10246. if (use_default_verify_paths
  10247. && SSL_CTX_set_default_verify_paths(ctx->ssl_ctx) != 1) {
  10248. mg_cry(fc(ctx),
  10249. "SSL_CTX_set_default_verify_paths error: %s",
  10250. ssl_error());
  10251. return 0;
  10252. }
  10253. if (ctx->config[SSL_VERIFY_DEPTH]) {
  10254. verify_depth = atoi(ctx->config[SSL_VERIFY_DEPTH]);
  10255. SSL_CTX_set_verify_depth(ctx->ssl_ctx, verify_depth);
  10256. }
  10257. }
  10258. if (ctx->config[SSL_CIPHER_LIST] != NULL) {
  10259. if (SSL_CTX_set_cipher_list(ctx->ssl_ctx, ctx->config[SSL_CIPHER_LIST])
  10260. != 1) {
  10261. mg_cry(fc(ctx), "SSL_CTX_set_cipher_list error: %s", ssl_error());
  10262. }
  10263. }
  10264. return 1;
  10265. }
  10266. static void
  10267. uninitialize_ssl(struct mg_context *ctx)
  10268. {
  10269. int i;
  10270. (void)ctx;
  10271. if (mg_atomic_dec(&cryptolib_users) == 0) {
  10272. /* Shutdown according to
  10273. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  10274. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  10275. */
  10276. CRYPTO_set_locking_callback(NULL);
  10277. CRYPTO_set_id_callback(NULL);
  10278. ENGINE_cleanup();
  10279. CONF_modules_unload(1);
  10280. ERR_free_strings();
  10281. EVP_cleanup();
  10282. CRYPTO_cleanup_all_ex_data();
  10283. ERR_remove_state(0);
  10284. for (i = 0; i < CRYPTO_num_locks(); i++) {
  10285. pthread_mutex_destroy(&ssl_mutexes[i]);
  10286. }
  10287. mg_free(ssl_mutexes);
  10288. ssl_mutexes = NULL;
  10289. }
  10290. }
  10291. #endif /* !NO_SSL */
  10292. static int
  10293. set_gpass_option(struct mg_context *ctx)
  10294. {
  10295. if (ctx) {
  10296. struct file file = STRUCT_FILE_INITIALIZER;
  10297. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  10298. if (path != NULL && !mg_stat(fc(ctx), path, &file)) {
  10299. mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  10300. return 0;
  10301. }
  10302. return 1;
  10303. }
  10304. return 0;
  10305. }
  10306. static int
  10307. set_acl_option(struct mg_context *ctx)
  10308. {
  10309. return check_acl(ctx, (uint32_t)0x7f000001UL) != -1;
  10310. }
  10311. static void
  10312. reset_per_request_attributes(struct mg_connection *conn)
  10313. {
  10314. if (!conn) {
  10315. return;
  10316. }
  10317. conn->path_info = NULL;
  10318. conn->num_bytes_sent = conn->consumed_content = 0;
  10319. conn->status_code = -1;
  10320. conn->is_chunked = 0;
  10321. conn->must_close = conn->request_len = conn->throttle = 0;
  10322. conn->request_info.content_length = -1;
  10323. conn->request_info.remote_user = NULL;
  10324. conn->request_info.request_method = NULL;
  10325. conn->request_info.request_uri = NULL;
  10326. conn->request_info.local_uri = NULL;
  10327. conn->request_info.uri = NULL; /* TODO: cleanup uri,
  10328. * local_uri and request_uri */
  10329. conn->request_info.http_version = NULL;
  10330. conn->request_info.num_headers = 0;
  10331. conn->data_len = 0;
  10332. conn->chunk_remainder = 0;
  10333. conn->internal_error = 0;
  10334. }
  10335. static int
  10336. set_sock_timeout(SOCKET sock, int milliseconds)
  10337. {
  10338. int r0 = 0, r1, r2;
  10339. #ifdef _WIN32
  10340. /* Windows specific */
  10341. DWORD tv = (DWORD)milliseconds;
  10342. #else
  10343. /* Linux, ... (not Windows) */
  10344. struct timeval tv;
  10345. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  10346. * max. time waiting for the acknowledged of TCP data before the connection
  10347. * will be forcefully closed and ETIMEDOUT is returned to the application.
  10348. * If this option is not set, the default timeout of 20-30 minutes is used.
  10349. */
  10350. /* #define TCP_USER_TIMEOUT (18) */
  10351. #if defined(TCP_USER_TIMEOUT)
  10352. unsigned int uto = (unsigned int)milliseconds;
  10353. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  10354. #endif
  10355. memset(&tv, 0, sizeof(tv));
  10356. tv.tv_sec = milliseconds / 1000;
  10357. tv.tv_usec = (milliseconds * 1000) % 1000000;
  10358. #endif /* _WIN32 */
  10359. r1 = setsockopt(
  10360. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  10361. r2 = setsockopt(
  10362. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  10363. return r0 || r1 || r2;
  10364. }
  10365. static int
  10366. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  10367. {
  10368. if (setsockopt(sock,
  10369. IPPROTO_TCP,
  10370. TCP_NODELAY,
  10371. (SOCK_OPT_TYPE)&nodelay_on,
  10372. sizeof(nodelay_on)) != 0) {
  10373. /* Error */
  10374. return 1;
  10375. }
  10376. /* OK */
  10377. return 0;
  10378. }
  10379. static void
  10380. close_socket_gracefully(struct mg_connection *conn)
  10381. {
  10382. #if defined(_WIN32)
  10383. char buf[MG_BUF_LEN];
  10384. int n;
  10385. #endif
  10386. struct linger linger;
  10387. int error_code = 0;
  10388. socklen_t opt_len = sizeof(error_code);
  10389. if (!conn) {
  10390. return;
  10391. }
  10392. /* Set linger option to avoid socket hanging out after close. This
  10393. * prevent ephemeral port exhaust problem under high QPS. */
  10394. linger.l_onoff = 1;
  10395. linger.l_linger = 1;
  10396. getsockopt(
  10397. conn->client.sock, SOL_SOCKET, SO_ERROR, (char *)&error_code, &opt_len);
  10398. if (error_code == ECONNRESET) {
  10399. /* Socket already closed by client/peer, close socket without linger */
  10400. } else {
  10401. if (setsockopt(conn->client.sock,
  10402. SOL_SOCKET,
  10403. SO_LINGER,
  10404. (char *)&linger,
  10405. sizeof(linger)) != 0) {
  10406. mg_cry(conn,
  10407. "%s: setsockopt(SOL_SOCKET SO_LINGER) failed: %s",
  10408. __func__,
  10409. strerror(ERRNO));
  10410. }
  10411. }
  10412. /* Send FIN to the client */
  10413. shutdown(conn->client.sock, SHUTDOWN_WR);
  10414. set_non_blocking_mode(conn->client.sock);
  10415. #if defined(_WIN32)
  10416. /* Read and discard pending incoming data. If we do not do that and
  10417. * close
  10418. * the socket, the data in the send buffer may be discarded. This
  10419. * behaviour is seen on Windows, when client keeps sending data
  10420. * when server decides to close the connection; then when client
  10421. * does recv() it gets no data back. */
  10422. do {
  10423. n = pull(
  10424. NULL, conn, buf, sizeof(buf), 1E-10 /* TODO: allow 0 as timeout */);
  10425. } while (n > 0);
  10426. #endif
  10427. /* Now we know that our FIN is ACK-ed, safe to close */
  10428. closesocket(conn->client.sock);
  10429. conn->client.sock = INVALID_SOCKET;
  10430. }
  10431. static void
  10432. close_connection(struct mg_connection *conn)
  10433. {
  10434. if (!conn || !conn->ctx) {
  10435. return;
  10436. }
  10437. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  10438. if (conn->lua_websocket_state) {
  10439. lua_websocket_close(conn, conn->lua_websocket_state);
  10440. conn->lua_websocket_state = NULL;
  10441. }
  10442. #endif
  10443. /* call the connection_close callback if assigned */
  10444. if ((conn->ctx->callbacks.connection_close != NULL)
  10445. && (conn->ctx->context_type == 1)) {
  10446. conn->ctx->callbacks.connection_close(conn);
  10447. }
  10448. mg_lock_connection(conn);
  10449. conn->must_close = 1;
  10450. #ifndef NO_SSL
  10451. if (conn->ssl != NULL) {
  10452. /* Run SSL_shutdown twice to ensure completly close SSL connection
  10453. */
  10454. SSL_shutdown(conn->ssl);
  10455. SSL_free(conn->ssl);
  10456. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  10457. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  10458. ERR_remove_state(0);
  10459. conn->ssl = NULL;
  10460. }
  10461. #endif
  10462. if (conn->client.sock != INVALID_SOCKET) {
  10463. close_socket_gracefully(conn);
  10464. conn->client.sock = INVALID_SOCKET;
  10465. }
  10466. mg_unlock_connection(conn);
  10467. }
  10468. void
  10469. mg_close_connection(struct mg_connection *conn)
  10470. {
  10471. struct mg_context *client_ctx = NULL;
  10472. unsigned int i;
  10473. if (conn == NULL) {
  10474. return;
  10475. }
  10476. if (conn->ctx->context_type == 2) {
  10477. client_ctx = conn->ctx;
  10478. /* client context: loops must end */
  10479. conn->ctx->stop_flag = 1;
  10480. }
  10481. #ifndef NO_SSL
  10482. if (conn->client_ssl_ctx != NULL) {
  10483. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  10484. }
  10485. #endif
  10486. close_connection(conn);
  10487. if (client_ctx != NULL) {
  10488. /* join worker thread and free context */
  10489. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  10490. if (client_ctx->workerthreadids[i] != 0) {
  10491. mg_join_thread(client_ctx->workerthreadids[i]);
  10492. }
  10493. }
  10494. mg_free(client_ctx->workerthreadids);
  10495. mg_free(client_ctx);
  10496. (void)pthread_mutex_destroy(&conn->mutex);
  10497. mg_free(conn);
  10498. }
  10499. }
  10500. static struct mg_connection *
  10501. mg_connect_client_impl(const struct mg_client_options *client_options,
  10502. int use_ssl,
  10503. char *ebuf,
  10504. size_t ebuf_len)
  10505. {
  10506. static struct mg_context fake_ctx;
  10507. struct mg_connection *conn = NULL;
  10508. SOCKET sock;
  10509. union usa sa;
  10510. if (!connect_socket(&fake_ctx,
  10511. client_options->host,
  10512. client_options->port,
  10513. use_ssl,
  10514. ebuf,
  10515. ebuf_len,
  10516. &sock,
  10517. &sa)) {
  10518. ;
  10519. } else if ((conn = (struct mg_connection *)
  10520. mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) {
  10521. mg_snprintf(NULL,
  10522. NULL, /* No truncation check for ebuf */
  10523. ebuf,
  10524. ebuf_len,
  10525. "calloc(): %s",
  10526. strerror(ERRNO));
  10527. closesocket(sock);
  10528. #ifndef NO_SSL
  10529. } else if (use_ssl
  10530. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  10531. == NULL) {
  10532. mg_snprintf(NULL,
  10533. NULL, /* No truncation check for ebuf */
  10534. ebuf,
  10535. ebuf_len,
  10536. "SSL_CTX_new error");
  10537. closesocket(sock);
  10538. mg_free(conn);
  10539. conn = NULL;
  10540. #endif /* NO_SSL */
  10541. } else {
  10542. #ifdef USE_IPV6
  10543. socklen_t len = (sa.sa.sa_family == AF_INET)
  10544. ? sizeof(conn->client.rsa.sin)
  10545. : sizeof(conn->client.rsa.sin6);
  10546. struct sockaddr *psa =
  10547. (sa.sa.sa_family == AF_INET)
  10548. ? (struct sockaddr *)&(conn->client.rsa.sin)
  10549. : (struct sockaddr *)&(conn->client.rsa.sin6);
  10550. #else
  10551. socklen_t len = sizeof(conn->client.rsa.sin);
  10552. struct sockaddr *psa = (struct sockaddr *)&(conn->client.rsa.sin);
  10553. #endif
  10554. conn->buf_size = MAX_REQUEST_SIZE;
  10555. conn->buf = (char *)(conn + 1);
  10556. conn->ctx = &fake_ctx;
  10557. conn->client.sock = sock;
  10558. conn->client.lsa = sa;
  10559. if (getsockname(sock, psa, &len) != 0) {
  10560. mg_cry(conn,
  10561. "%s: getsockname() failed: %s",
  10562. __func__,
  10563. strerror(ERRNO));
  10564. }
  10565. conn->client.is_ssl = use_ssl ? 1 : 0;
  10566. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  10567. #ifndef NO_SSL
  10568. if (use_ssl) {
  10569. fake_ctx.ssl_ctx = conn->client_ssl_ctx;
  10570. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  10571. * SSL_CTX_set_verify call is needed to switch off server
  10572. * certificate checking, which is off by default in OpenSSL and
  10573. * on in yaSSL. */
  10574. /* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  10575. * SSL_VERIFY_PEER, verify_ssl_server); */
  10576. if (client_options->client_cert) {
  10577. if (!ssl_use_pem_file(&fake_ctx, client_options->client_cert)) {
  10578. mg_snprintf(NULL,
  10579. NULL, /* No truncation check for ebuf */
  10580. ebuf,
  10581. ebuf_len,
  10582. "Can not use SSL client certificate");
  10583. SSL_CTX_free(conn->client_ssl_ctx);
  10584. closesocket(sock);
  10585. mg_free(conn);
  10586. conn = NULL;
  10587. }
  10588. }
  10589. if (client_options->server_cert) {
  10590. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  10591. client_options->server_cert,
  10592. NULL);
  10593. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  10594. } else {
  10595. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  10596. }
  10597. if (!sslize(conn, conn->client_ssl_ctx, SSL_connect)) {
  10598. mg_snprintf(NULL,
  10599. NULL, /* No truncation check for ebuf */
  10600. ebuf,
  10601. ebuf_len,
  10602. "SSL connection error");
  10603. SSL_CTX_free(conn->client_ssl_ctx);
  10604. closesocket(sock);
  10605. mg_free(conn);
  10606. conn = NULL;
  10607. }
  10608. }
  10609. #endif
  10610. }
  10611. return conn;
  10612. }
  10613. CIVETWEB_API struct mg_connection *
  10614. mg_connect_client_secure(const struct mg_client_options *client_options,
  10615. char *error_buffer,
  10616. size_t error_buffer_size)
  10617. {
  10618. return mg_connect_client_impl(client_options,
  10619. 1,
  10620. error_buffer,
  10621. error_buffer_size);
  10622. }
  10623. struct mg_connection *
  10624. mg_connect_client(const char *host,
  10625. int port,
  10626. int use_ssl,
  10627. char *error_buffer,
  10628. size_t error_buffer_size)
  10629. {
  10630. struct mg_client_options opts;
  10631. memset(&opts, 0, sizeof(opts));
  10632. opts.host = host;
  10633. opts.port = port;
  10634. return mg_connect_client_impl(&opts,
  10635. use_ssl,
  10636. error_buffer,
  10637. error_buffer_size);
  10638. }
  10639. static const struct {
  10640. const char *proto;
  10641. size_t proto_len;
  10642. unsigned default_port;
  10643. } abs_uri_protocols[] = {{"http://", 7, 80},
  10644. {"https://", 8, 443},
  10645. {"ws://", 5, 80},
  10646. {"wss://", 6, 443},
  10647. {NULL, 0, 0}};
  10648. /* Check if the uri is valid.
  10649. * return 0 for invalid uri,
  10650. * return 1 for *,
  10651. * return 2 for relative uri,
  10652. * return 3 for absolute uri without port,
  10653. * return 4 for absolute uri with port */
  10654. static int
  10655. get_uri_type(const char *uri)
  10656. {
  10657. int i;
  10658. char *hostend, *portbegin, *portend;
  10659. unsigned long port;
  10660. /* According to the HTTP standard
  10661. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  10662. * URI can be an asterisk (*) or should start with slash (relative uri),
  10663. * or it should start with the protocol (absolute uri). */
  10664. if (uri[0] == '*' && uri[1] == '\0') {
  10665. /* asterisk */
  10666. return 1;
  10667. }
  10668. /* Valid URIs according to RFC 3986
  10669. * (https://www.ietf.org/rfc/rfc3986.txt)
  10670. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  10671. * and unreserved characters A-Z a-z 0-9 and -._~
  10672. * and % encoded symbols.
  10673. */
  10674. for (i = 0; uri[i] != 0; i++) {
  10675. if (uri[i] < 33) {
  10676. /* control characters and spaces are invalid */
  10677. return 0;
  10678. }
  10679. if (uri[i] > 126) {
  10680. /* non-ascii characters must be % encoded */
  10681. return 0;
  10682. } else {
  10683. switch (uri[i]) {
  10684. case '"': /* 34 */
  10685. case '<': /* 60 */
  10686. case '>': /* 62 */
  10687. case '\\': /* 92 */
  10688. case '^': /* 94 */
  10689. case '`': /* 96 */
  10690. case '{': /* 123 */
  10691. case '|': /* 124 */
  10692. case '}': /* 125 */
  10693. return 0;
  10694. default:
  10695. /* character is ok */
  10696. break;
  10697. }
  10698. }
  10699. }
  10700. /* A relative uri starts with a / character */
  10701. if (uri[0] == '/') {
  10702. /* relative uri */
  10703. return 2;
  10704. }
  10705. /* It could be an absolute uri: */
  10706. /* This function only checks if the uri is valid, not if it is
  10707. * addressing the current server. So civetweb can also be used
  10708. * as a proxy server. */
  10709. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  10710. if (mg_strncasecmp(uri,
  10711. abs_uri_protocols[i].proto,
  10712. abs_uri_protocols[i].proto_len) == 0) {
  10713. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  10714. if (!hostend) {
  10715. return 0;
  10716. }
  10717. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  10718. if (!portbegin) {
  10719. return 3;
  10720. }
  10721. port = strtoul(portbegin + 1, &portend, 10);
  10722. if ((portend != hostend) || !port || !is_valid_port(port)) {
  10723. return 0;
  10724. }
  10725. return 4;
  10726. }
  10727. }
  10728. return 0;
  10729. }
  10730. /* Return NULL or the relative uri at the current server */
  10731. static const char *
  10732. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  10733. {
  10734. const char *server_domain;
  10735. size_t server_domain_len;
  10736. size_t request_domain_len = 0;
  10737. unsigned long port = 0;
  10738. int i;
  10739. const char *hostbegin = NULL;
  10740. const char *hostend = NULL;
  10741. const char *portbegin;
  10742. char *portend;
  10743. /* DNS is case insensitive, so use case insensitive string compare here
  10744. */
  10745. server_domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  10746. if (!server_domain) {
  10747. return 0;
  10748. }
  10749. server_domain_len = strlen(server_domain);
  10750. if (!server_domain_len) {
  10751. return 0;
  10752. }
  10753. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  10754. if (mg_strncasecmp(uri,
  10755. abs_uri_protocols[i].proto,
  10756. abs_uri_protocols[i].proto_len) == 0) {
  10757. hostbegin = uri + abs_uri_protocols[i].proto_len;
  10758. hostend = strchr(hostbegin, '/');
  10759. if (!hostend) {
  10760. return 0;
  10761. }
  10762. portbegin = strchr(hostbegin, ':');
  10763. if ((!portbegin) || (portbegin > hostend)) {
  10764. port = abs_uri_protocols[i].default_port;
  10765. request_domain_len = (size_t)(hostend - hostbegin);
  10766. } else {
  10767. port = strtoul(portbegin + 1, &portend, 10);
  10768. if ((portend != hostend) || !port || !is_valid_port(port)) {
  10769. return 0;
  10770. }
  10771. request_domain_len = (size_t)(portbegin - hostbegin);
  10772. }
  10773. /* protocol found, port set */
  10774. break;
  10775. }
  10776. }
  10777. if (!port) {
  10778. /* port remains 0 if the protocol is not found */
  10779. return 0;
  10780. }
  10781. #if defined(USE_IPV6)
  10782. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  10783. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  10784. /* Request is directed to a different port */
  10785. return 0;
  10786. }
  10787. } else
  10788. #endif
  10789. {
  10790. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  10791. /* Request is directed to a different port */
  10792. return 0;
  10793. }
  10794. }
  10795. if ((request_domain_len != server_domain_len)
  10796. || (0 != memcmp(server_domain, hostbegin, server_domain_len))) {
  10797. /* Request is directed to another server */
  10798. return 0;
  10799. }
  10800. return hostend;
  10801. }
  10802. static int
  10803. getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  10804. {
  10805. const char *cl;
  10806. if (ebuf_len > 0) {
  10807. ebuf[0] = '\0';
  10808. }
  10809. *err = 0;
  10810. reset_per_request_attributes(conn);
  10811. if (!conn) {
  10812. mg_snprintf(conn,
  10813. NULL, /* No truncation check for ebuf */
  10814. ebuf,
  10815. ebuf_len,
  10816. "%s",
  10817. "Internal error");
  10818. *err = 500;
  10819. return 0;
  10820. }
  10821. /* Set the time the request was received. This value should be used for
  10822. * timeouts. */
  10823. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  10824. conn->request_len =
  10825. read_request(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  10826. /* assert(conn->request_len < 0 || conn->data_len >= conn->request_len);
  10827. */
  10828. if (conn->request_len >= 0 && conn->data_len < conn->request_len) {
  10829. mg_snprintf(conn,
  10830. NULL, /* No truncation check for ebuf */
  10831. ebuf,
  10832. ebuf_len,
  10833. "%s",
  10834. "Invalid request size");
  10835. *err = 500;
  10836. return 0;
  10837. }
  10838. if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
  10839. mg_snprintf(conn,
  10840. NULL, /* No truncation check for ebuf */
  10841. ebuf,
  10842. ebuf_len,
  10843. "%s",
  10844. "Request Too Large");
  10845. *err = 413;
  10846. return 0;
  10847. } else if (conn->request_len <= 0) {
  10848. if (conn->data_len > 0) {
  10849. mg_snprintf(conn,
  10850. NULL, /* No truncation check for ebuf */
  10851. ebuf,
  10852. ebuf_len,
  10853. "%s",
  10854. "Client sent malformed request");
  10855. *err = 400;
  10856. } else {
  10857. /* Server did not send anything -> just close the connection */
  10858. conn->must_close = 1;
  10859. mg_snprintf(conn,
  10860. NULL, /* No truncation check for ebuf */
  10861. ebuf,
  10862. ebuf_len,
  10863. "%s",
  10864. "Client did not send a request");
  10865. *err = 0;
  10866. }
  10867. return 0;
  10868. } else if (parse_http_message(conn->buf,
  10869. conn->buf_size,
  10870. &conn->request_info) <= 0) {
  10871. mg_snprintf(conn,
  10872. NULL, /* No truncation check for ebuf */
  10873. ebuf,
  10874. ebuf_len,
  10875. "%s",
  10876. "Bad Request");
  10877. *err = 400;
  10878. return 0;
  10879. } else {
  10880. /* Message is a valid request or response */
  10881. if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) {
  10882. /* Request/response has content length set */
  10883. char *endptr = NULL;
  10884. conn->content_len = strtoll(cl, &endptr, 10);
  10885. if (endptr == cl) {
  10886. mg_snprintf(conn,
  10887. NULL, /* No truncation check for ebuf */
  10888. ebuf,
  10889. ebuf_len,
  10890. "%s",
  10891. "Bad Request");
  10892. *err = 411;
  10893. return 0;
  10894. }
  10895. /* Publish the content length back to the request info. */
  10896. conn->request_info.content_length = conn->content_len;
  10897. } else if ((cl = get_header(&conn->request_info, "Transfer-Encoding"))
  10898. != NULL
  10899. && !mg_strcasecmp(cl, "chunked")) {
  10900. conn->is_chunked = 1;
  10901. } else if (!mg_strcasecmp(conn->request_info.request_method, "POST")
  10902. || !mg_strcasecmp(conn->request_info.request_method,
  10903. "PUT")) {
  10904. /* POST or PUT request without content length set */
  10905. conn->content_len = -1;
  10906. } else if (!mg_strncasecmp(conn->request_info.request_method,
  10907. "HTTP/",
  10908. 5)) {
  10909. /* Response without content length set */
  10910. conn->content_len = -1;
  10911. } else {
  10912. /* Other request */
  10913. conn->content_len = 0;
  10914. }
  10915. }
  10916. return 1;
  10917. }
  10918. int
  10919. mg_get_response(struct mg_connection *conn,
  10920. char *ebuf,
  10921. size_t ebuf_len,
  10922. int timeout)
  10923. {
  10924. if (conn) {
  10925. /* Implementation of API function for HTTP clients */
  10926. int err, ret;
  10927. struct mg_context *octx = conn->ctx;
  10928. struct mg_context rctx = *(conn->ctx);
  10929. char txt[32]; /* will not overflow */
  10930. if (timeout >= 0) {
  10931. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  10932. rctx.config[REQUEST_TIMEOUT] = txt;
  10933. set_sock_timeout(conn->client.sock, timeout);
  10934. } else {
  10935. rctx.config[REQUEST_TIMEOUT] = NULL;
  10936. }
  10937. conn->ctx = &rctx;
  10938. ret = getreq(conn, ebuf, ebuf_len, &err);
  10939. conn->ctx = octx;
  10940. /* TODO: 1) uri is deprecated;
  10941. * 2) here, ri.uri is the http response code */
  10942. conn->request_info.uri = conn->request_info.request_uri;
  10943. /* TODO (mid): Define proper return values - maybe return length?
  10944. * For the first test use <0 for error and >0 for OK */
  10945. return (ret == 0) ? -1 : +1;
  10946. }
  10947. return -1;
  10948. }
  10949. struct mg_connection *
  10950. mg_download(const char *host,
  10951. int port,
  10952. int use_ssl,
  10953. char *ebuf,
  10954. size_t ebuf_len,
  10955. const char *fmt,
  10956. ...)
  10957. {
  10958. struct mg_connection *conn;
  10959. va_list ap;
  10960. int i;
  10961. int reqerr;
  10962. va_start(ap, fmt);
  10963. ebuf[0] = '\0';
  10964. /* open a connection */
  10965. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  10966. if (conn != NULL) {
  10967. i = mg_vprintf(conn, fmt, ap);
  10968. if (i <= 0) {
  10969. mg_snprintf(conn,
  10970. NULL, /* No truncation check for ebuf */
  10971. ebuf,
  10972. ebuf_len,
  10973. "%s",
  10974. "Error sending request");
  10975. } else {
  10976. getreq(conn, ebuf, ebuf_len, &reqerr);
  10977. /* TODO: 1) uri is deprecated;
  10978. * 2) here, ri.uri is the http response code */
  10979. conn->request_info.uri = conn->request_info.request_uri;
  10980. }
  10981. }
  10982. /* if an error occured, close the connection */
  10983. if (ebuf[0] != '\0' && conn != NULL) {
  10984. mg_close_connection(conn);
  10985. conn = NULL;
  10986. }
  10987. va_end(ap);
  10988. return conn;
  10989. }
  10990. struct websocket_client_thread_data {
  10991. struct mg_connection *conn;
  10992. mg_websocket_data_handler data_handler;
  10993. mg_websocket_close_handler close_handler;
  10994. void *callback_data;
  10995. };
  10996. #if defined(USE_WEBSOCKET)
  10997. #ifdef _WIN32
  10998. static unsigned __stdcall websocket_client_thread(void *data)
  10999. #else
  11000. static void *
  11001. websocket_client_thread(void *data)
  11002. #endif
  11003. {
  11004. struct websocket_client_thread_data *cdata =
  11005. (struct websocket_client_thread_data *)data;
  11006. mg_set_thread_name("ws-client");
  11007. if (cdata->conn->ctx) {
  11008. if (cdata->conn->ctx->callbacks.init_thread) {
  11009. /* 3 indicates a websocket client thread */
  11010. /* TODO: check if conn->ctx can be set */
  11011. cdata->conn->ctx->callbacks.init_thread(cdata->conn->ctx, 3);
  11012. }
  11013. }
  11014. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  11015. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  11016. if (cdata->close_handler != NULL) {
  11017. cdata->close_handler(cdata->conn, cdata->callback_data);
  11018. }
  11019. mg_free((void *)cdata);
  11020. #ifdef _WIN32
  11021. return 0;
  11022. #else
  11023. return NULL;
  11024. #endif
  11025. }
  11026. #endif
  11027. struct mg_connection *
  11028. mg_connect_websocket_client(const char *host,
  11029. int port,
  11030. int use_ssl,
  11031. char *error_buffer,
  11032. size_t error_buffer_size,
  11033. const char *path,
  11034. const char *origin,
  11035. mg_websocket_data_handler data_func,
  11036. mg_websocket_close_handler close_func,
  11037. void *user_data)
  11038. {
  11039. struct mg_connection *conn = NULL;
  11040. #if defined(USE_WEBSOCKET)
  11041. struct mg_context *newctx = NULL;
  11042. struct websocket_client_thread_data *thread_data;
  11043. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  11044. static const char *handshake_req;
  11045. if (origin != NULL) {
  11046. handshake_req = "GET %s HTTP/1.1\r\n"
  11047. "Host: %s\r\n"
  11048. "Upgrade: websocket\r\n"
  11049. "Connection: Upgrade\r\n"
  11050. "Sec-WebSocket-Key: %s\r\n"
  11051. "Sec-WebSocket-Version: 13\r\n"
  11052. "Origin: %s\r\n"
  11053. "\r\n";
  11054. } else {
  11055. handshake_req = "GET %s HTTP/1.1\r\n"
  11056. "Host: %s\r\n"
  11057. "Upgrade: websocket\r\n"
  11058. "Connection: Upgrade\r\n"
  11059. "Sec-WebSocket-Key: %s\r\n"
  11060. "Sec-WebSocket-Version: 13\r\n"
  11061. "\r\n";
  11062. }
  11063. /* Establish the client connection and request upgrade */
  11064. conn = mg_download(host,
  11065. port,
  11066. use_ssl,
  11067. error_buffer,
  11068. error_buffer_size,
  11069. handshake_req,
  11070. path,
  11071. host,
  11072. magic,
  11073. origin);
  11074. /* Connection object will be null if something goes wrong */
  11075. if (conn == NULL || (strcmp(conn->request_info.request_uri, "101") != 0)) {
  11076. if (!*error_buffer) {
  11077. /* if there is a connection, but it did not return 101,
  11078. * error_buffer is not yet set */
  11079. mg_snprintf(conn,
  11080. NULL, /* No truncation check for ebuf */
  11081. error_buffer,
  11082. error_buffer_size,
  11083. "Unexpected server reply");
  11084. }
  11085. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  11086. if (conn != NULL) {
  11087. mg_free(conn);
  11088. conn = NULL;
  11089. }
  11090. return conn;
  11091. }
  11092. /* For client connections, mg_context is fake. Since we need to set a
  11093. * callback function, we need to create a copy and modify it. */
  11094. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  11095. memcpy(newctx, conn->ctx, sizeof(struct mg_context));
  11096. newctx->user_data = user_data;
  11097. newctx->context_type = 2; /* client context type */
  11098. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  11099. newctx->workerthreadids =
  11100. (pthread_t *)mg_calloc(newctx->cfg_worker_threads, sizeof(pthread_t));
  11101. conn->ctx = newctx;
  11102. thread_data = (struct websocket_client_thread_data *)
  11103. mg_calloc(sizeof(struct websocket_client_thread_data), 1);
  11104. thread_data->conn = conn;
  11105. thread_data->data_handler = data_func;
  11106. thread_data->close_handler = close_func;
  11107. thread_data->callback_data = NULL;
  11108. /* Start a thread to read the websocket client connection
  11109. * This thread will automatically stop when mg_disconnect is
  11110. * called on the client connection */
  11111. if (mg_start_thread_with_id(websocket_client_thread,
  11112. (void *)thread_data,
  11113. newctx->workerthreadids) != 0) {
  11114. mg_free((void *)thread_data);
  11115. mg_free((void *)newctx->workerthreadids);
  11116. mg_free((void *)newctx);
  11117. mg_free((void *)conn);
  11118. conn = NULL;
  11119. DEBUG_TRACE("%s",
  11120. "Websocket client connect thread could not be started\r\n");
  11121. }
  11122. #else
  11123. /* Appease "unused parameter" warnings */
  11124. (void)host;
  11125. (void)port;
  11126. (void)use_ssl;
  11127. (void)error_buffer;
  11128. (void)error_buffer_size;
  11129. (void)path;
  11130. (void)origin;
  11131. (void)user_data;
  11132. (void)data_func;
  11133. (void)close_func;
  11134. #endif
  11135. return conn;
  11136. }
  11137. static void
  11138. process_new_connection(struct mg_connection *conn)
  11139. {
  11140. if (conn && conn->ctx) {
  11141. struct mg_request_info *ri = &conn->request_info;
  11142. int keep_alive_enabled, keep_alive, discard_len;
  11143. char ebuf[100];
  11144. const char *hostend;
  11145. int reqerr, uri_type;
  11146. keep_alive_enabled =
  11147. !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  11148. /* Important: on new connection, reset the receiving buffer. Credit
  11149. * goes to crule42. */
  11150. conn->data_len = 0;
  11151. do {
  11152. if (!getreq(conn, ebuf, sizeof(ebuf), &reqerr)) {
  11153. /* The request sent by the client could not be understood by
  11154. * the server, or it was incomplete or a timeout. Send an
  11155. * error message and close the connection. */
  11156. if (reqerr > 0) {
  11157. /*assert(ebuf[0] != '\0');*/
  11158. send_http_error(conn, reqerr, "%s", ebuf);
  11159. }
  11160. } else if (strcmp(ri->http_version, "1.0")
  11161. && strcmp(ri->http_version, "1.1")) {
  11162. mg_snprintf(conn,
  11163. NULL, /* No truncation check for ebuf */
  11164. ebuf,
  11165. sizeof(ebuf),
  11166. "Bad HTTP version: [%s]",
  11167. ri->http_version);
  11168. send_http_error(conn, 505, "%s", ebuf);
  11169. }
  11170. if (ebuf[0] == '\0') {
  11171. uri_type = get_uri_type(conn->request_info.request_uri);
  11172. switch (uri_type) {
  11173. case 1:
  11174. /* Asterisk */
  11175. conn->request_info.local_uri = NULL;
  11176. break;
  11177. case 2:
  11178. /* relative uri */
  11179. conn->request_info.local_uri =
  11180. conn->request_info.request_uri;
  11181. break;
  11182. case 3:
  11183. case 4:
  11184. /* absolute uri (with/without port) */
  11185. hostend = get_rel_url_at_current_server(
  11186. conn->request_info.request_uri, conn);
  11187. if (hostend) {
  11188. conn->request_info.local_uri = hostend;
  11189. } else {
  11190. conn->request_info.local_uri = NULL;
  11191. }
  11192. break;
  11193. default:
  11194. mg_snprintf(conn,
  11195. NULL, /* No truncation check for ebuf */
  11196. ebuf,
  11197. sizeof(ebuf),
  11198. "Invalid URI");
  11199. send_http_error(conn, 400, "%s", ebuf);
  11200. conn->request_info.local_uri = NULL;
  11201. break;
  11202. }
  11203. /* TODO: cleanup uri, local_uri and request_uri */
  11204. conn->request_info.uri = conn->request_info.local_uri;
  11205. }
  11206. if (ebuf[0] == '\0') {
  11207. if (conn->request_info.local_uri) {
  11208. /* handle request to local server */
  11209. handle_request(conn);
  11210. if (conn->ctx->callbacks.end_request != NULL) {
  11211. conn->ctx->callbacks.end_request(conn,
  11212. conn->status_code);
  11213. }
  11214. log_access(conn);
  11215. } else {
  11216. /* TODO: handle non-local request (PROXY) */
  11217. conn->must_close = 1;
  11218. }
  11219. } else {
  11220. conn->must_close = 1;
  11221. }
  11222. if (ri->remote_user != NULL) {
  11223. mg_free((void *)ri->remote_user);
  11224. /* Important! When having connections with and without auth
  11225. * would cause double free and then crash */
  11226. ri->remote_user = NULL;
  11227. }
  11228. /* NOTE(lsm): order is important here. should_keep_alive() call
  11229. * is
  11230. * using parsed request, which will be invalid after memmove's
  11231. * below.
  11232. * Therefore, memorize should_keep_alive() result now for later
  11233. * use
  11234. * in loop exit condition. */
  11235. keep_alive = conn->ctx->stop_flag == 0 && keep_alive_enabled
  11236. && conn->content_len >= 0 && should_keep_alive(conn);
  11237. /* Discard all buffered data for this request */
  11238. discard_len = ((conn->content_len >= 0) && (conn->request_len > 0)
  11239. && ((conn->request_len + conn->content_len)
  11240. < (int64_t)conn->data_len))
  11241. ? (int)(conn->request_len + conn->content_len)
  11242. : conn->data_len;
  11243. /*assert(discard_len >= 0);*/
  11244. if (discard_len < 0)
  11245. break;
  11246. conn->data_len -= discard_len;
  11247. if (conn->data_len > 0) {
  11248. memmove(conn->buf,
  11249. conn->buf + discard_len,
  11250. (size_t)conn->data_len);
  11251. }
  11252. /* assert(conn->data_len >= 0); */
  11253. /* assert(conn->data_len <= conn->buf_size); */
  11254. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  11255. break;
  11256. }
  11257. } while (keep_alive);
  11258. }
  11259. }
  11260. #if defined(ALTERNATIVE_QUEUE)
  11261. static void
  11262. produce_socket(struct mg_context *ctx, const struct socket *sp)
  11263. {
  11264. unsigned int i;
  11265. for (;;) {
  11266. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  11267. /* find a free worker slot and signal it */
  11268. if (ctx->client_socks[i].in_use == 0) {
  11269. ctx->client_socks[i] = *sp;
  11270. ctx->client_socks[i].in_use = 1;
  11271. event_signal(ctx->client_wait_events[i]);
  11272. return;
  11273. }
  11274. }
  11275. /* queue is full */
  11276. mg_sleep(1);
  11277. }
  11278. }
  11279. static int
  11280. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  11281. {
  11282. ctx->client_socks[thread_index].in_use = 0;
  11283. event_wait(ctx->client_wait_events[thread_index]);
  11284. *sp = ctx->client_socks[thread_index];
  11285. return !ctx->stop_flag;
  11286. }
  11287. #else /* ALTERNATIVE_QUEUE */
  11288. /* Worker threads take accepted socket from the queue */
  11289. static int
  11290. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  11291. {
  11292. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  11293. (void)thread_index;
  11294. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11295. DEBUG_TRACE("%s", "going idle");
  11296. /* If the queue is empty, wait. We're idle at this point. */
  11297. while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
  11298. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  11299. }
  11300. /* If we're stopping, sq_head may be equal to sq_tail. */
  11301. if (ctx->sq_head > ctx->sq_tail) {
  11302. /* Copy socket from the queue and increment tail */
  11303. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  11304. ctx->sq_tail++;
  11305. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  11306. /* Wrap pointers if needed */
  11307. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  11308. ctx->sq_tail -= QUEUE_SIZE(ctx);
  11309. ctx->sq_head -= QUEUE_SIZE(ctx);
  11310. }
  11311. }
  11312. (void)pthread_cond_signal(&ctx->sq_empty);
  11313. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11314. return !ctx->stop_flag;
  11315. #undef QUEUE_SIZE
  11316. }
  11317. /* Master thread adds accepted socket to a queue */
  11318. static void
  11319. produce_socket(struct mg_context *ctx, const struct socket *sp)
  11320. {
  11321. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  11322. if (!ctx) {
  11323. return;
  11324. }
  11325. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11326. /* If the queue is full, wait */
  11327. while (ctx->stop_flag == 0
  11328. && ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx)) {
  11329. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  11330. }
  11331. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  11332. /* Copy socket to the queue and increment head */
  11333. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  11334. ctx->sq_head++;
  11335. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  11336. }
  11337. (void)pthread_cond_signal(&ctx->sq_full);
  11338. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11339. #undef QUEUE_SIZE
  11340. }
  11341. #endif /* ALTERNATIVE_QUEUE */
  11342. struct worker_thread_args {
  11343. struct mg_context *ctx;
  11344. int index;
  11345. };
  11346. static void *
  11347. worker_thread_run(struct worker_thread_args *thread_args)
  11348. {
  11349. struct mg_context *ctx = thread_args->ctx;
  11350. struct mg_connection *conn;
  11351. struct mg_workerTLS tls;
  11352. #if defined(MG_LEGACY_INTERFACE)
  11353. uint32_t addr;
  11354. #endif
  11355. mg_set_thread_name("worker");
  11356. tls.is_master = 0;
  11357. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  11358. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11359. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  11360. #endif
  11361. if (ctx->callbacks.init_thread) {
  11362. /* call init_thread for a worker thread (type 1) */
  11363. ctx->callbacks.init_thread(ctx, 1);
  11364. }
  11365. conn =
  11366. (struct mg_connection *)mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE);
  11367. if (conn == NULL) {
  11368. mg_cry(fc(ctx), "%s", "Cannot create new connection struct, OOM");
  11369. } else {
  11370. pthread_setspecific(sTlsKey, &tls);
  11371. conn->buf_size = MAX_REQUEST_SIZE;
  11372. conn->buf = (char *)(conn + 1);
  11373. conn->ctx = ctx;
  11374. conn->thread_index = thread_args->index;
  11375. conn->request_info.user_data = ctx->user_data;
  11376. /* Allocate a mutex for this connection to allow communication both
  11377. * within the request handler and from elsewhere in the application
  11378. */
  11379. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  11380. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  11381. * signal sq_empty condvar to wake up the master waiting in
  11382. * produce_socket() */
  11383. while (consume_socket(ctx, &conn->client, conn->thread_index)) {
  11384. conn->conn_birth_time = time(NULL);
  11385. /* Fill in IP, port info early so even if SSL setup below fails,
  11386. * error handler would have the corresponding info.
  11387. * Thanks to Johannes Winkelmann for the patch.
  11388. */
  11389. #if defined(USE_IPV6)
  11390. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  11391. conn->request_info.remote_port =
  11392. ntohs(conn->client.rsa.sin6.sin6_port);
  11393. } else
  11394. #endif
  11395. {
  11396. conn->request_info.remote_port =
  11397. ntohs(conn->client.rsa.sin.sin_port);
  11398. }
  11399. sockaddr_to_string(conn->request_info.remote_addr,
  11400. sizeof(conn->request_info.remote_addr),
  11401. &conn->client.rsa);
  11402. #if defined(MG_LEGACY_INTERFACE)
  11403. /* This legacy interface only works for the IPv4 case */
  11404. addr = ntohl(conn->client.rsa.sin.sin_addr.s_addr);
  11405. memcpy(&conn->request_info.remote_ip, &addr, 4);
  11406. #endif
  11407. conn->request_info.is_ssl = conn->client.is_ssl;
  11408. if (conn->client.is_ssl) {
  11409. #ifndef NO_SSL
  11410. /* HTTPS connection */
  11411. if (sslize(conn, conn->ctx->ssl_ctx, SSL_accept)) {
  11412. /* Get SSL client certificate information (if set) */
  11413. ssl_get_client_cert_info(conn);
  11414. /* process HTTPS connection */
  11415. process_new_connection(conn);
  11416. /* Free client certificate info */
  11417. if (conn->request_info.client_cert) {
  11418. mg_free(
  11419. (void *)(conn->request_info.client_cert->subject));
  11420. mg_free(
  11421. (void *)(conn->request_info.client_cert->issuer));
  11422. mg_free(
  11423. (void *)(conn->request_info.client_cert->serial));
  11424. mg_free(
  11425. (void *)(conn->request_info.client_cert->finger));
  11426. conn->request_info.client_cert->subject = 0;
  11427. conn->request_info.client_cert->issuer = 0;
  11428. conn->request_info.client_cert->serial = 0;
  11429. conn->request_info.client_cert->finger = 0;
  11430. mg_free(conn->request_info.client_cert);
  11431. conn->request_info.client_cert = 0;
  11432. }
  11433. }
  11434. #endif
  11435. } else {
  11436. /* process HTTP connection */
  11437. process_new_connection(conn);
  11438. }
  11439. close_connection(conn);
  11440. }
  11441. }
  11442. pthread_setspecific(sTlsKey, NULL);
  11443. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11444. CloseHandle(tls.pthread_cond_helper_mutex);
  11445. #endif
  11446. pthread_mutex_destroy(&conn->mutex);
  11447. mg_free(conn);
  11448. DEBUG_TRACE("%s", "exiting");
  11449. return NULL;
  11450. }
  11451. /* Threads have different return types on Windows and Unix. */
  11452. #ifdef _WIN32
  11453. static unsigned __stdcall worker_thread(void *thread_func_param)
  11454. {
  11455. struct worker_thread_args *pwta =
  11456. (struct worker_thread_args *)thread_func_param;
  11457. worker_thread_run(pwta);
  11458. mg_free(thread_func_param);
  11459. return 0;
  11460. }
  11461. #else
  11462. static void *
  11463. worker_thread(void *thread_func_param)
  11464. {
  11465. struct worker_thread_args *pwta =
  11466. (struct worker_thread_args *)thread_func_param;
  11467. worker_thread_run(pwta);
  11468. mg_free(thread_func_param);
  11469. return NULL;
  11470. }
  11471. #endif /* _WIN32 */
  11472. static void
  11473. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  11474. {
  11475. struct socket so;
  11476. char src_addr[IP_ADDR_STR_LEN];
  11477. socklen_t len = sizeof(so.rsa);
  11478. int on = 1;
  11479. int timeout;
  11480. if (!listener) {
  11481. return;
  11482. }
  11483. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  11484. == INVALID_SOCKET) {
  11485. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  11486. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  11487. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  11488. closesocket(so.sock);
  11489. so.sock = INVALID_SOCKET;
  11490. } else {
  11491. /* Put so socket structure into the queue */
  11492. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  11493. set_close_on_exec(so.sock, fc(ctx));
  11494. so.is_ssl = listener->is_ssl;
  11495. so.ssl_redir = listener->ssl_redir;
  11496. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  11497. mg_cry(fc(ctx),
  11498. "%s: getsockname() failed: %s",
  11499. __func__,
  11500. strerror(ERRNO));
  11501. }
  11502. /* Set TCP keep-alive. This is needed because if HTTP-level
  11503. * keep-alive
  11504. * is enabled, and client resets the connection, server won't get
  11505. * TCP FIN or RST and will keep the connection open forever. With
  11506. * TCP keep-alive, next keep-alive handshake will figure out that
  11507. * the client is down and will close the server end.
  11508. * Thanks to Igor Klopov who suggested the patch. */
  11509. if (setsockopt(so.sock,
  11510. SOL_SOCKET,
  11511. SO_KEEPALIVE,
  11512. (SOCK_OPT_TYPE)&on,
  11513. sizeof(on)) != 0) {
  11514. mg_cry(fc(ctx),
  11515. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  11516. __func__,
  11517. strerror(ERRNO));
  11518. }
  11519. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  11520. * to effectively fill up the underlying IP packet payload and
  11521. * reduce the overhead of sending lots of small buffers. However
  11522. * this hurts the server's throughput (ie. operations per second)
  11523. * when HTTP 1.1 persistent connections are used and the responses
  11524. * are relatively small (eg. less than 1400 bytes).
  11525. */
  11526. if ((ctx != NULL) && (ctx->config[CONFIG_TCP_NODELAY] != NULL)
  11527. && (!strcmp(ctx->config[CONFIG_TCP_NODELAY], "1"))) {
  11528. if (set_tcp_nodelay(so.sock, 1) != 0) {
  11529. mg_cry(fc(ctx),
  11530. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  11531. __func__,
  11532. strerror(ERRNO));
  11533. }
  11534. }
  11535. if (ctx && ctx->config[REQUEST_TIMEOUT]) {
  11536. timeout = atoi(ctx->config[REQUEST_TIMEOUT]);
  11537. } else {
  11538. timeout = -1;
  11539. }
  11540. if (timeout > 0) {
  11541. set_sock_timeout(so.sock, timeout);
  11542. }
  11543. produce_socket(ctx, &so);
  11544. }
  11545. }
  11546. static void
  11547. master_thread_run(void *thread_func_param)
  11548. {
  11549. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  11550. struct mg_workerTLS tls;
  11551. struct pollfd *pfd;
  11552. unsigned int i;
  11553. unsigned int workerthreadcount;
  11554. if (!ctx) {
  11555. return;
  11556. }
  11557. mg_set_thread_name("master");
  11558. /* Increase priority of the master thread */
  11559. #if defined(_WIN32)
  11560. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  11561. #elif defined(USE_MASTER_THREAD_PRIORITY)
  11562. int min_prio = sched_get_priority_min(SCHED_RR);
  11563. int max_prio = sched_get_priority_max(SCHED_RR);
  11564. if ((min_prio >= 0) && (max_prio >= 0)
  11565. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  11566. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  11567. struct sched_param sched_param = {0};
  11568. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  11569. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  11570. }
  11571. #endif
  11572. /* Initialize thread local storage */
  11573. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11574. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  11575. #endif
  11576. tls.is_master = 1;
  11577. pthread_setspecific(sTlsKey, &tls);
  11578. if (ctx->callbacks.init_thread) {
  11579. /* Callback for the master thread (type 0) */
  11580. ctx->callbacks.init_thread(ctx, 0);
  11581. }
  11582. /* Server starts *now* */
  11583. ctx->start_time = time(NULL);
  11584. /* Start the server */
  11585. pfd = ctx->listening_socket_fds;
  11586. while (ctx->stop_flag == 0) {
  11587. for (i = 0; i < ctx->num_listening_sockets; i++) {
  11588. pfd[i].fd = ctx->listening_sockets[i].sock;
  11589. pfd[i].events = POLLIN;
  11590. }
  11591. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  11592. for (i = 0; i < ctx->num_listening_sockets; i++) {
  11593. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  11594. * successful poll, and POLLIN is defined as
  11595. * (POLLRDNORM | POLLRDBAND)
  11596. * Therefore, we're checking pfd[i].revents & POLLIN, not
  11597. * pfd[i].revents == POLLIN. */
  11598. if (ctx->stop_flag == 0 && (pfd[i].revents & POLLIN)) {
  11599. accept_new_connection(&ctx->listening_sockets[i], ctx);
  11600. }
  11601. }
  11602. }
  11603. }
  11604. /* Here stop_flag is 1 - Initiate shutdown. */
  11605. DEBUG_TRACE("%s", "stopping workers");
  11606. /* Stop signal received: somebody called mg_stop. Quit. */
  11607. close_all_listening_sockets(ctx);
  11608. /* Wakeup workers that are waiting for connections to handle. */
  11609. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11610. #if defined(ALTERNATIVE_QUEUE)
  11611. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  11612. event_signal(ctx->client_wait_events[i]);
  11613. /* Since we know all sockets, we can shutdown the connections. */
  11614. if (ctx->client_socks[i].in_use) {
  11615. shutdown(ctx->client_socks[i].sock, SHUTDOWN_BOTH);
  11616. }
  11617. }
  11618. #else
  11619. pthread_cond_broadcast(&ctx->sq_full);
  11620. #endif
  11621. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11622. /* Join all worker threads to avoid leaking threads. */
  11623. workerthreadcount = ctx->cfg_worker_threads;
  11624. for (i = 0; i < workerthreadcount; i++) {
  11625. if (ctx->workerthreadids[i] != 0) {
  11626. mg_join_thread(ctx->workerthreadids[i]);
  11627. }
  11628. }
  11629. #if !defined(NO_SSL)
  11630. if (ctx->ssl_ctx != NULL) {
  11631. uninitialize_ssl(ctx);
  11632. }
  11633. #endif
  11634. DEBUG_TRACE("%s", "exiting");
  11635. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11636. CloseHandle(tls.pthread_cond_helper_mutex);
  11637. #endif
  11638. pthread_setspecific(sTlsKey, NULL);
  11639. /* Signal mg_stop() that we're done.
  11640. * WARNING: This must be the very last thing this
  11641. * thread does, as ctx becomes invalid after this line. */
  11642. ctx->stop_flag = 2;
  11643. }
  11644. /* Threads have different return types on Windows and Unix. */
  11645. #ifdef _WIN32
  11646. static unsigned __stdcall master_thread(void *thread_func_param)
  11647. {
  11648. master_thread_run(thread_func_param);
  11649. return 0;
  11650. }
  11651. #else
  11652. static void *
  11653. master_thread(void *thread_func_param)
  11654. {
  11655. master_thread_run(thread_func_param);
  11656. return NULL;
  11657. }
  11658. #endif /* _WIN32 */
  11659. static void
  11660. free_context(struct mg_context *ctx)
  11661. {
  11662. int i;
  11663. struct mg_handler_info *tmp_rh;
  11664. if (ctx == NULL) {
  11665. return;
  11666. }
  11667. if (ctx->callbacks.exit_context) {
  11668. ctx->callbacks.exit_context(ctx);
  11669. }
  11670. /* All threads exited, no sync is needed. Destroy thread mutex and
  11671. * condvars
  11672. */
  11673. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  11674. #if defined(ALTERNATIVE_QUEUE)
  11675. mg_free(ctx->client_socks);
  11676. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  11677. event_destroy(ctx->client_wait_events[i]);
  11678. }
  11679. mg_free(ctx->client_wait_events);
  11680. #else
  11681. (void)pthread_cond_destroy(&ctx->sq_empty);
  11682. (void)pthread_cond_destroy(&ctx->sq_full);
  11683. #endif
  11684. /* Destroy other context global data structures mutex */
  11685. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  11686. #if defined(USE_TIMERS)
  11687. timers_exit(ctx);
  11688. #endif
  11689. /* Deallocate config parameters */
  11690. for (i = 0; i < NUM_OPTIONS; i++) {
  11691. if (ctx->config[i] != NULL) {
  11692. #if defined(_MSC_VER)
  11693. #pragma warning(suppress : 6001)
  11694. #endif
  11695. mg_free(ctx->config[i]);
  11696. }
  11697. }
  11698. /* Deallocate request handlers */
  11699. while (ctx->handlers) {
  11700. tmp_rh = ctx->handlers;
  11701. ctx->handlers = tmp_rh->next;
  11702. mg_free(tmp_rh->uri);
  11703. mg_free(tmp_rh);
  11704. }
  11705. #ifndef NO_SSL
  11706. /* Deallocate SSL context */
  11707. if (ctx->ssl_ctx != NULL) {
  11708. SSL_CTX_free(ctx->ssl_ctx);
  11709. }
  11710. #endif /* !NO_SSL */
  11711. /* Deallocate worker thread ID array */
  11712. if (ctx->workerthreadids != NULL) {
  11713. mg_free(ctx->workerthreadids);
  11714. }
  11715. /* Deallocate the tls variable */
  11716. if (mg_atomic_dec(&sTlsInit) == 0) {
  11717. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11718. DeleteCriticalSection(&global_log_file_lock);
  11719. #endif /* _WIN32 && !__SYMBIAN32__ */
  11720. #if !defined(_WIN32)
  11721. pthread_mutexattr_destroy(&pthread_mutex_attr);
  11722. #endif
  11723. pthread_key_delete(sTlsKey);
  11724. }
  11725. /* deallocate system name string */
  11726. mg_free(ctx->systemName);
  11727. /* Deallocate context itself */
  11728. mg_free(ctx);
  11729. }
  11730. void
  11731. mg_stop(struct mg_context *ctx)
  11732. {
  11733. pthread_t mt;
  11734. if (!ctx) {
  11735. return;
  11736. }
  11737. /* We don't use a lock here. Calling mg_stop with the same ctx from
  11738. * two threads is not allowed. */
  11739. mt = ctx->masterthreadid;
  11740. if (mt == 0) {
  11741. return;
  11742. }
  11743. ctx->masterthreadid = 0;
  11744. /* Set stop flag, so all threads know they have to exit. */
  11745. ctx->stop_flag = 1;
  11746. /* Wait until everything has stopped. */
  11747. while (ctx->stop_flag != 2) {
  11748. (void)mg_sleep(10);
  11749. }
  11750. mg_join_thread(mt);
  11751. free_context(ctx);
  11752. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11753. (void)WSACleanup();
  11754. #endif /* _WIN32 && !__SYMBIAN32__ */
  11755. }
  11756. static void
  11757. get_system_name(char **sysName)
  11758. {
  11759. #if defined(_WIN32)
  11760. #if !defined(__SYMBIAN32__)
  11761. #if defined(_WIN32_WCE)
  11762. *sysName = mg_strdup("WinCE");
  11763. #else
  11764. char name[128];
  11765. DWORD dwVersion = 0;
  11766. DWORD dwMajorVersion = 0;
  11767. DWORD dwMinorVersion = 0;
  11768. DWORD dwBuild = 0;
  11769. #ifdef _MSC_VER
  11770. #pragma warning(push)
  11771. // GetVersion was declared deprecated
  11772. #pragma warning(disable : 4996)
  11773. #endif
  11774. dwVersion = GetVersion();
  11775. #ifdef _MSC_VER
  11776. #pragma warning(pop)
  11777. #endif
  11778. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  11779. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  11780. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  11781. (void)dwBuild;
  11782. sprintf(name,
  11783. "Windows %u.%u",
  11784. (unsigned)dwMajorVersion,
  11785. (unsigned)dwMinorVersion);
  11786. *sysName = mg_strdup(name);
  11787. #endif
  11788. #else
  11789. *sysName = mg_strdup("Symbian");
  11790. #endif
  11791. #else
  11792. struct utsname name;
  11793. memset(&name, 0, sizeof(name));
  11794. uname(&name);
  11795. *sysName = mg_strdup(name.sysname);
  11796. #endif
  11797. }
  11798. struct mg_context *
  11799. mg_start(const struct mg_callbacks *callbacks,
  11800. void *user_data,
  11801. const char **options)
  11802. {
  11803. struct mg_context *ctx;
  11804. const char *name, *value, *default_value;
  11805. int idx, ok, workerthreadcount;
  11806. unsigned int i;
  11807. void (*exit_callback)(const struct mg_context *ctx) = 0;
  11808. struct mg_workerTLS tls;
  11809. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11810. WSADATA data;
  11811. WSAStartup(MAKEWORD(2, 2), &data);
  11812. #endif /* _WIN32 && !__SYMBIAN32__ */
  11813. /* Allocate context and initialize reasonable general case defaults. */
  11814. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  11815. return NULL;
  11816. }
  11817. /* Random number generator will initialize at the first call */
  11818. ctx->auth_nonce_mask =
  11819. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  11820. if (mg_atomic_inc(&sTlsInit) == 1) {
  11821. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11822. InitializeCriticalSection(&global_log_file_lock);
  11823. #endif /* _WIN32 && !__SYMBIAN32__ */
  11824. #if !defined(_WIN32)
  11825. pthread_mutexattr_init(&pthread_mutex_attr);
  11826. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  11827. #endif
  11828. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  11829. /* Fatal error - abort start. However, this situation should
  11830. * never
  11831. * occur in practice. */
  11832. mg_atomic_dec(&sTlsInit);
  11833. mg_cry(fc(ctx), "Cannot initialize thread local storage");
  11834. mg_free(ctx);
  11835. return NULL;
  11836. }
  11837. } else {
  11838. /* TODO (low): istead of sleeping, check if sTlsKey is already
  11839. * initialized. */
  11840. mg_sleep(1);
  11841. }
  11842. tls.is_master = -1;
  11843. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  11844. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11845. tls.pthread_cond_helper_mutex = NULL;
  11846. #endif
  11847. pthread_setspecific(sTlsKey, &tls);
  11848. #if defined(USE_LUA)
  11849. lua_init_optional_libraries();
  11850. #endif
  11851. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr);
  11852. #if !defined(ALTERNATIVE_QUEUE)
  11853. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  11854. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  11855. #endif
  11856. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr);
  11857. if (!ok) {
  11858. /* Fatal error - abort start. However, this situation should never
  11859. * occur in practice. */
  11860. mg_cry(fc(ctx), "Cannot initialize thread synchronization objects");
  11861. mg_free(ctx);
  11862. pthread_setspecific(sTlsKey, NULL);
  11863. return NULL;
  11864. }
  11865. if (callbacks) {
  11866. ctx->callbacks = *callbacks;
  11867. exit_callback = callbacks->exit_context;
  11868. ctx->callbacks.exit_context = 0;
  11869. }
  11870. ctx->user_data = user_data;
  11871. ctx->handlers = NULL;
  11872. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  11873. ctx->shared_lua_websockets = 0;
  11874. #endif
  11875. while (options && (name = *options++) != NULL) {
  11876. if ((idx = get_option_index(name)) == -1) {
  11877. mg_cry(fc(ctx), "Invalid option: %s", name);
  11878. free_context(ctx);
  11879. pthread_setspecific(sTlsKey, NULL);
  11880. return NULL;
  11881. } else if ((value = *options++) == NULL) {
  11882. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  11883. free_context(ctx);
  11884. pthread_setspecific(sTlsKey, NULL);
  11885. return NULL;
  11886. }
  11887. if (ctx->config[idx] != NULL) {
  11888. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  11889. mg_free(ctx->config[idx]);
  11890. }
  11891. ctx->config[idx] = mg_strdup(value);
  11892. DEBUG_TRACE("[%s] -> [%s]", name, value);
  11893. }
  11894. /* Set default value if needed */
  11895. for (i = 0; config_options[i].name != NULL; i++) {
  11896. default_value = config_options[i].default_value;
  11897. if (ctx->config[i] == NULL && default_value != NULL) {
  11898. ctx->config[i] = mg_strdup(default_value);
  11899. }
  11900. }
  11901. #if defined(NO_FILES)
  11902. if (ctx->config[DOCUMENT_ROOT] != NULL) {
  11903. mg_cry(fc(ctx), "%s", "Document root must not be set");
  11904. free_context(ctx);
  11905. pthread_setspecific(sTlsKey, NULL);
  11906. return NULL;
  11907. }
  11908. #endif
  11909. get_system_name(&ctx->systemName);
  11910. /* NOTE(lsm): order is important here. SSL certificates must
  11911. * be initialized before listening ports. UID must be set last. */
  11912. if (!set_gpass_option(ctx) ||
  11913. #if !defined(NO_SSL)
  11914. !set_ssl_option(ctx) ||
  11915. #endif
  11916. !set_ports_option(ctx) ||
  11917. #if !defined(_WIN32)
  11918. !set_uid_option(ctx) ||
  11919. #endif
  11920. !set_acl_option(ctx)) {
  11921. free_context(ctx);
  11922. pthread_setspecific(sTlsKey, NULL);
  11923. return NULL;
  11924. }
  11925. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  11926. /* Ignore SIGPIPE signal, so if browser cancels the request, it
  11927. * won't kill the whole process. */
  11928. (void)signal(SIGPIPE, SIG_IGN);
  11929. #endif /* !_WIN32 && !__SYMBIAN32__ */
  11930. workerthreadcount = atoi(ctx->config[NUM_THREADS]);
  11931. if (workerthreadcount > MAX_WORKER_THREADS) {
  11932. mg_cry(fc(ctx), "Too many worker threads");
  11933. free_context(ctx);
  11934. pthread_setspecific(sTlsKey, NULL);
  11935. return NULL;
  11936. }
  11937. if (workerthreadcount > 0) {
  11938. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  11939. ctx->workerthreadids =
  11940. (pthread_t *)mg_calloc(ctx->cfg_worker_threads, sizeof(pthread_t));
  11941. if (ctx->workerthreadids == NULL) {
  11942. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  11943. free_context(ctx);
  11944. pthread_setspecific(sTlsKey, NULL);
  11945. return NULL;
  11946. }
  11947. #if defined(ALTERNATIVE_QUEUE)
  11948. ctx->client_wait_events = mg_calloc(sizeof(ctx->client_wait_events[0]),
  11949. ctx->cfg_worker_threads);
  11950. if (ctx->client_wait_events == NULL) {
  11951. mg_cry(fc(ctx), "Not enough memory for worker event array");
  11952. mg_free(ctx->workerthreadids);
  11953. free_context(ctx);
  11954. pthread_setspecific(sTlsKey, NULL);
  11955. return NULL;
  11956. }
  11957. ctx->client_socks =
  11958. mg_calloc(sizeof(ctx->client_socks[0]), ctx->cfg_worker_threads);
  11959. if (ctx->client_wait_events == NULL) {
  11960. mg_cry(fc(ctx), "Not enough memory for worker socket array");
  11961. mg_free(ctx->client_socks);
  11962. mg_free(ctx->workerthreadids);
  11963. free_context(ctx);
  11964. pthread_setspecific(sTlsKey, NULL);
  11965. return NULL;
  11966. }
  11967. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  11968. ctx->client_wait_events[i] = event_create();
  11969. if (ctx->client_wait_events[i] == 0) {
  11970. mg_cry(fc(ctx), "Error creating worker event %i", i);
  11971. /* TODO: clean all and exit */
  11972. }
  11973. }
  11974. #endif
  11975. }
  11976. #if defined(USE_TIMERS)
  11977. if (timers_init(ctx) != 0) {
  11978. mg_cry(fc(ctx), "Error creating timers");
  11979. free_context(ctx);
  11980. pthread_setspecific(sTlsKey, NULL);
  11981. return NULL;
  11982. }
  11983. #endif
  11984. /* Context has been created - init user libraries */
  11985. if (ctx->callbacks.init_context) {
  11986. ctx->callbacks.init_context(ctx);
  11987. }
  11988. ctx->callbacks.exit_context = exit_callback;
  11989. ctx->context_type = 1; /* server context */
  11990. /* Start master (listening) thread */
  11991. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  11992. /* Start worker threads */
  11993. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  11994. struct worker_thread_args *wta =
  11995. mg_malloc(sizeof(struct worker_thread_args));
  11996. if (wta) {
  11997. wta->ctx = ctx;
  11998. wta->index = (int)i;
  11999. }
  12000. if ((wta == NULL)
  12001. || (mg_start_thread_with_id(worker_thread,
  12002. wta,
  12003. &ctx->workerthreadids[i]) != 0)) {
  12004. /* thread was not created */
  12005. if (wta != NULL) {
  12006. mg_free(wta);
  12007. }
  12008. if (i > 0) {
  12009. mg_cry(fc(ctx),
  12010. "Cannot start worker thread %i: error %ld",
  12011. i + 1,
  12012. (long)ERRNO);
  12013. } else {
  12014. mg_cry(fc(ctx),
  12015. "Cannot create threads: error %ld",
  12016. (long)ERRNO);
  12017. free_context(ctx);
  12018. pthread_setspecific(sTlsKey, NULL);
  12019. return NULL;
  12020. }
  12021. break;
  12022. }
  12023. }
  12024. pthread_setspecific(sTlsKey, NULL);
  12025. return ctx;
  12026. }
  12027. /* Feature check API function */
  12028. unsigned
  12029. mg_check_feature(unsigned feature)
  12030. {
  12031. static const unsigned feature_set = 0
  12032. /* Set bits for available features according to API documentation.
  12033. * This bit mask is created at compile time, according to the active
  12034. * preprocessor defines. It is a single const value at runtime. */
  12035. #if !defined(NO_FILES)
  12036. | 0x0001u
  12037. #endif
  12038. #if !defined(NO_SSL)
  12039. | 0x0002u
  12040. #endif
  12041. #if !defined(NO_CGI)
  12042. | 0x0004u
  12043. #endif
  12044. #if defined(USE_IPV6)
  12045. | 0x0008u
  12046. #endif
  12047. #if defined(USE_WEBSOCKET)
  12048. | 0x0010u
  12049. #endif
  12050. #if defined(USE_LUA)
  12051. | 0x0020u
  12052. #endif
  12053. #if defined(USE_DUKTAPE)
  12054. | 0x0040u
  12055. #endif
  12056. #if !defined(NO_CACHING)
  12057. | 0x0080u
  12058. #endif
  12059. /* Set some extra bits not defined in the API documentation.
  12060. * These bits may change without further notice. */
  12061. #if defined(MG_LEGACY_INTERFACE)
  12062. | 0x8000u
  12063. #endif
  12064. #if defined(MEMORY_DEBUGGING)
  12065. | 0x0100u
  12066. #endif
  12067. #if defined(USE_TIMERS)
  12068. | 0x0200u
  12069. #endif
  12070. #if !defined(NO_NONCE_CHECK)
  12071. | 0x0400u
  12072. #endif
  12073. #if !defined(NO_POPEN)
  12074. | 0x0800u
  12075. #endif
  12076. ;
  12077. return (feature & feature_set);
  12078. }