civetweb.c 402 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191
  1. /* Copyright (c) 2013-2017 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)
  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. #ifndef CIVETWEB_HEADER_INCLUDED
  101. /* Include the header file here, so the CivetWeb interface is defined for the
  102. * entire implementation, including the following forward definitions. */
  103. #include "civetweb.h"
  104. #endif
  105. #ifndef IGNORE_UNUSED_RESULT
  106. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  107. #endif
  108. #ifndef _WIN32_WCE /* Some ANSI #includes are not available on Windows CE */
  109. #include <sys/types.h>
  110. #include <sys/stat.h>
  111. #include <errno.h>
  112. #include <signal.h>
  113. #include <fcntl.h>
  114. #endif /* !_WIN32_WCE */
  115. #ifdef __clang__
  116. /* When using -Weverything, clang does not accept it's own headers
  117. * in a release build configuration. Disable what is too much in
  118. * -Weverything. */
  119. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  120. #endif
  121. #ifdef __MACH__ /* Apple OSX section */
  122. #ifdef __clang__
  123. /* Avoid warnings for Xopen 7.00 and higher */
  124. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  125. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  126. #endif
  127. #define CLOCK_MONOTONIC (1)
  128. #define CLOCK_REALTIME (2)
  129. #include <sys/errno.h>
  130. #include <sys/time.h>
  131. #include <mach/clock.h>
  132. #include <mach/mach.h>
  133. #include <mach/mach_time.h>
  134. #include <assert.h>
  135. /* clock_gettime is not implemented on OSX prior to 10.12 */
  136. static int
  137. _civet_clock_gettime(int clk_id, struct timespec *t)
  138. {
  139. memset(t, 0, sizeof(*t));
  140. if (clk_id == CLOCK_REALTIME) {
  141. struct timeval now;
  142. int rv = gettimeofday(&now, NULL);
  143. if (rv) {
  144. return rv;
  145. }
  146. t->tv_sec = now.tv_sec;
  147. t->tv_nsec = now.tv_usec * 1000;
  148. return 0;
  149. } else if (clk_id == CLOCK_MONOTONIC) {
  150. static uint64_t clock_start_time = 0;
  151. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  152. uint64_t now = mach_absolute_time();
  153. if (clock_start_time == 0) {
  154. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  155. #if defined(DEBUG)
  156. assert(mach_status == KERN_SUCCESS);
  157. #else
  158. /* appease "unused variable" warning for release builds */
  159. (void)mach_status;
  160. #endif
  161. clock_start_time = now;
  162. }
  163. now = (uint64_t)((double)(now - clock_start_time)
  164. * (double)timebase_ifo.numer
  165. / (double)timebase_ifo.denom);
  166. t->tv_sec = now / 1000000000;
  167. t->tv_nsec = now % 1000000000;
  168. return 0;
  169. }
  170. return -1; /* EINVAL - Clock ID is unknown */
  171. }
  172. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  173. #ifdef __CLOCK_AVAILABILITY
  174. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  175. * declared but it may be NULL at runtime. So we need to check before using
  176. * it. */
  177. static int
  178. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  179. {
  180. if (clock_gettime) {
  181. return clock_gettime(clk_id, t);
  182. }
  183. return _civet_clock_gettime(clk_id, t);
  184. }
  185. #define clock_gettime _civet_safe_clock_gettime
  186. #else
  187. #define clock_gettime _civet_clock_gettime
  188. #endif
  189. #endif
  190. #include <time.h>
  191. #include <stdlib.h>
  192. #include <stdarg.h>
  193. #include <assert.h>
  194. #include <string.h>
  195. #include <ctype.h>
  196. #include <limits.h>
  197. #include <stddef.h>
  198. #include <stdio.h>
  199. #include <stdint.h>
  200. #ifndef INT64_MAX
  201. #define INT64_MAX (9223372036854775807)
  202. #endif
  203. #ifndef MAX_WORKER_THREADS
  204. #define MAX_WORKER_THREADS (1024 * 64)
  205. #endif
  206. #ifndef SOCKET_TIMEOUT_QUANTUM /* in ms */
  207. #define SOCKET_TIMEOUT_QUANTUM (2000)
  208. #endif
  209. #define SHUTDOWN_RD (0)
  210. #define SHUTDOWN_WR (1)
  211. #define SHUTDOWN_BOTH (2)
  212. mg_static_assert(MAX_WORKER_THREADS >= 1,
  213. "worker threads must be a positive number");
  214. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  215. "size_t data type size check");
  216. #if defined(_WIN32) \
  217. && !defined(__SYMBIAN32__) /* WINDOWS / UNIX include block */
  218. #include <windows.h>
  219. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  220. #include <ws2tcpip.h>
  221. typedef const char *SOCK_OPT_TYPE;
  222. #if !defined(PATH_MAX)
  223. #define PATH_MAX (MAX_PATH)
  224. #endif
  225. #if !defined(PATH_MAX)
  226. #define PATH_MAX (4096)
  227. #endif
  228. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  229. #ifndef _IN_PORT_T
  230. #ifndef in_port_t
  231. #define in_port_t u_short
  232. #endif
  233. #endif
  234. #ifndef _WIN32_WCE
  235. #include <process.h>
  236. #include <direct.h>
  237. #include <io.h>
  238. #else /* _WIN32_WCE */
  239. #define NO_CGI /* WinCE has no pipes */
  240. #define NO_POPEN /* WinCE has no popen */
  241. typedef long off_t;
  242. #define errno ((int)(GetLastError()))
  243. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  244. #endif /* _WIN32_WCE */
  245. #define MAKEUQUAD(lo, hi) \
  246. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  247. #define RATE_DIFF (10000000) /* 100 nsecs */
  248. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  249. #define SYS2UNIX_TIME(lo, hi) \
  250. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  251. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  252. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  253. * Also use _strtoui64 on modern M$ compilers */
  254. #if defined(_MSC_VER)
  255. #if (_MSC_VER < 1300)
  256. #define STRX(x) #x
  257. #define STR(x) STRX(x)
  258. #define __func__ __FILE__ ":" STR(__LINE__)
  259. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  260. #define strtoll(x, y, z) (_atoi64(x))
  261. #else
  262. #define __func__ __FUNCTION__
  263. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  264. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  265. #endif
  266. #endif /* _MSC_VER */
  267. #define ERRNO ((int)(GetLastError()))
  268. #define NO_SOCKLEN_T
  269. #if defined(_WIN64) || defined(__MINGW64__)
  270. #define SSL_LIB "ssleay64.dll"
  271. #define CRYPTO_LIB "libeay64.dll"
  272. #else
  273. #define SSL_LIB "ssleay32.dll"
  274. #define CRYPTO_LIB "libeay32.dll"
  275. #endif
  276. #define O_NONBLOCK (0)
  277. #ifndef W_OK
  278. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  279. #endif
  280. #if !defined(EWOULDBLOCK)
  281. #define EWOULDBLOCK WSAEWOULDBLOCK
  282. #endif /* !EWOULDBLOCK */
  283. #define _POSIX_
  284. #define INT64_FMT "I64d"
  285. #define UINT64_FMT "I64u"
  286. #define WINCDECL __cdecl
  287. #define vsnprintf_impl _vsnprintf
  288. #define access _access
  289. #define mg_sleep(x) (Sleep(x))
  290. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  291. #ifndef popen
  292. #define popen(x, y) (_popen(x, y))
  293. #endif
  294. #ifndef pclose
  295. #define pclose(x) (_pclose(x))
  296. #endif
  297. #define close(x) (_close(x))
  298. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  299. #define RTLD_LAZY (0)
  300. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  301. #define fdopen(x, y) (_fdopen((x), (y)))
  302. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  303. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  304. #define flockfile(x) (EnterCriticalSection(&global_log_file_lock))
  305. #define funlockfile(x) (LeaveCriticalSection(&global_log_file_lock))
  306. #define sleep(x) (Sleep((x)*1000))
  307. #define rmdir(x) (_rmdir(x))
  308. #define timegm(x) (_mkgmtime(x))
  309. #if !defined(fileno)
  310. #define fileno(x) (_fileno(x))
  311. #endif /* !fileno MINGW #defines fileno */
  312. typedef HANDLE pthread_mutex_t;
  313. typedef DWORD pthread_key_t;
  314. typedef HANDLE pthread_t;
  315. typedef struct {
  316. CRITICAL_SECTION threadIdSec;
  317. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  318. } pthread_cond_t;
  319. #ifndef __clockid_t_defined
  320. typedef DWORD clockid_t;
  321. #endif
  322. #ifndef CLOCK_MONOTONIC
  323. #define CLOCK_MONOTONIC (1)
  324. #endif
  325. #ifndef CLOCK_REALTIME
  326. #define CLOCK_REALTIME (2)
  327. #endif
  328. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  329. #define _TIMESPEC_DEFINED
  330. #endif
  331. #ifndef _TIMESPEC_DEFINED
  332. struct timespec {
  333. time_t tv_sec; /* seconds */
  334. long tv_nsec; /* nanoseconds */
  335. };
  336. #endif
  337. #if !defined(WIN_PTHREADS_TIME_H)
  338. #define MUST_IMPLEMENT_CLOCK_GETTIME
  339. #endif
  340. #ifdef MUST_IMPLEMENT_CLOCK_GETTIME
  341. #define clock_gettime mg_clock_gettime
  342. static int
  343. clock_gettime(clockid_t clk_id, struct timespec *tp)
  344. {
  345. FILETIME ft;
  346. ULARGE_INTEGER li;
  347. BOOL ok = FALSE;
  348. double d;
  349. static double perfcnt_per_sec = 0.0;
  350. if (tp) {
  351. memset(tp, 0, sizeof(*tp));
  352. if (clk_id == CLOCK_REALTIME) {
  353. GetSystemTimeAsFileTime(&ft);
  354. li.LowPart = ft.dwLowDateTime;
  355. li.HighPart = ft.dwHighDateTime;
  356. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  357. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  358. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  359. ok = TRUE;
  360. } else if (clk_id == CLOCK_MONOTONIC) {
  361. if (perfcnt_per_sec == 0.0) {
  362. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  363. perfcnt_per_sec = 1.0 / li.QuadPart;
  364. }
  365. if (perfcnt_per_sec != 0.0) {
  366. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  367. d = li.QuadPart * perfcnt_per_sec;
  368. tp->tv_sec = (time_t)d;
  369. d -= tp->tv_sec;
  370. tp->tv_nsec = (long)(d * 1.0E9);
  371. ok = TRUE;
  372. }
  373. }
  374. }
  375. return ok ? 0 : -1;
  376. }
  377. #endif
  378. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  379. static int pthread_mutex_lock(pthread_mutex_t *);
  380. static int pthread_mutex_unlock(pthread_mutex_t *);
  381. static void path_to_unicode(const struct mg_connection *conn,
  382. const char *path,
  383. wchar_t *wbuf,
  384. size_t wbuf_len);
  385. /* All file operations need to be rewritten to solve #246. */
  386. #include "file_ops.inl"
  387. struct mg_file;
  388. static const char *
  389. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p);
  390. /* POSIX dirent interface */
  391. struct dirent {
  392. char d_name[PATH_MAX];
  393. };
  394. typedef struct DIR {
  395. HANDLE handle;
  396. WIN32_FIND_DATAW info;
  397. struct dirent result;
  398. } DIR;
  399. #if defined(_WIN32) && !defined(POLLIN)
  400. #ifndef HAVE_POLL
  401. struct pollfd {
  402. SOCKET fd;
  403. short events;
  404. short revents;
  405. };
  406. #define POLLIN (0x0300)
  407. #endif
  408. #endif
  409. /* Mark required libraries */
  410. #if defined(_MSC_VER)
  411. #pragma comment(lib, "Ws2_32.lib")
  412. #endif
  413. #else /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  414. WINDOWS / UNIX include block */
  415. #include <sys/wait.h>
  416. #include <sys/socket.h>
  417. #include <sys/poll.h>
  418. #include <netinet/in.h>
  419. #include <arpa/inet.h>
  420. #include <sys/time.h>
  421. #include <sys/utsname.h>
  422. #include <stdint.h>
  423. #include <inttypes.h>
  424. #include <netdb.h>
  425. #include <netinet/tcp.h>
  426. typedef const void *SOCK_OPT_TYPE;
  427. #if defined(ANDROID)
  428. typedef unsigned short int in_port_t;
  429. #endif
  430. #include <pwd.h>
  431. #include <unistd.h>
  432. #include <grp.h>
  433. #include <dirent.h>
  434. #define vsnprintf_impl vsnprintf
  435. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  436. #include <dlfcn.h>
  437. #endif
  438. #include <pthread.h>
  439. #if defined(__MACH__)
  440. #define SSL_LIB "libssl.dylib"
  441. #define CRYPTO_LIB "libcrypto.dylib"
  442. #else
  443. #if !defined(SSL_LIB)
  444. #define SSL_LIB "libssl.so"
  445. #endif
  446. #if !defined(CRYPTO_LIB)
  447. #define CRYPTO_LIB "libcrypto.so"
  448. #endif
  449. #endif
  450. #ifndef O_BINARY
  451. #define O_BINARY (0)
  452. #endif /* O_BINARY */
  453. #define closesocket(a) (close(a))
  454. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  455. #define mg_remove(conn, x) (remove(x))
  456. #define mg_sleep(x) (usleep((x)*1000))
  457. #define mg_opendir(conn, x) (opendir(x))
  458. #define mg_closedir(x) (closedir(x))
  459. #define mg_readdir(x) (readdir(x))
  460. #define ERRNO (errno)
  461. #define INVALID_SOCKET (-1)
  462. #define INT64_FMT PRId64
  463. #define UINT64_FMT PRIu64
  464. typedef int SOCKET;
  465. #define WINCDECL
  466. #if defined(__hpux)
  467. /* HPUX 11 does not have monotonic, fall back to realtime */
  468. #ifndef CLOCK_MONOTONIC
  469. #define CLOCK_MONOTONIC CLOCK_REALTIME
  470. #endif
  471. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  472. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  473. * the prototypes use int* rather than socklen_t* which matches the
  474. * actual library expectation. When called with the wrong size arg
  475. * accept() returns a zero client inet addr and check_acl() always
  476. * fails. Since socklen_t is widely used below, just force replace
  477. * their typedef with int. - DTL
  478. */
  479. #define socklen_t int
  480. #endif /* hpux */
  481. #endif /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  482. WINDOWS / UNIX include block */
  483. /* va_copy should always be a macro, C99 and C++11 - DTL */
  484. #ifndef va_copy
  485. #define va_copy(x, y) ((x) = (y))
  486. #endif
  487. #ifdef _WIN32
  488. /* Create substitutes for POSIX functions in Win32. */
  489. #if defined(__MINGW32__)
  490. /* Show no warning in case system functions are not used. */
  491. #pragma GCC diagnostic push
  492. #pragma GCC diagnostic ignored "-Wunused-function"
  493. #endif
  494. static CRITICAL_SECTION global_log_file_lock;
  495. static DWORD
  496. pthread_self(void)
  497. {
  498. return GetCurrentThreadId();
  499. }
  500. static int
  501. pthread_key_create(
  502. pthread_key_t *key,
  503. void (*_ignored)(void *) /* destructor not supported for Windows */
  504. )
  505. {
  506. (void)_ignored;
  507. if ((key != 0)) {
  508. *key = TlsAlloc();
  509. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  510. }
  511. return -2;
  512. }
  513. static int
  514. pthread_key_delete(pthread_key_t key)
  515. {
  516. return TlsFree(key) ? 0 : 1;
  517. }
  518. static int
  519. pthread_setspecific(pthread_key_t key, void *value)
  520. {
  521. return TlsSetValue(key, value) ? 0 : 1;
  522. }
  523. static void *
  524. pthread_getspecific(pthread_key_t key)
  525. {
  526. return TlsGetValue(key);
  527. }
  528. #if defined(__MINGW32__)
  529. /* Enable unused function warning again */
  530. #pragma GCC diagnostic pop
  531. #endif
  532. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  533. #else
  534. static pthread_mutexattr_t pthread_mutex_attr;
  535. #endif /* _WIN32 */
  536. #define PASSWORDS_FILE_NAME ".htpasswd"
  537. #define CGI_ENVIRONMENT_SIZE (4096)
  538. #define MAX_CGI_ENVIR_VARS (256)
  539. #define MG_BUF_LEN (8192)
  540. #ifndef MAX_REQUEST_SIZE
  541. #define MAX_REQUEST_SIZE (16384)
  542. #endif
  543. mg_static_assert(MAX_REQUEST_SIZE >= 256,
  544. "request size length must be a positive number");
  545. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  546. #if defined(_WIN32_WCE)
  547. /* Create substitutes for POSIX functions in Win32. */
  548. #if defined(__MINGW32__)
  549. /* Show no warning in case system functions are not used. */
  550. #pragma GCC diagnostic push
  551. #pragma GCC diagnostic ignored "-Wunused-function"
  552. #endif
  553. static time_t
  554. time(time_t *ptime)
  555. {
  556. time_t t;
  557. SYSTEMTIME st;
  558. FILETIME ft;
  559. GetSystemTime(&st);
  560. SystemTimeToFileTime(&st, &ft);
  561. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  562. if (ptime != NULL) {
  563. *ptime = t;
  564. }
  565. return t;
  566. }
  567. static struct tm *
  568. localtime_s(const time_t *ptime, struct tm *ptm)
  569. {
  570. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  571. FILETIME ft, lft;
  572. SYSTEMTIME st;
  573. TIME_ZONE_INFORMATION tzinfo;
  574. if (ptm == NULL) {
  575. return NULL;
  576. }
  577. *(int64_t *)&ft = t;
  578. FileTimeToLocalFileTime(&ft, &lft);
  579. FileTimeToSystemTime(&lft, &st);
  580. ptm->tm_year = st.wYear - 1900;
  581. ptm->tm_mon = st.wMonth - 1;
  582. ptm->tm_wday = st.wDayOfWeek;
  583. ptm->tm_mday = st.wDay;
  584. ptm->tm_hour = st.wHour;
  585. ptm->tm_min = st.wMinute;
  586. ptm->tm_sec = st.wSecond;
  587. ptm->tm_yday = 0; /* hope nobody uses this */
  588. ptm->tm_isdst =
  589. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  590. return ptm;
  591. }
  592. static struct tm *
  593. gmtime_s(const time_t *ptime, struct tm *ptm)
  594. {
  595. /* FIXME(lsm): fix this. */
  596. return localtime_s(ptime, ptm);
  597. }
  598. static int mg_atomic_inc(volatile int *addr);
  599. static struct tm tm_array[MAX_WORKER_THREADS];
  600. static int tm_index = 0;
  601. static struct tm *
  602. localtime(const time_t *ptime)
  603. {
  604. int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0]));
  605. return localtime_s(ptime, tm_array + i);
  606. }
  607. static struct tm *
  608. gmtime(const time_t *ptime)
  609. {
  610. int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  611. return gmtime_s(ptime, tm_array + i);
  612. }
  613. static size_t
  614. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  615. {
  616. /* TODO: (void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  617. * for WinCE"); */
  618. return 0;
  619. }
  620. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  621. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  622. #define remove(f) mg_remove(NULL, f)
  623. static int
  624. rename(const char *a, const char *b)
  625. {
  626. wchar_t wa[PATH_MAX];
  627. wchar_t wb[PATH_MAX];
  628. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  629. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  630. return MoveFileW(wa, wb) ? 0 : -1;
  631. }
  632. struct stat {
  633. int64_t st_size;
  634. time_t st_mtime;
  635. };
  636. static int
  637. stat(const char *name, struct stat *st)
  638. {
  639. wchar_t wbuf[PATH_MAX];
  640. WIN32_FILE_ATTRIBUTE_DATA attr;
  641. time_t creation_time, write_time;
  642. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  643. memset(&attr, 0, sizeof(attr));
  644. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  645. st->st_size =
  646. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  647. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  648. attr.ftLastWriteTime.dwHighDateTime);
  649. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  650. attr.ftCreationTime.dwHighDateTime);
  651. if (creation_time > write_time) {
  652. st->st_mtime = creation_time;
  653. } else {
  654. st->st_mtime = write_time;
  655. }
  656. return 0;
  657. }
  658. #define access(x, a) 1 /* not required anyway */
  659. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  660. /* Values from errno.h in Windows SDK (Visual Studio). */
  661. #define EEXIST 17
  662. #define EACCES 13
  663. #define ENOENT 2
  664. #if defined(__MINGW32__)
  665. /* Enable unused function warning again */
  666. #pragma GCC diagnostic pop
  667. #endif
  668. #endif /* defined(_WIN32_WCE) */
  669. static int
  670. mg_atomic_inc(volatile int *addr)
  671. {
  672. int ret;
  673. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  674. /* Depending on the SDK, this function uses either
  675. * (volatile unsigned int *) or (volatile LONG *),
  676. * so whatever you use, the other SDK is likely to raise a warning. */
  677. ret = InterlockedIncrement((volatile long *)addr);
  678. #elif defined(__GNUC__) \
  679. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  680. ret = __sync_add_and_fetch(addr, 1);
  681. #else
  682. ret = (++(*addr));
  683. #endif
  684. return ret;
  685. }
  686. static int
  687. mg_atomic_dec(volatile int *addr)
  688. {
  689. int ret;
  690. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  691. /* Depending on the SDK, this function uses either
  692. * (volatile unsigned int *) or (volatile LONG *),
  693. * so whatever you use, the other SDK is likely to raise a warning. */
  694. ret = InterlockedDecrement((volatile long *)addr);
  695. #elif defined(__GNUC__) \
  696. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  697. ret = __sync_sub_and_fetch(addr, 1);
  698. #else
  699. ret = (--(*addr));
  700. #endif
  701. return ret;
  702. }
  703. #if defined(MEMORY_DEBUGGING)
  704. static unsigned long mg_memory_debug_blockCount = 0;
  705. static unsigned long mg_memory_debug_totalMemUsed = 0;
  706. static void *
  707. mg_malloc_ex(size_t size, const char *file, unsigned line)
  708. {
  709. void *data = malloc(size + sizeof(size_t));
  710. void *memory = 0;
  711. char mallocStr[256];
  712. if (data) {
  713. *(size_t *)data = size;
  714. mg_memory_debug_totalMemUsed += size;
  715. mg_memory_debug_blockCount++;
  716. memory = (void *)(((char *)data) + sizeof(size_t));
  717. }
  718. sprintf(mallocStr,
  719. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  720. memory,
  721. (unsigned long)size,
  722. mg_memory_debug_totalMemUsed,
  723. mg_memory_debug_blockCount,
  724. file,
  725. line);
  726. #if defined(_WIN32)
  727. OutputDebugStringA(mallocStr);
  728. #else
  729. DEBUG_TRACE("%s", mallocStr);
  730. #endif
  731. return memory;
  732. }
  733. static void *
  734. mg_calloc_ex(size_t count, size_t size, const char *file, unsigned line)
  735. {
  736. void *data = mg_malloc_ex(size * count, file, line);
  737. if (data) {
  738. memset(data, 0, size * count);
  739. }
  740. return data;
  741. }
  742. static void
  743. mg_free_ex(void *memory, const char *file, unsigned line)
  744. {
  745. char mallocStr[256];
  746. void *data = (void *)(((char *)memory) - sizeof(size_t));
  747. size_t size;
  748. if (memory) {
  749. size = *(size_t *)data;
  750. mg_memory_debug_totalMemUsed -= size;
  751. mg_memory_debug_blockCount--;
  752. sprintf(mallocStr,
  753. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  754. memory,
  755. (unsigned long)size,
  756. mg_memory_debug_totalMemUsed,
  757. mg_memory_debug_blockCount,
  758. file,
  759. line);
  760. #if defined(_WIN32)
  761. OutputDebugStringA(mallocStr);
  762. #else
  763. DEBUG_TRACE("%s", mallocStr);
  764. #endif
  765. free(data);
  766. }
  767. }
  768. static void *
  769. mg_realloc_ex(void *memory, size_t newsize, const char *file, unsigned line)
  770. {
  771. char mallocStr[256];
  772. void *data;
  773. void *_realloc;
  774. size_t oldsize;
  775. if (newsize) {
  776. if (memory) {
  777. data = (void *)(((char *)memory) - sizeof(size_t));
  778. oldsize = *(size_t *)data;
  779. _realloc = realloc(data, newsize + sizeof(size_t));
  780. if (_realloc) {
  781. data = _realloc;
  782. mg_memory_debug_totalMemUsed -= oldsize;
  783. sprintf(mallocStr,
  784. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  785. memory,
  786. (unsigned long)oldsize,
  787. mg_memory_debug_totalMemUsed,
  788. mg_memory_debug_blockCount,
  789. file,
  790. line);
  791. #if defined(_WIN32)
  792. OutputDebugStringA(mallocStr);
  793. #else
  794. DEBUG_TRACE("%s", mallocStr);
  795. #endif
  796. mg_memory_debug_totalMemUsed += newsize;
  797. sprintf(mallocStr,
  798. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  799. memory,
  800. (unsigned long)newsize,
  801. mg_memory_debug_totalMemUsed,
  802. mg_memory_debug_blockCount,
  803. file,
  804. line);
  805. #if defined(_WIN32)
  806. OutputDebugStringA(mallocStr);
  807. #else
  808. DEBUG_TRACE("%s", mallocStr);
  809. #endif
  810. *(size_t *)data = newsize;
  811. data = (void *)(((char *)data) + sizeof(size_t));
  812. } else {
  813. #if defined(_WIN32)
  814. OutputDebugStringA("MEM: realloc failed\n");
  815. #else
  816. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  817. #endif
  818. return _realloc;
  819. }
  820. } else {
  821. data = mg_malloc_ex(newsize, file, line);
  822. }
  823. } else {
  824. data = 0;
  825. mg_free_ex(memory, file, line);
  826. }
  827. return data;
  828. }
  829. #define mg_malloc(a) mg_malloc_ex(a, __FILE__, __LINE__)
  830. #define mg_calloc(a, b) mg_calloc_ex(a, b, __FILE__, __LINE__)
  831. #define mg_realloc(a, b) mg_realloc_ex(a, b, __FILE__, __LINE__)
  832. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  833. #else
  834. static __inline void *
  835. mg_malloc(size_t a)
  836. {
  837. return malloc(a);
  838. }
  839. static __inline void *
  840. mg_calloc(size_t a, size_t b)
  841. {
  842. return calloc(a, b);
  843. }
  844. static __inline void *
  845. mg_realloc(void *a, size_t b)
  846. {
  847. return realloc(a, b);
  848. }
  849. static __inline void
  850. mg_free(void *a)
  851. {
  852. free(a);
  853. }
  854. #endif
  855. static void mg_vsnprintf(const struct mg_connection *conn,
  856. int *truncated,
  857. char *buf,
  858. size_t buflen,
  859. const char *fmt,
  860. va_list ap);
  861. static void mg_snprintf(const struct mg_connection *conn,
  862. int *truncated,
  863. char *buf,
  864. size_t buflen,
  865. PRINTF_FORMAT_STRING(const char *fmt),
  866. ...) PRINTF_ARGS(5, 6);
  867. /* This following lines are just meant as a reminder to use the mg-functions
  868. * for memory management */
  869. #ifdef malloc
  870. #undef malloc
  871. #endif
  872. #ifdef calloc
  873. #undef calloc
  874. #endif
  875. #ifdef realloc
  876. #undef realloc
  877. #endif
  878. #ifdef free
  879. #undef free
  880. #endif
  881. #ifdef snprintf
  882. #undef snprintf
  883. #endif
  884. #ifdef vsnprintf
  885. #undef vsnprintf
  886. #endif
  887. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  888. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  889. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  890. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  891. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  892. #ifdef _WIN32 /* vsnprintf must not be used in any system, * \ \ \ \
  893. * but this define only works well for Windows. */
  894. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  895. #endif
  896. static pthread_key_t sTlsKey; /* Thread local storage index */
  897. static int sTlsInit = 0;
  898. static int thread_idx_max = 0;
  899. struct mg_workerTLS {
  900. int is_master;
  901. unsigned long thread_idx;
  902. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  903. HANDLE pthread_cond_helper_mutex;
  904. struct mg_workerTLS *next_waiting_thread;
  905. #endif
  906. };
  907. #if defined(__GNUC__) || defined(__MINGW32__)
  908. /* Show no warning in case system functions are not used. */
  909. #pragma GCC diagnostic push
  910. #pragma GCC diagnostic ignored "-Wunused-function"
  911. #endif
  912. #if defined(__clang__)
  913. /* Show no warning in case system functions are not used. */
  914. #pragma clang diagnostic push
  915. #pragma clang diagnostic ignored "-Wunused-function"
  916. #endif
  917. /* Get a unique thread ID as unsigned long, independent from the data type
  918. * of thread IDs defined by the operating system API.
  919. * If two calls to mg_current_thread_id return the same value, they calls
  920. * are done from the same thread. If they return different values, they are
  921. * done from different threads. (Provided this function is used in the same
  922. * process context and threads are not repeatedly created and deleted, but
  923. * CivetWeb does not do that).
  924. * This function must match the signature required for SSL id callbacks:
  925. * CRYPTO_set_id_callback
  926. */
  927. static unsigned long
  928. mg_current_thread_id(void)
  929. {
  930. #ifdef _WIN32
  931. return GetCurrentThreadId();
  932. #else
  933. #ifdef __clang__
  934. #pragma clang diagnostic push
  935. #pragma clang diagnostic ignored "-Wunreachable-code"
  936. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  937. * or not, so one of the two conditions will be unreachable by construction.
  938. * Unfortunately the C standard does not define a way to check this at
  939. * compile time, since the #if preprocessor conditions can not use the sizeof
  940. * operator as an argument. */
  941. #endif
  942. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  943. /* This is the problematic case for CRYPTO_set_id_callback:
  944. * The OS pthread_t can not be cast to unsigned long. */
  945. struct mg_workerTLS *tls =
  946. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  947. if (tls == NULL) {
  948. /* SSL called from an unknown thread: Create some thread index.
  949. */
  950. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  951. tls->is_master = -2; /* -2 means "3rd party thread" */
  952. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  953. pthread_setspecific(sTlsKey, tls);
  954. }
  955. return tls->thread_idx;
  956. } else {
  957. /* pthread_t may be any data type, so a simple cast to unsigned long
  958. * can rise a warning/error, depending on the platform.
  959. * Here memcpy is used as an anything-to-anything cast. */
  960. unsigned long ret = 0;
  961. pthread_t t = pthread_self();
  962. memcpy(&ret, &t, sizeof(pthread_t));
  963. return ret;
  964. }
  965. #ifdef __clang__
  966. #pragma clang diagnostic pop
  967. #endif
  968. #endif
  969. }
  970. #if defined(__GNUC__)
  971. /* Show no warning in case system functions are not used. */
  972. #pragma GCC diagnostic pop
  973. #endif
  974. #if defined(__clang__)
  975. /* Show no warning in case system functions are not used. */
  976. #pragma clang diagnostic pop
  977. #endif
  978. #if !defined(DEBUG_TRACE)
  979. #if defined(DEBUG)
  980. static void DEBUG_TRACE_FUNC(const char *func,
  981. unsigned line,
  982. PRINTF_FORMAT_STRING(const char *fmt),
  983. ...) PRINTF_ARGS(3, 4);
  984. static void
  985. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  986. {
  987. va_list args;
  988. struct timespec tsnow;
  989. uint64_t nsnow;
  990. static uint64_t nslast;
  991. /* Get some operating system independent thread id */
  992. unsigned long thread_id = mg_current_thread_id();
  993. clock_gettime(CLOCK_REALTIME, &tsnow);
  994. nsnow = (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  995. flockfile(stdout);
  996. printf("*** %lu.%09lu %12" INT64_FMT " %lu %s:%u: ",
  997. (unsigned long)tsnow.tv_sec,
  998. (unsigned long)tsnow.tv_nsec,
  999. nsnow - nslast,
  1000. thread_id,
  1001. func,
  1002. line);
  1003. va_start(args, fmt);
  1004. vprintf(fmt, args);
  1005. va_end(args);
  1006. putchar('\n');
  1007. fflush(stdout);
  1008. funlockfile(stdout);
  1009. nslast = nsnow;
  1010. }
  1011. #define DEBUG_TRACE(fmt, ...) \
  1012. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  1013. #else
  1014. #define DEBUG_TRACE(fmt, ...) \
  1015. do { \
  1016. } while (0)
  1017. #endif /* DEBUG */
  1018. #endif /* DEBUG_TRACE */
  1019. #define MD5_STATIC static
  1020. #include "md5.inl"
  1021. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1022. #ifdef NO_SOCKLEN_T
  1023. typedef int socklen_t;
  1024. #endif /* NO_SOCKLEN_T */
  1025. #define _DARWIN_UNLIMITED_SELECT
  1026. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1027. #if !defined(MSG_NOSIGNAL)
  1028. #define MSG_NOSIGNAL (0)
  1029. #endif
  1030. #if !defined(SOMAXCONN)
  1031. #define SOMAXCONN (100)
  1032. #endif
  1033. /* Size of the accepted socket queue */
  1034. #if !defined(MGSQLEN)
  1035. #define MGSQLEN (20)
  1036. #endif
  1037. #if defined(NO_SSL)
  1038. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1039. typedef struct SSL_CTX SSL_CTX;
  1040. #else
  1041. #if defined(NO_SSL_DL)
  1042. #include <openssl/ssl.h>
  1043. #include <openssl/err.h>
  1044. #include <openssl/crypto.h>
  1045. #include <openssl/x509.h>
  1046. #include <openssl/pem.h>
  1047. #include <openssl/engine.h>
  1048. #include <openssl/conf.h>
  1049. #include <openssl/dh.h>
  1050. #include <openssl/bn.h>
  1051. #include <openssl/opensslv.h>
  1052. #else
  1053. /* SSL loaded dynamically from DLL.
  1054. * I put the prototypes here to be independent from OpenSSL source
  1055. * installation. */
  1056. typedef struct ssl_st SSL;
  1057. typedef struct ssl_method_st SSL_METHOD;
  1058. typedef struct ssl_ctx_st SSL_CTX;
  1059. typedef struct x509_store_ctx_st X509_STORE_CTX;
  1060. typedef struct x509_name X509_NAME;
  1061. typedef struct asn1_integer ASN1_INTEGER;
  1062. typedef struct bignum BIGNUM;
  1063. typedef struct ossl_init_settings_st OPENSSL_INIT_SETTINGS;
  1064. typedef struct evp_md EVP_MD;
  1065. typedef struct x509 X509;
  1066. #define SSL_CTRL_OPTIONS (32)
  1067. #define SSL_CTRL_CLEAR_OPTIONS (77)
  1068. #define SSL_CTRL_SET_ECDH_AUTO (94)
  1069. #define OPENSSL_INIT_NO_LOAD_SSL_STRINGS 0x00100000L
  1070. #define OPENSSL_INIT_LOAD_SSL_STRINGS 0x00200000L
  1071. #define OPENSSL_INIT_LOAD_CRYPTO_STRINGS 0x00000002L
  1072. #define SSL_VERIFY_NONE (0)
  1073. #define SSL_VERIFY_PEER (1)
  1074. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  1075. #define SSL_VERIFY_CLIENT_ONCE (4)
  1076. #define SSL_OP_ALL ((long)(0x80000BFFUL))
  1077. #define SSL_OP_NO_SSLv2 (0x01000000L)
  1078. #define SSL_OP_NO_SSLv3 (0x02000000L)
  1079. #define SSL_OP_NO_TLSv1 (0x04000000L)
  1080. #define SSL_OP_NO_TLSv1_2 (0x08000000L)
  1081. #define SSL_OP_NO_TLSv1_1 (0x10000000L)
  1082. #define SSL_OP_SINGLE_DH_USE (0x00100000L)
  1083. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000L)
  1084. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000L)
  1085. #define SSL_ERROR_NONE (0)
  1086. #define SSL_ERROR_SSL (1)
  1087. #define SSL_ERROR_WANT_READ (2)
  1088. #define SSL_ERROR_WANT_WRITE (3)
  1089. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  1090. #define SSL_ERROR_SYSCALL (5) /* see errno */
  1091. #define SSL_ERROR_ZERO_RETURN (6)
  1092. #define SSL_ERROR_WANT_CONNECT (7)
  1093. #define SSL_ERROR_WANT_ACCEPT (8)
  1094. struct ssl_func {
  1095. const char *name; /* SSL function name */
  1096. void (*ptr)(void); /* Function pointer */
  1097. };
  1098. #ifdef OPENSSL_API_1_1
  1099. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1100. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1101. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1102. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1103. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1104. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1105. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1106. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  1107. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  1108. #define TLS_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  1109. #define OPENSSL_init_ssl \
  1110. (*(int (*)(uint64_t opts, \
  1111. const OPENSSL_INIT_SETTINGS *settings))ssl_sw[10].ptr)
  1112. #define SSL_CTX_use_PrivateKey_file \
  1113. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1114. #define SSL_CTX_use_certificate_file \
  1115. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1116. #define SSL_CTX_set_default_passwd_cb \
  1117. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1118. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1119. #define SSL_CTX_use_certificate_chain_file \
  1120. (*(int (*)(SSL_CTX *, const char *))ssl_sw[15].ptr)
  1121. #define TLS_client_method (*(SSL_METHOD * (*)(void))ssl_sw[16].ptr)
  1122. #define SSL_pending (*(int (*)(SSL *))ssl_sw[17].ptr)
  1123. #define SSL_CTX_set_verify \
  1124. (*(void (*)(SSL_CTX *, \
  1125. int, \
  1126. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[18].ptr)
  1127. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[19].ptr)
  1128. #define SSL_CTX_load_verify_locations \
  1129. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[20].ptr)
  1130. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[21].ptr)
  1131. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[22].ptr)
  1132. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[23].ptr)
  1133. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[24].ptr)
  1134. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[25].ptr)
  1135. #define SSL_CIPHER_get_name \
  1136. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[26].ptr)
  1137. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[27].ptr)
  1138. #define SSL_CTX_set_session_id_context \
  1139. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[28].ptr)
  1140. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[29].ptr)
  1141. #define SSL_CTX_set_cipher_list \
  1142. (*(int (*)(SSL_CTX *, const char *))ssl_sw[30].ptr)
  1143. #define SSL_CTX_set_options \
  1144. (*(unsigned long (*)(SSL_CTX *, unsigned long))ssl_sw[31].ptr)
  1145. #define SSL_CTX_clear_options(ctx, op) \
  1146. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1147. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1148. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1149. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1150. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1151. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[0].ptr)
  1152. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[1].ptr)
  1153. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[2].ptr)
  1154. #define CONF_modules_unload (*(void (*)(int))crypto_sw[3].ptr)
  1155. #define X509_free (*(void (*)(X509 *))crypto_sw[4].ptr)
  1156. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[5].ptr)
  1157. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[6].ptr)
  1158. #define X509_NAME_oneline \
  1159. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[7].ptr)
  1160. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[8].ptr)
  1161. #define EVP_get_digestbyname \
  1162. (*(const EVP_MD *(*)(const char *))crypto_sw[9].ptr)
  1163. #define ASN1_digest \
  1164. (*(int (*)(int (*)(), \
  1165. const EVP_MD *, \
  1166. char *, \
  1167. unsigned char *, \
  1168. unsigned int *))crypto_sw[10].ptr)
  1169. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[11].ptr)
  1170. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[12].ptr)
  1171. #define ASN1_INTEGER_to_BN \
  1172. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn))crypto_sw[13].ptr)
  1173. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[14].ptr)
  1174. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[15].ptr)
  1175. #define OPENSSL_free(a) CRYPTO_free(a)
  1176. /* set_ssl_option() function updates this array.
  1177. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1178. * of respective functions. The macros above (like SSL_connect()) are really
  1179. * just calling these functions indirectly via the pointer. */
  1180. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1181. {"SSL_accept", NULL},
  1182. {"SSL_connect", NULL},
  1183. {"SSL_read", NULL},
  1184. {"SSL_write", NULL},
  1185. {"SSL_get_error", NULL},
  1186. {"SSL_set_fd", NULL},
  1187. {"SSL_new", NULL},
  1188. {"SSL_CTX_new", NULL},
  1189. {"TLS_server_method", NULL},
  1190. {"OPENSSL_init_ssl", NULL},
  1191. {"SSL_CTX_use_PrivateKey_file", NULL},
  1192. {"SSL_CTX_use_certificate_file", NULL},
  1193. {"SSL_CTX_set_default_passwd_cb", NULL},
  1194. {"SSL_CTX_free", NULL},
  1195. {"SSL_CTX_use_certificate_chain_file", NULL},
  1196. {"TLS_client_method", NULL},
  1197. {"SSL_pending", NULL},
  1198. {"SSL_CTX_set_verify", NULL},
  1199. {"SSL_shutdown", NULL},
  1200. {"SSL_CTX_load_verify_locations", NULL},
  1201. {"SSL_CTX_set_default_verify_paths", NULL},
  1202. {"SSL_CTX_set_verify_depth", NULL},
  1203. {"SSL_get_peer_certificate", NULL},
  1204. {"SSL_get_version", NULL},
  1205. {"SSL_get_current_cipher", NULL},
  1206. {"SSL_CIPHER_get_name", NULL},
  1207. {"SSL_CTX_check_private_key", NULL},
  1208. {"SSL_CTX_set_session_id_context", NULL},
  1209. {"SSL_CTX_ctrl", NULL},
  1210. {"SSL_CTX_set_cipher_list", NULL},
  1211. {"SSL_CTX_set_options", NULL},
  1212. {NULL, NULL}};
  1213. /* Similar array as ssl_sw. These functions could be located in different
  1214. * lib. */
  1215. static struct ssl_func crypto_sw[] = {{"ERR_get_error", NULL},
  1216. {"ERR_error_string", NULL},
  1217. {"ERR_remove_state", NULL},
  1218. {"CONF_modules_unload", NULL},
  1219. {"X509_free", NULL},
  1220. {"X509_get_subject_name", NULL},
  1221. {"X509_get_issuer_name", NULL},
  1222. {"X509_NAME_oneline", NULL},
  1223. {"X509_get_serialNumber", NULL},
  1224. {"EVP_get_digestbyname", NULL},
  1225. {"ASN1_digest", NULL},
  1226. {"i2d_X509", NULL},
  1227. {"BN_bn2hex", NULL},
  1228. {"ASN1_INTEGER_to_BN", NULL},
  1229. {"BN_free", NULL},
  1230. {"CRYPTO_free", NULL},
  1231. {NULL, NULL}};
  1232. #else
  1233. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1234. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1235. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1236. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1237. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1238. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1239. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1240. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  1241. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  1242. #define SSLv23_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  1243. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  1244. #define SSL_CTX_use_PrivateKey_file \
  1245. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1246. #define SSL_CTX_use_certificate_file \
  1247. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1248. #define SSL_CTX_set_default_passwd_cb \
  1249. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1250. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1251. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  1252. #define SSL_CTX_use_certificate_chain_file \
  1253. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  1254. #define SSLv23_client_method (*(SSL_METHOD * (*)(void))ssl_sw[17].ptr)
  1255. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  1256. #define SSL_CTX_set_verify \
  1257. (*(void (*)(SSL_CTX *, \
  1258. int, \
  1259. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19].ptr)
  1260. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  1261. #define SSL_CTX_load_verify_locations \
  1262. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  1263. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  1264. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  1265. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[24].ptr)
  1266. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  1267. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[26].ptr)
  1268. #define SSL_CIPHER_get_name \
  1269. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  1270. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  1271. #define SSL_CTX_set_session_id_context \
  1272. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  1273. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  1274. #define SSL_CTX_set_cipher_list \
  1275. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  1276. #define SSL_CTX_set_options(ctx, op) \
  1277. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  1278. #define SSL_CTX_clear_options(ctx, op) \
  1279. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1280. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1281. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1282. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1283. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1284. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  1285. #define CRYPTO_set_locking_callback \
  1286. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  1287. #define CRYPTO_set_id_callback \
  1288. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  1289. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  1290. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  1291. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  1292. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  1293. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  1294. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  1295. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  1296. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  1297. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  1298. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[12].ptr)
  1299. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[13].ptr)
  1300. #define X509_NAME_oneline \
  1301. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  1302. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[15].ptr)
  1303. #define i2c_ASN1_INTEGER \
  1304. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  1305. #define EVP_get_digestbyname \
  1306. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1307. #define ASN1_digest \
  1308. (*(int (*)(int (*)(), \
  1309. const EVP_MD *, \
  1310. char *, \
  1311. unsigned char *, \
  1312. unsigned int *))crypto_sw[18].ptr)
  1313. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1314. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[20].ptr)
  1315. #define ASN1_INTEGER_to_BN \
  1316. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn))crypto_sw[21].ptr)
  1317. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[22].ptr)
  1318. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[23].ptr)
  1319. #define OPENSSL_free(a) CRYPTO_free(a)
  1320. /* set_ssl_option() function updates this array.
  1321. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1322. * of respective functions. The macros above (like SSL_connect()) are really
  1323. * just calling these functions indirectly via the pointer. */
  1324. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1325. {"SSL_accept", NULL},
  1326. {"SSL_connect", NULL},
  1327. {"SSL_read", NULL},
  1328. {"SSL_write", NULL},
  1329. {"SSL_get_error", NULL},
  1330. {"SSL_set_fd", NULL},
  1331. {"SSL_new", NULL},
  1332. {"SSL_CTX_new", NULL},
  1333. {"SSLv23_server_method", NULL},
  1334. {"SSL_library_init", NULL},
  1335. {"SSL_CTX_use_PrivateKey_file", NULL},
  1336. {"SSL_CTX_use_certificate_file", NULL},
  1337. {"SSL_CTX_set_default_passwd_cb", NULL},
  1338. {"SSL_CTX_free", NULL},
  1339. {"SSL_load_error_strings", NULL},
  1340. {"SSL_CTX_use_certificate_chain_file", NULL},
  1341. {"SSLv23_client_method", NULL},
  1342. {"SSL_pending", NULL},
  1343. {"SSL_CTX_set_verify", NULL},
  1344. {"SSL_shutdown", NULL},
  1345. {"SSL_CTX_load_verify_locations", NULL},
  1346. {"SSL_CTX_set_default_verify_paths", NULL},
  1347. {"SSL_CTX_set_verify_depth", NULL},
  1348. {"SSL_get_peer_certificate", NULL},
  1349. {"SSL_get_version", NULL},
  1350. {"SSL_get_current_cipher", NULL},
  1351. {"SSL_CIPHER_get_name", NULL},
  1352. {"SSL_CTX_check_private_key", NULL},
  1353. {"SSL_CTX_set_session_id_context", NULL},
  1354. {"SSL_CTX_ctrl", NULL},
  1355. {"SSL_CTX_set_cipher_list", NULL},
  1356. {NULL, NULL}};
  1357. /* Similar array as ssl_sw. These functions could be located in different
  1358. * lib. */
  1359. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  1360. {"CRYPTO_set_locking_callback", NULL},
  1361. {"CRYPTO_set_id_callback", NULL},
  1362. {"ERR_get_error", NULL},
  1363. {"ERR_error_string", NULL},
  1364. {"ERR_remove_state", NULL},
  1365. {"ERR_free_strings", NULL},
  1366. {"ENGINE_cleanup", NULL},
  1367. {"CONF_modules_unload", NULL},
  1368. {"CRYPTO_cleanup_all_ex_data", NULL},
  1369. {"EVP_cleanup", NULL},
  1370. {"X509_free", NULL},
  1371. {"X509_get_subject_name", NULL},
  1372. {"X509_get_issuer_name", NULL},
  1373. {"X509_NAME_oneline", NULL},
  1374. {"X509_get_serialNumber", NULL},
  1375. {"i2c_ASN1_INTEGER", NULL},
  1376. {"EVP_get_digestbyname", NULL},
  1377. {"ASN1_digest", NULL},
  1378. {"i2d_X509", NULL},
  1379. {"BN_bn2hex", NULL},
  1380. {"ASN1_INTEGER_to_BN", NULL},
  1381. {"BN_free", NULL},
  1382. {"CRYPTO_free", NULL},
  1383. {NULL, NULL}};
  1384. #endif /* OPENSSL_API_1_1 */
  1385. #endif /* NO_SSL_DL */
  1386. #endif /* NO_SSL */
  1387. #if !defined(NO_CACHING)
  1388. static const char *month_names[] = {"Jan",
  1389. "Feb",
  1390. "Mar",
  1391. "Apr",
  1392. "May",
  1393. "Jun",
  1394. "Jul",
  1395. "Aug",
  1396. "Sep",
  1397. "Oct",
  1398. "Nov",
  1399. "Dec"};
  1400. #endif /* !NO_CACHING */
  1401. /* Unified socket address. For IPv6 support, add IPv6 address structure in the
  1402. * union u. */
  1403. union usa {
  1404. struct sockaddr sa;
  1405. struct sockaddr_in sin;
  1406. #if defined(USE_IPV6)
  1407. struct sockaddr_in6 sin6;
  1408. #endif
  1409. };
  1410. /* Describes a string (chunk of memory). */
  1411. struct vec {
  1412. const char *ptr;
  1413. size_t len;
  1414. };
  1415. struct mg_file_stat {
  1416. /* File properties filled by mg_stat: */
  1417. uint64_t size;
  1418. time_t last_modified;
  1419. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1420. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1421. * case we need a "Content-Eencoding: gzip" header */
  1422. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1423. };
  1424. struct mg_file_in_memory {
  1425. char *p;
  1426. uint32_t pos;
  1427. char mode;
  1428. };
  1429. struct mg_file_access {
  1430. /* File properties filled by mg_fopen: */
  1431. FILE *fp;
  1432. /* TODO (low): Replace "membuf" implementation by a "file in memory"
  1433. * support library. Use some struct mg_file_in_memory *mf; instead of
  1434. * membuf char pointer. */
  1435. const char *membuf;
  1436. };
  1437. struct mg_file {
  1438. struct mg_file_stat stat;
  1439. struct mg_file_access access;
  1440. };
  1441. #define STRUCT_FILE_INITIALIZER \
  1442. { \
  1443. { \
  1444. (uint64_t)0, (time_t)0, 0, 0, 0 \
  1445. } \
  1446. , \
  1447. { \
  1448. (FILE *) NULL, (const char *)NULL \
  1449. } \
  1450. }
  1451. /* Describes listening socket, or socket which was accept()-ed by the master
  1452. * thread and queued for future handling by the worker thread. */
  1453. struct socket {
  1454. SOCKET sock; /* Listening socket */
  1455. union usa lsa; /* Local socket address */
  1456. union usa rsa; /* Remote socket address */
  1457. unsigned char is_ssl; /* Is port SSL-ed */
  1458. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1459. * port */
  1460. unsigned char in_use; /* Is valid */
  1461. };
  1462. /* NOTE(lsm): this enum shoulds be in sync with the config_options below. */
  1463. enum {
  1464. CGI_EXTENSIONS,
  1465. CGI_ENVIRONMENT,
  1466. PUT_DELETE_PASSWORDS_FILE,
  1467. CGI_INTERPRETER,
  1468. PROTECT_URI,
  1469. AUTHENTICATION_DOMAIN,
  1470. ENABLE_AUTH_DOMAIN_CHECK,
  1471. SSI_EXTENSIONS,
  1472. THROTTLE,
  1473. ACCESS_LOG_FILE,
  1474. ENABLE_DIRECTORY_LISTING,
  1475. ERROR_LOG_FILE,
  1476. GLOBAL_PASSWORDS_FILE,
  1477. INDEX_FILES,
  1478. ENABLE_KEEP_ALIVE,
  1479. ACCESS_CONTROL_LIST,
  1480. EXTRA_MIME_TYPES,
  1481. LISTENING_PORTS,
  1482. DOCUMENT_ROOT,
  1483. SSL_CERTIFICATE,
  1484. NUM_THREADS,
  1485. RUN_AS_USER,
  1486. REWRITE,
  1487. HIDE_FILES,
  1488. REQUEST_TIMEOUT,
  1489. KEEP_ALIVE_TIMEOUT,
  1490. LINGER_TIMEOUT,
  1491. SSL_DO_VERIFY_PEER,
  1492. SSL_CA_PATH,
  1493. SSL_CA_FILE,
  1494. SSL_VERIFY_DEPTH,
  1495. SSL_DEFAULT_VERIFY_PATHS,
  1496. SSL_CIPHER_LIST,
  1497. SSL_PROTOCOL_VERSION,
  1498. SSL_SHORT_TRUST,
  1499. #if defined(USE_WEBSOCKET)
  1500. WEBSOCKET_TIMEOUT,
  1501. #endif
  1502. DECODE_URL,
  1503. #if defined(USE_LUA)
  1504. LUA_PRELOAD_FILE,
  1505. LUA_SCRIPT_EXTENSIONS,
  1506. LUA_SERVER_PAGE_EXTENSIONS,
  1507. #endif
  1508. #if defined(USE_DUKTAPE)
  1509. DUKTAPE_SCRIPT_EXTENSIONS,
  1510. #endif
  1511. #if defined(USE_WEBSOCKET)
  1512. WEBSOCKET_ROOT,
  1513. #endif
  1514. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1515. LUA_WEBSOCKET_EXTENSIONS,
  1516. #endif
  1517. ACCESS_CONTROL_ALLOW_ORIGIN,
  1518. ERROR_PAGES,
  1519. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1520. * socket option typedef TCP_NODELAY. */
  1521. #if !defined(NO_CACHING)
  1522. STATIC_FILE_MAX_AGE,
  1523. #endif
  1524. #if defined(__linux__)
  1525. ALLOW_SENDFILE_CALL,
  1526. #endif
  1527. #if defined(_WIN32)
  1528. CASE_SENSITIVE_FILES,
  1529. #endif
  1530. #if defined(USE_LUA)
  1531. LUA_BACKGROUND_SCRIPT,
  1532. #endif
  1533. NUM_OPTIONS
  1534. };
  1535. /* Config option name, config types, default value */
  1536. static struct mg_option config_options[] = {
  1537. {"cgi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1538. {"cgi_environment", CONFIG_TYPE_STRING, NULL},
  1539. {"put_delete_auth_file", CONFIG_TYPE_FILE, NULL},
  1540. {"cgi_interpreter", CONFIG_TYPE_FILE, NULL},
  1541. {"protect_uri", CONFIG_TYPE_STRING, NULL},
  1542. {"authentication_domain", CONFIG_TYPE_STRING, "mydomain.com"},
  1543. {"enable_auth_domain_check", CONFIG_TYPE_BOOLEAN, "yes"},
  1544. {"ssi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1545. {"throttle", CONFIG_TYPE_STRING, NULL},
  1546. {"access_log_file", CONFIG_TYPE_FILE, NULL},
  1547. {"enable_directory_listing", CONFIG_TYPE_BOOLEAN, "yes"},
  1548. {"error_log_file", CONFIG_TYPE_FILE, NULL},
  1549. {"global_auth_file", CONFIG_TYPE_FILE, NULL},
  1550. {"index_files",
  1551. CONFIG_TYPE_STRING,
  1552. #ifdef USE_LUA
  1553. "index.xhtml,index.html,index.htm,index.lp,index.lsp,index.lua,index.cgi,"
  1554. "index.shtml,index.php"},
  1555. #else
  1556. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1557. #endif
  1558. {"enable_keep_alive", CONFIG_TYPE_BOOLEAN, "no"},
  1559. {"access_control_list", CONFIG_TYPE_STRING, NULL},
  1560. {"extra_mime_types", CONFIG_TYPE_STRING, NULL},
  1561. {"listening_ports", CONFIG_TYPE_STRING, "8080"},
  1562. {"document_root", CONFIG_TYPE_DIRECTORY, NULL},
  1563. {"ssl_certificate", CONFIG_TYPE_FILE, NULL},
  1564. {"num_threads", CONFIG_TYPE_NUMBER, "50"},
  1565. {"run_as_user", CONFIG_TYPE_STRING, NULL},
  1566. {"url_rewrite_patterns", CONFIG_TYPE_STRING, NULL},
  1567. {"hide_files_patterns", CONFIG_TYPE_EXT_PATTERN, NULL},
  1568. {"request_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1569. {"keep_alive_timeout_ms", CONFIG_TYPE_NUMBER, "500"},
  1570. {"linger_timeout_ms", CONFIG_TYPE_NUMBER, NULL},
  1571. {"ssl_verify_peer", CONFIG_TYPE_BOOLEAN, "no"},
  1572. {"ssl_ca_path", CONFIG_TYPE_DIRECTORY, NULL},
  1573. {"ssl_ca_file", CONFIG_TYPE_FILE, NULL},
  1574. {"ssl_verify_depth", CONFIG_TYPE_NUMBER, "9"},
  1575. {"ssl_default_verify_paths", CONFIG_TYPE_BOOLEAN, "yes"},
  1576. {"ssl_cipher_list", CONFIG_TYPE_STRING, NULL},
  1577. {"ssl_protocol_version", CONFIG_TYPE_NUMBER, "0"},
  1578. {"ssl_short_trust", CONFIG_TYPE_BOOLEAN, "no"},
  1579. #if defined(USE_WEBSOCKET)
  1580. {"websocket_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1581. #endif
  1582. {"decode_url", CONFIG_TYPE_BOOLEAN, "yes"},
  1583. #if defined(USE_LUA)
  1584. {"lua_preload_file", CONFIG_TYPE_FILE, NULL},
  1585. {"lua_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1586. {"lua_server_page_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1587. #endif
  1588. #if defined(USE_DUKTAPE)
  1589. /* The support for duktape is still in alpha version state.
  1590. * The name of this config option might change. */
  1591. {"duktape_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1592. #endif
  1593. #if defined(USE_WEBSOCKET)
  1594. {"websocket_root", CONFIG_TYPE_DIRECTORY, NULL},
  1595. #endif
  1596. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1597. {"lua_websocket_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1598. #endif
  1599. {"access_control_allow_origin", CONFIG_TYPE_STRING, "*"},
  1600. {"error_pages", CONFIG_TYPE_DIRECTORY, NULL},
  1601. {"tcp_nodelay", CONFIG_TYPE_NUMBER, "0"},
  1602. #if !defined(NO_CACHING)
  1603. {"static_file_max_age", CONFIG_TYPE_NUMBER, "3600"},
  1604. #endif
  1605. #if defined(__linux__)
  1606. {"allow_sendfile_call", CONFIG_TYPE_BOOLEAN, "yes"},
  1607. #endif
  1608. #if defined(_WIN32)
  1609. {"case_sensitive", CONFIG_TYPE_BOOLEAN, "no"},
  1610. #endif
  1611. #if defined(USE_LUA)
  1612. {"lua_background_script", CONFIG_TYPE_FILE, NULL},
  1613. #endif
  1614. {NULL, CONFIG_TYPE_UNKNOWN, NULL}};
  1615. /* Check if the config_options and the corresponding enum have compatible
  1616. * sizes. */
  1617. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1618. == (NUM_OPTIONS + 1),
  1619. "config_options and enum not sync");
  1620. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1621. struct mg_handler_info {
  1622. /* Name/Pattern of the URI. */
  1623. char *uri;
  1624. size_t uri_len;
  1625. /* handler type */
  1626. int handler_type;
  1627. /* Handler for http/https or authorization requests. */
  1628. mg_request_handler handler;
  1629. /* Handler for ws/wss (websocket) requests. */
  1630. mg_websocket_connect_handler connect_handler;
  1631. mg_websocket_ready_handler ready_handler;
  1632. mg_websocket_data_handler data_handler;
  1633. mg_websocket_close_handler close_handler;
  1634. /* accepted subprotocols for ws/wss requests. */
  1635. struct mg_websocket_subprotocols *subprotocols;
  1636. /* Handler for authorization requests */
  1637. mg_authorization_handler auth_handler;
  1638. /* User supplied argument for the handler function. */
  1639. void *cbdata;
  1640. /* next handler in a linked list */
  1641. struct mg_handler_info *next;
  1642. };
  1643. struct mg_context {
  1644. volatile int stop_flag; /* Should we stop event loop */
  1645. SSL_CTX *ssl_ctx; /* SSL context */
  1646. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1647. struct mg_callbacks callbacks; /* User-defined callback function */
  1648. void *user_data; /* User-defined data */
  1649. int context_type; /* 1 = server context,
  1650. * 2 = ws/wss client context,
  1651. */
  1652. struct socket *listening_sockets;
  1653. struct pollfd *listening_socket_fds;
  1654. unsigned int num_listening_sockets;
  1655. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  1656. #ifdef ALTERNATIVE_QUEUE
  1657. struct socket *client_socks;
  1658. void **client_wait_events;
  1659. #else
  1660. struct socket queue[MGSQLEN]; /* Accepted sockets */
  1661. volatile int sq_head; /* Head of the socket queue */
  1662. volatile int sq_tail; /* Tail of the socket queue */
  1663. pthread_cond_t sq_full; /* Signaled when socket is produced */
  1664. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  1665. #endif
  1666. pthread_t masterthreadid; /* The master thread ID */
  1667. unsigned int
  1668. cfg_worker_threads; /* The number of configured worker threads. */
  1669. pthread_t *worker_threadids; /* The worker thread IDs */
  1670. struct mg_connection *worker_connections; /* The connection struct, pre-
  1671. * allocated for each worker */
  1672. time_t start_time; /* Server start time, used for authentication */
  1673. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1674. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  1675. unsigned long nonce_count; /* Used nonces, used for authentication */
  1676. char *systemName; /* What operating system is running */
  1677. /* linked list of uri handlers */
  1678. struct mg_handler_info *handlers;
  1679. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1680. /* linked list of shared lua websockets */
  1681. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1682. #endif
  1683. #if defined(USE_TIMERS)
  1684. struct ttimers *timers;
  1685. #endif
  1686. #if defined(USE_LUA)
  1687. void *lua_background_state;
  1688. #endif
  1689. };
  1690. struct mg_connection {
  1691. struct mg_request_info request_info;
  1692. struct mg_context *ctx;
  1693. SSL *ssl; /* SSL descriptor */
  1694. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  1695. struct socket client; /* Connected client */
  1696. time_t conn_birth_time; /* Time (wall clock) when connection was
  1697. * established */
  1698. struct timespec req_time; /* Time (since system start) when the request
  1699. * was received */
  1700. int64_t num_bytes_sent; /* Total bytes sent to client */
  1701. int64_t content_len; /* Content-Length header value */
  1702. int64_t consumed_content; /* How many bytes of content have been read */
  1703. int is_chunked; /* Transfer-Encoding is chunked: 0=no, 1=yes:
  1704. * data available, 2: all data read */
  1705. size_t chunk_remainder; /* Unread data from the last chunk */
  1706. char *buf; /* Buffer for received data */
  1707. char *path_info; /* PATH_INFO part of the URL */
  1708. int must_close; /* 1 if connection must be closed */
  1709. int in_error_handler; /* 1 if in handler for user defined error
  1710. * pages */
  1711. int handled_requests; /* Number of requests handled by this connection */
  1712. int buf_size; /* Buffer size */
  1713. int request_len; /* Size of the request + headers in a buffer */
  1714. int data_len; /* Total size of data in a buffer */
  1715. int status_code; /* HTTP reply status code, e.g. 200 */
  1716. int throttle; /* Throttling, bytes/sec. <= 0 means no
  1717. * throttle */
  1718. time_t last_throttle_time; /* Last time throttled data was sent */
  1719. int64_t last_throttle_bytes; /* Bytes sent this second */
  1720. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  1721. * atomic transmissions for websockets */
  1722. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1723. void *lua_websocket_state; /* Lua_State for a websocket connection */
  1724. #endif
  1725. int thread_index; /* Thread index within ctx */
  1726. };
  1727. /* Directory entry */
  1728. struct de {
  1729. struct mg_connection *conn;
  1730. char *file_name;
  1731. struct mg_file_stat file;
  1732. };
  1733. #if defined(USE_WEBSOCKET)
  1734. static int is_websocket_protocol(const struct mg_connection *conn);
  1735. #else
  1736. #define is_websocket_protocol(conn) (0)
  1737. #endif
  1738. #if !defined(NO_THREAD_NAME)
  1739. #if defined(_WIN32) && defined(_MSC_VER)
  1740. /* Set the thread name for debugging purposes in Visual Studio
  1741. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  1742. */
  1743. #pragma pack(push, 8)
  1744. typedef struct tagTHREADNAME_INFO {
  1745. DWORD dwType; /* Must be 0x1000. */
  1746. LPCSTR szName; /* Pointer to name (in user addr space). */
  1747. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  1748. DWORD dwFlags; /* Reserved for future use, must be zero. */
  1749. } THREADNAME_INFO;
  1750. #pragma pack(pop)
  1751. #elif defined(__linux__)
  1752. #include <sys/prctl.h>
  1753. #include <sys/sendfile.h>
  1754. #include <sys/eventfd.h>
  1755. #if defined(ALTERNATIVE_QUEUE)
  1756. static void *
  1757. event_create(void)
  1758. {
  1759. int ret = eventfd(0, EFD_CLOEXEC);
  1760. if (ret == -1) {
  1761. /* Linux uses -1 on error, Windows NULL. */
  1762. /* However, Linux does not return 0 on success either. */
  1763. return 0;
  1764. }
  1765. return (void *)ret;
  1766. }
  1767. static int
  1768. event_wait(void *eventhdl)
  1769. {
  1770. uint64_t u;
  1771. int s = (int)read((int)eventhdl, &u, sizeof(u));
  1772. if (s != sizeof(uint64_t)) {
  1773. /* error */
  1774. return 0;
  1775. }
  1776. (void)u; /* the value is not required */
  1777. return 1;
  1778. }
  1779. static int
  1780. event_signal(void *eventhdl)
  1781. {
  1782. uint64_t u = 1;
  1783. int s = (int)write((int)eventhdl, &u, sizeof(u));
  1784. if (s != sizeof(uint64_t)) {
  1785. /* error */
  1786. return 0;
  1787. }
  1788. return 1;
  1789. }
  1790. static void
  1791. event_destroy(void *eventhdl)
  1792. {
  1793. close((int)eventhdl);
  1794. }
  1795. #endif
  1796. #endif
  1797. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  1798. struct posix_event {
  1799. pthread_mutex_t mutex;
  1800. pthread_cond_t cond;
  1801. };
  1802. static void *
  1803. event_create(void)
  1804. {
  1805. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  1806. if (ret == 0) {
  1807. /* out of memory */
  1808. return 0;
  1809. }
  1810. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  1811. /* pthread mutex not available */
  1812. mg_free(ret);
  1813. return 0;
  1814. }
  1815. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  1816. /* pthread cond not available */
  1817. pthread_mutex_destroy(&(ret->mutex));
  1818. mg_free(ret);
  1819. return 0;
  1820. }
  1821. return (void *)ret;
  1822. }
  1823. static int
  1824. event_wait(void *eventhdl)
  1825. {
  1826. struct posix_event *ev = (struct posix_event *)eventhdl;
  1827. pthread_mutex_lock(&(ev->mutex));
  1828. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  1829. pthread_mutex_unlock(&(ev->mutex));
  1830. return 1;
  1831. }
  1832. static int
  1833. event_signal(void *eventhdl)
  1834. {
  1835. struct posix_event *ev = (struct posix_event *)eventhdl;
  1836. pthread_mutex_lock(&(ev->mutex));
  1837. pthread_cond_signal(&(ev->cond));
  1838. pthread_mutex_unlock(&(ev->mutex));
  1839. return 1;
  1840. }
  1841. static void
  1842. event_destroy(void *eventhdl)
  1843. {
  1844. struct posix_event *ev = (struct posix_event *)eventhdl;
  1845. pthread_cond_destroy(&(ev->cond));
  1846. pthread_mutex_destroy(&(ev->mutex));
  1847. mg_free(ev);
  1848. }
  1849. #endif
  1850. static void
  1851. mg_set_thread_name(const char *name)
  1852. {
  1853. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  1854. mg_snprintf(
  1855. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  1856. #if defined(_WIN32)
  1857. #if defined(_MSC_VER)
  1858. /* Windows and Visual Studio Compiler */
  1859. __try
  1860. {
  1861. THREADNAME_INFO info;
  1862. info.dwType = 0x1000;
  1863. info.szName = threadName;
  1864. info.dwThreadID = ~0U;
  1865. info.dwFlags = 0;
  1866. RaiseException(0x406D1388,
  1867. 0,
  1868. sizeof(info) / sizeof(ULONG_PTR),
  1869. (ULONG_PTR *)&info);
  1870. }
  1871. __except(EXCEPTION_EXECUTE_HANDLER)
  1872. {
  1873. }
  1874. #elif defined(__MINGW32__)
  1875. /* No option known to set thread name for MinGW */
  1876. #endif
  1877. #elif defined(__GLIBC__) \
  1878. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  1879. /* pthread_setname_np first appeared in glibc in version 2.12*/
  1880. (void)pthread_setname_np(pthread_self(), threadName);
  1881. #elif defined(__linux__)
  1882. /* on linux we can use the old prctl function */
  1883. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  1884. #endif
  1885. }
  1886. #else /* !defined(NO_THREAD_NAME) */
  1887. void
  1888. mg_set_thread_name(const char *threadName)
  1889. {
  1890. }
  1891. #endif
  1892. #if defined(MG_LEGACY_INTERFACE)
  1893. const char **
  1894. mg_get_valid_option_names(void)
  1895. {
  1896. /* This function is deprecated. Use mg_get_valid_options instead. */
  1897. static const char *
  1898. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  1899. int i;
  1900. for (i = 0; config_options[i].name != NULL; i++) {
  1901. data[i * 2] = config_options[i].name;
  1902. data[i * 2 + 1] = config_options[i].default_value;
  1903. }
  1904. return data;
  1905. }
  1906. #endif
  1907. const struct mg_option *
  1908. mg_get_valid_options(void)
  1909. {
  1910. return config_options;
  1911. }
  1912. /* Do not open file (used in is_file_in_memory) */
  1913. #define MG_FOPEN_MODE_NONE (0)
  1914. /* Open file for read only access */
  1915. #define MG_FOPEN_MODE_READ (1)
  1916. /* Open file for writing, create and overwrite */
  1917. #define MG_FOPEN_MODE_WRITE (2)
  1918. /* Open file for writing, create and append */
  1919. #define MG_FOPEN_MODE_APPEND (4)
  1920. /* If a file is in memory, set all "stat" members and the membuf pointer of
  1921. * output filep and return 1, otherwise return 0 and don't modify anything. */
  1922. static int
  1923. open_file_in_memory(const struct mg_connection *conn,
  1924. const char *path,
  1925. struct mg_file *filep,
  1926. int mode)
  1927. {
  1928. size_t size = 0;
  1929. const char *buf = NULL;
  1930. if (!conn) {
  1931. return 0;
  1932. }
  1933. if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
  1934. return 0;
  1935. }
  1936. if (conn->ctx->callbacks.open_file) {
  1937. buf = conn->ctx->callbacks.open_file(conn, path, &size);
  1938. if (buf != NULL) {
  1939. if (filep == NULL) {
  1940. /* This is a file in memory, but we cannot store the properties
  1941. * now.
  1942. * Called from "is_file_in_memory" function. */
  1943. return 1;
  1944. }
  1945. /* NOTE: override filep->size only on success. Otherwise, it might
  1946. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  1947. filep->access.membuf = buf;
  1948. filep->access.fp = NULL;
  1949. /* Size was set by the callback */
  1950. filep->stat.size = size;
  1951. /* Assume the data may change during runtime by setting
  1952. * last_modified = now */
  1953. filep->stat.last_modified = time(NULL);
  1954. filep->stat.is_directory = 0;
  1955. filep->stat.is_gzipped = 0;
  1956. }
  1957. }
  1958. return (buf != NULL);
  1959. }
  1960. static int
  1961. is_file_in_memory(const struct mg_connection *conn, const char *path)
  1962. {
  1963. return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
  1964. }
  1965. static int
  1966. is_file_opened(const struct mg_file_access *fileacc)
  1967. {
  1968. if (!fileacc) {
  1969. return 0;
  1970. }
  1971. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  1972. }
  1973. static int mg_stat(const struct mg_connection *conn,
  1974. const char *path,
  1975. struct mg_file_stat *filep);
  1976. /* mg_fopen will open a file either in memory or on the disk.
  1977. * The input parameter path is a string in UTF-8 encoding.
  1978. * The input parameter mode is MG_FOPEN_MODE_*
  1979. * On success, either fp or membuf will be set in the output
  1980. * struct file. All status members will also be set.
  1981. * The function returns 1 on success, 0 on error. */
  1982. static int
  1983. mg_fopen(const struct mg_connection *conn,
  1984. const char *path,
  1985. int mode,
  1986. struct mg_file *filep)
  1987. {
  1988. int found;
  1989. if (!filep) {
  1990. return 0;
  1991. }
  1992. filep->access.fp = NULL;
  1993. filep->access.membuf = NULL;
  1994. if (!is_file_in_memory(conn, path)) {
  1995. /* filep is initialized in mg_stat: all fields with memset to,
  1996. * some fields like size and modification date with values */
  1997. found = mg_stat(conn, path, &(filep->stat));
  1998. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  1999. /* file does not exist and will not be created */
  2000. return 0;
  2001. }
  2002. #ifdef _WIN32
  2003. {
  2004. wchar_t wbuf[PATH_MAX];
  2005. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2006. switch (mode) {
  2007. case MG_FOPEN_MODE_READ:
  2008. filep->access.fp = _wfopen(wbuf, L"rb");
  2009. break;
  2010. case MG_FOPEN_MODE_WRITE:
  2011. filep->access.fp = _wfopen(wbuf, L"wb");
  2012. break;
  2013. case MG_FOPEN_MODE_APPEND:
  2014. filep->access.fp = _wfopen(wbuf, L"ab");
  2015. break;
  2016. }
  2017. }
  2018. #else
  2019. /* Linux et al already use unicode. No need to convert. */
  2020. switch (mode) {
  2021. case MG_FOPEN_MODE_READ:
  2022. filep->access.fp = fopen(path, "r");
  2023. break;
  2024. case MG_FOPEN_MODE_WRITE:
  2025. filep->access.fp = fopen(path, "w");
  2026. break;
  2027. case MG_FOPEN_MODE_APPEND:
  2028. filep->access.fp = fopen(path, "a");
  2029. break;
  2030. }
  2031. #endif
  2032. if (!found) {
  2033. /* File did not exist before fopen was called.
  2034. * Maybe it has been created now. Get stat info
  2035. * like creation time now. */
  2036. found = mg_stat(conn, path, &(filep->stat));
  2037. (void)found;
  2038. }
  2039. /* file is on disk */
  2040. return (filep->access.fp != NULL);
  2041. } else {
  2042. /* is_file_in_memory returned true */
  2043. if (open_file_in_memory(conn, path, filep, mode)) {
  2044. /* file is in memory */
  2045. return (filep->access.membuf != NULL);
  2046. }
  2047. }
  2048. /* Open failed */
  2049. return 0;
  2050. }
  2051. /* return 0 on success, just like fclose */
  2052. static int
  2053. mg_fclose(struct mg_file_access *fileacc)
  2054. {
  2055. int ret = -1;
  2056. if (fileacc != NULL) {
  2057. if (fileacc->fp != NULL) {
  2058. ret = fclose(fileacc->fp);
  2059. } else if (fileacc->membuf != NULL) {
  2060. ret = 0;
  2061. }
  2062. /* reset all members of fileacc */
  2063. memset(fileacc, 0, sizeof(*fileacc));
  2064. }
  2065. return ret;
  2066. }
  2067. static void
  2068. mg_strlcpy(register char *dst, register const char *src, size_t n)
  2069. {
  2070. for (; *src != '\0' && n > 1; n--) {
  2071. *dst++ = *src++;
  2072. }
  2073. *dst = '\0';
  2074. }
  2075. static int
  2076. lowercase(const char *s)
  2077. {
  2078. return tolower(*(const unsigned char *)s);
  2079. }
  2080. int
  2081. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2082. {
  2083. int diff = 0;
  2084. if (len > 0) {
  2085. do {
  2086. diff = lowercase(s1++) - lowercase(s2++);
  2087. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2088. }
  2089. return diff;
  2090. }
  2091. int
  2092. mg_strcasecmp(const char *s1, const char *s2)
  2093. {
  2094. int diff;
  2095. do {
  2096. diff = lowercase(s1++) - lowercase(s2++);
  2097. } while (diff == 0 && s1[-1] != '\0');
  2098. return diff;
  2099. }
  2100. static char *
  2101. mg_strndup(const char *ptr, size_t len)
  2102. {
  2103. char *p;
  2104. if ((p = (char *)mg_malloc(len + 1)) != NULL) {
  2105. mg_strlcpy(p, ptr, len + 1);
  2106. }
  2107. return p;
  2108. }
  2109. static char *
  2110. mg_strdup(const char *str)
  2111. {
  2112. return mg_strndup(str, strlen(str));
  2113. }
  2114. static const char *
  2115. mg_strcasestr(const char *big_str, const char *small_str)
  2116. {
  2117. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2118. if (big_len >= small_len) {
  2119. for (i = 0; i <= (big_len - small_len); i++) {
  2120. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2121. return big_str + i;
  2122. }
  2123. }
  2124. }
  2125. return NULL;
  2126. }
  2127. /* Return null terminated string of given maximum length.
  2128. * Report errors if length is exceeded. */
  2129. static void
  2130. mg_vsnprintf(const struct mg_connection *conn,
  2131. int *truncated,
  2132. char *buf,
  2133. size_t buflen,
  2134. const char *fmt,
  2135. va_list ap)
  2136. {
  2137. int n, ok;
  2138. if (buflen == 0) {
  2139. return;
  2140. }
  2141. #ifdef __clang__
  2142. #pragma clang diagnostic push
  2143. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2144. /* Using fmt as a non-literal is intended here, since it is mostly called
  2145. * indirectly by mg_snprintf */
  2146. #endif
  2147. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2148. ok = (n >= 0) && ((size_t)n < buflen);
  2149. #ifdef __clang__
  2150. #pragma clang diagnostic pop
  2151. #endif
  2152. if (ok) {
  2153. if (truncated) {
  2154. *truncated = 0;
  2155. }
  2156. } else {
  2157. if (truncated) {
  2158. *truncated = 1;
  2159. }
  2160. mg_cry(conn,
  2161. "truncating vsnprintf buffer: [%.*s]",
  2162. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2163. buf);
  2164. n = (int)buflen - 1;
  2165. }
  2166. buf[n] = '\0';
  2167. }
  2168. static void
  2169. mg_snprintf(const struct mg_connection *conn,
  2170. int *truncated,
  2171. char *buf,
  2172. size_t buflen,
  2173. const char *fmt,
  2174. ...)
  2175. {
  2176. va_list ap;
  2177. va_start(ap, fmt);
  2178. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2179. va_end(ap);
  2180. }
  2181. static int
  2182. get_option_index(const char *name)
  2183. {
  2184. int i;
  2185. for (i = 0; config_options[i].name != NULL; i++) {
  2186. if (strcmp(config_options[i].name, name) == 0) {
  2187. return i;
  2188. }
  2189. }
  2190. return -1;
  2191. }
  2192. const char *
  2193. mg_get_option(const struct mg_context *ctx, const char *name)
  2194. {
  2195. int i;
  2196. if ((i = get_option_index(name)) == -1) {
  2197. return NULL;
  2198. } else if (!ctx || ctx->config[i] == NULL) {
  2199. return "";
  2200. } else {
  2201. return ctx->config[i];
  2202. }
  2203. }
  2204. struct mg_context *
  2205. mg_get_context(const struct mg_connection *conn)
  2206. {
  2207. return (conn == NULL) ? (struct mg_context *)NULL : (conn->ctx);
  2208. }
  2209. void *
  2210. mg_get_user_data(const struct mg_context *ctx)
  2211. {
  2212. return (ctx == NULL) ? NULL : ctx->user_data;
  2213. }
  2214. void
  2215. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  2216. {
  2217. if (conn != NULL) {
  2218. conn->request_info.conn_data = data;
  2219. }
  2220. }
  2221. void *
  2222. mg_get_user_connection_data(const struct mg_connection *conn)
  2223. {
  2224. if (conn != NULL) {
  2225. return conn->request_info.conn_data;
  2226. }
  2227. return NULL;
  2228. }
  2229. size_t
  2230. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  2231. {
  2232. size_t i;
  2233. if (!ctx) {
  2234. return 0;
  2235. }
  2236. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  2237. ssl[i] = ctx->listening_sockets[i].is_ssl;
  2238. ports[i] =
  2239. #if defined(USE_IPV6)
  2240. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2241. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2242. :
  2243. #endif
  2244. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2245. }
  2246. return i;
  2247. }
  2248. int
  2249. mg_get_server_ports(const struct mg_context *ctx,
  2250. int size,
  2251. struct mg_server_ports *ports)
  2252. {
  2253. int i, cnt = 0;
  2254. if (size <= 0) {
  2255. return -1;
  2256. }
  2257. memset(ports, 0, sizeof(*ports) * (size_t)size);
  2258. if (!ctx) {
  2259. return -1;
  2260. }
  2261. if (!ctx->listening_sockets) {
  2262. return -1;
  2263. }
  2264. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  2265. ports[cnt].port =
  2266. #if defined(USE_IPV6)
  2267. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2268. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2269. :
  2270. #endif
  2271. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2272. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  2273. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  2274. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  2275. /* IPv4 */
  2276. ports[cnt].protocol = 1;
  2277. cnt++;
  2278. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  2279. /* IPv6 */
  2280. ports[cnt].protocol = 3;
  2281. cnt++;
  2282. }
  2283. }
  2284. return cnt;
  2285. }
  2286. static void
  2287. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  2288. {
  2289. buf[0] = '\0';
  2290. if (!usa) {
  2291. return;
  2292. }
  2293. if (usa->sa.sa_family == AF_INET) {
  2294. getnameinfo(&usa->sa,
  2295. sizeof(usa->sin),
  2296. buf,
  2297. (unsigned)len,
  2298. NULL,
  2299. 0,
  2300. NI_NUMERICHOST);
  2301. }
  2302. #if defined(USE_IPV6)
  2303. else if (usa->sa.sa_family == AF_INET6) {
  2304. getnameinfo(&usa->sa,
  2305. sizeof(usa->sin6),
  2306. buf,
  2307. (unsigned)len,
  2308. NULL,
  2309. 0,
  2310. NI_NUMERICHOST);
  2311. }
  2312. #endif
  2313. }
  2314. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  2315. * included in all responses other than 100, 101, 5xx. */
  2316. static void
  2317. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  2318. {
  2319. struct tm *tm;
  2320. tm = ((t != NULL) ? gmtime(t) : NULL);
  2321. if (tm != NULL) {
  2322. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  2323. } else {
  2324. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  2325. buf[buf_len - 1] = '\0';
  2326. }
  2327. }
  2328. /* difftime for struct timespec. Return value is in seconds. */
  2329. static double
  2330. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  2331. {
  2332. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  2333. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  2334. }
  2335. /* Print error message to the opened error log stream. */
  2336. void
  2337. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  2338. {
  2339. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  2340. va_list ap;
  2341. struct mg_file fi;
  2342. time_t timestamp;
  2343. va_start(ap, fmt);
  2344. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  2345. va_end(ap);
  2346. buf[sizeof(buf) - 1] = 0;
  2347. if (!conn) {
  2348. puts(buf);
  2349. return;
  2350. }
  2351. /* Do not lock when getting the callback value, here and below.
  2352. * I suppose this is fine, since function cannot disappear in the
  2353. * same way string option can. */
  2354. if ((conn->ctx->callbacks.log_message == NULL)
  2355. || (conn->ctx->callbacks.log_message(conn, buf) == 0)) {
  2356. if (conn->ctx->config[ERROR_LOG_FILE] != NULL) {
  2357. if (mg_fopen(conn,
  2358. conn->ctx->config[ERROR_LOG_FILE],
  2359. MG_FOPEN_MODE_APPEND,
  2360. &fi) == 0) {
  2361. fi.access.fp = NULL;
  2362. }
  2363. } else {
  2364. fi.access.fp = NULL;
  2365. }
  2366. if (fi.access.fp != NULL) {
  2367. flockfile(fi.access.fp);
  2368. timestamp = time(NULL);
  2369. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  2370. fprintf(fi.access.fp,
  2371. "[%010lu] [error] [client %s] ",
  2372. (unsigned long)timestamp,
  2373. src_addr);
  2374. if (conn->request_info.request_method != NULL) {
  2375. fprintf(fi.access.fp,
  2376. "%s %s: ",
  2377. conn->request_info.request_method,
  2378. conn->request_info.request_uri);
  2379. }
  2380. fprintf(fi.access.fp, "%s", buf);
  2381. fputc('\n', fi.access.fp);
  2382. fflush(fi.access.fp);
  2383. funlockfile(fi.access.fp);
  2384. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  2385. * mg_cry here anyway ;-) */
  2386. }
  2387. }
  2388. }
  2389. /* Return fake connection structure. Used for logging, if connection
  2390. * is not applicable at the moment of logging. */
  2391. static struct mg_connection *
  2392. fc(struct mg_context *ctx)
  2393. {
  2394. static struct mg_connection fake_connection;
  2395. fake_connection.ctx = ctx;
  2396. return &fake_connection;
  2397. }
  2398. const char *
  2399. mg_version(void)
  2400. {
  2401. return CIVETWEB_VERSION;
  2402. }
  2403. const struct mg_request_info *
  2404. mg_get_request_info(const struct mg_connection *conn)
  2405. {
  2406. if (!conn) {
  2407. return NULL;
  2408. }
  2409. return &conn->request_info;
  2410. }
  2411. /* Skip the characters until one of the delimiters characters found.
  2412. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  2413. * Advance pointer to buffer to the next word. Return found 0-terminated word.
  2414. * Delimiters can be quoted with quotechar. */
  2415. static char *
  2416. skip_quoted(char **buf,
  2417. const char *delimiters,
  2418. const char *whitespace,
  2419. char quotechar)
  2420. {
  2421. char *p, *begin_word, *end_word, *end_whitespace;
  2422. begin_word = *buf;
  2423. end_word = begin_word + strcspn(begin_word, delimiters);
  2424. /* Check for quotechar */
  2425. if (end_word > begin_word) {
  2426. p = end_word - 1;
  2427. while (*p == quotechar) {
  2428. /* While the delimiter is quoted, look for the next delimiter. */
  2429. /* This happens, e.g., in calls from parse_auth_header,
  2430. * if the user name contains a " character. */
  2431. /* If there is anything beyond end_word, copy it. */
  2432. if (*end_word != '\0') {
  2433. size_t end_off = strcspn(end_word + 1, delimiters);
  2434. memmove(p, end_word, end_off + 1);
  2435. p += end_off; /* p must correspond to end_word - 1 */
  2436. end_word += end_off + 1;
  2437. } else {
  2438. *p = '\0';
  2439. break;
  2440. }
  2441. }
  2442. for (p++; p < end_word; p++) {
  2443. *p = '\0';
  2444. }
  2445. }
  2446. if (*end_word == '\0') {
  2447. *buf = end_word;
  2448. } else {
  2449. #if defined(__GNUC__) || defined(__MINGW32__)
  2450. /* Disable spurious conversion warning for GCC */
  2451. #pragma GCC diagnostic push
  2452. #pragma GCC diagnostic ignored "-Wsign-conversion"
  2453. #endif
  2454. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  2455. #if defined(__GNUC__) || defined(__MINGW32__)
  2456. #pragma GCC diagnostic pop
  2457. #endif
  2458. for (p = end_word; p < end_whitespace; p++) {
  2459. *p = '\0';
  2460. }
  2461. *buf = end_whitespace;
  2462. }
  2463. return begin_word;
  2464. }
  2465. /* Simplified version of skip_quoted without quote char
  2466. * and whitespace == delimiters */
  2467. static char *
  2468. skip(char **buf, const char *delimiters)
  2469. {
  2470. return skip_quoted(buf, delimiters, delimiters, 0);
  2471. }
  2472. /* Return HTTP header value, or NULL if not found. */
  2473. static const char *
  2474. get_header(const struct mg_request_info *ri, const char *name)
  2475. {
  2476. int i;
  2477. if (ri) {
  2478. for (i = 0; i < ri->num_headers; i++) {
  2479. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  2480. return ri->http_headers[i].value;
  2481. }
  2482. }
  2483. }
  2484. return NULL;
  2485. }
  2486. const char *
  2487. mg_get_header(const struct mg_connection *conn, const char *name)
  2488. {
  2489. if (!conn) {
  2490. return NULL;
  2491. }
  2492. return get_header(&conn->request_info, name);
  2493. }
  2494. /* A helper function for traversing a comma separated list of values.
  2495. * It returns a list pointer shifted to the next value, or NULL if the end
  2496. * of the list found.
  2497. * Value is stored in val vector. If value has form "x=y", then eq_val
  2498. * vector is initialized to point to the "y" part, and val vector length
  2499. * is adjusted to point only to "x". */
  2500. static const char *
  2501. next_option(const char *list, struct vec *val, struct vec *eq_val)
  2502. {
  2503. int end;
  2504. reparse:
  2505. if (val == NULL || list == NULL || *list == '\0') {
  2506. /* End of the list */
  2507. list = NULL;
  2508. } else {
  2509. /* Skip over leading LWS */
  2510. while (*list == ' ' || *list == '\t')
  2511. list++;
  2512. val->ptr = list;
  2513. if ((list = strchr(val->ptr, ',')) != NULL) {
  2514. /* Comma found. Store length and shift the list ptr */
  2515. val->len = ((size_t)(list - val->ptr));
  2516. list++;
  2517. } else {
  2518. /* This value is the last one */
  2519. list = val->ptr + strlen(val->ptr);
  2520. val->len = ((size_t)(list - val->ptr));
  2521. }
  2522. /* Adjust length for trailing LWS */
  2523. end = (int)val->len - 1;
  2524. while (end >= 0 && (val->ptr[end] == ' ' || val->ptr[end] == '\t'))
  2525. end--;
  2526. val->len = (size_t)(end + 1);
  2527. if (val->len == 0) {
  2528. /* Ignore any empty entries. */
  2529. goto reparse;
  2530. }
  2531. if (eq_val != NULL) {
  2532. /* Value has form "x=y", adjust pointers and lengths
  2533. * so that val points to "x", and eq_val points to "y". */
  2534. eq_val->len = 0;
  2535. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  2536. if (eq_val->ptr != NULL) {
  2537. eq_val->ptr++; /* Skip over '=' character */
  2538. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  2539. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  2540. }
  2541. }
  2542. }
  2543. return list;
  2544. }
  2545. /* A helper function for checking if a comma separated list of values contains
  2546. * the given option (case insensitvely).
  2547. * 'header' can be NULL, in which case false is returned. */
  2548. static int
  2549. header_has_option(const char *header, const char *option)
  2550. {
  2551. struct vec opt_vec;
  2552. struct vec eq_vec;
  2553. assert(option != NULL);
  2554. assert(option[0] != '\0');
  2555. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  2556. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  2557. return 1;
  2558. }
  2559. return 0;
  2560. }
  2561. /* Perform case-insensitive match of string against pattern */
  2562. static int
  2563. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  2564. {
  2565. const char *or_str;
  2566. size_t i;
  2567. int j, len, res;
  2568. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  2569. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  2570. return (res > 0) ? res : match_prefix(or_str + 1,
  2571. (size_t)((pattern + pattern_len)
  2572. - (or_str + 1)),
  2573. str);
  2574. }
  2575. for (i = 0, j = 0; i < pattern_len; i++, j++) {
  2576. if (pattern[i] == '?' && str[j] != '\0') {
  2577. continue;
  2578. } else if (pattern[i] == '$') {
  2579. return (str[j] == '\0') ? j : -1;
  2580. } else if (pattern[i] == '*') {
  2581. i++;
  2582. if (pattern[i] == '*') {
  2583. i++;
  2584. len = (int)strlen(str + j);
  2585. } else {
  2586. len = (int)strcspn(str + j, "/");
  2587. }
  2588. if (i == pattern_len) {
  2589. return j + len;
  2590. }
  2591. do {
  2592. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  2593. } while (res == -1 && len-- > 0);
  2594. return (res == -1) ? -1 : j + res + len;
  2595. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  2596. return -1;
  2597. }
  2598. }
  2599. return j;
  2600. }
  2601. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  2602. * This function must tolerate situations when connection info is not
  2603. * set up, for example if request parsing failed. */
  2604. static int
  2605. should_keep_alive(const struct mg_connection *conn)
  2606. {
  2607. if (conn != NULL) {
  2608. const char *http_version = conn->request_info.http_version;
  2609. const char *header = mg_get_header(conn, "Connection");
  2610. if (conn->must_close || conn->status_code == 401
  2611. || mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0
  2612. || (header != NULL && !header_has_option(header, "keep-alive"))
  2613. || (header == NULL && http_version
  2614. && 0 != strcmp(http_version, "1.1"))) {
  2615. return 0;
  2616. }
  2617. return 1;
  2618. }
  2619. return 0;
  2620. }
  2621. static int
  2622. should_decode_url(const struct mg_connection *conn)
  2623. {
  2624. if (!conn || !conn->ctx) {
  2625. return 0;
  2626. }
  2627. return (mg_strcasecmp(conn->ctx->config[DECODE_URL], "yes") == 0);
  2628. }
  2629. static const char *
  2630. suggest_connection_header(const struct mg_connection *conn)
  2631. {
  2632. return should_keep_alive(conn) ? "keep-alive" : "close";
  2633. }
  2634. static int
  2635. send_no_cache_header(struct mg_connection *conn)
  2636. {
  2637. /* Send all current and obsolete cache opt-out directives. */
  2638. return mg_printf(conn,
  2639. "Cache-Control: no-cache, no-store, "
  2640. "must-revalidate, private, max-age=0\r\n"
  2641. "Pragma: no-cache\r\n"
  2642. "Expires: 0\r\n");
  2643. }
  2644. static int
  2645. send_static_cache_header(struct mg_connection *conn)
  2646. {
  2647. #if !defined(NO_CACHING)
  2648. /* Read the server config to check how long a file may be cached.
  2649. * The configuration is in seconds. */
  2650. int max_age = atoi(conn->ctx->config[STATIC_FILE_MAX_AGE]);
  2651. if (max_age <= 0) {
  2652. /* 0 means "do not cache". All values <0 are reserved
  2653. * and may be used differently in the future. */
  2654. /* If a file should not be cached, do not only send
  2655. * max-age=0, but also pragmas and Expires headers. */
  2656. return send_no_cache_header(conn);
  2657. }
  2658. /* Use "Cache-Control: max-age" instead of "Expires" header.
  2659. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  2660. /* See also https://www.mnot.net/cache_docs/ */
  2661. /* According to RFC 2616, Section 14.21, caching times should not exceed
  2662. * one year. A year with 365 days corresponds to 31536000 seconds, a leap
  2663. * year to 31622400 seconds. For the moment, we just send whatever has
  2664. * been configured, still the behavior for >1 year should be considered
  2665. * as undefined. */
  2666. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  2667. #else /* NO_CACHING */
  2668. return send_no_cache_header(conn);
  2669. #endif /* !NO_CACHING */
  2670. }
  2671. static void handle_file_based_request(struct mg_connection *conn,
  2672. const char *path,
  2673. struct mg_file *filep);
  2674. const char *
  2675. mg_get_response_code_text(struct mg_connection *conn, int response_code)
  2676. {
  2677. /* See IANA HTTP status code assignment:
  2678. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  2679. */
  2680. switch (response_code) {
  2681. /* RFC2616 Section 10.1 - Informational 1xx */
  2682. case 100:
  2683. return "Continue"; /* RFC2616 Section 10.1.1 */
  2684. case 101:
  2685. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  2686. case 102:
  2687. return "Processing"; /* RFC2518 Section 10.1 */
  2688. /* RFC2616 Section 10.2 - Successful 2xx */
  2689. case 200:
  2690. return "OK"; /* RFC2616 Section 10.2.1 */
  2691. case 201:
  2692. return "Created"; /* RFC2616 Section 10.2.2 */
  2693. case 202:
  2694. return "Accepted"; /* RFC2616 Section 10.2.3 */
  2695. case 203:
  2696. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  2697. case 204:
  2698. return "No Content"; /* RFC2616 Section 10.2.5 */
  2699. case 205:
  2700. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  2701. case 206:
  2702. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  2703. case 207:
  2704. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1 */
  2705. case 208:
  2706. return "Already Reported"; /* RFC5842 Section 7.1 */
  2707. case 226:
  2708. return "IM used"; /* RFC3229 Section 10.4.1 */
  2709. /* RFC2616 Section 10.3 - Redirection 3xx */
  2710. case 300:
  2711. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  2712. case 301:
  2713. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  2714. case 302:
  2715. return "Found"; /* RFC2616 Section 10.3.3 */
  2716. case 303:
  2717. return "See Other"; /* RFC2616 Section 10.3.4 */
  2718. case 304:
  2719. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  2720. case 305:
  2721. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  2722. case 307:
  2723. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  2724. case 308:
  2725. return "Permanent Redirect"; /* RFC7238 Section 3 */
  2726. /* RFC2616 Section 10.4 - Client Error 4xx */
  2727. case 400:
  2728. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  2729. case 401:
  2730. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  2731. case 402:
  2732. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  2733. case 403:
  2734. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  2735. case 404:
  2736. return "Not Found"; /* RFC2616 Section 10.4.5 */
  2737. case 405:
  2738. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  2739. case 406:
  2740. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  2741. case 407:
  2742. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  2743. case 408:
  2744. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  2745. case 409:
  2746. return "Conflict"; /* RFC2616 Section 10.4.10 */
  2747. case 410:
  2748. return "Gone"; /* RFC2616 Section 10.4.11 */
  2749. case 411:
  2750. return "Length Required"; /* RFC2616 Section 10.4.12 */
  2751. case 412:
  2752. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  2753. case 413:
  2754. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  2755. case 414:
  2756. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  2757. case 415:
  2758. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  2759. case 416:
  2760. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17 */
  2761. case 417:
  2762. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  2763. case 421:
  2764. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  2765. case 422:
  2766. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  2767. * Section 11.2 */
  2768. case 423:
  2769. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  2770. case 424:
  2771. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  2772. * Section 11.4 */
  2773. case 426:
  2774. return "Upgrade Required"; /* RFC 2817 Section 4 */
  2775. case 428:
  2776. return "Precondition Required"; /* RFC 6585, Section 3 */
  2777. case 429:
  2778. return "Too Many Requests"; /* RFC 6585, Section 4 */
  2779. case 431:
  2780. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  2781. case 451:
  2782. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  2783. * Section 3 */
  2784. /* RFC2616 Section 10.5 - Server Error 5xx */
  2785. case 500:
  2786. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  2787. case 501:
  2788. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  2789. case 502:
  2790. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  2791. case 503:
  2792. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  2793. case 504:
  2794. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  2795. case 505:
  2796. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  2797. case 506:
  2798. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  2799. case 507:
  2800. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  2801. * Section 11.5 */
  2802. case 508:
  2803. return "Loop Detected"; /* RFC5842 Section 7.1 */
  2804. case 510:
  2805. return "Not Extended"; /* RFC 2774, Section 7 */
  2806. case 511:
  2807. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  2808. /* Other status codes, not shown in the IANA HTTP status code assignment.
  2809. * E.g., "de facto" standards due to common use, ... */
  2810. case 418:
  2811. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  2812. case 419:
  2813. return "Authentication Timeout"; /* common use */
  2814. case 420:
  2815. return "Enhance Your Calm"; /* common use */
  2816. case 440:
  2817. return "Login Timeout"; /* common use */
  2818. case 509:
  2819. return "Bandwidth Limit Exceeded"; /* common use */
  2820. default:
  2821. /* This error code is unknown. This should not happen. */
  2822. if (conn) {
  2823. mg_cry(conn, "Unknown HTTP response code: %u", response_code);
  2824. }
  2825. /* Return at least a category according to RFC 2616 Section 10. */
  2826. if (response_code >= 100 && response_code < 200) {
  2827. /* Unknown informational status code */
  2828. return "Information";
  2829. }
  2830. if (response_code >= 200 && response_code < 300) {
  2831. /* Unknown success code */
  2832. return "Success";
  2833. }
  2834. if (response_code >= 300 && response_code < 400) {
  2835. /* Unknown redirection code */
  2836. return "Redirection";
  2837. }
  2838. if (response_code >= 400 && response_code < 500) {
  2839. /* Unknown request error code */
  2840. return "Client Error";
  2841. }
  2842. if (response_code >= 500 && response_code < 600) {
  2843. /* Unknown server error code */
  2844. return "Server Error";
  2845. }
  2846. /* Response code not even within reasonable range */
  2847. return "";
  2848. }
  2849. }
  2850. static void send_http_error(struct mg_connection *,
  2851. int,
  2852. PRINTF_FORMAT_STRING(const char *fmt),
  2853. ...) PRINTF_ARGS(3, 4);
  2854. static void
  2855. send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  2856. {
  2857. char buf[MG_BUF_LEN];
  2858. va_list ap;
  2859. int len, i, page_handler_found, scope, truncated, has_body;
  2860. char date[64];
  2861. time_t curtime = time(NULL);
  2862. const char *error_handler = NULL;
  2863. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  2864. const char *error_page_file_ext, *tstr;
  2865. const char *status_text = mg_get_response_code_text(conn, status);
  2866. if (conn == NULL) {
  2867. return;
  2868. }
  2869. conn->status_code = status;
  2870. if (conn->in_error_handler || conn->ctx->callbacks.http_error == NULL
  2871. || conn->ctx->callbacks.http_error(conn, status)) {
  2872. if (!conn->in_error_handler) {
  2873. /* Send user defined error pages, if defined */
  2874. error_handler = conn->ctx->config[ERROR_PAGES];
  2875. error_page_file_ext = conn->ctx->config[INDEX_FILES];
  2876. page_handler_found = 0;
  2877. if (error_handler != NULL) {
  2878. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  2879. switch (scope) {
  2880. case 1: /* Handler for specific error, e.g. 404 error */
  2881. mg_snprintf(conn,
  2882. &truncated,
  2883. buf,
  2884. sizeof(buf) - 32,
  2885. "%serror%03u.",
  2886. error_handler,
  2887. status);
  2888. break;
  2889. case 2: /* Handler for error group, e.g., 5xx error handler
  2890. * for all server errors (500-599) */
  2891. mg_snprintf(conn,
  2892. &truncated,
  2893. buf,
  2894. sizeof(buf) - 32,
  2895. "%serror%01uxx.",
  2896. error_handler,
  2897. status / 100);
  2898. break;
  2899. default: /* Handler for all errors */
  2900. mg_snprintf(conn,
  2901. &truncated,
  2902. buf,
  2903. sizeof(buf) - 32,
  2904. "%serror.",
  2905. error_handler);
  2906. break;
  2907. }
  2908. /* String truncation in buf may only occur if error_handler
  2909. * is too long. This string is from the config, not from a
  2910. * client. */
  2911. (void)truncated;
  2912. len = (int)strlen(buf);
  2913. tstr = strchr(error_page_file_ext, '.');
  2914. while (tstr) {
  2915. for (i = 1; i < 32 && tstr[i] != 0 && tstr[i] != ',';
  2916. i++)
  2917. buf[len + i - 1] = tstr[i];
  2918. buf[len + i - 1] = 0;
  2919. if (mg_stat(conn, buf, &error_page_file.stat)) {
  2920. page_handler_found = 1;
  2921. break;
  2922. }
  2923. tstr = strchr(tstr + i, '.');
  2924. }
  2925. }
  2926. }
  2927. if (page_handler_found) {
  2928. conn->in_error_handler = 1;
  2929. handle_file_based_request(conn, buf, &error_page_file);
  2930. conn->in_error_handler = 0;
  2931. return;
  2932. }
  2933. }
  2934. /* No custom error page. Send default error page. */
  2935. gmt_time_string(date, sizeof(date), &curtime);
  2936. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  2937. has_body = (status > 199 && status != 204 && status != 304);
  2938. conn->must_close = 1;
  2939. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  2940. send_no_cache_header(conn);
  2941. if (has_body) {
  2942. mg_printf(conn,
  2943. "%s",
  2944. "Content-Type: text/plain; charset=utf-8\r\n");
  2945. }
  2946. mg_printf(conn,
  2947. "Date: %s\r\n"
  2948. "Connection: close\r\n\r\n",
  2949. date);
  2950. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  2951. if (has_body) {
  2952. mg_printf(conn, "Error %d: %s\n", status, status_text);
  2953. if (fmt != NULL) {
  2954. va_start(ap, fmt);
  2955. mg_vsnprintf(conn, NULL, buf, sizeof(buf), fmt, ap);
  2956. va_end(ap);
  2957. mg_write(conn, buf, strlen(buf));
  2958. DEBUG_TRACE("Error %i - [%s]", status, buf);
  2959. }
  2960. } else {
  2961. /* No body allowed. Close the connection. */
  2962. DEBUG_TRACE("Error %i", status);
  2963. }
  2964. }
  2965. }
  2966. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  2967. /* Create substitutes for POSIX functions in Win32. */
  2968. #if defined(__MINGW32__)
  2969. /* Show no warning in case system functions are not used. */
  2970. #pragma GCC diagnostic push
  2971. #pragma GCC diagnostic ignored "-Wunused-function"
  2972. #endif
  2973. static int
  2974. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  2975. {
  2976. (void)unused;
  2977. *mutex = CreateMutex(NULL, FALSE, NULL);
  2978. return (*mutex == NULL) ? -1 : 0;
  2979. }
  2980. static int
  2981. pthread_mutex_destroy(pthread_mutex_t *mutex)
  2982. {
  2983. return (CloseHandle(*mutex) == 0) ? -1 : 0;
  2984. }
  2985. static int
  2986. pthread_mutex_lock(pthread_mutex_t *mutex)
  2987. {
  2988. return (WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0) ? 0 : -1;
  2989. }
  2990. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  2991. static int
  2992. pthread_mutex_trylock(pthread_mutex_t *mutex)
  2993. {
  2994. switch (WaitForSingleObject(*mutex, 0)) {
  2995. case WAIT_OBJECT_0:
  2996. return 0;
  2997. case WAIT_TIMEOUT:
  2998. return -2; /* EBUSY */
  2999. }
  3000. return -1;
  3001. }
  3002. #endif
  3003. static int
  3004. pthread_mutex_unlock(pthread_mutex_t *mutex)
  3005. {
  3006. return (ReleaseMutex(*mutex) == 0) ? -1 : 0;
  3007. }
  3008. static int
  3009. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  3010. {
  3011. (void)unused;
  3012. InitializeCriticalSection(&cv->threadIdSec);
  3013. cv->waiting_thread = NULL;
  3014. return 0;
  3015. }
  3016. static int
  3017. pthread_cond_timedwait(pthread_cond_t *cv,
  3018. pthread_mutex_t *mutex,
  3019. const struct timespec *abstime)
  3020. {
  3021. struct mg_workerTLS **ptls,
  3022. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3023. int ok;
  3024. struct timespec tsnow;
  3025. int64_t nsnow, nswaitabs, nswaitrel;
  3026. DWORD mswaitrel;
  3027. EnterCriticalSection(&cv->threadIdSec);
  3028. /* Add this thread to cv's waiting list */
  3029. ptls = &cv->waiting_thread;
  3030. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  3031. ;
  3032. tls->next_waiting_thread = NULL;
  3033. *ptls = tls;
  3034. LeaveCriticalSection(&cv->threadIdSec);
  3035. if (abstime) {
  3036. clock_gettime(CLOCK_REALTIME, &tsnow);
  3037. nsnow = (((int64_t)tsnow.tv_sec) * 1000000000) + tsnow.tv_nsec;
  3038. nswaitabs =
  3039. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  3040. nswaitrel = nswaitabs - nsnow;
  3041. if (nswaitrel < 0) {
  3042. nswaitrel = 0;
  3043. }
  3044. mswaitrel = (DWORD)(nswaitrel / 1000000);
  3045. } else {
  3046. mswaitrel = INFINITE;
  3047. }
  3048. pthread_mutex_unlock(mutex);
  3049. ok = (WAIT_OBJECT_0
  3050. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  3051. if (!ok) {
  3052. ok = 1;
  3053. EnterCriticalSection(&cv->threadIdSec);
  3054. ptls = &cv->waiting_thread;
  3055. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  3056. if (*ptls == tls) {
  3057. *ptls = tls->next_waiting_thread;
  3058. ok = 0;
  3059. break;
  3060. }
  3061. }
  3062. LeaveCriticalSection(&cv->threadIdSec);
  3063. if (ok) {
  3064. WaitForSingleObject(tls->pthread_cond_helper_mutex, INFINITE);
  3065. }
  3066. }
  3067. /* This thread has been removed from cv's waiting list */
  3068. pthread_mutex_lock(mutex);
  3069. return ok ? 0 : -1;
  3070. }
  3071. static int
  3072. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  3073. {
  3074. return pthread_cond_timedwait(cv, mutex, NULL);
  3075. }
  3076. static int
  3077. pthread_cond_signal(pthread_cond_t *cv)
  3078. {
  3079. HANDLE wkup = NULL;
  3080. BOOL ok = FALSE;
  3081. EnterCriticalSection(&cv->threadIdSec);
  3082. if (cv->waiting_thread) {
  3083. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  3084. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  3085. ok = SetEvent(wkup);
  3086. assert(ok);
  3087. }
  3088. LeaveCriticalSection(&cv->threadIdSec);
  3089. return ok ? 0 : 1;
  3090. }
  3091. static int
  3092. pthread_cond_broadcast(pthread_cond_t *cv)
  3093. {
  3094. EnterCriticalSection(&cv->threadIdSec);
  3095. while (cv->waiting_thread) {
  3096. pthread_cond_signal(cv);
  3097. }
  3098. LeaveCriticalSection(&cv->threadIdSec);
  3099. return 0;
  3100. }
  3101. static int
  3102. pthread_cond_destroy(pthread_cond_t *cv)
  3103. {
  3104. EnterCriticalSection(&cv->threadIdSec);
  3105. assert(cv->waiting_thread == NULL);
  3106. LeaveCriticalSection(&cv->threadIdSec);
  3107. DeleteCriticalSection(&cv->threadIdSec);
  3108. return 0;
  3109. }
  3110. #ifdef ALTERNATIVE_QUEUE
  3111. static void *
  3112. event_create(void)
  3113. {
  3114. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  3115. }
  3116. static int
  3117. event_wait(void *eventhdl)
  3118. {
  3119. int res = WaitForSingleObject((HANDLE)eventhdl, INFINITE);
  3120. return (res == WAIT_OBJECT_0);
  3121. }
  3122. static int
  3123. event_signal(void *eventhdl)
  3124. {
  3125. return (int)SetEvent((HANDLE)eventhdl);
  3126. }
  3127. static void
  3128. event_destroy(void *eventhdl)
  3129. {
  3130. CloseHandle((HANDLE)eventhdl);
  3131. }
  3132. #endif
  3133. #if defined(__MINGW32__)
  3134. /* Enable unused function warning again */
  3135. #pragma GCC diagnostic pop
  3136. #endif
  3137. /* For Windows, change all slashes to backslashes in path names. */
  3138. static void
  3139. change_slashes_to_backslashes(char *path)
  3140. {
  3141. int i;
  3142. for (i = 0; path[i] != '\0'; i++) {
  3143. if (path[i] == '/') {
  3144. path[i] = '\\';
  3145. }
  3146. /* remove double backslash (check i > 0 to preserve UNC paths,
  3147. * like \\server\file.txt) */
  3148. if ((path[i] == '\\') && (i > 0)) {
  3149. while (path[i + 1] == '\\' || path[i + 1] == '/') {
  3150. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  3151. }
  3152. }
  3153. }
  3154. }
  3155. static int
  3156. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  3157. {
  3158. int diff;
  3159. do {
  3160. diff = tolower(*s1) - tolower(*s2);
  3161. s1++;
  3162. s2++;
  3163. } while (diff == 0 && s1[-1] != '\0');
  3164. return diff;
  3165. }
  3166. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  3167. * wbuf and wbuf_len is a target buffer and its length. */
  3168. static void
  3169. path_to_unicode(const struct mg_connection *conn,
  3170. const char *path,
  3171. wchar_t *wbuf,
  3172. size_t wbuf_len)
  3173. {
  3174. char buf[PATH_MAX], buf2[PATH_MAX];
  3175. wchar_t wbuf2[MAX_PATH + 1];
  3176. DWORD long_len, err;
  3177. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  3178. mg_strlcpy(buf, path, sizeof(buf));
  3179. change_slashes_to_backslashes(buf);
  3180. /* Convert to Unicode and back. If doubly-converted string does not
  3181. * match the original, something is fishy, reject. */
  3182. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  3183. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  3184. WideCharToMultiByte(
  3185. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  3186. if (strcmp(buf, buf2) != 0) {
  3187. wbuf[0] = L'\0';
  3188. }
  3189. /* Windows file systems are not case sensitive, but you can still use
  3190. * uppercase and lowercase letters (on all modern file systems).
  3191. * The server can check if the URI uses the same upper/lowercase
  3192. * letters an the file system, effectively making Windows servers
  3193. * case sensitive (like Linux servers are). It is still not possible
  3194. * to use two files with the same name in different cases on Windows
  3195. * (like /a and /A) - this would be possible in Linux.
  3196. * As a default, Windows is not case sensitive, but the case sensitive
  3197. * file name check can be activated by an additional configuration. */
  3198. if (conn) {
  3199. if (conn->ctx->config[CASE_SENSITIVE_FILES]
  3200. && !mg_strcasecmp(conn->ctx->config[CASE_SENSITIVE_FILES], "yes")) {
  3201. /* Use case sensitive compare function */
  3202. fcompare = wcscmp;
  3203. }
  3204. }
  3205. (void)conn; /* conn is currently unused */
  3206. #if !defined(_WIN32_WCE)
  3207. /* Only accept a full file path, not a Windows short (8.3) path. */
  3208. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  3209. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  3210. if (long_len == 0) {
  3211. err = GetLastError();
  3212. if (err == ERROR_FILE_NOT_FOUND) {
  3213. /* File does not exist. This is not always a problem here. */
  3214. return;
  3215. }
  3216. }
  3217. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  3218. /* Short name is used. */
  3219. wbuf[0] = L'\0';
  3220. }
  3221. #else
  3222. (void)long_len;
  3223. (void)wbuf2;
  3224. (void)err;
  3225. if (strchr(path, '~')) {
  3226. wbuf[0] = L'\0';
  3227. }
  3228. #endif
  3229. }
  3230. /* Windows happily opens files with some garbage at the end of file name.
  3231. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  3232. * "a.cgi", despite one would expect an error back.
  3233. * This function returns non-0 if path ends with some garbage. */
  3234. static int
  3235. path_cannot_disclose_cgi(const char *path)
  3236. {
  3237. static const char *allowed_last_characters = "_-";
  3238. int last = path[strlen(path) - 1];
  3239. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  3240. }
  3241. static int
  3242. mg_stat(const struct mg_connection *conn,
  3243. const char *path,
  3244. struct mg_file_stat *filep)
  3245. {
  3246. wchar_t wbuf[PATH_MAX];
  3247. WIN32_FILE_ATTRIBUTE_DATA info;
  3248. time_t creation_time;
  3249. if (!filep) {
  3250. return 0;
  3251. }
  3252. memset(filep, 0, sizeof(*filep));
  3253. if (conn && is_file_in_memory(conn, path)) {
  3254. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  3255. * memset */
  3256. /* Quick fix (for 1.9.x): */
  3257. /* mg_stat must fill all fields, also for files in memory */
  3258. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  3259. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  3260. filep->size = tmp_file.stat.size;
  3261. filep->location = 2;
  3262. /* TODO: for 1.10: restructure how files in memory are handled */
  3263. filep->last_modified = time(NULL); /* xxxxxxxx */
  3264. /* last_modified = now ... assumes the file may change during runtime,
  3265. * so every mg_fopen call may return different data */
  3266. /* last_modified = conn->ctx.start_time;
  3267. * May be used it the data does not change during runtime. This allows
  3268. * browser caching. Since we do not know, we have to assume the file
  3269. * in memory may change. */
  3270. return 1;
  3271. }
  3272. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3273. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  3274. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  3275. filep->last_modified =
  3276. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  3277. info.ftLastWriteTime.dwHighDateTime);
  3278. /* On Windows, the file creation time can be higher than the
  3279. * modification time, e.g. when a file is copied.
  3280. * Since the Last-Modified timestamp is used for caching
  3281. * it should be based on the most recent timestamp. */
  3282. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  3283. info.ftCreationTime.dwHighDateTime);
  3284. if (creation_time > filep->last_modified) {
  3285. filep->last_modified = creation_time;
  3286. }
  3287. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  3288. /* If file name is fishy, reset the file structure and return
  3289. * error.
  3290. * Note it is important to reset, not just return the error, cause
  3291. * functions like is_file_opened() check the struct. */
  3292. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  3293. memset(filep, 0, sizeof(*filep));
  3294. return 0;
  3295. }
  3296. return 1;
  3297. }
  3298. return 0;
  3299. }
  3300. static int
  3301. mg_remove(const struct mg_connection *conn, const char *path)
  3302. {
  3303. wchar_t wbuf[PATH_MAX];
  3304. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3305. return DeleteFileW(wbuf) ? 0 : -1;
  3306. }
  3307. static int
  3308. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  3309. {
  3310. wchar_t wbuf[PATH_MAX];
  3311. (void)mode;
  3312. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3313. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  3314. }
  3315. /* Create substitutes for POSIX functions in Win32. */
  3316. #if defined(__MINGW32__)
  3317. /* Show no warning in case system functions are not used. */
  3318. #pragma GCC diagnostic push
  3319. #pragma GCC diagnostic ignored "-Wunused-function"
  3320. #endif
  3321. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  3322. static DIR *
  3323. mg_opendir(const struct mg_connection *conn, const char *name)
  3324. {
  3325. DIR *dir = NULL;
  3326. wchar_t wpath[PATH_MAX];
  3327. DWORD attrs;
  3328. if (name == NULL) {
  3329. SetLastError(ERROR_BAD_ARGUMENTS);
  3330. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  3331. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  3332. } else {
  3333. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  3334. attrs = GetFileAttributesW(wpath);
  3335. if (attrs != 0xFFFFFFFF && ((attrs & FILE_ATTRIBUTE_DIRECTORY)
  3336. == FILE_ATTRIBUTE_DIRECTORY)) {
  3337. (void)wcscat(wpath, L"\\*");
  3338. dir->handle = FindFirstFileW(wpath, &dir->info);
  3339. dir->result.d_name[0] = '\0';
  3340. } else {
  3341. mg_free(dir);
  3342. dir = NULL;
  3343. }
  3344. }
  3345. return dir;
  3346. }
  3347. static int
  3348. mg_closedir(DIR *dir)
  3349. {
  3350. int result = 0;
  3351. if (dir != NULL) {
  3352. if (dir->handle != INVALID_HANDLE_VALUE)
  3353. result = FindClose(dir->handle) ? 0 : -1;
  3354. mg_free(dir);
  3355. } else {
  3356. result = -1;
  3357. SetLastError(ERROR_BAD_ARGUMENTS);
  3358. }
  3359. return result;
  3360. }
  3361. static struct dirent *
  3362. mg_readdir(DIR *dir)
  3363. {
  3364. struct dirent *result = 0;
  3365. if (dir) {
  3366. if (dir->handle != INVALID_HANDLE_VALUE) {
  3367. result = &dir->result;
  3368. (void)WideCharToMultiByte(CP_UTF8,
  3369. 0,
  3370. dir->info.cFileName,
  3371. -1,
  3372. result->d_name,
  3373. sizeof(result->d_name),
  3374. NULL,
  3375. NULL);
  3376. if (!FindNextFileW(dir->handle, &dir->info)) {
  3377. (void)FindClose(dir->handle);
  3378. dir->handle = INVALID_HANDLE_VALUE;
  3379. }
  3380. } else {
  3381. SetLastError(ERROR_FILE_NOT_FOUND);
  3382. }
  3383. } else {
  3384. SetLastError(ERROR_BAD_ARGUMENTS);
  3385. }
  3386. return result;
  3387. }
  3388. #ifndef HAVE_POLL
  3389. static int
  3390. poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  3391. {
  3392. struct timeval tv;
  3393. fd_set set;
  3394. unsigned int i;
  3395. int result;
  3396. SOCKET maxfd = 0;
  3397. memset(&tv, 0, sizeof(tv));
  3398. tv.tv_sec = milliseconds / 1000;
  3399. tv.tv_usec = (milliseconds % 1000) * 1000;
  3400. FD_ZERO(&set);
  3401. for (i = 0; i < n; i++) {
  3402. FD_SET((SOCKET)pfd[i].fd, &set);
  3403. pfd[i].revents = 0;
  3404. if (pfd[i].fd > maxfd) {
  3405. maxfd = pfd[i].fd;
  3406. }
  3407. }
  3408. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  3409. for (i = 0; i < n; i++) {
  3410. if (FD_ISSET(pfd[i].fd, &set)) {
  3411. pfd[i].revents = POLLIN;
  3412. }
  3413. }
  3414. }
  3415. /* We should subtract the time used in select from remaining
  3416. * "milliseconds", in particular if called from mg_poll with a
  3417. * timeout quantum.
  3418. * Unfortunately, the remaining time is not stored in "tv" in all
  3419. * implementations, so the result in "tv" must be considered undefined.
  3420. * See http://man7.org/linux/man-pages/man2/select.2.html */
  3421. return result;
  3422. }
  3423. #endif /* HAVE_POLL */
  3424. #if defined(__MINGW32__)
  3425. /* Enable unused function warning again */
  3426. #pragma GCC diagnostic pop
  3427. #endif
  3428. static void
  3429. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  3430. {
  3431. (void)conn; /* Unused. */
  3432. #if defined(_WIN32_WCE)
  3433. (void)sock;
  3434. #else
  3435. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  3436. #endif
  3437. }
  3438. int
  3439. mg_start_thread(mg_thread_func_t f, void *p)
  3440. {
  3441. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3442. /* Compile-time option to control stack size, e.g. -DUSE_STACK_SIZE=16384
  3443. */
  3444. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  3445. == ((uintptr_t)(-1L)))
  3446. ? -1
  3447. : 0);
  3448. #else
  3449. return (
  3450. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  3451. ? -1
  3452. : 0);
  3453. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3454. }
  3455. /* Start a thread storing the thread context. */
  3456. static int
  3457. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  3458. void *p,
  3459. pthread_t *threadidptr)
  3460. {
  3461. uintptr_t uip;
  3462. HANDLE threadhandle;
  3463. int result = -1;
  3464. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  3465. threadhandle = (HANDLE)uip;
  3466. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  3467. *threadidptr = threadhandle;
  3468. result = 0;
  3469. }
  3470. return result;
  3471. }
  3472. /* Wait for a thread to finish. */
  3473. static int
  3474. mg_join_thread(pthread_t threadid)
  3475. {
  3476. int result;
  3477. DWORD dwevent;
  3478. result = -1;
  3479. dwevent = WaitForSingleObject(threadid, INFINITE);
  3480. if (dwevent == WAIT_FAILED) {
  3481. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  3482. } else {
  3483. if (dwevent == WAIT_OBJECT_0) {
  3484. CloseHandle(threadid);
  3485. result = 0;
  3486. }
  3487. }
  3488. return result;
  3489. }
  3490. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  3491. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  3492. /* Create substitutes for POSIX functions in Win32. */
  3493. #if defined(__MINGW32__)
  3494. /* Show no warning in case system functions are not used. */
  3495. #pragma GCC diagnostic push
  3496. #pragma GCC diagnostic ignored "-Wunused-function"
  3497. #endif
  3498. static HANDLE
  3499. dlopen(const char *dll_name, int flags)
  3500. {
  3501. wchar_t wbuf[PATH_MAX];
  3502. (void)flags;
  3503. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  3504. return LoadLibraryW(wbuf);
  3505. }
  3506. static int
  3507. dlclose(void *handle)
  3508. {
  3509. int result;
  3510. if (FreeLibrary((HMODULE)handle) != 0) {
  3511. result = 0;
  3512. } else {
  3513. result = -1;
  3514. }
  3515. return result;
  3516. }
  3517. #if defined(__MINGW32__)
  3518. /* Enable unused function warning again */
  3519. #pragma GCC diagnostic pop
  3520. #endif
  3521. #endif
  3522. #if !defined(NO_CGI)
  3523. #define SIGKILL (0)
  3524. static int
  3525. kill(pid_t pid, int sig_num)
  3526. {
  3527. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  3528. (void)CloseHandle((HANDLE)pid);
  3529. return 0;
  3530. }
  3531. static void
  3532. trim_trailing_whitespaces(char *s)
  3533. {
  3534. char *e = s + strlen(s) - 1;
  3535. while (e > s && isspace(*(unsigned char *)e)) {
  3536. *e-- = '\0';
  3537. }
  3538. }
  3539. static pid_t
  3540. spawn_process(struct mg_connection *conn,
  3541. const char *prog,
  3542. char *envblk,
  3543. char *envp[],
  3544. int fdin[2],
  3545. int fdout[2],
  3546. int fderr[2],
  3547. const char *dir)
  3548. {
  3549. HANDLE me;
  3550. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  3551. cmdline[PATH_MAX], buf[PATH_MAX];
  3552. int truncated;
  3553. struct mg_file file = STRUCT_FILE_INITIALIZER;
  3554. STARTUPINFOA si;
  3555. PROCESS_INFORMATION pi = {0};
  3556. (void)envp;
  3557. memset(&si, 0, sizeof(si));
  3558. si.cb = sizeof(si);
  3559. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  3560. si.wShowWindow = SW_HIDE;
  3561. me = GetCurrentProcess();
  3562. DuplicateHandle(me,
  3563. (HANDLE)_get_osfhandle(fdin[0]),
  3564. me,
  3565. &si.hStdInput,
  3566. 0,
  3567. TRUE,
  3568. DUPLICATE_SAME_ACCESS);
  3569. DuplicateHandle(me,
  3570. (HANDLE)_get_osfhandle(fdout[1]),
  3571. me,
  3572. &si.hStdOutput,
  3573. 0,
  3574. TRUE,
  3575. DUPLICATE_SAME_ACCESS);
  3576. DuplicateHandle(me,
  3577. (HANDLE)_get_osfhandle(fderr[1]),
  3578. me,
  3579. &si.hStdError,
  3580. 0,
  3581. TRUE,
  3582. DUPLICATE_SAME_ACCESS);
  3583. /* Mark handles that should not be inherited. See
  3584. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  3585. */
  3586. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  3587. HANDLE_FLAG_INHERIT,
  3588. 0);
  3589. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  3590. HANDLE_FLAG_INHERIT,
  3591. 0);
  3592. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  3593. HANDLE_FLAG_INHERIT,
  3594. 0);
  3595. /* If CGI file is a script, try to read the interpreter line */
  3596. interp = conn->ctx->config[CGI_INTERPRETER];
  3597. if (interp == NULL) {
  3598. buf[0] = buf[1] = '\0';
  3599. /* Read the first line of the script into the buffer */
  3600. mg_snprintf(
  3601. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  3602. if (truncated) {
  3603. pi.hProcess = (pid_t)-1;
  3604. goto spawn_cleanup;
  3605. }
  3606. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  3607. p = (char *)file.access.membuf;
  3608. mg_fgets(buf, sizeof(buf), &file, &p);
  3609. (void)mg_fclose(&file.access); /* ignore error on read only file */
  3610. buf[sizeof(buf) - 1] = '\0';
  3611. }
  3612. if (buf[0] == '#' && buf[1] == '!') {
  3613. trim_trailing_whitespaces(buf + 2);
  3614. } else {
  3615. buf[2] = '\0';
  3616. }
  3617. interp = buf + 2;
  3618. }
  3619. if (interp[0] != '\0') {
  3620. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  3621. interp = full_interp;
  3622. }
  3623. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  3624. if (interp[0] != '\0') {
  3625. mg_snprintf(conn,
  3626. &truncated,
  3627. cmdline,
  3628. sizeof(cmdline),
  3629. "\"%s\" \"%s\\%s\"",
  3630. interp,
  3631. full_dir,
  3632. prog);
  3633. } else {
  3634. mg_snprintf(conn,
  3635. &truncated,
  3636. cmdline,
  3637. sizeof(cmdline),
  3638. "\"%s\\%s\"",
  3639. full_dir,
  3640. prog);
  3641. }
  3642. if (truncated) {
  3643. pi.hProcess = (pid_t)-1;
  3644. goto spawn_cleanup;
  3645. }
  3646. DEBUG_TRACE("Running [%s]", cmdline);
  3647. if (CreateProcessA(NULL,
  3648. cmdline,
  3649. NULL,
  3650. NULL,
  3651. TRUE,
  3652. CREATE_NEW_PROCESS_GROUP,
  3653. envblk,
  3654. NULL,
  3655. &si,
  3656. &pi) == 0) {
  3657. mg_cry(
  3658. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  3659. pi.hProcess = (pid_t)-1;
  3660. /* goto spawn_cleanup; */
  3661. }
  3662. spawn_cleanup:
  3663. (void)CloseHandle(si.hStdOutput);
  3664. (void)CloseHandle(si.hStdError);
  3665. (void)CloseHandle(si.hStdInput);
  3666. if (pi.hThread != NULL) {
  3667. (void)CloseHandle(pi.hThread);
  3668. }
  3669. return (pid_t)pi.hProcess;
  3670. }
  3671. #endif /* !NO_CGI */
  3672. static int
  3673. set_blocking_mode(SOCKET sock, int blocking)
  3674. {
  3675. unsigned long non_blocking = !blocking;
  3676. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  3677. }
  3678. #else
  3679. static int
  3680. mg_stat(const struct mg_connection *conn,
  3681. const char *path,
  3682. struct mg_file_stat *filep)
  3683. {
  3684. struct stat st;
  3685. if (!filep) {
  3686. return 0;
  3687. }
  3688. memset(filep, 0, sizeof(*filep));
  3689. if (conn && is_file_in_memory(conn, path)) {
  3690. /* Quick fix (for 1.9.x): */
  3691. /* mg_stat must fill all fields, also for files in memory */
  3692. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  3693. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  3694. filep->size = tmp_file.stat.size;
  3695. filep->last_modified = time(NULL);
  3696. filep->location = 2;
  3697. /* TODO: for 1.10: restructure how files in memory are handled */
  3698. return 1;
  3699. }
  3700. if (0 == stat(path, &st)) {
  3701. filep->size = (uint64_t)(st.st_size);
  3702. filep->last_modified = st.st_mtime;
  3703. filep->is_directory = S_ISDIR(st.st_mode);
  3704. return 1;
  3705. }
  3706. return 0;
  3707. }
  3708. static void
  3709. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  3710. {
  3711. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  3712. if (conn) {
  3713. mg_cry(conn,
  3714. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  3715. __func__,
  3716. strerror(ERRNO));
  3717. }
  3718. }
  3719. }
  3720. int
  3721. mg_start_thread(mg_thread_func_t func, void *param)
  3722. {
  3723. pthread_t thread_id;
  3724. pthread_attr_t attr;
  3725. int result;
  3726. (void)pthread_attr_init(&attr);
  3727. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  3728. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3729. /* Compile-time option to control stack size,
  3730. * e.g. -DUSE_STACK_SIZE=16384 */
  3731. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3732. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3733. result = pthread_create(&thread_id, &attr, func, param);
  3734. pthread_attr_destroy(&attr);
  3735. return result;
  3736. }
  3737. /* Start a thread storing the thread context. */
  3738. static int
  3739. mg_start_thread_with_id(mg_thread_func_t func,
  3740. void *param,
  3741. pthread_t *threadidptr)
  3742. {
  3743. pthread_t thread_id;
  3744. pthread_attr_t attr;
  3745. int result;
  3746. (void)pthread_attr_init(&attr);
  3747. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3748. /* Compile-time option to control stack size,
  3749. * e.g. -DUSE_STACK_SIZE=16384 */
  3750. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3751. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  3752. result = pthread_create(&thread_id, &attr, func, param);
  3753. pthread_attr_destroy(&attr);
  3754. if ((result == 0) && (threadidptr != NULL)) {
  3755. *threadidptr = thread_id;
  3756. }
  3757. return result;
  3758. }
  3759. /* Wait for a thread to finish. */
  3760. static int
  3761. mg_join_thread(pthread_t threadid)
  3762. {
  3763. int result;
  3764. result = pthread_join(threadid, NULL);
  3765. return result;
  3766. }
  3767. #ifndef NO_CGI
  3768. static pid_t
  3769. spawn_process(struct mg_connection *conn,
  3770. const char *prog,
  3771. char *envblk,
  3772. char *envp[],
  3773. int fdin[2],
  3774. int fdout[2],
  3775. int fderr[2],
  3776. const char *dir)
  3777. {
  3778. pid_t pid;
  3779. const char *interp;
  3780. (void)envblk;
  3781. if (conn == NULL) {
  3782. return 0;
  3783. }
  3784. if ((pid = fork()) == -1) {
  3785. /* Parent */
  3786. send_http_error(conn,
  3787. 500,
  3788. "Error: Creating CGI process\nfork(): %s",
  3789. strerror(ERRNO));
  3790. } else if (pid == 0) {
  3791. /* Child */
  3792. if (chdir(dir) != 0) {
  3793. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  3794. } else if (dup2(fdin[0], 0) == -1) {
  3795. mg_cry(conn,
  3796. "%s: dup2(%d, 0): %s",
  3797. __func__,
  3798. fdin[0],
  3799. strerror(ERRNO));
  3800. } else if (dup2(fdout[1], 1) == -1) {
  3801. mg_cry(conn,
  3802. "%s: dup2(%d, 1): %s",
  3803. __func__,
  3804. fdout[1],
  3805. strerror(ERRNO));
  3806. } else if (dup2(fderr[1], 2) == -1) {
  3807. mg_cry(conn,
  3808. "%s: dup2(%d, 2): %s",
  3809. __func__,
  3810. fderr[1],
  3811. strerror(ERRNO));
  3812. } else {
  3813. /* Keep stderr and stdout in two different pipes.
  3814. * Stdout will be sent back to the client,
  3815. * stderr should go into a server error log. */
  3816. (void)close(fdin[0]);
  3817. (void)close(fdout[1]);
  3818. (void)close(fderr[1]);
  3819. /* Close write end fdin and read end fdout and fderr */
  3820. (void)close(fdin[1]);
  3821. (void)close(fdout[0]);
  3822. (void)close(fderr[0]);
  3823. /* After exec, all signal handlers are restored to their default
  3824. * values, with one exception of SIGCHLD. According to
  3825. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler will
  3826. * leave unchanged after exec if it was set to be ignored. Restore
  3827. * it to default action. */
  3828. signal(SIGCHLD, SIG_DFL);
  3829. interp = conn->ctx->config[CGI_INTERPRETER];
  3830. if (interp == NULL) {
  3831. (void)execle(prog, prog, NULL, envp);
  3832. mg_cry(conn,
  3833. "%s: execle(%s): %s",
  3834. __func__,
  3835. prog,
  3836. strerror(ERRNO));
  3837. } else {
  3838. (void)execle(interp, interp, prog, NULL, envp);
  3839. mg_cry(conn,
  3840. "%s: execle(%s %s): %s",
  3841. __func__,
  3842. interp,
  3843. prog,
  3844. strerror(ERRNO));
  3845. }
  3846. }
  3847. exit(EXIT_FAILURE);
  3848. }
  3849. return pid;
  3850. }
  3851. #endif /* !NO_CGI */
  3852. static int
  3853. set_blocking_mode(SOCKET sock, int blocking)
  3854. {
  3855. int flags;
  3856. flags = fcntl(sock, F_GETFL, 0);
  3857. if (blocking) {
  3858. (void)fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  3859. } else {
  3860. (void)fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK)));
  3861. }
  3862. return 0;
  3863. }
  3864. #endif /* _WIN32 */
  3865. /* End of initial operating system specific define block. */
  3866. /* Get a random number (independent of C rand function) */
  3867. static uint64_t
  3868. get_random(void)
  3869. {
  3870. static uint64_t lfsr = 0; /* Linear feedback shift register */
  3871. static uint64_t lcg = 0; /* Linear congruential generator */
  3872. struct timespec now;
  3873. memset(&now, 0, sizeof(now));
  3874. clock_gettime(CLOCK_MONOTONIC, &now);
  3875. if (lfsr == 0) {
  3876. /* lfsr will be only 0 if has not been initialized,
  3877. * so this code is called only once. */
  3878. lfsr = (((uint64_t)now.tv_sec) << 21) ^ ((uint64_t)now.tv_nsec)
  3879. ^ ((uint64_t)(ptrdiff_t)&now) ^ (((uint64_t)time(NULL)) << 33);
  3880. lcg = (((uint64_t)now.tv_sec) << 25) + (uint64_t)now.tv_nsec
  3881. + (uint64_t)(ptrdiff_t)&now;
  3882. } else {
  3883. /* Get the next step of both random number generators. */
  3884. lfsr = (lfsr >> 1)
  3885. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  3886. << 63);
  3887. lcg = lcg * 6364136223846793005 + 1442695040888963407;
  3888. }
  3889. /* Combining two pseudo-random number generators and a high resolution part
  3890. * of the current server time will make it hard (impossible?) to guess the
  3891. * next number. */
  3892. return (lfsr ^ lcg ^ (uint64_t)now.tv_nsec);
  3893. }
  3894. static int
  3895. mg_poll(struct pollfd *pfd,
  3896. unsigned int n,
  3897. int milliseconds,
  3898. volatile int *stop_server)
  3899. {
  3900. int ms_now, result;
  3901. /* Call poll, but only for a maximum time of a few seconds.
  3902. * This will allow to stop the server after some seconds, instead
  3903. * of having to wait for a long socket timeout. */
  3904. ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  3905. do {
  3906. if (*stop_server) {
  3907. /* Shut down signal */
  3908. return -2;
  3909. }
  3910. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  3911. ms_now = milliseconds;
  3912. }
  3913. result = poll(pfd, n, ms_now);
  3914. if (result != 0) {
  3915. /* Poll returned either success (1) or error (-1).
  3916. * Forward both to the caller. */
  3917. return result;
  3918. }
  3919. /* Poll returned timeout (0). */
  3920. if (milliseconds > 0) {
  3921. milliseconds -= ms_now;
  3922. }
  3923. } while (milliseconds != 0);
  3924. return result;
  3925. }
  3926. /* Write data to the IO channel - opened file descriptor, socket or SSL
  3927. * descriptor. Return number of bytes written. */
  3928. static int
  3929. push(struct mg_context *ctx,
  3930. FILE *fp,
  3931. SOCKET sock,
  3932. SSL *ssl,
  3933. const char *buf,
  3934. int len,
  3935. double timeout)
  3936. {
  3937. struct timespec start, now;
  3938. int n, err;
  3939. #ifdef _WIN32
  3940. typedef int len_t;
  3941. #else
  3942. typedef size_t len_t;
  3943. #endif
  3944. if (timeout > 0) {
  3945. memset(&start, 0, sizeof(start));
  3946. memset(&now, 0, sizeof(now));
  3947. clock_gettime(CLOCK_MONOTONIC, &start);
  3948. }
  3949. if (ctx == NULL) {
  3950. return -1;
  3951. }
  3952. #ifdef NO_SSL
  3953. if (ssl) {
  3954. return -1;
  3955. }
  3956. #endif
  3957. do {
  3958. #ifndef NO_SSL
  3959. if (ssl != NULL) {
  3960. n = SSL_write(ssl, buf, len);
  3961. if (n <= 0) {
  3962. err = SSL_get_error(ssl, n);
  3963. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  3964. err = ERRNO;
  3965. } else if ((err == SSL_ERROR_WANT_READ)
  3966. || (err == SSL_ERROR_WANT_WRITE)) {
  3967. n = 0;
  3968. } else {
  3969. DEBUG_TRACE("SSL_write() failed, error %d", err);
  3970. return -1;
  3971. }
  3972. } else {
  3973. err = 0;
  3974. }
  3975. } else
  3976. #endif
  3977. if (fp != NULL) {
  3978. n = (int)fwrite(buf, 1, (size_t)len, fp);
  3979. if (ferror(fp)) {
  3980. n = -1;
  3981. err = ERRNO;
  3982. } else {
  3983. err = 0;
  3984. }
  3985. } else {
  3986. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  3987. err = (n < 0) ? ERRNO : 0;
  3988. #ifdef _WIN32
  3989. if (err == WSAEWOULDBLOCK) {
  3990. err = 0;
  3991. n = 0;
  3992. }
  3993. #else
  3994. if (err == EWOULDBLOCK) {
  3995. err = 0;
  3996. n = 0;
  3997. }
  3998. #endif
  3999. if (n < 0) {
  4000. /* shutdown of the socket at client side */
  4001. return -1;
  4002. }
  4003. }
  4004. if (ctx->stop_flag) {
  4005. return -1;
  4006. }
  4007. if ((n > 0) || (n == 0 && len == 0)) {
  4008. /* some data has been read, or no data was requested */
  4009. return n;
  4010. }
  4011. if (n < 0) {
  4012. /* socket error - check errno */
  4013. DEBUG_TRACE("send() failed, error %d", err);
  4014. /* TODO (mid): error handling depending on the error code.
  4015. * These codes are different between Windows and Linux.
  4016. * Currently there is no problem with failing send calls,
  4017. * if there is a reproducible situation, it should be
  4018. * investigated in detail.
  4019. */
  4020. return -1;
  4021. }
  4022. /* Only in case n=0 (timeout), repeat calling the write function */
  4023. if (timeout > 0) {
  4024. clock_gettime(CLOCK_MONOTONIC, &now);
  4025. }
  4026. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  4027. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  4028. used */
  4029. return -1;
  4030. }
  4031. static int64_t
  4032. push_all(struct mg_context *ctx,
  4033. FILE *fp,
  4034. SOCKET sock,
  4035. SSL *ssl,
  4036. const char *buf,
  4037. int64_t len)
  4038. {
  4039. double timeout = -1.0;
  4040. int64_t n, nwritten = 0;
  4041. if (ctx == NULL) {
  4042. return -1;
  4043. }
  4044. if (ctx->config[REQUEST_TIMEOUT]) {
  4045. timeout = atoi(ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  4046. }
  4047. while (len > 0 && ctx->stop_flag == 0) {
  4048. n = push(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  4049. if (n < 0) {
  4050. if (nwritten == 0) {
  4051. nwritten = n; /* Propagate the error */
  4052. }
  4053. break;
  4054. } else if (n == 0) {
  4055. break; /* No more data to write */
  4056. } else {
  4057. nwritten += n;
  4058. len -= n;
  4059. }
  4060. }
  4061. return nwritten;
  4062. }
  4063. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  4064. * Return negative value on error, or number of bytes read on success. */
  4065. static int
  4066. pull(FILE *fp, struct mg_connection *conn, char *buf, int len, double timeout)
  4067. {
  4068. int nread, err = 0;
  4069. #ifdef _WIN32
  4070. typedef int len_t;
  4071. #else
  4072. typedef size_t len_t;
  4073. #endif
  4074. if (fp != NULL) {
  4075. #if !defined(_WIN32_WCE)
  4076. /* Use read() instead of fread(), because if we're reading from the
  4077. * CGI pipe, fread() may block until IO buffer is filled up. We
  4078. * cannot afford to block and must pass all read bytes immediately
  4079. * to the client. */
  4080. nread = (int)read(fileno(fp), buf, (size_t)len);
  4081. #else
  4082. /* WinCE does not support CGI pipes */
  4083. nread = (int)fread(buf, 1, (size_t)len, fp);
  4084. #endif
  4085. err = (nread < 0) ? ERRNO : 0;
  4086. #ifndef NO_SSL
  4087. } else if (conn->ssl != NULL) {
  4088. struct pollfd pfd[1];
  4089. int pollres;
  4090. pfd[0].fd = conn->client.sock;
  4091. pfd[0].events = POLLIN;
  4092. pollres =
  4093. mg_poll(pfd, 1, (int)(timeout * 1000.0), &(conn->ctx->stop_flag));
  4094. if (conn->ctx->stop_flag) {
  4095. return -1;
  4096. }
  4097. if (pollres > 0) {
  4098. nread = SSL_read(conn->ssl, buf, len);
  4099. if (nread <= 0) {
  4100. err = SSL_get_error(conn->ssl, nread);
  4101. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  4102. err = ERRNO;
  4103. } else if ((err == SSL_ERROR_WANT_READ)
  4104. || (err == SSL_ERROR_WANT_WRITE)) {
  4105. nread = 0;
  4106. } else {
  4107. DEBUG_TRACE("SSL_read() failed, error %d", err);
  4108. return -1;
  4109. }
  4110. } else {
  4111. err = 0;
  4112. }
  4113. } else if (pollres < 0) {
  4114. /* Error */
  4115. return -1;
  4116. } else {
  4117. /* pollres = 0 means timeout */
  4118. nread = 0;
  4119. }
  4120. #endif
  4121. } else {
  4122. struct pollfd pfd[1];
  4123. int pollres;
  4124. pfd[0].fd = conn->client.sock;
  4125. pfd[0].events = POLLIN;
  4126. pollres =
  4127. mg_poll(pfd, 1, (int)(timeout * 1000.0), &(conn->ctx->stop_flag));
  4128. if (conn->ctx->stop_flag) {
  4129. return -1;
  4130. }
  4131. if (pollres > 0) {
  4132. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  4133. err = (nread < 0) ? ERRNO : 0;
  4134. if (nread <= 0) {
  4135. /* shutdown of the socket at client side */
  4136. return -1;
  4137. }
  4138. } else if (pollres < 0) {
  4139. /* error callint poll */
  4140. return -1;
  4141. } else {
  4142. /* pollres = 0 means timeout */
  4143. nread = 0;
  4144. }
  4145. }
  4146. if (conn->ctx->stop_flag) {
  4147. return -1;
  4148. }
  4149. if ((nread > 0) || (nread == 0 && len == 0)) {
  4150. /* some data has been read, or no data was requested */
  4151. return nread;
  4152. }
  4153. if (nread < 0) {
  4154. /* socket error - check errno */
  4155. #ifdef _WIN32
  4156. if (err == WSAEWOULDBLOCK) {
  4157. /* TODO (low): check if this is still required */
  4158. /* standard case if called from close_socket_gracefully */
  4159. return -1;
  4160. } else if (err == WSAETIMEDOUT) {
  4161. /* TODO (low): check if this is still required */
  4162. /* timeout is handled by the while loop */
  4163. return 0;
  4164. } else if (err == WSAECONNABORTED) {
  4165. /* See https://www.chilkatsoft.com/p/p_299.asp */
  4166. return -1;
  4167. } else {
  4168. DEBUG_TRACE("recv() failed, error %d", err);
  4169. return -1;
  4170. }
  4171. #else
  4172. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  4173. * if the timeout is reached and if the socket was set to non-
  4174. * blocking in close_socket_gracefully, so we can not distinguish
  4175. * here. We have to wait for the timeout in both cases for now.
  4176. */
  4177. if (err == EAGAIN || err == EWOULDBLOCK || err == EINTR) {
  4178. /* TODO (low): check if this is still required */
  4179. /* EAGAIN/EWOULDBLOCK:
  4180. * standard case if called from close_socket_gracefully
  4181. * => should return -1 */
  4182. /* or timeout occured
  4183. * => the code must stay in the while loop */
  4184. /* EINTR can be generated on a socket with a timeout set even
  4185. * when SA_RESTART is effective for all relevant signals
  4186. * (see signal(7)).
  4187. * => stay in the while loop */
  4188. } else {
  4189. DEBUG_TRACE("recv() failed, error %d", err);
  4190. return -1;
  4191. }
  4192. #endif
  4193. }
  4194. /* Timeout occured, but no data available. */
  4195. return -1;
  4196. }
  4197. static int
  4198. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  4199. {
  4200. int n, nread = 0;
  4201. double timeout = -1.0;
  4202. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  4203. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  4204. }
  4205. while (len > 0 && conn->ctx->stop_flag == 0) {
  4206. n = pull(fp, conn, buf + nread, len, timeout);
  4207. if (n < 0) {
  4208. if (nread == 0) {
  4209. nread = n; /* Propagate the error */
  4210. }
  4211. break;
  4212. } else if (n == 0) {
  4213. break; /* No more data to read */
  4214. } else {
  4215. conn->consumed_content += n;
  4216. nread += n;
  4217. len -= n;
  4218. }
  4219. }
  4220. return nread;
  4221. }
  4222. static void
  4223. discard_unread_request_data(struct mg_connection *conn)
  4224. {
  4225. char buf[MG_BUF_LEN];
  4226. size_t to_read;
  4227. int nread;
  4228. if (conn == NULL) {
  4229. return;
  4230. }
  4231. to_read = sizeof(buf);
  4232. if (conn->is_chunked) {
  4233. /* Chunked encoding: 1=chunk not read completely, 2=chunk read
  4234. * completely */
  4235. while (conn->is_chunked == 1) {
  4236. nread = mg_read(conn, buf, to_read);
  4237. if (nread <= 0) {
  4238. break;
  4239. }
  4240. }
  4241. } else {
  4242. /* Not chunked: content length is known */
  4243. while (conn->consumed_content < conn->content_len) {
  4244. if (to_read
  4245. > (size_t)(conn->content_len - conn->consumed_content)) {
  4246. to_read = (size_t)(conn->content_len - conn->consumed_content);
  4247. }
  4248. nread = mg_read(conn, buf, to_read);
  4249. if (nread <= 0) {
  4250. break;
  4251. }
  4252. }
  4253. }
  4254. }
  4255. static int
  4256. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  4257. {
  4258. int64_t n, buffered_len, nread;
  4259. int64_t len64 =
  4260. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  4261. * int, we may not read more
  4262. * bytes */
  4263. const char *body;
  4264. if (conn == NULL) {
  4265. return 0;
  4266. }
  4267. /* If Content-Length is not set for a PUT or POST request, read until
  4268. * socket is closed */
  4269. if (conn->consumed_content == 0 && conn->content_len == -1) {
  4270. conn->content_len = INT64_MAX;
  4271. conn->must_close = 1;
  4272. }
  4273. nread = 0;
  4274. if (conn->consumed_content < conn->content_len) {
  4275. /* Adjust number of bytes to read. */
  4276. int64_t left_to_read = conn->content_len - conn->consumed_content;
  4277. if (left_to_read < len64) {
  4278. /* Do not read more than the total content length of the request.
  4279. */
  4280. len64 = left_to_read;
  4281. }
  4282. /* Return buffered data */
  4283. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  4284. - conn->consumed_content;
  4285. if (buffered_len > 0) {
  4286. if (len64 < buffered_len) {
  4287. buffered_len = len64;
  4288. }
  4289. body = conn->buf + conn->request_len + conn->consumed_content;
  4290. memcpy(buf, body, (size_t)buffered_len);
  4291. len64 -= buffered_len;
  4292. conn->consumed_content += buffered_len;
  4293. nread += buffered_len;
  4294. buf = (char *)buf + buffered_len;
  4295. }
  4296. /* We have returned all buffered data. Read new data from the remote
  4297. * socket.
  4298. */
  4299. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  4300. nread += n;
  4301. } else {
  4302. nread = ((nread > 0) ? nread : n);
  4303. }
  4304. }
  4305. return (int)nread;
  4306. }
  4307. static char
  4308. mg_getc(struct mg_connection *conn)
  4309. {
  4310. char c;
  4311. if (conn == NULL) {
  4312. return 0;
  4313. }
  4314. conn->content_len++;
  4315. if (mg_read_inner(conn, &c, 1) <= 0) {
  4316. return (char)0;
  4317. }
  4318. return c;
  4319. }
  4320. int
  4321. mg_read(struct mg_connection *conn, void *buf, size_t len)
  4322. {
  4323. if (len > INT_MAX) {
  4324. len = INT_MAX;
  4325. }
  4326. if (conn == NULL) {
  4327. return 0;
  4328. }
  4329. if (conn->is_chunked) {
  4330. size_t all_read = 0;
  4331. while (len > 0) {
  4332. if (conn->is_chunked == 2) {
  4333. /* No more data left to read */
  4334. return 0;
  4335. }
  4336. if (conn->chunk_remainder) {
  4337. /* copy from the remainder of the last received chunk */
  4338. long read_ret;
  4339. size_t read_now =
  4340. ((conn->chunk_remainder > len) ? (len)
  4341. : (conn->chunk_remainder));
  4342. conn->content_len += (int)read_now;
  4343. read_ret =
  4344. mg_read_inner(conn, (char *)buf + all_read, read_now);
  4345. if (read_ret < 1) {
  4346. /* read error */
  4347. return -1;
  4348. }
  4349. all_read += (size_t)read_ret;
  4350. conn->chunk_remainder -= (size_t)read_ret;
  4351. len -= (size_t)read_ret;
  4352. if (conn->chunk_remainder == 0) {
  4353. /* Add data bytes in the current chunk have been read,
  4354. * so we are expecting \r\n now. */
  4355. char x1 = mg_getc(conn);
  4356. char x2 = mg_getc(conn);
  4357. if ((x1 != '\r') || (x2 != '\n')) {
  4358. /* Protocol violation */
  4359. return -1;
  4360. }
  4361. }
  4362. } else {
  4363. /* fetch a new chunk */
  4364. int i = 0;
  4365. char lenbuf[64];
  4366. char *end = 0;
  4367. unsigned long chunkSize = 0;
  4368. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  4369. lenbuf[i] = mg_getc(conn);
  4370. if (i > 0 && lenbuf[i] == '\r' && lenbuf[i - 1] != '\r') {
  4371. continue;
  4372. }
  4373. if (i > 1 && lenbuf[i] == '\n' && lenbuf[i - 1] == '\r') {
  4374. lenbuf[i + 1] = 0;
  4375. chunkSize = strtoul(lenbuf, &end, 16);
  4376. if (chunkSize == 0) {
  4377. /* regular end of content */
  4378. conn->is_chunked = 2;
  4379. }
  4380. break;
  4381. }
  4382. if (!isxdigit(lenbuf[i])) {
  4383. /* illegal character for chunk length */
  4384. return -1;
  4385. }
  4386. }
  4387. if ((end == NULL) || (*end != '\r')) {
  4388. /* chunksize not set correctly */
  4389. return -1;
  4390. }
  4391. if (chunkSize == 0) {
  4392. break;
  4393. }
  4394. conn->chunk_remainder = chunkSize;
  4395. }
  4396. }
  4397. return (int)all_read;
  4398. }
  4399. return mg_read_inner(conn, buf, len);
  4400. }
  4401. int
  4402. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  4403. {
  4404. time_t now;
  4405. int64_t n, total, allowed;
  4406. if (conn == NULL) {
  4407. return 0;
  4408. }
  4409. if (conn->throttle > 0) {
  4410. if ((now = time(NULL)) != conn->last_throttle_time) {
  4411. conn->last_throttle_time = now;
  4412. conn->last_throttle_bytes = 0;
  4413. }
  4414. allowed = conn->throttle - conn->last_throttle_bytes;
  4415. if (allowed > (int64_t)len) {
  4416. allowed = (int64_t)len;
  4417. }
  4418. if ((total = push_all(conn->ctx,
  4419. NULL,
  4420. conn->client.sock,
  4421. conn->ssl,
  4422. (const char *)buf,
  4423. (int64_t)allowed)) == allowed) {
  4424. buf = (const char *)buf + total;
  4425. conn->last_throttle_bytes += total;
  4426. while (total < (int64_t)len && conn->ctx->stop_flag == 0) {
  4427. allowed = (conn->throttle > ((int64_t)len - total))
  4428. ? (int64_t)len - total
  4429. : conn->throttle;
  4430. if ((n = push_all(conn->ctx,
  4431. NULL,
  4432. conn->client.sock,
  4433. conn->ssl,
  4434. (const char *)buf,
  4435. (int64_t)allowed)) != allowed) {
  4436. break;
  4437. }
  4438. sleep(1);
  4439. conn->last_throttle_bytes = allowed;
  4440. conn->last_throttle_time = time(NULL);
  4441. buf = (const char *)buf + n;
  4442. total += n;
  4443. }
  4444. }
  4445. } else {
  4446. total = push_all(conn->ctx,
  4447. NULL,
  4448. conn->client.sock,
  4449. conn->ssl,
  4450. (const char *)buf,
  4451. (int64_t)len);
  4452. }
  4453. return (int)total;
  4454. }
  4455. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  4456. static int
  4457. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  4458. {
  4459. va_list ap_copy;
  4460. size_t size = MG_BUF_LEN / 4;
  4461. int len = -1;
  4462. *buf = NULL;
  4463. while (len < 0) {
  4464. if (*buf) {
  4465. mg_free(*buf);
  4466. }
  4467. size *= 4;
  4468. *buf = (char *)mg_malloc(size);
  4469. if (!*buf) {
  4470. break;
  4471. }
  4472. va_copy(ap_copy, ap);
  4473. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  4474. va_end(ap_copy);
  4475. (*buf)[size - 1] = 0;
  4476. }
  4477. return len;
  4478. }
  4479. /* Print message to buffer. If buffer is large enough to hold the message,
  4480. * return buffer. If buffer is to small, allocate large enough buffer on heap,
  4481. * and return allocated buffer. */
  4482. static int
  4483. alloc_vprintf(char **out_buf,
  4484. char *prealloc_buf,
  4485. size_t prealloc_size,
  4486. const char *fmt,
  4487. va_list ap)
  4488. {
  4489. va_list ap_copy;
  4490. int len;
  4491. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  4492. * buffer is too small. Also, older versions of msvcrt.dll do not have
  4493. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  4494. * Therefore, we make two passes: on first pass, get required message
  4495. * length.
  4496. * On second pass, actually print the message. */
  4497. va_copy(ap_copy, ap);
  4498. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  4499. va_end(ap_copy);
  4500. if (len < 0) {
  4501. /* C runtime is not standard compliant, vsnprintf() returned -1.
  4502. * Switch to alternative code path that uses incremental allocations.
  4503. */
  4504. va_copy(ap_copy, ap);
  4505. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  4506. va_end(ap_copy);
  4507. } else if ((size_t)(len) >= prealloc_size) {
  4508. /* The pre-allocated buffer not large enough. */
  4509. /* Allocate a new buffer. */
  4510. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  4511. if (!*out_buf) {
  4512. /* Allocation failed. Return -1 as "out of memory" error. */
  4513. return -1;
  4514. }
  4515. /* Buffer allocation successful. Store the string there. */
  4516. va_copy(ap_copy, ap);
  4517. IGNORE_UNUSED_RESULT(
  4518. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  4519. va_end(ap_copy);
  4520. } else {
  4521. /* The pre-allocated buffer is large enough.
  4522. * Use it to store the string and return the address. */
  4523. va_copy(ap_copy, ap);
  4524. IGNORE_UNUSED_RESULT(
  4525. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  4526. va_end(ap_copy);
  4527. *out_buf = prealloc_buf;
  4528. }
  4529. return len;
  4530. }
  4531. static int
  4532. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  4533. {
  4534. char mem[MG_BUF_LEN];
  4535. char *buf = NULL;
  4536. int len;
  4537. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  4538. len = mg_write(conn, buf, (size_t)len);
  4539. }
  4540. if (buf != mem && buf != NULL) {
  4541. mg_free(buf);
  4542. }
  4543. return len;
  4544. }
  4545. int
  4546. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  4547. {
  4548. va_list ap;
  4549. int result;
  4550. va_start(ap, fmt);
  4551. result = mg_vprintf(conn, fmt, ap);
  4552. va_end(ap);
  4553. return result;
  4554. }
  4555. int
  4556. mg_url_decode(const char *src,
  4557. int src_len,
  4558. char *dst,
  4559. int dst_len,
  4560. int is_form_url_encoded)
  4561. {
  4562. int i, j, a, b;
  4563. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  4564. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  4565. if (i < src_len - 2 && src[i] == '%'
  4566. && isxdigit(*(const unsigned char *)(src + i + 1))
  4567. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  4568. a = tolower(*(const unsigned char *)(src + i + 1));
  4569. b = tolower(*(const unsigned char *)(src + i + 2));
  4570. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  4571. i += 2;
  4572. } else if (is_form_url_encoded && src[i] == '+') {
  4573. dst[j] = ' ';
  4574. } else {
  4575. dst[j] = src[i];
  4576. }
  4577. }
  4578. dst[j] = '\0'; /* Null-terminate the destination */
  4579. return (i >= src_len) ? j : -1;
  4580. }
  4581. int
  4582. mg_get_var(const char *data,
  4583. size_t data_len,
  4584. const char *name,
  4585. char *dst,
  4586. size_t dst_len)
  4587. {
  4588. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  4589. }
  4590. int
  4591. mg_get_var2(const char *data,
  4592. size_t data_len,
  4593. const char *name,
  4594. char *dst,
  4595. size_t dst_len,
  4596. size_t occurrence)
  4597. {
  4598. const char *p, *e, *s;
  4599. size_t name_len;
  4600. int len;
  4601. if (dst == NULL || dst_len == 0) {
  4602. len = -2;
  4603. } else if (data == NULL || name == NULL || data_len == 0) {
  4604. len = -1;
  4605. dst[0] = '\0';
  4606. } else {
  4607. name_len = strlen(name);
  4608. e = data + data_len;
  4609. len = -1;
  4610. dst[0] = '\0';
  4611. /* data is "var1=val1&var2=val2...". Find variable first */
  4612. for (p = data; p + name_len < e; p++) {
  4613. if ((p == data || p[-1] == '&') && p[name_len] == '='
  4614. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  4615. /* Point p to variable value */
  4616. p += name_len + 1;
  4617. /* Point s to the end of the value */
  4618. s = (const char *)memchr(p, '&', (size_t)(e - p));
  4619. if (s == NULL) {
  4620. s = e;
  4621. }
  4622. /* assert(s >= p); */
  4623. if (s < p) {
  4624. return -3;
  4625. }
  4626. /* Decode variable into destination buffer */
  4627. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  4628. /* Redirect error code from -1 to -2 (destination buffer too
  4629. * small). */
  4630. if (len == -1) {
  4631. len = -2;
  4632. }
  4633. break;
  4634. }
  4635. }
  4636. }
  4637. return len;
  4638. }
  4639. /* HCP24: some changes to compare hole var_name */
  4640. int
  4641. mg_get_cookie(const char *cookie_header,
  4642. const char *var_name,
  4643. char *dst,
  4644. size_t dst_size)
  4645. {
  4646. const char *s, *p, *end;
  4647. int name_len, len = -1;
  4648. if (dst == NULL || dst_size == 0) {
  4649. return -2;
  4650. }
  4651. dst[0] = '\0';
  4652. if (var_name == NULL || (s = cookie_header) == NULL) {
  4653. return -1;
  4654. }
  4655. name_len = (int)strlen(var_name);
  4656. end = s + strlen(s);
  4657. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  4658. if (s[name_len] == '=') {
  4659. /* HCP24: now check is it a substring or a full cookie name */
  4660. if ((s == cookie_header) || (s[-1] == ' ')) {
  4661. s += name_len + 1;
  4662. if ((p = strchr(s, ' ')) == NULL) {
  4663. p = end;
  4664. }
  4665. if (p[-1] == ';') {
  4666. p--;
  4667. }
  4668. if (*s == '"' && p[-1] == '"' && p > s + 1) {
  4669. s++;
  4670. p--;
  4671. }
  4672. if ((size_t)(p - s) < dst_size) {
  4673. len = (int)(p - s);
  4674. mg_strlcpy(dst, s, (size_t)len + 1);
  4675. } else {
  4676. len = -3;
  4677. }
  4678. break;
  4679. }
  4680. }
  4681. }
  4682. return len;
  4683. }
  4684. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  4685. static void
  4686. base64_encode(const unsigned char *src, int src_len, char *dst)
  4687. {
  4688. static const char *b64 =
  4689. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  4690. int i, j, a, b, c;
  4691. for (i = j = 0; i < src_len; i += 3) {
  4692. a = src[i];
  4693. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  4694. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  4695. dst[j++] = b64[a >> 2];
  4696. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  4697. if (i + 1 < src_len) {
  4698. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  4699. }
  4700. if (i + 2 < src_len) {
  4701. dst[j++] = b64[c & 63];
  4702. }
  4703. }
  4704. while (j % 4 != 0) {
  4705. dst[j++] = '=';
  4706. }
  4707. dst[j++] = '\0';
  4708. }
  4709. #endif
  4710. #if defined(USE_LUA)
  4711. static unsigned char
  4712. b64reverse(char letter)
  4713. {
  4714. if (letter >= 'A' && letter <= 'Z') {
  4715. return letter - 'A';
  4716. }
  4717. if (letter >= 'a' && letter <= 'z') {
  4718. return letter - 'a' + 26;
  4719. }
  4720. if (letter >= '0' && letter <= '9') {
  4721. return letter - '0' + 52;
  4722. }
  4723. if (letter == '+') {
  4724. return 62;
  4725. }
  4726. if (letter == '/') {
  4727. return 63;
  4728. }
  4729. if (letter == '=') {
  4730. return 255; /* normal end */
  4731. }
  4732. return 254; /* error */
  4733. }
  4734. static int
  4735. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  4736. {
  4737. int i;
  4738. unsigned char a, b, c, d;
  4739. *dst_len = 0;
  4740. for (i = 0; i < src_len; i += 4) {
  4741. a = b64reverse(src[i]);
  4742. if (a >= 254) {
  4743. return i;
  4744. }
  4745. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  4746. if (b >= 254) {
  4747. return i + 1;
  4748. }
  4749. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  4750. if (c == 254) {
  4751. return i + 2;
  4752. }
  4753. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  4754. if (d == 254) {
  4755. return i + 3;
  4756. }
  4757. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  4758. if (c != 255) {
  4759. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  4760. if (d != 255) {
  4761. dst[(*dst_len)++] = (c << 6) + d;
  4762. }
  4763. }
  4764. }
  4765. return -1;
  4766. }
  4767. #endif
  4768. static int
  4769. is_put_or_delete_method(const struct mg_connection *conn)
  4770. {
  4771. if (conn) {
  4772. const char *s = conn->request_info.request_method;
  4773. return s != NULL && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  4774. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  4775. }
  4776. return 0;
  4777. }
  4778. static void
  4779. interpret_uri(struct mg_connection *conn, /* in: request (must be valid) */
  4780. char *filename, /* out: filename */
  4781. size_t filename_buf_len, /* in: size of filename buffer */
  4782. struct mg_file_stat *filestat, /* out: file structure */
  4783. int *is_found, /* out: file found (directly) */
  4784. int *is_script_resource, /* out: handled by a script? */
  4785. int *is_websocket_request, /* out: websocket connetion? */
  4786. int *is_put_or_delete_request /* out: put/delete a file? */
  4787. )
  4788. {
  4789. /* TODO (high / maintainability issue): Restructure this function */
  4790. #if !defined(NO_FILES)
  4791. const char *uri = conn->request_info.local_uri;
  4792. const char *root = conn->ctx->config[DOCUMENT_ROOT];
  4793. const char *rewrite;
  4794. struct vec a, b;
  4795. int match_len;
  4796. char gz_path[PATH_MAX];
  4797. char const *accept_encoding;
  4798. int truncated;
  4799. #if !defined(NO_CGI) || defined(USE_LUA)
  4800. char *p;
  4801. #endif
  4802. #else
  4803. (void)filename_buf_len; /* unused if NO_FILES is defined */
  4804. #endif
  4805. memset(filestat, 0, sizeof(*filestat));
  4806. *filename = 0;
  4807. *is_found = 0;
  4808. *is_script_resource = 0;
  4809. *is_put_or_delete_request = is_put_or_delete_method(conn);
  4810. #if defined(USE_WEBSOCKET)
  4811. *is_websocket_request = is_websocket_protocol(conn);
  4812. #if !defined(NO_FILES)
  4813. if (*is_websocket_request && conn->ctx->config[WEBSOCKET_ROOT]) {
  4814. root = conn->ctx->config[WEBSOCKET_ROOT];
  4815. }
  4816. #endif /* !NO_FILES */
  4817. #else /* USE_WEBSOCKET */
  4818. *is_websocket_request = 0;
  4819. #endif /* USE_WEBSOCKET */
  4820. #if !defined(NO_FILES)
  4821. /* Note that root == NULL is a regular use case here. This occurs,
  4822. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  4823. * config is not required. */
  4824. if (root == NULL) {
  4825. /* all file related outputs have already been set to 0, just return
  4826. */
  4827. return;
  4828. }
  4829. /* Using buf_len - 1 because memmove() for PATH_INFO may shift part
  4830. * of the path one byte on the right.
  4831. * If document_root is NULL, leave the file empty. */
  4832. mg_snprintf(
  4833. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  4834. if (truncated) {
  4835. goto interpret_cleanup;
  4836. }
  4837. rewrite = conn->ctx->config[REWRITE];
  4838. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  4839. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  4840. mg_snprintf(conn,
  4841. &truncated,
  4842. filename,
  4843. filename_buf_len - 1,
  4844. "%.*s%s",
  4845. (int)b.len,
  4846. b.ptr,
  4847. uri + match_len);
  4848. break;
  4849. }
  4850. }
  4851. if (truncated) {
  4852. goto interpret_cleanup;
  4853. }
  4854. /* Local file path and name, corresponding to requested URI
  4855. * is now stored in "filename" variable. */
  4856. if (mg_stat(conn, filename, filestat)) {
  4857. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  4858. /* File exists. Check if it is a script type. */
  4859. if (0
  4860. #if !defined(NO_CGI)
  4861. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  4862. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4863. filename) > 0
  4864. #endif
  4865. #if defined(USE_LUA)
  4866. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  4867. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  4868. filename) > 0
  4869. #endif
  4870. #if defined(USE_DUKTAPE)
  4871. || match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  4872. strlen(
  4873. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  4874. filename) > 0
  4875. #endif
  4876. ) {
  4877. /* The request addresses a CGI script or a Lua script. The URI
  4878. * corresponds to the script itself (like /path/script.cgi),
  4879. * and there is no additional resource path
  4880. * (like /path/script.cgi/something).
  4881. * Requests that modify (replace or delete) a resource, like
  4882. * PUT and DELETE requests, should replace/delete the script
  4883. * file.
  4884. * Requests that read or write from/to a resource, like GET and
  4885. * POST requests, should call the script and return the
  4886. * generated response. */
  4887. *is_script_resource = !*is_put_or_delete_request;
  4888. }
  4889. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  4890. *is_found = 1;
  4891. return;
  4892. }
  4893. /* If we can't find the actual file, look for the file
  4894. * with the same name but a .gz extension. If we find it,
  4895. * use that and set the gzipped flag in the file struct
  4896. * to indicate that the response need to have the content-
  4897. * encoding: gzip header.
  4898. * We can only do this if the browser declares support. */
  4899. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  4900. if (strstr(accept_encoding, "gzip") != NULL) {
  4901. mg_snprintf(
  4902. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  4903. if (truncated) {
  4904. goto interpret_cleanup;
  4905. }
  4906. if (mg_stat(conn, gz_path, filestat)) {
  4907. if (filestat) {
  4908. filestat->is_gzipped = 1;
  4909. *is_found = 1;
  4910. }
  4911. /* Currently gz files can not be scripts. */
  4912. return;
  4913. }
  4914. }
  4915. }
  4916. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  4917. /* Support PATH_INFO for CGI scripts. */
  4918. for (p = filename + strlen(filename); p > filename + 1; p--) {
  4919. if (*p == '/') {
  4920. *p = '\0';
  4921. if ((0
  4922. #if !defined(NO_CGI)
  4923. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  4924. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4925. filename) > 0
  4926. #endif
  4927. #if defined(USE_LUA)
  4928. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  4929. strlen(
  4930. conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  4931. filename) > 0
  4932. #endif
  4933. #if defined(USE_DUKTAPE)
  4934. || match_prefix(
  4935. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  4936. strlen(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  4937. filename) > 0
  4938. #endif
  4939. ) && mg_stat(conn, filename, filestat)) {
  4940. /* Shift PATH_INFO block one character right, e.g.
  4941. * "/x.cgi/foo/bar\x00" => "/x.cgi\x00/foo/bar\x00"
  4942. * conn->path_info is pointing to the local variable "path"
  4943. * declared in handle_request(), so PATH_INFO is not valid
  4944. * after handle_request returns. */
  4945. conn->path_info = p + 1;
  4946. memmove(p + 2, p + 1, strlen(p + 1) + 1); /* +1 is for
  4947. * trailing \0 */
  4948. p[1] = '/';
  4949. *is_script_resource = 1;
  4950. break;
  4951. } else {
  4952. *p = '/';
  4953. }
  4954. }
  4955. }
  4956. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  4957. #endif /* !defined(NO_FILES) */
  4958. return;
  4959. #if !defined(NO_FILES)
  4960. /* Reset all outputs */
  4961. interpret_cleanup:
  4962. memset(filestat, 0, sizeof(*filestat));
  4963. *filename = 0;
  4964. *is_found = 0;
  4965. *is_script_resource = 0;
  4966. *is_websocket_request = 0;
  4967. *is_put_or_delete_request = 0;
  4968. #endif /* !defined(NO_FILES) */
  4969. }
  4970. /* Check whether full request is buffered. Return:
  4971. * -1 if request is malformed
  4972. * 0 if request is not yet fully buffered
  4973. * >0 actual request length, including last \r\n\r\n */
  4974. static int
  4975. get_request_len(const char *buf, int buflen)
  4976. {
  4977. const char *s, *e;
  4978. int len = 0;
  4979. for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
  4980. /* Control characters are not allowed but >=128 is. */
  4981. if (!isprint(*(const unsigned char *)s) && *s != '\r' && *s != '\n'
  4982. && *(const unsigned char *)s < 128) {
  4983. len = -1;
  4984. break; /* [i_a] abort scan as soon as one malformed character is
  4985. * found; */
  4986. /* don't let subsequent \r\n\r\n win us over anyhow */
  4987. } else if (s[0] == '\n' && s[1] == '\n') {
  4988. len = (int)(s - buf) + 2;
  4989. } else if (s[0] == '\n' && &s[1] < e && s[1] == '\r' && s[2] == '\n') {
  4990. len = (int)(s - buf) + 3;
  4991. }
  4992. return len;
  4993. }
  4994. #if !defined(NO_CACHING)
  4995. /* Convert month to the month number. Return -1 on error, or month number */
  4996. static int
  4997. get_month_index(const char *s)
  4998. {
  4999. size_t i;
  5000. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  5001. if (!strcmp(s, month_names[i])) {
  5002. return (int)i;
  5003. }
  5004. }
  5005. return -1;
  5006. }
  5007. /* Parse UTC date-time string, and return the corresponding time_t value. */
  5008. static time_t
  5009. parse_date_string(const char *datetime)
  5010. {
  5011. char month_str[32] = {0};
  5012. int second, minute, hour, day, month, year;
  5013. time_t result = (time_t)0;
  5014. struct tm tm;
  5015. if ((sscanf(datetime,
  5016. "%d/%3s/%d %d:%d:%d",
  5017. &day,
  5018. month_str,
  5019. &year,
  5020. &hour,
  5021. &minute,
  5022. &second) == 6) || (sscanf(datetime,
  5023. "%d %3s %d %d:%d:%d",
  5024. &day,
  5025. month_str,
  5026. &year,
  5027. &hour,
  5028. &minute,
  5029. &second) == 6)
  5030. || (sscanf(datetime,
  5031. "%*3s, %d %3s %d %d:%d:%d",
  5032. &day,
  5033. month_str,
  5034. &year,
  5035. &hour,
  5036. &minute,
  5037. &second) == 6) || (sscanf(datetime,
  5038. "%d-%3s-%d %d:%d:%d",
  5039. &day,
  5040. month_str,
  5041. &year,
  5042. &hour,
  5043. &minute,
  5044. &second) == 6)) {
  5045. month = get_month_index(month_str);
  5046. if ((month >= 0) && (year >= 1970)) {
  5047. memset(&tm, 0, sizeof(tm));
  5048. tm.tm_year = year - 1900;
  5049. tm.tm_mon = month;
  5050. tm.tm_mday = day;
  5051. tm.tm_hour = hour;
  5052. tm.tm_min = minute;
  5053. tm.tm_sec = second;
  5054. result = timegm(&tm);
  5055. }
  5056. }
  5057. return result;
  5058. }
  5059. #endif /* !NO_CACHING */
  5060. /* Protect against directory disclosure attack by removing '..',
  5061. * excessive '/' and '\' characters */
  5062. static void
  5063. remove_double_dots_and_double_slashes(char *s)
  5064. {
  5065. char *p = s;
  5066. while ((s[0] == '.') && (s[1] == '.')) {
  5067. s++;
  5068. }
  5069. while (*s != '\0') {
  5070. *p++ = *s++;
  5071. if (s[-1] == '/' || s[-1] == '\\') {
  5072. /* Skip all following slashes, backslashes and double-dots */
  5073. while (s[0] != '\0') {
  5074. if (s[0] == '/' || s[0] == '\\') {
  5075. s++;
  5076. } else if (s[0] == '.' && s[1] == '.') {
  5077. s += 2;
  5078. } else {
  5079. break;
  5080. }
  5081. }
  5082. }
  5083. }
  5084. *p = '\0';
  5085. }
  5086. static const struct {
  5087. const char *extension;
  5088. size_t ext_len;
  5089. const char *mime_type;
  5090. } builtin_mime_types[] = {
  5091. /* IANA registered MIME types (http://www.iana.org/assignments/media-types)
  5092. * application types */
  5093. {".doc", 4, "application/msword"},
  5094. {".eps", 4, "application/postscript"},
  5095. {".exe", 4, "application/octet-stream"},
  5096. {".js", 3, "application/javascript"},
  5097. {".json", 5, "application/json"},
  5098. {".pdf", 4, "application/pdf"},
  5099. {".ps", 3, "application/postscript"},
  5100. {".rtf", 4, "application/rtf"},
  5101. {".xhtml", 6, "application/xhtml+xml"},
  5102. {".xsl", 4, "application/xml"},
  5103. {".xslt", 5, "application/xml"},
  5104. /* fonts */
  5105. {".ttf", 4, "application/font-sfnt"},
  5106. {".cff", 4, "application/font-sfnt"},
  5107. {".otf", 4, "application/font-sfnt"},
  5108. {".aat", 4, "application/font-sfnt"},
  5109. {".sil", 4, "application/font-sfnt"},
  5110. {".pfr", 4, "application/font-tdpfr"},
  5111. {".woff", 5, "application/font-woff"},
  5112. /* audio */
  5113. {".mp3", 4, "audio/mpeg"},
  5114. {".oga", 4, "audio/ogg"},
  5115. {".ogg", 4, "audio/ogg"},
  5116. /* image */
  5117. {".gif", 4, "image/gif"},
  5118. {".ief", 4, "image/ief"},
  5119. {".jpeg", 5, "image/jpeg"},
  5120. {".jpg", 4, "image/jpeg"},
  5121. {".jpm", 4, "image/jpm"},
  5122. {".jpx", 4, "image/jpx"},
  5123. {".png", 4, "image/png"},
  5124. {".svg", 4, "image/svg+xml"},
  5125. {".tif", 4, "image/tiff"},
  5126. {".tiff", 5, "image/tiff"},
  5127. /* model */
  5128. {".wrl", 4, "model/vrml"},
  5129. /* text */
  5130. {".css", 4, "text/css"},
  5131. {".csv", 4, "text/csv"},
  5132. {".htm", 4, "text/html"},
  5133. {".html", 5, "text/html"},
  5134. {".sgm", 4, "text/sgml"},
  5135. {".shtm", 5, "text/html"},
  5136. {".shtml", 6, "text/html"},
  5137. {".txt", 4, "text/plain"},
  5138. {".xml", 4, "text/xml"},
  5139. /* video */
  5140. {".mov", 4, "video/quicktime"},
  5141. {".mp4", 4, "video/mp4"},
  5142. {".mpeg", 5, "video/mpeg"},
  5143. {".mpg", 4, "video/mpeg"},
  5144. {".ogv", 4, "video/ogg"},
  5145. {".qt", 3, "video/quicktime"},
  5146. /* not registered types
  5147. * (http://reference.sitepoint.com/html/mime-types-full,
  5148. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  5149. {".arj", 4, "application/x-arj-compressed"},
  5150. {".gz", 3, "application/x-gunzip"},
  5151. {".rar", 4, "application/x-arj-compressed"},
  5152. {".swf", 4, "application/x-shockwave-flash"},
  5153. {".tar", 4, "application/x-tar"},
  5154. {".tgz", 4, "application/x-tar-gz"},
  5155. {".torrent", 8, "application/x-bittorrent"},
  5156. {".ppt", 4, "application/x-mspowerpoint"},
  5157. {".xls", 4, "application/x-msexcel"},
  5158. {".zip", 4, "application/x-zip-compressed"},
  5159. {".aac",
  5160. 4,
  5161. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  5162. {".aif", 4, "audio/x-aif"},
  5163. {".m3u", 4, "audio/x-mpegurl"},
  5164. {".mid", 4, "audio/x-midi"},
  5165. {".ra", 3, "audio/x-pn-realaudio"},
  5166. {".ram", 4, "audio/x-pn-realaudio"},
  5167. {".wav", 4, "audio/x-wav"},
  5168. {".bmp", 4, "image/bmp"},
  5169. {".ico", 4, "image/x-icon"},
  5170. {".pct", 4, "image/x-pct"},
  5171. {".pict", 5, "image/pict"},
  5172. {".rgb", 4, "image/x-rgb"},
  5173. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  5174. {".asf", 4, "video/x-ms-asf"},
  5175. {".avi", 4, "video/x-msvideo"},
  5176. {".m4v", 4, "video/x-m4v"},
  5177. {NULL, 0, NULL}};
  5178. const char *
  5179. mg_get_builtin_mime_type(const char *path)
  5180. {
  5181. const char *ext;
  5182. size_t i, path_len;
  5183. path_len = strlen(path);
  5184. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  5185. ext = path + (path_len - builtin_mime_types[i].ext_len);
  5186. if (path_len > builtin_mime_types[i].ext_len
  5187. && mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {
  5188. return builtin_mime_types[i].mime_type;
  5189. }
  5190. }
  5191. return "text/plain";
  5192. }
  5193. /* Look at the "path" extension and figure what mime type it has.
  5194. * Store mime type in the vector. */
  5195. static void
  5196. get_mime_type(struct mg_context *ctx, const char *path, struct vec *vec)
  5197. {
  5198. struct vec ext_vec, mime_vec;
  5199. const char *list, *ext;
  5200. size_t path_len;
  5201. path_len = strlen(path);
  5202. if (ctx == NULL || vec == NULL) {
  5203. return;
  5204. }
  5205. /* Scan user-defined mime types first, in case user wants to
  5206. * override default mime types. */
  5207. list = ctx->config[EXTRA_MIME_TYPES];
  5208. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  5209. /* ext now points to the path suffix */
  5210. ext = path + path_len - ext_vec.len;
  5211. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  5212. *vec = mime_vec;
  5213. return;
  5214. }
  5215. }
  5216. vec->ptr = mg_get_builtin_mime_type(path);
  5217. vec->len = strlen(vec->ptr);
  5218. }
  5219. /* Stringify binary data. Output buffer must be twice as big as input,
  5220. * because each byte takes 2 bytes in string representation */
  5221. static void
  5222. bin2str(char *to, const unsigned char *p, size_t len)
  5223. {
  5224. static const char *hex = "0123456789abcdef";
  5225. for (; len--; p++) {
  5226. *to++ = hex[p[0] >> 4];
  5227. *to++ = hex[p[0] & 0x0f];
  5228. }
  5229. *to = '\0';
  5230. }
  5231. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes. */
  5232. char *
  5233. mg_md5(char buf[33], ...)
  5234. {
  5235. md5_byte_t hash[16];
  5236. const char *p;
  5237. va_list ap;
  5238. md5_state_t ctx;
  5239. md5_init(&ctx);
  5240. va_start(ap, buf);
  5241. while ((p = va_arg(ap, const char *)) != NULL) {
  5242. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  5243. }
  5244. va_end(ap);
  5245. md5_finish(&ctx, hash);
  5246. bin2str(buf, hash, sizeof(hash));
  5247. return buf;
  5248. }
  5249. /* Check the user's password, return 1 if OK */
  5250. static int
  5251. check_password(const char *method,
  5252. const char *ha1,
  5253. const char *uri,
  5254. const char *nonce,
  5255. const char *nc,
  5256. const char *cnonce,
  5257. const char *qop,
  5258. const char *response)
  5259. {
  5260. char ha2[32 + 1], expected_response[32 + 1];
  5261. /* Some of the parameters may be NULL */
  5262. if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL
  5263. || qop == NULL
  5264. || response == NULL) {
  5265. return 0;
  5266. }
  5267. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  5268. if (strlen(response) != 32) {
  5269. return 0;
  5270. }
  5271. mg_md5(ha2, method, ":", uri, NULL);
  5272. mg_md5(expected_response,
  5273. ha1,
  5274. ":",
  5275. nonce,
  5276. ":",
  5277. nc,
  5278. ":",
  5279. cnonce,
  5280. ":",
  5281. qop,
  5282. ":",
  5283. ha2,
  5284. NULL);
  5285. return mg_strcasecmp(response, expected_response) == 0;
  5286. }
  5287. /* Use the global passwords file, if specified by auth_gpass option,
  5288. * or search for .htpasswd in the requested directory. */
  5289. static void
  5290. open_auth_file(struct mg_connection *conn,
  5291. const char *path,
  5292. struct mg_file *filep)
  5293. {
  5294. if (conn != NULL && conn->ctx != NULL) {
  5295. char name[PATH_MAX];
  5296. const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
  5297. int truncated;
  5298. if (gpass != NULL) {
  5299. /* Use global passwords file */
  5300. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  5301. #ifdef DEBUG
  5302. /* Use mg_cry here, since gpass has been configured. */
  5303. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  5304. #endif
  5305. }
  5306. /* Important: using local struct mg_file to test path for
  5307. * is_directory flag. If filep is used, mg_stat() makes it
  5308. * appear as if auth file was opened.
  5309. * TODO(mid): Check if this is still required after rewriting
  5310. * mg_stat */
  5311. } else if (mg_stat(conn, path, &filep->stat)
  5312. && filep->stat.is_directory) {
  5313. mg_snprintf(conn,
  5314. &truncated,
  5315. name,
  5316. sizeof(name),
  5317. "%s/%s",
  5318. path,
  5319. PASSWORDS_FILE_NAME);
  5320. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  5321. #ifdef DEBUG
  5322. /* Don't use mg_cry here, but only a trace, since this is
  5323. * a typical case. It will occur for every directory
  5324. * without a password file. */
  5325. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  5326. #endif
  5327. }
  5328. } else {
  5329. /* Try to find .htpasswd in requested directory. */
  5330. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  5331. if (e[0] == '/') {
  5332. break;
  5333. }
  5334. }
  5335. mg_snprintf(conn,
  5336. &truncated,
  5337. name,
  5338. sizeof(name),
  5339. "%.*s/%s",
  5340. (int)(e - p),
  5341. p,
  5342. PASSWORDS_FILE_NAME);
  5343. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  5344. #ifdef DEBUG
  5345. /* Don't use mg_cry here, but only a trace, since this is
  5346. * a typical case. It will occur for every directory
  5347. * without a password file. */
  5348. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  5349. #endif
  5350. }
  5351. }
  5352. }
  5353. }
  5354. /* Parsed Authorization header */
  5355. struct ah {
  5356. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  5357. };
  5358. /* Return 1 on success. Always initializes the ah structure. */
  5359. static int
  5360. parse_auth_header(struct mg_connection *conn,
  5361. char *buf,
  5362. size_t buf_size,
  5363. struct ah *ah)
  5364. {
  5365. char *name, *value, *s;
  5366. const char *auth_header;
  5367. uint64_t nonce;
  5368. if (!ah || !conn) {
  5369. return 0;
  5370. }
  5371. (void)memset(ah, 0, sizeof(*ah));
  5372. if ((auth_header = mg_get_header(conn, "Authorization")) == NULL
  5373. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  5374. return 0;
  5375. }
  5376. /* Make modifiable copy of the auth header */
  5377. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  5378. s = buf;
  5379. /* Parse authorization header */
  5380. for (;;) {
  5381. /* Gobble initial spaces */
  5382. while (isspace(*(unsigned char *)s)) {
  5383. s++;
  5384. }
  5385. name = skip_quoted(&s, "=", " ", 0);
  5386. /* Value is either quote-delimited, or ends at first comma or space. */
  5387. if (s[0] == '\"') {
  5388. s++;
  5389. value = skip_quoted(&s, "\"", " ", '\\');
  5390. if (s[0] == ',') {
  5391. s++;
  5392. }
  5393. } else {
  5394. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  5395. * spaces */
  5396. }
  5397. if (*name == '\0') {
  5398. break;
  5399. }
  5400. if (!strcmp(name, "username")) {
  5401. ah->user = value;
  5402. } else if (!strcmp(name, "cnonce")) {
  5403. ah->cnonce = value;
  5404. } else if (!strcmp(name, "response")) {
  5405. ah->response = value;
  5406. } else if (!strcmp(name, "uri")) {
  5407. ah->uri = value;
  5408. } else if (!strcmp(name, "qop")) {
  5409. ah->qop = value;
  5410. } else if (!strcmp(name, "nc")) {
  5411. ah->nc = value;
  5412. } else if (!strcmp(name, "nonce")) {
  5413. ah->nonce = value;
  5414. }
  5415. }
  5416. #ifndef NO_NONCE_CHECK
  5417. /* Read the nonce from the response. */
  5418. if (ah->nonce == NULL) {
  5419. return 0;
  5420. }
  5421. s = NULL;
  5422. nonce = strtoull(ah->nonce, &s, 10);
  5423. if ((s == NULL) || (*s != 0)) {
  5424. return 0;
  5425. }
  5426. /* Convert the nonce from the client to a number. */
  5427. nonce ^= conn->ctx->auth_nonce_mask;
  5428. /* The converted number corresponds to the time the nounce has been
  5429. * created. This should not be earlier than the server start. */
  5430. /* Server side nonce check is valuable in all situations but one:
  5431. * if the server restarts frequently, but the client should not see
  5432. * that, so the server should accept nonces from previous starts. */
  5433. /* However, the reasonable default is to not accept a nonce from a
  5434. * previous start, so if anyone changed the access rights between
  5435. * two restarts, a new login is required. */
  5436. if (nonce < (uint64_t)conn->ctx->start_time) {
  5437. /* nonce is from a previous start of the server and no longer valid
  5438. * (replay attack?) */
  5439. return 0;
  5440. }
  5441. /* Check if the nonce is too high, so it has not (yet) been used by the
  5442. * server. */
  5443. if (nonce >= ((uint64_t)conn->ctx->start_time + conn->ctx->nonce_count)) {
  5444. return 0;
  5445. }
  5446. #else
  5447. (void)nonce;
  5448. #endif
  5449. /* CGI needs it as REMOTE_USER */
  5450. if (ah->user != NULL) {
  5451. conn->request_info.remote_user = mg_strdup(ah->user);
  5452. } else {
  5453. return 0;
  5454. }
  5455. return 1;
  5456. }
  5457. static const char *
  5458. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  5459. {
  5460. const char *eof;
  5461. size_t len;
  5462. const char *memend;
  5463. if (!filep) {
  5464. return NULL;
  5465. }
  5466. if (filep->access.membuf != NULL && *p != NULL) {
  5467. memend = (const char *)&filep->access.membuf[filep->stat.size];
  5468. /* Search for \n from p till the end of stream */
  5469. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  5470. if (eof != NULL) {
  5471. eof += 1; /* Include \n */
  5472. } else {
  5473. eof = memend; /* Copy remaining data */
  5474. }
  5475. len =
  5476. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  5477. memcpy(buf, *p, len);
  5478. buf[len] = '\0';
  5479. *p += len;
  5480. return len ? eof : NULL;
  5481. } else if (filep->access.fp != NULL) {
  5482. return fgets(buf, (int)size, filep->access.fp);
  5483. } else {
  5484. return NULL;
  5485. }
  5486. }
  5487. /* Define the initial recursion depth for procesesing htpasswd files that
  5488. * include other htpasswd
  5489. * (or even the same) files. It is not difficult to provide a file or files
  5490. * s.t. they force civetweb
  5491. * to infinitely recurse and then crash.
  5492. */
  5493. #define INITIAL_DEPTH 9
  5494. #if INITIAL_DEPTH <= 0
  5495. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  5496. #endif
  5497. struct read_auth_file_struct {
  5498. struct mg_connection *conn;
  5499. struct ah ah;
  5500. char *domain;
  5501. char buf[256 + 256 + 40];
  5502. char *f_user;
  5503. char *f_domain;
  5504. char *f_ha1;
  5505. };
  5506. static int
  5507. read_auth_file(struct mg_file *filep,
  5508. struct read_auth_file_struct *workdata,
  5509. int depth)
  5510. {
  5511. char *p;
  5512. int is_authorized = 0;
  5513. struct mg_file fp;
  5514. size_t l;
  5515. if (!filep || !workdata || 0 == depth) {
  5516. return 0;
  5517. }
  5518. /* Loop over passwords file */
  5519. p = (char *)filep->access.membuf;
  5520. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  5521. l = strlen(workdata->buf);
  5522. while (l > 0) {
  5523. if (isspace(workdata->buf[l - 1])
  5524. || iscntrl(workdata->buf[l - 1])) {
  5525. l--;
  5526. workdata->buf[l] = 0;
  5527. } else
  5528. break;
  5529. }
  5530. if (l < 1) {
  5531. continue;
  5532. }
  5533. workdata->f_user = workdata->buf;
  5534. if (workdata->f_user[0] == ':') {
  5535. /* user names may not contain a ':' and may not be empty,
  5536. * so lines starting with ':' may be used for a special purpose */
  5537. if (workdata->f_user[1] == '#') {
  5538. /* :# is a comment */
  5539. continue;
  5540. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  5541. if (mg_fopen(workdata->conn,
  5542. workdata->f_user + 9,
  5543. MG_FOPEN_MODE_READ,
  5544. &fp)) {
  5545. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  5546. (void)mg_fclose(
  5547. &fp.access); /* ignore error on read only file */
  5548. /* No need to continue processing files once we have a
  5549. * match, since nothing will reset it back
  5550. * to 0.
  5551. */
  5552. if (is_authorized) {
  5553. return is_authorized;
  5554. }
  5555. } else {
  5556. mg_cry(workdata->conn,
  5557. "%s: cannot open authorization file: %s",
  5558. __func__,
  5559. workdata->buf);
  5560. }
  5561. continue;
  5562. }
  5563. /* everything is invalid for the moment (might change in the
  5564. * future) */
  5565. mg_cry(workdata->conn,
  5566. "%s: syntax error in authorization file: %s",
  5567. __func__,
  5568. workdata->buf);
  5569. continue;
  5570. }
  5571. workdata->f_domain = strchr(workdata->f_user, ':');
  5572. if (workdata->f_domain == NULL) {
  5573. mg_cry(workdata->conn,
  5574. "%s: syntax error in authorization file: %s",
  5575. __func__,
  5576. workdata->buf);
  5577. continue;
  5578. }
  5579. *(workdata->f_domain) = 0;
  5580. (workdata->f_domain)++;
  5581. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  5582. if (workdata->f_ha1 == NULL) {
  5583. mg_cry(workdata->conn,
  5584. "%s: syntax error in authorization file: %s",
  5585. __func__,
  5586. workdata->buf);
  5587. continue;
  5588. }
  5589. *(workdata->f_ha1) = 0;
  5590. (workdata->f_ha1)++;
  5591. if (!strcmp(workdata->ah.user, workdata->f_user)
  5592. && !strcmp(workdata->domain, workdata->f_domain)) {
  5593. return check_password(workdata->conn->request_info.request_method,
  5594. workdata->f_ha1,
  5595. workdata->ah.uri,
  5596. workdata->ah.nonce,
  5597. workdata->ah.nc,
  5598. workdata->ah.cnonce,
  5599. workdata->ah.qop,
  5600. workdata->ah.response);
  5601. }
  5602. }
  5603. return is_authorized;
  5604. }
  5605. /* Authorize against the opened passwords file. Return 1 if authorized. */
  5606. static int
  5607. authorize(struct mg_connection *conn, struct mg_file *filep)
  5608. {
  5609. struct read_auth_file_struct workdata;
  5610. char buf[MG_BUF_LEN];
  5611. if (!conn || !conn->ctx) {
  5612. return 0;
  5613. }
  5614. memset(&workdata, 0, sizeof(workdata));
  5615. workdata.conn = conn;
  5616. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  5617. return 0;
  5618. }
  5619. workdata.domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  5620. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  5621. }
  5622. /* Return 1 if request is authorised, 0 otherwise. */
  5623. static int
  5624. check_authorization(struct mg_connection *conn, const char *path)
  5625. {
  5626. char fname[PATH_MAX];
  5627. struct vec uri_vec, filename_vec;
  5628. const char *list;
  5629. struct mg_file file = STRUCT_FILE_INITIALIZER;
  5630. int authorized = 1, truncated;
  5631. if (!conn || !conn->ctx) {
  5632. return 0;
  5633. }
  5634. list = conn->ctx->config[PROTECT_URI];
  5635. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  5636. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  5637. mg_snprintf(conn,
  5638. &truncated,
  5639. fname,
  5640. sizeof(fname),
  5641. "%.*s",
  5642. (int)filename_vec.len,
  5643. filename_vec.ptr);
  5644. if (truncated
  5645. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  5646. mg_cry(conn,
  5647. "%s: cannot open %s: %s",
  5648. __func__,
  5649. fname,
  5650. strerror(errno));
  5651. }
  5652. break;
  5653. }
  5654. }
  5655. if (!is_file_opened(&file.access)) {
  5656. open_auth_file(conn, path, &file);
  5657. }
  5658. if (is_file_opened(&file.access)) {
  5659. authorized = authorize(conn, &file);
  5660. (void)mg_fclose(&file.access); /* ignore error on read only file */
  5661. }
  5662. return authorized;
  5663. }
  5664. static void
  5665. send_authorization_request(struct mg_connection *conn)
  5666. {
  5667. char date[64];
  5668. time_t curtime = time(NULL);
  5669. if (conn && conn->ctx) {
  5670. uint64_t nonce = (uint64_t)(conn->ctx->start_time);
  5671. (void)pthread_mutex_lock(&conn->ctx->nonce_mutex);
  5672. nonce += conn->ctx->nonce_count;
  5673. ++conn->ctx->nonce_count;
  5674. (void)pthread_mutex_unlock(&conn->ctx->nonce_mutex);
  5675. nonce ^= conn->ctx->auth_nonce_mask;
  5676. conn->status_code = 401;
  5677. conn->must_close = 1;
  5678. gmt_time_string(date, sizeof(date), &curtime);
  5679. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  5680. send_no_cache_header(conn);
  5681. mg_printf(conn,
  5682. "Date: %s\r\n"
  5683. "Connection: %s\r\n"
  5684. "Content-Length: 0\r\n"
  5685. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  5686. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  5687. date,
  5688. suggest_connection_header(conn),
  5689. conn->ctx->config[AUTHENTICATION_DOMAIN],
  5690. nonce);
  5691. }
  5692. }
  5693. #if !defined(NO_FILES)
  5694. static int
  5695. is_authorized_for_put(struct mg_connection *conn)
  5696. {
  5697. if (conn) {
  5698. struct mg_file file = STRUCT_FILE_INITIALIZER;
  5699. const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
  5700. int ret = 0;
  5701. if (passfile != NULL
  5702. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  5703. ret = authorize(conn, &file);
  5704. (void)mg_fclose(&file.access); /* ignore error on read only file */
  5705. }
  5706. return ret;
  5707. }
  5708. return 0;
  5709. }
  5710. #endif
  5711. int
  5712. mg_modify_passwords_file(const char *fname,
  5713. const char *domain,
  5714. const char *user,
  5715. const char *pass)
  5716. {
  5717. int found, i;
  5718. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  5719. FILE *fp, *fp2;
  5720. found = 0;
  5721. fp = fp2 = NULL;
  5722. /* Regard empty password as no password - remove user record. */
  5723. if (pass != NULL && pass[0] == '\0') {
  5724. pass = NULL;
  5725. }
  5726. /* Other arguments must not be empty */
  5727. if (fname == NULL || domain == NULL || user == NULL) {
  5728. return 0;
  5729. }
  5730. /* Using the given file format, user name and domain must not contain ':'
  5731. */
  5732. if (strchr(user, ':') != NULL) {
  5733. return 0;
  5734. }
  5735. if (strchr(domain, ':') != NULL) {
  5736. return 0;
  5737. }
  5738. /* Do not allow control characters like newline in user name and domain.
  5739. * Do not allow excessively long names either. */
  5740. for (i = 0; i < 255 && user[i] != 0; i++) {
  5741. if (iscntrl(user[i])) {
  5742. return 0;
  5743. }
  5744. }
  5745. if (user[i]) {
  5746. return 0;
  5747. }
  5748. for (i = 0; i < 255 && domain[i] != 0; i++) {
  5749. if (iscntrl(domain[i])) {
  5750. return 0;
  5751. }
  5752. }
  5753. if (domain[i]) {
  5754. return 0;
  5755. }
  5756. /* The maximum length of the path to the password file is limited */
  5757. if ((strlen(fname) + 4) >= PATH_MAX) {
  5758. return 0;
  5759. }
  5760. /* Create a temporary file name. Length has been checked before. */
  5761. strcpy(tmp, fname);
  5762. strcat(tmp, ".tmp");
  5763. /* Create the file if does not exist */
  5764. /* Use of fopen here is OK, since fname is only ASCII */
  5765. if ((fp = fopen(fname, "a+")) != NULL) {
  5766. (void)fclose(fp);
  5767. }
  5768. /* Open the given file and temporary file */
  5769. if ((fp = fopen(fname, "r")) == NULL) {
  5770. return 0;
  5771. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  5772. fclose(fp);
  5773. return 0;
  5774. }
  5775. /* Copy the stuff to temporary file */
  5776. while (fgets(line, sizeof(line), fp) != NULL) {
  5777. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  5778. continue;
  5779. }
  5780. u[255] = 0;
  5781. d[255] = 0;
  5782. if (!strcmp(u, user) && !strcmp(d, domain)) {
  5783. found++;
  5784. if (pass != NULL) {
  5785. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  5786. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  5787. }
  5788. } else {
  5789. fprintf(fp2, "%s", line);
  5790. }
  5791. }
  5792. /* If new user, just add it */
  5793. if (!found && pass != NULL) {
  5794. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  5795. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  5796. }
  5797. /* Close files */
  5798. fclose(fp);
  5799. fclose(fp2);
  5800. /* Put the temp file in place of real file */
  5801. IGNORE_UNUSED_RESULT(remove(fname));
  5802. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  5803. return 1;
  5804. }
  5805. static int
  5806. is_valid_port(unsigned long port)
  5807. {
  5808. return (port <= 0xffff);
  5809. }
  5810. static int
  5811. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  5812. {
  5813. struct addrinfo hints, *res, *ressave;
  5814. int func_ret = 0;
  5815. int gai_ret;
  5816. memset(&hints, 0, sizeof(struct addrinfo));
  5817. hints.ai_family = af;
  5818. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  5819. if (gai_ret != 0) {
  5820. /* gai_strerror could be used to convert gai_ret to a string */
  5821. /* POSIX return values: see
  5822. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  5823. */
  5824. /* Windows return values: see
  5825. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  5826. */
  5827. return 0;
  5828. }
  5829. ressave = res;
  5830. while (res) {
  5831. if (dstlen >= res->ai_addrlen) {
  5832. memcpy(dst, res->ai_addr, res->ai_addrlen);
  5833. func_ret = 1;
  5834. }
  5835. res = res->ai_next;
  5836. }
  5837. freeaddrinfo(ressave);
  5838. return func_ret;
  5839. }
  5840. static int
  5841. connect_socket(struct mg_context *ctx /* may be NULL */,
  5842. const char *host,
  5843. int port,
  5844. int use_ssl,
  5845. char *ebuf,
  5846. size_t ebuf_len,
  5847. SOCKET *sock /* output: socket, must not be NULL */,
  5848. union usa *sa /* output: socket address, must not be NULL */
  5849. )
  5850. {
  5851. int ip_ver = 0;
  5852. *sock = INVALID_SOCKET;
  5853. memset(sa, 0, sizeof(*sa));
  5854. if (ebuf_len > 0) {
  5855. *ebuf = 0;
  5856. }
  5857. if (host == NULL) {
  5858. mg_snprintf(NULL,
  5859. NULL, /* No truncation check for ebuf */
  5860. ebuf,
  5861. ebuf_len,
  5862. "%s",
  5863. "NULL host");
  5864. return 0;
  5865. }
  5866. if (port <= 0 || !is_valid_port((unsigned)port)) {
  5867. mg_snprintf(NULL,
  5868. NULL, /* No truncation check for ebuf */
  5869. ebuf,
  5870. ebuf_len,
  5871. "%s",
  5872. "invalid port");
  5873. return 0;
  5874. }
  5875. #if !defined(NO_SSL)
  5876. #if !defined(NO_SSL_DL)
  5877. #ifdef OPENSSL_API_1_1
  5878. if (use_ssl && (TLS_client_method == NULL)) {
  5879. mg_snprintf(NULL,
  5880. NULL, /* No truncation check for ebuf */
  5881. ebuf,
  5882. ebuf_len,
  5883. "%s",
  5884. "SSL is not initialized");
  5885. return 0;
  5886. }
  5887. #else
  5888. if (use_ssl && (SSLv23_client_method == NULL)) {
  5889. mg_snprintf(NULL,
  5890. NULL, /* No truncation check for ebuf */
  5891. ebuf,
  5892. ebuf_len,
  5893. "%s",
  5894. "SSL is not initialized");
  5895. return 0;
  5896. }
  5897. #endif /* OPENSSL_API_1_1 */
  5898. #else
  5899. (void)use_ssl;
  5900. #endif /* NO_SSL_DL */
  5901. #else
  5902. (void)use_ssl;
  5903. #endif /* !defined(NO_SSL) */
  5904. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  5905. sa->sin.sin_port = htons((uint16_t)port);
  5906. ip_ver = 4;
  5907. #ifdef USE_IPV6
  5908. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  5909. sa->sin6.sin6_port = htons((uint16_t)port);
  5910. ip_ver = 6;
  5911. } else if (host[0] == '[') {
  5912. /* While getaddrinfo on Windows will work with [::1],
  5913. * getaddrinfo on Linux only works with ::1 (without []). */
  5914. size_t l = strlen(host + 1);
  5915. char *h = (l > 1) ? mg_strdup(host + 1) : NULL;
  5916. if (h) {
  5917. h[l - 1] = 0;
  5918. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  5919. sa->sin6.sin6_port = htons((uint16_t)port);
  5920. ip_ver = 6;
  5921. }
  5922. mg_free(h);
  5923. }
  5924. #endif
  5925. }
  5926. if (ip_ver == 0) {
  5927. mg_snprintf(NULL,
  5928. NULL, /* No truncation check for ebuf */
  5929. ebuf,
  5930. ebuf_len,
  5931. "%s",
  5932. "host not found");
  5933. return 0;
  5934. }
  5935. if (ip_ver == 4) {
  5936. *sock = socket(PF_INET, SOCK_STREAM, 0);
  5937. }
  5938. #ifdef USE_IPV6
  5939. else if (ip_ver == 6) {
  5940. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  5941. }
  5942. #endif
  5943. if (*sock == INVALID_SOCKET) {
  5944. mg_snprintf(NULL,
  5945. NULL, /* No truncation check for ebuf */
  5946. ebuf,
  5947. ebuf_len,
  5948. "socket(): %s",
  5949. strerror(ERRNO));
  5950. return 0;
  5951. }
  5952. set_close_on_exec(*sock, fc(ctx));
  5953. if ((ip_ver == 4)
  5954. && (connect(*sock, (struct sockaddr *)&sa->sin, sizeof(sa->sin))
  5955. == 0)) {
  5956. /* connected with IPv4 */
  5957. set_blocking_mode(*sock, 0);
  5958. return 1;
  5959. }
  5960. #ifdef USE_IPV6
  5961. if ((ip_ver == 6)
  5962. && (connect(*sock, (struct sockaddr *)&sa->sin6, sizeof(sa->sin6))
  5963. == 0)) {
  5964. /* connected with IPv6 */
  5965. set_blocking_mode(*sock, 0);
  5966. return 1;
  5967. }
  5968. #endif
  5969. /* Not connected */
  5970. mg_snprintf(NULL,
  5971. NULL, /* No truncation check for ebuf */
  5972. ebuf,
  5973. ebuf_len,
  5974. "connect(%s:%d): %s",
  5975. host,
  5976. port,
  5977. strerror(ERRNO));
  5978. closesocket(*sock);
  5979. *sock = INVALID_SOCKET;
  5980. return 0;
  5981. }
  5982. int
  5983. mg_url_encode(const char *src, char *dst, size_t dst_len)
  5984. {
  5985. static const char *dont_escape = "._-$,;~()";
  5986. static const char *hex = "0123456789abcdef";
  5987. char *pos = dst;
  5988. const char *end = dst + dst_len - 1;
  5989. for (; *src != '\0' && pos < end; src++, pos++) {
  5990. if (isalnum(*(const unsigned char *)src)
  5991. || strchr(dont_escape, *(const unsigned char *)src) != NULL) {
  5992. *pos = *src;
  5993. } else if (pos + 2 < end) {
  5994. pos[0] = '%';
  5995. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  5996. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  5997. pos += 2;
  5998. } else {
  5999. break;
  6000. }
  6001. }
  6002. *pos = '\0';
  6003. return (*src == '\0') ? (int)(pos - dst) : -1;
  6004. }
  6005. static void
  6006. print_dir_entry(struct de *de)
  6007. {
  6008. char size[64], mod[64], href[PATH_MAX * 3 /* worst case */];
  6009. struct tm *tm;
  6010. if (de->file.is_directory) {
  6011. mg_snprintf(de->conn,
  6012. NULL, /* Buffer is big enough */
  6013. size,
  6014. sizeof(size),
  6015. "%s",
  6016. "[DIRECTORY]");
  6017. } else {
  6018. /* We use (signed) cast below because MSVC 6 compiler cannot
  6019. * convert unsigned __int64 to double. Sigh. */
  6020. if (de->file.size < 1024) {
  6021. mg_snprintf(de->conn,
  6022. NULL, /* Buffer is big enough */
  6023. size,
  6024. sizeof(size),
  6025. "%d",
  6026. (int)de->file.size);
  6027. } else if (de->file.size < 0x100000) {
  6028. mg_snprintf(de->conn,
  6029. NULL, /* Buffer is big enough */
  6030. size,
  6031. sizeof(size),
  6032. "%.1fk",
  6033. (double)de->file.size / 1024.0);
  6034. } else if (de->file.size < 0x40000000) {
  6035. mg_snprintf(de->conn,
  6036. NULL, /* Buffer is big enough */
  6037. size,
  6038. sizeof(size),
  6039. "%.1fM",
  6040. (double)de->file.size / 1048576);
  6041. } else {
  6042. mg_snprintf(de->conn,
  6043. NULL, /* Buffer is big enough */
  6044. size,
  6045. sizeof(size),
  6046. "%.1fG",
  6047. (double)de->file.size / 1073741824);
  6048. }
  6049. }
  6050. /* Note: mg_snprintf will not cause a buffer overflow above.
  6051. * So, string truncation checks are not required here. */
  6052. tm = localtime(&de->file.last_modified);
  6053. if (tm != NULL) {
  6054. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  6055. } else {
  6056. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  6057. mod[sizeof(mod) - 1] = '\0';
  6058. }
  6059. mg_url_encode(de->file_name, href, sizeof(href));
  6060. de->conn->num_bytes_sent +=
  6061. mg_printf(de->conn,
  6062. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  6063. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  6064. de->conn->request_info.local_uri,
  6065. href,
  6066. de->file.is_directory ? "/" : "",
  6067. de->file_name,
  6068. de->file.is_directory ? "/" : "",
  6069. mod,
  6070. size);
  6071. }
  6072. /* This function is called from send_directory() and used for
  6073. * sorting directory entries by size, or name, or modification time.
  6074. * On windows, __cdecl specification is needed in case if project is built
  6075. * with __stdcall convention. qsort always requires __cdels callback. */
  6076. static int WINCDECL
  6077. compare_dir_entries(const void *p1, const void *p2)
  6078. {
  6079. if (p1 && p2) {
  6080. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  6081. const char *query_string = a->conn->request_info.query_string;
  6082. int cmp_result = 0;
  6083. if (query_string == NULL) {
  6084. query_string = "na";
  6085. }
  6086. if (a->file.is_directory && !b->file.is_directory) {
  6087. return -1; /* Always put directories on top */
  6088. } else if (!a->file.is_directory && b->file.is_directory) {
  6089. return 1; /* Always put directories on top */
  6090. } else if (*query_string == 'n') {
  6091. cmp_result = strcmp(a->file_name, b->file_name);
  6092. } else if (*query_string == 's') {
  6093. cmp_result = (a->file.size == b->file.size)
  6094. ? 0
  6095. : ((a->file.size > b->file.size) ? 1 : -1);
  6096. } else if (*query_string == 'd') {
  6097. cmp_result =
  6098. (a->file.last_modified == b->file.last_modified)
  6099. ? 0
  6100. : ((a->file.last_modified > b->file.last_modified) ? 1
  6101. : -1);
  6102. }
  6103. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  6104. }
  6105. return 0;
  6106. }
  6107. static int
  6108. must_hide_file(struct mg_connection *conn, const char *path)
  6109. {
  6110. if (conn && conn->ctx) {
  6111. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  6112. const char *pattern = conn->ctx->config[HIDE_FILES];
  6113. return match_prefix(pw_pattern, strlen(pw_pattern), path) > 0
  6114. || (pattern != NULL
  6115. && match_prefix(pattern, strlen(pattern), path) > 0);
  6116. }
  6117. return 0;
  6118. }
  6119. static int
  6120. scan_directory(struct mg_connection *conn,
  6121. const char *dir,
  6122. void *data,
  6123. void (*cb)(struct de *, void *))
  6124. {
  6125. char path[PATH_MAX];
  6126. struct dirent *dp;
  6127. DIR *dirp;
  6128. struct de de;
  6129. int truncated;
  6130. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  6131. return 0;
  6132. } else {
  6133. de.conn = conn;
  6134. while ((dp = mg_readdir(dirp)) != NULL) {
  6135. /* Do not show current dir and hidden files */
  6136. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  6137. || must_hide_file(conn, dp->d_name)) {
  6138. continue;
  6139. }
  6140. mg_snprintf(
  6141. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  6142. /* If we don't memset stat structure to zero, mtime will have
  6143. * garbage and strftime() will segfault later on in
  6144. * print_dir_entry(). memset is required only if mg_stat()
  6145. * fails. For more details, see
  6146. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  6147. memset(&de.file, 0, sizeof(de.file));
  6148. if (truncated) {
  6149. /* If the path is not complete, skip processing. */
  6150. continue;
  6151. }
  6152. if (!mg_stat(conn, path, &de.file)) {
  6153. mg_cry(conn,
  6154. "%s: mg_stat(%s) failed: %s",
  6155. __func__,
  6156. path,
  6157. strerror(ERRNO));
  6158. }
  6159. de.file_name = dp->d_name;
  6160. cb(&de, data);
  6161. }
  6162. (void)mg_closedir(dirp);
  6163. }
  6164. return 1;
  6165. }
  6166. #if !defined(NO_FILES)
  6167. static int
  6168. remove_directory(struct mg_connection *conn, const char *dir)
  6169. {
  6170. char path[PATH_MAX];
  6171. struct dirent *dp;
  6172. DIR *dirp;
  6173. struct de de;
  6174. int truncated;
  6175. int ok = 1;
  6176. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  6177. return 0;
  6178. } else {
  6179. de.conn = conn;
  6180. while ((dp = mg_readdir(dirp)) != NULL) {
  6181. /* Do not show current dir (but show hidden files as they will
  6182. * also be removed) */
  6183. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  6184. continue;
  6185. }
  6186. mg_snprintf(
  6187. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  6188. /* If we don't memset stat structure to zero, mtime will have
  6189. * garbage and strftime() will segfault later on in
  6190. * print_dir_entry(). memset is required only if mg_stat()
  6191. * fails. For more details, see
  6192. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  6193. memset(&de.file, 0, sizeof(de.file));
  6194. if (truncated) {
  6195. /* Do not delete anything shorter */
  6196. ok = 0;
  6197. continue;
  6198. }
  6199. if (!mg_stat(conn, path, &de.file)) {
  6200. mg_cry(conn,
  6201. "%s: mg_stat(%s) failed: %s",
  6202. __func__,
  6203. path,
  6204. strerror(ERRNO));
  6205. ok = 0;
  6206. }
  6207. if (de.file.is_directory) {
  6208. if (remove_directory(conn, path) == 0) {
  6209. ok = 0;
  6210. }
  6211. } else {
  6212. /* This will fail file is the file is in memory */
  6213. if (mg_remove(conn, path) == 0) {
  6214. ok = 0;
  6215. }
  6216. }
  6217. }
  6218. (void)mg_closedir(dirp);
  6219. IGNORE_UNUSED_RESULT(rmdir(dir));
  6220. }
  6221. return ok;
  6222. }
  6223. #endif
  6224. struct dir_scan_data {
  6225. struct de *entries;
  6226. unsigned int num_entries;
  6227. unsigned int arr_size;
  6228. };
  6229. /* Behaves like realloc(), but frees original pointer on failure */
  6230. static void *
  6231. realloc2(void *ptr, size_t size)
  6232. {
  6233. void *new_ptr = mg_realloc(ptr, size);
  6234. if (new_ptr == NULL) {
  6235. mg_free(ptr);
  6236. }
  6237. return new_ptr;
  6238. }
  6239. static void
  6240. dir_scan_callback(struct de *de, void *data)
  6241. {
  6242. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  6243. if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {
  6244. dsd->arr_size *= 2;
  6245. dsd->entries =
  6246. (struct de *)realloc2(dsd->entries,
  6247. dsd->arr_size * sizeof(dsd->entries[0]));
  6248. }
  6249. if (dsd->entries == NULL) {
  6250. /* TODO(lsm, low): propagate an error to the caller */
  6251. dsd->num_entries = 0;
  6252. } else {
  6253. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  6254. dsd->entries[dsd->num_entries].file = de->file;
  6255. dsd->entries[dsd->num_entries].conn = de->conn;
  6256. dsd->num_entries++;
  6257. }
  6258. }
  6259. static void
  6260. handle_directory_request(struct mg_connection *conn, const char *dir)
  6261. {
  6262. unsigned int i;
  6263. int sort_direction;
  6264. struct dir_scan_data data = {NULL, 0, 128};
  6265. char date[64];
  6266. time_t curtime = time(NULL);
  6267. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  6268. send_http_error(conn,
  6269. 500,
  6270. "Error: Cannot open directory\nopendir(%s): %s",
  6271. dir,
  6272. strerror(ERRNO));
  6273. return;
  6274. }
  6275. gmt_time_string(date, sizeof(date), &curtime);
  6276. if (!conn) {
  6277. return;
  6278. }
  6279. sort_direction = ((conn->request_info.query_string != NULL)
  6280. && (conn->request_info.query_string[1] == 'd'))
  6281. ? 'a'
  6282. : 'd';
  6283. conn->must_close = 1;
  6284. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  6285. send_static_cache_header(conn);
  6286. mg_printf(conn,
  6287. "Date: %s\r\n"
  6288. "Connection: close\r\n"
  6289. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  6290. date);
  6291. conn->num_bytes_sent +=
  6292. mg_printf(conn,
  6293. "<html><head><title>Index of %s</title>"
  6294. "<style>th {text-align: left;}</style></head>"
  6295. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  6296. "<tr><th><a href=\"?n%c\">Name</a></th>"
  6297. "<th><a href=\"?d%c\">Modified</a></th>"
  6298. "<th><a href=\"?s%c\">Size</a></th></tr>"
  6299. "<tr><td colspan=\"3\"><hr></td></tr>",
  6300. conn->request_info.local_uri,
  6301. conn->request_info.local_uri,
  6302. sort_direction,
  6303. sort_direction,
  6304. sort_direction);
  6305. /* Print first entry - link to a parent directory */
  6306. conn->num_bytes_sent +=
  6307. mg_printf(conn,
  6308. "<tr><td><a href=\"%s%s\">%s</a></td>"
  6309. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  6310. conn->request_info.local_uri,
  6311. "..",
  6312. "Parent directory",
  6313. "-",
  6314. "-");
  6315. /* Sort and print directory entries */
  6316. if (data.entries != NULL) {
  6317. qsort(data.entries,
  6318. (size_t)data.num_entries,
  6319. sizeof(data.entries[0]),
  6320. compare_dir_entries);
  6321. for (i = 0; i < data.num_entries; i++) {
  6322. print_dir_entry(&data.entries[i]);
  6323. mg_free(data.entries[i].file_name);
  6324. }
  6325. mg_free(data.entries);
  6326. }
  6327. conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");
  6328. conn->status_code = 200;
  6329. }
  6330. /* Send len bytes from the opened file to the client. */
  6331. static void
  6332. send_file_data(struct mg_connection *conn,
  6333. struct mg_file *filep,
  6334. int64_t offset,
  6335. int64_t len)
  6336. {
  6337. char buf[MG_BUF_LEN];
  6338. int to_read, num_read, num_written;
  6339. int64_t size;
  6340. if (!filep || !conn) {
  6341. return;
  6342. }
  6343. /* Sanity check the offset */
  6344. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  6345. : (int64_t)(filep->stat.size);
  6346. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  6347. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  6348. /* file stored in memory */
  6349. if (len > size - offset) {
  6350. len = size - offset;
  6351. }
  6352. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  6353. } else if (len > 0 && filep->access.fp != NULL) {
  6354. /* file stored on disk */
  6355. #if defined(__linux__)
  6356. /* sendfile is only available for Linux */
  6357. if ((conn->ssl == 0) && (conn->throttle == 0)
  6358. && (!mg_strcasecmp(conn->ctx->config[ALLOW_SENDFILE_CALL],
  6359. "yes"))) {
  6360. off_t sf_offs = (off_t)offset;
  6361. ssize_t sf_sent;
  6362. int sf_file = fileno(filep->access.fp);
  6363. int loop_cnt = 0;
  6364. do {
  6365. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  6366. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  6367. size_t sf_tosend =
  6368. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  6369. sf_sent =
  6370. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  6371. if (sf_sent > 0) {
  6372. conn->num_bytes_sent += sf_sent;
  6373. len -= sf_sent;
  6374. offset += sf_sent;
  6375. } else if (loop_cnt == 0) {
  6376. /* This file can not be sent using sendfile.
  6377. * This might be the case for pseudo-files in the
  6378. * /sys/ and /proc/ file system.
  6379. * Use the regular user mode copy code instead. */
  6380. break;
  6381. } else if (sf_sent == 0) {
  6382. /* No error, but 0 bytes sent. May be EOF? */
  6383. return;
  6384. }
  6385. loop_cnt++;
  6386. } while ((len > 0) && (sf_sent >= 0));
  6387. if (sf_sent > 0) {
  6388. return; /* OK */
  6389. }
  6390. /* sf_sent<0 means error, thus fall back to the classic way */
  6391. /* This is always the case, if sf_file is not a "normal" file,
  6392. * e.g., for sending data from the output of a CGI process. */
  6393. offset = (int64_t)sf_offs;
  6394. }
  6395. #endif
  6396. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  6397. mg_cry(conn, "%s: fseeko() failed: %s", __func__, strerror(ERRNO));
  6398. send_http_error(
  6399. conn,
  6400. 500,
  6401. "%s",
  6402. "Error: Unable to access file at requested position.");
  6403. } else {
  6404. while (len > 0) {
  6405. /* Calculate how much to read from the file in the buffer */
  6406. to_read = sizeof(buf);
  6407. if ((int64_t)to_read > len) {
  6408. to_read = (int)len;
  6409. }
  6410. /* Read from file, exit the loop on error */
  6411. if ((num_read =
  6412. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  6413. <= 0) {
  6414. break;
  6415. }
  6416. /* Send read bytes to the client, exit the loop on error */
  6417. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  6418. != num_read) {
  6419. break;
  6420. }
  6421. /* Both read and were successful, adjust counters */
  6422. conn->num_bytes_sent += num_written;
  6423. len -= num_written;
  6424. }
  6425. }
  6426. }
  6427. }
  6428. static int
  6429. parse_range_header(const char *header, int64_t *a, int64_t *b)
  6430. {
  6431. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  6432. }
  6433. static void
  6434. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  6435. {
  6436. if (filestat != NULL && buf != NULL) {
  6437. mg_snprintf(NULL,
  6438. NULL, /* All calls to construct_etag use 64 byte buffer */
  6439. buf,
  6440. buf_len,
  6441. "\"%lx.%" INT64_FMT "\"",
  6442. (unsigned long)filestat->last_modified,
  6443. filestat->size);
  6444. }
  6445. }
  6446. static void
  6447. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  6448. {
  6449. if (filep != NULL && filep->fp != NULL) {
  6450. #ifdef _WIN32
  6451. (void)conn; /* Unused. */
  6452. #else
  6453. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  6454. mg_cry(conn,
  6455. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  6456. __func__,
  6457. strerror(ERRNO));
  6458. }
  6459. #endif
  6460. }
  6461. }
  6462. static void
  6463. handle_static_file_request(struct mg_connection *conn,
  6464. const char *path,
  6465. struct mg_file *filep,
  6466. const char *mime_type,
  6467. const char *additional_headers)
  6468. {
  6469. char date[64], lm[64], etag[64];
  6470. char range[128]; /* large enough, so there will be no overflow */
  6471. const char *msg = "OK", *hdr;
  6472. time_t curtime = time(NULL);
  6473. int64_t cl, r1, r2;
  6474. struct vec mime_vec;
  6475. int n, truncated;
  6476. char gz_path[PATH_MAX];
  6477. const char *encoding = "";
  6478. const char *cors1, *cors2, *cors3;
  6479. if (conn == NULL || conn->ctx == NULL || filep == NULL) {
  6480. return;
  6481. }
  6482. if (mime_type == NULL) {
  6483. get_mime_type(conn->ctx, path, &mime_vec);
  6484. } else {
  6485. mime_vec.ptr = mime_type;
  6486. mime_vec.len = strlen(mime_type);
  6487. }
  6488. if (filep->stat.size > INT64_MAX) {
  6489. send_http_error(conn,
  6490. 500,
  6491. "Error: File size is too large to send\n%" INT64_FMT,
  6492. filep->stat.size);
  6493. }
  6494. cl = (int64_t)filep->stat.size;
  6495. conn->status_code = 200;
  6496. range[0] = '\0';
  6497. /* if this file is in fact a pre-gzipped file, rewrite its filename
  6498. * it's important to rewrite the filename after resolving
  6499. * the mime type from it, to preserve the actual file's type */
  6500. if (filep->stat.is_gzipped) {
  6501. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  6502. if (truncated) {
  6503. send_http_error(conn,
  6504. 500,
  6505. "Error: Path of zipped file too long (%s)",
  6506. path);
  6507. return;
  6508. }
  6509. path = gz_path;
  6510. encoding = "Content-Encoding: gzip\r\n";
  6511. }
  6512. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  6513. send_http_error(conn,
  6514. 500,
  6515. "Error: Cannot open file\nfopen(%s): %s",
  6516. path,
  6517. strerror(ERRNO));
  6518. return;
  6519. }
  6520. fclose_on_exec(&filep->access, conn);
  6521. /* If Range: header specified, act accordingly */
  6522. r1 = r2 = 0;
  6523. hdr = mg_get_header(conn, "Range");
  6524. if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 && r1 >= 0
  6525. && r2 >= 0) {
  6526. /* actually, range requests don't play well with a pre-gzipped
  6527. * file (since the range is specified in the uncompressed space) */
  6528. if (filep->stat.is_gzipped) {
  6529. send_http_error(
  6530. conn,
  6531. 501,
  6532. "%s",
  6533. "Error: Range requests in gzipped files are not supported");
  6534. (void)mg_fclose(
  6535. &filep->access); /* ignore error on read only file */
  6536. return;
  6537. }
  6538. conn->status_code = 206;
  6539. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  6540. mg_snprintf(conn,
  6541. NULL, /* range buffer is big enough */
  6542. range,
  6543. sizeof(range),
  6544. "Content-Range: bytes "
  6545. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  6546. r1,
  6547. r1 + cl - 1,
  6548. filep->stat.size);
  6549. msg = "Partial Content";
  6550. }
  6551. hdr = mg_get_header(conn, "Origin");
  6552. if (hdr) {
  6553. /* Cross-origin resource sharing (CORS), see
  6554. * http://www.html5rocks.com/en/tutorials/cors/,
  6555. * http://www.html5rocks.com/static/images/cors_server_flowchart.png -
  6556. * preflight is not supported for files. */
  6557. cors1 = "Access-Control-Allow-Origin: ";
  6558. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  6559. cors3 = "\r\n";
  6560. } else {
  6561. cors1 = cors2 = cors3 = "";
  6562. }
  6563. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
  6564. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  6565. gmt_time_string(date, sizeof(date), &curtime);
  6566. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  6567. construct_etag(etag, sizeof(etag), &filep->stat);
  6568. (void)mg_printf(conn,
  6569. "HTTP/1.1 %d %s\r\n"
  6570. "%s%s%s"
  6571. "Date: %s\r\n",
  6572. conn->status_code,
  6573. msg,
  6574. cors1,
  6575. cors2,
  6576. cors3,
  6577. date);
  6578. send_static_cache_header(conn);
  6579. (void)mg_printf(conn,
  6580. "Last-Modified: %s\r\n"
  6581. "Etag: %s\r\n"
  6582. "Content-Type: %.*s\r\n"
  6583. "Content-Length: %" INT64_FMT "\r\n"
  6584. "Connection: %s\r\n"
  6585. "Accept-Ranges: bytes\r\n"
  6586. "%s%s",
  6587. lm,
  6588. etag,
  6589. (int)mime_vec.len,
  6590. mime_vec.ptr,
  6591. cl,
  6592. suggest_connection_header(conn),
  6593. range,
  6594. encoding);
  6595. /* The previous code must not add any header starting with X- to make
  6596. * sure no one of the additional_headers is included twice */
  6597. if (additional_headers != NULL) {
  6598. (void)mg_printf(conn,
  6599. "%.*s\r\n\r\n",
  6600. (int)strlen(additional_headers),
  6601. additional_headers);
  6602. } else {
  6603. (void)mg_printf(conn, "\r\n");
  6604. }
  6605. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  6606. send_file_data(conn, filep, r1, cl);
  6607. }
  6608. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  6609. }
  6610. #if !defined(NO_CACHING)
  6611. static void
  6612. handle_not_modified_static_file_request(struct mg_connection *conn,
  6613. struct mg_file *filep)
  6614. {
  6615. char date[64], lm[64], etag[64];
  6616. time_t curtime = time(NULL);
  6617. if (conn == NULL || filep == NULL) {
  6618. return;
  6619. }
  6620. conn->status_code = 304;
  6621. gmt_time_string(date, sizeof(date), &curtime);
  6622. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  6623. construct_etag(etag, sizeof(etag), &filep->stat);
  6624. (void)mg_printf(conn,
  6625. "HTTP/1.1 %d %s\r\n"
  6626. "Date: %s\r\n",
  6627. conn->status_code,
  6628. mg_get_response_code_text(conn, conn->status_code),
  6629. date);
  6630. send_static_cache_header(conn);
  6631. (void)mg_printf(conn,
  6632. "Last-Modified: %s\r\n"
  6633. "Etag: %s\r\n"
  6634. "Connection: %s\r\n"
  6635. "\r\n",
  6636. lm,
  6637. etag,
  6638. suggest_connection_header(conn));
  6639. }
  6640. #endif
  6641. void
  6642. mg_send_file(struct mg_connection *conn, const char *path)
  6643. {
  6644. mg_send_mime_file(conn, path, NULL);
  6645. }
  6646. void
  6647. mg_send_mime_file(struct mg_connection *conn,
  6648. const char *path,
  6649. const char *mime_type)
  6650. {
  6651. mg_send_mime_file2(conn, path, mime_type, NULL);
  6652. }
  6653. void
  6654. mg_send_mime_file2(struct mg_connection *conn,
  6655. const char *path,
  6656. const char *mime_type,
  6657. const char *additional_headers)
  6658. {
  6659. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6660. if (mg_stat(conn, path, &file.stat)) {
  6661. if (file.stat.is_directory) {
  6662. if (!conn) {
  6663. return;
  6664. }
  6665. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  6666. "yes")) {
  6667. handle_directory_request(conn, path);
  6668. } else {
  6669. send_http_error(conn,
  6670. 403,
  6671. "%s",
  6672. "Error: Directory listing denied");
  6673. }
  6674. } else {
  6675. handle_static_file_request(
  6676. conn, path, &file, mime_type, additional_headers);
  6677. }
  6678. } else {
  6679. send_http_error(conn, 404, "%s", "Error: File not found");
  6680. }
  6681. }
  6682. /* For a given PUT path, create all intermediate subdirectories.
  6683. * Return 0 if the path itself is a directory.
  6684. * Return 1 if the path leads to a file.
  6685. * Return -1 for if the path is too long.
  6686. * Return -2 if path can not be created.
  6687. */
  6688. static int
  6689. put_dir(struct mg_connection *conn, const char *path)
  6690. {
  6691. char buf[PATH_MAX];
  6692. const char *s, *p;
  6693. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6694. size_t len;
  6695. int res = 1;
  6696. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  6697. len = (size_t)(p - path);
  6698. if (len >= sizeof(buf)) {
  6699. /* path too long */
  6700. res = -1;
  6701. break;
  6702. }
  6703. memcpy(buf, path, len);
  6704. buf[len] = '\0';
  6705. /* Try to create intermediate directory */
  6706. DEBUG_TRACE("mkdir(%s)", buf);
  6707. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  6708. /* path does not exixt and can not be created */
  6709. res = -2;
  6710. break;
  6711. }
  6712. /* Is path itself a directory? */
  6713. if (p[1] == '\0') {
  6714. res = 0;
  6715. }
  6716. }
  6717. return res;
  6718. }
  6719. static void
  6720. remove_bad_file(const struct mg_connection *conn, const char *path)
  6721. {
  6722. int r = mg_remove(conn, path);
  6723. if (r != 0) {
  6724. mg_cry(conn, "%s: Cannot remove invalid file %s", __func__, path);
  6725. }
  6726. }
  6727. long long
  6728. mg_store_body(struct mg_connection *conn, const char *path)
  6729. {
  6730. char buf[MG_BUF_LEN];
  6731. long long len = 0;
  6732. int ret, n;
  6733. struct mg_file fi;
  6734. if (conn->consumed_content != 0) {
  6735. mg_cry(conn, "%s: Contents already consumed", __func__);
  6736. return -11;
  6737. }
  6738. ret = put_dir(conn, path);
  6739. if (ret < 0) {
  6740. /* -1 for path too long,
  6741. * -2 for path can not be created. */
  6742. return ret;
  6743. }
  6744. if (ret != 1) {
  6745. /* Return 0 means, path itself is a directory. */
  6746. return 0;
  6747. }
  6748. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  6749. return -12;
  6750. }
  6751. ret = mg_read(conn, buf, sizeof(buf));
  6752. while (ret > 0) {
  6753. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  6754. if (n != ret) {
  6755. (void)mg_fclose(
  6756. &fi.access); /* File is bad and will be removed anyway. */
  6757. remove_bad_file(conn, path);
  6758. return -13;
  6759. }
  6760. ret = mg_read(conn, buf, sizeof(buf));
  6761. }
  6762. /* File is open for writing. If fclose fails, there was probably an
  6763. * error flushing the buffer to disk, so the file on disk might be
  6764. * broken. Delete it and return an error to the caller. */
  6765. if (mg_fclose(&fi.access) != 0) {
  6766. remove_bad_file(conn, path);
  6767. return -14;
  6768. }
  6769. return len;
  6770. }
  6771. /* Parse HTTP headers from the given buffer, advance buf pointer
  6772. * to the point where parsing stopped.
  6773. * All parameters must be valid pointers (not NULL).
  6774. * Return <0 on error. */
  6775. static int
  6776. parse_http_headers(char **buf, struct mg_request_info *ri)
  6777. {
  6778. int i;
  6779. ri->num_headers = 0;
  6780. for (i = 0; i < (int)ARRAY_SIZE(ri->http_headers); i++) {
  6781. char *dp = *buf;
  6782. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  6783. dp++;
  6784. }
  6785. if (dp == *buf) {
  6786. /* End of headers reached. */
  6787. break;
  6788. }
  6789. if (*dp != ':') {
  6790. /* This is not a valid field. */
  6791. return -1;
  6792. }
  6793. /* End of header key (*dp == ':') */
  6794. /* Truncate here and set the key name */
  6795. *dp = 0;
  6796. ri->http_headers[i].name = *buf;
  6797. do {
  6798. dp++;
  6799. } while (*dp == ' ');
  6800. /* The rest of the line is the value */
  6801. ri->http_headers[i].value = dp;
  6802. *buf = dp + strcspn(dp, "\r\n");
  6803. if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) {
  6804. *buf = NULL;
  6805. }
  6806. ri->num_headers = i + 1;
  6807. if (*buf) {
  6808. (*buf)[0] = 0;
  6809. (*buf)[1] = 0;
  6810. *buf += 2;
  6811. } else {
  6812. *buf = dp;
  6813. break;
  6814. }
  6815. if ((*buf)[0] == '\r') {
  6816. /* This is the end of the header */
  6817. break;
  6818. }
  6819. }
  6820. return ri->num_headers;
  6821. }
  6822. static int
  6823. is_valid_http_method(const char *method)
  6824. {
  6825. return !strcmp(method, "GET") /* HTTP (RFC 2616) */
  6826. || !strcmp(method, "POST") /* HTTP (RFC 2616) */
  6827. || !strcmp(method, "HEAD") /* HTTP (RFC 2616) */
  6828. || !strcmp(method, "PUT") /* HTTP (RFC 2616) */
  6829. || !strcmp(method, "DELETE") /* HTTP (RFC 2616) */
  6830. || !strcmp(method, "OPTIONS") /* HTTP (RFC 2616) */
  6831. /* TRACE method (RFC 2616) is not supported for security reasons */
  6832. || !strcmp(method, "CONNECT") /* HTTP (RFC 2616) */
  6833. || !strcmp(method, "PROPFIND") /* WEBDAV (RFC 2518) */
  6834. || !strcmp(method, "MKCOL") /* WEBDAV (RFC 2518) */
  6835. /* Unsupported WEBDAV Methods: */
  6836. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  6837. /* + 11 methods from RFC 3253 */
  6838. /* ORDERPATCH (RFC 3648) */
  6839. /* ACL (RFC 3744) */
  6840. /* SEARCH (RFC 5323) */
  6841. /* + MicroSoft extensions
  6842. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  6843. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  6844. || !strcmp(method, "PATCH"); /* PATCH method (RFC 5789) */
  6845. }
  6846. /* Parse HTTP request, fill in mg_request_info structure.
  6847. * This function modifies the buffer by NUL-terminating
  6848. * HTTP request components, header names and header values.
  6849. * Parameters:
  6850. * buf (in/out): pointer to the HTTP header to parse and split
  6851. * len (in): length of HTTP header buffer
  6852. * re (out): parsed header as mg_request_info
  6853. * buf and ri must be valid pointers (not NULL), len>0.
  6854. * Returns <0 on error. */
  6855. static int
  6856. parse_http_message(char *buf, int len, struct mg_request_info *ri)
  6857. {
  6858. int is_request, request_length;
  6859. char *start_line;
  6860. request_length = get_request_len(buf, len);
  6861. if (request_length > 0) {
  6862. /* Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_addr,
  6863. * remote_port */
  6864. ri->remote_user = ri->request_method = ri->request_uri =
  6865. ri->http_version = NULL;
  6866. ri->num_headers = 0;
  6867. buf[request_length - 1] = '\0';
  6868. /* RFC says that all initial whitespaces should be ingored */
  6869. while (*buf != '\0' && isspace(*(unsigned char *)buf)) {
  6870. buf++;
  6871. }
  6872. start_line = skip(&buf, "\r\n");
  6873. ri->request_method = skip(&start_line, " ");
  6874. ri->request_uri = skip(&start_line, " ");
  6875. ri->http_version = start_line;
  6876. /* HTTP message could be either HTTP request:
  6877. * "GET / HTTP/1.0 ..."
  6878. * or a HTTP response:
  6879. * "HTTP/1.0 200 OK ..."
  6880. * otherwise it is invalid.
  6881. */
  6882. is_request = is_valid_http_method(ri->request_method);
  6883. if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0)
  6884. || (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
  6885. /* Not a valid request or response: invalid */
  6886. return -1;
  6887. }
  6888. if (is_request) {
  6889. ri->http_version += 5;
  6890. }
  6891. if (parse_http_headers(&buf, ri) < 0) {
  6892. /* Error while parsing headers */
  6893. return -1;
  6894. }
  6895. }
  6896. return request_length;
  6897. }
  6898. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  6899. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  6900. * buffer (which marks the end of HTTP request). Buffer buf may already
  6901. * have some data. The length of the data is stored in nread.
  6902. * Upon every read operation, increase nread by the number of bytes read. */
  6903. static int
  6904. read_request(FILE *fp,
  6905. struct mg_connection *conn,
  6906. char *buf,
  6907. int bufsiz,
  6908. int *nread)
  6909. {
  6910. int request_len, n = 0;
  6911. struct timespec last_action_time;
  6912. double request_timeout;
  6913. if (!conn) {
  6914. return 0;
  6915. }
  6916. memset(&last_action_time, 0, sizeof(last_action_time));
  6917. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  6918. /* value of request_timeout is in seconds, config in milliseconds */
  6919. request_timeout = atof(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  6920. } else {
  6921. request_timeout = -1.0;
  6922. }
  6923. if (conn->handled_requests > 0) {
  6924. if (conn->ctx->config[KEEP_ALIVE_TIMEOUT]) {
  6925. request_timeout =
  6926. atof(conn->ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  6927. }
  6928. }
  6929. request_len = get_request_len(buf, *nread);
  6930. /* first time reading from this connection */
  6931. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  6932. while (request_len == 0) {
  6933. /* Full request not yet received */
  6934. if (conn->ctx->stop_flag != 0) {
  6935. /* Server is to be stopped. */
  6936. return -1;
  6937. }
  6938. if (*nread >= bufsiz) {
  6939. /* Request too long */
  6940. return -2;
  6941. }
  6942. n = pull(fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  6943. if (n < 0) {
  6944. /* Receive error */
  6945. return -1;
  6946. }
  6947. *nread += n;
  6948. request_len = get_request_len(buf, *nread);
  6949. if ((request_len == 0) && (request_timeout >= 0)) {
  6950. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  6951. > request_timeout) {
  6952. /* Timeout */
  6953. return -1;
  6954. }
  6955. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  6956. }
  6957. }
  6958. return request_len;
  6959. }
  6960. #if !defined(NO_FILES)
  6961. /* For given directory path, substitute it to valid index file.
  6962. * Return 1 if index file has been found, 0 if not found.
  6963. * If the file is found, it's stats is returned in stp. */
  6964. static int
  6965. substitute_index_file(struct mg_connection *conn,
  6966. char *path,
  6967. size_t path_len,
  6968. struct mg_file *filep)
  6969. {
  6970. if (conn && conn->ctx) {
  6971. const char *list = conn->ctx->config[INDEX_FILES];
  6972. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6973. struct vec filename_vec;
  6974. size_t n = strlen(path);
  6975. int found = 0;
  6976. /* The 'path' given to us points to the directory. Remove all trailing
  6977. * directory separator characters from the end of the path, and
  6978. * then append single directory separator character. */
  6979. while (n > 0 && path[n - 1] == '/') {
  6980. n--;
  6981. }
  6982. path[n] = '/';
  6983. /* Traverse index files list. For each entry, append it to the given
  6984. * path and see if the file exists. If it exists, break the loop */
  6985. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6986. /* Ignore too long entries that may overflow path buffer */
  6987. if (filename_vec.len > path_len - (n + 2)) {
  6988. continue;
  6989. }
  6990. /* Prepare full path to the index file */
  6991. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6992. /* Does it exist? */
  6993. if (mg_stat(conn, path, &file.stat)) {
  6994. /* Yes it does, break the loop */
  6995. *filep = file;
  6996. found = 1;
  6997. break;
  6998. }
  6999. }
  7000. /* If no index file exists, restore directory path */
  7001. if (!found) {
  7002. path[n] = '\0';
  7003. }
  7004. return found;
  7005. }
  7006. return 0;
  7007. }
  7008. #endif
  7009. #if !defined(NO_CACHING)
  7010. /* Return True if we should reply 304 Not Modified. */
  7011. static int
  7012. is_not_modified(const struct mg_connection *conn,
  7013. const struct mg_file_stat *filestat)
  7014. {
  7015. char etag[64];
  7016. const char *ims = mg_get_header(conn, "If-Modified-Since");
  7017. const char *inm = mg_get_header(conn, "If-None-Match");
  7018. construct_etag(etag, sizeof(etag), filestat);
  7019. return (inm != NULL && !mg_strcasecmp(etag, inm))
  7020. || ((ims != NULL)
  7021. && (filestat->last_modified <= parse_date_string(ims)));
  7022. }
  7023. #endif /* !NO_CACHING */
  7024. #if !defined(NO_CGI) || !defined(NO_FILES)
  7025. static int
  7026. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  7027. {
  7028. const char *expect, *body;
  7029. char buf[MG_BUF_LEN];
  7030. int to_read, nread, success = 0;
  7031. int64_t buffered_len;
  7032. double timeout = -1.0;
  7033. if (!conn) {
  7034. return 0;
  7035. }
  7036. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  7037. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  7038. }
  7039. expect = mg_get_header(conn, "Expect");
  7040. /* assert(fp != NULL); */
  7041. if (!fp) {
  7042. send_http_error(conn, 500, "%s", "Error: NULL File");
  7043. return 0;
  7044. }
  7045. if (conn->content_len == -1 && !conn->is_chunked) {
  7046. /* Content length is not specified by the client. */
  7047. send_http_error(conn,
  7048. 411,
  7049. "%s",
  7050. "Error: Client did not specify content length");
  7051. } else if ((expect != NULL)
  7052. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  7053. /* Client sent an "Expect: xyz" header and xyz is not 100-continue. */
  7054. send_http_error(conn,
  7055. 417,
  7056. "Error: Can not fulfill expectation %s",
  7057. expect);
  7058. } else {
  7059. if (expect != NULL) {
  7060. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  7061. conn->status_code = 100;
  7062. } else {
  7063. conn->status_code = 200;
  7064. }
  7065. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  7066. - conn->consumed_content;
  7067. /* assert(buffered_len >= 0); */
  7068. /* assert(conn->consumed_content == 0); */
  7069. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  7070. send_http_error(conn, 500, "%s", "Error: Size mismatch");
  7071. return 0;
  7072. }
  7073. if (buffered_len > 0) {
  7074. if ((int64_t)buffered_len > conn->content_len) {
  7075. buffered_len = (int)conn->content_len;
  7076. }
  7077. body = conn->buf + conn->request_len + conn->consumed_content;
  7078. push_all(conn->ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  7079. conn->consumed_content += buffered_len;
  7080. }
  7081. nread = 0;
  7082. while (conn->consumed_content < conn->content_len) {
  7083. to_read = sizeof(buf);
  7084. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  7085. to_read = (int)(conn->content_len - conn->consumed_content);
  7086. }
  7087. nread = pull(NULL, conn, buf, to_read, timeout);
  7088. if (nread <= 0
  7089. || push_all(conn->ctx, fp, sock, ssl, buf, nread) != nread) {
  7090. break;
  7091. }
  7092. conn->consumed_content += nread;
  7093. }
  7094. if (conn->consumed_content == conn->content_len) {
  7095. success = (nread >= 0);
  7096. }
  7097. /* Each error code path in this function must send an error */
  7098. if (!success) {
  7099. /* NOTE: Maybe some data has already been sent. */
  7100. /* TODO (low): If some data has been sent, a correct error
  7101. * reply can no longer be sent, so just close the connection */
  7102. send_http_error(conn, 500, "%s", "");
  7103. }
  7104. }
  7105. return success;
  7106. }
  7107. #endif
  7108. #if !defined(NO_CGI)
  7109. /* This structure helps to create an environment for the spawned CGI program.
  7110. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  7111. * last element must be NULL.
  7112. * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  7113. * strings must reside in a contiguous buffer. The end of the buffer is
  7114. * marked by two '\0' characters.
  7115. * We satisfy both worlds: we create an envp array (which is vars), all
  7116. * entries are actually pointers inside buf. */
  7117. struct cgi_environment {
  7118. struct mg_connection *conn;
  7119. /* Data block */
  7120. char *buf; /* Environment buffer */
  7121. size_t buflen; /* Space available in buf */
  7122. size_t bufused; /* Space taken in buf */
  7123. /* Index block */
  7124. char **var; /* char **envp */
  7125. size_t varlen; /* Number of variables available in var */
  7126. size_t varused; /* Number of variables stored in var */
  7127. };
  7128. static void addenv(struct cgi_environment *env,
  7129. PRINTF_FORMAT_STRING(const char *fmt),
  7130. ...) PRINTF_ARGS(2, 3);
  7131. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  7132. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  7133. static void
  7134. addenv(struct cgi_environment *env, const char *fmt, ...)
  7135. {
  7136. size_t n, space;
  7137. int truncated = 0;
  7138. char *added;
  7139. va_list ap;
  7140. /* Calculate how much space is left in the buffer */
  7141. space = (env->buflen - env->bufused);
  7142. /* Calculate an estimate for the required space */
  7143. n = strlen(fmt) + 2 + 128;
  7144. do {
  7145. if (space <= n) {
  7146. /* Allocate new buffer */
  7147. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  7148. added = (char *)mg_realloc(env->buf, n);
  7149. if (!added) {
  7150. /* Out of memory */
  7151. mg_cry(env->conn,
  7152. "%s: Cannot allocate memory for CGI variable [%s]",
  7153. __func__,
  7154. fmt);
  7155. return;
  7156. }
  7157. env->buf = added;
  7158. env->buflen = n;
  7159. space = (env->buflen - env->bufused);
  7160. }
  7161. /* Make a pointer to the free space int the buffer */
  7162. added = env->buf + env->bufused;
  7163. /* Copy VARIABLE=VALUE\0 string into the free space */
  7164. va_start(ap, fmt);
  7165. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  7166. va_end(ap);
  7167. /* Do not add truncated strings to the environment */
  7168. if (truncated) {
  7169. /* Reallocate the buffer */
  7170. space = 0;
  7171. n = 1;
  7172. }
  7173. } while (truncated);
  7174. /* Calculate number of bytes added to the environment */
  7175. n = strlen(added) + 1;
  7176. env->bufused += n;
  7177. /* Now update the variable index */
  7178. space = (env->varlen - env->varused);
  7179. if (space < 2) {
  7180. mg_cry(env->conn,
  7181. "%s: Cannot register CGI variable [%s]",
  7182. __func__,
  7183. fmt);
  7184. return;
  7185. }
  7186. /* Append a pointer to the added string into the envp array */
  7187. env->var[env->varused] = added;
  7188. env->varused++;
  7189. }
  7190. static void
  7191. prepare_cgi_environment(struct mg_connection *conn,
  7192. const char *prog,
  7193. struct cgi_environment *env)
  7194. {
  7195. const char *s;
  7196. struct vec var_vec;
  7197. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  7198. int i, truncated, uri_len;
  7199. if (conn == NULL || prog == NULL || env == NULL) {
  7200. return;
  7201. }
  7202. env->conn = conn;
  7203. env->buflen = CGI_ENVIRONMENT_SIZE;
  7204. env->bufused = 0;
  7205. env->buf = (char *)mg_malloc(env->buflen);
  7206. env->varlen = MAX_CGI_ENVIR_VARS;
  7207. env->varused = 0;
  7208. env->var = (char **)mg_malloc(env->buflen * sizeof(char *));
  7209. addenv(env, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  7210. addenv(env, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  7211. addenv(env, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  7212. addenv(env, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  7213. /* Prepare the environment block */
  7214. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  7215. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  7216. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  7217. #if defined(USE_IPV6)
  7218. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  7219. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  7220. } else
  7221. #endif
  7222. {
  7223. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  7224. }
  7225. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  7226. addenv(env, "REMOTE_ADDR=%s", src_addr);
  7227. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  7228. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  7229. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  7230. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  7231. /* SCRIPT_NAME */
  7232. uri_len = (int)strlen(conn->request_info.local_uri);
  7233. if (conn->path_info == NULL) {
  7234. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  7235. /* URI: /path_to_script/script.cgi */
  7236. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  7237. } else {
  7238. /* URI: /path_to_script/ ... using index.cgi */
  7239. char *index_file = strrchr(prog, '/');
  7240. if (index_file) {
  7241. addenv(env,
  7242. "SCRIPT_NAME=%s%s",
  7243. conn->request_info.local_uri,
  7244. index_file + 1);
  7245. }
  7246. }
  7247. } else {
  7248. /* URI: /path_to_script/script.cgi/path_info */
  7249. addenv(env,
  7250. "SCRIPT_NAME=%.*s",
  7251. uri_len - (int)strlen(conn->path_info),
  7252. conn->request_info.local_uri);
  7253. }
  7254. addenv(env, "SCRIPT_FILENAME=%s", prog);
  7255. if (conn->path_info == NULL) {
  7256. addenv(env, "PATH_TRANSLATED=%s", conn->ctx->config[DOCUMENT_ROOT]);
  7257. } else {
  7258. addenv(env,
  7259. "PATH_TRANSLATED=%s%s",
  7260. conn->ctx->config[DOCUMENT_ROOT],
  7261. conn->path_info);
  7262. }
  7263. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  7264. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  7265. addenv(env, "CONTENT_TYPE=%s", s);
  7266. }
  7267. if (conn->request_info.query_string != NULL) {
  7268. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  7269. }
  7270. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  7271. addenv(env, "CONTENT_LENGTH=%s", s);
  7272. }
  7273. if ((s = getenv("PATH")) != NULL) {
  7274. addenv(env, "PATH=%s", s);
  7275. }
  7276. if (conn->path_info != NULL) {
  7277. addenv(env, "PATH_INFO=%s", conn->path_info);
  7278. }
  7279. if (conn->status_code > 0) {
  7280. /* CGI error handler should show the status code */
  7281. addenv(env, "STATUS=%d", conn->status_code);
  7282. }
  7283. #if defined(_WIN32)
  7284. if ((s = getenv("COMSPEC")) != NULL) {
  7285. addenv(env, "COMSPEC=%s", s);
  7286. }
  7287. if ((s = getenv("SYSTEMROOT")) != NULL) {
  7288. addenv(env, "SYSTEMROOT=%s", s);
  7289. }
  7290. if ((s = getenv("SystemDrive")) != NULL) {
  7291. addenv(env, "SystemDrive=%s", s);
  7292. }
  7293. if ((s = getenv("ProgramFiles")) != NULL) {
  7294. addenv(env, "ProgramFiles=%s", s);
  7295. }
  7296. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  7297. addenv(env, "ProgramFiles(x86)=%s", s);
  7298. }
  7299. #else
  7300. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  7301. addenv(env, "LD_LIBRARY_PATH=%s", s);
  7302. }
  7303. #endif /* _WIN32 */
  7304. if ((s = getenv("PERLLIB")) != NULL) {
  7305. addenv(env, "PERLLIB=%s", s);
  7306. }
  7307. if (conn->request_info.remote_user != NULL) {
  7308. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  7309. addenv(env, "%s", "AUTH_TYPE=Digest");
  7310. }
  7311. /* Add all headers as HTTP_* variables */
  7312. for (i = 0; i < conn->request_info.num_headers; i++) {
  7313. (void)mg_snprintf(conn,
  7314. &truncated,
  7315. http_var_name,
  7316. sizeof(http_var_name),
  7317. "HTTP_%s",
  7318. conn->request_info.http_headers[i].name);
  7319. if (truncated) {
  7320. mg_cry(conn,
  7321. "%s: HTTP header variable too long [%s]",
  7322. __func__,
  7323. conn->request_info.http_headers[i].name);
  7324. continue;
  7325. }
  7326. /* Convert variable name into uppercase, and change - to _ */
  7327. for (p = http_var_name; *p != '\0'; p++) {
  7328. if (*p == '-') {
  7329. *p = '_';
  7330. }
  7331. *p = (char)toupper(*(unsigned char *)p);
  7332. }
  7333. addenv(env,
  7334. "%s=%s",
  7335. http_var_name,
  7336. conn->request_info.http_headers[i].value);
  7337. }
  7338. /* Add user-specified variables */
  7339. s = conn->ctx->config[CGI_ENVIRONMENT];
  7340. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  7341. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  7342. }
  7343. env->var[env->varused] = NULL;
  7344. env->buf[env->bufused] = '\0';
  7345. }
  7346. static void
  7347. handle_cgi_request(struct mg_connection *conn, const char *prog)
  7348. {
  7349. char *buf;
  7350. size_t buflen;
  7351. int headers_len, data_len, i, truncated;
  7352. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  7353. const char *status, *status_text, *connection_state;
  7354. char *pbuf, dir[PATH_MAX], *p;
  7355. struct mg_request_info ri;
  7356. struct cgi_environment blk;
  7357. FILE *in = NULL, *out = NULL, *err = NULL;
  7358. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  7359. pid_t pid = (pid_t)-1;
  7360. if (conn == NULL) {
  7361. return;
  7362. }
  7363. buf = NULL;
  7364. buflen = 16384;
  7365. prepare_cgi_environment(conn, prog, &blk);
  7366. /* CGI must be executed in its own directory. 'dir' must point to the
  7367. * directory containing executable program, 'p' must point to the
  7368. * executable program name relative to 'dir'. */
  7369. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  7370. if (truncated) {
  7371. mg_cry(conn, "Error: CGI program \"%s\": Path too long", prog);
  7372. send_http_error(conn, 500, "Error: %s", "CGI path too long");
  7373. goto done;
  7374. }
  7375. if ((p = strrchr(dir, '/')) != NULL) {
  7376. *p++ = '\0';
  7377. } else {
  7378. dir[0] = '.', dir[1] = '\0';
  7379. p = (char *)prog;
  7380. }
  7381. if (pipe(fdin) != 0 || pipe(fdout) != 0 || pipe(fderr) != 0) {
  7382. status = strerror(ERRNO);
  7383. mg_cry(conn,
  7384. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  7385. prog,
  7386. status);
  7387. send_http_error(conn, 500, "Error: Cannot create CGI pipe: %s", status);
  7388. goto done;
  7389. }
  7390. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  7391. if (pid == (pid_t)-1) {
  7392. status = strerror(ERRNO);
  7393. mg_cry(conn,
  7394. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  7395. prog,
  7396. status);
  7397. send_http_error(conn,
  7398. 500,
  7399. "Error: Cannot spawn CGI process [%s]: %s",
  7400. prog,
  7401. status);
  7402. goto done;
  7403. }
  7404. /* Make sure child closes all pipe descriptors. It must dup them to 0,1 */
  7405. set_close_on_exec((SOCKET)fdin[0], conn); /* stdin read */
  7406. set_close_on_exec((SOCKET)fdout[1], conn); /* stdout write */
  7407. set_close_on_exec((SOCKET)fderr[1], conn); /* stderr write */
  7408. set_close_on_exec((SOCKET)fdin[1], conn); /* stdin write */
  7409. set_close_on_exec((SOCKET)fdout[0], conn); /* stdout read */
  7410. set_close_on_exec((SOCKET)fderr[0], conn); /* stderr read */
  7411. /* Parent closes only one side of the pipes.
  7412. * If we don't mark them as closed, close() attempt before
  7413. * return from this function throws an exception on Windows.
  7414. * Windows does not like when closed descriptor is closed again. */
  7415. (void)close(fdin[0]);
  7416. (void)close(fdout[1]);
  7417. (void)close(fderr[1]);
  7418. fdin[0] = fdout[1] = fderr[1] = -1;
  7419. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  7420. status = strerror(ERRNO);
  7421. mg_cry(conn,
  7422. "Error: CGI program \"%s\": Can not open stdin: %s",
  7423. prog,
  7424. status);
  7425. send_http_error(conn,
  7426. 500,
  7427. "Error: CGI can not open fdin\nfopen: %s",
  7428. status);
  7429. goto done;
  7430. }
  7431. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  7432. status = strerror(ERRNO);
  7433. mg_cry(conn,
  7434. "Error: CGI program \"%s\": Can not open stdout: %s",
  7435. prog,
  7436. status);
  7437. send_http_error(conn,
  7438. 500,
  7439. "Error: CGI can not open fdout\nfopen: %s",
  7440. status);
  7441. goto done;
  7442. }
  7443. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  7444. status = strerror(ERRNO);
  7445. mg_cry(conn,
  7446. "Error: CGI program \"%s\": Can not open stderr: %s",
  7447. prog,
  7448. status);
  7449. send_http_error(conn,
  7450. 500,
  7451. "Error: CGI can not open fdout\nfopen: %s",
  7452. status);
  7453. goto done;
  7454. }
  7455. setbuf(in, NULL);
  7456. setbuf(out, NULL);
  7457. setbuf(err, NULL);
  7458. fout.access.fp = out;
  7459. if ((conn->request_info.content_length > 0) || conn->is_chunked) {
  7460. /* This is a POST/PUT request, or another request with body data. */
  7461. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  7462. /* Error sending the body data */
  7463. mg_cry(conn,
  7464. "Error: CGI program \"%s\": Forward body data failed",
  7465. prog);
  7466. goto done;
  7467. }
  7468. }
  7469. /* Close so child gets an EOF. */
  7470. fclose(in);
  7471. in = NULL;
  7472. fdin[1] = -1;
  7473. /* Now read CGI reply into a buffer. We need to set correct
  7474. * status code, thus we need to see all HTTP headers first.
  7475. * Do not send anything back to client, until we buffer in all
  7476. * HTTP headers. */
  7477. data_len = 0;
  7478. buf = (char *)mg_malloc(buflen);
  7479. if (buf == NULL) {
  7480. send_http_error(conn,
  7481. 500,
  7482. "Error: Not enough memory for CGI buffer (%u bytes)",
  7483. (unsigned int)buflen);
  7484. mg_cry(conn,
  7485. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  7486. "bytes)",
  7487. prog,
  7488. (unsigned int)buflen);
  7489. goto done;
  7490. }
  7491. headers_len = read_request(out, conn, buf, (int)buflen, &data_len);
  7492. if (headers_len <= 0) {
  7493. /* Could not parse the CGI response. Check if some error message on
  7494. * stderr. */
  7495. i = pull_all(err, conn, buf, (int)buflen);
  7496. if (i > 0) {
  7497. mg_cry(conn,
  7498. "Error: CGI program \"%s\" sent error "
  7499. "message: [%.*s]",
  7500. prog,
  7501. i,
  7502. buf);
  7503. send_http_error(conn,
  7504. 500,
  7505. "Error: CGI program \"%s\" sent error "
  7506. "message: [%.*s]",
  7507. prog,
  7508. i,
  7509. buf);
  7510. } else {
  7511. mg_cry(conn,
  7512. "Error: CGI program sent malformed or too big "
  7513. "(>%u bytes) HTTP headers: [%.*s]",
  7514. (unsigned)buflen,
  7515. data_len,
  7516. buf);
  7517. send_http_error(conn,
  7518. 500,
  7519. "Error: CGI program sent malformed or too big "
  7520. "(>%u bytes) HTTP headers: [%.*s]",
  7521. (unsigned)buflen,
  7522. data_len,
  7523. buf);
  7524. }
  7525. goto done;
  7526. }
  7527. pbuf = buf;
  7528. buf[headers_len - 1] = '\0';
  7529. parse_http_headers(&pbuf, &ri);
  7530. /* Make up and send the status line */
  7531. status_text = "OK";
  7532. if ((status = get_header(&ri, "Status")) != NULL) {
  7533. conn->status_code = atoi(status);
  7534. status_text = status;
  7535. while (isdigit(*(const unsigned char *)status_text)
  7536. || *status_text == ' ') {
  7537. status_text++;
  7538. }
  7539. } else if (get_header(&ri, "Location") != NULL) {
  7540. conn->status_code = 302;
  7541. } else {
  7542. conn->status_code = 200;
  7543. }
  7544. connection_state = get_header(&ri, "Connection");
  7545. if (!header_has_option(connection_state, "keep-alive")) {
  7546. conn->must_close = 1;
  7547. }
  7548. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  7549. /* Send headers */
  7550. for (i = 0; i < ri.num_headers; i++) {
  7551. mg_printf(conn,
  7552. "%s: %s\r\n",
  7553. ri.http_headers[i].name,
  7554. ri.http_headers[i].value);
  7555. }
  7556. mg_write(conn, "\r\n", 2);
  7557. /* Send chunk of data that may have been read after the headers */
  7558. conn->num_bytes_sent +=
  7559. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  7560. /* Read the rest of CGI output and send to the client */
  7561. send_file_data(conn, &fout, 0, INT64_MAX);
  7562. done:
  7563. mg_free(blk.var);
  7564. mg_free(blk.buf);
  7565. if (pid != (pid_t)-1) {
  7566. kill(pid, SIGKILL);
  7567. #if !defined(_WIN32)
  7568. {
  7569. int st;
  7570. while (waitpid(pid, &st, 0) != -1)
  7571. ; /* clean zombies */
  7572. }
  7573. #endif
  7574. }
  7575. if (fdin[0] != -1) {
  7576. close(fdin[0]);
  7577. }
  7578. if (fdout[1] != -1) {
  7579. close(fdout[1]);
  7580. }
  7581. if (in != NULL) {
  7582. fclose(in);
  7583. } else if (fdin[1] != -1) {
  7584. close(fdin[1]);
  7585. }
  7586. if (out != NULL) {
  7587. fclose(out);
  7588. } else if (fdout[0] != -1) {
  7589. close(fdout[0]);
  7590. }
  7591. if (err != NULL) {
  7592. fclose(err);
  7593. } else if (fderr[0] != -1) {
  7594. close(fderr[0]);
  7595. }
  7596. if (buf != NULL) {
  7597. mg_free(buf);
  7598. }
  7599. }
  7600. #endif /* !NO_CGI */
  7601. #if !defined(NO_FILES)
  7602. static void
  7603. mkcol(struct mg_connection *conn, const char *path)
  7604. {
  7605. int rc, body_len;
  7606. struct de de;
  7607. char date[64];
  7608. time_t curtime = time(NULL);
  7609. if (conn == NULL) {
  7610. return;
  7611. }
  7612. /* TODO (mid): Check the send_http_error situations in this function */
  7613. memset(&de.file, 0, sizeof(de.file));
  7614. if (!mg_stat(conn, path, &de.file)) {
  7615. mg_cry(conn,
  7616. "%s: mg_stat(%s) failed: %s",
  7617. __func__,
  7618. path,
  7619. strerror(ERRNO));
  7620. }
  7621. if (de.file.last_modified) {
  7622. /* TODO (mid): This check does not seem to make any sense ! */
  7623. /* TODO (mid): Add a webdav unit test first, before changing
  7624. * anything here. */
  7625. send_http_error(
  7626. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7627. return;
  7628. }
  7629. body_len = conn->data_len - conn->request_len;
  7630. if (body_len > 0) {
  7631. send_http_error(
  7632. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7633. return;
  7634. }
  7635. rc = mg_mkdir(conn, path, 0755);
  7636. if (rc == 0) {
  7637. conn->status_code = 201;
  7638. gmt_time_string(date, sizeof(date), &curtime);
  7639. mg_printf(conn,
  7640. "HTTP/1.1 %d Created\r\n"
  7641. "Date: %s\r\n",
  7642. conn->status_code,
  7643. date);
  7644. send_static_cache_header(conn);
  7645. mg_printf(conn,
  7646. "Content-Length: 0\r\n"
  7647. "Connection: %s\r\n\r\n",
  7648. suggest_connection_header(conn));
  7649. } else if (rc == -1) {
  7650. if (errno == EEXIST) {
  7651. send_http_error(
  7652. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7653. } else if (errno == EACCES) {
  7654. send_http_error(
  7655. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7656. } else if (errno == ENOENT) {
  7657. send_http_error(
  7658. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7659. } else {
  7660. send_http_error(conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  7661. }
  7662. }
  7663. }
  7664. static void
  7665. put_file(struct mg_connection *conn, const char *path)
  7666. {
  7667. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7668. const char *range;
  7669. int64_t r1, r2;
  7670. int rc;
  7671. char date[64];
  7672. time_t curtime = time(NULL);
  7673. if (conn == NULL) {
  7674. return;
  7675. }
  7676. if (mg_stat(conn, path, &file.stat)) {
  7677. /* File already exists */
  7678. conn->status_code = 200;
  7679. if (file.stat.is_directory) {
  7680. /* This is an already existing directory,
  7681. * so there is nothing to do for the server. */
  7682. rc = 0;
  7683. } else {
  7684. /* File exists and is not a directory. */
  7685. /* Can it be replaced? */
  7686. if (file.access.membuf != NULL) {
  7687. /* This is an "in-memory" file, that can not be replaced */
  7688. send_http_error(
  7689. conn,
  7690. 405,
  7691. "Error: Put not possible\nReplacing %s is not supported",
  7692. path);
  7693. return;
  7694. }
  7695. /* Check if the server may write this file */
  7696. if (access(path, W_OK) == 0) {
  7697. /* Access granted */
  7698. conn->status_code = 200;
  7699. rc = 1;
  7700. } else {
  7701. send_http_error(
  7702. conn,
  7703. 403,
  7704. "Error: Put not possible\nReplacing %s is not allowed",
  7705. path);
  7706. return;
  7707. }
  7708. }
  7709. } else {
  7710. /* File should be created */
  7711. conn->status_code = 201;
  7712. rc = put_dir(conn, path);
  7713. }
  7714. if (rc == 0) {
  7715. /* put_dir returns 0 if path is a directory */
  7716. gmt_time_string(date, sizeof(date), &curtime);
  7717. mg_printf(conn,
  7718. "HTTP/1.1 %d %s\r\n",
  7719. conn->status_code,
  7720. mg_get_response_code_text(NULL, conn->status_code));
  7721. send_no_cache_header(conn);
  7722. mg_printf(conn,
  7723. "Date: %s\r\n"
  7724. "Content-Length: 0\r\n"
  7725. "Connection: %s\r\n\r\n",
  7726. date,
  7727. suggest_connection_header(conn));
  7728. /* Request to create a directory has been fulfilled successfully.
  7729. * No need to put a file. */
  7730. return;
  7731. }
  7732. if (rc == -1) {
  7733. /* put_dir returns -1 if the path is too long */
  7734. send_http_error(conn,
  7735. 414,
  7736. "Error: Path too long\nput_dir(%s): %s",
  7737. path,
  7738. strerror(ERRNO));
  7739. return;
  7740. }
  7741. if (rc == -2) {
  7742. /* put_dir returns -2 if the directory can not be created */
  7743. send_http_error(conn,
  7744. 500,
  7745. "Error: Can not create directory\nput_dir(%s): %s",
  7746. path,
  7747. strerror(ERRNO));
  7748. return;
  7749. }
  7750. /* A file should be created or overwritten. */
  7751. /* Currently CivetWeb does not nead read+write access. */
  7752. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  7753. || file.access.fp == NULL) {
  7754. (void)mg_fclose(&file.access);
  7755. send_http_error(conn,
  7756. 500,
  7757. "Error: Can not create file\nfopen(%s): %s",
  7758. path,
  7759. strerror(ERRNO));
  7760. return;
  7761. }
  7762. fclose_on_exec(&file.access, conn);
  7763. range = mg_get_header(conn, "Content-Range");
  7764. r1 = r2 = 0;
  7765. if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
  7766. conn->status_code = 206; /* Partial content */
  7767. fseeko(file.access.fp, r1, SEEK_SET);
  7768. }
  7769. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  7770. /* forward_body_data failed.
  7771. * The error code has already been sent to the client,
  7772. * and conn->status_code is already set. */
  7773. (void)mg_fclose(&file.access);
  7774. return;
  7775. }
  7776. if (mg_fclose(&file.access) != 0) {
  7777. /* fclose failed. This might have different reasons, but a likely
  7778. * one is "no space on disk", http 507. */
  7779. conn->status_code = 507;
  7780. }
  7781. gmt_time_string(date, sizeof(date), &curtime);
  7782. mg_printf(conn,
  7783. "HTTP/1.1 %d %s\r\n",
  7784. conn->status_code,
  7785. mg_get_response_code_text(NULL, conn->status_code));
  7786. send_no_cache_header(conn);
  7787. mg_printf(conn,
  7788. "Date: %s\r\n"
  7789. "Content-Length: 0\r\n"
  7790. "Connection: %s\r\n\r\n",
  7791. date,
  7792. suggest_connection_header(conn));
  7793. }
  7794. static void
  7795. delete_file(struct mg_connection *conn, const char *path)
  7796. {
  7797. struct de de;
  7798. memset(&de.file, 0, sizeof(de.file));
  7799. if (!mg_stat(conn, path, &de.file)) {
  7800. /* mg_stat returns 0 if the file does not exist */
  7801. send_http_error(conn,
  7802. 404,
  7803. "Error: Cannot delete file\nFile %s not found",
  7804. path);
  7805. return;
  7806. }
  7807. #if 0 /* Ignore if a file in memory is inside a folder */
  7808. if (de.access.membuf != NULL) {
  7809. /* the file is cached in memory */
  7810. send_http_error(
  7811. conn,
  7812. 405,
  7813. "Error: Delete not possible\nDeleting %s is not supported",
  7814. path);
  7815. return;
  7816. }
  7817. #endif
  7818. if (de.file.is_directory) {
  7819. if (remove_directory(conn, path)) {
  7820. /* Delete is successful: Return 204 without content. */
  7821. send_http_error(conn, 204, "%s", "");
  7822. } else {
  7823. /* Delete is not successful: Return 500 (Server error). */
  7824. send_http_error(conn, 500, "Error: Could not delete %s", path);
  7825. }
  7826. return;
  7827. }
  7828. /* This is an existing file (not a directory).
  7829. * Check if write permission is granted. */
  7830. if (access(path, W_OK) != 0) {
  7831. /* File is read only */
  7832. send_http_error(
  7833. conn,
  7834. 403,
  7835. "Error: Delete not possible\nDeleting %s is not allowed",
  7836. path);
  7837. return;
  7838. }
  7839. /* Try to delete it. */
  7840. if (mg_remove(conn, path) == 0) {
  7841. /* Delete was successful: Return 204 without content. */
  7842. send_http_error(conn, 204, "%s", "");
  7843. } else {
  7844. /* Delete not successful (file locked). */
  7845. send_http_error(conn,
  7846. 423,
  7847. "Error: Cannot delete file\nremove(%s): %s",
  7848. path,
  7849. strerror(ERRNO));
  7850. }
  7851. }
  7852. #endif /* !NO_FILES */
  7853. static void
  7854. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  7855. static void
  7856. do_ssi_include(struct mg_connection *conn,
  7857. const char *ssi,
  7858. char *tag,
  7859. int include_level)
  7860. {
  7861. char file_name[MG_BUF_LEN], path[512], *p;
  7862. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7863. size_t len;
  7864. int truncated = 0;
  7865. if (conn == NULL) {
  7866. return;
  7867. }
  7868. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  7869. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  7870. * always < MG_BUF_LEN. */
  7871. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  7872. /* File name is relative to the webserver root */
  7873. file_name[511] = 0;
  7874. (void)mg_snprintf(conn,
  7875. &truncated,
  7876. path,
  7877. sizeof(path),
  7878. "%s/%s",
  7879. conn->ctx->config[DOCUMENT_ROOT],
  7880. file_name);
  7881. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  7882. /* File name is relative to the webserver working directory
  7883. * or it is absolute system path */
  7884. file_name[511] = 0;
  7885. (void)
  7886. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  7887. } else if (sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1
  7888. || sscanf(tag, " \"%511[^\"]\"", file_name) == 1) {
  7889. /* File name is relative to the currect document */
  7890. file_name[511] = 0;
  7891. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  7892. if (!truncated) {
  7893. if ((p = strrchr(path, '/')) != NULL) {
  7894. p[1] = '\0';
  7895. }
  7896. len = strlen(path);
  7897. (void)mg_snprintf(conn,
  7898. &truncated,
  7899. path + len,
  7900. sizeof(path) - len,
  7901. "%s",
  7902. file_name);
  7903. }
  7904. } else {
  7905. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  7906. return;
  7907. }
  7908. if (truncated) {
  7909. mg_cry(conn, "SSI #include path length overflow: [%s]", tag);
  7910. return;
  7911. }
  7912. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  7913. mg_cry(conn,
  7914. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  7915. tag,
  7916. path,
  7917. strerror(ERRNO));
  7918. } else {
  7919. fclose_on_exec(&file.access, conn);
  7920. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  7921. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  7922. path) > 0) {
  7923. send_ssi_file(conn, path, &file, include_level + 1);
  7924. } else {
  7925. send_file_data(conn, &file, 0, INT64_MAX);
  7926. }
  7927. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  7928. }
  7929. }
  7930. #if !defined(NO_POPEN)
  7931. static void
  7932. do_ssi_exec(struct mg_connection *conn, char *tag)
  7933. {
  7934. char cmd[1024] = "";
  7935. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7936. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  7937. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  7938. } else {
  7939. cmd[1023] = 0;
  7940. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  7941. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  7942. } else {
  7943. send_file_data(conn, &file, 0, INT64_MAX);
  7944. pclose(file.access.fp);
  7945. }
  7946. }
  7947. }
  7948. #endif /* !NO_POPEN */
  7949. static int
  7950. mg_fgetc(struct mg_file *filep, int offset)
  7951. {
  7952. if (filep == NULL) {
  7953. return EOF;
  7954. }
  7955. if (filep->access.membuf != NULL && offset >= 0
  7956. && ((unsigned int)(offset)) < filep->stat.size) {
  7957. return ((const unsigned char *)filep->access.membuf)[offset];
  7958. } else if (filep->access.fp != NULL) {
  7959. return fgetc(filep->access.fp);
  7960. } else {
  7961. return EOF;
  7962. }
  7963. }
  7964. static void
  7965. send_ssi_file(struct mg_connection *conn,
  7966. const char *path,
  7967. struct mg_file *filep,
  7968. int include_level)
  7969. {
  7970. char buf[MG_BUF_LEN];
  7971. int ch, offset, len, in_ssi_tag;
  7972. if (include_level > 10) {
  7973. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  7974. return;
  7975. }
  7976. in_ssi_tag = len = offset = 0;
  7977. while ((ch = mg_fgetc(filep, offset)) != EOF) {
  7978. if (in_ssi_tag && ch == '>') {
  7979. in_ssi_tag = 0;
  7980. buf[len++] = (char)ch;
  7981. buf[len] = '\0';
  7982. /* assert(len <= (int) sizeof(buf)); */
  7983. if (len > (int)sizeof(buf)) {
  7984. break;
  7985. }
  7986. if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
  7987. /* Not an SSI tag, pass it */
  7988. (void)mg_write(conn, buf, (size_t)len);
  7989. } else {
  7990. if (!memcmp(buf + 5, "include", 7)) {
  7991. do_ssi_include(conn, path, buf + 12, include_level);
  7992. #if !defined(NO_POPEN)
  7993. } else if (!memcmp(buf + 5, "exec", 4)) {
  7994. do_ssi_exec(conn, buf + 9);
  7995. #endif /* !NO_POPEN */
  7996. } else {
  7997. mg_cry(conn,
  7998. "%s: unknown SSI "
  7999. "command: \"%s\"",
  8000. path,
  8001. buf);
  8002. }
  8003. }
  8004. len = 0;
  8005. } else if (in_ssi_tag) {
  8006. if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
  8007. /* Not an SSI tag */
  8008. in_ssi_tag = 0;
  8009. } else if (len == (int)sizeof(buf) - 2) {
  8010. mg_cry(conn, "%s: SSI tag is too large", path);
  8011. len = 0;
  8012. }
  8013. buf[len++] = (char)(ch & 0xff);
  8014. } else if (ch == '<') {
  8015. in_ssi_tag = 1;
  8016. if (len > 0) {
  8017. mg_write(conn, buf, (size_t)len);
  8018. }
  8019. len = 0;
  8020. buf[len++] = (char)(ch & 0xff);
  8021. } else {
  8022. buf[len++] = (char)(ch & 0xff);
  8023. if (len == (int)sizeof(buf)) {
  8024. mg_write(conn, buf, (size_t)len);
  8025. len = 0;
  8026. }
  8027. }
  8028. }
  8029. /* Send the rest of buffered data */
  8030. if (len > 0) {
  8031. mg_write(conn, buf, (size_t)len);
  8032. }
  8033. }
  8034. static void
  8035. handle_ssi_file_request(struct mg_connection *conn,
  8036. const char *path,
  8037. struct mg_file *filep)
  8038. {
  8039. char date[64];
  8040. time_t curtime = time(NULL);
  8041. const char *cors1, *cors2, *cors3;
  8042. if (conn == NULL || path == NULL || filep == NULL) {
  8043. return;
  8044. }
  8045. if (mg_get_header(conn, "Origin")) {
  8046. /* Cross-origin resource sharing (CORS). */
  8047. cors1 = "Access-Control-Allow-Origin: ";
  8048. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  8049. cors3 = "\r\n";
  8050. } else {
  8051. cors1 = cors2 = cors3 = "";
  8052. }
  8053. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8054. /* File exists (precondition for calling this function),
  8055. * but can not be opened by the server. */
  8056. send_http_error(conn,
  8057. 500,
  8058. "Error: Cannot read file\nfopen(%s): %s",
  8059. path,
  8060. strerror(ERRNO));
  8061. } else {
  8062. conn->must_close = 1;
  8063. gmt_time_string(date, sizeof(date), &curtime);
  8064. fclose_on_exec(&filep->access, conn);
  8065. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  8066. send_no_cache_header(conn);
  8067. mg_printf(conn,
  8068. "%s%s%s"
  8069. "Date: %s\r\n"
  8070. "Content-Type: text/html\r\n"
  8071. "Connection: %s\r\n\r\n",
  8072. cors1,
  8073. cors2,
  8074. cors3,
  8075. date,
  8076. suggest_connection_header(conn));
  8077. send_ssi_file(conn, path, filep, 0);
  8078. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  8079. }
  8080. }
  8081. #if !defined(NO_FILES)
  8082. static void
  8083. send_options(struct mg_connection *conn)
  8084. {
  8085. char date[64];
  8086. time_t curtime = time(NULL);
  8087. if (!conn) {
  8088. return;
  8089. }
  8090. conn->status_code = 200;
  8091. conn->must_close = 1;
  8092. gmt_time_string(date, sizeof(date), &curtime);
  8093. /* We do not set a "Cache-Control" header here, but leave the default.
  8094. * Since browsers do not send an OPTIONS request, we can not test the
  8095. * effect anyway. */
  8096. mg_printf(conn,
  8097. "HTTP/1.1 200 OK\r\n"
  8098. "Date: %s\r\n"
  8099. "Connection: %s\r\n"
  8100. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  8101. "PROPFIND, MKCOL\r\n"
  8102. "DAV: 1\r\n\r\n",
  8103. date,
  8104. suggest_connection_header(conn));
  8105. }
  8106. /* Writes PROPFIND properties for a collection element */
  8107. static void
  8108. print_props(struct mg_connection *conn,
  8109. const char *uri,
  8110. struct mg_file_stat *filep)
  8111. {
  8112. char mtime[64];
  8113. if (conn == NULL || uri == NULL || filep == NULL) {
  8114. return;
  8115. }
  8116. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  8117. conn->num_bytes_sent +=
  8118. mg_printf(conn,
  8119. "<d:response>"
  8120. "<d:href>%s</d:href>"
  8121. "<d:propstat>"
  8122. "<d:prop>"
  8123. "<d:resourcetype>%s</d:resourcetype>"
  8124. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  8125. "<d:getlastmodified>%s</d:getlastmodified>"
  8126. "</d:prop>"
  8127. "<d:status>HTTP/1.1 200 OK</d:status>"
  8128. "</d:propstat>"
  8129. "</d:response>\n",
  8130. uri,
  8131. filep->is_directory ? "<d:collection/>" : "",
  8132. filep->size,
  8133. mtime);
  8134. }
  8135. static void
  8136. print_dav_dir_entry(struct de *de, void *data)
  8137. {
  8138. char href[PATH_MAX];
  8139. char href_encoded[PATH_MAX * 3 /* worst case */];
  8140. int truncated;
  8141. struct mg_connection *conn = (struct mg_connection *)data;
  8142. if (!de || !conn) {
  8143. return;
  8144. }
  8145. mg_snprintf(conn,
  8146. &truncated,
  8147. href,
  8148. sizeof(href),
  8149. "%s%s",
  8150. conn->request_info.local_uri,
  8151. de->file_name);
  8152. if (!truncated) {
  8153. mg_url_encode(href, href_encoded, PATH_MAX * 3);
  8154. print_props(conn, href_encoded, &de->file);
  8155. }
  8156. }
  8157. static void
  8158. handle_propfind(struct mg_connection *conn,
  8159. const char *path,
  8160. struct mg_file_stat *filep)
  8161. {
  8162. const char *depth = mg_get_header(conn, "Depth");
  8163. char date[64];
  8164. time_t curtime = time(NULL);
  8165. gmt_time_string(date, sizeof(date), &curtime);
  8166. if (!conn || !path || !filep || !conn->ctx) {
  8167. return;
  8168. }
  8169. conn->must_close = 1;
  8170. conn->status_code = 207;
  8171. mg_printf(conn,
  8172. "HTTP/1.1 207 Multi-Status\r\n"
  8173. "Date: %s\r\n",
  8174. date);
  8175. send_static_cache_header(conn);
  8176. mg_printf(conn,
  8177. "Connection: %s\r\n"
  8178. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  8179. suggest_connection_header(conn));
  8180. conn->num_bytes_sent +=
  8181. mg_printf(conn,
  8182. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  8183. "<d:multistatus xmlns:d='DAV:'>\n");
  8184. /* Print properties for the requested resource itself */
  8185. print_props(conn, conn->request_info.local_uri, filep);
  8186. /* If it is a directory, print directory entries too if Depth is not 0 */
  8187. if (filep && filep->is_directory
  8188. && !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")
  8189. && (depth == NULL || strcmp(depth, "0") != 0)) {
  8190. scan_directory(conn, path, conn, &print_dav_dir_entry);
  8191. }
  8192. conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");
  8193. }
  8194. #endif
  8195. void
  8196. mg_lock_connection(struct mg_connection *conn)
  8197. {
  8198. if (conn) {
  8199. (void)pthread_mutex_lock(&conn->mutex);
  8200. }
  8201. }
  8202. void
  8203. mg_unlock_connection(struct mg_connection *conn)
  8204. {
  8205. if (conn) {
  8206. (void)pthread_mutex_unlock(&conn->mutex);
  8207. }
  8208. }
  8209. void
  8210. mg_lock_context(struct mg_context *ctx)
  8211. {
  8212. if (ctx) {
  8213. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  8214. }
  8215. }
  8216. void
  8217. mg_unlock_context(struct mg_context *ctx)
  8218. {
  8219. if (ctx) {
  8220. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  8221. }
  8222. }
  8223. #if defined(USE_TIMERS)
  8224. #include "timer.inl"
  8225. #endif /* USE_TIMERS */
  8226. #ifdef USE_LUA
  8227. #include "mod_lua.inl"
  8228. #endif /* USE_LUA */
  8229. #ifdef USE_DUKTAPE
  8230. #include "mod_duktape.inl"
  8231. #endif /* USE_DUKTAPE */
  8232. #if defined(USE_WEBSOCKET)
  8233. #if !defined(NO_SSL_DL)
  8234. #define SHA_API static
  8235. #include "sha1.inl"
  8236. #endif
  8237. static int
  8238. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  8239. {
  8240. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  8241. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  8242. SHA_CTX sha_ctx;
  8243. int truncated;
  8244. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  8245. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  8246. if (truncated) {
  8247. conn->must_close = 1;
  8248. return 0;
  8249. }
  8250. SHA1_Init(&sha_ctx);
  8251. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  8252. SHA1_Final((unsigned char *)sha, &sha_ctx);
  8253. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  8254. mg_printf(conn,
  8255. "HTTP/1.1 101 Switching Protocols\r\n"
  8256. "Upgrade: websocket\r\n"
  8257. "Connection: Upgrade\r\n"
  8258. "Sec-WebSocket-Accept: %s\r\n",
  8259. b64_sha);
  8260. if (conn->request_info.acceptedWebSocketSubprotocol) {
  8261. mg_printf(conn,
  8262. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  8263. conn->request_info.acceptedWebSocketSubprotocol);
  8264. } else {
  8265. mg_printf(conn, "%s", "\r\n");
  8266. }
  8267. return 1;
  8268. }
  8269. static void
  8270. read_websocket(struct mg_connection *conn,
  8271. mg_websocket_data_handler ws_data_handler,
  8272. void *callback_data)
  8273. {
  8274. /* Pointer to the beginning of the portion of the incoming websocket
  8275. * message queue.
  8276. * The original websocket upgrade request is never removed, so the queue
  8277. * begins after it. */
  8278. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  8279. int n, error, exit_by_callback;
  8280. /* body_len is the length of the entire queue in bytes
  8281. * len is the length of the current message
  8282. * data_len is the length of the current message's data payload
  8283. * header_len is the length of the current message's header */
  8284. size_t i, len, mask_len = 0, data_len = 0, header_len, body_len;
  8285. /* "The masking key is a 32-bit value chosen at random by the client."
  8286. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  8287. */
  8288. unsigned char mask[4];
  8289. /* data points to the place where the message is stored when passed to
  8290. * the
  8291. * websocket_data callback. This is either mem on the stack, or a
  8292. * dynamically allocated buffer if it is too large. */
  8293. unsigned char mem[4096];
  8294. unsigned char *data = mem;
  8295. unsigned char mop; /* mask flag and opcode */
  8296. double timeout = -1.0;
  8297. if (conn->ctx->config[WEBSOCKET_TIMEOUT]) {
  8298. timeout = atoi(conn->ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  8299. }
  8300. if ((timeout <= 0.0) && (conn->ctx->config[REQUEST_TIMEOUT])) {
  8301. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  8302. }
  8303. mg_set_thread_name("wsock");
  8304. /* Loop continuously, reading messages from the socket, invoking the
  8305. * callback, and waiting repeatedly until an error occurs. */
  8306. while (!conn->ctx->stop_flag) {
  8307. header_len = 0;
  8308. assert(conn->data_len >= conn->request_len);
  8309. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  8310. len = buf[1] & 127;
  8311. mask_len = (buf[1] & 128) ? 4 : 0;
  8312. if ((len < 126) && (body_len >= mask_len)) {
  8313. data_len = len;
  8314. header_len = 2 + mask_len;
  8315. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  8316. header_len = 4 + mask_len;
  8317. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  8318. } else if (body_len >= (10 + mask_len)) {
  8319. header_len = 10 + mask_len;
  8320. data_len = (((uint64_t)ntohl(*(uint32_t *)(void *)&buf[2]))
  8321. << 32) + ntohl(*(uint32_t *)(void *)&buf[6]);
  8322. }
  8323. }
  8324. if (header_len > 0 && body_len >= header_len) {
  8325. /* Allocate space to hold websocket payload */
  8326. data = mem;
  8327. if (data_len > sizeof(mem)) {
  8328. data = (unsigned char *)mg_malloc(data_len);
  8329. if (data == NULL) {
  8330. /* Allocation failed, exit the loop and then close the
  8331. * connection */
  8332. mg_cry(conn, "websocket out of memory; closing connection");
  8333. break;
  8334. }
  8335. }
  8336. /* Copy the mask before we shift the queue and destroy it */
  8337. if (mask_len > 0) {
  8338. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  8339. } else {
  8340. memset(mask, 0, sizeof(mask));
  8341. }
  8342. /* Read frame payload from the first message in the queue into
  8343. * data and advance the queue by moving the memory in place. */
  8344. assert(body_len >= header_len);
  8345. if (data_len + header_len > body_len) {
  8346. mop = buf[0]; /* current mask and opcode */
  8347. /* Overflow case */
  8348. len = body_len - header_len;
  8349. memcpy(data, buf + header_len, len);
  8350. error = 0;
  8351. while (len < data_len) {
  8352. n = pull(NULL,
  8353. conn,
  8354. (char *)(data + len),
  8355. (int)(data_len - len),
  8356. timeout);
  8357. if (n <= 0) {
  8358. error = 1;
  8359. break;
  8360. }
  8361. len += (size_t)n;
  8362. }
  8363. if (error) {
  8364. mg_cry(conn, "Websocket pull failed; closing connection");
  8365. break;
  8366. }
  8367. conn->data_len = conn->request_len;
  8368. } else {
  8369. mop = buf[0]; /* current mask and opcode, overwritten by
  8370. * memmove() */
  8371. /* Length of the message being read at the front of the
  8372. * queue */
  8373. len = data_len + header_len;
  8374. /* Copy the data payload into the data pointer for the
  8375. * callback */
  8376. memcpy(data, buf + header_len, data_len);
  8377. /* Move the queue forward len bytes */
  8378. memmove(buf, buf + len, body_len - len);
  8379. /* Mark the queue as advanced */
  8380. conn->data_len -= (int)len;
  8381. }
  8382. /* Apply mask if necessary */
  8383. if (mask_len > 0) {
  8384. for (i = 0; i < data_len; ++i) {
  8385. data[i] ^= mask[i & 3];
  8386. }
  8387. }
  8388. /* Exit the loop if callback signals to exit (server side),
  8389. * or "connection close" opcode received (client side). */
  8390. exit_by_callback = 0;
  8391. if ((ws_data_handler != NULL)
  8392. && !ws_data_handler(
  8393. conn, mop, (char *)data, data_len, callback_data)) {
  8394. exit_by_callback = 1;
  8395. }
  8396. if (data != mem) {
  8397. mg_free(data);
  8398. }
  8399. if (exit_by_callback
  8400. || ((mop & 0xf) == WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  8401. /* Opcode == 8, connection close */
  8402. break;
  8403. }
  8404. /* Not breaking the loop, process next websocket frame. */
  8405. } else {
  8406. /* Read from the socket into the next available location in the
  8407. * message queue. */
  8408. if ((n = pull(NULL,
  8409. conn,
  8410. conn->buf + conn->data_len,
  8411. conn->buf_size - conn->data_len,
  8412. timeout)) <= 0) {
  8413. /* Error, no bytes read */
  8414. break;
  8415. }
  8416. conn->data_len += n;
  8417. }
  8418. }
  8419. mg_set_thread_name("worker");
  8420. }
  8421. static int
  8422. mg_websocket_write_exec(struct mg_connection *conn,
  8423. int opcode,
  8424. const char *data,
  8425. size_t dataLen,
  8426. uint32_t masking_key)
  8427. {
  8428. unsigned char header[14];
  8429. size_t headerLen = 1;
  8430. int retval = -1;
  8431. #if defined(__GNUC__) || defined(__MINGW32__)
  8432. /* Disable spurious conversion warning for GCC */
  8433. #pragma GCC diagnostic push
  8434. #pragma GCC diagnostic ignored "-Wconversion"
  8435. #endif
  8436. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  8437. #if defined(__GNUC__) || defined(__MINGW32__)
  8438. #pragma GCC diagnostic pop
  8439. #endif
  8440. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  8441. if (dataLen < 126) {
  8442. /* inline 7-bit length field */
  8443. header[1] = (unsigned char)dataLen;
  8444. headerLen = 2;
  8445. } else if (dataLen <= 0xFFFF) {
  8446. /* 16-bit length field */
  8447. uint16_t len = htons((uint16_t)dataLen);
  8448. header[1] = 126;
  8449. memcpy(header + 2, &len, 2);
  8450. headerLen = 4;
  8451. } else {
  8452. /* 64-bit length field */
  8453. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  8454. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  8455. header[1] = 127;
  8456. memcpy(header + 2, &len1, 4);
  8457. memcpy(header + 6, &len2, 4);
  8458. headerLen = 10;
  8459. }
  8460. if (masking_key) {
  8461. /* add mask */
  8462. header[1] |= 0x80;
  8463. memcpy(header + headerLen, &masking_key, 4);
  8464. headerLen += 4;
  8465. }
  8466. /* Note that POSIX/Winsock's send() is threadsafe
  8467. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  8468. * but mongoose's mg_printf/mg_write is not (because of the loop in
  8469. * push(), although that is only a problem if the packet is large or
  8470. * outgoing buffer is full). */
  8471. (void)mg_lock_connection(conn);
  8472. retval = mg_write(conn, header, headerLen);
  8473. if (dataLen > 0) {
  8474. retval = mg_write(conn, data, dataLen);
  8475. }
  8476. mg_unlock_connection(conn);
  8477. return retval;
  8478. }
  8479. int
  8480. mg_websocket_write(struct mg_connection *conn,
  8481. int opcode,
  8482. const char *data,
  8483. size_t dataLen)
  8484. {
  8485. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  8486. }
  8487. static void
  8488. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  8489. {
  8490. size_t i = 0;
  8491. i = 0;
  8492. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  8493. /* Convert in 32 bit words, if data is 4 byte aligned */
  8494. while (i < (in_len - 3)) {
  8495. *(uint32_t *)(void *)(out + i) =
  8496. *(uint32_t *)(void *)(in + i) ^ masking_key;
  8497. i += 4;
  8498. }
  8499. }
  8500. if (i != in_len) {
  8501. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  8502. while (i < in_len) {
  8503. *(uint8_t *)(void *)(out + i) =
  8504. *(uint8_t *)(void *)(in + i)
  8505. ^ *(((uint8_t *)&masking_key) + (i % 4));
  8506. i++;
  8507. }
  8508. }
  8509. }
  8510. int
  8511. mg_websocket_client_write(struct mg_connection *conn,
  8512. int opcode,
  8513. const char *data,
  8514. size_t dataLen)
  8515. {
  8516. int retval = -1;
  8517. char *masked_data = (char *)mg_malloc(((dataLen + 7) / 4) * 4);
  8518. uint32_t masking_key = (uint32_t)get_random();
  8519. if (masked_data == NULL) {
  8520. /* Return -1 in an error case */
  8521. mg_cry(conn,
  8522. "Cannot allocate buffer for masked websocket response: "
  8523. "Out of memory");
  8524. return -1;
  8525. }
  8526. mask_data(data, dataLen, masking_key, masked_data);
  8527. retval = mg_websocket_write_exec(
  8528. conn, opcode, masked_data, dataLen, masking_key);
  8529. mg_free(masked_data);
  8530. return retval;
  8531. }
  8532. static void
  8533. handle_websocket_request(struct mg_connection *conn,
  8534. const char *path,
  8535. int is_callback_resource,
  8536. struct mg_websocket_subprotocols *subprotocols,
  8537. mg_websocket_connect_handler ws_connect_handler,
  8538. mg_websocket_ready_handler ws_ready_handler,
  8539. mg_websocket_data_handler ws_data_handler,
  8540. mg_websocket_close_handler ws_close_handler,
  8541. void *cbData)
  8542. {
  8543. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  8544. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  8545. int lua_websock = 0;
  8546. #if !defined(USE_LUA)
  8547. (void)path;
  8548. #endif
  8549. /* Step 1: Check websocket protocol version. */
  8550. /* Step 1.1: Check Sec-WebSocket-Key. */
  8551. if (!websock_key) {
  8552. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  8553. * requires a Sec-WebSocket-Key header.
  8554. */
  8555. /* It could be the hixie draft version
  8556. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  8557. */
  8558. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  8559. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  8560. char key3[8];
  8561. if ((key1 != NULL) && (key2 != NULL)) {
  8562. /* This version uses 8 byte body data in a GET request */
  8563. conn->content_len = 8;
  8564. if (8 == mg_read(conn, key3, 8)) {
  8565. /* This is the hixie version */
  8566. send_http_error(conn,
  8567. 426,
  8568. "%s",
  8569. "Protocol upgrade to RFC 6455 required");
  8570. return;
  8571. }
  8572. }
  8573. /* This is an unknown version */
  8574. send_http_error(conn, 400, "%s", "Malformed websocket request");
  8575. return;
  8576. }
  8577. /* Step 1.2: Check websocket protocol version. */
  8578. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  8579. if (version == NULL || strcmp(version, "13") != 0) {
  8580. /* Reject wrong versions */
  8581. send_http_error(conn, 426, "%s", "Protocol upgrade required");
  8582. return;
  8583. }
  8584. /* Step 1.3: Could check for "Host", but we do not really nead this
  8585. * value for anything, so just ignore it. */
  8586. /* Step 2: If a callback is responsible, call it. */
  8587. if (is_callback_resource) {
  8588. /* Step 2.1 check and select subprotocol */
  8589. const char *protocol = mg_get_header(conn, "Sec-WebSocket-Protocol");
  8590. if (protocol && subprotocols) {
  8591. int idx;
  8592. unsigned long len;
  8593. const char *sep, *curSubProtocol,
  8594. *acceptedWebSocketSubprotocol = NULL;
  8595. /* look for matching subprotocol */
  8596. do {
  8597. sep = strchr(protocol, ',');
  8598. curSubProtocol = protocol;
  8599. len = sep ? (unsigned long)(sep - protocol)
  8600. : (unsigned long)strlen(protocol);
  8601. while (sep && isspace(*++sep)) {
  8602. ; /* ignore leading whitespaces */
  8603. }
  8604. protocol = sep;
  8605. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  8606. if ((strlen(subprotocols->subprotocols[idx]) == len)
  8607. && (strncmp(curSubProtocol,
  8608. subprotocols->subprotocols[idx],
  8609. len) == 0)) {
  8610. acceptedWebSocketSubprotocol =
  8611. subprotocols->subprotocols[idx];
  8612. break;
  8613. }
  8614. }
  8615. } while (sep && !acceptedWebSocketSubprotocol);
  8616. conn->request_info.acceptedWebSocketSubprotocol =
  8617. acceptedWebSocketSubprotocol;
  8618. } else if (protocol) {
  8619. /* keep legacy behavior */
  8620. /* The protocol is a comma seperated list of names. */
  8621. /* The server must only return one value from this list. */
  8622. /* First check if it is a list or just a single value. */
  8623. const char *sep = strrchr(protocol, ',');
  8624. if (sep == NULL) {
  8625. /* Just a single protocol -> accept it. */
  8626. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  8627. } else {
  8628. /* Multiple protocols -> accept the last one. */
  8629. /* This is just a quick fix if the client offers multiple
  8630. * protocols. The handler should have a list of accepted
  8631. * protocols on his own
  8632. * and use it to select one protocol among those the client has
  8633. * offered.
  8634. */
  8635. while (isspace(*++sep)) {
  8636. ; /* ignore leading whitespaces */
  8637. }
  8638. conn->request_info.acceptedWebSocketSubprotocol = sep;
  8639. }
  8640. }
  8641. if (ws_connect_handler != NULL
  8642. && ws_connect_handler(conn, cbData) != 0) {
  8643. /* C callback has returned non-zero, do not proceed with
  8644. * handshake.
  8645. */
  8646. /* Note that C callbacks are no longer called when Lua is
  8647. * responsible, so C can no longer filter callbacks for Lua. */
  8648. return;
  8649. }
  8650. }
  8651. #if defined(USE_LUA)
  8652. /* Step 3: No callback. Check if Lua is responsible. */
  8653. else {
  8654. /* Step 3.1: Check if Lua is responsible. */
  8655. if (conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  8656. lua_websock =
  8657. match_prefix(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  8658. strlen(
  8659. conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  8660. path);
  8661. }
  8662. if (lua_websock) {
  8663. /* Step 3.2: Lua is responsible: call it. */
  8664. conn->lua_websocket_state = lua_websocket_new(path, conn);
  8665. if (!conn->lua_websocket_state) {
  8666. /* Lua rejected the new client */
  8667. return;
  8668. }
  8669. }
  8670. }
  8671. #endif
  8672. /* Step 4: Check if there is a responsible websocket handler. */
  8673. if (!is_callback_resource && !lua_websock) {
  8674. /* There is no callback, and Lua is not responsible either. */
  8675. /* Reply with a 404 Not Found. We are still at a standard
  8676. * HTTP request here, before the websocket handshake, so
  8677. * we can still send standard HTTP error replies. */
  8678. send_http_error(conn, 404, "%s", "Not found");
  8679. return;
  8680. }
  8681. /* Step 5: The websocket connection has been accepted */
  8682. if (!send_websocket_handshake(conn, websock_key)) {
  8683. send_http_error(conn, 500, "%s", "Websocket handshake failed");
  8684. return;
  8685. }
  8686. /* Step 6: Call the ready handler */
  8687. if (is_callback_resource) {
  8688. if (ws_ready_handler != NULL) {
  8689. ws_ready_handler(conn, cbData);
  8690. }
  8691. #if defined(USE_LUA)
  8692. } else if (lua_websock) {
  8693. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  8694. /* the ready handler returned false */
  8695. return;
  8696. }
  8697. #endif
  8698. }
  8699. /* Step 7: Enter the read loop */
  8700. if (is_callback_resource) {
  8701. read_websocket(conn, ws_data_handler, cbData);
  8702. #if defined(USE_LUA)
  8703. } else if (lua_websock) {
  8704. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  8705. #endif
  8706. }
  8707. /* Step 8: Call the close handler */
  8708. if (ws_close_handler) {
  8709. ws_close_handler(conn, cbData);
  8710. }
  8711. }
  8712. static int
  8713. is_websocket_protocol(const struct mg_connection *conn)
  8714. {
  8715. const char *upgrade, *connection;
  8716. /* A websocket protocoll has the following HTTP headers:
  8717. *
  8718. * Connection: Upgrade
  8719. * Upgrade: Websocket
  8720. */
  8721. upgrade = mg_get_header(conn, "Upgrade");
  8722. if (upgrade == NULL) {
  8723. return 0; /* fail early, don't waste time checking other header
  8724. * fields
  8725. */
  8726. }
  8727. if (!mg_strcasestr(upgrade, "websocket")) {
  8728. return 0;
  8729. }
  8730. connection = mg_get_header(conn, "Connection");
  8731. if (connection == NULL) {
  8732. return 0;
  8733. }
  8734. if (!mg_strcasestr(connection, "upgrade")) {
  8735. return 0;
  8736. }
  8737. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  8738. * "Sec-WebSocket-Version" are also required.
  8739. * Don't check them here, since even an unsupported websocket protocol
  8740. * request still IS a websocket request (in contrast to a standard HTTP
  8741. * request). It will fail later in handle_websocket_request.
  8742. */
  8743. return 1;
  8744. }
  8745. #endif /* !USE_WEBSOCKET */
  8746. static int
  8747. isbyte(int n)
  8748. {
  8749. return n >= 0 && n <= 255;
  8750. }
  8751. static int
  8752. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  8753. {
  8754. int n, a, b, c, d, slash = 32, len = 0;
  8755. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5
  8756. || sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) && isbyte(a)
  8757. && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0
  8758. && slash < 33) {
  8759. len = n;
  8760. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  8761. | (uint32_t)d;
  8762. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  8763. }
  8764. return len;
  8765. }
  8766. static int
  8767. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  8768. {
  8769. int throttle = 0;
  8770. struct vec vec, val;
  8771. uint32_t net, mask;
  8772. char mult;
  8773. double v;
  8774. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  8775. mult = ',';
  8776. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  8777. || (v < 0) || ((lowercase(&mult) != 'k')
  8778. && (lowercase(&mult) != 'm') && (mult != ','))) {
  8779. continue;
  8780. }
  8781. v *= (lowercase(&mult) == 'k')
  8782. ? 1024
  8783. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  8784. if (vec.len == 1 && vec.ptr[0] == '*') {
  8785. throttle = (int)v;
  8786. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  8787. if ((remote_ip & mask) == net) {
  8788. throttle = (int)v;
  8789. }
  8790. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  8791. throttle = (int)v;
  8792. }
  8793. }
  8794. return throttle;
  8795. }
  8796. static uint32_t
  8797. get_remote_ip(const struct mg_connection *conn)
  8798. {
  8799. if (!conn) {
  8800. return 0;
  8801. }
  8802. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  8803. }
  8804. /* The mg_upload function is superseeded by mg_handle_form_request. */
  8805. #include "handle_form.inl"
  8806. #if defined(MG_LEGACY_INTERFACE)
  8807. /* Implement the deprecated mg_upload function by calling the new
  8808. * mg_handle_form_request function. While mg_upload could only handle
  8809. * HTML forms sent as POST request in multipart/form-data format
  8810. * containing only file input elements, mg_handle_form_request can
  8811. * handle all form input elements and all standard request methods. */
  8812. struct mg_upload_user_data {
  8813. struct mg_connection *conn;
  8814. const char *destination_dir;
  8815. int num_uploaded_files;
  8816. };
  8817. /* Helper function for deprecated mg_upload. */
  8818. static int
  8819. mg_upload_field_found(const char *key,
  8820. const char *filename,
  8821. char *path,
  8822. size_t pathlen,
  8823. void *user_data)
  8824. {
  8825. int truncated = 0;
  8826. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  8827. (void)key;
  8828. if (!filename) {
  8829. mg_cry(fud->conn, "%s: No filename set", __func__);
  8830. return FORM_FIELD_STORAGE_ABORT;
  8831. }
  8832. mg_snprintf(fud->conn,
  8833. &truncated,
  8834. path,
  8835. pathlen - 1,
  8836. "%s/%s",
  8837. fud->destination_dir,
  8838. filename);
  8839. if (!truncated) {
  8840. mg_cry(fud->conn, "%s: File path too long", __func__);
  8841. return FORM_FIELD_STORAGE_ABORT;
  8842. }
  8843. return FORM_FIELD_STORAGE_STORE;
  8844. }
  8845. /* Helper function for deprecated mg_upload. */
  8846. static int
  8847. mg_upload_field_get(const char *key,
  8848. const char *value,
  8849. size_t value_size,
  8850. void *user_data)
  8851. {
  8852. /* Function should never be called */
  8853. (void)key;
  8854. (void)value;
  8855. (void)value_size;
  8856. (void)user_data;
  8857. return 0;
  8858. }
  8859. /* Helper function for deprecated mg_upload. */
  8860. static int
  8861. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  8862. {
  8863. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  8864. (void)file_size;
  8865. fud->num_uploaded_files++;
  8866. fud->conn->ctx->callbacks.upload(fud->conn, path);
  8867. return 0;
  8868. }
  8869. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  8870. int
  8871. mg_upload(struct mg_connection *conn, const char *destination_dir)
  8872. {
  8873. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  8874. struct mg_form_data_handler fdh = {mg_upload_field_found,
  8875. mg_upload_field_get,
  8876. mg_upload_field_stored,
  8877. 0};
  8878. int ret;
  8879. fdh.user_data = (void *)&fud;
  8880. ret = mg_handle_form_request(conn, &fdh);
  8881. if (ret < 0) {
  8882. mg_cry(conn, "%s: Error while parsing the request", __func__);
  8883. }
  8884. return fud.num_uploaded_files;
  8885. }
  8886. #endif
  8887. static int
  8888. get_first_ssl_listener_index(const struct mg_context *ctx)
  8889. {
  8890. unsigned int i;
  8891. int idx = -1;
  8892. if (ctx) {
  8893. for (i = 0; idx == -1 && i < ctx->num_listening_sockets; i++) {
  8894. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  8895. }
  8896. }
  8897. return idx;
  8898. }
  8899. static void
  8900. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  8901. {
  8902. char host[1025];
  8903. const char *host_header;
  8904. size_t hostlen;
  8905. host_header = mg_get_header(conn, "Host");
  8906. hostlen = sizeof(host);
  8907. if (host_header != NULL) {
  8908. char *pos;
  8909. mg_strlcpy(host, host_header, hostlen);
  8910. host[hostlen - 1] = '\0';
  8911. pos = strchr(host, ':');
  8912. if (pos != NULL) {
  8913. *pos = '\0';
  8914. }
  8915. } else {
  8916. /* Cannot get host from the Host: header.
  8917. * Fallback to our IP address. */
  8918. if (conn) {
  8919. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  8920. }
  8921. }
  8922. /* Send host, port, uri and (if it exists) ?query_string */
  8923. if (conn) {
  8924. mg_printf(conn,
  8925. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  8926. host,
  8927. #if defined(USE_IPV6)
  8928. (conn->ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  8929. == AF_INET6)
  8930. ? (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  8931. .lsa.sin6.sin6_port)
  8932. :
  8933. #endif
  8934. (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  8935. .lsa.sin.sin_port),
  8936. conn->request_info.local_uri,
  8937. (conn->request_info.query_string == NULL) ? "" : "?",
  8938. (conn->request_info.query_string == NULL)
  8939. ? ""
  8940. : conn->request_info.query_string);
  8941. }
  8942. }
  8943. static void
  8944. mg_set_handler_type(struct mg_context *ctx,
  8945. const char *uri,
  8946. int handler_type,
  8947. int is_delete_request,
  8948. mg_request_handler handler,
  8949. struct mg_websocket_subprotocols *subprotocols,
  8950. mg_websocket_connect_handler connect_handler,
  8951. mg_websocket_ready_handler ready_handler,
  8952. mg_websocket_data_handler data_handler,
  8953. mg_websocket_close_handler close_handler,
  8954. mg_authorization_handler auth_handler,
  8955. void *cbdata)
  8956. {
  8957. struct mg_handler_info *tmp_rh, **lastref;
  8958. size_t urilen = strlen(uri);
  8959. if (handler_type == WEBSOCKET_HANDLER) {
  8960. /* assert(handler == NULL); */
  8961. /* assert(is_delete_request || connect_handler!=NULL ||
  8962. * ready_handler!=NULL || data_handler!=NULL ||
  8963. * close_handler!=NULL);
  8964. */
  8965. /* assert(auth_handler == NULL); */
  8966. if (handler != NULL) {
  8967. return;
  8968. }
  8969. if (!is_delete_request && connect_handler == NULL
  8970. && ready_handler == NULL
  8971. && data_handler == NULL
  8972. && close_handler == NULL) {
  8973. return;
  8974. }
  8975. if (auth_handler != NULL) {
  8976. return;
  8977. }
  8978. } else if (handler_type == REQUEST_HANDLER) {
  8979. /* assert(connect_handler==NULL && ready_handler==NULL &&
  8980. * data_handler==NULL && close_handler==NULL); */
  8981. /* assert(is_delete_request || (handler!=NULL));
  8982. */
  8983. /* assert(auth_handler == NULL); */
  8984. if (connect_handler != NULL || ready_handler != NULL
  8985. || data_handler != NULL
  8986. || close_handler != NULL) {
  8987. return;
  8988. }
  8989. if (!is_delete_request && (handler == NULL)) {
  8990. return;
  8991. }
  8992. if (auth_handler != NULL) {
  8993. return;
  8994. }
  8995. } else { /* AUTH_HANDLER */
  8996. /* assert(handler == NULL); */
  8997. /* assert(connect_handler==NULL && ready_handler==NULL &&
  8998. * data_handler==NULL && close_handler==NULL); */
  8999. /* assert(auth_handler != NULL); */
  9000. if (handler != NULL) {
  9001. return;
  9002. }
  9003. if (connect_handler != NULL || ready_handler != NULL
  9004. || data_handler != NULL
  9005. || close_handler != NULL) {
  9006. return;
  9007. }
  9008. if (!is_delete_request && (auth_handler == NULL)) {
  9009. return;
  9010. }
  9011. }
  9012. if (!ctx) {
  9013. return;
  9014. }
  9015. mg_lock_context(ctx);
  9016. /* first try to find an existing handler */
  9017. lastref = &(ctx->handlers);
  9018. for (tmp_rh = ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  9019. if (tmp_rh->handler_type == handler_type) {
  9020. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  9021. if (!is_delete_request) {
  9022. /* update existing handler */
  9023. if (handler_type == REQUEST_HANDLER) {
  9024. tmp_rh->handler = handler;
  9025. } else if (handler_type == WEBSOCKET_HANDLER) {
  9026. tmp_rh->subprotocols = subprotocols;
  9027. tmp_rh->connect_handler = connect_handler;
  9028. tmp_rh->ready_handler = ready_handler;
  9029. tmp_rh->data_handler = data_handler;
  9030. tmp_rh->close_handler = close_handler;
  9031. } else { /* AUTH_HANDLER */
  9032. tmp_rh->auth_handler = auth_handler;
  9033. }
  9034. tmp_rh->cbdata = cbdata;
  9035. } else {
  9036. /* remove existing handler */
  9037. *lastref = tmp_rh->next;
  9038. mg_free(tmp_rh->uri);
  9039. mg_free(tmp_rh);
  9040. }
  9041. mg_unlock_context(ctx);
  9042. return;
  9043. }
  9044. }
  9045. lastref = &(tmp_rh->next);
  9046. }
  9047. if (is_delete_request) {
  9048. /* no handler to set, this was a remove request to a non-existing
  9049. * handler */
  9050. mg_unlock_context(ctx);
  9051. return;
  9052. }
  9053. tmp_rh =
  9054. (struct mg_handler_info *)mg_calloc(sizeof(struct mg_handler_info), 1);
  9055. if (tmp_rh == NULL) {
  9056. mg_unlock_context(ctx);
  9057. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  9058. return;
  9059. }
  9060. tmp_rh->uri = mg_strdup(uri);
  9061. if (!tmp_rh->uri) {
  9062. mg_unlock_context(ctx);
  9063. mg_free(tmp_rh);
  9064. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  9065. return;
  9066. }
  9067. tmp_rh->uri_len = urilen;
  9068. if (handler_type == REQUEST_HANDLER) {
  9069. tmp_rh->handler = handler;
  9070. } else if (handler_type == WEBSOCKET_HANDLER) {
  9071. tmp_rh->subprotocols = subprotocols;
  9072. tmp_rh->connect_handler = connect_handler;
  9073. tmp_rh->ready_handler = ready_handler;
  9074. tmp_rh->data_handler = data_handler;
  9075. tmp_rh->close_handler = close_handler;
  9076. } else { /* AUTH_HANDLER */
  9077. tmp_rh->auth_handler = auth_handler;
  9078. }
  9079. tmp_rh->cbdata = cbdata;
  9080. tmp_rh->handler_type = handler_type;
  9081. tmp_rh->next = NULL;
  9082. *lastref = tmp_rh;
  9083. mg_unlock_context(ctx);
  9084. }
  9085. void
  9086. mg_set_request_handler(struct mg_context *ctx,
  9087. const char *uri,
  9088. mg_request_handler handler,
  9089. void *cbdata)
  9090. {
  9091. mg_set_handler_type(ctx,
  9092. uri,
  9093. REQUEST_HANDLER,
  9094. handler == NULL,
  9095. handler,
  9096. NULL,
  9097. NULL,
  9098. NULL,
  9099. NULL,
  9100. NULL,
  9101. NULL,
  9102. cbdata);
  9103. }
  9104. void
  9105. mg_set_websocket_handler(struct mg_context *ctx,
  9106. const char *uri,
  9107. mg_websocket_connect_handler connect_handler,
  9108. mg_websocket_ready_handler ready_handler,
  9109. mg_websocket_data_handler data_handler,
  9110. mg_websocket_close_handler close_handler,
  9111. void *cbdata)
  9112. {
  9113. mg_set_websocket_handler_with_subprotocols(ctx,
  9114. uri,
  9115. NULL,
  9116. connect_handler,
  9117. ready_handler,
  9118. data_handler,
  9119. close_handler,
  9120. cbdata);
  9121. }
  9122. void
  9123. mg_set_websocket_handler_with_subprotocols(
  9124. struct mg_context *ctx,
  9125. const char *uri,
  9126. struct mg_websocket_subprotocols *subprotocols,
  9127. mg_websocket_connect_handler connect_handler,
  9128. mg_websocket_ready_handler ready_handler,
  9129. mg_websocket_data_handler data_handler,
  9130. mg_websocket_close_handler close_handler,
  9131. void *cbdata)
  9132. {
  9133. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  9134. && (data_handler == NULL)
  9135. && (close_handler == NULL);
  9136. mg_set_handler_type(ctx,
  9137. uri,
  9138. WEBSOCKET_HANDLER,
  9139. is_delete_request,
  9140. NULL,
  9141. subprotocols,
  9142. connect_handler,
  9143. ready_handler,
  9144. data_handler,
  9145. close_handler,
  9146. NULL,
  9147. cbdata);
  9148. }
  9149. void
  9150. mg_set_auth_handler(struct mg_context *ctx,
  9151. const char *uri,
  9152. mg_request_handler handler,
  9153. void *cbdata)
  9154. {
  9155. mg_set_handler_type(ctx,
  9156. uri,
  9157. AUTH_HANDLER,
  9158. handler == NULL,
  9159. NULL,
  9160. NULL,
  9161. NULL,
  9162. NULL,
  9163. NULL,
  9164. NULL,
  9165. handler,
  9166. cbdata);
  9167. }
  9168. static int
  9169. get_request_handler(struct mg_connection *conn,
  9170. int handler_type,
  9171. mg_request_handler *handler,
  9172. struct mg_websocket_subprotocols **subprotocols,
  9173. mg_websocket_connect_handler *connect_handler,
  9174. mg_websocket_ready_handler *ready_handler,
  9175. mg_websocket_data_handler *data_handler,
  9176. mg_websocket_close_handler *close_handler,
  9177. mg_authorization_handler *auth_handler,
  9178. void **cbdata)
  9179. {
  9180. const struct mg_request_info *request_info = mg_get_request_info(conn);
  9181. if (request_info) {
  9182. const char *uri = request_info->local_uri;
  9183. size_t urilen = strlen(uri);
  9184. struct mg_handler_info *tmp_rh;
  9185. if (!conn || !conn->ctx) {
  9186. return 0;
  9187. }
  9188. mg_lock_context(conn->ctx);
  9189. /* first try for an exact match */
  9190. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  9191. tmp_rh = tmp_rh->next) {
  9192. if (tmp_rh->handler_type == handler_type) {
  9193. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  9194. if (handler_type == WEBSOCKET_HANDLER) {
  9195. *subprotocols = tmp_rh->subprotocols;
  9196. *connect_handler = tmp_rh->connect_handler;
  9197. *ready_handler = tmp_rh->ready_handler;
  9198. *data_handler = tmp_rh->data_handler;
  9199. *close_handler = tmp_rh->close_handler;
  9200. } else if (handler_type == REQUEST_HANDLER) {
  9201. *handler = tmp_rh->handler;
  9202. } else { /* AUTH_HANDLER */
  9203. *auth_handler = tmp_rh->auth_handler;
  9204. }
  9205. *cbdata = tmp_rh->cbdata;
  9206. mg_unlock_context(conn->ctx);
  9207. return 1;
  9208. }
  9209. }
  9210. }
  9211. /* next try for a partial match, we will accept uri/something */
  9212. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  9213. tmp_rh = tmp_rh->next) {
  9214. if (tmp_rh->handler_type == handler_type) {
  9215. if (tmp_rh->uri_len < urilen && uri[tmp_rh->uri_len] == '/'
  9216. && memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0) {
  9217. if (handler_type == WEBSOCKET_HANDLER) {
  9218. *subprotocols = tmp_rh->subprotocols;
  9219. *connect_handler = tmp_rh->connect_handler;
  9220. *ready_handler = tmp_rh->ready_handler;
  9221. *data_handler = tmp_rh->data_handler;
  9222. *close_handler = tmp_rh->close_handler;
  9223. } else if (handler_type == REQUEST_HANDLER) {
  9224. *handler = tmp_rh->handler;
  9225. } else { /* AUTH_HANDLER */
  9226. *auth_handler = tmp_rh->auth_handler;
  9227. }
  9228. *cbdata = tmp_rh->cbdata;
  9229. mg_unlock_context(conn->ctx);
  9230. return 1;
  9231. }
  9232. }
  9233. }
  9234. /* finally try for pattern match */
  9235. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  9236. tmp_rh = tmp_rh->next) {
  9237. if (tmp_rh->handler_type == handler_type) {
  9238. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  9239. if (handler_type == WEBSOCKET_HANDLER) {
  9240. *subprotocols = tmp_rh->subprotocols;
  9241. *connect_handler = tmp_rh->connect_handler;
  9242. *ready_handler = tmp_rh->ready_handler;
  9243. *data_handler = tmp_rh->data_handler;
  9244. *close_handler = tmp_rh->close_handler;
  9245. } else if (handler_type == REQUEST_HANDLER) {
  9246. *handler = tmp_rh->handler;
  9247. } else { /* AUTH_HANDLER */
  9248. *auth_handler = tmp_rh->auth_handler;
  9249. }
  9250. *cbdata = tmp_rh->cbdata;
  9251. mg_unlock_context(conn->ctx);
  9252. return 1;
  9253. }
  9254. }
  9255. }
  9256. mg_unlock_context(conn->ctx);
  9257. }
  9258. return 0; /* none found */
  9259. }
  9260. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  9261. static int
  9262. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  9263. void *cbdata)
  9264. {
  9265. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9266. if (pcallbacks->websocket_connect) {
  9267. return pcallbacks->websocket_connect(conn);
  9268. }
  9269. /* No handler set - assume "OK" */
  9270. return 0;
  9271. }
  9272. static void
  9273. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  9274. {
  9275. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9276. if (pcallbacks->websocket_ready) {
  9277. pcallbacks->websocket_ready(conn);
  9278. }
  9279. }
  9280. static int
  9281. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  9282. int bits,
  9283. char *data,
  9284. size_t len,
  9285. void *cbdata)
  9286. {
  9287. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9288. if (pcallbacks->websocket_data) {
  9289. return pcallbacks->websocket_data(conn, bits, data, len);
  9290. }
  9291. /* No handler set - assume "OK" */
  9292. return 1;
  9293. }
  9294. #endif
  9295. /* This is the heart of the Civetweb's logic.
  9296. * This function is called when the request is read, parsed and validated,
  9297. * and Civetweb must decide what action to take: serve a file, or
  9298. * a directory, or call embedded function, etcetera. */
  9299. static void
  9300. handle_request(struct mg_connection *conn)
  9301. {
  9302. struct mg_request_info *ri = &conn->request_info;
  9303. char path[PATH_MAX];
  9304. int uri_len, ssl_index;
  9305. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  9306. is_put_or_delete_request = 0, is_callback_resource = 0;
  9307. int i;
  9308. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9309. mg_request_handler callback_handler = NULL;
  9310. struct mg_websocket_subprotocols *subprotocols;
  9311. mg_websocket_connect_handler ws_connect_handler = NULL;
  9312. mg_websocket_ready_handler ws_ready_handler = NULL;
  9313. mg_websocket_data_handler ws_data_handler = NULL;
  9314. mg_websocket_close_handler ws_close_handler = NULL;
  9315. void *callback_data = NULL;
  9316. mg_authorization_handler auth_handler = NULL;
  9317. void *auth_callback_data = NULL;
  9318. #if !defined(NO_FILES)
  9319. time_t curtime = time(NULL);
  9320. char date[64];
  9321. #endif
  9322. path[0] = 0;
  9323. if (!ri) {
  9324. return;
  9325. }
  9326. /* 1. get the request url */
  9327. /* 1.1. split into url and query string */
  9328. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  9329. != NULL) {
  9330. *((char *)conn->request_info.query_string++) = '\0';
  9331. }
  9332. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  9333. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  9334. ssl_index = get_first_ssl_listener_index(conn->ctx);
  9335. if (ssl_index >= 0) {
  9336. redirect_to_https_port(conn, ssl_index);
  9337. } else {
  9338. /* A http to https forward port has been specified,
  9339. * but no https port to forward to. */
  9340. send_http_error(conn,
  9341. 503,
  9342. "%s",
  9343. "Error: SSL forward not configured properly");
  9344. mg_cry(conn, "Can not redirect to SSL, no SSL port available");
  9345. }
  9346. return;
  9347. }
  9348. uri_len = (int)strlen(ri->local_uri);
  9349. /* 1.3. decode url (if config says so) */
  9350. if (should_decode_url(conn)) {
  9351. mg_url_decode(
  9352. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  9353. }
  9354. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  9355. * not possible */
  9356. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  9357. /* step 1. completed, the url is known now */
  9358. uri_len = (int)strlen(ri->local_uri);
  9359. DEBUG_TRACE("URL: %s", ri->local_uri);
  9360. /* 3. if this ip has limited speed, set it for this connection */
  9361. conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
  9362. get_remote_ip(conn),
  9363. ri->local_uri);
  9364. /* 4. call a "handle everything" callback, if registered */
  9365. if (conn->ctx->callbacks.begin_request != NULL) {
  9366. /* Note that since V1.7 the "begin_request" function is called
  9367. * before an authorization check. If an authorization check is
  9368. * required, use a request_handler instead. */
  9369. i = conn->ctx->callbacks.begin_request(conn);
  9370. if (i > 0) {
  9371. /* callback already processed the request. Store the
  9372. return value as a status code for the access log. */
  9373. conn->status_code = i;
  9374. discard_unread_request_data(conn);
  9375. return;
  9376. } else if (i == 0) {
  9377. /* civetweb should process the request */
  9378. } else {
  9379. /* unspecified - may change with the next version */
  9380. return;
  9381. }
  9382. }
  9383. /* request not yet handled by a handler or redirect, so the request
  9384. * is processed here */
  9385. /* 5. interpret the url to find out how the request must be handled
  9386. */
  9387. /* 5.1. first test, if the request targets the regular http(s)://
  9388. * protocol namespace or the websocket ws(s):// protocol namespace.
  9389. */
  9390. is_websocket_request = is_websocket_protocol(conn);
  9391. /* 5.2. check if the request will be handled by a callback */
  9392. if (get_request_handler(conn,
  9393. is_websocket_request ? WEBSOCKET_HANDLER
  9394. : REQUEST_HANDLER,
  9395. &callback_handler,
  9396. &subprotocols,
  9397. &ws_connect_handler,
  9398. &ws_ready_handler,
  9399. &ws_data_handler,
  9400. &ws_close_handler,
  9401. NULL,
  9402. &callback_data)) {
  9403. /* 5.2.1. A callback will handle this request. All requests
  9404. * handled
  9405. * by a callback have to be considered as requests to a script
  9406. * resource. */
  9407. is_callback_resource = 1;
  9408. is_script_resource = 1;
  9409. is_put_or_delete_request = is_put_or_delete_method(conn);
  9410. } else {
  9411. no_callback_resource:
  9412. /* 5.2.2. No callback is responsible for this request. The URI
  9413. * addresses a file based resource (static content or Lua/cgi
  9414. * scripts in the file system). */
  9415. is_callback_resource = 0;
  9416. interpret_uri(conn,
  9417. path,
  9418. sizeof(path),
  9419. &file.stat,
  9420. &is_found,
  9421. &is_script_resource,
  9422. &is_websocket_request,
  9423. &is_put_or_delete_request);
  9424. }
  9425. /* 6. authorization check */
  9426. /* 6.1. a custom authorization handler is installed */
  9427. if (get_request_handler(conn,
  9428. AUTH_HANDLER,
  9429. NULL,
  9430. NULL,
  9431. NULL,
  9432. NULL,
  9433. NULL,
  9434. NULL,
  9435. &auth_handler,
  9436. &auth_callback_data)) {
  9437. if (!auth_handler(conn, auth_callback_data)) {
  9438. return;
  9439. }
  9440. } else if (is_put_or_delete_request && !is_script_resource
  9441. && !is_callback_resource) {
  9442. /* 6.2. this request is a PUT/DELETE to a real file */
  9443. /* 6.2.1. thus, the server must have real files */
  9444. #if defined(NO_FILES)
  9445. if (1) {
  9446. #else
  9447. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  9448. #endif
  9449. /* This server does not have any real files, thus the
  9450. * PUT/DELETE methods are not valid. */
  9451. send_http_error(conn,
  9452. 405,
  9453. "%s method not allowed",
  9454. conn->request_info.request_method);
  9455. return;
  9456. }
  9457. #if !defined(NO_FILES)
  9458. /* 6.2.2. Check if put authorization for static files is
  9459. * available.
  9460. */
  9461. if (!is_authorized_for_put(conn)) {
  9462. send_authorization_request(conn);
  9463. return;
  9464. }
  9465. #endif
  9466. } else {
  9467. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  9468. * or it is a PUT or DELETE request to a resource that does not
  9469. * correspond to a file. Check authorization. */
  9470. if (!check_authorization(conn, path)) {
  9471. send_authorization_request(conn);
  9472. return;
  9473. }
  9474. }
  9475. /* request is authorized or does not need authorization */
  9476. /* 7. check if there are request handlers for this uri */
  9477. if (is_callback_resource) {
  9478. if (!is_websocket_request) {
  9479. i = callback_handler(conn, callback_data);
  9480. if (i > 0) {
  9481. /* Do nothing, callback has served the request. Store
  9482. * the
  9483. * return value as status code for the log and discard
  9484. * all
  9485. * data from the client not used by the callback. */
  9486. conn->status_code = i;
  9487. discard_unread_request_data(conn);
  9488. } else {
  9489. /* TODO (high): what if the handler did NOT handle the
  9490. * request */
  9491. /* The last version did handle this as a file request,
  9492. * but
  9493. * since a file request is not always a script resource,
  9494. * the authorization check might be different */
  9495. interpret_uri(conn,
  9496. path,
  9497. sizeof(path),
  9498. &file.stat,
  9499. &is_found,
  9500. &is_script_resource,
  9501. &is_websocket_request,
  9502. &is_put_or_delete_request);
  9503. callback_handler = NULL;
  9504. /* Here we are at a dead end:
  9505. * According to URI matching, a callback should be
  9506. * responsible for handling the request,
  9507. * we called it, but the callback declared itself
  9508. * not responsible.
  9509. * We use a goto here, to get out of this dead end,
  9510. * and continue with the default handling.
  9511. * A goto here is simpler and better to understand
  9512. * than some curious loop. */
  9513. goto no_callback_resource;
  9514. }
  9515. } else {
  9516. #if defined(USE_WEBSOCKET)
  9517. handle_websocket_request(conn,
  9518. path,
  9519. is_callback_resource,
  9520. subprotocols,
  9521. ws_connect_handler,
  9522. ws_ready_handler,
  9523. ws_data_handler,
  9524. ws_close_handler,
  9525. callback_data);
  9526. #endif
  9527. }
  9528. return;
  9529. }
  9530. /* 8. handle websocket requests */
  9531. #if defined(USE_WEBSOCKET)
  9532. if (is_websocket_request) {
  9533. if (is_script_resource) {
  9534. /* Websocket Lua script */
  9535. handle_websocket_request(conn,
  9536. path,
  9537. 0 /* Lua Script */,
  9538. NULL,
  9539. NULL,
  9540. NULL,
  9541. NULL,
  9542. NULL,
  9543. &conn->ctx->callbacks);
  9544. } else {
  9545. #if defined(MG_LEGACY_INTERFACE)
  9546. handle_websocket_request(
  9547. conn,
  9548. path,
  9549. !is_script_resource /* could be deprecated global callback */,
  9550. NULL,
  9551. deprecated_websocket_connect_wrapper,
  9552. deprecated_websocket_ready_wrapper,
  9553. deprecated_websocket_data_wrapper,
  9554. NULL,
  9555. &conn->ctx->callbacks);
  9556. #else
  9557. send_http_error(conn, 404, "%s", "Not found");
  9558. #endif
  9559. }
  9560. return;
  9561. } else
  9562. #endif
  9563. #if defined(NO_FILES)
  9564. /* 9a. In case the server uses only callbacks, this uri is
  9565. * unknown.
  9566. * Then, all request handling ends here. */
  9567. send_http_error(conn, 404, "%s", "Not Found");
  9568. #else
  9569. /* 9b. This request is either for a static file or resource handled
  9570. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  9571. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  9572. send_http_error(conn, 404, "%s", "Not Found");
  9573. return;
  9574. }
  9575. /* 10. File is handled by a script. */
  9576. if (is_script_resource) {
  9577. handle_file_based_request(conn, path, &file);
  9578. return;
  9579. }
  9580. /* 11. Handle put/delete/mkcol requests */
  9581. if (is_put_or_delete_request) {
  9582. /* 11.1. PUT method */
  9583. if (!strcmp(ri->request_method, "PUT")) {
  9584. put_file(conn, path);
  9585. return;
  9586. }
  9587. /* 11.2. DELETE method */
  9588. if (!strcmp(ri->request_method, "DELETE")) {
  9589. delete_file(conn, path);
  9590. return;
  9591. }
  9592. /* 11.3. MKCOL method */
  9593. if (!strcmp(ri->request_method, "MKCOL")) {
  9594. mkcol(conn, path);
  9595. return;
  9596. }
  9597. /* 11.4. PATCH method
  9598. * This method is not supported for static resources,
  9599. * only for scripts (Lua, CGI) and callbacks. */
  9600. send_http_error(conn,
  9601. 405,
  9602. "%s method not allowed",
  9603. conn->request_info.request_method);
  9604. return;
  9605. }
  9606. /* 11. File does not exist, or it was configured that it should be
  9607. * hidden */
  9608. if (!is_found || (must_hide_file(conn, path))) {
  9609. send_http_error(conn, 404, "%s", "Not found");
  9610. return;
  9611. }
  9612. /* 12. Directory uris should end with a slash */
  9613. if (file.stat.is_directory && (uri_len > 0)
  9614. && (ri->local_uri[uri_len - 1] != '/')) {
  9615. gmt_time_string(date, sizeof(date), &curtime);
  9616. mg_printf(conn,
  9617. "HTTP/1.1 301 Moved Permanently\r\n"
  9618. "Location: %s/\r\n"
  9619. "Date: %s\r\n"
  9620. /* "Cache-Control: private\r\n" (= default) */
  9621. "Content-Length: 0\r\n"
  9622. "Connection: %s\r\n\r\n",
  9623. ri->request_uri,
  9624. date,
  9625. suggest_connection_header(conn));
  9626. return;
  9627. }
  9628. /* 13. Handle other methods than GET/HEAD */
  9629. /* 13.1. Handle PROPFIND */
  9630. if (!strcmp(ri->request_method, "PROPFIND")) {
  9631. handle_propfind(conn, path, &file.stat);
  9632. return;
  9633. }
  9634. /* 13.2. Handle OPTIONS for files */
  9635. if (!strcmp(ri->request_method, "OPTIONS")) {
  9636. /* This standard handler is only used for real files.
  9637. * Scripts should support the OPTIONS method themselves, to allow a
  9638. * maximum flexibility.
  9639. * Lua and CGI scripts may fully support CORS this way (including
  9640. * preflights). */
  9641. send_options(conn);
  9642. return;
  9643. }
  9644. /* 13.3. everything but GET and HEAD (e.g. POST) */
  9645. if (0 != strcmp(ri->request_method, "GET")
  9646. && 0 != strcmp(ri->request_method, "HEAD")) {
  9647. send_http_error(conn,
  9648. 405,
  9649. "%s method not allowed",
  9650. conn->request_info.request_method);
  9651. return;
  9652. }
  9653. /* 14. directories */
  9654. if (file.stat.is_directory) {
  9655. if (substitute_index_file(conn, path, sizeof(path), &file)) {
  9656. /* 14.1. use a substitute file */
  9657. /* TODO (high): substitute index may be a script resource.
  9658. * define what should be possible in this case. */
  9659. } else {
  9660. /* 14.2. no substitute file */
  9661. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  9662. "yes")) {
  9663. handle_directory_request(conn, path);
  9664. } else {
  9665. send_http_error(conn,
  9666. 403,
  9667. "%s",
  9668. "Error: Directory listing denied");
  9669. }
  9670. return;
  9671. }
  9672. }
  9673. handle_file_based_request(conn, path, &file);
  9674. #endif /* !defined(NO_FILES) */
  9675. #if 0
  9676. /* Perform redirect and auth checks before calling begin_request()
  9677. * handler.
  9678. * Otherwise, begin_request() would need to perform auth checks and
  9679. * redirects. */
  9680. #endif
  9681. }
  9682. static void
  9683. handle_file_based_request(struct mg_connection *conn,
  9684. const char *path,
  9685. struct mg_file *file)
  9686. {
  9687. if (!conn || !conn->ctx) {
  9688. return;
  9689. }
  9690. if (0) {
  9691. #ifdef USE_LUA
  9692. } else if (match_prefix(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  9693. strlen(
  9694. conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  9695. path) > 0) {
  9696. /* Lua server page: an SSI like page containing mostly plain html
  9697. * code
  9698. * plus some tags with server generated contents. */
  9699. handle_lsp_request(conn, path, file, NULL);
  9700. } else if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  9701. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  9702. path) > 0) {
  9703. /* Lua in-server module script: a CGI like script used to generate
  9704. * the
  9705. * entire reply. */
  9706. mg_exec_lua_script(conn, path, NULL);
  9707. #endif
  9708. #if defined(USE_DUKTAPE)
  9709. } else if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  9710. strlen(
  9711. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  9712. path) > 0) {
  9713. /* Call duktape to generate the page */
  9714. mg_exec_duktape_script(conn, path);
  9715. #endif
  9716. #if !defined(NO_CGI)
  9717. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  9718. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  9719. path) > 0) {
  9720. /* CGI scripts may support all HTTP methods */
  9721. handle_cgi_request(conn, path);
  9722. #endif /* !NO_CGI */
  9723. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  9724. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  9725. path) > 0) {
  9726. handle_ssi_file_request(conn, path, file);
  9727. #if !defined(NO_CACHING)
  9728. } else if ((!conn->in_error_handler)
  9729. && is_not_modified(conn, &file->stat)) {
  9730. /* Send 304 "Not Modified" - this must not send any body data */
  9731. handle_not_modified_static_file_request(conn, file);
  9732. #endif /* !NO_CACHING */
  9733. } else {
  9734. handle_static_file_request(conn, path, file, NULL, NULL);
  9735. }
  9736. }
  9737. static void
  9738. close_all_listening_sockets(struct mg_context *ctx)
  9739. {
  9740. unsigned int i;
  9741. if (!ctx) {
  9742. return;
  9743. }
  9744. for (i = 0; i < ctx->num_listening_sockets; i++) {
  9745. closesocket(ctx->listening_sockets[i].sock);
  9746. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  9747. }
  9748. mg_free(ctx->listening_sockets);
  9749. ctx->listening_sockets = NULL;
  9750. mg_free(ctx->listening_socket_fds);
  9751. ctx->listening_socket_fds = NULL;
  9752. }
  9753. /* Valid listening port specification is: [ip_address:]port[s]
  9754. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  9755. * Examples for IPv6: [::]:80, [::1]:80,
  9756. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  9757. * see https://tools.ietf.org/html/rfc3513#section-2.2
  9758. * In order to bind to both, IPv4 and IPv6, you can either add
  9759. * both ports using 8080,[::]:8080, or the short form +8080.
  9760. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  9761. * one only accepting IPv4 the other only IPv6. +8080 creates
  9762. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  9763. * environment, they might work differently, or might not work
  9764. * at all - it must be tested what options work best in the
  9765. * relevant network environment.
  9766. */
  9767. static int
  9768. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  9769. {
  9770. unsigned int a, b, c, d, port;
  9771. int ch, len;
  9772. #if defined(USE_IPV6)
  9773. char buf[100] = {0};
  9774. #endif
  9775. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  9776. * Also, all-zeroes in the socket address means binding to all addresses
  9777. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  9778. memset(so, 0, sizeof(*so));
  9779. so->lsa.sin.sin_family = AF_INET;
  9780. *ip_version = 0;
  9781. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  9782. == 5) {
  9783. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  9784. so->lsa.sin.sin_addr.s_addr =
  9785. htonl((a << 24) | (b << 16) | (c << 8) | d);
  9786. so->lsa.sin.sin_port = htons((uint16_t)port);
  9787. *ip_version = 4;
  9788. #if defined(USE_IPV6)
  9789. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  9790. && mg_inet_pton(
  9791. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  9792. /* IPv6 address, examples: see above */
  9793. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  9794. */
  9795. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  9796. *ip_version = 6;
  9797. #endif
  9798. } else if ((vec->ptr[0] == '+')
  9799. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  9800. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  9801. /* Add 1 to len for the + character we skipped before */
  9802. len++;
  9803. #if defined(USE_IPV6)
  9804. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  9805. so->lsa.sin6.sin6_family = AF_INET6;
  9806. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  9807. *ip_version = 4 + 6;
  9808. #else
  9809. /* Bind to IPv4 only, since IPv6 is not built in. */
  9810. so->lsa.sin.sin_port = htons((uint16_t)port);
  9811. *ip_version = 4;
  9812. #endif
  9813. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  9814. /* If only port is specified, bind to IPv4, INADDR_ANY */
  9815. so->lsa.sin.sin_port = htons((uint16_t)port);
  9816. *ip_version = 4;
  9817. } else {
  9818. /* Parsing failure. Make port invalid. */
  9819. port = 0;
  9820. len = 0;
  9821. }
  9822. /* sscanf and the option splitting code ensure the following condition
  9823. */
  9824. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  9825. *ip_version = 0;
  9826. return 0;
  9827. }
  9828. ch = vec->ptr[len]; /* Next character after the port number */
  9829. so->is_ssl = (ch == 's');
  9830. so->ssl_redir = (ch == 'r');
  9831. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  9832. if (is_valid_port(port)
  9833. && (ch == '\0' || ch == 's' || ch == 'r' || ch == ',')) {
  9834. return 1;
  9835. }
  9836. /* Reset ip_version to 0 of there is an error */
  9837. *ip_version = 0;
  9838. return 0;
  9839. }
  9840. static int
  9841. set_ports_option(struct mg_context *ctx)
  9842. {
  9843. const char *list;
  9844. int on = 1;
  9845. #if defined(USE_IPV6)
  9846. int off = 0;
  9847. #endif
  9848. struct vec vec;
  9849. struct socket so, *ptr;
  9850. struct pollfd *pfd;
  9851. union usa usa;
  9852. socklen_t len;
  9853. int ip_version;
  9854. int portsTotal = 0;
  9855. int portsOk = 0;
  9856. if (!ctx) {
  9857. return 0;
  9858. }
  9859. memset(&so, 0, sizeof(so));
  9860. memset(&usa, 0, sizeof(usa));
  9861. len = sizeof(usa);
  9862. list = ctx->config[LISTENING_PORTS];
  9863. while ((list = next_option(list, &vec, NULL)) != NULL) {
  9864. portsTotal++;
  9865. if (!parse_port_string(&vec, &so, &ip_version)) {
  9866. mg_cry(fc(ctx),
  9867. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  9868. (int)vec.len,
  9869. vec.ptr,
  9870. portsTotal,
  9871. "[IP_ADDRESS:]PORT[s|r]");
  9872. continue;
  9873. }
  9874. #if !defined(NO_SSL)
  9875. if (so.is_ssl && ctx->ssl_ctx == NULL) {
  9876. mg_cry(fc(ctx),
  9877. "Cannot add SSL socket (entry %i). Is -ssl_certificate "
  9878. "option set?",
  9879. portsTotal);
  9880. continue;
  9881. }
  9882. #endif
  9883. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  9884. == INVALID_SOCKET) {
  9885. mg_cry(fc(ctx), "cannot create socket (entry %i)", portsTotal);
  9886. continue;
  9887. }
  9888. #ifdef _WIN32
  9889. /* Windows SO_REUSEADDR lets many procs binds to a
  9890. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  9891. * if someone already has the socket -- DTL */
  9892. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  9893. * Windows might need a few seconds before
  9894. * the same port can be used again in the
  9895. * same process, so a short Sleep may be
  9896. * required between mg_stop and mg_start.
  9897. */
  9898. if (setsockopt(so.sock,
  9899. SOL_SOCKET,
  9900. SO_EXCLUSIVEADDRUSE,
  9901. (SOCK_OPT_TYPE)&on,
  9902. sizeof(on)) != 0) {
  9903. /* Set reuse option, but don't abort on errors. */
  9904. mg_cry(fc(ctx),
  9905. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  9906. portsTotal);
  9907. }
  9908. #else
  9909. if (setsockopt(so.sock,
  9910. SOL_SOCKET,
  9911. SO_REUSEADDR,
  9912. (SOCK_OPT_TYPE)&on,
  9913. sizeof(on)) != 0) {
  9914. /* Set reuse option, but don't abort on errors. */
  9915. mg_cry(fc(ctx),
  9916. "cannot set socket option SO_REUSEADDR (entry %i)",
  9917. portsTotal);
  9918. }
  9919. #endif
  9920. if (ip_version > 4) {
  9921. #if defined(USE_IPV6)
  9922. if (ip_version == 6) {
  9923. if (so.lsa.sa.sa_family == AF_INET6
  9924. && setsockopt(so.sock,
  9925. IPPROTO_IPV6,
  9926. IPV6_V6ONLY,
  9927. (void *)&off,
  9928. sizeof(off)) != 0) {
  9929. /* Set IPv6 only option, but don't abort on errors. */
  9930. mg_cry(fc(ctx),
  9931. "cannot set socket option IPV6_V6ONLY (entry %i)",
  9932. portsTotal);
  9933. }
  9934. }
  9935. #else
  9936. mg_cry(fc(ctx), "IPv6 not available");
  9937. closesocket(so.sock);
  9938. so.sock = INVALID_SOCKET;
  9939. continue;
  9940. #endif
  9941. }
  9942. if (so.lsa.sa.sa_family == AF_INET) {
  9943. len = sizeof(so.lsa.sin);
  9944. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  9945. mg_cry(fc(ctx),
  9946. "cannot bind to %.*s: %d (%s)",
  9947. (int)vec.len,
  9948. vec.ptr,
  9949. (int)ERRNO,
  9950. strerror(errno));
  9951. closesocket(so.sock);
  9952. so.sock = INVALID_SOCKET;
  9953. continue;
  9954. }
  9955. }
  9956. #if defined(USE_IPV6)
  9957. else if (so.lsa.sa.sa_family == AF_INET6) {
  9958. len = sizeof(so.lsa.sin6);
  9959. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  9960. mg_cry(fc(ctx),
  9961. "cannot bind to IPv6 %.*s: %d (%s)",
  9962. (int)vec.len,
  9963. vec.ptr,
  9964. (int)ERRNO,
  9965. strerror(errno));
  9966. closesocket(so.sock);
  9967. so.sock = INVALID_SOCKET;
  9968. continue;
  9969. }
  9970. }
  9971. #endif
  9972. else {
  9973. mg_cry(fc(ctx),
  9974. "cannot bind: address family not supported (entry %i)",
  9975. portsTotal);
  9976. continue;
  9977. }
  9978. if (listen(so.sock, SOMAXCONN) != 0) {
  9979. mg_cry(fc(ctx),
  9980. "cannot listen to %.*s: %d (%s)",
  9981. (int)vec.len,
  9982. vec.ptr,
  9983. (int)ERRNO,
  9984. strerror(errno));
  9985. closesocket(so.sock);
  9986. so.sock = INVALID_SOCKET;
  9987. continue;
  9988. }
  9989. if (getsockname(so.sock, &(usa.sa), &len) != 0
  9990. || usa.sa.sa_family != so.lsa.sa.sa_family) {
  9991. int err = (int)ERRNO;
  9992. mg_cry(fc(ctx),
  9993. "call to getsockname failed %.*s: %d (%s)",
  9994. (int)vec.len,
  9995. vec.ptr,
  9996. err,
  9997. strerror(errno));
  9998. closesocket(so.sock);
  9999. so.sock = INVALID_SOCKET;
  10000. continue;
  10001. }
  10002. /* Update lsa port in case of random free ports */
  10003. #if defined(USE_IPV6)
  10004. if (so.lsa.sa.sa_family == AF_INET6) {
  10005. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  10006. } else
  10007. #endif
  10008. {
  10009. so.lsa.sin.sin_port = usa.sin.sin_port;
  10010. }
  10011. if ((ptr = (struct socket *)
  10012. mg_realloc(ctx->listening_sockets,
  10013. (ctx->num_listening_sockets + 1)
  10014. * sizeof(ctx->listening_sockets[0]))) == NULL) {
  10015. mg_cry(fc(ctx), "%s", "Out of memory");
  10016. closesocket(so.sock);
  10017. so.sock = INVALID_SOCKET;
  10018. continue;
  10019. }
  10020. if ((pfd = (struct pollfd *)mg_realloc(
  10021. ctx->listening_socket_fds,
  10022. (ctx->num_listening_sockets + 1)
  10023. * sizeof(ctx->listening_socket_fds[0]))) == NULL) {
  10024. mg_cry(fc(ctx), "%s", "Out of memory");
  10025. closesocket(so.sock);
  10026. so.sock = INVALID_SOCKET;
  10027. mg_free(ptr);
  10028. continue;
  10029. }
  10030. set_close_on_exec(so.sock, fc(ctx));
  10031. ctx->listening_sockets = ptr;
  10032. ctx->listening_sockets[ctx->num_listening_sockets] = so;
  10033. ctx->listening_socket_fds = pfd;
  10034. ctx->num_listening_sockets++;
  10035. portsOk++;
  10036. }
  10037. if (portsOk != portsTotal) {
  10038. close_all_listening_sockets(ctx);
  10039. portsOk = 0;
  10040. }
  10041. return portsOk;
  10042. }
  10043. static const char *
  10044. header_val(const struct mg_connection *conn, const char *header)
  10045. {
  10046. const char *header_value;
  10047. if ((header_value = mg_get_header(conn, header)) == NULL) {
  10048. return "-";
  10049. } else {
  10050. return header_value;
  10051. }
  10052. }
  10053. static void
  10054. log_access(const struct mg_connection *conn)
  10055. {
  10056. const struct mg_request_info *ri;
  10057. struct mg_file fi;
  10058. char date[64], src_addr[IP_ADDR_STR_LEN];
  10059. struct tm *tm;
  10060. const char *referer;
  10061. const char *user_agent;
  10062. char buf[4096];
  10063. if (!conn || !conn->ctx) {
  10064. return;
  10065. }
  10066. if (conn->ctx->config[ACCESS_LOG_FILE] != NULL) {
  10067. if (mg_fopen(conn,
  10068. conn->ctx->config[ACCESS_LOG_FILE],
  10069. MG_FOPEN_MODE_APPEND,
  10070. &fi) == 0) {
  10071. fi.access.fp = NULL;
  10072. }
  10073. } else {
  10074. fi.access.fp = NULL;
  10075. }
  10076. /* Log is written to a file and/or a callback. If both are not set,
  10077. * executing the rest of the function is pointless. */
  10078. if ((fi.access.fp == NULL) && (conn->ctx->callbacks.log_access == NULL)) {
  10079. return;
  10080. }
  10081. tm = localtime(&conn->conn_birth_time);
  10082. if (tm != NULL) {
  10083. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  10084. } else {
  10085. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  10086. date[sizeof(date) - 1] = '\0';
  10087. }
  10088. ri = &conn->request_info;
  10089. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  10090. referer = header_val(conn, "Referer");
  10091. user_agent = header_val(conn, "User-Agent");
  10092. mg_snprintf(conn,
  10093. NULL, /* Ignore truncation in access log */
  10094. buf,
  10095. sizeof(buf),
  10096. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  10097. src_addr,
  10098. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  10099. date,
  10100. ri->request_method ? ri->request_method : "-",
  10101. ri->request_uri ? ri->request_uri : "-",
  10102. ri->query_string ? "?" : "",
  10103. ri->query_string ? ri->query_string : "",
  10104. ri->http_version,
  10105. conn->status_code,
  10106. conn->num_bytes_sent,
  10107. referer,
  10108. user_agent);
  10109. if (conn->ctx->callbacks.log_access) {
  10110. conn->ctx->callbacks.log_access(conn, buf);
  10111. }
  10112. if (fi.access.fp) {
  10113. int ok = 1;
  10114. flockfile(fi.access.fp);
  10115. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  10116. ok = 0;
  10117. }
  10118. if (fflush(fi.access.fp) != 0) {
  10119. ok = 0;
  10120. }
  10121. funlockfile(fi.access.fp);
  10122. if (mg_fclose(&fi.access) != 0) {
  10123. ok = 0;
  10124. }
  10125. if (!ok) {
  10126. mg_cry(conn,
  10127. "Error writing log file %s",
  10128. conn->ctx->config[ACCESS_LOG_FILE]);
  10129. }
  10130. }
  10131. }
  10132. /* Verify given socket address against the ACL.
  10133. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  10134. */
  10135. static int
  10136. check_acl(struct mg_context *ctx, uint32_t remote_ip)
  10137. {
  10138. int allowed, flag;
  10139. uint32_t net, mask;
  10140. struct vec vec;
  10141. if (ctx) {
  10142. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  10143. /* If any ACL is set, deny by default */
  10144. allowed = (list == NULL) ? '+' : '-';
  10145. while ((list = next_option(list, &vec, NULL)) != NULL) {
  10146. flag = vec.ptr[0];
  10147. if ((flag != '+' && flag != '-')
  10148. || parse_net(&vec.ptr[1], &net, &mask) == 0) {
  10149. mg_cry(fc(ctx),
  10150. "%s: subnet must be [+|-]x.x.x.x[/x]",
  10151. __func__);
  10152. return -1;
  10153. }
  10154. if (net == (remote_ip & mask)) {
  10155. allowed = flag;
  10156. }
  10157. }
  10158. return allowed == '+';
  10159. }
  10160. return -1;
  10161. }
  10162. #if !defined(_WIN32)
  10163. static int
  10164. set_uid_option(struct mg_context *ctx)
  10165. {
  10166. struct passwd *pw;
  10167. if (ctx) {
  10168. const char *uid = ctx->config[RUN_AS_USER];
  10169. int success = 0;
  10170. if (uid == NULL) {
  10171. success = 1;
  10172. } else {
  10173. if ((pw = getpwnam(uid)) == NULL) {
  10174. mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  10175. } else if (setgid(pw->pw_gid) == -1) {
  10176. mg_cry(fc(ctx),
  10177. "%s: setgid(%s): %s",
  10178. __func__,
  10179. uid,
  10180. strerror(errno));
  10181. } else if (setgroups(0, NULL)) {
  10182. mg_cry(fc(ctx),
  10183. "%s: setgroups(): %s",
  10184. __func__,
  10185. strerror(errno));
  10186. } else if (setuid(pw->pw_uid) == -1) {
  10187. mg_cry(fc(ctx),
  10188. "%s: setuid(%s): %s",
  10189. __func__,
  10190. uid,
  10191. strerror(errno));
  10192. } else {
  10193. success = 1;
  10194. }
  10195. }
  10196. return success;
  10197. }
  10198. return 0;
  10199. }
  10200. #endif /* !_WIN32 */
  10201. static void
  10202. tls_dtor(void *key)
  10203. {
  10204. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  10205. /* key == pthread_getspecific(sTlsKey); */
  10206. if (tls) {
  10207. if (tls->is_master == 2) {
  10208. tls->is_master = -3; /* Mark memory as dead */
  10209. mg_free(tls);
  10210. }
  10211. }
  10212. pthread_setspecific(sTlsKey, NULL);
  10213. }
  10214. #if !defined(NO_SSL)
  10215. static int ssl_use_pem_file(struct mg_context *ctx, const char *pem);
  10216. static const char *ssl_error(void);
  10217. static int
  10218. refresh_trust(struct mg_connection *conn)
  10219. {
  10220. static int reload_lock = 0;
  10221. static long int data_check = 0;
  10222. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  10223. struct stat cert_buf;
  10224. long int t;
  10225. char *pem;
  10226. int should_verify_peer;
  10227. if ((pem = conn->ctx->config[SSL_CERTIFICATE]) == NULL) {
  10228. /* If peem is NULL and conn->ctx->callbacks.init_ssl is not,
  10229. * refresh_trust still can not work. */
  10230. return 0;
  10231. }
  10232. t = data_check;
  10233. if (stat(pem, &cert_buf) != -1) {
  10234. t = (long int)cert_buf.st_mtime;
  10235. }
  10236. if (data_check != t) {
  10237. data_check = t;
  10238. should_verify_peer =
  10239. (conn->ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  10240. && (mg_strcasecmp(conn->ctx->config[SSL_DO_VERIFY_PEER], "yes")
  10241. == 0);
  10242. if (should_verify_peer) {
  10243. char *ca_path = conn->ctx->config[SSL_CA_PATH];
  10244. char *ca_file = conn->ctx->config[SSL_CA_FILE];
  10245. if (SSL_CTX_load_verify_locations(conn->ctx->ssl_ctx,
  10246. ca_file,
  10247. ca_path) != 1) {
  10248. mg_cry(fc(conn->ctx),
  10249. "SSL_CTX_load_verify_locations error: %s "
  10250. "ssl_verify_peer requires setting "
  10251. "either ssl_ca_path or ssl_ca_file. Is any of them "
  10252. "present in "
  10253. "the .conf file?",
  10254. ssl_error());
  10255. return 0;
  10256. }
  10257. }
  10258. if (1 == mg_atomic_inc(p_reload_lock)) {
  10259. if (ssl_use_pem_file(conn->ctx, pem) == 0) {
  10260. return 0;
  10261. }
  10262. *p_reload_lock = 0;
  10263. }
  10264. }
  10265. /* lock while cert is reloading */
  10266. while (*p_reload_lock) {
  10267. sleep(1);
  10268. }
  10269. return 1;
  10270. }
  10271. #ifdef OPENSSL_API_1_1
  10272. #else
  10273. static pthread_mutex_t *ssl_mutexes;
  10274. #endif /* OPENSSL_API_1_1 */
  10275. static int
  10276. sslize(struct mg_connection *conn,
  10277. SSL_CTX *s,
  10278. int (*func)(SSL *),
  10279. volatile int *stop_server)
  10280. {
  10281. int ret, err;
  10282. int short_trust;
  10283. unsigned i;
  10284. if (!conn) {
  10285. return 0;
  10286. }
  10287. short_trust =
  10288. (conn->ctx->config[SSL_SHORT_TRUST] != NULL)
  10289. && (mg_strcasecmp(conn->ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  10290. if (short_trust) {
  10291. int trust_ret = refresh_trust(conn);
  10292. if (!trust_ret) {
  10293. return trust_ret;
  10294. }
  10295. }
  10296. conn->ssl = SSL_new(s);
  10297. if (conn->ssl == NULL) {
  10298. return 0;
  10299. }
  10300. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  10301. if (ret != 1) {
  10302. err = SSL_get_error(conn->ssl, ret);
  10303. (void)err; /* TODO: set some error message */
  10304. SSL_free(conn->ssl);
  10305. conn->ssl = NULL;
  10306. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  10307. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  10308. #ifndef OPENSSL_API_1_1
  10309. ERR_remove_state(0);
  10310. #endif
  10311. return 0;
  10312. }
  10313. /* SSL functions may fail and require to be called again:
  10314. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  10315. * Here "func" could be SSL_connect or SSL_accept. */
  10316. for (i = 16; i <= 1024; i *= 2) {
  10317. ret = func(conn->ssl);
  10318. if (ret != 1) {
  10319. err = SSL_get_error(conn->ssl, ret);
  10320. if ((err == SSL_ERROR_WANT_CONNECT)
  10321. || (err == SSL_ERROR_WANT_ACCEPT)
  10322. || (err == SSL_ERROR_WANT_READ)
  10323. || (err == SSL_ERROR_WANT_WRITE)) {
  10324. /* Need to retry the function call "later".
  10325. * See https://linux.die.net/man/3/ssl_get_error
  10326. * This is typical for non-blocking sockets. */
  10327. if (*stop_server) {
  10328. /* Don't wait if the server is going to be stopped. */
  10329. break;
  10330. }
  10331. mg_sleep(i);
  10332. } else if (err == SSL_ERROR_SYSCALL) {
  10333. /* This is an IO error. Look at errno. */
  10334. err = errno;
  10335. /* TODO: set some error message */
  10336. break;
  10337. } else {
  10338. /* This is an SSL specific error */
  10339. /* TODO: set some error message */
  10340. break;
  10341. }
  10342. } else {
  10343. /* success */
  10344. break;
  10345. }
  10346. }
  10347. if (ret != 1) {
  10348. SSL_free(conn->ssl);
  10349. conn->ssl = NULL;
  10350. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  10351. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  10352. #ifndef OPENSSL_API_1_1
  10353. ERR_remove_state(0);
  10354. #endif
  10355. return 0;
  10356. }
  10357. return 1;
  10358. }
  10359. /* Return OpenSSL error message (from CRYPTO lib) */
  10360. static const char *
  10361. ssl_error(void)
  10362. {
  10363. unsigned long err;
  10364. err = ERR_get_error();
  10365. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  10366. }
  10367. static int
  10368. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  10369. {
  10370. int i;
  10371. const char hexdigit[] = "0123456789abcdef";
  10372. if (memlen <= 0 || buflen <= 0) {
  10373. return 0;
  10374. }
  10375. if (buflen < (3 * memlen)) {
  10376. return 0;
  10377. }
  10378. for (i = 0; i < memlen; i++) {
  10379. if (i > 0) {
  10380. buf[3 * i - 1] = ' ';
  10381. }
  10382. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  10383. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  10384. }
  10385. buf[3 * memlen - 1] = 0;
  10386. return 1;
  10387. }
  10388. static void
  10389. ssl_get_client_cert_info(struct mg_connection *conn)
  10390. {
  10391. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  10392. if (cert) {
  10393. char str_subject[1024];
  10394. char str_issuer[1024];
  10395. char str_finger[1024];
  10396. unsigned char buf[256];
  10397. char *str_serial = NULL;
  10398. unsigned int ulen;
  10399. /* Handle to algorithm used for fingerprint */
  10400. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  10401. /* Get Subject and issuer */
  10402. X509_NAME *subj = X509_get_subject_name(cert);
  10403. X509_NAME *iss = X509_get_issuer_name(cert);
  10404. /* Get serial number */
  10405. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  10406. /* Translate serial number to a hex string */
  10407. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  10408. str_serial = BN_bn2hex(serial_bn);
  10409. BN_free(serial_bn);
  10410. /* Translate subject and issuer to a string */
  10411. (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
  10412. (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
  10413. /* Calculate SHA1 fingerprint and store as a hex string */
  10414. ulen = 0;
  10415. ASN1_digest((int (*)())i2d_X509, digest, (char *)cert, buf, &ulen);
  10416. if (!hexdump2string(
  10417. buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
  10418. *str_finger = 0;
  10419. }
  10420. conn->request_info.client_cert =
  10421. (struct client_cert *)mg_malloc(sizeof(struct client_cert));
  10422. if (conn->request_info.client_cert) {
  10423. conn->request_info.client_cert->subject = mg_strdup(str_subject);
  10424. conn->request_info.client_cert->issuer = mg_strdup(str_issuer);
  10425. conn->request_info.client_cert->serial = mg_strdup(str_serial);
  10426. conn->request_info.client_cert->finger = mg_strdup(str_finger);
  10427. } else {
  10428. /* TODO: write some OOM message */
  10429. }
  10430. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  10431. * see https://linux.die.net/man/3/bn_bn2hex */
  10432. OPENSSL_free(str_serial);
  10433. /* Free certificate memory */
  10434. X509_free(cert);
  10435. }
  10436. }
  10437. #ifdef OPENSSL_API_1_1
  10438. #else
  10439. static void
  10440. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  10441. {
  10442. (void)line;
  10443. (void)file;
  10444. if (mode & 1) {
  10445. /* 1 is CRYPTO_LOCK */
  10446. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  10447. } else {
  10448. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  10449. }
  10450. }
  10451. #endif /* OPENSSL_API_1_1 */
  10452. #if !defined(NO_SSL_DL)
  10453. static void *
  10454. load_dll(struct mg_context *ctx, const char *dll_name, struct ssl_func *sw)
  10455. {
  10456. union {
  10457. void *p;
  10458. void (*fp)(void);
  10459. } u;
  10460. void *dll_handle;
  10461. struct ssl_func *fp;
  10462. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  10463. mg_cry(fc(ctx), "%s: cannot load %s", __func__, dll_name);
  10464. return NULL;
  10465. }
  10466. for (fp = sw; fp->name != NULL; fp++) {
  10467. #ifdef _WIN32
  10468. /* GetProcAddress() returns pointer to function */
  10469. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  10470. #else
  10471. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  10472. * pointers to function pointers. We need to use a union to make a
  10473. * cast. */
  10474. u.p = dlsym(dll_handle, fp->name);
  10475. #endif /* _WIN32 */
  10476. if (u.fp == NULL) {
  10477. mg_cry(fc(ctx),
  10478. "%s: %s: cannot find %s",
  10479. __func__,
  10480. dll_name,
  10481. fp->name);
  10482. dlclose(dll_handle);
  10483. return NULL;
  10484. } else {
  10485. fp->ptr = u.fp;
  10486. }
  10487. }
  10488. return dll_handle;
  10489. }
  10490. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  10491. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  10492. #endif /* NO_SSL_DL */
  10493. #if defined(SSL_ALREADY_INITIALIZED)
  10494. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  10495. #else
  10496. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  10497. #endif
  10498. static int
  10499. initialize_ssl(struct mg_context *ctx)
  10500. {
  10501. #ifdef OPENSSL_API_1_1
  10502. #if !defined(NO_SSL_DL)
  10503. if (!cryptolib_dll_handle) {
  10504. cryptolib_dll_handle = load_dll(ctx, CRYPTO_LIB, crypto_sw);
  10505. if (!cryptolib_dll_handle) {
  10506. return 0;
  10507. }
  10508. }
  10509. #else
  10510. (void)ctx;
  10511. #endif /* NO_SSL_DL */
  10512. if (mg_atomic_inc(&cryptolib_users) > 1) {
  10513. return 1;
  10514. }
  10515. #else
  10516. int i;
  10517. size_t size;
  10518. #if !defined(NO_SSL_DL)
  10519. if (!cryptolib_dll_handle) {
  10520. cryptolib_dll_handle = load_dll(ctx, CRYPTO_LIB, crypto_sw);
  10521. if (!cryptolib_dll_handle) {
  10522. return 0;
  10523. }
  10524. }
  10525. #else
  10526. (void)ctx;
  10527. #endif /* NO_SSL_DL */
  10528. if (mg_atomic_inc(&cryptolib_users) > 1) {
  10529. return 1;
  10530. }
  10531. /* Initialize locking callbacks, needed for thread safety.
  10532. * http://www.openssl.org/support/faq.html#PROG1
  10533. */
  10534. i = CRYPTO_num_locks();
  10535. if (i < 0) {
  10536. i = 0;
  10537. }
  10538. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  10539. if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  10540. mg_cry(fc(ctx),
  10541. "%s: cannot allocate mutexes: %s",
  10542. __func__,
  10543. ssl_error());
  10544. return 0;
  10545. }
  10546. for (i = 0; i < CRYPTO_num_locks(); i++) {
  10547. pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr);
  10548. }
  10549. CRYPTO_set_locking_callback(&ssl_locking_callback);
  10550. CRYPTO_set_id_callback(&mg_current_thread_id);
  10551. #endif /* OPENSSL_API_1_1 */
  10552. return 1;
  10553. }
  10554. static int
  10555. ssl_use_pem_file(struct mg_context *ctx, const char *pem)
  10556. {
  10557. if (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0) {
  10558. mg_cry(fc(ctx),
  10559. "%s: cannot open certificate file %s: %s",
  10560. __func__,
  10561. pem,
  10562. ssl_error());
  10563. return 0;
  10564. }
  10565. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  10566. if (SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0) {
  10567. mg_cry(fc(ctx),
  10568. "%s: cannot open private key file %s: %s",
  10569. __func__,
  10570. pem,
  10571. ssl_error());
  10572. return 0;
  10573. }
  10574. if (SSL_CTX_check_private_key(ctx->ssl_ctx) == 0) {
  10575. mg_cry(fc(ctx),
  10576. "%s: certificate and private key do not match: %s",
  10577. __func__,
  10578. pem);
  10579. return 0;
  10580. }
  10581. if (SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem) == 0) {
  10582. mg_cry(fc(ctx),
  10583. "%s: cannot use certificate chain file %s: %s",
  10584. __func__,
  10585. pem,
  10586. ssl_error());
  10587. return 0;
  10588. }
  10589. return 1;
  10590. }
  10591. #ifdef OPENSSL_API_1_1
  10592. static unsigned long
  10593. ssl_get_protocol(int version_id)
  10594. {
  10595. long unsigned ret = SSL_OP_ALL;
  10596. if (version_id > 0)
  10597. ret |= SSL_OP_NO_SSLv2;
  10598. if (version_id > 1)
  10599. ret |= SSL_OP_NO_SSLv3;
  10600. if (version_id > 2)
  10601. ret |= SSL_OP_NO_TLSv1;
  10602. if (version_id > 3)
  10603. ret |= SSL_OP_NO_TLSv1_1;
  10604. return ret;
  10605. }
  10606. #else
  10607. static long
  10608. ssl_get_protocol(int version_id)
  10609. {
  10610. long ret = SSL_OP_ALL;
  10611. if (version_id > 0)
  10612. ret |= SSL_OP_NO_SSLv2;
  10613. if (version_id > 1)
  10614. ret |= SSL_OP_NO_SSLv3;
  10615. if (version_id > 2)
  10616. ret |= SSL_OP_NO_TLSv1;
  10617. if (version_id > 3)
  10618. ret |= SSL_OP_NO_TLSv1_1;
  10619. return ret;
  10620. }
  10621. #endif /* OPENSSL_API_1_1 */
  10622. /* Dynamically load SSL library. Set up ctx->ssl_ctx pointer. */
  10623. static int
  10624. set_ssl_option(struct mg_context *ctx)
  10625. {
  10626. const char *pem;
  10627. int callback_ret;
  10628. int should_verify_peer;
  10629. const char *ca_path;
  10630. const char *ca_file;
  10631. int use_default_verify_paths;
  10632. int verify_depth;
  10633. time_t now_rt = time(NULL);
  10634. struct timespec now_mt;
  10635. md5_byte_t ssl_context_id[16];
  10636. md5_state_t md5state;
  10637. int protocol_ver;
  10638. /* If PEM file is not specified and the init_ssl callback
  10639. * is not specified, skip SSL initialization. */
  10640. if (!ctx) {
  10641. return 0;
  10642. }
  10643. if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL
  10644. && ctx->callbacks.init_ssl == NULL) {
  10645. return 1;
  10646. }
  10647. if (!initialize_ssl(ctx)) {
  10648. return 0;
  10649. }
  10650. #if !defined(NO_SSL_DL)
  10651. if (!ssllib_dll_handle) {
  10652. ssllib_dll_handle = load_dll(ctx, SSL_LIB, ssl_sw);
  10653. if (!ssllib_dll_handle) {
  10654. return 0;
  10655. }
  10656. }
  10657. #endif /* NO_SSL_DL */
  10658. #ifdef OPENSSL_API_1_1
  10659. /* Initialize SSL library */
  10660. OPENSSL_init_ssl(0, NULL);
  10661. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  10662. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  10663. NULL);
  10664. if ((ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  10665. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  10666. return 0;
  10667. }
  10668. #else
  10669. /* Initialize SSL library */
  10670. SSL_library_init();
  10671. SSL_load_error_strings();
  10672. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  10673. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  10674. return 0;
  10675. }
  10676. #endif /* OPENSSL_API_1_1 */
  10677. SSL_CTX_clear_options(ctx->ssl_ctx,
  10678. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  10679. | SSL_OP_NO_TLSv1_1);
  10680. protocol_ver = atoi(ctx->config[SSL_PROTOCOL_VERSION]);
  10681. SSL_CTX_set_options(ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  10682. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  10683. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  10684. #if !defined(NO_SSL_DL)
  10685. SSL_CTX_set_ecdh_auto(ctx->ssl_ctx, 1);
  10686. #endif /* NO_SSL_DL */
  10687. /* If a callback has been specified, call it. */
  10688. callback_ret =
  10689. (ctx->callbacks.init_ssl == NULL)
  10690. ? 0
  10691. : (ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data));
  10692. /* If callback returns 0, civetweb sets up the SSL certificate.
  10693. * If it returns 1, civetweb assumes the calback already did this.
  10694. * If it returns -1, initializing ssl fails. */
  10695. if (callback_ret < 0) {
  10696. mg_cry(fc(ctx), "SSL callback returned error: %i", callback_ret);
  10697. return 0;
  10698. }
  10699. if (callback_ret > 0) {
  10700. if (pem != NULL) {
  10701. (void)SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
  10702. }
  10703. return 1;
  10704. }
  10705. /* Use some UID as session context ID. */
  10706. md5_init(&md5state);
  10707. md5_append(&md5state, (const md5_byte_t *)&now_rt, sizeof(now_rt));
  10708. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  10709. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  10710. md5_append(&md5state,
  10711. (const md5_byte_t *)ctx->config[LISTENING_PORTS],
  10712. strlen(ctx->config[LISTENING_PORTS]));
  10713. md5_append(&md5state, (const md5_byte_t *)ctx, sizeof(*ctx));
  10714. md5_finish(&md5state, ssl_context_id);
  10715. SSL_CTX_set_session_id_context(ctx->ssl_ctx,
  10716. (const unsigned char *)&ssl_context_id,
  10717. sizeof(ssl_context_id));
  10718. if (pem != NULL) {
  10719. if (!ssl_use_pem_file(ctx, pem)) {
  10720. return 0;
  10721. }
  10722. }
  10723. should_verify_peer =
  10724. (ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  10725. && (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0);
  10726. use_default_verify_paths =
  10727. (ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  10728. && (mg_strcasecmp(ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes") == 0);
  10729. if (should_verify_peer) {
  10730. ca_path = ctx->config[SSL_CA_PATH];
  10731. ca_file = ctx->config[SSL_CA_FILE];
  10732. if (SSL_CTX_load_verify_locations(ctx->ssl_ctx, ca_file, ca_path)
  10733. != 1) {
  10734. mg_cry(fc(ctx),
  10735. "SSL_CTX_load_verify_locations error: %s "
  10736. "ssl_verify_peer requires setting "
  10737. "either ssl_ca_path or ssl_ca_file. Is any of them "
  10738. "present in "
  10739. "the .conf file?",
  10740. ssl_error());
  10741. return 0;
  10742. }
  10743. SSL_CTX_set_verify(ctx->ssl_ctx,
  10744. SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  10745. NULL);
  10746. if (use_default_verify_paths
  10747. && SSL_CTX_set_default_verify_paths(ctx->ssl_ctx) != 1) {
  10748. mg_cry(fc(ctx),
  10749. "SSL_CTX_set_default_verify_paths error: %s",
  10750. ssl_error());
  10751. return 0;
  10752. }
  10753. if (ctx->config[SSL_VERIFY_DEPTH]) {
  10754. verify_depth = atoi(ctx->config[SSL_VERIFY_DEPTH]);
  10755. SSL_CTX_set_verify_depth(ctx->ssl_ctx, verify_depth);
  10756. }
  10757. }
  10758. if (ctx->config[SSL_CIPHER_LIST] != NULL) {
  10759. if (SSL_CTX_set_cipher_list(ctx->ssl_ctx, ctx->config[SSL_CIPHER_LIST])
  10760. != 1) {
  10761. mg_cry(fc(ctx), "SSL_CTX_set_cipher_list error: %s", ssl_error());
  10762. }
  10763. }
  10764. return 1;
  10765. }
  10766. static void
  10767. uninitialize_ssl(struct mg_context *ctx)
  10768. {
  10769. #ifdef OPENSSL_API_1_1
  10770. (void)ctx;
  10771. if (mg_atomic_dec(&cryptolib_users) == 0) {
  10772. /* Shutdown according to
  10773. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  10774. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  10775. */
  10776. CONF_modules_unload(1);
  10777. #else
  10778. int i;
  10779. (void)ctx;
  10780. if (mg_atomic_dec(&cryptolib_users) == 0) {
  10781. /* Shutdown according to
  10782. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  10783. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  10784. */
  10785. CRYPTO_set_locking_callback(NULL);
  10786. CRYPTO_set_id_callback(NULL);
  10787. ENGINE_cleanup();
  10788. CONF_modules_unload(1);
  10789. ERR_free_strings();
  10790. EVP_cleanup();
  10791. CRYPTO_cleanup_all_ex_data();
  10792. ERR_remove_state(0);
  10793. for (i = 0; i < CRYPTO_num_locks(); i++) {
  10794. pthread_mutex_destroy(&ssl_mutexes[i]);
  10795. }
  10796. mg_free(ssl_mutexes);
  10797. ssl_mutexes = NULL;
  10798. #endif /* OPENSSL_API_1_1 */
  10799. }
  10800. }
  10801. #endif /* !NO_SSL */
  10802. static int
  10803. set_gpass_option(struct mg_context *ctx)
  10804. {
  10805. if (ctx) {
  10806. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10807. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  10808. if (path != NULL && !mg_stat(fc(ctx), path, &file.stat)) {
  10809. mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  10810. return 0;
  10811. }
  10812. return 1;
  10813. }
  10814. return 0;
  10815. }
  10816. static int
  10817. set_acl_option(struct mg_context *ctx)
  10818. {
  10819. return check_acl(ctx, (uint32_t)0x7f000001UL) != -1;
  10820. }
  10821. static void
  10822. reset_per_request_attributes(struct mg_connection *conn)
  10823. {
  10824. if (!conn) {
  10825. return;
  10826. }
  10827. conn->path_info = NULL;
  10828. conn->num_bytes_sent = conn->consumed_content = 0;
  10829. conn->status_code = -1;
  10830. conn->is_chunked = 0;
  10831. conn->must_close = conn->request_len = conn->throttle = 0;
  10832. conn->request_info.content_length = -1;
  10833. conn->request_info.remote_user = NULL;
  10834. conn->request_info.request_method = NULL;
  10835. conn->request_info.request_uri = NULL;
  10836. conn->request_info.local_uri = NULL;
  10837. conn->request_info.uri = NULL; /* TODO: cleanup uri,
  10838. * local_uri and request_uri */
  10839. conn->request_info.http_version = NULL;
  10840. conn->request_info.num_headers = 0;
  10841. conn->data_len = 0;
  10842. conn->chunk_remainder = 0;
  10843. }
  10844. #if 0
  10845. /* Note: set_sock_timeout is not required for non-blocking sockets.
  10846. * Leave this function here (commented out) for reference until
  10847. * CivetWeb 1.9 is tested, and the tests confirme this function is
  10848. * no longer required.
  10849. */
  10850. static int
  10851. set_sock_timeout(SOCKET sock, int milliseconds)
  10852. {
  10853. int r0 = 0, r1, r2;
  10854. #ifdef _WIN32
  10855. /* Windows specific */
  10856. DWORD tv = (DWORD)milliseconds;
  10857. #else
  10858. /* Linux, ... (not Windows) */
  10859. struct timeval tv;
  10860. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  10861. * max. time waiting for the acknowledged of TCP data before the connection
  10862. * will be forcefully closed and ETIMEDOUT is returned to the application.
  10863. * If this option is not set, the default timeout of 20-30 minutes is used.
  10864. */
  10865. /* #define TCP_USER_TIMEOUT (18) */
  10866. #if defined(TCP_USER_TIMEOUT)
  10867. unsigned int uto = (unsigned int)milliseconds;
  10868. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  10869. #endif
  10870. memset(&tv, 0, sizeof(tv));
  10871. tv.tv_sec = milliseconds / 1000;
  10872. tv.tv_usec = (milliseconds * 1000) % 1000000;
  10873. #endif /* _WIN32 */
  10874. r1 = setsockopt(
  10875. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  10876. r2 = setsockopt(
  10877. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  10878. return r0 || r1 || r2;
  10879. }
  10880. #endif
  10881. static int
  10882. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  10883. {
  10884. if (setsockopt(sock,
  10885. IPPROTO_TCP,
  10886. TCP_NODELAY,
  10887. (SOCK_OPT_TYPE)&nodelay_on,
  10888. sizeof(nodelay_on)) != 0) {
  10889. /* Error */
  10890. return 1;
  10891. }
  10892. /* OK */
  10893. return 0;
  10894. }
  10895. static void
  10896. close_socket_gracefully(struct mg_connection *conn)
  10897. {
  10898. #if defined(_WIN32)
  10899. char buf[MG_BUF_LEN];
  10900. int n;
  10901. #endif
  10902. struct linger linger;
  10903. int error_code = 0;
  10904. int linger_timeout = -2;
  10905. socklen_t opt_len = sizeof(error_code);
  10906. if (!conn) {
  10907. return;
  10908. }
  10909. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  10910. * "Note that enabling a nonzero timeout on a nonblocking socket
  10911. * is not recommended.", so set it to blocking now */
  10912. set_blocking_mode(conn->client.sock, 1);
  10913. /* Send FIN to the client */
  10914. shutdown(conn->client.sock, SHUTDOWN_WR);
  10915. #if defined(_WIN32)
  10916. /* Read and discard pending incoming data. If we do not do that and
  10917. * close
  10918. * the socket, the data in the send buffer may be discarded. This
  10919. * behaviour is seen on Windows, when client keeps sending data
  10920. * when server decides to close the connection; then when client
  10921. * does recv() it gets no data back. */
  10922. do {
  10923. n = pull(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  10924. } while (n > 0);
  10925. #endif
  10926. if (conn->ctx->config[LINGER_TIMEOUT]) {
  10927. linger_timeout = atoi(conn->ctx->config[LINGER_TIMEOUT]);
  10928. }
  10929. /* Set linger option according to configuration */
  10930. if (linger_timeout >= 0) {
  10931. /* Set linger option to avoid socket hanging out after close. This
  10932. * prevent ephemeral port exhaust problem under high QPS. */
  10933. linger.l_onoff = 1;
  10934. #if defined(_MSC_VER)
  10935. #pragma warning(push)
  10936. #pragma warning(disable : 4244)
  10937. #endif
  10938. linger.l_linger = (linger_timeout + 999) / 1000;
  10939. #if defined(_MSC_VER)
  10940. #pragma warning(pop)
  10941. #endif
  10942. } else {
  10943. linger.l_onoff = 0;
  10944. linger.l_linger = 0;
  10945. }
  10946. if (linger_timeout < -1) {
  10947. /* Default: don't configure any linger */
  10948. } else if (getsockopt(conn->client.sock,
  10949. SOL_SOCKET,
  10950. SO_ERROR,
  10951. (char *)&error_code,
  10952. &opt_len) != 0) {
  10953. /* Cannot determine if socket is already closed. This should
  10954. * not occur and never did in a test. Log an error message
  10955. * and continue. */
  10956. mg_cry(conn,
  10957. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  10958. __func__,
  10959. strerror(ERRNO));
  10960. } else if (error_code == ECONNRESET) {
  10961. /* Socket already closed by client/peer, close socket without linger */
  10962. } else {
  10963. /* Set linger timeout */
  10964. if (setsockopt(conn->client.sock,
  10965. SOL_SOCKET,
  10966. SO_LINGER,
  10967. (char *)&linger,
  10968. sizeof(linger)) != 0) {
  10969. mg_cry(conn,
  10970. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  10971. __func__,
  10972. linger.l_onoff,
  10973. linger.l_linger,
  10974. strerror(ERRNO));
  10975. }
  10976. }
  10977. /* Now we know that our FIN is ACK-ed, safe to close */
  10978. closesocket(conn->client.sock);
  10979. conn->client.sock = INVALID_SOCKET;
  10980. }
  10981. static void
  10982. close_connection(struct mg_connection *conn)
  10983. {
  10984. if (!conn || !conn->ctx) {
  10985. return;
  10986. }
  10987. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  10988. if (conn->lua_websocket_state) {
  10989. lua_websocket_close(conn, conn->lua_websocket_state);
  10990. conn->lua_websocket_state = NULL;
  10991. }
  10992. #endif
  10993. /* call the connection_close callback if assigned */
  10994. if ((conn->ctx->callbacks.connection_close != NULL)
  10995. && (conn->ctx->context_type == 1)) {
  10996. conn->ctx->callbacks.connection_close(conn);
  10997. }
  10998. mg_lock_connection(conn);
  10999. conn->must_close = 1;
  11000. #ifndef NO_SSL
  11001. if (conn->ssl != NULL) {
  11002. /* Run SSL_shutdown twice to ensure completly close SSL connection
  11003. */
  11004. SSL_shutdown(conn->ssl);
  11005. SSL_free(conn->ssl);
  11006. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  11007. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  11008. #ifndef OPENSSL_API_1_1
  11009. ERR_remove_state(0);
  11010. #endif
  11011. conn->ssl = NULL;
  11012. }
  11013. #endif
  11014. if (conn->client.sock != INVALID_SOCKET) {
  11015. close_socket_gracefully(conn);
  11016. conn->client.sock = INVALID_SOCKET;
  11017. }
  11018. mg_unlock_connection(conn);
  11019. }
  11020. void
  11021. mg_close_connection(struct mg_connection *conn)
  11022. {
  11023. struct mg_context *client_ctx = NULL;
  11024. if (conn == NULL) {
  11025. return;
  11026. }
  11027. #if defined(USE_WEBSOCKET)
  11028. if (conn->ctx->context_type == 2) {
  11029. unsigned int i;
  11030. /* ws/wss client */
  11031. client_ctx = conn->ctx;
  11032. /* client context: loops must end */
  11033. conn->ctx->stop_flag = 1;
  11034. /* We need to get the client thread out of the select/recv call here. */
  11035. /* Since we use a sleep quantum of some seconds to check for recv
  11036. * timeouts, we will just wait a few seconds in mg_join_thread. */
  11037. /* join worker thread */
  11038. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  11039. if (client_ctx->worker_threadids[i] != 0) {
  11040. mg_join_thread(client_ctx->worker_threadids[i]);
  11041. }
  11042. }
  11043. }
  11044. #else
  11045. (void)client_ctx;
  11046. #endif
  11047. close_connection(conn);
  11048. #ifndef NO_SSL
  11049. if (conn->client_ssl_ctx != NULL) {
  11050. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  11051. }
  11052. #endif
  11053. if (client_ctx != NULL) {
  11054. /* free context */
  11055. mg_free(client_ctx->worker_threadids);
  11056. mg_free(client_ctx);
  11057. (void)pthread_mutex_destroy(&conn->mutex);
  11058. mg_free(conn);
  11059. }
  11060. }
  11061. static struct mg_connection *
  11062. mg_connect_client_impl(const struct mg_client_options *client_options,
  11063. int use_ssl,
  11064. char *ebuf,
  11065. size_t ebuf_len)
  11066. {
  11067. static struct mg_context fake_ctx;
  11068. struct mg_connection *conn = NULL;
  11069. SOCKET sock;
  11070. union usa sa;
  11071. if (!connect_socket(&fake_ctx,
  11072. client_options->host,
  11073. client_options->port,
  11074. use_ssl,
  11075. ebuf,
  11076. ebuf_len,
  11077. &sock,
  11078. &sa)) {
  11079. ;
  11080. } else if ((conn = (struct mg_connection *)
  11081. mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) {
  11082. mg_snprintf(NULL,
  11083. NULL, /* No truncation check for ebuf */
  11084. ebuf,
  11085. ebuf_len,
  11086. "calloc(): %s",
  11087. strerror(ERRNO));
  11088. closesocket(sock);
  11089. #ifndef NO_SSL
  11090. #ifdef OPENSSL_API_1_1
  11091. } else if (use_ssl
  11092. && (conn->client_ssl_ctx = SSL_CTX_new(TLS_client_method()))
  11093. == NULL) {
  11094. mg_snprintf(NULL,
  11095. NULL, /* No truncation check for ebuf */
  11096. ebuf,
  11097. ebuf_len,
  11098. "SSL_CTX_new error");
  11099. closesocket(sock);
  11100. mg_free(conn);
  11101. conn = NULL;
  11102. #else
  11103. } else if (use_ssl
  11104. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  11105. == NULL) {
  11106. mg_snprintf(NULL,
  11107. NULL, /* No truncation check for ebuf */
  11108. ebuf,
  11109. ebuf_len,
  11110. "SSL_CTX_new error");
  11111. closesocket(sock);
  11112. mg_free(conn);
  11113. conn = NULL;
  11114. #endif /* OPENSSL_API_1_1 */
  11115. #endif /* NO_SSL */
  11116. } else {
  11117. #ifdef USE_IPV6
  11118. socklen_t len = (sa.sa.sa_family == AF_INET)
  11119. ? sizeof(conn->client.rsa.sin)
  11120. : sizeof(conn->client.rsa.sin6);
  11121. struct sockaddr *psa =
  11122. (sa.sa.sa_family == AF_INET)
  11123. ? (struct sockaddr *)&(conn->client.rsa.sin)
  11124. : (struct sockaddr *)&(conn->client.rsa.sin6);
  11125. #else
  11126. socklen_t len = sizeof(conn->client.rsa.sin);
  11127. struct sockaddr *psa = (struct sockaddr *)&(conn->client.rsa.sin);
  11128. #endif
  11129. conn->buf_size = MAX_REQUEST_SIZE;
  11130. conn->buf = (char *)(conn + 1);
  11131. conn->ctx = &fake_ctx;
  11132. conn->client.sock = sock;
  11133. conn->client.lsa = sa;
  11134. if (getsockname(sock, psa, &len) != 0) {
  11135. mg_cry(conn,
  11136. "%s: getsockname() failed: %s",
  11137. __func__,
  11138. strerror(ERRNO));
  11139. }
  11140. conn->client.is_ssl = use_ssl ? 1 : 0;
  11141. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  11142. #ifndef NO_SSL
  11143. if (use_ssl) {
  11144. fake_ctx.ssl_ctx = conn->client_ssl_ctx;
  11145. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  11146. * SSL_CTX_set_verify call is needed to switch off server
  11147. * certificate checking, which is off by default in OpenSSL and
  11148. * on in yaSSL. */
  11149. /* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  11150. * SSL_VERIFY_PEER, verify_ssl_server); */
  11151. if (client_options->client_cert) {
  11152. if (!ssl_use_pem_file(&fake_ctx, client_options->client_cert)) {
  11153. mg_snprintf(NULL,
  11154. NULL, /* No truncation check for ebuf */
  11155. ebuf,
  11156. ebuf_len,
  11157. "Can not use SSL client certificate");
  11158. SSL_CTX_free(conn->client_ssl_ctx);
  11159. closesocket(sock);
  11160. mg_free(conn);
  11161. conn = NULL;
  11162. }
  11163. }
  11164. if (client_options->server_cert) {
  11165. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  11166. client_options->server_cert,
  11167. NULL);
  11168. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  11169. } else {
  11170. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  11171. }
  11172. if (!sslize(conn,
  11173. conn->client_ssl_ctx,
  11174. SSL_connect,
  11175. &(conn->ctx->stop_flag))) {
  11176. mg_snprintf(NULL,
  11177. NULL, /* No truncation check for ebuf */
  11178. ebuf,
  11179. ebuf_len,
  11180. "SSL connection error");
  11181. SSL_CTX_free(conn->client_ssl_ctx);
  11182. closesocket(sock);
  11183. mg_free(conn);
  11184. conn = NULL;
  11185. }
  11186. }
  11187. #endif
  11188. }
  11189. if (conn) {
  11190. set_blocking_mode(sock, 0);
  11191. }
  11192. return conn;
  11193. }
  11194. CIVETWEB_API struct mg_connection *
  11195. mg_connect_client_secure(const struct mg_client_options *client_options,
  11196. char *error_buffer,
  11197. size_t error_buffer_size)
  11198. {
  11199. return mg_connect_client_impl(client_options,
  11200. 1,
  11201. error_buffer,
  11202. error_buffer_size);
  11203. }
  11204. struct mg_connection *
  11205. mg_connect_client(const char *host,
  11206. int port,
  11207. int use_ssl,
  11208. char *error_buffer,
  11209. size_t error_buffer_size)
  11210. {
  11211. struct mg_client_options opts;
  11212. memset(&opts, 0, sizeof(opts));
  11213. opts.host = host;
  11214. opts.port = port;
  11215. return mg_connect_client_impl(&opts,
  11216. use_ssl,
  11217. error_buffer,
  11218. error_buffer_size);
  11219. }
  11220. static const struct {
  11221. const char *proto;
  11222. size_t proto_len;
  11223. unsigned default_port;
  11224. } abs_uri_protocols[] = {{"http://", 7, 80},
  11225. {"https://", 8, 443},
  11226. {"ws://", 5, 80},
  11227. {"wss://", 6, 443},
  11228. {NULL, 0, 0}};
  11229. /* Check if the uri is valid.
  11230. * return 0 for invalid uri,
  11231. * return 1 for *,
  11232. * return 2 for relative uri,
  11233. * return 3 for absolute uri without port,
  11234. * return 4 for absolute uri with port */
  11235. static int
  11236. get_uri_type(const char *uri)
  11237. {
  11238. int i;
  11239. char *hostend, *portbegin, *portend;
  11240. unsigned long port;
  11241. /* According to the HTTP standard
  11242. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  11243. * URI can be an asterisk (*) or should start with slash (relative uri),
  11244. * or it should start with the protocol (absolute uri). */
  11245. if (uri[0] == '*' && uri[1] == '\0') {
  11246. /* asterisk */
  11247. return 1;
  11248. }
  11249. /* Valid URIs according to RFC 3986
  11250. * (https://www.ietf.org/rfc/rfc3986.txt)
  11251. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  11252. * and unreserved characters A-Z a-z 0-9 and -._~
  11253. * and % encoded symbols.
  11254. */
  11255. for (i = 0; uri[i] != 0; i++) {
  11256. if (uri[i] < 33) {
  11257. /* control characters and spaces are invalid */
  11258. return 0;
  11259. }
  11260. if (uri[i] > 126) {
  11261. /* non-ascii characters must be % encoded */
  11262. return 0;
  11263. } else {
  11264. switch (uri[i]) {
  11265. case '"': /* 34 */
  11266. case '<': /* 60 */
  11267. case '>': /* 62 */
  11268. case '\\': /* 92 */
  11269. case '^': /* 94 */
  11270. case '`': /* 96 */
  11271. case '{': /* 123 */
  11272. case '|': /* 124 */
  11273. case '}': /* 125 */
  11274. return 0;
  11275. default:
  11276. /* character is ok */
  11277. break;
  11278. }
  11279. }
  11280. }
  11281. /* A relative uri starts with a / character */
  11282. if (uri[0] == '/') {
  11283. /* relative uri */
  11284. return 2;
  11285. }
  11286. /* It could be an absolute uri: */
  11287. /* This function only checks if the uri is valid, not if it is
  11288. * addressing the current server. So civetweb can also be used
  11289. * as a proxy server. */
  11290. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  11291. if (mg_strncasecmp(uri,
  11292. abs_uri_protocols[i].proto,
  11293. abs_uri_protocols[i].proto_len) == 0) {
  11294. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  11295. if (!hostend) {
  11296. return 0;
  11297. }
  11298. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  11299. if (!portbegin) {
  11300. return 3;
  11301. }
  11302. port = strtoul(portbegin + 1, &portend, 10);
  11303. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  11304. return 0;
  11305. }
  11306. return 4;
  11307. }
  11308. }
  11309. return 0;
  11310. }
  11311. /* Return NULL or the relative uri at the current server */
  11312. static const char *
  11313. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  11314. {
  11315. const char *server_domain;
  11316. size_t server_domain_len;
  11317. size_t request_domain_len = 0;
  11318. unsigned long port = 0;
  11319. int i, auth_domain_check_enabled;
  11320. const char *hostbegin = NULL;
  11321. const char *hostend = NULL;
  11322. const char *portbegin;
  11323. char *portend;
  11324. auth_domain_check_enabled =
  11325. !strcmp(conn->ctx->config[ENABLE_AUTH_DOMAIN_CHECK],"yes");
  11326. /* DNS is case insensitive, so use case insensitive string compare here
  11327. */
  11328. server_domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  11329. if (!server_domain && auth_domain_check_enabled) {
  11330. return 0;
  11331. }
  11332. server_domain_len = strlen(server_domain);
  11333. if (!server_domain_len) {
  11334. return 0;
  11335. }
  11336. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  11337. if (mg_strncasecmp(uri,
  11338. abs_uri_protocols[i].proto,
  11339. abs_uri_protocols[i].proto_len) == 0) {
  11340. hostbegin = uri + abs_uri_protocols[i].proto_len;
  11341. hostend = strchr(hostbegin, '/');
  11342. if (!hostend) {
  11343. return 0;
  11344. }
  11345. portbegin = strchr(hostbegin, ':');
  11346. if ((!portbegin) || (portbegin > hostend)) {
  11347. port = abs_uri_protocols[i].default_port;
  11348. request_domain_len = (size_t)(hostend - hostbegin);
  11349. } else {
  11350. port = strtoul(portbegin + 1, &portend, 10);
  11351. if ((portend != hostend) || (port <= 0)
  11352. || !is_valid_port(port)) {
  11353. return 0;
  11354. }
  11355. request_domain_len = (size_t)(portbegin - hostbegin);
  11356. }
  11357. /* protocol found, port set */
  11358. break;
  11359. }
  11360. }
  11361. if (!port) {
  11362. /* port remains 0 if the protocol is not found */
  11363. return 0;
  11364. }
  11365. /* Check if the request is directed to a different server. */
  11366. /* First check if the port is the same (IPv4 and IPv6). */
  11367. #if defined(USE_IPV6)
  11368. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  11369. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  11370. /* Request is directed to a different port */
  11371. return 0;
  11372. }
  11373. } else
  11374. #endif
  11375. {
  11376. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  11377. /* Request is directed to a different port */
  11378. return 0;
  11379. }
  11380. }
  11381. /* Finally check if the server corresponds to the authentication
  11382. * domain of the server (the server domain).
  11383. * Allow full matches (like http://mydomain.com/path/file.ext), and
  11384. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  11385. * but do not allow substrings (like http://notmydomain.com/path/file.ext
  11386. * or http://mydomain.com.fake/path/file.ext).
  11387. */
  11388. if (auth_domain_check_enabled) {
  11389. if ((request_domain_len == server_domain_len)
  11390. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  11391. /* Request is directed to this server - full name match. */
  11392. } else {
  11393. if (request_domain_len < (server_domain_len + 2)) {
  11394. /* Request is directed to another server: The server name is longer
  11395. * than
  11396. * the request name. Drop this case here to avoid overflows in the
  11397. * following checks. */
  11398. return 0;
  11399. }
  11400. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  11401. /* Request is directed to another server: It could be a substring
  11402. * like notmyserver.com */
  11403. return 0;
  11404. }
  11405. if (0 != memcmp(server_domain,
  11406. hostbegin + request_domain_len - server_domain_len,
  11407. server_domain_len)) {
  11408. /* Request is directed to another server:
  11409. * The server name is different. */
  11410. return 0;
  11411. }
  11412. }
  11413. }
  11414. return hostend;
  11415. }
  11416. static int
  11417. getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  11418. {
  11419. const char *cl;
  11420. if (ebuf_len > 0) {
  11421. ebuf[0] = '\0';
  11422. }
  11423. *err = 0;
  11424. reset_per_request_attributes(conn);
  11425. if (!conn) {
  11426. mg_snprintf(conn,
  11427. NULL, /* No truncation check for ebuf */
  11428. ebuf,
  11429. ebuf_len,
  11430. "%s",
  11431. "Internal error");
  11432. *err = 500;
  11433. return 0;
  11434. }
  11435. /* Set the time the request was received. This value should be used for
  11436. * timeouts. */
  11437. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  11438. conn->request_len =
  11439. read_request(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  11440. /* assert(conn->request_len < 0 || conn->data_len >= conn->request_len);
  11441. */
  11442. if (conn->request_len >= 0 && conn->data_len < conn->request_len) {
  11443. mg_snprintf(conn,
  11444. NULL, /* No truncation check for ebuf */
  11445. ebuf,
  11446. ebuf_len,
  11447. "%s",
  11448. "Invalid request size");
  11449. *err = 500;
  11450. return 0;
  11451. }
  11452. if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
  11453. mg_snprintf(conn,
  11454. NULL, /* No truncation check for ebuf */
  11455. ebuf,
  11456. ebuf_len,
  11457. "%s",
  11458. "Request Too Large");
  11459. *err = 413;
  11460. return 0;
  11461. } else if (conn->request_len <= 0) {
  11462. if (conn->data_len > 0) {
  11463. mg_snprintf(conn,
  11464. NULL, /* No truncation check for ebuf */
  11465. ebuf,
  11466. ebuf_len,
  11467. "%s",
  11468. "Client sent malformed request");
  11469. *err = 400;
  11470. } else {
  11471. /* Server did not recv anything -> just close the connection */
  11472. conn->must_close = 1;
  11473. mg_snprintf(conn,
  11474. NULL, /* No truncation check for ebuf */
  11475. ebuf,
  11476. ebuf_len,
  11477. "%s",
  11478. "Client did not send a request");
  11479. *err = 0;
  11480. }
  11481. return 0;
  11482. } else if (parse_http_message(conn->buf,
  11483. conn->buf_size,
  11484. &conn->request_info) <= 0) {
  11485. mg_snprintf(conn,
  11486. NULL, /* No truncation check for ebuf */
  11487. ebuf,
  11488. ebuf_len,
  11489. "%s",
  11490. "Bad Request");
  11491. *err = 400;
  11492. return 0;
  11493. } else {
  11494. /* Message is a valid request or response */
  11495. if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) {
  11496. /* Request/response has content length set */
  11497. char *endptr = NULL;
  11498. conn->content_len = strtoll(cl, &endptr, 10);
  11499. if (endptr == cl) {
  11500. mg_snprintf(conn,
  11501. NULL, /* No truncation check for ebuf */
  11502. ebuf,
  11503. ebuf_len,
  11504. "%s",
  11505. "Bad Request");
  11506. *err = 411;
  11507. return 0;
  11508. }
  11509. /* Publish the content length back to the request info. */
  11510. conn->request_info.content_length = conn->content_len;
  11511. } else if ((cl = get_header(&conn->request_info, "Transfer-Encoding"))
  11512. != NULL
  11513. && !mg_strcasecmp(cl, "chunked")) {
  11514. conn->is_chunked = 1;
  11515. } else if (!mg_strcasecmp(conn->request_info.request_method, "POST")
  11516. || !mg_strcasecmp(conn->request_info.request_method,
  11517. "PUT")) {
  11518. /* POST or PUT request without content length set */
  11519. conn->content_len = -1;
  11520. } else if (!mg_strncasecmp(conn->request_info.request_method,
  11521. "HTTP/",
  11522. 5)) {
  11523. /* Response without content length set */
  11524. conn->content_len = -1;
  11525. } else {
  11526. /* Other request */
  11527. conn->content_len = 0;
  11528. }
  11529. }
  11530. return 1;
  11531. }
  11532. int
  11533. mg_get_response(struct mg_connection *conn,
  11534. char *ebuf,
  11535. size_t ebuf_len,
  11536. int timeout)
  11537. {
  11538. if (conn) {
  11539. /* Implementation of API function for HTTP clients */
  11540. int err, ret;
  11541. struct mg_context *octx = conn->ctx;
  11542. struct mg_context rctx = *(conn->ctx);
  11543. char txt[32]; /* will not overflow */
  11544. if (timeout >= 0) {
  11545. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  11546. rctx.config[REQUEST_TIMEOUT] = txt;
  11547. /* Not required for non-blocking sockets.
  11548. set_sock_timeout(conn->client.sock, timeout);
  11549. */
  11550. } else {
  11551. rctx.config[REQUEST_TIMEOUT] = NULL;
  11552. }
  11553. conn->ctx = &rctx;
  11554. ret = getreq(conn, ebuf, ebuf_len, &err);
  11555. conn->ctx = octx;
  11556. /* TODO: 1) uri is deprecated;
  11557. * 2) here, ri.uri is the http response code */
  11558. conn->request_info.uri = conn->request_info.request_uri;
  11559. /* TODO (mid): Define proper return values - maybe return length?
  11560. * For the first test use <0 for error and >0 for OK */
  11561. return (ret == 0) ? -1 : +1;
  11562. }
  11563. return -1;
  11564. }
  11565. struct mg_connection *
  11566. mg_download(const char *host,
  11567. int port,
  11568. int use_ssl,
  11569. char *ebuf,
  11570. size_t ebuf_len,
  11571. const char *fmt,
  11572. ...)
  11573. {
  11574. struct mg_connection *conn;
  11575. va_list ap;
  11576. int i;
  11577. int reqerr;
  11578. va_start(ap, fmt);
  11579. ebuf[0] = '\0';
  11580. /* open a connection */
  11581. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  11582. if (conn != NULL) {
  11583. i = mg_vprintf(conn, fmt, ap);
  11584. if (i <= 0) {
  11585. mg_snprintf(conn,
  11586. NULL, /* No truncation check for ebuf */
  11587. ebuf,
  11588. ebuf_len,
  11589. "%s",
  11590. "Error sending request");
  11591. } else {
  11592. getreq(conn, ebuf, ebuf_len, &reqerr);
  11593. /* TODO: 1) uri is deprecated;
  11594. * 2) here, ri.uri is the http response code */
  11595. conn->request_info.uri = conn->request_info.request_uri;
  11596. }
  11597. }
  11598. /* if an error occured, close the connection */
  11599. if (ebuf[0] != '\0' && conn != NULL) {
  11600. mg_close_connection(conn);
  11601. conn = NULL;
  11602. }
  11603. va_end(ap);
  11604. return conn;
  11605. }
  11606. struct websocket_client_thread_data {
  11607. struct mg_connection *conn;
  11608. mg_websocket_data_handler data_handler;
  11609. mg_websocket_close_handler close_handler;
  11610. void *callback_data;
  11611. };
  11612. #if defined(USE_WEBSOCKET)
  11613. #ifdef _WIN32
  11614. static unsigned __stdcall websocket_client_thread(void *data)
  11615. #else
  11616. static void *
  11617. websocket_client_thread(void *data)
  11618. #endif
  11619. {
  11620. struct websocket_client_thread_data *cdata =
  11621. (struct websocket_client_thread_data *)data;
  11622. mg_set_thread_name("ws-clnt");
  11623. if (cdata->conn->ctx) {
  11624. if (cdata->conn->ctx->callbacks.init_thread) {
  11625. /* 3 indicates a websocket client thread */
  11626. /* TODO: check if conn->ctx can be set */
  11627. cdata->conn->ctx->callbacks.init_thread(cdata->conn->ctx, 3);
  11628. }
  11629. }
  11630. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  11631. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  11632. if (cdata->close_handler != NULL) {
  11633. cdata->close_handler(cdata->conn, cdata->callback_data);
  11634. }
  11635. /* The websocket_client context has only this thread. If it runs out,
  11636. set the stop_flag to 2 (= "stopped"). */
  11637. cdata->conn->ctx->stop_flag = 2;
  11638. mg_free((void *)cdata);
  11639. #ifdef _WIN32
  11640. return 0;
  11641. #else
  11642. return NULL;
  11643. #endif
  11644. }
  11645. #endif
  11646. struct mg_connection *
  11647. mg_connect_websocket_client(const char *host,
  11648. int port,
  11649. int use_ssl,
  11650. char *error_buffer,
  11651. size_t error_buffer_size,
  11652. const char *path,
  11653. const char *origin,
  11654. mg_websocket_data_handler data_func,
  11655. mg_websocket_close_handler close_func,
  11656. void *user_data)
  11657. {
  11658. struct mg_connection *conn = NULL;
  11659. #if defined(USE_WEBSOCKET)
  11660. struct mg_context *newctx = NULL;
  11661. struct websocket_client_thread_data *thread_data;
  11662. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  11663. static const char *handshake_req;
  11664. if (origin != NULL) {
  11665. handshake_req = "GET %s HTTP/1.1\r\n"
  11666. "Host: %s\r\n"
  11667. "Upgrade: websocket\r\n"
  11668. "Connection: Upgrade\r\n"
  11669. "Sec-WebSocket-Key: %s\r\n"
  11670. "Sec-WebSocket-Version: 13\r\n"
  11671. "Origin: %s\r\n"
  11672. "\r\n";
  11673. } else {
  11674. handshake_req = "GET %s HTTP/1.1\r\n"
  11675. "Host: %s\r\n"
  11676. "Upgrade: websocket\r\n"
  11677. "Connection: Upgrade\r\n"
  11678. "Sec-WebSocket-Key: %s\r\n"
  11679. "Sec-WebSocket-Version: 13\r\n"
  11680. "\r\n";
  11681. }
  11682. /* Establish the client connection and request upgrade */
  11683. conn = mg_download(host,
  11684. port,
  11685. use_ssl,
  11686. error_buffer,
  11687. error_buffer_size,
  11688. handshake_req,
  11689. path,
  11690. host,
  11691. magic,
  11692. origin);
  11693. /* Connection object will be null if something goes wrong */
  11694. if (conn == NULL || (strcmp(conn->request_info.request_uri, "101") != 0)) {
  11695. if (!*error_buffer) {
  11696. /* if there is a connection, but it did not return 101,
  11697. * error_buffer is not yet set */
  11698. mg_snprintf(conn,
  11699. NULL, /* No truncation check for ebuf */
  11700. error_buffer,
  11701. error_buffer_size,
  11702. "Unexpected server reply");
  11703. }
  11704. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  11705. if (conn != NULL) {
  11706. mg_free(conn);
  11707. conn = NULL;
  11708. }
  11709. return conn;
  11710. }
  11711. /* For client connections, mg_context is fake. Since we need to set a
  11712. * callback function, we need to create a copy and modify it. */
  11713. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  11714. memcpy(newctx, conn->ctx, sizeof(struct mg_context));
  11715. newctx->user_data = user_data;
  11716. newctx->context_type = 2; /* ws/wss client context type */
  11717. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  11718. newctx->worker_threadids =
  11719. (pthread_t *)mg_calloc(newctx->cfg_worker_threads, sizeof(pthread_t));
  11720. conn->ctx = newctx;
  11721. thread_data = (struct websocket_client_thread_data *)
  11722. mg_calloc(sizeof(struct websocket_client_thread_data), 1);
  11723. thread_data->conn = conn;
  11724. thread_data->data_handler = data_func;
  11725. thread_data->close_handler = close_func;
  11726. thread_data->callback_data = NULL;
  11727. /* Start a thread to read the websocket client connection
  11728. * This thread will automatically stop when mg_disconnect is
  11729. * called on the client connection */
  11730. if (mg_start_thread_with_id(websocket_client_thread,
  11731. (void *)thread_data,
  11732. newctx->worker_threadids) != 0) {
  11733. mg_free((void *)thread_data);
  11734. mg_free((void *)newctx->worker_threadids);
  11735. mg_free((void *)newctx);
  11736. mg_free((void *)conn);
  11737. conn = NULL;
  11738. DEBUG_TRACE("%s",
  11739. "Websocket client connect thread could not be started\r\n");
  11740. }
  11741. #else
  11742. /* Appease "unused parameter" warnings */
  11743. (void)host;
  11744. (void)port;
  11745. (void)use_ssl;
  11746. (void)error_buffer;
  11747. (void)error_buffer_size;
  11748. (void)path;
  11749. (void)origin;
  11750. (void)user_data;
  11751. (void)data_func;
  11752. (void)close_func;
  11753. #endif
  11754. return conn;
  11755. }
  11756. static void
  11757. process_new_connection(struct mg_connection *conn)
  11758. {
  11759. if (conn && conn->ctx) {
  11760. struct mg_request_info *ri = &conn->request_info;
  11761. int keep_alive_enabled, keep_alive, discard_len;
  11762. char ebuf[100];
  11763. const char *hostend;
  11764. int reqerr, uri_type;
  11765. keep_alive_enabled =
  11766. !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  11767. /* Important: on new connection, reset the receiving buffer. Credit
  11768. * goes to crule42. */
  11769. conn->data_len = 0;
  11770. conn->handled_requests = 0;
  11771. do {
  11772. DEBUG_TRACE("calling getreq (%i times for this connection)",
  11773. conn->handled_requests + 1);
  11774. if (!getreq(conn, ebuf, sizeof(ebuf), &reqerr)) {
  11775. /* The request sent by the client could not be understood by
  11776. * the server, or it was incomplete or a timeout. Send an
  11777. * error message and close the connection. */
  11778. if (reqerr > 0) {
  11779. /*assert(ebuf[0] != '\0');*/
  11780. send_http_error(conn, reqerr, "%s", ebuf);
  11781. }
  11782. } else if (strcmp(ri->http_version, "1.0")
  11783. && strcmp(ri->http_version, "1.1")) {
  11784. mg_snprintf(conn,
  11785. NULL, /* No truncation check for ebuf */
  11786. ebuf,
  11787. sizeof(ebuf),
  11788. "Bad HTTP version: [%s]",
  11789. ri->http_version);
  11790. send_http_error(conn, 505, "%s", ebuf);
  11791. }
  11792. if (ebuf[0] == '\0') {
  11793. uri_type = get_uri_type(conn->request_info.request_uri);
  11794. switch (uri_type) {
  11795. case 1:
  11796. /* Asterisk */
  11797. conn->request_info.local_uri = NULL;
  11798. break;
  11799. case 2:
  11800. /* relative uri */
  11801. conn->request_info.local_uri =
  11802. conn->request_info.request_uri;
  11803. break;
  11804. case 3:
  11805. case 4:
  11806. /* absolute uri (with/without port) */
  11807. hostend = get_rel_url_at_current_server(
  11808. conn->request_info.request_uri, conn);
  11809. if (hostend) {
  11810. conn->request_info.local_uri = hostend;
  11811. } else {
  11812. conn->request_info.local_uri = NULL;
  11813. }
  11814. break;
  11815. default:
  11816. mg_snprintf(conn,
  11817. NULL, /* No truncation check for ebuf */
  11818. ebuf,
  11819. sizeof(ebuf),
  11820. "Invalid URI");
  11821. send_http_error(conn, 400, "%s", ebuf);
  11822. conn->request_info.local_uri = NULL;
  11823. break;
  11824. }
  11825. /* TODO: cleanup uri, local_uri and request_uri */
  11826. conn->request_info.uri = conn->request_info.local_uri;
  11827. }
  11828. DEBUG_TRACE("http: %s, error: %s",
  11829. (ri->http_version ? ri->http_version : "none"),
  11830. (ebuf[0] ? ebuf : "none"));
  11831. if (ebuf[0] == '\0') {
  11832. if (conn->request_info.local_uri) {
  11833. /* handle request to local server */
  11834. handle_request(conn);
  11835. DEBUG_TRACE("%s", "handle_request done");
  11836. if (conn->ctx->callbacks.end_request != NULL) {
  11837. conn->ctx->callbacks.end_request(conn,
  11838. conn->status_code);
  11839. DEBUG_TRACE("%s", "end_request callback done");
  11840. }
  11841. log_access(conn);
  11842. } else {
  11843. /* TODO: handle non-local request (PROXY) */
  11844. conn->must_close = 1;
  11845. }
  11846. } else {
  11847. conn->must_close = 1;
  11848. }
  11849. if (ri->remote_user != NULL) {
  11850. mg_free((void *)ri->remote_user);
  11851. /* Important! When having connections with and without auth
  11852. * would cause double free and then crash */
  11853. ri->remote_user = NULL;
  11854. }
  11855. /* NOTE(lsm): order is important here. should_keep_alive() call
  11856. * is
  11857. * using parsed request, which will be invalid after memmove's
  11858. * below.
  11859. * Therefore, memorize should_keep_alive() result now for later
  11860. * use
  11861. * in loop exit condition. */
  11862. keep_alive = (conn->ctx->stop_flag == 0) && keep_alive_enabled
  11863. && (conn->content_len >= 0) && should_keep_alive(conn);
  11864. /* Discard all buffered data for this request */
  11865. discard_len = ((conn->content_len >= 0) && (conn->request_len > 0)
  11866. && ((conn->request_len + conn->content_len)
  11867. < (int64_t)conn->data_len))
  11868. ? (int)(conn->request_len + conn->content_len)
  11869. : conn->data_len;
  11870. /*assert(discard_len >= 0);*/
  11871. if (discard_len < 0) {
  11872. DEBUG_TRACE("internal error: discard_len = %li",
  11873. (long int)discard_len);
  11874. break;
  11875. }
  11876. conn->data_len -= discard_len;
  11877. if (conn->data_len > 0) {
  11878. DEBUG_TRACE("discard_len = %lu", (long unsigned)discard_len);
  11879. memmove(conn->buf,
  11880. conn->buf + discard_len,
  11881. (size_t)conn->data_len);
  11882. }
  11883. /* assert(conn->data_len >= 0); */
  11884. /* assert(conn->data_len <= conn->buf_size); */
  11885. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  11886. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  11887. (long int)conn->data_len,
  11888. (long int)conn->buf_size);
  11889. break;
  11890. }
  11891. conn->handled_requests++;
  11892. } while (keep_alive);
  11893. }
  11894. }
  11895. #if defined(ALTERNATIVE_QUEUE)
  11896. static void
  11897. produce_socket(struct mg_context *ctx, const struct socket *sp)
  11898. {
  11899. unsigned int i;
  11900. for (;;) {
  11901. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  11902. /* find a free worker slot and signal it */
  11903. if (ctx->client_socks[i].in_use == 0) {
  11904. ctx->client_socks[i] = *sp;
  11905. ctx->client_socks[i].in_use = 1;
  11906. event_signal(ctx->client_wait_events[i]);
  11907. return;
  11908. }
  11909. }
  11910. /* queue is full */
  11911. mg_sleep(1);
  11912. }
  11913. }
  11914. static int
  11915. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  11916. {
  11917. DEBUG_TRACE("%s", "going idle");
  11918. ctx->client_socks[thread_index].in_use = 0;
  11919. event_wait(ctx->client_wait_events[thread_index]);
  11920. *sp = ctx->client_socks[thread_index];
  11921. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  11922. return !ctx->stop_flag;
  11923. }
  11924. #else /* ALTERNATIVE_QUEUE */
  11925. /* Worker threads take accepted socket from the queue */
  11926. static int
  11927. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  11928. {
  11929. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  11930. (void)thread_index;
  11931. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11932. DEBUG_TRACE("%s", "going idle");
  11933. /* If the queue is empty, wait. We're idle at this point. */
  11934. while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
  11935. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  11936. }
  11937. /* If we're stopping, sq_head may be equal to sq_tail. */
  11938. if (ctx->sq_head > ctx->sq_tail) {
  11939. /* Copy socket from the queue and increment tail */
  11940. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  11941. ctx->sq_tail++;
  11942. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  11943. /* Wrap pointers if needed */
  11944. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  11945. ctx->sq_tail -= QUEUE_SIZE(ctx);
  11946. ctx->sq_head -= QUEUE_SIZE(ctx);
  11947. }
  11948. }
  11949. (void)pthread_cond_signal(&ctx->sq_empty);
  11950. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11951. return !ctx->stop_flag;
  11952. #undef QUEUE_SIZE
  11953. }
  11954. /* Master thread adds accepted socket to a queue */
  11955. static void
  11956. produce_socket(struct mg_context *ctx, const struct socket *sp)
  11957. {
  11958. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  11959. if (!ctx) {
  11960. return;
  11961. }
  11962. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11963. /* If the queue is full, wait */
  11964. while (ctx->stop_flag == 0
  11965. && ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx)) {
  11966. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  11967. }
  11968. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  11969. /* Copy socket to the queue and increment head */
  11970. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  11971. ctx->sq_head++;
  11972. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  11973. }
  11974. (void)pthread_cond_signal(&ctx->sq_full);
  11975. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11976. #undef QUEUE_SIZE
  11977. }
  11978. #endif /* ALTERNATIVE_QUEUE */
  11979. struct worker_thread_args {
  11980. struct mg_context *ctx;
  11981. int index;
  11982. };
  11983. static void *
  11984. worker_thread_run(struct worker_thread_args *thread_args)
  11985. {
  11986. struct mg_context *ctx = thread_args->ctx;
  11987. struct mg_connection *conn;
  11988. struct mg_workerTLS tls;
  11989. #if defined(MG_LEGACY_INTERFACE)
  11990. uint32_t addr;
  11991. #endif
  11992. mg_set_thread_name("worker");
  11993. tls.is_master = 0;
  11994. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  11995. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11996. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  11997. #endif
  11998. /* Initialize thread local storage before calling any callback */
  11999. pthread_setspecific(sTlsKey, &tls);
  12000. if (ctx->callbacks.init_thread) {
  12001. /* call init_thread for a worker thread (type 1) */
  12002. ctx->callbacks.init_thread(ctx, 1);
  12003. }
  12004. /* Connection structure has been pre-allocated */
  12005. if (((int)thread_args->index < 0)
  12006. || ((unsigned)thread_args->index
  12007. >= (unsigned)ctx->cfg_worker_threads)) {
  12008. mg_cry(fc(ctx),
  12009. "Internal error: Invalid worker index %i",
  12010. (int)thread_args->index);
  12011. return NULL;
  12012. }
  12013. conn = ctx->worker_connections + thread_args->index;
  12014. /* Request buffers are not pre-allocated. They are private to the
  12015. * request and do not contain any state information that might be
  12016. * of interest to anyone observing a server status. */
  12017. conn->buf = (char *)mg_malloc(MAX_REQUEST_SIZE);
  12018. if (conn->buf == NULL) {
  12019. mg_cry(fc(ctx),
  12020. "Out of memory: Cannot allocate buffer for worker %i",
  12021. (int)thread_args->index);
  12022. return NULL;
  12023. }
  12024. conn->buf_size = MAX_REQUEST_SIZE;
  12025. conn->ctx = ctx;
  12026. conn->thread_index = thread_args->index;
  12027. conn->request_info.user_data = ctx->user_data;
  12028. /* Allocate a mutex for this connection to allow communication both
  12029. * within the request handler and from elsewhere in the application
  12030. */
  12031. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  12032. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  12033. * signal sq_empty condvar to wake up the master waiting in
  12034. * produce_socket() */
  12035. while (consume_socket(ctx, &conn->client, conn->thread_index)) {
  12036. conn->conn_birth_time = time(NULL);
  12037. /* Fill in IP, port info early so even if SSL setup below fails,
  12038. * error handler would have the corresponding info.
  12039. * Thanks to Johannes Winkelmann for the patch.
  12040. */
  12041. #if defined(USE_IPV6)
  12042. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  12043. conn->request_info.remote_port =
  12044. ntohs(conn->client.rsa.sin6.sin6_port);
  12045. } else
  12046. #endif
  12047. {
  12048. conn->request_info.remote_port =
  12049. ntohs(conn->client.rsa.sin.sin_port);
  12050. }
  12051. sockaddr_to_string(conn->request_info.remote_addr,
  12052. sizeof(conn->request_info.remote_addr),
  12053. &conn->client.rsa);
  12054. DEBUG_TRACE("Start processing connection from %s",
  12055. conn->request_info.remote_addr);
  12056. #if defined(MG_LEGACY_INTERFACE)
  12057. /* This legacy interface only works for the IPv4 case */
  12058. addr = ntohl(conn->client.rsa.sin.sin_addr.s_addr);
  12059. memcpy(&conn->request_info.remote_ip, &addr, 4);
  12060. #endif
  12061. conn->request_info.is_ssl = conn->client.is_ssl;
  12062. if (conn->client.is_ssl) {
  12063. #ifndef NO_SSL
  12064. /* HTTPS connection */
  12065. if (sslize(conn,
  12066. conn->ctx->ssl_ctx,
  12067. SSL_accept,
  12068. &(conn->ctx->stop_flag))) {
  12069. /* Get SSL client certificate information (if set) */
  12070. ssl_get_client_cert_info(conn);
  12071. /* process HTTPS connection */
  12072. process_new_connection(conn);
  12073. /* Free client certificate info */
  12074. if (conn->request_info.client_cert) {
  12075. mg_free((void *)(conn->request_info.client_cert->subject));
  12076. mg_free((void *)(conn->request_info.client_cert->issuer));
  12077. mg_free((void *)(conn->request_info.client_cert->serial));
  12078. mg_free((void *)(conn->request_info.client_cert->finger));
  12079. conn->request_info.client_cert->subject = 0;
  12080. conn->request_info.client_cert->issuer = 0;
  12081. conn->request_info.client_cert->serial = 0;
  12082. conn->request_info.client_cert->finger = 0;
  12083. mg_free(conn->request_info.client_cert);
  12084. conn->request_info.client_cert = 0;
  12085. }
  12086. }
  12087. #endif
  12088. } else {
  12089. /* process HTTP connection */
  12090. process_new_connection(conn);
  12091. }
  12092. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  12093. conn->request_info.remote_addr,
  12094. difftime(time(NULL), conn->conn_birth_time));
  12095. close_connection(conn);
  12096. DEBUG_TRACE("%s", "Connection closed");
  12097. }
  12098. pthread_setspecific(sTlsKey, NULL);
  12099. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12100. CloseHandle(tls.pthread_cond_helper_mutex);
  12101. #endif
  12102. pthread_mutex_destroy(&conn->mutex);
  12103. /* Free the request buffer. */
  12104. conn->buf_size = 0;
  12105. mg_free(conn->buf);
  12106. conn->buf = NULL;
  12107. DEBUG_TRACE("%s", "exiting");
  12108. return NULL;
  12109. }
  12110. /* Threads have different return types on Windows and Unix. */
  12111. #ifdef _WIN32
  12112. static unsigned __stdcall worker_thread(void *thread_func_param)
  12113. {
  12114. struct worker_thread_args *pwta =
  12115. (struct worker_thread_args *)thread_func_param;
  12116. worker_thread_run(pwta);
  12117. mg_free(thread_func_param);
  12118. return 0;
  12119. }
  12120. #else
  12121. static void *
  12122. worker_thread(void *thread_func_param)
  12123. {
  12124. struct worker_thread_args *pwta =
  12125. (struct worker_thread_args *)thread_func_param;
  12126. worker_thread_run(pwta);
  12127. mg_free(thread_func_param);
  12128. return NULL;
  12129. }
  12130. #endif /* _WIN32 */
  12131. static void
  12132. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  12133. {
  12134. struct socket so;
  12135. char src_addr[IP_ADDR_STR_LEN];
  12136. socklen_t len = sizeof(so.rsa);
  12137. int on = 1;
  12138. if (!listener) {
  12139. return;
  12140. }
  12141. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  12142. == INVALID_SOCKET) {
  12143. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  12144. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  12145. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  12146. closesocket(so.sock);
  12147. so.sock = INVALID_SOCKET;
  12148. } else {
  12149. /* Put so socket structure into the queue */
  12150. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  12151. set_close_on_exec(so.sock, fc(ctx));
  12152. so.is_ssl = listener->is_ssl;
  12153. so.ssl_redir = listener->ssl_redir;
  12154. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  12155. mg_cry(fc(ctx),
  12156. "%s: getsockname() failed: %s",
  12157. __func__,
  12158. strerror(ERRNO));
  12159. }
  12160. /* Set TCP keep-alive. This is needed because if HTTP-level
  12161. * keep-alive
  12162. * is enabled, and client resets the connection, server won't get
  12163. * TCP FIN or RST and will keep the connection open forever. With
  12164. * TCP keep-alive, next keep-alive handshake will figure out that
  12165. * the client is down and will close the server end.
  12166. * Thanks to Igor Klopov who suggested the patch. */
  12167. if (setsockopt(so.sock,
  12168. SOL_SOCKET,
  12169. SO_KEEPALIVE,
  12170. (SOCK_OPT_TYPE)&on,
  12171. sizeof(on)) != 0) {
  12172. mg_cry(fc(ctx),
  12173. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  12174. __func__,
  12175. strerror(ERRNO));
  12176. }
  12177. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  12178. * to effectively fill up the underlying IP packet payload and
  12179. * reduce the overhead of sending lots of small buffers. However
  12180. * this hurts the server's throughput (ie. operations per second)
  12181. * when HTTP 1.1 persistent connections are used and the responses
  12182. * are relatively small (eg. less than 1400 bytes).
  12183. */
  12184. if ((ctx != NULL) && (ctx->config[CONFIG_TCP_NODELAY] != NULL)
  12185. && (!strcmp(ctx->config[CONFIG_TCP_NODELAY], "1"))) {
  12186. if (set_tcp_nodelay(so.sock, 1) != 0) {
  12187. mg_cry(fc(ctx),
  12188. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  12189. __func__,
  12190. strerror(ERRNO));
  12191. }
  12192. }
  12193. /* We are using non-blocking sockets. Thus, the
  12194. * set_sock_timeout(so.sock, timeout);
  12195. * call is no longer required. */
  12196. set_blocking_mode(so.sock, 0);
  12197. produce_socket(ctx, &so);
  12198. }
  12199. }
  12200. static void
  12201. master_thread_run(void *thread_func_param)
  12202. {
  12203. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  12204. struct mg_workerTLS tls;
  12205. struct pollfd *pfd;
  12206. unsigned int i;
  12207. unsigned int workerthreadcount;
  12208. if (!ctx) {
  12209. return;
  12210. }
  12211. mg_set_thread_name("master");
  12212. /* Increase priority of the master thread */
  12213. #if defined(_WIN32)
  12214. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  12215. #elif defined(USE_MASTER_THREAD_PRIORITY)
  12216. int min_prio = sched_get_priority_min(SCHED_RR);
  12217. int max_prio = sched_get_priority_max(SCHED_RR);
  12218. if ((min_prio >= 0) && (max_prio >= 0)
  12219. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  12220. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  12221. struct sched_param sched_param = {0};
  12222. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  12223. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  12224. }
  12225. #endif
  12226. /* Initialize thread local storage */
  12227. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12228. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  12229. #endif
  12230. tls.is_master = 1;
  12231. pthread_setspecific(sTlsKey, &tls);
  12232. if (ctx->callbacks.init_thread) {
  12233. /* Callback for the master thread (type 0) */
  12234. ctx->callbacks.init_thread(ctx, 0);
  12235. }
  12236. /* Server starts *now* */
  12237. ctx->start_time = time(NULL);
  12238. /* Start the server */
  12239. pfd = ctx->listening_socket_fds;
  12240. while (ctx->stop_flag == 0) {
  12241. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12242. pfd[i].fd = ctx->listening_sockets[i].sock;
  12243. pfd[i].events = POLLIN;
  12244. }
  12245. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  12246. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12247. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  12248. * successful poll, and POLLIN is defined as
  12249. * (POLLRDNORM | POLLRDBAND)
  12250. * Therefore, we're checking pfd[i].revents & POLLIN, not
  12251. * pfd[i].revents == POLLIN. */
  12252. if (ctx->stop_flag == 0 && (pfd[i].revents & POLLIN)) {
  12253. accept_new_connection(&ctx->listening_sockets[i], ctx);
  12254. }
  12255. }
  12256. }
  12257. }
  12258. /* Here stop_flag is 1 - Initiate shutdown. */
  12259. DEBUG_TRACE("%s", "stopping workers");
  12260. /* Stop signal received: somebody called mg_stop. Quit. */
  12261. close_all_listening_sockets(ctx);
  12262. /* Wakeup workers that are waiting for connections to handle. */
  12263. (void)pthread_mutex_lock(&ctx->thread_mutex);
  12264. #if defined(ALTERNATIVE_QUEUE)
  12265. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  12266. event_signal(ctx->client_wait_events[i]);
  12267. /* Since we know all sockets, we can shutdown the connections. */
  12268. if (ctx->client_socks[i].in_use) {
  12269. shutdown(ctx->client_socks[i].sock, SHUTDOWN_BOTH);
  12270. }
  12271. }
  12272. #else
  12273. pthread_cond_broadcast(&ctx->sq_full);
  12274. #endif
  12275. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  12276. /* Join all worker threads to avoid leaking threads. */
  12277. workerthreadcount = ctx->cfg_worker_threads;
  12278. for (i = 0; i < workerthreadcount; i++) {
  12279. if (ctx->worker_threadids[i] != 0) {
  12280. mg_join_thread(ctx->worker_threadids[i]);
  12281. }
  12282. }
  12283. #if defined(USE_LUA)
  12284. /* Free Lua state of lua background task */
  12285. if (ctx->lua_background_state) {
  12286. lua_close((lua_State *)ctx->lua_background_state);
  12287. ctx->lua_background_state = 0;
  12288. }
  12289. #endif
  12290. #if !defined(NO_SSL)
  12291. if (ctx->ssl_ctx != NULL) {
  12292. uninitialize_ssl(ctx);
  12293. }
  12294. #endif
  12295. DEBUG_TRACE("%s", "exiting");
  12296. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12297. CloseHandle(tls.pthread_cond_helper_mutex);
  12298. #endif
  12299. pthread_setspecific(sTlsKey, NULL);
  12300. /* Signal mg_stop() that we're done.
  12301. * WARNING: This must be the very last thing this
  12302. * thread does, as ctx becomes invalid after this line. */
  12303. ctx->stop_flag = 2;
  12304. }
  12305. /* Threads have different return types on Windows and Unix. */
  12306. #ifdef _WIN32
  12307. static unsigned __stdcall master_thread(void *thread_func_param)
  12308. {
  12309. master_thread_run(thread_func_param);
  12310. return 0;
  12311. }
  12312. #else
  12313. static void *
  12314. master_thread(void *thread_func_param)
  12315. {
  12316. master_thread_run(thread_func_param);
  12317. return NULL;
  12318. }
  12319. #endif /* _WIN32 */
  12320. static void
  12321. free_context(struct mg_context *ctx)
  12322. {
  12323. int i;
  12324. struct mg_handler_info *tmp_rh;
  12325. if (ctx == NULL) {
  12326. return;
  12327. }
  12328. if (ctx->callbacks.exit_context) {
  12329. ctx->callbacks.exit_context(ctx);
  12330. }
  12331. /* All threads exited, no sync is needed. Destroy thread mutex and
  12332. * condvars
  12333. */
  12334. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  12335. #if defined(ALTERNATIVE_QUEUE)
  12336. mg_free(ctx->client_socks);
  12337. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  12338. event_destroy(ctx->client_wait_events[i]);
  12339. }
  12340. mg_free(ctx->client_wait_events);
  12341. #else
  12342. (void)pthread_cond_destroy(&ctx->sq_empty);
  12343. (void)pthread_cond_destroy(&ctx->sq_full);
  12344. #endif
  12345. /* Destroy other context global data structures mutex */
  12346. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  12347. #if defined(USE_TIMERS)
  12348. timers_exit(ctx);
  12349. #endif
  12350. /* Deallocate config parameters */
  12351. for (i = 0; i < NUM_OPTIONS; i++) {
  12352. if (ctx->config[i] != NULL) {
  12353. #if defined(_MSC_VER)
  12354. #pragma warning(suppress : 6001)
  12355. #endif
  12356. mg_free(ctx->config[i]);
  12357. }
  12358. }
  12359. /* Deallocate request handlers */
  12360. while (ctx->handlers) {
  12361. tmp_rh = ctx->handlers;
  12362. ctx->handlers = tmp_rh->next;
  12363. mg_free(tmp_rh->uri);
  12364. mg_free(tmp_rh);
  12365. }
  12366. #ifndef NO_SSL
  12367. /* Deallocate SSL context */
  12368. if (ctx->ssl_ctx != NULL) {
  12369. SSL_CTX_free(ctx->ssl_ctx);
  12370. }
  12371. #endif /* !NO_SSL */
  12372. /* Deallocate worker thread ID array */
  12373. if (ctx->worker_threadids != NULL) {
  12374. mg_free(ctx->worker_threadids);
  12375. }
  12376. /* Deallocate worker thread ID array */
  12377. if (ctx->worker_connections != NULL) {
  12378. mg_free(ctx->worker_connections);
  12379. }
  12380. /* Deallocate the tls variable */
  12381. if (mg_atomic_dec(&sTlsInit) == 0) {
  12382. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12383. DeleteCriticalSection(&global_log_file_lock);
  12384. #endif /* _WIN32 && !__SYMBIAN32__ */
  12385. #if !defined(_WIN32)
  12386. pthread_mutexattr_destroy(&pthread_mutex_attr);
  12387. #endif
  12388. pthread_key_delete(sTlsKey);
  12389. #if defined(USE_LUA)
  12390. lua_exit_optional_libraries();
  12391. #endif
  12392. }
  12393. /* deallocate system name string */
  12394. mg_free(ctx->systemName);
  12395. /* Deallocate context itself */
  12396. mg_free(ctx);
  12397. }
  12398. void
  12399. mg_stop(struct mg_context *ctx)
  12400. {
  12401. pthread_t mt;
  12402. if (!ctx) {
  12403. return;
  12404. }
  12405. /* We don't use a lock here. Calling mg_stop with the same ctx from
  12406. * two threads is not allowed. */
  12407. mt = ctx->masterthreadid;
  12408. if (mt == 0) {
  12409. return;
  12410. }
  12411. ctx->masterthreadid = 0;
  12412. /* Set stop flag, so all threads know they have to exit. */
  12413. ctx->stop_flag = 1;
  12414. /* Wait until everything has stopped. */
  12415. while (ctx->stop_flag != 2) {
  12416. (void)mg_sleep(10);
  12417. }
  12418. mg_join_thread(mt);
  12419. free_context(ctx);
  12420. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12421. (void)WSACleanup();
  12422. #endif /* _WIN32 && !__SYMBIAN32__ */
  12423. }
  12424. static void
  12425. get_system_name(char **sysName)
  12426. {
  12427. #if defined(_WIN32)
  12428. #if !defined(__SYMBIAN32__)
  12429. #if defined(_WIN32_WCE)
  12430. *sysName = mg_strdup("WinCE");
  12431. #else
  12432. char name[128];
  12433. DWORD dwVersion = 0;
  12434. DWORD dwMajorVersion = 0;
  12435. DWORD dwMinorVersion = 0;
  12436. DWORD dwBuild = 0;
  12437. #ifdef _MSC_VER
  12438. #pragma warning(push)
  12439. /* GetVersion was declared deprecated */
  12440. #pragma warning(disable : 4996)
  12441. #endif
  12442. dwVersion = GetVersion();
  12443. #ifdef _MSC_VER
  12444. #pragma warning(pop)
  12445. #endif
  12446. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  12447. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  12448. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  12449. (void)dwBuild;
  12450. sprintf(name,
  12451. "Windows %u.%u",
  12452. (unsigned)dwMajorVersion,
  12453. (unsigned)dwMinorVersion);
  12454. *sysName = mg_strdup(name);
  12455. #endif
  12456. #else
  12457. *sysName = mg_strdup("Symbian");
  12458. #endif
  12459. #else
  12460. struct utsname name;
  12461. memset(&name, 0, sizeof(name));
  12462. uname(&name);
  12463. *sysName = mg_strdup(name.sysname);
  12464. #endif
  12465. }
  12466. struct mg_context *
  12467. mg_start(const struct mg_callbacks *callbacks,
  12468. void *user_data,
  12469. const char **options)
  12470. {
  12471. struct mg_context *ctx;
  12472. const char *name, *value, *default_value;
  12473. int idx, ok, workerthreadcount;
  12474. unsigned int i;
  12475. void (*exit_callback)(const struct mg_context *ctx) = 0;
  12476. struct mg_workerTLS tls;
  12477. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12478. WSADATA data;
  12479. WSAStartup(MAKEWORD(2, 2), &data);
  12480. #endif /* _WIN32 && !__SYMBIAN32__ */
  12481. /* Allocate context and initialize reasonable general case defaults. */
  12482. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  12483. return NULL;
  12484. }
  12485. /* Random number generator will initialize at the first call */
  12486. ctx->auth_nonce_mask =
  12487. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  12488. if (mg_atomic_inc(&sTlsInit) == 1) {
  12489. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12490. InitializeCriticalSection(&global_log_file_lock);
  12491. #endif /* _WIN32 && !__SYMBIAN32__ */
  12492. #if !defined(_WIN32)
  12493. pthread_mutexattr_init(&pthread_mutex_attr);
  12494. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  12495. #endif
  12496. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  12497. /* Fatal error - abort start. However, this situation should
  12498. * never
  12499. * occur in practice. */
  12500. mg_atomic_dec(&sTlsInit);
  12501. mg_cry(fc(ctx), "Cannot initialize thread local storage");
  12502. mg_free(ctx);
  12503. return NULL;
  12504. }
  12505. #if defined(USE_LUA)
  12506. lua_init_optional_libraries();
  12507. #endif
  12508. } else {
  12509. /* TODO (low): istead of sleeping, check if sTlsKey is already
  12510. * initialized. */
  12511. mg_sleep(1);
  12512. }
  12513. tls.is_master = -1;
  12514. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  12515. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12516. tls.pthread_cond_helper_mutex = NULL;
  12517. #endif
  12518. pthread_setspecific(sTlsKey, &tls);
  12519. /* Dummy use this function - in some #ifdef combinations it's used,
  12520. * while it's not used in others, but GCC seems to stupid to understand
  12521. * #pragma GCC diagnostic ignored "-Wunused-function"
  12522. * in cases the function is unused, and it also complains on
  12523. * __attribute((unused))__ in cases it is used.
  12524. * So dummy use it, to have our peace. */
  12525. (void)mg_current_thread_id();
  12526. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr);
  12527. #if !defined(ALTERNATIVE_QUEUE)
  12528. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  12529. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  12530. #endif
  12531. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr);
  12532. if (!ok) {
  12533. /* Fatal error - abort start. However, this situation should never
  12534. * occur in practice. */
  12535. mg_cry(fc(ctx), "Cannot initialize thread synchronization objects");
  12536. mg_free(ctx);
  12537. pthread_setspecific(sTlsKey, NULL);
  12538. return NULL;
  12539. }
  12540. if (callbacks) {
  12541. ctx->callbacks = *callbacks;
  12542. exit_callback = callbacks->exit_context;
  12543. ctx->callbacks.exit_context = 0;
  12544. }
  12545. ctx->user_data = user_data;
  12546. ctx->handlers = NULL;
  12547. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  12548. ctx->shared_lua_websockets = 0;
  12549. #endif
  12550. while (options && (name = *options++) != NULL) {
  12551. if ((idx = get_option_index(name)) == -1) {
  12552. mg_cry(fc(ctx), "Invalid option: %s", name);
  12553. free_context(ctx);
  12554. pthread_setspecific(sTlsKey, NULL);
  12555. return NULL;
  12556. } else if ((value = *options++) == NULL) {
  12557. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  12558. free_context(ctx);
  12559. pthread_setspecific(sTlsKey, NULL);
  12560. return NULL;
  12561. }
  12562. if (ctx->config[idx] != NULL) {
  12563. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  12564. mg_free(ctx->config[idx]);
  12565. }
  12566. ctx->config[idx] = mg_strdup(value);
  12567. DEBUG_TRACE("[%s] -> [%s]", name, value);
  12568. }
  12569. /* Set default value if needed */
  12570. for (i = 0; config_options[i].name != NULL; i++) {
  12571. default_value = config_options[i].default_value;
  12572. if (ctx->config[i] == NULL && default_value != NULL) {
  12573. ctx->config[i] = mg_strdup(default_value);
  12574. }
  12575. }
  12576. workerthreadcount = atoi(ctx->config[NUM_THREADS]);
  12577. if (workerthreadcount > MAX_WORKER_THREADS) {
  12578. mg_cry(fc(ctx), "Too many worker threads");
  12579. free_context(ctx);
  12580. pthread_setspecific(sTlsKey, NULL);
  12581. return NULL;
  12582. }
  12583. if (workerthreadcount <= 0) {
  12584. mg_cry(fc(ctx), "Invalid number of worker threads");
  12585. free_context(ctx);
  12586. pthread_setspecific(sTlsKey, NULL);
  12587. return NULL;
  12588. }
  12589. #if defined(NO_FILES)
  12590. if (ctx->config[DOCUMENT_ROOT] != NULL) {
  12591. mg_cry(fc(ctx), "%s", "Document root must not be set");
  12592. free_context(ctx);
  12593. pthread_setspecific(sTlsKey, NULL);
  12594. return NULL;
  12595. }
  12596. #endif
  12597. get_system_name(&ctx->systemName);
  12598. #if defined(USE_LUA)
  12599. /* If a Lua background script has been configured, start it. */
  12600. if (ctx->config[LUA_BACKGROUND_SCRIPT] != NULL) {
  12601. char ebuf[256];
  12602. void *state = (void *)mg_prepare_lua_context_script(
  12603. ctx->config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  12604. if (!state) {
  12605. mg_cry(fc(ctx), "lua_background_script error: %s", ebuf);
  12606. free_context(ctx);
  12607. pthread_setspecific(sTlsKey, NULL);
  12608. return NULL;
  12609. }
  12610. ctx->lua_background_state = state;
  12611. } else {
  12612. ctx->lua_background_state = 0;
  12613. }
  12614. #endif
  12615. /* NOTE(lsm): order is important here. SSL certificates must
  12616. * be initialized before listening ports. UID must be set last. */
  12617. if (!set_gpass_option(ctx) ||
  12618. #if !defined(NO_SSL)
  12619. !set_ssl_option(ctx) ||
  12620. #endif
  12621. !set_ports_option(ctx) ||
  12622. #if !defined(_WIN32)
  12623. !set_uid_option(ctx) ||
  12624. #endif
  12625. !set_acl_option(ctx)) {
  12626. free_context(ctx);
  12627. pthread_setspecific(sTlsKey, NULL);
  12628. return NULL;
  12629. }
  12630. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  12631. /* Ignore SIGPIPE signal, so if browser cancels the request, it
  12632. * won't kill the whole process. */
  12633. (void)signal(SIGPIPE, SIG_IGN);
  12634. #endif /* !_WIN32 && !__SYMBIAN32__ */
  12635. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  12636. ctx->worker_threadids =
  12637. (pthread_t *)mg_calloc(ctx->cfg_worker_threads, sizeof(pthread_t));
  12638. if (ctx->worker_threadids == NULL) {
  12639. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  12640. free_context(ctx);
  12641. pthread_setspecific(sTlsKey, NULL);
  12642. return NULL;
  12643. }
  12644. ctx->worker_connections =
  12645. (struct mg_connection *)mg_calloc(ctx->cfg_worker_threads,
  12646. sizeof(struct mg_connection));
  12647. if (ctx->worker_connections == NULL) {
  12648. mg_cry(fc(ctx), "Not enough memory for worker thread connection array");
  12649. free_context(ctx);
  12650. pthread_setspecific(sTlsKey, NULL);
  12651. return NULL;
  12652. }
  12653. #if defined(ALTERNATIVE_QUEUE)
  12654. ctx->client_wait_events =
  12655. mg_calloc(sizeof(ctx->client_wait_events[0]), ctx->cfg_worker_threads);
  12656. if (ctx->client_wait_events == NULL) {
  12657. mg_cry(fc(ctx), "Not enough memory for worker event array");
  12658. mg_free(ctx->worker_threadids);
  12659. free_context(ctx);
  12660. pthread_setspecific(sTlsKey, NULL);
  12661. return NULL;
  12662. }
  12663. ctx->client_socks =
  12664. mg_calloc(sizeof(ctx->client_socks[0]), ctx->cfg_worker_threads);
  12665. if (ctx->client_wait_events == NULL) {
  12666. mg_cry(fc(ctx), "Not enough memory for worker socket array");
  12667. mg_free(ctx->client_socks);
  12668. mg_free(ctx->worker_threadids);
  12669. free_context(ctx);
  12670. pthread_setspecific(sTlsKey, NULL);
  12671. return NULL;
  12672. }
  12673. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  12674. ctx->client_wait_events[i] = event_create();
  12675. if (ctx->client_wait_events[i] == 0) {
  12676. mg_cry(fc(ctx), "Error creating worker event %i", i);
  12677. while (i > 0) {
  12678. i--;
  12679. event_destroy(ctx->client_wait_events[i]);
  12680. }
  12681. mg_free(ctx->client_socks);
  12682. mg_free(ctx->worker_threadids);
  12683. free_context(ctx);
  12684. pthread_setspecific(sTlsKey, NULL);
  12685. return NULL;
  12686. }
  12687. }
  12688. #endif
  12689. #if defined(USE_TIMERS)
  12690. if (timers_init(ctx) != 0) {
  12691. mg_cry(fc(ctx), "Error creating timers");
  12692. free_context(ctx);
  12693. pthread_setspecific(sTlsKey, NULL);
  12694. return NULL;
  12695. }
  12696. #endif
  12697. /* Context has been created - init user libraries */
  12698. if (ctx->callbacks.init_context) {
  12699. ctx->callbacks.init_context(ctx);
  12700. }
  12701. ctx->callbacks.exit_context = exit_callback;
  12702. ctx->context_type = 1; /* server context */
  12703. /* Start master (listening) thread */
  12704. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  12705. /* Start worker threads */
  12706. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  12707. struct worker_thread_args *wta =
  12708. mg_malloc(sizeof(struct worker_thread_args));
  12709. if (wta) {
  12710. wta->ctx = ctx;
  12711. wta->index = (int)i;
  12712. }
  12713. if ((wta == NULL)
  12714. || (mg_start_thread_with_id(worker_thread,
  12715. wta,
  12716. &ctx->worker_threadids[i]) != 0)) {
  12717. /* thread was not created */
  12718. if (wta != NULL) {
  12719. mg_free(wta);
  12720. }
  12721. if (i > 0) {
  12722. mg_cry(fc(ctx),
  12723. "Cannot start worker thread %i: error %ld",
  12724. i + 1,
  12725. (long)ERRNO);
  12726. } else {
  12727. mg_cry(fc(ctx),
  12728. "Cannot create threads: error %ld",
  12729. (long)ERRNO);
  12730. free_context(ctx);
  12731. pthread_setspecific(sTlsKey, NULL);
  12732. return NULL;
  12733. }
  12734. break;
  12735. }
  12736. }
  12737. pthread_setspecific(sTlsKey, NULL);
  12738. return ctx;
  12739. }
  12740. /* Feature check API function */
  12741. unsigned
  12742. mg_check_feature(unsigned feature)
  12743. {
  12744. static const unsigned feature_set = 0
  12745. /* Set bits for available features according to API documentation.
  12746. * This bit mask is created at compile time, according to the active
  12747. * preprocessor defines. It is a single const value at runtime. */
  12748. #if !defined(NO_FILES)
  12749. | 0x0001u
  12750. #endif
  12751. #if !defined(NO_SSL)
  12752. | 0x0002u
  12753. #endif
  12754. #if !defined(NO_CGI)
  12755. | 0x0004u
  12756. #endif
  12757. #if defined(USE_IPV6)
  12758. | 0x0008u
  12759. #endif
  12760. #if defined(USE_WEBSOCKET)
  12761. | 0x0010u
  12762. #endif
  12763. #if defined(USE_LUA)
  12764. | 0x0020u
  12765. #endif
  12766. #if defined(USE_DUKTAPE)
  12767. | 0x0040u
  12768. #endif
  12769. #if !defined(NO_CACHING)
  12770. | 0x0080u
  12771. #endif
  12772. /* Set some extra bits not defined in the API documentation.
  12773. * These bits may change without further notice. */
  12774. #if defined(MG_LEGACY_INTERFACE)
  12775. | 0x8000u
  12776. #endif
  12777. #if defined(MEMORY_DEBUGGING)
  12778. | 0x0100u
  12779. #endif
  12780. #if defined(USE_TIMERS)
  12781. | 0x0200u
  12782. #endif
  12783. #if !defined(NO_NONCE_CHECK)
  12784. | 0x0400u
  12785. #endif
  12786. #if !defined(NO_POPEN)
  12787. | 0x0800u
  12788. #endif
  12789. ;
  12790. return (feature & feature_set);
  12791. }
  12792. /* Get system information. It can be printed or stored by the caller.
  12793. * Return the size of available information. */
  12794. static int
  12795. mg_get_system_info_impl(char *buffer, int buflen)
  12796. {
  12797. char block[256];
  12798. int system_info_length = 0;
  12799. #if defined(_WIN32)
  12800. const char *eol = "\r\n";
  12801. #else
  12802. const char *eol = "\n";
  12803. #endif
  12804. /* Server version */
  12805. {
  12806. const char *version = mg_version();
  12807. mg_snprintf(NULL,
  12808. NULL,
  12809. block,
  12810. sizeof(block),
  12811. "Server Version: %s%s",
  12812. version,
  12813. eol);
  12814. system_info_length += (int)strlen(block);
  12815. if (system_info_length < buflen) {
  12816. strcat(buffer, block);
  12817. }
  12818. }
  12819. /* System info */
  12820. {
  12821. #if defined(_WIN32)
  12822. #if !defined(__SYMBIAN32__)
  12823. DWORD dwVersion = 0;
  12824. DWORD dwMajorVersion = 0;
  12825. DWORD dwMinorVersion = 0;
  12826. SYSTEM_INFO si;
  12827. GetSystemInfo(&si);
  12828. #ifdef _MSC_VER
  12829. #pragma warning(push)
  12830. /* GetVersion was declared deprecated */
  12831. #pragma warning(disable : 4996)
  12832. #endif
  12833. dwVersion = GetVersion();
  12834. #ifdef _MSC_VER
  12835. #pragma warning(pop)
  12836. #endif
  12837. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  12838. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  12839. mg_snprintf(NULL,
  12840. NULL,
  12841. block,
  12842. sizeof(block),
  12843. "Windows %u.%u%s",
  12844. (unsigned)dwMajorVersion,
  12845. (unsigned)dwMinorVersion,
  12846. eol);
  12847. system_info_length += (int)strlen(block);
  12848. if (system_info_length < buflen) {
  12849. strcat(buffer, block);
  12850. }
  12851. mg_snprintf(NULL,
  12852. NULL,
  12853. block,
  12854. sizeof(block),
  12855. "CPU: type %u, cores %u, mask %x%s",
  12856. (unsigned)si.wProcessorArchitecture,
  12857. (unsigned)si.dwNumberOfProcessors,
  12858. (unsigned)si.dwActiveProcessorMask,
  12859. eol);
  12860. system_info_length += (int)strlen(block);
  12861. if (system_info_length < buflen) {
  12862. strcat(buffer, block);
  12863. }
  12864. #else
  12865. mg_snprintf(NULL, NULL, block, sizeof(block), "%s - Symbian%s", eol);
  12866. system_info_length += (int)strlen(block);
  12867. if (system_info_length < buflen) {
  12868. strcat(buffer, block);
  12869. }
  12870. #endif
  12871. #else
  12872. struct utsname name;
  12873. memset(&name, 0, sizeof(name));
  12874. uname(&name);
  12875. mg_snprintf(NULL,
  12876. NULL,
  12877. block,
  12878. sizeof(block),
  12879. "%s %s (%s) - %s%s",
  12880. name.sysname,
  12881. name.version,
  12882. name.release,
  12883. name.machine,
  12884. eol);
  12885. system_info_length += (int)strlen(block);
  12886. if (system_info_length < buflen) {
  12887. strcat(buffer, block);
  12888. }
  12889. #endif
  12890. }
  12891. /* Features */
  12892. {
  12893. mg_snprintf(NULL,
  12894. NULL,
  12895. block,
  12896. sizeof(block),
  12897. "Features: %X%s%s%s%s%s%s%s%s%s%s",
  12898. mg_check_feature(0xFFFFFFFFu),
  12899. eol,
  12900. mg_check_feature(1) ? " Files" : "",
  12901. mg_check_feature(2) ? " HTTPS" : "",
  12902. mg_check_feature(4) ? " CGI" : "",
  12903. mg_check_feature(8) ? " IPv6" : "",
  12904. mg_check_feature(16) ? " WebSockets" : "",
  12905. mg_check_feature(32) ? " Lua" : "",
  12906. mg_check_feature(64) ? " JavaScript" : "",
  12907. mg_check_feature(128) ? " Cache" : "",
  12908. eol);
  12909. system_info_length += (int)strlen(block);
  12910. if (system_info_length < buflen) {
  12911. strcat(buffer, block);
  12912. }
  12913. #ifdef USE_LUA
  12914. mg_snprintf(NULL,
  12915. NULL,
  12916. block,
  12917. sizeof(block),
  12918. "Lua Version: %u (%s)%s",
  12919. (unsigned)LUA_VERSION_NUM,
  12920. LUA_RELEASE,
  12921. eol);
  12922. system_info_length += (int)strlen(block);
  12923. if (system_info_length < buflen) {
  12924. strcat(buffer, block);
  12925. }
  12926. #endif
  12927. #if defined(USE_DUKTAPE)
  12928. mg_snprintf(NULL,
  12929. NULL,
  12930. block,
  12931. sizeof(block),
  12932. "JavaScript: Duktape %u.%u.%u%s",
  12933. (unsigned)DUK_VERSION / 10000,
  12934. ((unsigned)DUK_VERSION / 100) % 100,
  12935. (unsigned)DUK_VERSION % 100,
  12936. eol);
  12937. system_info_length += (int)strlen(block);
  12938. if (system_info_length < buflen) {
  12939. strcat(buffer, block);
  12940. }
  12941. #endif
  12942. }
  12943. /* Build date */
  12944. {
  12945. mg_snprintf(
  12946. NULL, NULL, block, sizeof(block), "Build: %s%s", __DATE__, eol);
  12947. system_info_length += (int)strlen(block);
  12948. if (system_info_length < buflen) {
  12949. strcat(buffer, block);
  12950. }
  12951. }
  12952. /* Compiler information */
  12953. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  12954. {
  12955. #if defined(_MSC_VER)
  12956. mg_snprintf(NULL,
  12957. NULL,
  12958. block,
  12959. sizeof(block),
  12960. "MSC: %u (%u)%s",
  12961. (unsigned)_MSC_VER,
  12962. (unsigned)_MSC_FULL_VER,
  12963. eol);
  12964. system_info_length += (int)strlen(block);
  12965. if (system_info_length < buflen) {
  12966. strcat(buffer, block);
  12967. }
  12968. #elif defined(__MINGW64__)
  12969. mg_snprintf(NULL,
  12970. NULL,
  12971. block,
  12972. sizeof(block),
  12973. "MinGW64: %u.%u%s",
  12974. (unsigned)__MINGW64_VERSION_MAJOR,
  12975. (unsigned)__MINGW64_VERSION_MINOR,
  12976. eol);
  12977. system_info_length += (int)strlen(block);
  12978. if (system_info_length < buflen) {
  12979. strcat(buffer, block);
  12980. }
  12981. mg_snprintf(NULL,
  12982. NULL,
  12983. block,
  12984. sizeof(block),
  12985. "MinGW32: %u.%u%s",
  12986. (unsigned)__MINGW32_MAJOR_VERSION,
  12987. (unsigned)__MINGW32_MINOR_VERSION,
  12988. eol);
  12989. system_info_length += (int)strlen(block);
  12990. if (system_info_length < buflen) {
  12991. strcat(buffer, block);
  12992. }
  12993. #elif defined(__MINGW32__)
  12994. mg_snprintf(NULL,
  12995. NULL,
  12996. block,
  12997. sizeof(block),
  12998. "MinGW32: %u.%u%s",
  12999. (unsigned)__MINGW32_MAJOR_VERSION,
  13000. (unsigned)__MINGW32_MINOR_VERSION,
  13001. eol);
  13002. system_info_length += (int)strlen(block);
  13003. if (system_info_length < buflen) {
  13004. strcat(buffer, block);
  13005. }
  13006. #elif defined(__clang__)
  13007. mg_snprintf(NULL,
  13008. NULL,
  13009. block,
  13010. sizeof(block),
  13011. "clang: %u.%u.%u (%s)%s",
  13012. __clang_major__,
  13013. __clang_minor__,
  13014. __clang_patchlevel__,
  13015. __clang_version__,
  13016. eol);
  13017. system_info_length += (int)strlen(block);
  13018. if (system_info_length < buflen) {
  13019. strcat(buffer, block);
  13020. }
  13021. #elif defined(__GNUC__)
  13022. mg_snprintf(NULL,
  13023. NULL,
  13024. block,
  13025. sizeof(block),
  13026. "gcc: %u.%u.%u%s",
  13027. (unsigned)__GNUC__,
  13028. (unsigned)__GNUC_MINOR__,
  13029. (unsigned)__GNUC_PATCHLEVEL__,
  13030. eol);
  13031. system_info_length += (int)strlen(block);
  13032. if (system_info_length < buflen) {
  13033. strcat(buffer, block);
  13034. }
  13035. #elif defined(__INTEL_COMPILER)
  13036. mg_snprintf(NULL,
  13037. NULL,
  13038. block,
  13039. sizeof(block),
  13040. "Intel C/C++: %u%s",
  13041. (unsigned)__INTEL_COMPILER,
  13042. eol);
  13043. system_info_length += (int)strlen(block);
  13044. if (system_info_length < buflen) {
  13045. strcat(buffer, block);
  13046. }
  13047. #elif defined(__BORLANDC__)
  13048. mg_snprintf(NULL,
  13049. NULL,
  13050. block,
  13051. sizeof(block),
  13052. "Borland C: 0x%x%s",
  13053. (unsigned)__BORLANDC__,
  13054. eol);
  13055. system_info_length += (int)strlen(block);
  13056. if (system_info_length < buflen) {
  13057. strcat(buffer, block);
  13058. }
  13059. #elif defined(__SUNPRO_C)
  13060. mg_snprintf(NULL,
  13061. NULL,
  13062. block,
  13063. sizeof(block),
  13064. "Solaris: 0x%x%s",
  13065. (unsigned)__SUNPRO_C,
  13066. eol);
  13067. system_info_length += (int)strlen(block);
  13068. if (system_info_length < buflen) {
  13069. strcat(buffer, block);
  13070. }
  13071. #else
  13072. mg_snprintf(NULL, NULL, block, sizeof(block), "Other compiler%s", eol);
  13073. system_info_length += (int)strlen(block);
  13074. if (system_info_length < buflen) {
  13075. strcat(buffer, block);
  13076. }
  13077. #endif
  13078. }
  13079. /* Determine 32/64 bit data mode.
  13080. * see https://en.wikipedia.org/wiki/64-bit_computing */
  13081. {
  13082. mg_snprintf(NULL,
  13083. NULL,
  13084. block,
  13085. sizeof(block),
  13086. "Data model: int:%u/%u/%u/%u, float:%u/%u/%u, char:%u/%u, "
  13087. "ptr:%u, size:%u, time:%u%s",
  13088. (unsigned)sizeof(short),
  13089. (unsigned)sizeof(int),
  13090. (unsigned)sizeof(long),
  13091. (unsigned)sizeof(long long),
  13092. (unsigned)sizeof(float),
  13093. (unsigned)sizeof(double),
  13094. (unsigned)sizeof(long double),
  13095. (unsigned)sizeof(char),
  13096. (unsigned)sizeof(wchar_t),
  13097. (unsigned)sizeof(void *),
  13098. (unsigned)sizeof(size_t),
  13099. (unsigned)sizeof(time_t),
  13100. eol);
  13101. system_info_length += (int)strlen(block);
  13102. if (system_info_length < buflen) {
  13103. strcat(buffer, block);
  13104. }
  13105. }
  13106. return system_info_length;
  13107. }
  13108. /* Get system information. It can be printed or stored by the caller.
  13109. * Return the size of available information. */
  13110. int
  13111. mg_get_system_info(char *buffer, int buflen)
  13112. {
  13113. if ((buffer == NULL) || (buflen < 1)) {
  13114. return mg_get_system_info_impl(NULL, 0);
  13115. } else {
  13116. /* Reset buffer, so we can always use strcat. */
  13117. buffer[0] = 0;
  13118. return mg_get_system_info_impl(buffer, buflen);
  13119. }
  13120. }
  13121. /* mg_init_library counter */
  13122. static int mg_init_library_called = 0;
  13123. /* Initialize this library. This function does not need to be thread safe. */
  13124. unsigned
  13125. mg_init_library(unsigned features)
  13126. {
  13127. /* Currently we do nothing here. This is planned for Version 1.10.
  13128. * For now, we just add this function, so clients can be changed early. */
  13129. if (mg_init_library_called <= 0) {
  13130. mg_init_library_called = 1;
  13131. return mg_check_feature(features & 0xFFu);
  13132. }
  13133. return 0;
  13134. }
  13135. /* Un-initialize this library. */
  13136. unsigned
  13137. mg_exit_library(void)
  13138. {
  13139. if (mg_init_library_called <= 0) {
  13140. return 0;
  13141. }
  13142. mg_init_library_called--;
  13143. return 1;
  13144. }
  13145. /* End of civetweb.c */