civetweb.c 450 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122
  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. /* According to https://en.wikipedia.org/wiki/Symbian#History,
  97. * Symbian is no longer maintained since 2014-01-01.
  98. * Recent versions of CivetWeb are no longer tested for Symbian.
  99. * It makes no sense, to support an abandoned operating system.
  100. * All remaining "#ifdef __SYMBIAN__" cases will be droped from
  101. * the code sooner or later.
  102. */
  103. #pragma message \
  104. "Symbian is no longer maintained. CivetWeb will drop Symbian support."
  105. #define NO_SSL /* SSL is not supported */
  106. #define NO_CGI /* CGI is not supported */
  107. #define PATH_MAX FILENAME_MAX
  108. #endif /* __SYMBIAN32__ */
  109. #ifndef CIVETWEB_HEADER_INCLUDED
  110. /* Include the header file here, so the CivetWeb interface is defined for the
  111. * entire implementation, including the following forward definitions. */
  112. #include "civetweb.h"
  113. #endif
  114. #ifndef IGNORE_UNUSED_RESULT
  115. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  116. #endif
  117. #if defined(__GNUC__) || defined(__MINGW32__)
  118. /* GCC unused function attribute seems fundamentally broken.
  119. * Several attempts to tell the compiler "THIS FUNCTION MAY BE USED
  120. * OR UNUSED" for individual functions failed.
  121. * Either the compiler creates an "unused-function" warning if a
  122. * function is not marked with __attribute__((unused)).
  123. * On the other hand, if the function is marked with this attribute,
  124. * but is used, the compiler raises a completely idiotic
  125. * "used-but-marked-unused" warning - and
  126. * #pragma GCC diagnostic ignored "-Wused-but-marked-unused"
  127. * raises error: unknown option after ‘#pragma GCC diagnostic’.
  128. * Disable this warning completely, until the GCC guys sober up
  129. * again.
  130. */
  131. #pragma GCC diagnostic ignored "-Wunused-function"
  132. #define FUNCTION_MAY_BE_UNUSED /* __attribute__((unused)) */
  133. #else
  134. #define FUNCTION_MAY_BE_UNUSED
  135. #endif
  136. #ifndef _WIN32_WCE /* Some ANSI #includes are not available on Windows CE */
  137. #include <sys/types.h>
  138. #include <sys/stat.h>
  139. #include <errno.h>
  140. #include <signal.h>
  141. #include <fcntl.h>
  142. #endif /* !_WIN32_WCE */
  143. #ifdef __clang__
  144. /* When using -Weverything, clang does not accept it's own headers
  145. * in a release build configuration. Disable what is too much in
  146. * -Weverything. */
  147. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  148. #endif
  149. #ifdef __MACH__ /* Apple OSX section */
  150. #ifdef __clang__
  151. /* Avoid warnings for Xopen 7.00 and higher */
  152. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  153. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  154. #endif
  155. #define CLOCK_MONOTONIC (1)
  156. #define CLOCK_REALTIME (2)
  157. #include <sys/errno.h>
  158. #include <sys/time.h>
  159. #include <mach/clock.h>
  160. #include <mach/mach.h>
  161. #include <mach/mach_time.h>
  162. #include <assert.h>
  163. /* clock_gettime is not implemented on OSX prior to 10.12 */
  164. static int
  165. _civet_clock_gettime(int clk_id, struct timespec *t)
  166. {
  167. memset(t, 0, sizeof(*t));
  168. if (clk_id == CLOCK_REALTIME) {
  169. struct timeval now;
  170. int rv = gettimeofday(&now, NULL);
  171. if (rv) {
  172. return rv;
  173. }
  174. t->tv_sec = now.tv_sec;
  175. t->tv_nsec = now.tv_usec * 1000;
  176. return 0;
  177. } else if (clk_id == CLOCK_MONOTONIC) {
  178. static uint64_t clock_start_time = 0;
  179. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  180. uint64_t now = mach_absolute_time();
  181. if (clock_start_time == 0) {
  182. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  183. #if defined(DEBUG)
  184. assert(mach_status == KERN_SUCCESS);
  185. #else
  186. /* appease "unused variable" warning for release builds */
  187. (void)mach_status;
  188. #endif
  189. clock_start_time = now;
  190. }
  191. now = (uint64_t)((double)(now - clock_start_time)
  192. * (double)timebase_ifo.numer
  193. / (double)timebase_ifo.denom);
  194. t->tv_sec = now / 1000000000;
  195. t->tv_nsec = now % 1000000000;
  196. return 0;
  197. }
  198. return -1; /* EINVAL - Clock ID is unknown */
  199. }
  200. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  201. #ifdef __CLOCK_AVAILABILITY
  202. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  203. * declared but it may be NULL at runtime. So we need to check before using
  204. * it. */
  205. static int
  206. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  207. {
  208. if (clock_gettime) {
  209. return clock_gettime(clk_id, t);
  210. }
  211. return _civet_clock_gettime(clk_id, t);
  212. }
  213. #define clock_gettime _civet_safe_clock_gettime
  214. #else
  215. #define clock_gettime _civet_clock_gettime
  216. #endif
  217. #endif
  218. #include <time.h>
  219. #include <stdlib.h>
  220. #include <stdarg.h>
  221. #include <assert.h>
  222. #include <string.h>
  223. #include <ctype.h>
  224. #include <limits.h>
  225. #include <stddef.h>
  226. #include <stdio.h>
  227. #include <stdint.h>
  228. #ifndef INT64_MAX
  229. #define INT64_MAX (9223372036854775807)
  230. #endif
  231. #ifndef MAX_WORKER_THREADS
  232. #define MAX_WORKER_THREADS (1024 * 64)
  233. #endif
  234. #ifndef SOCKET_TIMEOUT_QUANTUM /* in ms */
  235. #define SOCKET_TIMEOUT_QUANTUM (2000)
  236. #endif
  237. #define SHUTDOWN_RD (0)
  238. #define SHUTDOWN_WR (1)
  239. #define SHUTDOWN_BOTH (2)
  240. mg_static_assert(MAX_WORKER_THREADS >= 1,
  241. "worker threads must be a positive number");
  242. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  243. "size_t data type size check");
  244. #if defined(_WIN32) \
  245. && !defined(__SYMBIAN32__) /* WINDOWS / UNIX include block */
  246. #include <windows.h>
  247. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  248. #include <ws2tcpip.h>
  249. typedef const char *SOCK_OPT_TYPE;
  250. #if !defined(PATH_MAX)
  251. #define PATH_MAX (MAX_PATH)
  252. #endif
  253. #if !defined(PATH_MAX)
  254. #define PATH_MAX (4096)
  255. #endif
  256. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  257. #ifndef _IN_PORT_T
  258. #ifndef in_port_t
  259. #define in_port_t u_short
  260. #endif
  261. #endif
  262. #ifndef _WIN32_WCE
  263. #include <process.h>
  264. #include <direct.h>
  265. #include <io.h>
  266. #else /* _WIN32_WCE */
  267. #define NO_CGI /* WinCE has no pipes */
  268. #define NO_POPEN /* WinCE has no popen */
  269. typedef long off_t;
  270. #define errno ((int)(GetLastError()))
  271. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  272. #endif /* _WIN32_WCE */
  273. #define MAKEUQUAD(lo, hi) \
  274. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  275. #define RATE_DIFF (10000000) /* 100 nsecs */
  276. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  277. #define SYS2UNIX_TIME(lo, hi) \
  278. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  279. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  280. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  281. * Also use _strtoui64 on modern M$ compilers */
  282. #if defined(_MSC_VER)
  283. #if (_MSC_VER < 1300)
  284. #define STRX(x) #x
  285. #define STR(x) STRX(x)
  286. #define __func__ __FILE__ ":" STR(__LINE__)
  287. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  288. #define strtoll(x, y, z) (_atoi64(x))
  289. #else
  290. #define __func__ __FUNCTION__
  291. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  292. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  293. #endif
  294. #endif /* _MSC_VER */
  295. #define ERRNO ((int)(GetLastError()))
  296. #define NO_SOCKLEN_T
  297. #if defined(_WIN64) || defined(__MINGW64__)
  298. #define SSL_LIB "ssleay64.dll"
  299. #define CRYPTO_LIB "libeay64.dll"
  300. #else
  301. #define SSL_LIB "ssleay32.dll"
  302. #define CRYPTO_LIB "libeay32.dll"
  303. #endif
  304. #define O_NONBLOCK (0)
  305. #ifndef W_OK
  306. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  307. #endif
  308. #if !defined(EWOULDBLOCK)
  309. #define EWOULDBLOCK WSAEWOULDBLOCK
  310. #endif /* !EWOULDBLOCK */
  311. #define _POSIX_
  312. #define INT64_FMT "I64d"
  313. #define UINT64_FMT "I64u"
  314. #define WINCDECL __cdecl
  315. #define vsnprintf_impl _vsnprintf
  316. #define access _access
  317. #define mg_sleep(x) (Sleep(x))
  318. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  319. #ifndef popen
  320. #define popen(x, y) (_popen(x, y))
  321. #endif
  322. #ifndef pclose
  323. #define pclose(x) (_pclose(x))
  324. #endif
  325. #define close(x) (_close(x))
  326. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  327. #define RTLD_LAZY (0)
  328. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  329. #define fdopen(x, y) (_fdopen((x), (y)))
  330. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  331. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  332. #define flockfile(x) (EnterCriticalSection(&global_log_file_lock))
  333. #define funlockfile(x) (LeaveCriticalSection(&global_log_file_lock))
  334. #define sleep(x) (Sleep((x)*1000))
  335. #define rmdir(x) (_rmdir(x))
  336. #define timegm(x) (_mkgmtime(x))
  337. #if !defined(fileno)
  338. #define fileno(x) (_fileno(x))
  339. #endif /* !fileno MINGW #defines fileno */
  340. typedef HANDLE pthread_mutex_t;
  341. typedef DWORD pthread_key_t;
  342. typedef HANDLE pthread_t;
  343. typedef struct {
  344. CRITICAL_SECTION threadIdSec;
  345. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  346. } pthread_cond_t;
  347. #ifndef __clockid_t_defined
  348. typedef DWORD clockid_t;
  349. #endif
  350. #ifndef CLOCK_MONOTONIC
  351. #define CLOCK_MONOTONIC (1)
  352. #endif
  353. #ifndef CLOCK_REALTIME
  354. #define CLOCK_REALTIME (2)
  355. #endif
  356. #ifndef CLOCK_THREAD
  357. #define CLOCK_THREAD (3)
  358. #endif
  359. #ifndef CLOCK_PROCESS
  360. #define CLOCK_PROCESS (4)
  361. #endif
  362. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  363. #define _TIMESPEC_DEFINED
  364. #endif
  365. #ifndef _TIMESPEC_DEFINED
  366. struct timespec {
  367. time_t tv_sec; /* seconds */
  368. long tv_nsec; /* nanoseconds */
  369. };
  370. #endif
  371. #if !defined(WIN_PTHREADS_TIME_H)
  372. #define MUST_IMPLEMENT_CLOCK_GETTIME
  373. #endif
  374. #ifdef MUST_IMPLEMENT_CLOCK_GETTIME
  375. #define clock_gettime mg_clock_gettime
  376. static int
  377. clock_gettime(clockid_t clk_id, struct timespec *tp)
  378. {
  379. FILETIME ft;
  380. ULARGE_INTEGER li, li2;
  381. BOOL ok = FALSE;
  382. double d;
  383. static double perfcnt_per_sec = 0.0;
  384. if (tp) {
  385. memset(tp, 0, sizeof(*tp));
  386. if (clk_id == CLOCK_REALTIME) {
  387. /* BEGIN: CLOCK_REALTIME = wall clock (date and time) */
  388. GetSystemTimeAsFileTime(&ft);
  389. li.LowPart = ft.dwLowDateTime;
  390. li.HighPart = ft.dwHighDateTime;
  391. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  392. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  393. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  394. ok = TRUE;
  395. /* END: CLOCK_REALTIME */
  396. } else if (clk_id == CLOCK_MONOTONIC) {
  397. /* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */
  398. if (perfcnt_per_sec == 0.0) {
  399. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  400. perfcnt_per_sec = 1.0 / li.QuadPart;
  401. }
  402. if (perfcnt_per_sec != 0.0) {
  403. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  404. d = li.QuadPart * perfcnt_per_sec;
  405. tp->tv_sec = (time_t)d;
  406. d -= tp->tv_sec;
  407. tp->tv_nsec = (long)(d * 1.0E9);
  408. ok = TRUE;
  409. }
  410. /* END: CLOCK_MONOTONIC */
  411. } else if (clk_id == CLOCK_THREAD) {
  412. /* BEGIN: CLOCK_THREAD = CPU usage of thread */
  413. FILETIME t_create, t_exit, t_kernel, t_user;
  414. if (GetThreadTimes(GetCurrentThread(),
  415. &t_create,
  416. &t_exit,
  417. &t_kernel,
  418. &t_user)) {
  419. li.LowPart = t_user.dwLowDateTime;
  420. li.HighPart = t_user.dwHighDateTime;
  421. li2.LowPart = t_kernel.dwLowDateTime;
  422. li2.HighPart = t_kernel.dwHighDateTime;
  423. li.QuadPart += li2.QuadPart;
  424. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  425. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  426. ok = TRUE;
  427. }
  428. /* END: CLOCK_THREAD */
  429. } else if (clk_id == CLOCK_PROCESS) {
  430. /* BEGIN: CLOCK_PROCESS = CPU usage of process */
  431. FILETIME t_create, t_exit, t_kernel, t_user;
  432. if (GetProcessTimes(GetCurrentProcess(),
  433. &t_create,
  434. &t_exit,
  435. &t_kernel,
  436. &t_user)) {
  437. li.LowPart = t_user.dwLowDateTime;
  438. li.HighPart = t_user.dwHighDateTime;
  439. li2.LowPart = t_kernel.dwLowDateTime;
  440. li2.HighPart = t_kernel.dwHighDateTime;
  441. li.QuadPart += li2.QuadPart;
  442. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  443. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  444. ok = TRUE;
  445. }
  446. /* END: CLOCK_PROCESS */
  447. } else {
  448. /* BEGIN: unknown clock */
  449. /* ok = FALSE; already set by init */
  450. /* END: unknown clock */
  451. }
  452. }
  453. return ok ? 0 : -1;
  454. }
  455. #endif
  456. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  457. static int pthread_mutex_lock(pthread_mutex_t *);
  458. static int pthread_mutex_unlock(pthread_mutex_t *);
  459. static void path_to_unicode(const struct mg_connection *conn,
  460. const char *path,
  461. wchar_t *wbuf,
  462. size_t wbuf_len);
  463. /* All file operations need to be rewritten to solve #246. */
  464. #include "file_ops.inl"
  465. struct mg_file;
  466. static const char *
  467. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p);
  468. /* POSIX dirent interface */
  469. struct dirent {
  470. char d_name[PATH_MAX];
  471. };
  472. typedef struct DIR {
  473. HANDLE handle;
  474. WIN32_FIND_DATAW info;
  475. struct dirent result;
  476. } DIR;
  477. #if defined(_WIN32) && !defined(POLLIN)
  478. #ifndef HAVE_POLL
  479. struct pollfd {
  480. SOCKET fd;
  481. short events;
  482. short revents;
  483. };
  484. #define POLLIN (0x0300)
  485. #endif
  486. #endif
  487. /* Mark required libraries */
  488. #if defined(_MSC_VER)
  489. #pragma comment(lib, "Ws2_32.lib")
  490. #endif
  491. #else /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  492. WINDOWS / UNIX include block */
  493. #include <sys/wait.h>
  494. #include <sys/socket.h>
  495. #include <sys/poll.h>
  496. #include <netinet/in.h>
  497. #include <arpa/inet.h>
  498. #include <sys/time.h>
  499. #include <sys/utsname.h>
  500. #include <stdint.h>
  501. #include <inttypes.h>
  502. #include <netdb.h>
  503. #include <netinet/tcp.h>
  504. typedef const void *SOCK_OPT_TYPE;
  505. #if defined(ANDROID)
  506. typedef unsigned short int in_port_t;
  507. #endif
  508. #include <pwd.h>
  509. #include <unistd.h>
  510. #include <grp.h>
  511. #include <dirent.h>
  512. #define vsnprintf_impl vsnprintf
  513. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  514. #include <dlfcn.h>
  515. #endif
  516. #include <pthread.h>
  517. #if defined(__MACH__)
  518. #define SSL_LIB "libssl.dylib"
  519. #define CRYPTO_LIB "libcrypto.dylib"
  520. #else
  521. #if !defined(SSL_LIB)
  522. #define SSL_LIB "libssl.so"
  523. #endif
  524. #if !defined(CRYPTO_LIB)
  525. #define CRYPTO_LIB "libcrypto.so"
  526. #endif
  527. #endif
  528. #ifndef O_BINARY
  529. #define O_BINARY (0)
  530. #endif /* O_BINARY */
  531. #define closesocket(a) (close(a))
  532. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  533. #define mg_remove(conn, x) (remove(x))
  534. #define mg_sleep(x) (usleep((x)*1000))
  535. #define mg_opendir(conn, x) (opendir(x))
  536. #define mg_closedir(x) (closedir(x))
  537. #define mg_readdir(x) (readdir(x))
  538. #define ERRNO (errno)
  539. #define INVALID_SOCKET (-1)
  540. #define INT64_FMT PRId64
  541. #define UINT64_FMT PRIu64
  542. typedef int SOCKET;
  543. #define WINCDECL
  544. #if defined(__hpux)
  545. /* HPUX 11 does not have monotonic, fall back to realtime */
  546. #ifndef CLOCK_MONOTONIC
  547. #define CLOCK_MONOTONIC CLOCK_REALTIME
  548. #endif
  549. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  550. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  551. * the prototypes use int* rather than socklen_t* which matches the
  552. * actual library expectation. When called with the wrong size arg
  553. * accept() returns a zero client inet addr and check_acl() always
  554. * fails. Since socklen_t is widely used below, just force replace
  555. * their typedef with int. - DTL
  556. */
  557. #define socklen_t int
  558. #endif /* hpux */
  559. #endif /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  560. WINDOWS / UNIX include block */
  561. /* va_copy should always be a macro, C99 and C++11 - DTL */
  562. #ifndef va_copy
  563. #define va_copy(x, y) ((x) = (y))
  564. #endif
  565. #ifdef _WIN32
  566. /* Create substitutes for POSIX functions in Win32. */
  567. #if defined(__MINGW32__)
  568. /* Show no warning in case system functions are not used. */
  569. #pragma GCC diagnostic push
  570. #pragma GCC diagnostic ignored "-Wunused-function"
  571. #endif
  572. static CRITICAL_SECTION global_log_file_lock;
  573. FUNCTION_MAY_BE_UNUSED
  574. static DWORD
  575. pthread_self(void)
  576. {
  577. return GetCurrentThreadId();
  578. }
  579. FUNCTION_MAY_BE_UNUSED
  580. static int
  581. pthread_key_create(
  582. pthread_key_t *key,
  583. void (*_ignored)(void *) /* destructor not supported for Windows */
  584. )
  585. {
  586. (void)_ignored;
  587. if ((key != 0)) {
  588. *key = TlsAlloc();
  589. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  590. }
  591. return -2;
  592. }
  593. FUNCTION_MAY_BE_UNUSED
  594. static int
  595. pthread_key_delete(pthread_key_t key)
  596. {
  597. return TlsFree(key) ? 0 : 1;
  598. }
  599. FUNCTION_MAY_BE_UNUSED
  600. static int
  601. pthread_setspecific(pthread_key_t key, void *value)
  602. {
  603. return TlsSetValue(key, value) ? 0 : 1;
  604. }
  605. FUNCTION_MAY_BE_UNUSED
  606. static void *
  607. pthread_getspecific(pthread_key_t key)
  608. {
  609. return TlsGetValue(key);
  610. }
  611. #if defined(__MINGW32__)
  612. /* Enable unused function warning again */
  613. #pragma GCC diagnostic pop
  614. #endif
  615. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  616. #else
  617. static pthread_mutexattr_t pthread_mutex_attr;
  618. #endif /* _WIN32 */
  619. #define PASSWORDS_FILE_NAME ".htpasswd"
  620. #define CGI_ENVIRONMENT_SIZE (4096)
  621. #define MAX_CGI_ENVIR_VARS (256)
  622. #define MG_BUF_LEN (8192)
  623. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  624. #if defined(_WIN32_WCE)
  625. /* Create substitutes for POSIX functions in Win32. */
  626. #if defined(__MINGW32__)
  627. /* Show no warning in case system functions are not used. */
  628. #pragma GCC diagnostic push
  629. #pragma GCC diagnostic ignored "-Wunused-function"
  630. #endif
  631. FUNCTION_MAY_BE_UNUSED
  632. static time_t
  633. time(time_t *ptime)
  634. {
  635. time_t t;
  636. SYSTEMTIME st;
  637. FILETIME ft;
  638. GetSystemTime(&st);
  639. SystemTimeToFileTime(&st, &ft);
  640. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  641. if (ptime != NULL) {
  642. *ptime = t;
  643. }
  644. return t;
  645. }
  646. FUNCTION_MAY_BE_UNUSED
  647. static struct tm *
  648. localtime_s(const time_t *ptime, struct tm *ptm)
  649. {
  650. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  651. FILETIME ft, lft;
  652. SYSTEMTIME st;
  653. TIME_ZONE_INFORMATION tzinfo;
  654. if (ptm == NULL) {
  655. return NULL;
  656. }
  657. *(int64_t *)&ft = t;
  658. FileTimeToLocalFileTime(&ft, &lft);
  659. FileTimeToSystemTime(&lft, &st);
  660. ptm->tm_year = st.wYear - 1900;
  661. ptm->tm_mon = st.wMonth - 1;
  662. ptm->tm_wday = st.wDayOfWeek;
  663. ptm->tm_mday = st.wDay;
  664. ptm->tm_hour = st.wHour;
  665. ptm->tm_min = st.wMinute;
  666. ptm->tm_sec = st.wSecond;
  667. ptm->tm_yday = 0; /* hope nobody uses this */
  668. ptm->tm_isdst =
  669. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  670. return ptm;
  671. }
  672. FUNCTION_MAY_BE_UNUSED
  673. static struct tm *
  674. gmtime_s(const time_t *ptime, struct tm *ptm)
  675. {
  676. /* FIXME(lsm): fix this. */
  677. return localtime_s(ptime, ptm);
  678. }
  679. static int mg_atomic_inc(volatile int *addr);
  680. static struct tm tm_array[MAX_WORKER_THREADS];
  681. static int tm_index = 0;
  682. FUNCTION_MAY_BE_UNUSED
  683. static struct tm *
  684. localtime(const time_t *ptime)
  685. {
  686. int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0]));
  687. return localtime_s(ptime, tm_array + i);
  688. }
  689. FUNCTION_MAY_BE_UNUSED
  690. static struct tm *
  691. gmtime(const time_t *ptime)
  692. {
  693. int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  694. return gmtime_s(ptime, tm_array + i);
  695. }
  696. FUNCTION_MAY_BE_UNUSED
  697. static size_t
  698. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  699. {
  700. /* TODO: (void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  701. * for WinCE"); */
  702. return 0;
  703. }
  704. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  705. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  706. #define remove(f) mg_remove(NULL, f)
  707. FUNCTION_MAY_BE_UNUSED
  708. static int
  709. rename(const char *a, const char *b)
  710. {
  711. wchar_t wa[PATH_MAX];
  712. wchar_t wb[PATH_MAX];
  713. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  714. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  715. return MoveFileW(wa, wb) ? 0 : -1;
  716. }
  717. struct stat {
  718. int64_t st_size;
  719. time_t st_mtime;
  720. };
  721. FUNCTION_MAY_BE_UNUSED
  722. static int
  723. stat(const char *name, struct stat *st)
  724. {
  725. wchar_t wbuf[PATH_MAX];
  726. WIN32_FILE_ATTRIBUTE_DATA attr;
  727. time_t creation_time, write_time;
  728. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  729. memset(&attr, 0, sizeof(attr));
  730. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  731. st->st_size =
  732. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  733. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  734. attr.ftLastWriteTime.dwHighDateTime);
  735. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  736. attr.ftCreationTime.dwHighDateTime);
  737. if (creation_time > write_time) {
  738. st->st_mtime = creation_time;
  739. } else {
  740. st->st_mtime = write_time;
  741. }
  742. return 0;
  743. }
  744. #define access(x, a) 1 /* not required anyway */
  745. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  746. /* Values from errno.h in Windows SDK (Visual Studio). */
  747. #define EEXIST 17
  748. #define EACCES 13
  749. #define ENOENT 2
  750. #if defined(__MINGW32__)
  751. /* Enable unused function warning again */
  752. #pragma GCC diagnostic pop
  753. #endif
  754. #endif /* defined(_WIN32_WCE) */
  755. #if defined(__GNUC__) || defined(__MINGW32__)
  756. /* Show no warning in case system functions are not used. */
  757. #define GCC_VERSION \
  758. (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
  759. #if GCC_VERSION >= 40500
  760. #pragma GCC diagnostic push
  761. #pragma GCC diagnostic ignored "-Wunused-function"
  762. #endif /* GCC_VERSION >= 40500 */
  763. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  764. #if defined(__clang__)
  765. /* Show no warning in case system functions are not used. */
  766. #pragma clang diagnostic push
  767. #pragma clang diagnostic ignored "-Wunused-function"
  768. #endif
  769. static pthread_mutex_t global_lock_mutex;
  770. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  771. /* Forward declaration for Windows */
  772. FUNCTION_MAY_BE_UNUSED
  773. static int pthread_mutex_lock(pthread_mutex_t *mutex);
  774. FUNCTION_MAY_BE_UNUSED
  775. static int pthread_mutex_unlock(pthread_mutex_t *mutex);
  776. #endif
  777. FUNCTION_MAY_BE_UNUSED
  778. static void
  779. mg_global_lock(void)
  780. {
  781. (void)pthread_mutex_lock(&global_lock_mutex);
  782. }
  783. FUNCTION_MAY_BE_UNUSED
  784. static void
  785. mg_global_unlock(void)
  786. {
  787. (void)pthread_mutex_unlock(&global_lock_mutex);
  788. }
  789. FUNCTION_MAY_BE_UNUSED
  790. static int
  791. mg_atomic_inc(volatile int *addr)
  792. {
  793. int ret;
  794. #if defined(_WIN32) && !defined(__SYMBIAN32__) && !defined(NO_ATOMICS)
  795. /* Depending on the SDK, this function uses either
  796. * (volatile unsigned int *) or (volatile LONG *),
  797. * so whatever you use, the other SDK is likely to raise a warning. */
  798. ret = InterlockedIncrement((volatile long *)addr);
  799. #elif defined(__GNUC__) \
  800. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  801. && !defined(NO_ATOMICS)
  802. ret = __sync_add_and_fetch(addr, 1);
  803. #else
  804. mg_global_lock();
  805. ret = (++(*addr));
  806. mg_global_unlock();
  807. #endif
  808. return ret;
  809. }
  810. FUNCTION_MAY_BE_UNUSED
  811. static int
  812. mg_atomic_dec(volatile int *addr)
  813. {
  814. int ret;
  815. #if defined(_WIN32) && !defined(__SYMBIAN32__) && !defined(NO_ATOMICS)
  816. /* Depending on the SDK, this function uses either
  817. * (volatile unsigned int *) or (volatile LONG *),
  818. * so whatever you use, the other SDK is likely to raise a warning. */
  819. ret = InterlockedDecrement((volatile long *)addr);
  820. #elif defined(__GNUC__) \
  821. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  822. && !defined(NO_ATOMICS)
  823. ret = __sync_sub_and_fetch(addr, 1);
  824. #else
  825. mg_global_lock();
  826. ret = (--(*addr));
  827. mg_global_unlock();
  828. #endif
  829. return ret;
  830. }
  831. #if defined(USE_SERVER_STATS)
  832. static int64_t
  833. mg_atomic_add(volatile int64_t *addr, int64_t value)
  834. {
  835. int64_t ret;
  836. #if defined(_WIN32) && !defined(__SYMBIAN32__) && !defined(NO_ATOMICS)
  837. ret = InterlockedAdd64(addr, value);
  838. #elif defined(__GNUC__) \
  839. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  840. && !defined(NO_ATOMICS)
  841. ret = __sync_add_and_fetch(addr, value);
  842. #else
  843. mg_global_lock();
  844. *addr += value;
  845. ret = (*addr);
  846. mg_global_unlock();
  847. #endif
  848. return ret;
  849. }
  850. #endif
  851. #if defined(__GNUC__)
  852. /* Show no warning in case system functions are not used. */
  853. #if GCC_VERSION >= 40500
  854. #pragma GCC diagnostic pop
  855. #endif /* GCC_VERSION >= 40500 */
  856. #endif /* defined(__GNUC__) */
  857. #if defined(__clang__)
  858. /* Show no warning in case system functions are not used. */
  859. #pragma clang diagnostic pop
  860. #endif
  861. #if defined(USE_SERVER_STATS)
  862. struct mg_memory_stat {
  863. volatile int64_t totalMemUsed;
  864. volatile int64_t maxMemUsed;
  865. volatile int blockCount;
  866. };
  867. static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
  868. static void *
  869. mg_malloc_ex(size_t size,
  870. struct mg_context *ctx,
  871. const char *file,
  872. unsigned line)
  873. {
  874. void *data = malloc(size + 2 * sizeof(uintptr_t));
  875. void *memory = 0;
  876. struct mg_memory_stat *mstat = get_memory_stat(ctx);
  877. #if defined(MEMORY_DEBUGGING)
  878. char mallocStr[256];
  879. #else
  880. (void)file;
  881. (void)line;
  882. #endif
  883. if (data) {
  884. int64_t mmem = mg_atomic_add(&mstat->totalMemUsed, (int64_t)size);
  885. if (mmem > mstat->maxMemUsed) {
  886. /* could use atomic compare exchange, but this
  887. * seems overkill for statistics data */
  888. mstat->maxMemUsed = mmem;
  889. }
  890. mg_atomic_inc(&mstat->blockCount);
  891. ((uintptr_t *)data)[0] = size;
  892. ((uintptr_t *)data)[1] = (uintptr_t)mstat;
  893. memory = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  894. }
  895. #if defined(MEMORY_DEBUGGING)
  896. sprintf(mallocStr,
  897. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  898. memory,
  899. (unsigned long)size,
  900. (unsigned long)mstat->totalMemUsed,
  901. (unsigned long)mstat->blockCount,
  902. file,
  903. line);
  904. #if defined(_WIN32)
  905. OutputDebugStringA(mallocStr);
  906. #else
  907. DEBUG_TRACE("%s", mallocStr);
  908. #endif
  909. #endif
  910. return memory;
  911. }
  912. static void *
  913. mg_calloc_ex(size_t count,
  914. size_t size,
  915. struct mg_context *ctx,
  916. const char *file,
  917. unsigned line)
  918. {
  919. void *data = mg_malloc_ex(size * count, ctx, file, line);
  920. if (data) {
  921. memset(data, 0, size * count);
  922. }
  923. return data;
  924. }
  925. static void
  926. mg_free_ex(void *memory, const char *file, unsigned line)
  927. {
  928. void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  929. #if defined(MEMORY_DEBUGGING)
  930. char mallocStr[256];
  931. #else
  932. (void)file;
  933. (void)line;
  934. #endif
  935. if (memory) {
  936. uintptr_t size = ((uintptr_t *)data)[0];
  937. struct mg_memory_stat *mstat =
  938. (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
  939. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)size);
  940. mg_atomic_dec(&mstat->blockCount);
  941. #if defined(MEMORY_DEBUGGING)
  942. sprintf(mallocStr,
  943. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  944. memory,
  945. (unsigned long)size,
  946. (unsigned long)mstat->totalMemUsed,
  947. (unsigned long)mstat->blockCount,
  948. file,
  949. line);
  950. #if defined(_WIN32)
  951. OutputDebugStringA(mallocStr);
  952. #else
  953. DEBUG_TRACE("%s", mallocStr);
  954. #endif
  955. #endif
  956. free(data);
  957. }
  958. }
  959. static void *
  960. mg_realloc_ex(void *memory,
  961. size_t newsize,
  962. struct mg_context *ctx,
  963. const char *file,
  964. unsigned line)
  965. {
  966. void *data;
  967. void *_realloc;
  968. uintptr_t oldsize;
  969. #if defined(MEMORY_DEBUGGING)
  970. char mallocStr[256];
  971. #else
  972. (void)file;
  973. (void)line;
  974. #endif
  975. if (newsize) {
  976. if (memory) {
  977. /* Reallocate existing block */
  978. struct mg_memory_stat *mstat;
  979. data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  980. oldsize = ((uintptr_t *)data)[0];
  981. mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
  982. _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
  983. if (_realloc) {
  984. data = _realloc;
  985. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)oldsize);
  986. #if defined(MEMORY_DEBUGGING)
  987. sprintf(mallocStr,
  988. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  989. memory,
  990. (unsigned long)oldsize,
  991. (unsigned long)mstat->totalMemUsed,
  992. (unsigned long)mstat->blockCount,
  993. file,
  994. line);
  995. #if defined(_WIN32)
  996. OutputDebugStringA(mallocStr);
  997. #else
  998. DEBUG_TRACE("%s", mallocStr);
  999. #endif
  1000. #endif
  1001. mg_atomic_add(&mstat->totalMemUsed, (int64_t)newsize);
  1002. #if defined(MEMORY_DEBUGGING)
  1003. sprintf(mallocStr,
  1004. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  1005. memory,
  1006. (unsigned long)newsize,
  1007. (unsigned long)mstat->totalMemUsed,
  1008. (unsigned long)mstat->blockCount,
  1009. file,
  1010. line);
  1011. #if defined(_WIN32)
  1012. OutputDebugStringA(mallocStr);
  1013. #else
  1014. DEBUG_TRACE("%s", mallocStr);
  1015. #endif
  1016. #endif
  1017. *(uintptr_t *)data = newsize;
  1018. data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1019. } else {
  1020. #if defined(MEMORY_DEBUGGING)
  1021. #if defined(_WIN32)
  1022. OutputDebugStringA("MEM: realloc failed\n");
  1023. #else
  1024. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  1025. #endif
  1026. #endif
  1027. return _realloc;
  1028. }
  1029. } else {
  1030. /* Allocate new block */
  1031. data = mg_malloc_ex(newsize, ctx, file, line);
  1032. }
  1033. } else {
  1034. /* Free existing block */
  1035. data = 0;
  1036. mg_free_ex(memory, file, line);
  1037. }
  1038. return data;
  1039. }
  1040. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  1041. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  1042. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  1043. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  1044. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  1045. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  1046. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  1047. #else /* USE_SERVER_STATS */
  1048. static __inline void *
  1049. mg_malloc(size_t a)
  1050. {
  1051. return malloc(a);
  1052. }
  1053. static __inline void *
  1054. mg_calloc(size_t a, size_t b)
  1055. {
  1056. return calloc(a, b);
  1057. }
  1058. static __inline void *
  1059. mg_realloc(void *a, size_t b)
  1060. {
  1061. return realloc(a, b);
  1062. }
  1063. static __inline void
  1064. mg_free(void *a)
  1065. {
  1066. free(a);
  1067. }
  1068. #define mg_malloc_ctx(a, c) mg_malloc(a)
  1069. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  1070. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  1071. #define mg_free_ctx(a, c) mg_free(a)
  1072. #endif /* USE_SERVER_STATS */
  1073. static void mg_vsnprintf(const struct mg_connection *conn,
  1074. int *truncated,
  1075. char *buf,
  1076. size_t buflen,
  1077. const char *fmt,
  1078. va_list ap);
  1079. static void mg_snprintf(const struct mg_connection *conn,
  1080. int *truncated,
  1081. char *buf,
  1082. size_t buflen,
  1083. PRINTF_FORMAT_STRING(const char *fmt),
  1084. ...) PRINTF_ARGS(5, 6);
  1085. /* This following lines are just meant as a reminder to use the mg-functions
  1086. * for memory management */
  1087. #ifdef malloc
  1088. #undef malloc
  1089. #endif
  1090. #ifdef calloc
  1091. #undef calloc
  1092. #endif
  1093. #ifdef realloc
  1094. #undef realloc
  1095. #endif
  1096. #ifdef free
  1097. #undef free
  1098. #endif
  1099. #ifdef snprintf
  1100. #undef snprintf
  1101. #endif
  1102. #ifdef vsnprintf
  1103. #undef vsnprintf
  1104. #endif
  1105. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  1106. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  1107. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  1108. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  1109. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  1110. #ifdef _WIN32 /* vsnprintf must not be used in any system, * \ \ \ \
  1111. * but this define only works well for Windows. */
  1112. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  1113. #endif
  1114. /* mg_init_library counter */
  1115. static int mg_init_library_called = 0;
  1116. #if !defined(NO_SSL)
  1117. static int mg_ssl_initialized = 0;
  1118. #endif
  1119. static pthread_key_t sTlsKey; /* Thread local storage index */
  1120. static int thread_idx_max = 0;
  1121. struct mg_workerTLS {
  1122. int is_master;
  1123. unsigned long thread_idx;
  1124. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1125. HANDLE pthread_cond_helper_mutex;
  1126. struct mg_workerTLS *next_waiting_thread;
  1127. #endif
  1128. };
  1129. #if defined(__GNUC__) || defined(__MINGW32__)
  1130. /* Show no warning in case system functions are not used. */
  1131. #if GCC_VERSION >= 40500
  1132. #pragma GCC diagnostic push
  1133. #pragma GCC diagnostic ignored "-Wunused-function"
  1134. #endif /* GCC_VERSION >= 40500 */
  1135. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  1136. #if defined(__clang__)
  1137. /* Show no warning in case system functions are not used. */
  1138. #pragma clang diagnostic push
  1139. #pragma clang diagnostic ignored "-Wunused-function"
  1140. #endif
  1141. /* Get a unique thread ID as unsigned long, independent from the data type
  1142. * of thread IDs defined by the operating system API.
  1143. * If two calls to mg_current_thread_id return the same value, they calls
  1144. * are done from the same thread. If they return different values, they are
  1145. * done from different threads. (Provided this function is used in the same
  1146. * process context and threads are not repeatedly created and deleted, but
  1147. * CivetWeb does not do that).
  1148. * This function must match the signature required for SSL id callbacks:
  1149. * CRYPTO_set_id_callback
  1150. */
  1151. FUNCTION_MAY_BE_UNUSED
  1152. static unsigned long
  1153. mg_current_thread_id(void)
  1154. {
  1155. #ifdef _WIN32
  1156. return GetCurrentThreadId();
  1157. #else
  1158. #ifdef __clang__
  1159. #pragma clang diagnostic push
  1160. #pragma clang diagnostic ignored "-Wunreachable-code"
  1161. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  1162. * or not, so one of the two conditions will be unreachable by construction.
  1163. * Unfortunately the C standard does not define a way to check this at
  1164. * compile time, since the #if preprocessor conditions can not use the sizeof
  1165. * operator as an argument. */
  1166. #endif
  1167. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  1168. /* This is the problematic case for CRYPTO_set_id_callback:
  1169. * The OS pthread_t can not be cast to unsigned long. */
  1170. struct mg_workerTLS *tls =
  1171. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  1172. if (tls == NULL) {
  1173. /* SSL called from an unknown thread: Create some thread index.
  1174. */
  1175. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  1176. tls->is_master = -2; /* -2 means "3rd party thread" */
  1177. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  1178. pthread_setspecific(sTlsKey, tls);
  1179. }
  1180. return tls->thread_idx;
  1181. } else {
  1182. /* pthread_t may be any data type, so a simple cast to unsigned long
  1183. * can rise a warning/error, depending on the platform.
  1184. * Here memcpy is used as an anything-to-anything cast. */
  1185. unsigned long ret = 0;
  1186. pthread_t t = pthread_self();
  1187. memcpy(&ret, &t, sizeof(pthread_t));
  1188. return ret;
  1189. }
  1190. #ifdef __clang__
  1191. #pragma clang diagnostic pop
  1192. #endif
  1193. #endif
  1194. }
  1195. FUNCTION_MAY_BE_UNUSED
  1196. static uint64_t
  1197. mg_get_current_time_ns(void)
  1198. {
  1199. struct timespec tsnow;
  1200. clock_gettime(CLOCK_REALTIME, &tsnow);
  1201. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  1202. }
  1203. #if defined(__GNUC__)
  1204. /* Show no warning in case system functions are not used. */
  1205. #if GCC_VERSION >= 40500
  1206. #pragma GCC diagnostic pop
  1207. #endif /* GCC_VERSION >= 40500 */
  1208. #endif /* defined(__GNUC__) */
  1209. #if defined(__clang__)
  1210. /* Show no warning in case system functions are not used. */
  1211. #pragma clang diagnostic pop
  1212. #endif
  1213. #if !defined(DEBUG_TRACE)
  1214. #if defined(DEBUG)
  1215. static void DEBUG_TRACE_FUNC(const char *func,
  1216. unsigned line,
  1217. PRINTF_FORMAT_STRING(const char *fmt),
  1218. ...) PRINTF_ARGS(3, 4);
  1219. static void
  1220. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  1221. {
  1222. va_list args;
  1223. uint64_t nsnow;
  1224. static uint64_t nslast;
  1225. struct timespec tsnow;
  1226. /* Get some operating system independent thread id */
  1227. unsigned long thread_id = mg_current_thread_id();
  1228. clock_gettime(CLOCK_REALTIME, &tsnow);
  1229. nsnow = ((uint64_t)tsnow.tv_sec) * ((uint64_t)1000000000)
  1230. + ((uint64_t)tsnow.tv_nsec);
  1231. if (!nslast) {
  1232. nslast = nsnow;
  1233. }
  1234. flockfile(stdout);
  1235. printf("*** %lu.%09lu %12" INT64_FMT " %lu %s:%u: ",
  1236. (unsigned long)tsnow.tv_sec,
  1237. (unsigned long)tsnow.tv_nsec,
  1238. nsnow - nslast,
  1239. thread_id,
  1240. func,
  1241. line);
  1242. va_start(args, fmt);
  1243. vprintf(fmt, args);
  1244. va_end(args);
  1245. putchar('\n');
  1246. fflush(stdout);
  1247. funlockfile(stdout);
  1248. nslast = nsnow;
  1249. }
  1250. #define DEBUG_TRACE(fmt, ...) \
  1251. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  1252. #else
  1253. #define DEBUG_TRACE(fmt, ...) \
  1254. do { \
  1255. } while (0)
  1256. #endif /* DEBUG */
  1257. #endif /* DEBUG_TRACE */
  1258. #define MD5_STATIC static
  1259. #include "md5.inl"
  1260. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1261. #ifdef NO_SOCKLEN_T
  1262. typedef int socklen_t;
  1263. #endif /* NO_SOCKLEN_T */
  1264. #define _DARWIN_UNLIMITED_SELECT
  1265. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1266. #if !defined(MSG_NOSIGNAL)
  1267. #define MSG_NOSIGNAL (0)
  1268. #endif
  1269. #if !defined(SOMAXCONN)
  1270. #define SOMAXCONN (100)
  1271. #endif
  1272. /* Size of the accepted socket queue */
  1273. #if !defined(MGSQLEN)
  1274. #define MGSQLEN (20)
  1275. #endif
  1276. #if defined(NO_SSL)
  1277. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1278. typedef struct SSL_CTX SSL_CTX;
  1279. #else
  1280. #if defined(NO_SSL_DL)
  1281. #include <openssl/ssl.h>
  1282. #include <openssl/err.h>
  1283. #include <openssl/crypto.h>
  1284. #include <openssl/x509.h>
  1285. #include <openssl/pem.h>
  1286. #include <openssl/engine.h>
  1287. #include <openssl/conf.h>
  1288. #include <openssl/dh.h>
  1289. #include <openssl/bn.h>
  1290. #include <openssl/opensslv.h>
  1291. #else
  1292. /* SSL loaded dynamically from DLL.
  1293. * I put the prototypes here to be independent from OpenSSL source
  1294. * installation. */
  1295. typedef struct ssl_st SSL;
  1296. typedef struct ssl_method_st SSL_METHOD;
  1297. typedef struct ssl_ctx_st SSL_CTX;
  1298. typedef struct x509_store_ctx_st X509_STORE_CTX;
  1299. typedef struct x509_name X509_NAME;
  1300. typedef struct asn1_integer ASN1_INTEGER;
  1301. typedef struct bignum BIGNUM;
  1302. typedef struct ossl_init_settings_st OPENSSL_INIT_SETTINGS;
  1303. typedef struct evp_md EVP_MD;
  1304. typedef struct x509 X509;
  1305. #define SSL_CTRL_OPTIONS (32)
  1306. #define SSL_CTRL_CLEAR_OPTIONS (77)
  1307. #define SSL_CTRL_SET_ECDH_AUTO (94)
  1308. #define OPENSSL_INIT_NO_LOAD_SSL_STRINGS 0x00100000L
  1309. #define OPENSSL_INIT_LOAD_SSL_STRINGS 0x00200000L
  1310. #define OPENSSL_INIT_LOAD_CRYPTO_STRINGS 0x00000002L
  1311. #define SSL_VERIFY_NONE (0)
  1312. #define SSL_VERIFY_PEER (1)
  1313. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  1314. #define SSL_VERIFY_CLIENT_ONCE (4)
  1315. #define SSL_OP_ALL ((long)(0x80000BFFUL))
  1316. #define SSL_OP_NO_SSLv2 (0x01000000L)
  1317. #define SSL_OP_NO_SSLv3 (0x02000000L)
  1318. #define SSL_OP_NO_TLSv1 (0x04000000L)
  1319. #define SSL_OP_NO_TLSv1_2 (0x08000000L)
  1320. #define SSL_OP_NO_TLSv1_1 (0x10000000L)
  1321. #define SSL_OP_SINGLE_DH_USE (0x00100000L)
  1322. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000L)
  1323. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000L)
  1324. #define SSL_ERROR_NONE (0)
  1325. #define SSL_ERROR_SSL (1)
  1326. #define SSL_ERROR_WANT_READ (2)
  1327. #define SSL_ERROR_WANT_WRITE (3)
  1328. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  1329. #define SSL_ERROR_SYSCALL (5) /* see errno */
  1330. #define SSL_ERROR_ZERO_RETURN (6)
  1331. #define SSL_ERROR_WANT_CONNECT (7)
  1332. #define SSL_ERROR_WANT_ACCEPT (8)
  1333. struct ssl_func {
  1334. const char *name; /* SSL function name */
  1335. void (*ptr)(void); /* Function pointer */
  1336. };
  1337. #ifdef OPENSSL_API_1_1
  1338. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1339. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1340. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1341. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1342. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1343. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1344. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1345. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  1346. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  1347. #define TLS_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  1348. #define OPENSSL_init_ssl \
  1349. (*(int (*)(uint64_t opts, \
  1350. const OPENSSL_INIT_SETTINGS *settings))ssl_sw[10].ptr)
  1351. #define SSL_CTX_use_PrivateKey_file \
  1352. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1353. #define SSL_CTX_use_certificate_file \
  1354. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1355. #define SSL_CTX_set_default_passwd_cb \
  1356. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1357. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1358. #define SSL_CTX_use_certificate_chain_file \
  1359. (*(int (*)(SSL_CTX *, const char *))ssl_sw[15].ptr)
  1360. #define TLS_client_method (*(SSL_METHOD * (*)(void))ssl_sw[16].ptr)
  1361. #define SSL_pending (*(int (*)(SSL *))ssl_sw[17].ptr)
  1362. #define SSL_CTX_set_verify \
  1363. (*(void (*)(SSL_CTX *, \
  1364. int, \
  1365. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[18].ptr)
  1366. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[19].ptr)
  1367. #define SSL_CTX_load_verify_locations \
  1368. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[20].ptr)
  1369. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[21].ptr)
  1370. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[22].ptr)
  1371. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[23].ptr)
  1372. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[24].ptr)
  1373. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[25].ptr)
  1374. #define SSL_CIPHER_get_name \
  1375. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[26].ptr)
  1376. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[27].ptr)
  1377. #define SSL_CTX_set_session_id_context \
  1378. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[28].ptr)
  1379. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[29].ptr)
  1380. #define SSL_CTX_set_cipher_list \
  1381. (*(int (*)(SSL_CTX *, const char *))ssl_sw[30].ptr)
  1382. #define SSL_CTX_set_options \
  1383. (*(unsigned long (*)(SSL_CTX *, unsigned long))ssl_sw[31].ptr)
  1384. #define SSL_CTX_clear_options(ctx, op) \
  1385. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1386. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1387. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1388. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1389. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1390. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[0].ptr)
  1391. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[1].ptr)
  1392. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[2].ptr)
  1393. #define CONF_modules_unload (*(void (*)(int))crypto_sw[3].ptr)
  1394. #define X509_free (*(void (*)(X509 *))crypto_sw[4].ptr)
  1395. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[5].ptr)
  1396. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[6].ptr)
  1397. #define X509_NAME_oneline \
  1398. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[7].ptr)
  1399. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[8].ptr)
  1400. #define EVP_get_digestbyname \
  1401. (*(const EVP_MD *(*)(const char *))crypto_sw[9].ptr)
  1402. #define EVP_Digest \
  1403. (*(int (*)( \
  1404. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1405. crypto_sw[10].ptr)
  1406. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[11].ptr)
  1407. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[12].ptr)
  1408. #define ASN1_INTEGER_to_BN \
  1409. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn))crypto_sw[13].ptr)
  1410. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[14].ptr)
  1411. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[15].ptr)
  1412. #define OPENSSL_free(a) CRYPTO_free(a)
  1413. /* set_ssl_option() function updates this array.
  1414. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1415. * of respective functions. The macros above (like SSL_connect()) are really
  1416. * just calling these functions indirectly via the pointer. */
  1417. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1418. {"SSL_accept", NULL},
  1419. {"SSL_connect", NULL},
  1420. {"SSL_read", NULL},
  1421. {"SSL_write", NULL},
  1422. {"SSL_get_error", NULL},
  1423. {"SSL_set_fd", NULL},
  1424. {"SSL_new", NULL},
  1425. {"SSL_CTX_new", NULL},
  1426. {"TLS_server_method", NULL},
  1427. {"OPENSSL_init_ssl", NULL},
  1428. {"SSL_CTX_use_PrivateKey_file", NULL},
  1429. {"SSL_CTX_use_certificate_file", NULL},
  1430. {"SSL_CTX_set_default_passwd_cb", NULL},
  1431. {"SSL_CTX_free", NULL},
  1432. {"SSL_CTX_use_certificate_chain_file", NULL},
  1433. {"TLS_client_method", NULL},
  1434. {"SSL_pending", NULL},
  1435. {"SSL_CTX_set_verify", NULL},
  1436. {"SSL_shutdown", NULL},
  1437. {"SSL_CTX_load_verify_locations", NULL},
  1438. {"SSL_CTX_set_default_verify_paths", NULL},
  1439. {"SSL_CTX_set_verify_depth", NULL},
  1440. {"SSL_get_peer_certificate", NULL},
  1441. {"SSL_get_version", NULL},
  1442. {"SSL_get_current_cipher", NULL},
  1443. {"SSL_CIPHER_get_name", NULL},
  1444. {"SSL_CTX_check_private_key", NULL},
  1445. {"SSL_CTX_set_session_id_context", NULL},
  1446. {"SSL_CTX_ctrl", NULL},
  1447. {"SSL_CTX_set_cipher_list", NULL},
  1448. {"SSL_CTX_set_options", NULL},
  1449. {NULL, NULL}};
  1450. /* Similar array as ssl_sw. These functions could be located in different
  1451. * lib. */
  1452. static struct ssl_func crypto_sw[] = {{"ERR_get_error", NULL},
  1453. {"ERR_error_string", NULL},
  1454. {"ERR_remove_state", NULL},
  1455. {"CONF_modules_unload", NULL},
  1456. {"X509_free", NULL},
  1457. {"X509_get_subject_name", NULL},
  1458. {"X509_get_issuer_name", NULL},
  1459. {"X509_NAME_oneline", NULL},
  1460. {"X509_get_serialNumber", NULL},
  1461. {"EVP_get_digestbyname", NULL},
  1462. {"EVP_Digest", NULL},
  1463. {"i2d_X509", NULL},
  1464. {"BN_bn2hex", NULL},
  1465. {"ASN1_INTEGER_to_BN", NULL},
  1466. {"BN_free", NULL},
  1467. {"CRYPTO_free", NULL},
  1468. {NULL, NULL}};
  1469. #else
  1470. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1471. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1472. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1473. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1474. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1475. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1476. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1477. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  1478. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  1479. #define SSLv23_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  1480. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  1481. #define SSL_CTX_use_PrivateKey_file \
  1482. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1483. #define SSL_CTX_use_certificate_file \
  1484. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1485. #define SSL_CTX_set_default_passwd_cb \
  1486. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1487. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1488. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  1489. #define SSL_CTX_use_certificate_chain_file \
  1490. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  1491. #define SSLv23_client_method (*(SSL_METHOD * (*)(void))ssl_sw[17].ptr)
  1492. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  1493. #define SSL_CTX_set_verify \
  1494. (*(void (*)(SSL_CTX *, \
  1495. int, \
  1496. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19].ptr)
  1497. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  1498. #define SSL_CTX_load_verify_locations \
  1499. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  1500. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  1501. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  1502. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[24].ptr)
  1503. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  1504. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[26].ptr)
  1505. #define SSL_CIPHER_get_name \
  1506. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  1507. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  1508. #define SSL_CTX_set_session_id_context \
  1509. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  1510. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  1511. #define SSL_CTX_set_cipher_list \
  1512. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  1513. #define SSL_CTX_set_options(ctx, op) \
  1514. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  1515. #define SSL_CTX_clear_options(ctx, op) \
  1516. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1517. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1518. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1519. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1520. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1521. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  1522. #define CRYPTO_set_locking_callback \
  1523. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  1524. #define CRYPTO_set_id_callback \
  1525. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  1526. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  1527. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  1528. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  1529. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  1530. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  1531. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  1532. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  1533. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  1534. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  1535. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[12].ptr)
  1536. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[13].ptr)
  1537. #define X509_NAME_oneline \
  1538. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  1539. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[15].ptr)
  1540. #define i2c_ASN1_INTEGER \
  1541. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  1542. #define EVP_get_digestbyname \
  1543. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1544. #define EVP_Digest \
  1545. (*(int (*)( \
  1546. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1547. crypto_sw[18].ptr)
  1548. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1549. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[20].ptr)
  1550. #define ASN1_INTEGER_to_BN \
  1551. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn))crypto_sw[21].ptr)
  1552. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[22].ptr)
  1553. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[23].ptr)
  1554. #define OPENSSL_free(a) CRYPTO_free(a)
  1555. /* set_ssl_option() function updates this array.
  1556. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1557. * of respective functions. The macros above (like SSL_connect()) are really
  1558. * just calling these functions indirectly via the pointer. */
  1559. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1560. {"SSL_accept", NULL},
  1561. {"SSL_connect", NULL},
  1562. {"SSL_read", NULL},
  1563. {"SSL_write", NULL},
  1564. {"SSL_get_error", NULL},
  1565. {"SSL_set_fd", NULL},
  1566. {"SSL_new", NULL},
  1567. {"SSL_CTX_new", NULL},
  1568. {"SSLv23_server_method", NULL},
  1569. {"SSL_library_init", NULL},
  1570. {"SSL_CTX_use_PrivateKey_file", NULL},
  1571. {"SSL_CTX_use_certificate_file", NULL},
  1572. {"SSL_CTX_set_default_passwd_cb", NULL},
  1573. {"SSL_CTX_free", NULL},
  1574. {"SSL_load_error_strings", NULL},
  1575. {"SSL_CTX_use_certificate_chain_file", NULL},
  1576. {"SSLv23_client_method", NULL},
  1577. {"SSL_pending", NULL},
  1578. {"SSL_CTX_set_verify", NULL},
  1579. {"SSL_shutdown", NULL},
  1580. {"SSL_CTX_load_verify_locations", NULL},
  1581. {"SSL_CTX_set_default_verify_paths", NULL},
  1582. {"SSL_CTX_set_verify_depth", NULL},
  1583. {"SSL_get_peer_certificate", NULL},
  1584. {"SSL_get_version", NULL},
  1585. {"SSL_get_current_cipher", NULL},
  1586. {"SSL_CIPHER_get_name", NULL},
  1587. {"SSL_CTX_check_private_key", NULL},
  1588. {"SSL_CTX_set_session_id_context", NULL},
  1589. {"SSL_CTX_ctrl", NULL},
  1590. {"SSL_CTX_set_cipher_list", NULL},
  1591. {NULL, NULL}};
  1592. /* Similar array as ssl_sw. These functions could be located in different
  1593. * lib. */
  1594. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  1595. {"CRYPTO_set_locking_callback", NULL},
  1596. {"CRYPTO_set_id_callback", NULL},
  1597. {"ERR_get_error", NULL},
  1598. {"ERR_error_string", NULL},
  1599. {"ERR_remove_state", NULL},
  1600. {"ERR_free_strings", NULL},
  1601. {"ENGINE_cleanup", NULL},
  1602. {"CONF_modules_unload", NULL},
  1603. {"CRYPTO_cleanup_all_ex_data", NULL},
  1604. {"EVP_cleanup", NULL},
  1605. {"X509_free", NULL},
  1606. {"X509_get_subject_name", NULL},
  1607. {"X509_get_issuer_name", NULL},
  1608. {"X509_NAME_oneline", NULL},
  1609. {"X509_get_serialNumber", NULL},
  1610. {"i2c_ASN1_INTEGER", NULL},
  1611. {"EVP_get_digestbyname", NULL},
  1612. {"EVP_Digest", NULL},
  1613. {"i2d_X509", NULL},
  1614. {"BN_bn2hex", NULL},
  1615. {"ASN1_INTEGER_to_BN", NULL},
  1616. {"BN_free", NULL},
  1617. {"CRYPTO_free", NULL},
  1618. {NULL, NULL}};
  1619. #endif /* OPENSSL_API_1_1 */
  1620. #endif /* NO_SSL_DL */
  1621. #endif /* NO_SSL */
  1622. #if !defined(NO_CACHING)
  1623. static const char *month_names[] = {"Jan",
  1624. "Feb",
  1625. "Mar",
  1626. "Apr",
  1627. "May",
  1628. "Jun",
  1629. "Jul",
  1630. "Aug",
  1631. "Sep",
  1632. "Oct",
  1633. "Nov",
  1634. "Dec"};
  1635. #endif /* !NO_CACHING */
  1636. /* Unified socket address. For IPv6 support, add IPv6 address structure in
  1637. * the
  1638. * union u. */
  1639. union usa {
  1640. struct sockaddr sa;
  1641. struct sockaddr_in sin;
  1642. #if defined(USE_IPV6)
  1643. struct sockaddr_in6 sin6;
  1644. #endif
  1645. };
  1646. /* Describes a string (chunk of memory). */
  1647. struct vec {
  1648. const char *ptr;
  1649. size_t len;
  1650. };
  1651. struct mg_file_stat {
  1652. /* File properties filled by mg_stat: */
  1653. uint64_t size;
  1654. time_t last_modified;
  1655. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1656. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1657. * case we need a "Content-Eencoding: gzip" header */
  1658. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1659. };
  1660. struct mg_file_in_memory {
  1661. char *p;
  1662. uint32_t pos;
  1663. char mode;
  1664. };
  1665. struct mg_file_access {
  1666. /* File properties filled by mg_fopen: */
  1667. FILE *fp;
  1668. /* TODO (low): Replace "membuf" implementation by a "file in memory"
  1669. * support library. Use some struct mg_file_in_memory *mf; instead of
  1670. * membuf char pointer. */
  1671. const char *membuf;
  1672. };
  1673. struct mg_file {
  1674. struct mg_file_stat stat;
  1675. struct mg_file_access access;
  1676. };
  1677. #define STRUCT_FILE_INITIALIZER \
  1678. { \
  1679. { \
  1680. (uint64_t)0, (time_t)0, 0, 0, 0 \
  1681. } \
  1682. , \
  1683. { \
  1684. (FILE *) NULL, (const char *)NULL \
  1685. } \
  1686. }
  1687. /* Describes listening socket, or socket which was accept()-ed by the master
  1688. * thread and queued for future handling by the worker thread. */
  1689. struct socket {
  1690. SOCKET sock; /* Listening socket */
  1691. union usa lsa; /* Local socket address */
  1692. union usa rsa; /* Remote socket address */
  1693. unsigned char is_ssl; /* Is port SSL-ed */
  1694. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1695. * port */
  1696. unsigned char in_use; /* Is valid */
  1697. };
  1698. /* NOTE(lsm): this enum shoulds be in sync with the config_options below. */
  1699. enum {
  1700. CGI_EXTENSIONS,
  1701. CGI_ENVIRONMENT,
  1702. PUT_DELETE_PASSWORDS_FILE,
  1703. CGI_INTERPRETER,
  1704. PROTECT_URI,
  1705. AUTHENTICATION_DOMAIN,
  1706. ENABLE_AUTH_DOMAIN_CHECK,
  1707. SSI_EXTENSIONS,
  1708. THROTTLE,
  1709. ACCESS_LOG_FILE,
  1710. ENABLE_DIRECTORY_LISTING,
  1711. ERROR_LOG_FILE,
  1712. GLOBAL_PASSWORDS_FILE,
  1713. INDEX_FILES,
  1714. ENABLE_KEEP_ALIVE,
  1715. ACCESS_CONTROL_LIST,
  1716. EXTRA_MIME_TYPES,
  1717. LISTENING_PORTS,
  1718. DOCUMENT_ROOT,
  1719. SSL_CERTIFICATE,
  1720. SSL_CERTIFICATE_CHAIN,
  1721. NUM_THREADS,
  1722. RUN_AS_USER,
  1723. URL_REWRITE_PATTERN,
  1724. HIDE_FILES,
  1725. REQUEST_TIMEOUT,
  1726. KEEP_ALIVE_TIMEOUT,
  1727. LINGER_TIMEOUT,
  1728. SSL_DO_VERIFY_PEER,
  1729. SSL_CA_PATH,
  1730. SSL_CA_FILE,
  1731. SSL_VERIFY_DEPTH,
  1732. SSL_DEFAULT_VERIFY_PATHS,
  1733. SSL_CIPHER_LIST,
  1734. SSL_PROTOCOL_VERSION,
  1735. SSL_SHORT_TRUST,
  1736. #if defined(USE_WEBSOCKET)
  1737. WEBSOCKET_TIMEOUT,
  1738. #endif
  1739. DECODE_URL,
  1740. #if defined(USE_LUA)
  1741. LUA_PRELOAD_FILE,
  1742. LUA_SCRIPT_EXTENSIONS,
  1743. LUA_SERVER_PAGE_EXTENSIONS,
  1744. #endif
  1745. #if defined(USE_DUKTAPE)
  1746. DUKTAPE_SCRIPT_EXTENSIONS,
  1747. #endif
  1748. #if defined(USE_WEBSOCKET)
  1749. WEBSOCKET_ROOT,
  1750. #endif
  1751. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1752. LUA_WEBSOCKET_EXTENSIONS,
  1753. #endif
  1754. ACCESS_CONTROL_ALLOW_ORIGIN,
  1755. ACCESS_CONTROL_ALLOW_METHODS,
  1756. ACCESS_CONTROL_ALLOW_HEADERS,
  1757. ERROR_PAGES,
  1758. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1759. * socket option typedef TCP_NODELAY. */
  1760. #if !defined(NO_CACHING)
  1761. STATIC_FILE_MAX_AGE,
  1762. #endif
  1763. #if !defined(NO_SSL)
  1764. STRICT_HTTPS_MAX_AGE,
  1765. #endif
  1766. #if defined(__linux__)
  1767. ALLOW_SENDFILE_CALL,
  1768. #endif
  1769. #if defined(_WIN32)
  1770. CASE_SENSITIVE_FILES,
  1771. #endif
  1772. #if defined(USE_LUA)
  1773. LUA_BACKGROUND_SCRIPT,
  1774. #endif
  1775. ADDITIONAL_HEADER,
  1776. MAX_REQUEST_SIZE,
  1777. NUM_OPTIONS
  1778. };
  1779. /* Config option name, config types, default value */
  1780. static struct mg_option config_options[] = {
  1781. {"cgi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1782. {"cgi_environment", CONFIG_TYPE_STRING_LIST, NULL},
  1783. {"put_delete_auth_file", CONFIG_TYPE_FILE, NULL},
  1784. {"cgi_interpreter", CONFIG_TYPE_FILE, NULL},
  1785. {"protect_uri", CONFIG_TYPE_STRING_LIST, NULL},
  1786. {"authentication_domain", CONFIG_TYPE_STRING, "mydomain.com"},
  1787. {"enable_auth_domain_check", CONFIG_TYPE_BOOLEAN, "yes"},
  1788. {"ssi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1789. {"throttle", CONFIG_TYPE_STRING_LIST, NULL},
  1790. {"access_log_file", CONFIG_TYPE_FILE, NULL},
  1791. {"enable_directory_listing", CONFIG_TYPE_BOOLEAN, "yes"},
  1792. {"error_log_file", CONFIG_TYPE_FILE, NULL},
  1793. {"global_auth_file", CONFIG_TYPE_FILE, NULL},
  1794. {"index_files",
  1795. CONFIG_TYPE_STRING_LIST,
  1796. #ifdef USE_LUA
  1797. "index.xhtml,index.html,index.htm,index.lp,index.lsp,index.lua,index."
  1798. "cgi,"
  1799. "index.shtml,index.php"},
  1800. #else
  1801. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1802. #endif
  1803. {"enable_keep_alive", CONFIG_TYPE_BOOLEAN, "no"},
  1804. {"access_control_list", CONFIG_TYPE_STRING_LIST, NULL},
  1805. {"extra_mime_types", CONFIG_TYPE_STRING_LIST, NULL},
  1806. {"listening_ports", CONFIG_TYPE_STRING_LIST, "8080"},
  1807. {"document_root", CONFIG_TYPE_DIRECTORY, NULL},
  1808. {"ssl_certificate", CONFIG_TYPE_FILE, NULL},
  1809. {"ssl_certificate_chain", CONFIG_TYPE_FILE, NULL},
  1810. {"num_threads", CONFIG_TYPE_NUMBER, "50"},
  1811. {"run_as_user", CONFIG_TYPE_STRING, NULL},
  1812. {"url_rewrite_patterns", CONFIG_TYPE_STRING_LIST, NULL},
  1813. {"hide_files_patterns", CONFIG_TYPE_EXT_PATTERN, NULL},
  1814. {"request_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1815. {"keep_alive_timeout_ms", CONFIG_TYPE_NUMBER, "500"},
  1816. {"linger_timeout_ms", CONFIG_TYPE_NUMBER, NULL},
  1817. /* TODO(Feature): this is no longer a boolean, but yes/no/optional */
  1818. {"ssl_verify_peer", CONFIG_TYPE_BOOLEAN, "no"},
  1819. {"ssl_ca_path", CONFIG_TYPE_DIRECTORY, NULL},
  1820. {"ssl_ca_file", CONFIG_TYPE_FILE, NULL},
  1821. {"ssl_verify_depth", CONFIG_TYPE_NUMBER, "9"},
  1822. {"ssl_default_verify_paths", CONFIG_TYPE_BOOLEAN, "yes"},
  1823. {"ssl_cipher_list", CONFIG_TYPE_STRING, NULL},
  1824. {"ssl_protocol_version", CONFIG_TYPE_NUMBER, "0"},
  1825. {"ssl_short_trust", CONFIG_TYPE_BOOLEAN, "no"},
  1826. #if defined(USE_WEBSOCKET)
  1827. {"websocket_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1828. #endif
  1829. {"decode_url", CONFIG_TYPE_BOOLEAN, "yes"},
  1830. #if defined(USE_LUA)
  1831. {"lua_preload_file", CONFIG_TYPE_FILE, NULL},
  1832. {"lua_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1833. {"lua_server_page_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1834. #endif
  1835. #if defined(USE_DUKTAPE)
  1836. /* The support for duktape is still in alpha version state.
  1837. * The name of this config option might change. */
  1838. {"duktape_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1839. #endif
  1840. #if defined(USE_WEBSOCKET)
  1841. {"websocket_root", CONFIG_TYPE_DIRECTORY, NULL},
  1842. #endif
  1843. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1844. {"lua_websocket_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1845. #endif
  1846. {"access_control_allow_origin", CONFIG_TYPE_STRING, "*"},
  1847. {"access_control_allow_methods", CONFIG_TYPE_STRING, "*"},
  1848. {"access_control_allow_headers", CONFIG_TYPE_STRING, "*"},
  1849. {"error_pages", CONFIG_TYPE_DIRECTORY, NULL},
  1850. {"tcp_nodelay", CONFIG_TYPE_NUMBER, "0"},
  1851. #if !defined(NO_CACHING)
  1852. {"static_file_max_age", CONFIG_TYPE_NUMBER, "3600"},
  1853. #endif
  1854. #if !defined(NO_SSL)
  1855. {"strict_transport_security_max_age", CONFIG_TYPE_NUMBER, NULL},
  1856. #endif
  1857. #if defined(__linux__)
  1858. {"allow_sendfile_call", CONFIG_TYPE_BOOLEAN, "yes"},
  1859. #endif
  1860. #if defined(_WIN32)
  1861. {"case_sensitive", CONFIG_TYPE_BOOLEAN, "no"},
  1862. #endif
  1863. #if defined(USE_LUA)
  1864. {"lua_background_script", CONFIG_TYPE_FILE, NULL},
  1865. #endif
  1866. {"additional_header", CONFIG_TYPE_STRING_MULTILINE, NULL},
  1867. {"max_request_size", CONFIG_TYPE_NUMBER, "16384"},
  1868. {NULL, CONFIG_TYPE_UNKNOWN, NULL}};
  1869. /* Check if the config_options and the corresponding enum have compatible
  1870. * sizes. */
  1871. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1872. == (NUM_OPTIONS + 1),
  1873. "config_options and enum not sync");
  1874. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1875. struct mg_handler_info {
  1876. /* Name/Pattern of the URI. */
  1877. char *uri;
  1878. size_t uri_len;
  1879. /* handler type */
  1880. int handler_type;
  1881. /* Handler for http/https or authorization requests. */
  1882. mg_request_handler handler;
  1883. /* Handler for ws/wss (websocket) requests. */
  1884. mg_websocket_connect_handler connect_handler;
  1885. mg_websocket_ready_handler ready_handler;
  1886. mg_websocket_data_handler data_handler;
  1887. mg_websocket_close_handler close_handler;
  1888. /* accepted subprotocols for ws/wss requests. */
  1889. struct mg_websocket_subprotocols *subprotocols;
  1890. /* Handler for authorization requests */
  1891. mg_authorization_handler auth_handler;
  1892. /* User supplied argument for the handler function. */
  1893. void *cbdata;
  1894. /* next handler in a linked list */
  1895. struct mg_handler_info *next;
  1896. };
  1897. struct mg_context {
  1898. volatile int stop_flag; /* Should we stop event loop */
  1899. SSL_CTX *ssl_ctx; /* SSL context */
  1900. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1901. struct mg_callbacks callbacks; /* User-defined callback function */
  1902. void *user_data; /* User-defined data */
  1903. int context_type; /* 1 = server context,
  1904. * 2 = ws/wss client context,
  1905. */
  1906. struct socket *listening_sockets;
  1907. struct pollfd *listening_socket_fds;
  1908. unsigned int num_listening_sockets;
  1909. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  1910. #ifdef ALTERNATIVE_QUEUE
  1911. struct socket *client_socks;
  1912. void **client_wait_events;
  1913. #else
  1914. struct socket queue[MGSQLEN]; /* Accepted sockets */
  1915. volatile int sq_head; /* Head of the socket queue */
  1916. volatile int sq_tail; /* Tail of the socket queue */
  1917. pthread_cond_t sq_full; /* Signaled when socket is produced */
  1918. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  1919. #endif
  1920. unsigned int max_request_size; /* The max request size */
  1921. pthread_t masterthreadid; /* The master thread ID */
  1922. unsigned int
  1923. cfg_worker_threads; /* The number of configured worker threads. */
  1924. pthread_t *worker_threadids; /* The worker thread IDs */
  1925. struct mg_connection *worker_connections; /* The connection struct, pre-
  1926. * allocated for each worker */
  1927. time_t start_time; /* Server start time, used for authentication
  1928. * and for diagnstics. */
  1929. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1930. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  1931. unsigned long nonce_count; /* Used nonces, used for authentication */
  1932. char *systemName; /* What operating system is running */
  1933. /* linked list of uri handlers */
  1934. struct mg_handler_info *handlers;
  1935. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1936. /* linked list of shared lua websockets */
  1937. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1938. #endif
  1939. #if defined(USE_TIMERS)
  1940. struct ttimers *timers;
  1941. #endif
  1942. #if defined(USE_LUA)
  1943. void *lua_background_state;
  1944. #endif
  1945. #if defined(USE_SERVER_STATS)
  1946. int active_connections;
  1947. int max_connections;
  1948. int64_t total_connections;
  1949. int64_t total_requests;
  1950. struct mg_memory_stat ctx_memory;
  1951. #endif
  1952. };
  1953. #if defined(USE_SERVER_STATS)
  1954. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  1955. static struct mg_memory_stat *
  1956. get_memory_stat(struct mg_context *ctx)
  1957. {
  1958. if (ctx) {
  1959. return &(ctx->ctx_memory);
  1960. }
  1961. return &mg_common_memory;
  1962. }
  1963. #endif
  1964. struct mg_connection {
  1965. int connection_type; /* 0 none
  1966. * 1 request (we are server, mg_request_info valid)
  1967. * 2 response (we are client, response_info valid)
  1968. */
  1969. struct mg_request_info request_info;
  1970. struct mg_response_info response_info;
  1971. struct mg_context *ctx;
  1972. SSL *ssl; /* SSL descriptor */
  1973. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  1974. struct socket client; /* Connected client */
  1975. time_t conn_birth_time; /* Time (wall clock) when connection was
  1976. * established */
  1977. struct timespec req_time; /* Time (since system start) when the request
  1978. * was received */
  1979. int64_t num_bytes_sent; /* Total bytes sent to client */
  1980. int64_t content_len; /* Content-Length header value */
  1981. int64_t consumed_content; /* How many bytes of content have been read */
  1982. int is_chunked; /* Transfer-Encoding is chunked: 0=no, 1=yes:
  1983. * data available, 2: all data read */
  1984. size_t chunk_remainder; /* Unread data from the last chunk */
  1985. char *buf; /* Buffer for received data */
  1986. char *path_info; /* PATH_INFO part of the URL */
  1987. int must_close; /* 1 if connection must be closed */
  1988. int in_error_handler; /* 1 if in handler for user defined error
  1989. * pages */
  1990. int handled_requests; /* Number of requests handled by this connection
  1991. */
  1992. int buf_size; /* Buffer size */
  1993. int request_len; /* Size of the request + headers in a buffer */
  1994. int data_len; /* Total size of data in a buffer */
  1995. int status_code; /* HTTP reply status code, e.g. 200 */
  1996. int throttle; /* Throttling, bytes/sec. <= 0 means no
  1997. * throttle */
  1998. time_t last_throttle_time; /* Last time throttled data was sent */
  1999. int64_t last_throttle_bytes; /* Bytes sent this second */
  2000. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2001. * atomic transmissions for websockets */
  2002. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2003. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2004. #endif
  2005. int thread_index; /* Thread index within ctx */
  2006. };
  2007. /* Directory entry */
  2008. struct de {
  2009. struct mg_connection *conn;
  2010. char *file_name;
  2011. struct mg_file_stat file;
  2012. };
  2013. #if defined(USE_WEBSOCKET)
  2014. static int is_websocket_protocol(const struct mg_connection *conn);
  2015. #else
  2016. #define is_websocket_protocol(conn) (0)
  2017. #endif
  2018. #if !defined(NO_THREAD_NAME)
  2019. #if defined(_WIN32) && defined(_MSC_VER)
  2020. /* Set the thread name for debugging purposes in Visual Studio
  2021. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2022. */
  2023. #pragma pack(push, 8)
  2024. typedef struct tagTHREADNAME_INFO {
  2025. DWORD dwType; /* Must be 0x1000. */
  2026. LPCSTR szName; /* Pointer to name (in user addr space). */
  2027. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2028. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2029. } THREADNAME_INFO;
  2030. #pragma pack(pop)
  2031. #elif defined(__linux__)
  2032. #include <sys/prctl.h>
  2033. #include <sys/sendfile.h>
  2034. #ifdef ALTERNATIVE_QUEUE
  2035. #include <sys/eventfd.h>
  2036. #endif /* ALTERNATIVE_QUEUE */
  2037. #if defined(ALTERNATIVE_QUEUE)
  2038. static void *
  2039. event_create(void)
  2040. {
  2041. int ret = eventfd(0, EFD_CLOEXEC);
  2042. if (ret == -1) {
  2043. /* Linux uses -1 on error, Windows NULL. */
  2044. /* However, Linux does not return 0 on success either. */
  2045. return 0;
  2046. }
  2047. return (void *)ret;
  2048. }
  2049. static int
  2050. event_wait(void *eventhdl)
  2051. {
  2052. uint64_t u;
  2053. int s = (int)read((int)eventhdl, &u, sizeof(u));
  2054. if (s != sizeof(uint64_t)) {
  2055. /* error */
  2056. return 0;
  2057. }
  2058. (void)u; /* the value is not required */
  2059. return 1;
  2060. }
  2061. static int
  2062. event_signal(void *eventhdl)
  2063. {
  2064. uint64_t u = 1;
  2065. int s = (int)write((int)eventhdl, &u, sizeof(u));
  2066. if (s != sizeof(uint64_t)) {
  2067. /* error */
  2068. return 0;
  2069. }
  2070. return 1;
  2071. }
  2072. static void
  2073. event_destroy(void *eventhdl)
  2074. {
  2075. close((int)eventhdl);
  2076. }
  2077. #endif
  2078. #endif
  2079. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2080. struct posix_event {
  2081. pthread_mutex_t mutex;
  2082. pthread_cond_t cond;
  2083. };
  2084. static void *
  2085. event_create(void)
  2086. {
  2087. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2088. if (ret == 0) {
  2089. /* out of memory */
  2090. return 0;
  2091. }
  2092. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2093. /* pthread mutex not available */
  2094. mg_free(ret);
  2095. return 0;
  2096. }
  2097. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2098. /* pthread cond not available */
  2099. pthread_mutex_destroy(&(ret->mutex));
  2100. mg_free(ret);
  2101. return 0;
  2102. }
  2103. return (void *)ret;
  2104. }
  2105. static int
  2106. event_wait(void *eventhdl)
  2107. {
  2108. struct posix_event *ev = (struct posix_event *)eventhdl;
  2109. pthread_mutex_lock(&(ev->mutex));
  2110. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2111. pthread_mutex_unlock(&(ev->mutex));
  2112. return 1;
  2113. }
  2114. static int
  2115. event_signal(void *eventhdl)
  2116. {
  2117. struct posix_event *ev = (struct posix_event *)eventhdl;
  2118. pthread_mutex_lock(&(ev->mutex));
  2119. pthread_cond_signal(&(ev->cond));
  2120. pthread_mutex_unlock(&(ev->mutex));
  2121. return 1;
  2122. }
  2123. static void
  2124. event_destroy(void *eventhdl)
  2125. {
  2126. struct posix_event *ev = (struct posix_event *)eventhdl;
  2127. pthread_cond_destroy(&(ev->cond));
  2128. pthread_mutex_destroy(&(ev->mutex));
  2129. mg_free(ev);
  2130. }
  2131. #endif
  2132. static void
  2133. mg_set_thread_name(const char *name)
  2134. {
  2135. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2136. mg_snprintf(
  2137. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2138. #if defined(_WIN32)
  2139. #if defined(_MSC_VER)
  2140. /* Windows and Visual Studio Compiler */
  2141. __try
  2142. {
  2143. THREADNAME_INFO info;
  2144. info.dwType = 0x1000;
  2145. info.szName = threadName;
  2146. info.dwThreadID = ~0U;
  2147. info.dwFlags = 0;
  2148. RaiseException(0x406D1388,
  2149. 0,
  2150. sizeof(info) / sizeof(ULONG_PTR),
  2151. (ULONG_PTR *)&info);
  2152. }
  2153. __except(EXCEPTION_EXECUTE_HANDLER)
  2154. {
  2155. }
  2156. #elif defined(__MINGW32__)
  2157. /* No option known to set thread name for MinGW */
  2158. #endif
  2159. #elif defined(__GLIBC__) \
  2160. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2161. /* pthread_setname_np first appeared in glibc in version 2.12*/
  2162. (void)pthread_setname_np(pthread_self(), threadName);
  2163. #elif defined(__linux__)
  2164. /* on linux we can use the old prctl function */
  2165. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2166. #endif
  2167. }
  2168. #else /* !defined(NO_THREAD_NAME) */
  2169. void
  2170. mg_set_thread_name(const char *threadName)
  2171. {
  2172. }
  2173. #endif
  2174. #if defined(MG_LEGACY_INTERFACE)
  2175. const char **
  2176. mg_get_valid_option_names(void)
  2177. {
  2178. /* This function is deprecated. Use mg_get_valid_options instead. */
  2179. static const char *
  2180. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  2181. int i;
  2182. for (i = 0; config_options[i].name != NULL; i++) {
  2183. data[i * 2] = config_options[i].name;
  2184. data[i * 2 + 1] = config_options[i].default_value;
  2185. }
  2186. return data;
  2187. }
  2188. #endif
  2189. const struct mg_option *
  2190. mg_get_valid_options(void)
  2191. {
  2192. return config_options;
  2193. }
  2194. /* Do not open file (used in is_file_in_memory) */
  2195. #define MG_FOPEN_MODE_NONE (0)
  2196. /* Open file for read only access */
  2197. #define MG_FOPEN_MODE_READ (1)
  2198. /* Open file for writing, create and overwrite */
  2199. #define MG_FOPEN_MODE_WRITE (2)
  2200. /* Open file for writing, create and append */
  2201. #define MG_FOPEN_MODE_APPEND (4)
  2202. /* If a file is in memory, set all "stat" members and the membuf pointer of
  2203. * output filep and return 1, otherwise return 0 and don't modify anything.
  2204. */
  2205. static int
  2206. open_file_in_memory(const struct mg_connection *conn,
  2207. const char *path,
  2208. struct mg_file *filep,
  2209. int mode)
  2210. {
  2211. #if defined(MG_USE_OPEN_FILE)
  2212. size_t size = 0;
  2213. const char *buf = NULL;
  2214. if (!conn) {
  2215. return 0;
  2216. }
  2217. if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
  2218. return 0;
  2219. }
  2220. if (conn->ctx->callbacks.open_file) {
  2221. buf = conn->ctx->callbacks.open_file(conn, path, &size);
  2222. if (buf != NULL) {
  2223. if (filep == NULL) {
  2224. /* This is a file in memory, but we cannot store the
  2225. * properties
  2226. * now.
  2227. * Called from "is_file_in_memory" function. */
  2228. return 1;
  2229. }
  2230. /* NOTE: override filep->size only on success. Otherwise, it
  2231. * might
  2232. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  2233. filep->access.membuf = buf;
  2234. filep->access.fp = NULL;
  2235. /* Size was set by the callback */
  2236. filep->stat.size = size;
  2237. /* Assume the data may change during runtime by setting
  2238. * last_modified = now */
  2239. filep->stat.last_modified = time(NULL);
  2240. filep->stat.is_directory = 0;
  2241. filep->stat.is_gzipped = 0;
  2242. }
  2243. }
  2244. return (buf != NULL);
  2245. #else
  2246. (void)conn;
  2247. (void)path;
  2248. (void)filep;
  2249. (void)mode;
  2250. return 0;
  2251. #endif
  2252. }
  2253. static int
  2254. is_file_in_memory(const struct mg_connection *conn, const char *path)
  2255. {
  2256. return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
  2257. }
  2258. static int
  2259. is_file_opened(const struct mg_file_access *fileacc)
  2260. {
  2261. if (!fileacc) {
  2262. return 0;
  2263. }
  2264. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  2265. }
  2266. static int mg_stat(const struct mg_connection *conn,
  2267. const char *path,
  2268. struct mg_file_stat *filep);
  2269. /* mg_fopen will open a file either in memory or on the disk.
  2270. * The input parameter path is a string in UTF-8 encoding.
  2271. * The input parameter mode is MG_FOPEN_MODE_*
  2272. * On success, either fp or membuf will be set in the output
  2273. * struct file. All status members will also be set.
  2274. * The function returns 1 on success, 0 on error. */
  2275. static int
  2276. mg_fopen(const struct mg_connection *conn,
  2277. const char *path,
  2278. int mode,
  2279. struct mg_file *filep)
  2280. {
  2281. int found;
  2282. if (!filep) {
  2283. return 0;
  2284. }
  2285. filep->access.fp = NULL;
  2286. filep->access.membuf = NULL;
  2287. if (!is_file_in_memory(conn, path)) {
  2288. /* filep is initialized in mg_stat: all fields with memset to,
  2289. * some fields like size and modification date with values */
  2290. found = mg_stat(conn, path, &(filep->stat));
  2291. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2292. /* file does not exist and will not be created */
  2293. return 0;
  2294. }
  2295. #ifdef _WIN32
  2296. {
  2297. wchar_t wbuf[PATH_MAX];
  2298. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2299. switch (mode) {
  2300. case MG_FOPEN_MODE_READ:
  2301. filep->access.fp = _wfopen(wbuf, L"rb");
  2302. break;
  2303. case MG_FOPEN_MODE_WRITE:
  2304. filep->access.fp = _wfopen(wbuf, L"wb");
  2305. break;
  2306. case MG_FOPEN_MODE_APPEND:
  2307. filep->access.fp = _wfopen(wbuf, L"ab");
  2308. break;
  2309. }
  2310. }
  2311. #else
  2312. /* Linux et al already use unicode. No need to convert. */
  2313. switch (mode) {
  2314. case MG_FOPEN_MODE_READ:
  2315. filep->access.fp = fopen(path, "r");
  2316. break;
  2317. case MG_FOPEN_MODE_WRITE:
  2318. filep->access.fp = fopen(path, "w");
  2319. break;
  2320. case MG_FOPEN_MODE_APPEND:
  2321. filep->access.fp = fopen(path, "a");
  2322. break;
  2323. }
  2324. #endif
  2325. if (!found) {
  2326. /* File did not exist before fopen was called.
  2327. * Maybe it has been created now. Get stat info
  2328. * like creation time now. */
  2329. found = mg_stat(conn, path, &(filep->stat));
  2330. (void)found;
  2331. }
  2332. /* file is on disk */
  2333. return (filep->access.fp != NULL);
  2334. } else {
  2335. /* is_file_in_memory returned true */
  2336. if (open_file_in_memory(conn, path, filep, mode)) {
  2337. /* file is in memory */
  2338. return (filep->access.membuf != NULL);
  2339. }
  2340. }
  2341. /* Open failed */
  2342. return 0;
  2343. }
  2344. /* return 0 on success, just like fclose */
  2345. static int
  2346. mg_fclose(struct mg_file_access *fileacc)
  2347. {
  2348. int ret = -1;
  2349. if (fileacc != NULL) {
  2350. if (fileacc->fp != NULL) {
  2351. ret = fclose(fileacc->fp);
  2352. } else if (fileacc->membuf != NULL) {
  2353. ret = 0;
  2354. }
  2355. /* reset all members of fileacc */
  2356. memset(fileacc, 0, sizeof(*fileacc));
  2357. }
  2358. return ret;
  2359. }
  2360. static void
  2361. mg_strlcpy(register char *dst, register const char *src, size_t n)
  2362. {
  2363. for (; *src != '\0' && n > 1; n--) {
  2364. *dst++ = *src++;
  2365. }
  2366. *dst = '\0';
  2367. }
  2368. static int
  2369. lowercase(const char *s)
  2370. {
  2371. return tolower(*(const unsigned char *)s);
  2372. }
  2373. int
  2374. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2375. {
  2376. int diff = 0;
  2377. if (len > 0) {
  2378. do {
  2379. diff = lowercase(s1++) - lowercase(s2++);
  2380. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2381. }
  2382. return diff;
  2383. }
  2384. int
  2385. mg_strcasecmp(const char *s1, const char *s2)
  2386. {
  2387. int diff;
  2388. do {
  2389. diff = lowercase(s1++) - lowercase(s2++);
  2390. } while (diff == 0 && s1[-1] != '\0');
  2391. return diff;
  2392. }
  2393. static char *
  2394. mg_strndup(const char *ptr, size_t len)
  2395. {
  2396. char *p;
  2397. if ((p = (char *)mg_malloc(len + 1)) != NULL) {
  2398. mg_strlcpy(p, ptr, len + 1);
  2399. }
  2400. return p;
  2401. }
  2402. static char *
  2403. mg_strdup(const char *str)
  2404. {
  2405. return mg_strndup(str, strlen(str));
  2406. }
  2407. static const char *
  2408. mg_strcasestr(const char *big_str, const char *small_str)
  2409. {
  2410. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2411. if (big_len >= small_len) {
  2412. for (i = 0; i <= (big_len - small_len); i++) {
  2413. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2414. return big_str + i;
  2415. }
  2416. }
  2417. }
  2418. return NULL;
  2419. }
  2420. /* Return null terminated string of given maximum length.
  2421. * Report errors if length is exceeded. */
  2422. static void
  2423. mg_vsnprintf(const struct mg_connection *conn,
  2424. int *truncated,
  2425. char *buf,
  2426. size_t buflen,
  2427. const char *fmt,
  2428. va_list ap)
  2429. {
  2430. int n, ok;
  2431. if (buflen == 0) {
  2432. if (truncated) {
  2433. *truncated = 1;
  2434. }
  2435. return;
  2436. }
  2437. #ifdef __clang__
  2438. #pragma clang diagnostic push
  2439. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2440. /* Using fmt as a non-literal is intended here, since it is mostly called
  2441. * indirectly by mg_snprintf */
  2442. #endif
  2443. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2444. ok = (n >= 0) && ((size_t)n < buflen);
  2445. #ifdef __clang__
  2446. #pragma clang diagnostic pop
  2447. #endif
  2448. if (ok) {
  2449. if (truncated) {
  2450. *truncated = 0;
  2451. }
  2452. } else {
  2453. if (truncated) {
  2454. *truncated = 1;
  2455. }
  2456. mg_cry(conn,
  2457. "truncating vsnprintf buffer: [%.*s]",
  2458. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2459. buf);
  2460. n = (int)buflen - 1;
  2461. }
  2462. buf[n] = '\0';
  2463. }
  2464. static void
  2465. mg_snprintf(const struct mg_connection *conn,
  2466. int *truncated,
  2467. char *buf,
  2468. size_t buflen,
  2469. const char *fmt,
  2470. ...)
  2471. {
  2472. va_list ap;
  2473. va_start(ap, fmt);
  2474. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2475. va_end(ap);
  2476. }
  2477. static int
  2478. get_option_index(const char *name)
  2479. {
  2480. int i;
  2481. for (i = 0; config_options[i].name != NULL; i++) {
  2482. if (strcmp(config_options[i].name, name) == 0) {
  2483. return i;
  2484. }
  2485. }
  2486. return -1;
  2487. }
  2488. const char *
  2489. mg_get_option(const struct mg_context *ctx, const char *name)
  2490. {
  2491. int i;
  2492. if ((i = get_option_index(name)) == -1) {
  2493. return NULL;
  2494. } else if (!ctx || ctx->config[i] == NULL) {
  2495. return "";
  2496. } else {
  2497. return ctx->config[i];
  2498. }
  2499. }
  2500. struct mg_context *
  2501. mg_get_context(const struct mg_connection *conn)
  2502. {
  2503. return (conn == NULL) ? (struct mg_context *)NULL : (conn->ctx);
  2504. }
  2505. void *
  2506. mg_get_user_data(const struct mg_context *ctx)
  2507. {
  2508. return (ctx == NULL) ? NULL : ctx->user_data;
  2509. }
  2510. void
  2511. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  2512. {
  2513. if (conn != NULL) {
  2514. conn->request_info.conn_data = data;
  2515. }
  2516. }
  2517. void *
  2518. mg_get_user_connection_data(const struct mg_connection *conn)
  2519. {
  2520. if (conn != NULL) {
  2521. return conn->request_info.conn_data;
  2522. }
  2523. return NULL;
  2524. }
  2525. #if defined(MG_LEGACY_INTERFACE)
  2526. /* Deprecated: Use mg_get_server_ports instead. */
  2527. size_t
  2528. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  2529. {
  2530. size_t i;
  2531. if (!ctx) {
  2532. return 0;
  2533. }
  2534. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  2535. ssl[i] = ctx->listening_sockets[i].is_ssl;
  2536. ports[i] =
  2537. #if defined(USE_IPV6)
  2538. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2539. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2540. :
  2541. #endif
  2542. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2543. }
  2544. return i;
  2545. }
  2546. #endif
  2547. int
  2548. mg_get_server_ports(const struct mg_context *ctx,
  2549. int size,
  2550. struct mg_server_ports *ports)
  2551. {
  2552. int i, cnt = 0;
  2553. if (size <= 0) {
  2554. return -1;
  2555. }
  2556. memset(ports, 0, sizeof(*ports) * (size_t)size);
  2557. if (!ctx) {
  2558. return -1;
  2559. }
  2560. if (!ctx->listening_sockets) {
  2561. return -1;
  2562. }
  2563. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  2564. ports[cnt].port =
  2565. #if defined(USE_IPV6)
  2566. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2567. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2568. :
  2569. #endif
  2570. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2571. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  2572. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  2573. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  2574. /* IPv4 */
  2575. ports[cnt].protocol = 1;
  2576. cnt++;
  2577. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  2578. /* IPv6 */
  2579. ports[cnt].protocol = 3;
  2580. cnt++;
  2581. }
  2582. }
  2583. return cnt;
  2584. }
  2585. static void
  2586. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  2587. {
  2588. buf[0] = '\0';
  2589. if (!usa) {
  2590. return;
  2591. }
  2592. if (usa->sa.sa_family == AF_INET) {
  2593. getnameinfo(&usa->sa,
  2594. sizeof(usa->sin),
  2595. buf,
  2596. (unsigned)len,
  2597. NULL,
  2598. 0,
  2599. NI_NUMERICHOST);
  2600. }
  2601. #if defined(USE_IPV6)
  2602. else if (usa->sa.sa_family == AF_INET6) {
  2603. getnameinfo(&usa->sa,
  2604. sizeof(usa->sin6),
  2605. buf,
  2606. (unsigned)len,
  2607. NULL,
  2608. 0,
  2609. NI_NUMERICHOST);
  2610. }
  2611. #endif
  2612. }
  2613. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  2614. * included in all responses other than 100, 101, 5xx. */
  2615. static void
  2616. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  2617. {
  2618. struct tm *tm;
  2619. tm = ((t != NULL) ? gmtime(t) : NULL);
  2620. if (tm != NULL) {
  2621. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  2622. } else {
  2623. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  2624. buf[buf_len - 1] = '\0';
  2625. }
  2626. }
  2627. /* difftime for struct timespec. Return value is in seconds. */
  2628. static double
  2629. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  2630. {
  2631. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  2632. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  2633. }
  2634. /* Print error message to the opened error log stream. */
  2635. void
  2636. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  2637. {
  2638. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  2639. va_list ap;
  2640. struct mg_file fi;
  2641. time_t timestamp;
  2642. va_start(ap, fmt);
  2643. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  2644. va_end(ap);
  2645. buf[sizeof(buf) - 1] = 0;
  2646. if (!conn) {
  2647. puts(buf);
  2648. return;
  2649. }
  2650. /* Do not lock when getting the callback value, here and below.
  2651. * I suppose this is fine, since function cannot disappear in the
  2652. * same way string option can. */
  2653. if ((conn->ctx->callbacks.log_message == NULL)
  2654. || (conn->ctx->callbacks.log_message(conn, buf) == 0)) {
  2655. if (conn->ctx->config[ERROR_LOG_FILE] != NULL) {
  2656. if (mg_fopen(conn,
  2657. conn->ctx->config[ERROR_LOG_FILE],
  2658. MG_FOPEN_MODE_APPEND,
  2659. &fi) == 0) {
  2660. fi.access.fp = NULL;
  2661. }
  2662. } else {
  2663. fi.access.fp = NULL;
  2664. }
  2665. if (fi.access.fp != NULL) {
  2666. flockfile(fi.access.fp);
  2667. timestamp = time(NULL);
  2668. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  2669. fprintf(fi.access.fp,
  2670. "[%010lu] [error] [client %s] ",
  2671. (unsigned long)timestamp,
  2672. src_addr);
  2673. if (conn->request_info.request_method != NULL) {
  2674. fprintf(fi.access.fp,
  2675. "%s %s: ",
  2676. conn->request_info.request_method,
  2677. conn->request_info.request_uri
  2678. ? conn->request_info.request_uri
  2679. : "");
  2680. }
  2681. fprintf(fi.access.fp, "%s", buf);
  2682. fputc('\n', fi.access.fp);
  2683. fflush(fi.access.fp);
  2684. funlockfile(fi.access.fp);
  2685. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  2686. * mg_cry here anyway ;-) */
  2687. }
  2688. }
  2689. }
  2690. /* Return fake connection structure. Used for logging, if connection
  2691. * is not applicable at the moment of logging. */
  2692. static struct mg_connection *
  2693. fc(struct mg_context *ctx)
  2694. {
  2695. static struct mg_connection fake_connection;
  2696. fake_connection.ctx = ctx;
  2697. return &fake_connection;
  2698. }
  2699. const char *
  2700. mg_version(void)
  2701. {
  2702. return CIVETWEB_VERSION;
  2703. }
  2704. const struct mg_request_info *
  2705. mg_get_request_info(const struct mg_connection *conn)
  2706. {
  2707. if (!conn) {
  2708. return NULL;
  2709. }
  2710. #if 1 /* TODO: deal with legacy */
  2711. if (conn->connection_type == 2) {
  2712. static char txt[16];
  2713. sprintf(txt, "%03i", conn->response_info.status_code);
  2714. ((struct mg_connection *)conn)->request_info.local_uri =
  2715. ((struct mg_connection *)conn)->request_info.request_uri =
  2716. txt; /* TODO: not thread safe */
  2717. ((struct mg_connection *)conn)->request_info.num_headers =
  2718. conn->response_info.num_headers;
  2719. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  2720. conn->response_info.http_headers,
  2721. sizeof(conn->response_info.http_headers));
  2722. } else
  2723. #endif
  2724. if (conn->connection_type != 1) {
  2725. return NULL;
  2726. }
  2727. return &conn->request_info;
  2728. }
  2729. const struct mg_response_info *
  2730. mg_get_response_info(const struct mg_connection *conn)
  2731. {
  2732. if (!conn) {
  2733. return NULL;
  2734. }
  2735. if (conn->connection_type != 2) {
  2736. return NULL;
  2737. }
  2738. return &conn->response_info;
  2739. }
  2740. int
  2741. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  2742. {
  2743. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  2744. return -1;
  2745. } else {
  2746. int truncated = 0;
  2747. const struct mg_request_info *ri = &conn->request_info;
  2748. #ifdef __clang__
  2749. #pragma clang diagnostic push
  2750. #pragma clang diagnostic ignored "-Wunreachable-code"
  2751. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  2752. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  2753. * unreachable, but splitting into four different #ifdef clauses here is more
  2754. * complicated.
  2755. */
  2756. #endif
  2757. const char *proto =
  2758. (is_websocket_protocol(conn) ? (ri->is_ssl ? "wss" : "ws")
  2759. : (ri->is_ssl ? "https" : "http"));
  2760. #ifdef __clang__
  2761. #pragma clang diagnostic pop
  2762. #endif
  2763. if (ri->local_uri == NULL) {
  2764. return -1;
  2765. }
  2766. if ((ri->request_uri != NULL)
  2767. && strcmp(ri->local_uri, ri->request_uri)) {
  2768. mg_snprintf(conn,
  2769. &truncated,
  2770. buf,
  2771. buflen,
  2772. "%s://%s",
  2773. proto,
  2774. ri->request_uri);
  2775. if (truncated) {
  2776. return -1;
  2777. }
  2778. return 0;
  2779. } else {
  2780. #if defined(USE_IPV6)
  2781. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  2782. int port = is_ipv6 ? htons(conn->client.lsa.sin6.sin6_port)
  2783. : htons(conn->client.lsa.sin.sin_port);
  2784. #else
  2785. int port = htons(conn->client.lsa.sin.sin_port);
  2786. #endif
  2787. int def_port = ri->is_ssl ? 443 : 80;
  2788. int auth_domain_check_enabled =
  2789. conn->ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  2790. && (!strcmp(conn->ctx->config[ENABLE_AUTH_DOMAIN_CHECK],
  2791. "yes"));
  2792. const char *server_domain =
  2793. conn->ctx->config[AUTHENTICATION_DOMAIN];
  2794. char portstr[16];
  2795. char server_ip[48];
  2796. if (port != def_port) {
  2797. sprintf(portstr, ":%u", (unsigned)port);
  2798. } else {
  2799. portstr[0] = 0;
  2800. }
  2801. if (!auth_domain_check_enabled || !server_domain) {
  2802. sockaddr_to_string(server_ip,
  2803. sizeof(server_ip),
  2804. &conn->client.lsa);
  2805. server_domain = server_ip;
  2806. }
  2807. mg_snprintf(conn,
  2808. &truncated,
  2809. buf,
  2810. buflen,
  2811. "%s://%s%s%s",
  2812. proto,
  2813. server_domain,
  2814. portstr,
  2815. ri->local_uri);
  2816. if (truncated) {
  2817. return -1;
  2818. }
  2819. return 0;
  2820. }
  2821. }
  2822. }
  2823. /* Skip the characters until one of the delimiters characters found.
  2824. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  2825. * Advance pointer to buffer to the next word. Return found 0-terminated
  2826. * word.
  2827. * Delimiters can be quoted with quotechar. */
  2828. static char *
  2829. skip_quoted(char **buf,
  2830. const char *delimiters,
  2831. const char *whitespace,
  2832. char quotechar)
  2833. {
  2834. char *p, *begin_word, *end_word, *end_whitespace;
  2835. begin_word = *buf;
  2836. end_word = begin_word + strcspn(begin_word, delimiters);
  2837. /* Check for quotechar */
  2838. if (end_word > begin_word) {
  2839. p = end_word - 1;
  2840. while (*p == quotechar) {
  2841. /* While the delimiter is quoted, look for the next delimiter.
  2842. */
  2843. /* This happens, e.g., in calls from parse_auth_header,
  2844. * if the user name contains a " character. */
  2845. /* If there is anything beyond end_word, copy it. */
  2846. if (*end_word != '\0') {
  2847. size_t end_off = strcspn(end_word + 1, delimiters);
  2848. memmove(p, end_word, end_off + 1);
  2849. p += end_off; /* p must correspond to end_word - 1 */
  2850. end_word += end_off + 1;
  2851. } else {
  2852. *p = '\0';
  2853. break;
  2854. }
  2855. }
  2856. for (p++; p < end_word; p++) {
  2857. *p = '\0';
  2858. }
  2859. }
  2860. if (*end_word == '\0') {
  2861. *buf = end_word;
  2862. } else {
  2863. #if defined(__GNUC__) || defined(__MINGW32__)
  2864. /* Disable spurious conversion warning for GCC */
  2865. #if GCC_VERSION >= 40500
  2866. #pragma GCC diagnostic push
  2867. #pragma GCC diagnostic ignored "-Wsign-conversion"
  2868. #endif /* GCC_VERSION >= 40500 */
  2869. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  2870. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  2871. #if defined(__GNUC__) || defined(__MINGW32__)
  2872. #if GCC_VERSION >= 40500
  2873. #pragma GCC diagnostic pop
  2874. #endif /* GCC_VERSION >= 40500 */
  2875. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  2876. for (p = end_word; p < end_whitespace; p++) {
  2877. *p = '\0';
  2878. }
  2879. *buf = end_whitespace;
  2880. }
  2881. return begin_word;
  2882. }
  2883. /* Return HTTP header value, or NULL if not found. */
  2884. static const char *
  2885. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  2886. {
  2887. int i;
  2888. for (i = 0; i < num_hdr; i++) {
  2889. if (!mg_strcasecmp(name, hdr[i].name)) {
  2890. return hdr[i].value;
  2891. }
  2892. }
  2893. return NULL;
  2894. }
  2895. #if defined(USE_WEBSOCKET)
  2896. /* Retrieve requested HTTP header multiple values, and return the number of
  2897. * found occurences */
  2898. static int
  2899. get_req_headers(const struct mg_request_info *ri,
  2900. const char *name,
  2901. const char **output,
  2902. int output_max_size)
  2903. {
  2904. int i;
  2905. int cnt = 0;
  2906. if (ri) {
  2907. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  2908. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  2909. output[cnt++] = ri->http_headers[i].value;
  2910. }
  2911. }
  2912. }
  2913. return cnt;
  2914. }
  2915. #endif
  2916. const char *
  2917. mg_get_header(const struct mg_connection *conn, const char *name)
  2918. {
  2919. if (!conn) {
  2920. return NULL;
  2921. }
  2922. if (conn->connection_type == 1) {
  2923. return get_header(conn->request_info.http_headers,
  2924. conn->request_info.num_headers,
  2925. name);
  2926. }
  2927. if (conn->connection_type == 2) {
  2928. return get_header(conn->response_info.http_headers,
  2929. conn->request_info.num_headers,
  2930. name);
  2931. }
  2932. return NULL;
  2933. }
  2934. static const char *
  2935. get_http_version(const struct mg_connection *conn)
  2936. {
  2937. if (!conn) {
  2938. return NULL;
  2939. }
  2940. if (conn->connection_type == 1) {
  2941. return conn->request_info.http_version;
  2942. }
  2943. if (conn->connection_type == 2) {
  2944. return conn->response_info.http_version;
  2945. }
  2946. return NULL;
  2947. }
  2948. /* A helper function for traversing a comma separated list of values.
  2949. * It returns a list pointer shifted to the next value, or NULL if the end
  2950. * of the list found.
  2951. * Value is stored in val vector. If value has form "x=y", then eq_val
  2952. * vector is initialized to point to the "y" part, and val vector length
  2953. * is adjusted to point only to "x". */
  2954. static const char *
  2955. next_option(const char *list, struct vec *val, struct vec *eq_val)
  2956. {
  2957. int end;
  2958. reparse:
  2959. if (val == NULL || list == NULL || *list == '\0') {
  2960. /* End of the list */
  2961. list = NULL;
  2962. } else {
  2963. /* Skip over leading LWS */
  2964. while (*list == ' ' || *list == '\t')
  2965. list++;
  2966. val->ptr = list;
  2967. if ((list = strchr(val->ptr, ',')) != NULL) {
  2968. /* Comma found. Store length and shift the list ptr */
  2969. val->len = ((size_t)(list - val->ptr));
  2970. list++;
  2971. } else {
  2972. /* This value is the last one */
  2973. list = val->ptr + strlen(val->ptr);
  2974. val->len = ((size_t)(list - val->ptr));
  2975. }
  2976. /* Adjust length for trailing LWS */
  2977. end = (int)val->len - 1;
  2978. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  2979. end--;
  2980. val->len = (size_t)(end + 1);
  2981. if (val->len == 0) {
  2982. /* Ignore any empty entries. */
  2983. goto reparse;
  2984. }
  2985. if (eq_val != NULL) {
  2986. /* Value has form "x=y", adjust pointers and lengths
  2987. * so that val points to "x", and eq_val points to "y". */
  2988. eq_val->len = 0;
  2989. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  2990. if (eq_val->ptr != NULL) {
  2991. eq_val->ptr++; /* Skip over '=' character */
  2992. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  2993. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  2994. }
  2995. }
  2996. }
  2997. return list;
  2998. }
  2999. /* A helper function for checking if a comma separated list of values
  3000. * contains
  3001. * the given option (case insensitvely).
  3002. * 'header' can be NULL, in which case false is returned. */
  3003. static int
  3004. header_has_option(const char *header, const char *option)
  3005. {
  3006. struct vec opt_vec;
  3007. struct vec eq_vec;
  3008. /*
  3009. assert(option != NULL);
  3010. assert(option[0] != '\0');
  3011. */
  3012. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3013. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3014. return 1;
  3015. }
  3016. return 0;
  3017. }
  3018. /* Perform case-insensitive match of string against pattern */
  3019. static int
  3020. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  3021. {
  3022. const char *or_str;
  3023. size_t i;
  3024. int j, len, res;
  3025. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  3026. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  3027. return (res > 0) ? res : match_prefix(or_str + 1,
  3028. (size_t)((pattern + pattern_len)
  3029. - (or_str + 1)),
  3030. str);
  3031. }
  3032. for (i = 0, j = 0; (i < pattern_len); i++, j++) {
  3033. if ((pattern[i] == '?') && (str[j] != '\0')) {
  3034. continue;
  3035. } else if (pattern[i] == '$') {
  3036. return (str[j] == '\0') ? j : -1;
  3037. } else if (pattern[i] == '*') {
  3038. i++;
  3039. if (pattern[i] == '*') {
  3040. i++;
  3041. len = (int)strlen(str + j);
  3042. } else {
  3043. len = (int)strcspn(str + j, "/");
  3044. }
  3045. if (i == pattern_len) {
  3046. return j + len;
  3047. }
  3048. do {
  3049. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  3050. } while (res == -1 && len-- > 0);
  3051. return (res == -1) ? -1 : j + res + len;
  3052. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  3053. return -1;
  3054. }
  3055. }
  3056. return j;
  3057. }
  3058. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3059. * This function must tolerate situations when connection info is not
  3060. * set up, for example if request parsing failed. */
  3061. static int
  3062. should_keep_alive(const struct mg_connection *conn)
  3063. {
  3064. const char *http_version;
  3065. const char *header;
  3066. /* First satisfy needs of the server */
  3067. if ((conn == NULL) || conn->must_close) {
  3068. /* Close, if civetweb framework needs to close */
  3069. return 0;
  3070. }
  3071. if (mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3072. /* Close, if keep alive is not enabled */
  3073. return 0;
  3074. }
  3075. /* Check explicit wish of the client */
  3076. header = mg_get_header(conn, "Connection");
  3077. if (header) {
  3078. /* If there is a connection header from the client, obey */
  3079. if (header_has_option(header, "keep-alive")) {
  3080. return 1;
  3081. }
  3082. return 0;
  3083. }
  3084. /* Use default of the standard */
  3085. http_version = get_http_version(conn);
  3086. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3087. /* HTTP 1.1 default is keep alive */
  3088. return 1;
  3089. }
  3090. /* HTTP 1.0 (and earlier) default is to close the connection */
  3091. return 0;
  3092. }
  3093. static int
  3094. should_decode_url(const struct mg_connection *conn)
  3095. {
  3096. if (!conn || !conn->ctx) {
  3097. return 0;
  3098. }
  3099. return (mg_strcasecmp(conn->ctx->config[DECODE_URL], "yes") == 0);
  3100. }
  3101. static const char *
  3102. suggest_connection_header(const struct mg_connection *conn)
  3103. {
  3104. return should_keep_alive(conn) ? "keep-alive" : "close";
  3105. }
  3106. static int
  3107. send_no_cache_header(struct mg_connection *conn)
  3108. {
  3109. /* Send all current and obsolete cache opt-out directives. */
  3110. return mg_printf(conn,
  3111. "Cache-Control: no-cache, no-store, "
  3112. "must-revalidate, private, max-age=0\r\n"
  3113. "Pragma: no-cache\r\n"
  3114. "Expires: 0\r\n");
  3115. }
  3116. static int
  3117. send_static_cache_header(struct mg_connection *conn)
  3118. {
  3119. #if !defined(NO_CACHING)
  3120. /* Read the server config to check how long a file may be cached.
  3121. * The configuration is in seconds. */
  3122. int max_age = atoi(conn->ctx->config[STATIC_FILE_MAX_AGE]);
  3123. if (max_age <= 0) {
  3124. /* 0 means "do not cache". All values <0 are reserved
  3125. * and may be used differently in the future. */
  3126. /* If a file should not be cached, do not only send
  3127. * max-age=0, but also pragmas and Expires headers. */
  3128. return send_no_cache_header(conn);
  3129. }
  3130. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3131. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3132. /* See also https://www.mnot.net/cache_docs/ */
  3133. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3134. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3135. * leap
  3136. * year to 31622400 seconds. For the moment, we just send whatever has
  3137. * been configured, still the behavior for >1 year should be considered
  3138. * as undefined. */
  3139. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  3140. #else /* NO_CACHING */
  3141. return send_no_cache_header(conn);
  3142. #endif /* !NO_CACHING */
  3143. }
  3144. static int
  3145. send_additional_header(struct mg_connection *conn)
  3146. {
  3147. int i = 0;
  3148. const char *header = conn->ctx->config[ADDITIONAL_HEADER];
  3149. #if !defined(NO_SSL)
  3150. if (conn->ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3151. int max_age = atoi(conn->ctx->config[STRICT_HTTPS_MAX_AGE]);
  3152. if (max_age >= 0) {
  3153. i += mg_printf(conn,
  3154. "Strict-Transport-Security: max-age=%u\r\n",
  3155. (unsigned)max_age);
  3156. }
  3157. }
  3158. #endif
  3159. if (header && header[0]) {
  3160. i += mg_printf(conn, "%s\r\n", header);
  3161. }
  3162. return i;
  3163. }
  3164. static void handle_file_based_request(struct mg_connection *conn,
  3165. const char *path,
  3166. struct mg_file *filep);
  3167. const char *
  3168. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3169. {
  3170. /* See IANA HTTP status code assignment:
  3171. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3172. */
  3173. switch (response_code) {
  3174. /* RFC2616 Section 10.1 - Informational 1xx */
  3175. case 100:
  3176. return "Continue"; /* RFC2616 Section 10.1.1 */
  3177. case 101:
  3178. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3179. case 102:
  3180. return "Processing"; /* RFC2518 Section 10.1 */
  3181. /* RFC2616 Section 10.2 - Successful 2xx */
  3182. case 200:
  3183. return "OK"; /* RFC2616 Section 10.2.1 */
  3184. case 201:
  3185. return "Created"; /* RFC2616 Section 10.2.2 */
  3186. case 202:
  3187. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3188. case 203:
  3189. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3190. case 204:
  3191. return "No Content"; /* RFC2616 Section 10.2.5 */
  3192. case 205:
  3193. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3194. case 206:
  3195. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3196. case 207:
  3197. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3198. */
  3199. case 208:
  3200. return "Already Reported"; /* RFC5842 Section 7.1 */
  3201. case 226:
  3202. return "IM used"; /* RFC3229 Section 10.4.1 */
  3203. /* RFC2616 Section 10.3 - Redirection 3xx */
  3204. case 300:
  3205. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3206. case 301:
  3207. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3208. case 302:
  3209. return "Found"; /* RFC2616 Section 10.3.3 */
  3210. case 303:
  3211. return "See Other"; /* RFC2616 Section 10.3.4 */
  3212. case 304:
  3213. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3214. case 305:
  3215. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3216. case 307:
  3217. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3218. case 308:
  3219. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3220. /* RFC2616 Section 10.4 - Client Error 4xx */
  3221. case 400:
  3222. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3223. case 401:
  3224. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3225. case 402:
  3226. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3227. case 403:
  3228. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3229. case 404:
  3230. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3231. case 405:
  3232. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3233. case 406:
  3234. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3235. case 407:
  3236. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3237. case 408:
  3238. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3239. case 409:
  3240. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3241. case 410:
  3242. return "Gone"; /* RFC2616 Section 10.4.11 */
  3243. case 411:
  3244. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3245. case 412:
  3246. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3247. case 413:
  3248. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3249. case 414:
  3250. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3251. case 415:
  3252. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3253. case 416:
  3254. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3255. */
  3256. case 417:
  3257. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3258. case 421:
  3259. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3260. case 422:
  3261. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3262. * Section 11.2 */
  3263. case 423:
  3264. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3265. case 424:
  3266. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3267. * Section 11.4 */
  3268. case 426:
  3269. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3270. case 428:
  3271. return "Precondition Required"; /* RFC 6585, Section 3 */
  3272. case 429:
  3273. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3274. case 431:
  3275. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3276. case 451:
  3277. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3278. * Section 3 */
  3279. /* RFC2616 Section 10.5 - Server Error 5xx */
  3280. case 500:
  3281. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3282. case 501:
  3283. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3284. case 502:
  3285. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3286. case 503:
  3287. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3288. case 504:
  3289. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3290. case 505:
  3291. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3292. case 506:
  3293. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3294. case 507:
  3295. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3296. * Section 11.5 */
  3297. case 508:
  3298. return "Loop Detected"; /* RFC5842 Section 7.1 */
  3299. case 510:
  3300. return "Not Extended"; /* RFC 2774, Section 7 */
  3301. case 511:
  3302. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  3303. /* Other status codes, not shown in the IANA HTTP status code
  3304. * assignment.
  3305. * E.g., "de facto" standards due to common use, ... */
  3306. case 418:
  3307. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  3308. case 419:
  3309. return "Authentication Timeout"; /* common use */
  3310. case 420:
  3311. return "Enhance Your Calm"; /* common use */
  3312. case 440:
  3313. return "Login Timeout"; /* common use */
  3314. case 509:
  3315. return "Bandwidth Limit Exceeded"; /* common use */
  3316. default:
  3317. /* This error code is unknown. This should not happen. */
  3318. if (conn) {
  3319. mg_cry(conn, "Unknown HTTP response code: %u", response_code);
  3320. }
  3321. /* Return at least a category according to RFC 2616 Section 10. */
  3322. if (response_code >= 100 && response_code < 200) {
  3323. /* Unknown informational status code */
  3324. return "Information";
  3325. }
  3326. if (response_code >= 200 && response_code < 300) {
  3327. /* Unknown success code */
  3328. return "Success";
  3329. }
  3330. if (response_code >= 300 && response_code < 400) {
  3331. /* Unknown redirection code */
  3332. return "Redirection";
  3333. }
  3334. if (response_code >= 400 && response_code < 500) {
  3335. /* Unknown request error code */
  3336. return "Client Error";
  3337. }
  3338. if (response_code >= 500 && response_code < 600) {
  3339. /* Unknown server error code */
  3340. return "Server Error";
  3341. }
  3342. /* Response code not even within reasonable range */
  3343. return "";
  3344. }
  3345. }
  3346. void
  3347. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  3348. {
  3349. char buf[MG_BUF_LEN];
  3350. va_list ap;
  3351. int len, i, page_handler_found, scope, truncated, has_body;
  3352. char date[64];
  3353. time_t curtime = time(NULL);
  3354. const char *error_handler = NULL;
  3355. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  3356. const char *error_page_file_ext, *tstr;
  3357. const char *status_text = mg_get_response_code_text(conn, status);
  3358. if (conn == NULL) {
  3359. return;
  3360. }
  3361. conn->status_code = status;
  3362. if (conn->in_error_handler || (conn->ctx->callbacks.http_error == NULL)
  3363. || conn->ctx->callbacks.http_error(conn, status)) {
  3364. if (!conn->in_error_handler) {
  3365. /* Send user defined error pages, if defined */
  3366. error_handler = conn->ctx->config[ERROR_PAGES];
  3367. error_page_file_ext = conn->ctx->config[INDEX_FILES];
  3368. page_handler_found = 0;
  3369. if (error_handler != NULL) {
  3370. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  3371. switch (scope) {
  3372. case 1: /* Handler for specific error, e.g. 404 error */
  3373. mg_snprintf(conn,
  3374. &truncated,
  3375. buf,
  3376. sizeof(buf) - 32,
  3377. "%serror%03u.",
  3378. error_handler,
  3379. status);
  3380. break;
  3381. case 2: /* Handler for error group, e.g., 5xx error
  3382. * handler
  3383. * for all server errors (500-599) */
  3384. mg_snprintf(conn,
  3385. &truncated,
  3386. buf,
  3387. sizeof(buf) - 32,
  3388. "%serror%01uxx.",
  3389. error_handler,
  3390. status / 100);
  3391. break;
  3392. default: /* Handler for all errors */
  3393. mg_snprintf(conn,
  3394. &truncated,
  3395. buf,
  3396. sizeof(buf) - 32,
  3397. "%serror.",
  3398. error_handler);
  3399. break;
  3400. }
  3401. /* String truncation in buf may only occur if
  3402. * error_handler
  3403. * is too long. This string is from the config, not from
  3404. * a
  3405. * client. */
  3406. (void)truncated;
  3407. len = (int)strlen(buf);
  3408. tstr = strchr(error_page_file_ext, '.');
  3409. while (tstr) {
  3410. for (i = 1;
  3411. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  3412. i++)
  3413. buf[len + i - 1] = tstr[i];
  3414. buf[len + i - 1] = 0;
  3415. if (mg_stat(conn, buf, &error_page_file.stat)) {
  3416. page_handler_found = 1;
  3417. break;
  3418. }
  3419. tstr = strchr(tstr + i, '.');
  3420. }
  3421. }
  3422. }
  3423. if (page_handler_found) {
  3424. conn->in_error_handler = 1;
  3425. handle_file_based_request(conn, buf, &error_page_file);
  3426. conn->in_error_handler = 0;
  3427. return;
  3428. }
  3429. }
  3430. /* No custom error page. Send default error page. */
  3431. gmt_time_string(date, sizeof(date), &curtime);
  3432. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3433. has_body = ((status > 199) && (status != 204) && (status != 304));
  3434. conn->must_close = 1;
  3435. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  3436. send_no_cache_header(conn);
  3437. send_additional_header(conn);
  3438. if (has_body) {
  3439. mg_printf(conn,
  3440. "%s",
  3441. "Content-Type: text/plain; charset=utf-8\r\n");
  3442. }
  3443. mg_printf(conn,
  3444. "Date: %s\r\n"
  3445. "Connection: close\r\n\r\n",
  3446. date);
  3447. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3448. if (has_body) {
  3449. mg_printf(conn, "Error %d: %s\n", status, status_text);
  3450. if (fmt != NULL) {
  3451. va_start(ap, fmt);
  3452. mg_vsnprintf(conn, NULL, buf, sizeof(buf), fmt, ap);
  3453. va_end(ap);
  3454. mg_write(conn, buf, strlen(buf));
  3455. DEBUG_TRACE("Error %i - [%s]", status, buf);
  3456. }
  3457. } else {
  3458. /* No body allowed. Close the connection. */
  3459. DEBUG_TRACE("Error %i", status);
  3460. }
  3461. }
  3462. }
  3463. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  3464. /* Create substitutes for POSIX functions in Win32. */
  3465. #if defined(__MINGW32__)
  3466. /* Show no warning in case system functions are not used. */
  3467. #pragma GCC diagnostic push
  3468. #pragma GCC diagnostic ignored "-Wunused-function"
  3469. #endif
  3470. FUNCTION_MAY_BE_UNUSED
  3471. static int
  3472. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  3473. {
  3474. (void)unused;
  3475. *mutex = CreateMutex(NULL, FALSE, NULL);
  3476. return (*mutex == NULL) ? -1 : 0;
  3477. }
  3478. FUNCTION_MAY_BE_UNUSED
  3479. static int
  3480. pthread_mutex_destroy(pthread_mutex_t *mutex)
  3481. {
  3482. return (CloseHandle(*mutex) == 0) ? -1 : 0;
  3483. }
  3484. FUNCTION_MAY_BE_UNUSED
  3485. static int
  3486. pthread_mutex_lock(pthread_mutex_t *mutex)
  3487. {
  3488. return (WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0) ? 0 : -1;
  3489. }
  3490. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  3491. FUNCTION_MAY_BE_UNUSED
  3492. static int
  3493. pthread_mutex_trylock(pthread_mutex_t *mutex)
  3494. {
  3495. switch (WaitForSingleObject(*mutex, 0)) {
  3496. case WAIT_OBJECT_0:
  3497. return 0;
  3498. case WAIT_TIMEOUT:
  3499. return -2; /* EBUSY */
  3500. }
  3501. return -1;
  3502. }
  3503. #endif
  3504. FUNCTION_MAY_BE_UNUSED
  3505. static int
  3506. pthread_mutex_unlock(pthread_mutex_t *mutex)
  3507. {
  3508. return (ReleaseMutex(*mutex) == 0) ? -1 : 0;
  3509. }
  3510. FUNCTION_MAY_BE_UNUSED
  3511. static int
  3512. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  3513. {
  3514. (void)unused;
  3515. InitializeCriticalSection(&cv->threadIdSec);
  3516. cv->waiting_thread = NULL;
  3517. return 0;
  3518. }
  3519. FUNCTION_MAY_BE_UNUSED
  3520. static int
  3521. pthread_cond_timedwait(pthread_cond_t *cv,
  3522. pthread_mutex_t *mutex,
  3523. const struct timespec *abstime)
  3524. {
  3525. struct mg_workerTLS **ptls,
  3526. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3527. int ok;
  3528. int64_t nsnow, nswaitabs, nswaitrel;
  3529. DWORD mswaitrel;
  3530. EnterCriticalSection(&cv->threadIdSec);
  3531. /* Add this thread to cv's waiting list */
  3532. ptls = &cv->waiting_thread;
  3533. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  3534. ;
  3535. tls->next_waiting_thread = NULL;
  3536. *ptls = tls;
  3537. LeaveCriticalSection(&cv->threadIdSec);
  3538. if (abstime) {
  3539. nsnow = mg_get_current_time_ns();
  3540. nswaitabs =
  3541. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  3542. nswaitrel = nswaitabs - nsnow;
  3543. if (nswaitrel < 0) {
  3544. nswaitrel = 0;
  3545. }
  3546. mswaitrel = (DWORD)(nswaitrel / 1000000);
  3547. } else {
  3548. mswaitrel = INFINITE;
  3549. }
  3550. pthread_mutex_unlock(mutex);
  3551. ok = (WAIT_OBJECT_0
  3552. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  3553. if (!ok) {
  3554. ok = 1;
  3555. EnterCriticalSection(&cv->threadIdSec);
  3556. ptls = &cv->waiting_thread;
  3557. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  3558. if (*ptls == tls) {
  3559. *ptls = tls->next_waiting_thread;
  3560. ok = 0;
  3561. break;
  3562. }
  3563. }
  3564. LeaveCriticalSection(&cv->threadIdSec);
  3565. if (ok) {
  3566. WaitForSingleObject(tls->pthread_cond_helper_mutex, INFINITE);
  3567. }
  3568. }
  3569. /* This thread has been removed from cv's waiting list */
  3570. pthread_mutex_lock(mutex);
  3571. return ok ? 0 : -1;
  3572. }
  3573. FUNCTION_MAY_BE_UNUSED
  3574. static int
  3575. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  3576. {
  3577. return pthread_cond_timedwait(cv, mutex, NULL);
  3578. }
  3579. FUNCTION_MAY_BE_UNUSED
  3580. static int
  3581. pthread_cond_signal(pthread_cond_t *cv)
  3582. {
  3583. HANDLE wkup = NULL;
  3584. BOOL ok = FALSE;
  3585. EnterCriticalSection(&cv->threadIdSec);
  3586. if (cv->waiting_thread) {
  3587. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  3588. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  3589. ok = SetEvent(wkup);
  3590. assert(ok);
  3591. }
  3592. LeaveCriticalSection(&cv->threadIdSec);
  3593. return ok ? 0 : 1;
  3594. }
  3595. FUNCTION_MAY_BE_UNUSED
  3596. static int
  3597. pthread_cond_broadcast(pthread_cond_t *cv)
  3598. {
  3599. EnterCriticalSection(&cv->threadIdSec);
  3600. while (cv->waiting_thread) {
  3601. pthread_cond_signal(cv);
  3602. }
  3603. LeaveCriticalSection(&cv->threadIdSec);
  3604. return 0;
  3605. }
  3606. FUNCTION_MAY_BE_UNUSED
  3607. static int
  3608. pthread_cond_destroy(pthread_cond_t *cv)
  3609. {
  3610. EnterCriticalSection(&cv->threadIdSec);
  3611. assert(cv->waiting_thread == NULL);
  3612. LeaveCriticalSection(&cv->threadIdSec);
  3613. DeleteCriticalSection(&cv->threadIdSec);
  3614. return 0;
  3615. }
  3616. #ifdef ALTERNATIVE_QUEUE
  3617. FUNCTION_MAY_BE_UNUSED
  3618. static void *
  3619. event_create(void)
  3620. {
  3621. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  3622. }
  3623. FUNCTION_MAY_BE_UNUSED
  3624. static int
  3625. event_wait(void *eventhdl)
  3626. {
  3627. int res = WaitForSingleObject((HANDLE)eventhdl, INFINITE);
  3628. return (res == WAIT_OBJECT_0);
  3629. }
  3630. FUNCTION_MAY_BE_UNUSED
  3631. static int
  3632. event_signal(void *eventhdl)
  3633. {
  3634. return (int)SetEvent((HANDLE)eventhdl);
  3635. }
  3636. FUNCTION_MAY_BE_UNUSED
  3637. static void
  3638. event_destroy(void *eventhdl)
  3639. {
  3640. CloseHandle((HANDLE)eventhdl);
  3641. }
  3642. #endif
  3643. #if defined(__MINGW32__)
  3644. /* Enable unused function warning again */
  3645. #pragma GCC diagnostic pop
  3646. #endif
  3647. /* For Windows, change all slashes to backslashes in path names. */
  3648. static void
  3649. change_slashes_to_backslashes(char *path)
  3650. {
  3651. int i;
  3652. for (i = 0; path[i] != '\0'; i++) {
  3653. if (path[i] == '/') {
  3654. path[i] = '\\';
  3655. }
  3656. /* remove double backslash (check i > 0 to preserve UNC paths,
  3657. * like \\server\file.txt) */
  3658. if ((path[i] == '\\') && (i > 0)) {
  3659. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  3660. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  3661. }
  3662. }
  3663. }
  3664. }
  3665. static int
  3666. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  3667. {
  3668. int diff;
  3669. do {
  3670. diff = tolower(*s1) - tolower(*s2);
  3671. s1++;
  3672. s2++;
  3673. } while ((diff == 0) && (s1[-1] != '\0'));
  3674. return diff;
  3675. }
  3676. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  3677. * wbuf and wbuf_len is a target buffer and its length. */
  3678. static void
  3679. path_to_unicode(const struct mg_connection *conn,
  3680. const char *path,
  3681. wchar_t *wbuf,
  3682. size_t wbuf_len)
  3683. {
  3684. char buf[PATH_MAX], buf2[PATH_MAX];
  3685. wchar_t wbuf2[MAX_PATH + 1];
  3686. DWORD long_len, err;
  3687. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  3688. mg_strlcpy(buf, path, sizeof(buf));
  3689. change_slashes_to_backslashes(buf);
  3690. /* Convert to Unicode and back. If doubly-converted string does not
  3691. * match the original, something is fishy, reject. */
  3692. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  3693. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  3694. WideCharToMultiByte(
  3695. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  3696. if (strcmp(buf, buf2) != 0) {
  3697. wbuf[0] = L'\0';
  3698. }
  3699. /* Windows file systems are not case sensitive, but you can still use
  3700. * uppercase and lowercase letters (on all modern file systems).
  3701. * The server can check if the URI uses the same upper/lowercase
  3702. * letters an the file system, effectively making Windows servers
  3703. * case sensitive (like Linux servers are). It is still not possible
  3704. * to use two files with the same name in different cases on Windows
  3705. * (like /a and /A) - this would be possible in Linux.
  3706. * As a default, Windows is not case sensitive, but the case sensitive
  3707. * file name check can be activated by an additional configuration. */
  3708. if (conn) {
  3709. if (conn->ctx->config[CASE_SENSITIVE_FILES]
  3710. && !mg_strcasecmp(conn->ctx->config[CASE_SENSITIVE_FILES], "yes")) {
  3711. /* Use case sensitive compare function */
  3712. fcompare = wcscmp;
  3713. }
  3714. }
  3715. (void)conn; /* conn is currently unused */
  3716. #if !defined(_WIN32_WCE)
  3717. /* Only accept a full file path, not a Windows short (8.3) path. */
  3718. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  3719. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  3720. if (long_len == 0) {
  3721. err = GetLastError();
  3722. if (err == ERROR_FILE_NOT_FOUND) {
  3723. /* File does not exist. This is not always a problem here. */
  3724. return;
  3725. }
  3726. }
  3727. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  3728. /* Short name is used. */
  3729. wbuf[0] = L'\0';
  3730. }
  3731. #else
  3732. (void)long_len;
  3733. (void)wbuf2;
  3734. (void)err;
  3735. if (strchr(path, '~')) {
  3736. wbuf[0] = L'\0';
  3737. }
  3738. #endif
  3739. }
  3740. /* Windows happily opens files with some garbage at the end of file name.
  3741. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  3742. * "a.cgi", despite one would expect an error back.
  3743. * This function returns non-0 if path ends with some garbage. */
  3744. static int
  3745. path_cannot_disclose_cgi(const char *path)
  3746. {
  3747. static const char *allowed_last_characters = "_-";
  3748. int last = path[strlen(path) - 1];
  3749. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  3750. }
  3751. static int
  3752. mg_stat(const struct mg_connection *conn,
  3753. const char *path,
  3754. struct mg_file_stat *filep)
  3755. {
  3756. wchar_t wbuf[PATH_MAX];
  3757. WIN32_FILE_ATTRIBUTE_DATA info;
  3758. time_t creation_time;
  3759. if (!filep) {
  3760. return 0;
  3761. }
  3762. memset(filep, 0, sizeof(*filep));
  3763. if (conn && is_file_in_memory(conn, path)) {
  3764. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  3765. * memset */
  3766. /* Quick fix (for 1.9.x): */
  3767. /* mg_stat must fill all fields, also for files in memory */
  3768. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  3769. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  3770. filep->size = tmp_file.stat.size;
  3771. filep->location = 2;
  3772. /* TODO: for 1.10: restructure how files in memory are handled */
  3773. /* The "file in memory" feature is a candidate for deletion.
  3774. * Please join the discussion at
  3775. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  3776. */
  3777. filep->last_modified = time(NULL); /* TODO */
  3778. /* last_modified = now ... assumes the file may change during
  3779. * runtime,
  3780. * so every mg_fopen call may return different data */
  3781. /* last_modified = conn->ctx.start_time;
  3782. * May be used it the data does not change during runtime. This
  3783. * allows
  3784. * browser caching. Since we do not know, we have to assume the file
  3785. * in memory may change. */
  3786. return 1;
  3787. }
  3788. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3789. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  3790. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  3791. filep->last_modified =
  3792. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  3793. info.ftLastWriteTime.dwHighDateTime);
  3794. /* On Windows, the file creation time can be higher than the
  3795. * modification time, e.g. when a file is copied.
  3796. * Since the Last-Modified timestamp is used for caching
  3797. * it should be based on the most recent timestamp. */
  3798. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  3799. info.ftCreationTime.dwHighDateTime);
  3800. if (creation_time > filep->last_modified) {
  3801. filep->last_modified = creation_time;
  3802. }
  3803. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  3804. /* If file name is fishy, reset the file structure and return
  3805. * error.
  3806. * Note it is important to reset, not just return the error, cause
  3807. * functions like is_file_opened() check the struct. */
  3808. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  3809. memset(filep, 0, sizeof(*filep));
  3810. return 0;
  3811. }
  3812. return 1;
  3813. }
  3814. return 0;
  3815. }
  3816. static int
  3817. mg_remove(const struct mg_connection *conn, const char *path)
  3818. {
  3819. wchar_t wbuf[PATH_MAX];
  3820. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3821. return DeleteFileW(wbuf) ? 0 : -1;
  3822. }
  3823. static int
  3824. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  3825. {
  3826. wchar_t wbuf[PATH_MAX];
  3827. (void)mode;
  3828. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3829. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  3830. }
  3831. /* Create substitutes for POSIX functions in Win32. */
  3832. #if defined(__MINGW32__)
  3833. /* Show no warning in case system functions are not used. */
  3834. #pragma GCC diagnostic push
  3835. #pragma GCC diagnostic ignored "-Wunused-function"
  3836. #endif
  3837. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  3838. FUNCTION_MAY_BE_UNUSED
  3839. static DIR *
  3840. mg_opendir(const struct mg_connection *conn, const char *name)
  3841. {
  3842. DIR *dir = NULL;
  3843. wchar_t wpath[PATH_MAX];
  3844. DWORD attrs;
  3845. if (name == NULL) {
  3846. SetLastError(ERROR_BAD_ARGUMENTS);
  3847. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  3848. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  3849. } else {
  3850. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  3851. attrs = GetFileAttributesW(wpath);
  3852. if (attrs != 0xFFFFFFFF && ((attrs & FILE_ATTRIBUTE_DIRECTORY)
  3853. == FILE_ATTRIBUTE_DIRECTORY)) {
  3854. (void)wcscat(wpath, L"\\*");
  3855. dir->handle = FindFirstFileW(wpath, &dir->info);
  3856. dir->result.d_name[0] = '\0';
  3857. } else {
  3858. mg_free(dir);
  3859. dir = NULL;
  3860. }
  3861. }
  3862. return dir;
  3863. }
  3864. FUNCTION_MAY_BE_UNUSED
  3865. static int
  3866. mg_closedir(DIR *dir)
  3867. {
  3868. int result = 0;
  3869. if (dir != NULL) {
  3870. if (dir->handle != INVALID_HANDLE_VALUE)
  3871. result = FindClose(dir->handle) ? 0 : -1;
  3872. mg_free(dir);
  3873. } else {
  3874. result = -1;
  3875. SetLastError(ERROR_BAD_ARGUMENTS);
  3876. }
  3877. return result;
  3878. }
  3879. FUNCTION_MAY_BE_UNUSED
  3880. static struct dirent *
  3881. mg_readdir(DIR *dir)
  3882. {
  3883. struct dirent *result = 0;
  3884. if (dir) {
  3885. if (dir->handle != INVALID_HANDLE_VALUE) {
  3886. result = &dir->result;
  3887. (void)WideCharToMultiByte(CP_UTF8,
  3888. 0,
  3889. dir->info.cFileName,
  3890. -1,
  3891. result->d_name,
  3892. sizeof(result->d_name),
  3893. NULL,
  3894. NULL);
  3895. if (!FindNextFileW(dir->handle, &dir->info)) {
  3896. (void)FindClose(dir->handle);
  3897. dir->handle = INVALID_HANDLE_VALUE;
  3898. }
  3899. } else {
  3900. SetLastError(ERROR_FILE_NOT_FOUND);
  3901. }
  3902. } else {
  3903. SetLastError(ERROR_BAD_ARGUMENTS);
  3904. }
  3905. return result;
  3906. }
  3907. #ifndef HAVE_POLL
  3908. FUNCTION_MAY_BE_UNUSED
  3909. static int
  3910. poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  3911. {
  3912. struct timeval tv;
  3913. fd_set set;
  3914. unsigned int i;
  3915. int result;
  3916. SOCKET maxfd = 0;
  3917. memset(&tv, 0, sizeof(tv));
  3918. tv.tv_sec = milliseconds / 1000;
  3919. tv.tv_usec = (milliseconds % 1000) * 1000;
  3920. FD_ZERO(&set);
  3921. for (i = 0; i < n; i++) {
  3922. FD_SET((SOCKET)pfd[i].fd, &set);
  3923. pfd[i].revents = 0;
  3924. if (pfd[i].fd > maxfd) {
  3925. maxfd = pfd[i].fd;
  3926. }
  3927. }
  3928. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  3929. for (i = 0; i < n; i++) {
  3930. if (FD_ISSET(pfd[i].fd, &set)) {
  3931. pfd[i].revents = POLLIN;
  3932. }
  3933. }
  3934. }
  3935. /* We should subtract the time used in select from remaining
  3936. * "milliseconds", in particular if called from mg_poll with a
  3937. * timeout quantum.
  3938. * Unfortunately, the remaining time is not stored in "tv" in all
  3939. * implementations, so the result in "tv" must be considered undefined.
  3940. * See http://man7.org/linux/man-pages/man2/select.2.html */
  3941. return result;
  3942. }
  3943. #endif /* HAVE_POLL */
  3944. #if defined(__MINGW32__)
  3945. /* Enable unused function warning again */
  3946. #pragma GCC diagnostic pop
  3947. #endif
  3948. static void
  3949. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  3950. {
  3951. (void)conn; /* Unused. */
  3952. #if defined(_WIN32_WCE)
  3953. (void)sock;
  3954. #else
  3955. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  3956. #endif
  3957. }
  3958. int
  3959. mg_start_thread(mg_thread_func_t f, void *p)
  3960. {
  3961. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3962. /* Compile-time option to control stack size, e.g.
  3963. * -DUSE_STACK_SIZE=16384
  3964. */
  3965. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  3966. == ((uintptr_t)(-1L)))
  3967. ? -1
  3968. : 0);
  3969. #else
  3970. return (
  3971. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  3972. ? -1
  3973. : 0);
  3974. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3975. }
  3976. /* Start a thread storing the thread context. */
  3977. static int
  3978. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  3979. void *p,
  3980. pthread_t *threadidptr)
  3981. {
  3982. uintptr_t uip;
  3983. HANDLE threadhandle;
  3984. int result = -1;
  3985. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  3986. threadhandle = (HANDLE)uip;
  3987. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  3988. *threadidptr = threadhandle;
  3989. result = 0;
  3990. }
  3991. return result;
  3992. }
  3993. /* Wait for a thread to finish. */
  3994. static int
  3995. mg_join_thread(pthread_t threadid)
  3996. {
  3997. int result;
  3998. DWORD dwevent;
  3999. result = -1;
  4000. dwevent = WaitForSingleObject(threadid, INFINITE);
  4001. if (dwevent == WAIT_FAILED) {
  4002. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4003. } else {
  4004. if (dwevent == WAIT_OBJECT_0) {
  4005. CloseHandle(threadid);
  4006. result = 0;
  4007. }
  4008. }
  4009. return result;
  4010. }
  4011. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4012. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4013. /* Create substitutes for POSIX functions in Win32. */
  4014. #if defined(__MINGW32__)
  4015. /* Show no warning in case system functions are not used. */
  4016. #pragma GCC diagnostic push
  4017. #pragma GCC diagnostic ignored "-Wunused-function"
  4018. #endif
  4019. FUNCTION_MAY_BE_UNUSED
  4020. static HANDLE
  4021. dlopen(const char *dll_name, int flags)
  4022. {
  4023. wchar_t wbuf[PATH_MAX];
  4024. (void)flags;
  4025. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4026. return LoadLibraryW(wbuf);
  4027. }
  4028. FUNCTION_MAY_BE_UNUSED
  4029. static int
  4030. dlclose(void *handle)
  4031. {
  4032. int result;
  4033. if (FreeLibrary((HMODULE)handle) != 0) {
  4034. result = 0;
  4035. } else {
  4036. result = -1;
  4037. }
  4038. return result;
  4039. }
  4040. #if defined(__MINGW32__)
  4041. /* Enable unused function warning again */
  4042. #pragma GCC diagnostic pop
  4043. #endif
  4044. #endif
  4045. #if !defined(NO_CGI)
  4046. #define SIGKILL (0)
  4047. static int
  4048. kill(pid_t pid, int sig_num)
  4049. {
  4050. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4051. (void)CloseHandle((HANDLE)pid);
  4052. return 0;
  4053. }
  4054. static void
  4055. trim_trailing_whitespaces(char *s)
  4056. {
  4057. char *e = s + strlen(s) - 1;
  4058. while ((e > s) && isspace(*(unsigned char *)e)) {
  4059. *e-- = '\0';
  4060. }
  4061. }
  4062. static pid_t
  4063. spawn_process(struct mg_connection *conn,
  4064. const char *prog,
  4065. char *envblk,
  4066. char *envp[],
  4067. int fdin[2],
  4068. int fdout[2],
  4069. int fderr[2],
  4070. const char *dir)
  4071. {
  4072. HANDLE me;
  4073. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  4074. cmdline[PATH_MAX], buf[PATH_MAX];
  4075. int truncated;
  4076. struct mg_file file = STRUCT_FILE_INITIALIZER;
  4077. STARTUPINFOA si;
  4078. PROCESS_INFORMATION pi = {0};
  4079. (void)envp;
  4080. memset(&si, 0, sizeof(si));
  4081. si.cb = sizeof(si);
  4082. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  4083. si.wShowWindow = SW_HIDE;
  4084. me = GetCurrentProcess();
  4085. DuplicateHandle(me,
  4086. (HANDLE)_get_osfhandle(fdin[0]),
  4087. me,
  4088. &si.hStdInput,
  4089. 0,
  4090. TRUE,
  4091. DUPLICATE_SAME_ACCESS);
  4092. DuplicateHandle(me,
  4093. (HANDLE)_get_osfhandle(fdout[1]),
  4094. me,
  4095. &si.hStdOutput,
  4096. 0,
  4097. TRUE,
  4098. DUPLICATE_SAME_ACCESS);
  4099. DuplicateHandle(me,
  4100. (HANDLE)_get_osfhandle(fderr[1]),
  4101. me,
  4102. &si.hStdError,
  4103. 0,
  4104. TRUE,
  4105. DUPLICATE_SAME_ACCESS);
  4106. /* Mark handles that should not be inherited. See
  4107. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  4108. */
  4109. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  4110. HANDLE_FLAG_INHERIT,
  4111. 0);
  4112. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  4113. HANDLE_FLAG_INHERIT,
  4114. 0);
  4115. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  4116. HANDLE_FLAG_INHERIT,
  4117. 0);
  4118. /* If CGI file is a script, try to read the interpreter line */
  4119. interp = conn->ctx->config[CGI_INTERPRETER];
  4120. if (interp == NULL) {
  4121. buf[0] = buf[1] = '\0';
  4122. /* Read the first line of the script into the buffer */
  4123. mg_snprintf(
  4124. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  4125. if (truncated) {
  4126. pi.hProcess = (pid_t)-1;
  4127. goto spawn_cleanup;
  4128. }
  4129. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  4130. p = (char *)file.access.membuf;
  4131. mg_fgets(buf, sizeof(buf), &file, &p);
  4132. (void)mg_fclose(&file.access); /* ignore error on read only file */
  4133. buf[sizeof(buf) - 1] = '\0';
  4134. }
  4135. if ((buf[0] == '#') && (buf[1] == '!')) {
  4136. trim_trailing_whitespaces(buf + 2);
  4137. } else {
  4138. buf[2] = '\0';
  4139. }
  4140. interp = buf + 2;
  4141. }
  4142. if (interp[0] != '\0') {
  4143. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  4144. interp = full_interp;
  4145. }
  4146. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  4147. if (interp[0] != '\0') {
  4148. mg_snprintf(conn,
  4149. &truncated,
  4150. cmdline,
  4151. sizeof(cmdline),
  4152. "\"%s\" \"%s\\%s\"",
  4153. interp,
  4154. full_dir,
  4155. prog);
  4156. } else {
  4157. mg_snprintf(conn,
  4158. &truncated,
  4159. cmdline,
  4160. sizeof(cmdline),
  4161. "\"%s\\%s\"",
  4162. full_dir,
  4163. prog);
  4164. }
  4165. if (truncated) {
  4166. pi.hProcess = (pid_t)-1;
  4167. goto spawn_cleanup;
  4168. }
  4169. DEBUG_TRACE("Running [%s]", cmdline);
  4170. if (CreateProcessA(NULL,
  4171. cmdline,
  4172. NULL,
  4173. NULL,
  4174. TRUE,
  4175. CREATE_NEW_PROCESS_GROUP,
  4176. envblk,
  4177. NULL,
  4178. &si,
  4179. &pi) == 0) {
  4180. mg_cry(
  4181. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  4182. pi.hProcess = (pid_t)-1;
  4183. /* goto spawn_cleanup; */
  4184. }
  4185. spawn_cleanup:
  4186. (void)CloseHandle(si.hStdOutput);
  4187. (void)CloseHandle(si.hStdError);
  4188. (void)CloseHandle(si.hStdInput);
  4189. if (pi.hThread != NULL) {
  4190. (void)CloseHandle(pi.hThread);
  4191. }
  4192. return (pid_t)pi.hProcess;
  4193. }
  4194. #endif /* !NO_CGI */
  4195. static int
  4196. set_blocking_mode(SOCKET sock, int blocking)
  4197. {
  4198. unsigned long non_blocking = !blocking;
  4199. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4200. }
  4201. #else
  4202. static int
  4203. mg_stat(const struct mg_connection *conn,
  4204. const char *path,
  4205. struct mg_file_stat *filep)
  4206. {
  4207. struct stat st;
  4208. if (!filep) {
  4209. return 0;
  4210. }
  4211. memset(filep, 0, sizeof(*filep));
  4212. if (conn && is_file_in_memory(conn, path)) {
  4213. /* Quick fix (for 1.9.x): */
  4214. /* mg_stat must fill all fields, also for files in memory */
  4215. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4216. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4217. filep->size = tmp_file.stat.size;
  4218. filep->last_modified = time(NULL);
  4219. filep->location = 2;
  4220. /* TODO: for 1.10: restructure how files in memory are handled */
  4221. return 1;
  4222. }
  4223. if (0 == stat(path, &st)) {
  4224. filep->size = (uint64_t)(st.st_size);
  4225. filep->last_modified = st.st_mtime;
  4226. filep->is_directory = S_ISDIR(st.st_mode);
  4227. return 1;
  4228. }
  4229. return 0;
  4230. }
  4231. static void
  4232. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  4233. {
  4234. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  4235. if (conn) {
  4236. mg_cry(conn,
  4237. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  4238. __func__,
  4239. strerror(ERRNO));
  4240. }
  4241. }
  4242. }
  4243. int
  4244. mg_start_thread(mg_thread_func_t func, void *param)
  4245. {
  4246. pthread_t thread_id;
  4247. pthread_attr_t attr;
  4248. int result;
  4249. (void)pthread_attr_init(&attr);
  4250. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  4251. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4252. /* Compile-time option to control stack size,
  4253. * e.g. -DUSE_STACK_SIZE=16384 */
  4254. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4255. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4256. result = pthread_create(&thread_id, &attr, func, param);
  4257. pthread_attr_destroy(&attr);
  4258. return result;
  4259. }
  4260. /* Start a thread storing the thread context. */
  4261. static int
  4262. mg_start_thread_with_id(mg_thread_func_t func,
  4263. void *param,
  4264. pthread_t *threadidptr)
  4265. {
  4266. pthread_t thread_id;
  4267. pthread_attr_t attr;
  4268. int result;
  4269. (void)pthread_attr_init(&attr);
  4270. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4271. /* Compile-time option to control stack size,
  4272. * e.g. -DUSE_STACK_SIZE=16384 */
  4273. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4274. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  4275. result = pthread_create(&thread_id, &attr, func, param);
  4276. pthread_attr_destroy(&attr);
  4277. if ((result == 0) && (threadidptr != NULL)) {
  4278. *threadidptr = thread_id;
  4279. }
  4280. return result;
  4281. }
  4282. /* Wait for a thread to finish. */
  4283. static int
  4284. mg_join_thread(pthread_t threadid)
  4285. {
  4286. int result;
  4287. result = pthread_join(threadid, NULL);
  4288. return result;
  4289. }
  4290. #ifndef NO_CGI
  4291. static pid_t
  4292. spawn_process(struct mg_connection *conn,
  4293. const char *prog,
  4294. char *envblk,
  4295. char *envp[],
  4296. int fdin[2],
  4297. int fdout[2],
  4298. int fderr[2],
  4299. const char *dir)
  4300. {
  4301. pid_t pid;
  4302. const char *interp;
  4303. (void)envblk;
  4304. if (conn == NULL) {
  4305. return 0;
  4306. }
  4307. if ((pid = fork()) == -1) {
  4308. /* Parent */
  4309. mg_send_http_error(conn,
  4310. 500,
  4311. "Error: Creating CGI process\nfork(): %s",
  4312. strerror(ERRNO));
  4313. } else if (pid == 0) {
  4314. /* Child */
  4315. if (chdir(dir) != 0) {
  4316. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  4317. } else if (dup2(fdin[0], 0) == -1) {
  4318. mg_cry(conn,
  4319. "%s: dup2(%d, 0): %s",
  4320. __func__,
  4321. fdin[0],
  4322. strerror(ERRNO));
  4323. } else if (dup2(fdout[1], 1) == -1) {
  4324. mg_cry(conn,
  4325. "%s: dup2(%d, 1): %s",
  4326. __func__,
  4327. fdout[1],
  4328. strerror(ERRNO));
  4329. } else if (dup2(fderr[1], 2) == -1) {
  4330. mg_cry(conn,
  4331. "%s: dup2(%d, 2): %s",
  4332. __func__,
  4333. fderr[1],
  4334. strerror(ERRNO));
  4335. } else {
  4336. /* Keep stderr and stdout in two different pipes.
  4337. * Stdout will be sent back to the client,
  4338. * stderr should go into a server error log. */
  4339. (void)close(fdin[0]);
  4340. (void)close(fdout[1]);
  4341. (void)close(fderr[1]);
  4342. /* Close write end fdin and read end fdout and fderr */
  4343. (void)close(fdin[1]);
  4344. (void)close(fdout[0]);
  4345. (void)close(fderr[0]);
  4346. /* After exec, all signal handlers are restored to their default
  4347. * values, with one exception of SIGCHLD. According to
  4348. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler will
  4349. * leave unchanged after exec if it was set to be ignored. Restore
  4350. * it to default action. */
  4351. signal(SIGCHLD, SIG_DFL);
  4352. interp = conn->ctx->config[CGI_INTERPRETER];
  4353. if (interp == NULL) {
  4354. (void)execle(prog, prog, NULL, envp);
  4355. mg_cry(conn,
  4356. "%s: execle(%s): %s",
  4357. __func__,
  4358. prog,
  4359. strerror(ERRNO));
  4360. } else {
  4361. (void)execle(interp, interp, prog, NULL, envp);
  4362. mg_cry(conn,
  4363. "%s: execle(%s %s): %s",
  4364. __func__,
  4365. interp,
  4366. prog,
  4367. strerror(ERRNO));
  4368. }
  4369. }
  4370. exit(EXIT_FAILURE);
  4371. }
  4372. return pid;
  4373. }
  4374. #endif /* !NO_CGI */
  4375. static int
  4376. set_blocking_mode(SOCKET sock, int blocking)
  4377. {
  4378. int flags;
  4379. flags = fcntl(sock, F_GETFL, 0);
  4380. if (blocking) {
  4381. (void)fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  4382. } else {
  4383. (void)fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK)));
  4384. }
  4385. return 0;
  4386. }
  4387. #endif /* _WIN32 */
  4388. /* End of initial operating system specific define block. */
  4389. /* Get a random number (independent of C rand function) */
  4390. static uint64_t
  4391. get_random(void)
  4392. {
  4393. static uint64_t lfsr = 0; /* Linear feedback shift register */
  4394. static uint64_t lcg = 0; /* Linear congruential generator */
  4395. uint64_t now = mg_get_current_time_ns();
  4396. if (lfsr == 0) {
  4397. /* lfsr will be only 0 if has not been initialized,
  4398. * so this code is called only once. */
  4399. lfsr = mg_get_current_time_ns();
  4400. lcg = mg_get_current_time_ns();
  4401. } else {
  4402. /* Get the next step of both random number generators. */
  4403. lfsr = (lfsr >> 1)
  4404. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  4405. << 63);
  4406. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  4407. }
  4408. /* Combining two pseudo-random number generators and a high resolution
  4409. * part
  4410. * of the current server time will make it hard (impossible?) to guess
  4411. * the
  4412. * next number. */
  4413. return (lfsr ^ lcg ^ now);
  4414. }
  4415. static int
  4416. mg_poll(struct pollfd *pfd,
  4417. unsigned int n,
  4418. int milliseconds,
  4419. volatile int *stop_server)
  4420. {
  4421. int ms_now, result;
  4422. /* Call poll, but only for a maximum time of a few seconds.
  4423. * This will allow to stop the server after some seconds, instead
  4424. * of having to wait for a long socket timeout. */
  4425. ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  4426. do {
  4427. if (*stop_server) {
  4428. /* Shut down signal */
  4429. return -2;
  4430. }
  4431. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  4432. ms_now = milliseconds;
  4433. }
  4434. result = poll(pfd, n, ms_now);
  4435. if (result != 0) {
  4436. /* Poll returned either success (1) or error (-1).
  4437. * Forward both to the caller. */
  4438. return result;
  4439. }
  4440. /* Poll returned timeout (0). */
  4441. if (milliseconds > 0) {
  4442. milliseconds -= ms_now;
  4443. }
  4444. } while (milliseconds != 0);
  4445. return result;
  4446. }
  4447. /* Write data to the IO channel - opened file descriptor, socket or SSL
  4448. * descriptor.
  4449. * Return value:
  4450. * >=0 .. number of bytes successfully written
  4451. * -1 .. timeout
  4452. * -2 .. error
  4453. */
  4454. static int
  4455. push_inner(struct mg_context *ctx,
  4456. FILE *fp,
  4457. SOCKET sock,
  4458. SSL *ssl,
  4459. const char *buf,
  4460. int len,
  4461. double timeout)
  4462. {
  4463. uint64_t start = 0, now = 0, timeout_ns = 0;
  4464. int n, err;
  4465. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  4466. #ifdef _WIN32
  4467. typedef int len_t;
  4468. #else
  4469. typedef size_t len_t;
  4470. #endif
  4471. if (timeout > 0) {
  4472. now = mg_get_current_time_ns();
  4473. start = now;
  4474. timeout_ns = (uint64_t)(timeout * 1.0E9);
  4475. }
  4476. if (ctx == NULL) {
  4477. return -2;
  4478. }
  4479. #ifdef NO_SSL
  4480. if (ssl) {
  4481. return -2;
  4482. }
  4483. #endif
  4484. /* Try to read until it succeeds, fails, times out, or the server
  4485. * shuts down. */
  4486. for (;;) {
  4487. #ifndef NO_SSL
  4488. if (ssl != NULL) {
  4489. n = SSL_write(ssl, buf, len);
  4490. if (n <= 0) {
  4491. err = SSL_get_error(ssl, n);
  4492. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  4493. err = ERRNO;
  4494. } else if ((err == SSL_ERROR_WANT_READ)
  4495. || (err == SSL_ERROR_WANT_WRITE)) {
  4496. n = 0;
  4497. } else {
  4498. DEBUG_TRACE("SSL_write() failed, error %d", err);
  4499. return -2;
  4500. }
  4501. } else {
  4502. err = 0;
  4503. }
  4504. } else
  4505. #endif
  4506. if (fp != NULL) {
  4507. n = (int)fwrite(buf, 1, (size_t)len, fp);
  4508. if (ferror(fp)) {
  4509. n = -1;
  4510. err = ERRNO;
  4511. } else {
  4512. err = 0;
  4513. }
  4514. } else {
  4515. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  4516. err = (n < 0) ? ERRNO : 0;
  4517. #ifdef _WIN32
  4518. if (err == WSAEWOULDBLOCK) {
  4519. err = 0;
  4520. n = 0;
  4521. }
  4522. #else
  4523. if (err == EWOULDBLOCK) {
  4524. err = 0;
  4525. n = 0;
  4526. }
  4527. #endif
  4528. if (n < 0) {
  4529. /* shutdown of the socket at client side */
  4530. return -2;
  4531. }
  4532. }
  4533. if (ctx->stop_flag) {
  4534. return -2;
  4535. }
  4536. if ((n > 0) || ((n == 0) && (len == 0))) {
  4537. /* some data has been read, or no data was requested */
  4538. return n;
  4539. }
  4540. if (n < 0) {
  4541. /* socket error - check errno */
  4542. DEBUG_TRACE("send() failed, error %d", err);
  4543. /* TODO (mid): error handling depending on the error code.
  4544. * These codes are different between Windows and Linux.
  4545. * Currently there is no problem with failing send calls,
  4546. * if there is a reproducible situation, it should be
  4547. * investigated in detail.
  4548. */
  4549. return -2;
  4550. }
  4551. /* Only in case n=0 (timeout), repeat calling the write function */
  4552. /* If send failed, wait before retry */
  4553. if (fp != NULL) {
  4554. /* For files, just wait a fixed time,
  4555. * maybe an average disk seek time. */
  4556. mg_sleep(ms_wait > 10 ? 10 : ms_wait);
  4557. } else {
  4558. /* For sockets, wait for the socket using select */
  4559. fd_set wfds;
  4560. struct timeval tv;
  4561. int sret;
  4562. #if defined(__GNUC__) || defined(__MINGW32__)
  4563. /* GCC seems to have a flaw with it's own socket macros:
  4564. * http://www.linuxquestions.org/questions/programming-9/impossible-to-use-gcc-with-wconversion-and-standard-socket-macros-841935/
  4565. */
  4566. #pragma GCC diagnostic push
  4567. #pragma GCC diagnostic ignored "-Wsign-conversion"
  4568. #endif
  4569. FD_ZERO(&wfds);
  4570. FD_SET(sock, &wfds);
  4571. tv.tv_sec = (time_t)(ms_wait / 1000);
  4572. tv.tv_usec = (long)((ms_wait % 1000) * 1000);
  4573. sret = select((int)sock + 1, NULL, &wfds, NULL, &tv);
  4574. #if defined(__GNUC__) || defined(__MINGW32__)
  4575. #pragma GCC diagnostic pop
  4576. #endif
  4577. if (sret > 0) {
  4578. /* We got ready to write. Don't check the timeout
  4579. * but directly go back to write again. */
  4580. continue;
  4581. }
  4582. }
  4583. if (timeout > 0) {
  4584. now = mg_get_current_time_ns();
  4585. if ((now - start) > timeout_ns) {
  4586. /* Timeout */
  4587. break;
  4588. }
  4589. }
  4590. }
  4591. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  4592. used */
  4593. return -1;
  4594. }
  4595. static int64_t
  4596. push_all(struct mg_context *ctx,
  4597. FILE *fp,
  4598. SOCKET sock,
  4599. SSL *ssl,
  4600. const char *buf,
  4601. int64_t len)
  4602. {
  4603. double timeout = -1.0;
  4604. int64_t n, nwritten = 0;
  4605. if (ctx == NULL) {
  4606. return -1;
  4607. }
  4608. if (ctx->config[REQUEST_TIMEOUT]) {
  4609. timeout = atoi(ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  4610. }
  4611. while ((len > 0) && (ctx->stop_flag == 0)) {
  4612. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  4613. if (n < 0) {
  4614. if (nwritten == 0) {
  4615. nwritten = n; /* Propagate the error */
  4616. }
  4617. break;
  4618. } else if (n == 0) {
  4619. break; /* No more data to write */
  4620. } else {
  4621. nwritten += n;
  4622. len -= n;
  4623. }
  4624. }
  4625. return nwritten;
  4626. }
  4627. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  4628. * Return value:
  4629. * >=0 .. number of bytes successfully read
  4630. * -1 .. timeout
  4631. * -2 .. error
  4632. */
  4633. static int
  4634. pull_inner(FILE *fp,
  4635. struct mg_connection *conn,
  4636. char *buf,
  4637. int len,
  4638. double timeout)
  4639. {
  4640. int nread, err = 0;
  4641. #ifdef _WIN32
  4642. typedef int len_t;
  4643. #else
  4644. typedef size_t len_t;
  4645. #endif
  4646. #ifndef NO_SSL
  4647. int ssl_pending;
  4648. #endif
  4649. /* We need an additional wait loop around this, because in some cases
  4650. * with TLSwe may get data from the socket but not from SSL_read.
  4651. * In this case we need to repeat at least once.
  4652. */
  4653. if (fp != NULL) {
  4654. #if !defined(_WIN32_WCE)
  4655. /* Use read() instead of fread(), because if we're reading from the
  4656. * CGI pipe, fread() may block until IO buffer is filled up. We
  4657. * cannot afford to block and must pass all read bytes immediately
  4658. * to the client. */
  4659. nread = (int)read(fileno(fp), buf, (size_t)len);
  4660. #else
  4661. /* WinCE does not support CGI pipes */
  4662. nread = (int)fread(buf, 1, (size_t)len, fp);
  4663. #endif
  4664. err = (nread < 0) ? ERRNO : 0;
  4665. #ifndef NO_SSL
  4666. } else if ((conn->ssl != NULL)
  4667. && ((ssl_pending = SSL_pending(conn->ssl)) > 0)) {
  4668. /* We already know there is no more data buffered in conn->buf
  4669. * but there is more available in the SSL layer. So don't poll
  4670. * conn->client.sock yet. */
  4671. if (ssl_pending > len) {
  4672. ssl_pending = len;
  4673. }
  4674. nread = SSL_read(conn->ssl, buf, ssl_pending);
  4675. if (nread <= 0) {
  4676. err = SSL_get_error(conn->ssl, nread);
  4677. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  4678. err = ERRNO;
  4679. } else if ((err == SSL_ERROR_WANT_READ)
  4680. || (err == SSL_ERROR_WANT_WRITE)) {
  4681. nread = 0;
  4682. } else {
  4683. DEBUG_TRACE("SSL_read() failed, error %d", err);
  4684. return -1;
  4685. }
  4686. } else {
  4687. err = 0;
  4688. }
  4689. } else if (conn->ssl != NULL) {
  4690. struct pollfd pfd[1];
  4691. int pollres;
  4692. pfd[0].fd = conn->client.sock;
  4693. pfd[0].events = POLLIN;
  4694. pollres =
  4695. mg_poll(pfd, 1, (int)(timeout * 1000.0), &(conn->ctx->stop_flag));
  4696. if (conn->ctx->stop_flag) {
  4697. return -2;
  4698. }
  4699. if (pollres > 0) {
  4700. nread = SSL_read(conn->ssl, buf, len);
  4701. if (nread <= 0) {
  4702. err = SSL_get_error(conn->ssl, nread);
  4703. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  4704. err = ERRNO;
  4705. } else if ((err == SSL_ERROR_WANT_READ)
  4706. || (err == SSL_ERROR_WANT_WRITE)) {
  4707. nread = 0;
  4708. } else {
  4709. DEBUG_TRACE("SSL_read() failed, error %d", err);
  4710. return -2;
  4711. }
  4712. } else {
  4713. err = 0;
  4714. }
  4715. } else if (pollres < 0) {
  4716. /* Error */
  4717. return -2;
  4718. } else {
  4719. /* pollres = 0 means timeout */
  4720. nread = 0;
  4721. }
  4722. #endif
  4723. } else {
  4724. struct pollfd pfd[1];
  4725. int pollres;
  4726. pfd[0].fd = conn->client.sock;
  4727. pfd[0].events = POLLIN;
  4728. pollres =
  4729. mg_poll(pfd, 1, (int)(timeout * 1000.0), &(conn->ctx->stop_flag));
  4730. if (conn->ctx->stop_flag) {
  4731. return -2;
  4732. }
  4733. if (pollres > 0) {
  4734. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  4735. err = (nread < 0) ? ERRNO : 0;
  4736. if (nread <= 0) {
  4737. /* shutdown of the socket at client side */
  4738. return -2;
  4739. }
  4740. } else if (pollres < 0) {
  4741. /* error callint poll */
  4742. return -2;
  4743. } else {
  4744. /* pollres = 0 means timeout */
  4745. nread = 0;
  4746. }
  4747. }
  4748. if (conn->ctx->stop_flag) {
  4749. return -2;
  4750. }
  4751. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  4752. /* some data has been read, or no data was requested */
  4753. return nread;
  4754. }
  4755. if (nread < 0) {
  4756. /* socket error - check errno */
  4757. #ifdef _WIN32
  4758. if (err == WSAEWOULDBLOCK) {
  4759. /* TODO (low): check if this is still required */
  4760. /* standard case if called from close_socket_gracefully */
  4761. return -2;
  4762. } else if (err == WSAETIMEDOUT) {
  4763. /* TODO (low): check if this is still required */
  4764. /* timeout is handled by the while loop */
  4765. return 0;
  4766. } else if (err == WSAECONNABORTED) {
  4767. /* See https://www.chilkatsoft.com/p/p_299.asp */
  4768. return -2;
  4769. } else {
  4770. DEBUG_TRACE("recv() failed, error %d", err);
  4771. return -2;
  4772. }
  4773. #else
  4774. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  4775. * if the timeout is reached and if the socket was set to non-
  4776. * blocking in close_socket_gracefully, so we can not distinguish
  4777. * here. We have to wait for the timeout in both cases for now.
  4778. */
  4779. if ((err == EAGAIN) || (err == EWOULDBLOCK) || (err == EINTR)) {
  4780. /* TODO (low): check if this is still required */
  4781. /* EAGAIN/EWOULDBLOCK:
  4782. * standard case if called from close_socket_gracefully
  4783. * => should return -1 */
  4784. /* or timeout occured
  4785. * => the code must stay in the while loop */
  4786. /* EINTR can be generated on a socket with a timeout set even
  4787. * when SA_RESTART is effective for all relevant signals
  4788. * (see signal(7)).
  4789. * => stay in the while loop */
  4790. } else {
  4791. DEBUG_TRACE("recv() failed, error %d", err);
  4792. return -2;
  4793. }
  4794. #endif
  4795. }
  4796. /* Timeout occured, but no data available. */
  4797. return -1;
  4798. }
  4799. static int
  4800. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  4801. {
  4802. int n, nread = 0;
  4803. double timeout = -1.0;
  4804. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  4805. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  4806. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  4807. }
  4808. if (timeout >= 0.0) {
  4809. start_time = mg_get_current_time_ns();
  4810. timeout_ns = (uint64_t)(timeout * 1.0E9);
  4811. }
  4812. while ((len > 0) && (conn->ctx->stop_flag == 0)) {
  4813. n = pull_inner(fp, conn, buf + nread, len, timeout);
  4814. if (n == -2) {
  4815. if (nread == 0) {
  4816. nread = -1; /* Propagate the error */
  4817. }
  4818. break;
  4819. } else if (n == -1) {
  4820. /* timeout */
  4821. if (timeout >= 0.0) {
  4822. now = mg_get_current_time_ns();
  4823. if ((now - start_time) <= timeout_ns) {
  4824. continue;
  4825. }
  4826. }
  4827. break;
  4828. } else if (n == 0) {
  4829. break; /* No more data to read */
  4830. } else {
  4831. conn->consumed_content += n;
  4832. nread += n;
  4833. len -= n;
  4834. }
  4835. }
  4836. return nread;
  4837. }
  4838. static void
  4839. discard_unread_request_data(struct mg_connection *conn)
  4840. {
  4841. char buf[MG_BUF_LEN];
  4842. size_t to_read;
  4843. int nread;
  4844. if (conn == NULL) {
  4845. return;
  4846. }
  4847. to_read = sizeof(buf);
  4848. if (conn->is_chunked) {
  4849. /* Chunked encoding: 1=chunk not read completely, 2=chunk read
  4850. * completely */
  4851. while (conn->is_chunked == 1) {
  4852. nread = mg_read(conn, buf, to_read);
  4853. if (nread <= 0) {
  4854. break;
  4855. }
  4856. }
  4857. } else {
  4858. /* Not chunked: content length is known */
  4859. while (conn->consumed_content < conn->content_len) {
  4860. if (to_read
  4861. > (size_t)(conn->content_len - conn->consumed_content)) {
  4862. to_read = (size_t)(conn->content_len - conn->consumed_content);
  4863. }
  4864. nread = mg_read(conn, buf, to_read);
  4865. if (nread <= 0) {
  4866. break;
  4867. }
  4868. }
  4869. }
  4870. }
  4871. static int
  4872. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  4873. {
  4874. int64_t n, buffered_len, nread;
  4875. int64_t len64 =
  4876. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  4877. * int, we may not read more
  4878. * bytes */
  4879. const char *body;
  4880. if (conn == NULL) {
  4881. return 0;
  4882. }
  4883. /* If Content-Length is not set for a PUT or POST request, read until
  4884. * socket is closed */
  4885. if ((conn->consumed_content) == 0 && (conn->content_len == -1)) {
  4886. conn->content_len = INT64_MAX;
  4887. conn->must_close = 1;
  4888. }
  4889. nread = 0;
  4890. if (conn->consumed_content < conn->content_len) {
  4891. /* Adjust number of bytes to read. */
  4892. int64_t left_to_read = conn->content_len - conn->consumed_content;
  4893. if (left_to_read < len64) {
  4894. /* Do not read more than the total content length of the
  4895. * request.
  4896. */
  4897. len64 = left_to_read;
  4898. }
  4899. /* Return buffered data */
  4900. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  4901. - conn->consumed_content;
  4902. if (buffered_len > 0) {
  4903. if (len64 < buffered_len) {
  4904. buffered_len = len64;
  4905. }
  4906. body = conn->buf + conn->request_len + conn->consumed_content;
  4907. memcpy(buf, body, (size_t)buffered_len);
  4908. len64 -= buffered_len;
  4909. conn->consumed_content += buffered_len;
  4910. nread += buffered_len;
  4911. buf = (char *)buf + buffered_len;
  4912. }
  4913. /* We have returned all buffered data. Read new data from the remote
  4914. * socket.
  4915. */
  4916. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  4917. nread += n;
  4918. } else {
  4919. nread = ((nread > 0) ? nread : n);
  4920. }
  4921. }
  4922. return (int)nread;
  4923. }
  4924. static char
  4925. mg_getc(struct mg_connection *conn)
  4926. {
  4927. char c;
  4928. if (conn == NULL) {
  4929. return 0;
  4930. }
  4931. conn->content_len++;
  4932. if (mg_read_inner(conn, &c, 1) <= 0) {
  4933. return (char)0;
  4934. }
  4935. return c;
  4936. }
  4937. int
  4938. mg_read(struct mg_connection *conn, void *buf, size_t len)
  4939. {
  4940. if (len > INT_MAX) {
  4941. len = INT_MAX;
  4942. }
  4943. if (conn == NULL) {
  4944. return 0;
  4945. }
  4946. if (conn->is_chunked) {
  4947. size_t all_read = 0;
  4948. while (len > 0) {
  4949. if (conn->is_chunked == 2) {
  4950. /* No more data left to read */
  4951. return 0;
  4952. }
  4953. if (conn->chunk_remainder) {
  4954. /* copy from the remainder of the last received chunk */
  4955. long read_ret;
  4956. size_t read_now =
  4957. ((conn->chunk_remainder > len) ? (len)
  4958. : (conn->chunk_remainder));
  4959. conn->content_len += (int)read_now;
  4960. read_ret =
  4961. mg_read_inner(conn, (char *)buf + all_read, read_now);
  4962. if (read_ret < 1) {
  4963. /* read error */
  4964. return -1;
  4965. }
  4966. all_read += (size_t)read_ret;
  4967. conn->chunk_remainder -= (size_t)read_ret;
  4968. len -= (size_t)read_ret;
  4969. if (conn->chunk_remainder == 0) {
  4970. /* Add data bytes in the current chunk have been read,
  4971. * so we are expecting \r\n now. */
  4972. char x1 = mg_getc(conn);
  4973. char x2 = mg_getc(conn);
  4974. if ((x1 != '\r') || (x2 != '\n')) {
  4975. /* Protocol violation */
  4976. return -1;
  4977. }
  4978. }
  4979. } else {
  4980. /* fetch a new chunk */
  4981. int i = 0;
  4982. char lenbuf[64];
  4983. char *end = 0;
  4984. unsigned long chunkSize = 0;
  4985. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  4986. lenbuf[i] = mg_getc(conn);
  4987. if ((i > 0) && (lenbuf[i] == '\r')
  4988. && (lenbuf[i - 1] != '\r')) {
  4989. continue;
  4990. }
  4991. if ((i > 1) && (lenbuf[i] == '\n')
  4992. && (lenbuf[i - 1] == '\r')) {
  4993. lenbuf[i + 1] = 0;
  4994. chunkSize = strtoul(lenbuf, &end, 16);
  4995. if (chunkSize == 0) {
  4996. /* regular end of content */
  4997. conn->is_chunked = 2;
  4998. }
  4999. break;
  5000. }
  5001. if (!isxdigit(lenbuf[i])) {
  5002. /* illegal character for chunk length */
  5003. return -1;
  5004. }
  5005. }
  5006. if ((end == NULL) || (*end != '\r')) {
  5007. /* chunksize not set correctly */
  5008. return -1;
  5009. }
  5010. if (chunkSize == 0) {
  5011. break;
  5012. }
  5013. conn->chunk_remainder = chunkSize;
  5014. }
  5015. }
  5016. return (int)all_read;
  5017. }
  5018. return mg_read_inner(conn, buf, len);
  5019. }
  5020. int
  5021. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5022. {
  5023. time_t now;
  5024. int64_t n, total, allowed;
  5025. if (conn == NULL) {
  5026. return 0;
  5027. }
  5028. if (conn->throttle > 0) {
  5029. if ((now = time(NULL)) != conn->last_throttle_time) {
  5030. conn->last_throttle_time = now;
  5031. conn->last_throttle_bytes = 0;
  5032. }
  5033. allowed = conn->throttle - conn->last_throttle_bytes;
  5034. if (allowed > (int64_t)len) {
  5035. allowed = (int64_t)len;
  5036. }
  5037. if ((total = push_all(conn->ctx,
  5038. NULL,
  5039. conn->client.sock,
  5040. conn->ssl,
  5041. (const char *)buf,
  5042. (int64_t)allowed)) == allowed) {
  5043. buf = (const char *)buf + total;
  5044. conn->last_throttle_bytes += total;
  5045. while ((total < (int64_t)len) && (conn->ctx->stop_flag == 0)) {
  5046. allowed = (conn->throttle > ((int64_t)len - total))
  5047. ? (int64_t)len - total
  5048. : conn->throttle;
  5049. if ((n = push_all(conn->ctx,
  5050. NULL,
  5051. conn->client.sock,
  5052. conn->ssl,
  5053. (const char *)buf,
  5054. (int64_t)allowed)) != allowed) {
  5055. break;
  5056. }
  5057. sleep(1);
  5058. conn->last_throttle_bytes = allowed;
  5059. conn->last_throttle_time = time(NULL);
  5060. buf = (const char *)buf + n;
  5061. total += n;
  5062. }
  5063. }
  5064. } else {
  5065. total = push_all(conn->ctx,
  5066. NULL,
  5067. conn->client.sock,
  5068. conn->ssl,
  5069. (const char *)buf,
  5070. (int64_t)len);
  5071. }
  5072. if (total > 0) {
  5073. conn->num_bytes_sent += total;
  5074. }
  5075. return (int)total;
  5076. }
  5077. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  5078. int
  5079. mg_send_chunk(struct mg_connection *conn,
  5080. const char *chunk,
  5081. unsigned int chunk_len)
  5082. {
  5083. char lenbuf[16];
  5084. size_t lenbuf_len;
  5085. int ret;
  5086. int t;
  5087. /* First store the length information in a text buffer. */
  5088. sprintf(lenbuf, "%x\r\n", chunk_len);
  5089. lenbuf_len = strlen(lenbuf);
  5090. /* Then send length information, chunk and terminating \r\n. */
  5091. ret = mg_write(conn, lenbuf, lenbuf_len);
  5092. if (ret != (int)lenbuf_len) {
  5093. return -1;
  5094. }
  5095. t = ret;
  5096. ret = mg_write(conn, chunk, chunk_len);
  5097. if (ret != (int)chunk_len) {
  5098. return -1;
  5099. }
  5100. t += ret;
  5101. ret = mg_write(conn, "\r\n", 2);
  5102. if (ret != 2) {
  5103. return -1;
  5104. }
  5105. t += ret;
  5106. return t;
  5107. }
  5108. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  5109. static int
  5110. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  5111. {
  5112. va_list ap_copy;
  5113. size_t size = MG_BUF_LEN / 4;
  5114. int len = -1;
  5115. *buf = NULL;
  5116. while (len < 0) {
  5117. if (*buf) {
  5118. mg_free(*buf);
  5119. }
  5120. size *= 4;
  5121. *buf = (char *)mg_malloc(size);
  5122. if (!*buf) {
  5123. break;
  5124. }
  5125. va_copy(ap_copy, ap);
  5126. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  5127. va_end(ap_copy);
  5128. (*buf)[size - 1] = 0;
  5129. }
  5130. return len;
  5131. }
  5132. /* Print message to buffer. If buffer is large enough to hold the message,
  5133. * return buffer. If buffer is to small, allocate large enough buffer on
  5134. * heap,
  5135. * and return allocated buffer. */
  5136. static int
  5137. alloc_vprintf(char **out_buf,
  5138. char *prealloc_buf,
  5139. size_t prealloc_size,
  5140. const char *fmt,
  5141. va_list ap)
  5142. {
  5143. va_list ap_copy;
  5144. int len;
  5145. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  5146. * buffer is too small. Also, older versions of msvcrt.dll do not have
  5147. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  5148. * Therefore, we make two passes: on first pass, get required message
  5149. * length.
  5150. * On second pass, actually print the message. */
  5151. va_copy(ap_copy, ap);
  5152. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  5153. va_end(ap_copy);
  5154. if (len < 0) {
  5155. /* C runtime is not standard compliant, vsnprintf() returned -1.
  5156. * Switch to alternative code path that uses incremental
  5157. * allocations.
  5158. */
  5159. va_copy(ap_copy, ap);
  5160. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  5161. va_end(ap_copy);
  5162. } else if ((size_t)(len) >= prealloc_size) {
  5163. /* The pre-allocated buffer not large enough. */
  5164. /* Allocate a new buffer. */
  5165. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  5166. if (!*out_buf) {
  5167. /* Allocation failed. Return -1 as "out of memory" error. */
  5168. return -1;
  5169. }
  5170. /* Buffer allocation successful. Store the string there. */
  5171. va_copy(ap_copy, ap);
  5172. IGNORE_UNUSED_RESULT(
  5173. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  5174. va_end(ap_copy);
  5175. } else {
  5176. /* The pre-allocated buffer is large enough.
  5177. * Use it to store the string and return the address. */
  5178. va_copy(ap_copy, ap);
  5179. IGNORE_UNUSED_RESULT(
  5180. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  5181. va_end(ap_copy);
  5182. *out_buf = prealloc_buf;
  5183. }
  5184. return len;
  5185. }
  5186. static int
  5187. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  5188. {
  5189. char mem[MG_BUF_LEN];
  5190. char *buf = NULL;
  5191. int len;
  5192. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  5193. len = mg_write(conn, buf, (size_t)len);
  5194. }
  5195. if ((buf != mem) && (buf != NULL)) {
  5196. mg_free(buf);
  5197. }
  5198. return len;
  5199. }
  5200. int
  5201. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  5202. {
  5203. va_list ap;
  5204. int result;
  5205. va_start(ap, fmt);
  5206. result = mg_vprintf(conn, fmt, ap);
  5207. va_end(ap);
  5208. return result;
  5209. }
  5210. int
  5211. mg_url_decode(const char *src,
  5212. int src_len,
  5213. char *dst,
  5214. int dst_len,
  5215. int is_form_url_encoded)
  5216. {
  5217. int i, j, a, b;
  5218. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  5219. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  5220. if ((i < src_len - 2) && (src[i] == '%')
  5221. && isxdigit(*(const unsigned char *)(src + i + 1))
  5222. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  5223. a = tolower(*(const unsigned char *)(src + i + 1));
  5224. b = tolower(*(const unsigned char *)(src + i + 2));
  5225. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  5226. i += 2;
  5227. } else if (is_form_url_encoded && (src[i] == '+')) {
  5228. dst[j] = ' ';
  5229. } else {
  5230. dst[j] = src[i];
  5231. }
  5232. }
  5233. dst[j] = '\0'; /* Null-terminate the destination */
  5234. return (i >= src_len) ? j : -1;
  5235. }
  5236. int
  5237. mg_get_var(const char *data,
  5238. size_t data_len,
  5239. const char *name,
  5240. char *dst,
  5241. size_t dst_len)
  5242. {
  5243. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  5244. }
  5245. int
  5246. mg_get_var2(const char *data,
  5247. size_t data_len,
  5248. const char *name,
  5249. char *dst,
  5250. size_t dst_len,
  5251. size_t occurrence)
  5252. {
  5253. const char *p, *e, *s;
  5254. size_t name_len;
  5255. int len;
  5256. if ((dst == NULL) || (dst_len == 0)) {
  5257. len = -2;
  5258. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  5259. len = -1;
  5260. dst[0] = '\0';
  5261. } else {
  5262. name_len = strlen(name);
  5263. e = data + data_len;
  5264. len = -1;
  5265. dst[0] = '\0';
  5266. /* data is "var1=val1&var2=val2...". Find variable first */
  5267. for (p = data; p + name_len < e; p++) {
  5268. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  5269. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  5270. /* Point p to variable value */
  5271. p += name_len + 1;
  5272. /* Point s to the end of the value */
  5273. s = (const char *)memchr(p, '&', (size_t)(e - p));
  5274. if (s == NULL) {
  5275. s = e;
  5276. }
  5277. /* assert(s >= p); */
  5278. if (s < p) {
  5279. return -3;
  5280. }
  5281. /* Decode variable into destination buffer */
  5282. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  5283. /* Redirect error code from -1 to -2 (destination buffer too
  5284. * small). */
  5285. if (len == -1) {
  5286. len = -2;
  5287. }
  5288. break;
  5289. }
  5290. }
  5291. }
  5292. return len;
  5293. }
  5294. /* HCP24: some changes to compare hole var_name */
  5295. int
  5296. mg_get_cookie(const char *cookie_header,
  5297. const char *var_name,
  5298. char *dst,
  5299. size_t dst_size)
  5300. {
  5301. const char *s, *p, *end;
  5302. int name_len, len = -1;
  5303. if ((dst == NULL) || (dst_size == 0)) {
  5304. return -2;
  5305. }
  5306. dst[0] = '\0';
  5307. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  5308. return -1;
  5309. }
  5310. name_len = (int)strlen(var_name);
  5311. end = s + strlen(s);
  5312. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  5313. if (s[name_len] == '=') {
  5314. /* HCP24: now check is it a substring or a full cookie name */
  5315. if ((s == cookie_header) || (s[-1] == ' ')) {
  5316. s += name_len + 1;
  5317. if ((p = strchr(s, ' ')) == NULL) {
  5318. p = end;
  5319. }
  5320. if (p[-1] == ';') {
  5321. p--;
  5322. }
  5323. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  5324. s++;
  5325. p--;
  5326. }
  5327. if ((size_t)(p - s) < dst_size) {
  5328. len = (int)(p - s);
  5329. mg_strlcpy(dst, s, (size_t)len + 1);
  5330. } else {
  5331. len = -3;
  5332. }
  5333. break;
  5334. }
  5335. }
  5336. }
  5337. return len;
  5338. }
  5339. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  5340. static void
  5341. base64_encode(const unsigned char *src, int src_len, char *dst)
  5342. {
  5343. static const char *b64 =
  5344. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  5345. int i, j, a, b, c;
  5346. for (i = j = 0; i < src_len; i += 3) {
  5347. a = src[i];
  5348. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  5349. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  5350. dst[j++] = b64[a >> 2];
  5351. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  5352. if (i + 1 < src_len) {
  5353. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  5354. }
  5355. if (i + 2 < src_len) {
  5356. dst[j++] = b64[c & 63];
  5357. }
  5358. }
  5359. while (j % 4 != 0) {
  5360. dst[j++] = '=';
  5361. }
  5362. dst[j++] = '\0';
  5363. }
  5364. #endif
  5365. #if defined(USE_LUA)
  5366. static unsigned char
  5367. b64reverse(char letter)
  5368. {
  5369. if ((letter >= 'A') && (letter <= 'Z')) {
  5370. return letter - 'A';
  5371. }
  5372. if ((letter >= 'a') && (letter <= 'z')) {
  5373. return letter - 'a' + 26;
  5374. }
  5375. if ((letter >= '0') && (letter <= '9')) {
  5376. return letter - '0' + 52;
  5377. }
  5378. if (letter == '+') {
  5379. return 62;
  5380. }
  5381. if (letter == '/') {
  5382. return 63;
  5383. }
  5384. if (letter == '=') {
  5385. return 255; /* normal end */
  5386. }
  5387. return 254; /* error */
  5388. }
  5389. static int
  5390. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  5391. {
  5392. int i;
  5393. unsigned char a, b, c, d;
  5394. *dst_len = 0;
  5395. for (i = 0; i < src_len; i += 4) {
  5396. a = b64reverse(src[i]);
  5397. if (a >= 254) {
  5398. return i;
  5399. }
  5400. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  5401. if (b >= 254) {
  5402. return i + 1;
  5403. }
  5404. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  5405. if (c == 254) {
  5406. return i + 2;
  5407. }
  5408. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  5409. if (d == 254) {
  5410. return i + 3;
  5411. }
  5412. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  5413. if (c != 255) {
  5414. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  5415. if (d != 255) {
  5416. dst[(*dst_len)++] = (c << 6) + d;
  5417. }
  5418. }
  5419. }
  5420. return -1;
  5421. }
  5422. #endif
  5423. static int
  5424. is_put_or_delete_method(const struct mg_connection *conn)
  5425. {
  5426. if (conn) {
  5427. const char *s = conn->request_info.request_method;
  5428. return (s != NULL) && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  5429. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  5430. }
  5431. return 0;
  5432. }
  5433. #if !defined(NO_FILES)
  5434. static int
  5435. extention_matches_script(
  5436. struct mg_connection *conn, /* in: request (must be valid) */
  5437. const char *filename /* in: filename (must be valid) */
  5438. )
  5439. {
  5440. #if !defined(NO_CGI)
  5441. if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  5442. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  5443. filename) > 0) {
  5444. return 1;
  5445. }
  5446. #endif
  5447. #if defined(USE_LUA)
  5448. if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  5449. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  5450. filename) > 0) {
  5451. return 1;
  5452. }
  5453. #endif
  5454. #if defined(USE_DUKTAPE)
  5455. if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  5456. strlen(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  5457. filename) > 0) {
  5458. return 1;
  5459. }
  5460. #endif
  5461. /* filename and conn could be unused, if all preocessor conditions
  5462. * are false (no script language supported). */
  5463. (void)filename;
  5464. (void)conn;
  5465. return 0;
  5466. }
  5467. /* For given directory path, substitute it to valid index file.
  5468. * Return 1 if index file has been found, 0 if not found.
  5469. * If the file is found, it's stats is returned in stp. */
  5470. static int
  5471. substitute_index_file(struct mg_connection *conn,
  5472. char *path,
  5473. size_t path_len,
  5474. struct mg_file_stat *filestat)
  5475. {
  5476. const char *list = conn->ctx->config[INDEX_FILES];
  5477. struct vec filename_vec;
  5478. size_t n = strlen(path);
  5479. int found = 0;
  5480. /* The 'path' given to us points to the directory. Remove all trailing
  5481. * directory separator characters from the end of the path, and
  5482. * then append single directory separator character. */
  5483. while ((n > 0) && (path[n - 1] == '/')) {
  5484. n--;
  5485. }
  5486. path[n] = '/';
  5487. /* Traverse index files list. For each entry, append it to the given
  5488. * path and see if the file exists. If it exists, break the loop */
  5489. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  5490. /* Ignore too long entries that may overflow path buffer */
  5491. if (filename_vec.len > (path_len - (n + 2))) {
  5492. continue;
  5493. }
  5494. /* Prepare full path to the index file */
  5495. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  5496. /* Does it exist? */
  5497. if (mg_stat(conn, path, filestat)) {
  5498. /* Yes it does, break the loop */
  5499. found = 1;
  5500. break;
  5501. }
  5502. }
  5503. /* If no index file exists, restore directory path */
  5504. if (!found) {
  5505. path[n] = '\0';
  5506. }
  5507. return found;
  5508. }
  5509. #endif
  5510. static void
  5511. interpret_uri(struct mg_connection *conn, /* in: request (must be valid) */
  5512. char *filename, /* out: filename */
  5513. size_t filename_buf_len, /* in: size of filename buffer */
  5514. struct mg_file_stat *filestat, /* out: file status structure */
  5515. int *is_found, /* out: file found (directly) */
  5516. int *is_script_resource, /* out: handled by a script? */
  5517. int *is_websocket_request, /* out: websocket connetion? */
  5518. int *is_put_or_delete_request /* out: put/delete a file? */
  5519. )
  5520. {
  5521. #if !defined(NO_FILES)
  5522. const char *uri = conn->request_info.local_uri;
  5523. const char *root = conn->ctx->config[DOCUMENT_ROOT];
  5524. const char *rewrite;
  5525. struct vec a, b;
  5526. int match_len;
  5527. char gz_path[PATH_MAX];
  5528. char const *accept_encoding;
  5529. int truncated;
  5530. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  5531. char *tmp_str;
  5532. size_t tmp_str_len, sep_pos;
  5533. #endif
  5534. #else
  5535. (void)filename_buf_len; /* unused if NO_FILES is defined */
  5536. #endif
  5537. /* Step 1: Set all initially unknown outputs to zero */
  5538. memset(filestat, 0, sizeof(*filestat));
  5539. *filename = 0;
  5540. *is_found = 0;
  5541. *is_script_resource = 0;
  5542. /* Step 2: Check if the request attempts to modify the file system */
  5543. *is_put_or_delete_request = is_put_or_delete_method(conn);
  5544. /* Step 3: Check if it is a websocket request, and modify the document
  5545. * root if required */
  5546. #if defined(USE_WEBSOCKET)
  5547. *is_websocket_request = is_websocket_protocol(conn);
  5548. #if !defined(NO_FILES)
  5549. if (*is_websocket_request && conn->ctx->config[WEBSOCKET_ROOT]) {
  5550. root = conn->ctx->config[WEBSOCKET_ROOT];
  5551. }
  5552. #endif /* !NO_FILES */
  5553. #else /* USE_WEBSOCKET */
  5554. *is_websocket_request = 0;
  5555. #endif /* USE_WEBSOCKET */
  5556. #if !defined(NO_FILES)
  5557. /* Step 4: If there is no root directory, don't look for files. */
  5558. /* Note that root == NULL is a regular use case here. This occurs,
  5559. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  5560. * config is not required. */
  5561. if (root == NULL) {
  5562. /* all file related outputs have already been set to 0, just return
  5563. */
  5564. return;
  5565. }
  5566. /* Step 5: Determine the local file path from the root path and the
  5567. * request uri. */
  5568. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  5569. * part of the path one byte on the right. */
  5570. mg_snprintf(
  5571. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  5572. if (truncated) {
  5573. goto interpret_cleanup;
  5574. }
  5575. /* Step 6: URI rewriting */
  5576. rewrite = conn->ctx->config[URL_REWRITE_PATTERN];
  5577. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  5578. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  5579. mg_snprintf(conn,
  5580. &truncated,
  5581. filename,
  5582. filename_buf_len - 1,
  5583. "%.*s%s",
  5584. (int)b.len,
  5585. b.ptr,
  5586. uri + match_len);
  5587. break;
  5588. }
  5589. }
  5590. if (truncated) {
  5591. goto interpret_cleanup;
  5592. }
  5593. /* Step 7: Check if the file exists at the server */
  5594. /* Local file path and name, corresponding to requested URI
  5595. * is now stored in "filename" variable. */
  5596. if (mg_stat(conn, filename, filestat)) {
  5597. /* 7.1: File exists. */
  5598. *is_found = 1;
  5599. /* 7.2: Check if it is a script type. */
  5600. if (extention_matches_script(conn, filename)) {
  5601. /* The request addresses a CGI resource, Lua script or
  5602. * server-side javascript.
  5603. * The URI corresponds to the script itself (like
  5604. * /path/script.cgi), and there is no additional resource
  5605. * path (like /path/script.cgi/something).
  5606. * Requests that modify (replace or delete) a resource, like
  5607. * PUT and DELETE requests, should replace/delete the script
  5608. * file.
  5609. * Requests that read or write from/to a resource, like GET and
  5610. * POST requests, should call the script and return the
  5611. * generated response. */
  5612. *is_script_resource = (!*is_put_or_delete_request);
  5613. }
  5614. /* 7.3: If the request target is a directory, there could be
  5615. * a substitute file (index.html, index.cgi, ...). */
  5616. if (filestat->is_directory) {
  5617. /* Use a local copy here, since substitute_index_file will
  5618. * change the content of the file status */
  5619. struct mg_file_stat tmp_filestat;
  5620. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  5621. if (substitute_index_file(
  5622. conn, filename, filename_buf_len, &tmp_filestat)) {
  5623. /* Substitute file found. Copy stat to the output, then
  5624. * check if the file is a script file */
  5625. *filestat = tmp_filestat;
  5626. if (extention_matches_script(conn, filename)) {
  5627. /* Substitute file is a script file */
  5628. *is_script_resource = 1;
  5629. } else {
  5630. /* Substitute file is a regular file */
  5631. *is_script_resource = 0;
  5632. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  5633. }
  5634. }
  5635. /* If there is no substitute file, the server could return
  5636. * a directory listing in a later step */
  5637. }
  5638. return;
  5639. }
  5640. /* Step 8: Check for zipped files: */
  5641. /* If we can't find the actual file, look for the file
  5642. * with the same name but a .gz extension. If we find it,
  5643. * use that and set the gzipped flag in the file struct
  5644. * to indicate that the response need to have the content-
  5645. * encoding: gzip header.
  5646. * We can only do this if the browser declares support. */
  5647. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  5648. if (strstr(accept_encoding, "gzip") != NULL) {
  5649. mg_snprintf(
  5650. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  5651. if (truncated) {
  5652. goto interpret_cleanup;
  5653. }
  5654. if (mg_stat(conn, gz_path, filestat)) {
  5655. if (filestat) {
  5656. filestat->is_gzipped = 1;
  5657. *is_found = 1;
  5658. }
  5659. /* Currently gz files can not be scripts. */
  5660. return;
  5661. }
  5662. }
  5663. }
  5664. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  5665. /* Step 9: Script resources may handle sub-resources */
  5666. /* Support PATH_INFO for CGI scripts. */
  5667. tmp_str_len = strlen(filename);
  5668. tmp_str = mg_malloc_ctx(tmp_str_len + PATH_MAX + 1, conn->ctx);
  5669. if (!tmp_str) {
  5670. /* Out of memory */
  5671. goto interpret_cleanup;
  5672. }
  5673. memcpy(tmp_str, filename, tmp_str_len + 1);
  5674. sep_pos = tmp_str_len;
  5675. while (sep_pos > 0) {
  5676. sep_pos--;
  5677. if (tmp_str[sep_pos] == '/') {
  5678. int is_script = 0, does_exist = 0;
  5679. tmp_str[sep_pos] = 0;
  5680. if (tmp_str[0]) {
  5681. is_script = extention_matches_script(conn, tmp_str);
  5682. does_exist = mg_stat(conn, tmp_str, filestat);
  5683. }
  5684. if (does_exist && is_script) {
  5685. filename[sep_pos] = 0;
  5686. memmove(filename + sep_pos + 2,
  5687. filename + sep_pos + 1,
  5688. strlen(filename + sep_pos + 1) + 1);
  5689. conn->path_info = filename + sep_pos + 1;
  5690. filename[sep_pos + 1] = '/';
  5691. *is_script_resource = 1;
  5692. *is_found = 1;
  5693. break;
  5694. }
  5695. if (substitute_index_file(
  5696. conn, tmp_str, tmp_str_len + PATH_MAX, filestat)) {
  5697. /* some intermediate directory has an index file */
  5698. if (extention_matches_script(conn, tmp_str)) {
  5699. /* this index file is a script */
  5700. char *tmp_str2 = mg_strdup(filename + sep_pos + 1);
  5701. mg_snprintf(conn,
  5702. &truncated,
  5703. filename,
  5704. filename_buf_len,
  5705. "%s//%s",
  5706. tmp_str,
  5707. tmp_str2);
  5708. mg_free(tmp_str2);
  5709. if (truncated) {
  5710. mg_free(tmp_str);
  5711. goto interpret_cleanup;
  5712. }
  5713. sep_pos = strlen(tmp_str);
  5714. filename[sep_pos] = 0;
  5715. conn->path_info = filename + sep_pos + 1;
  5716. *is_script_resource = 1;
  5717. *is_found = 1;
  5718. break;
  5719. } else {
  5720. /* non-script files will not have sub-resources */
  5721. filename[sep_pos] = 0;
  5722. conn->path_info = 0;
  5723. *is_script_resource = 0;
  5724. *is_found = 0;
  5725. break;
  5726. }
  5727. }
  5728. tmp_str[sep_pos] = '/';
  5729. }
  5730. }
  5731. mg_free(tmp_str);
  5732. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  5733. #endif /* !defined(NO_FILES) */
  5734. return;
  5735. #if !defined(NO_FILES)
  5736. /* Reset all outputs */
  5737. interpret_cleanup:
  5738. memset(filestat, 0, sizeof(*filestat));
  5739. *filename = 0;
  5740. *is_found = 0;
  5741. *is_script_resource = 0;
  5742. *is_websocket_request = 0;
  5743. *is_put_or_delete_request = 0;
  5744. #endif /* !defined(NO_FILES) */
  5745. }
  5746. /* Check whether full request is buffered. Return:
  5747. * -1 if request or response is malformed
  5748. * 0 if request or response is not yet fully buffered
  5749. * >0 actual request length, including last \r\n\r\n */
  5750. static int
  5751. get_http_header_len(const char *buf, int buflen)
  5752. {
  5753. int i;
  5754. for (i = 0; i < buflen; i++) {
  5755. /* Do an unsigned comparison in some conditions below */
  5756. const unsigned char c = ((const unsigned char *)buf)[i];
  5757. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  5758. && !isprint(c)) {
  5759. /* abort scan as soon as one malformed character is found */
  5760. return -1;
  5761. }
  5762. if (i < buflen - 1) {
  5763. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  5764. /* Two newline, no carriage return - not standard compliant,
  5765. * but
  5766. * it
  5767. * should be accepted */
  5768. return i + 2;
  5769. }
  5770. }
  5771. if (i < buflen - 3) {
  5772. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  5773. && (buf[i + 3] == '\n')) {
  5774. /* Two \r\n - standard compliant */
  5775. return i + 4;
  5776. }
  5777. }
  5778. }
  5779. return 0;
  5780. }
  5781. #if !defined(NO_CACHING)
  5782. /* Convert month to the month number. Return -1 on error, or month number */
  5783. static int
  5784. get_month_index(const char *s)
  5785. {
  5786. size_t i;
  5787. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  5788. if (!strcmp(s, month_names[i])) {
  5789. return (int)i;
  5790. }
  5791. }
  5792. return -1;
  5793. }
  5794. /* Parse UTC date-time string, and return the corresponding time_t value. */
  5795. static time_t
  5796. parse_date_string(const char *datetime)
  5797. {
  5798. char month_str[32] = {0};
  5799. int second, minute, hour, day, month, year;
  5800. time_t result = (time_t)0;
  5801. struct tm tm;
  5802. if ((sscanf(datetime,
  5803. "%d/%3s/%d %d:%d:%d",
  5804. &day,
  5805. month_str,
  5806. &year,
  5807. &hour,
  5808. &minute,
  5809. &second) == 6) || (sscanf(datetime,
  5810. "%d %3s %d %d:%d:%d",
  5811. &day,
  5812. month_str,
  5813. &year,
  5814. &hour,
  5815. &minute,
  5816. &second) == 6)
  5817. || (sscanf(datetime,
  5818. "%*3s, %d %3s %d %d:%d:%d",
  5819. &day,
  5820. month_str,
  5821. &year,
  5822. &hour,
  5823. &minute,
  5824. &second) == 6) || (sscanf(datetime,
  5825. "%d-%3s-%d %d:%d:%d",
  5826. &day,
  5827. month_str,
  5828. &year,
  5829. &hour,
  5830. &minute,
  5831. &second) == 6)) {
  5832. month = get_month_index(month_str);
  5833. if ((month >= 0) && (year >= 1970)) {
  5834. memset(&tm, 0, sizeof(tm));
  5835. tm.tm_year = year - 1900;
  5836. tm.tm_mon = month;
  5837. tm.tm_mday = day;
  5838. tm.tm_hour = hour;
  5839. tm.tm_min = minute;
  5840. tm.tm_sec = second;
  5841. result = timegm(&tm);
  5842. }
  5843. }
  5844. return result;
  5845. }
  5846. #endif /* !NO_CACHING */
  5847. /* Protect against directory disclosure attack by removing '..',
  5848. * excessive '/' and '\' characters */
  5849. static void
  5850. remove_double_dots_and_double_slashes(char *s)
  5851. {
  5852. char *p = s;
  5853. while ((s[0] == '.') && (s[1] == '.')) {
  5854. s++;
  5855. }
  5856. while (*s != '\0') {
  5857. *p++ = *s++;
  5858. if ((s[-1] == '/') || (s[-1] == '\\')) {
  5859. /* Skip all following slashes, backslashes and double-dots */
  5860. while (s[0] != '\0') {
  5861. if ((s[0] == '/') || (s[0] == '\\')) {
  5862. s++;
  5863. } else if ((s[0] == '.') && (s[1] == '.')) {
  5864. s += 2;
  5865. } else {
  5866. break;
  5867. }
  5868. }
  5869. }
  5870. }
  5871. *p = '\0';
  5872. }
  5873. static const struct {
  5874. const char *extension;
  5875. size_t ext_len;
  5876. const char *mime_type;
  5877. } builtin_mime_types[] = {
  5878. /* IANA registered MIME types
  5879. * (http://www.iana.org/assignments/media-types)
  5880. * application types */
  5881. {".doc", 4, "application/msword"},
  5882. {".eps", 4, "application/postscript"},
  5883. {".exe", 4, "application/octet-stream"},
  5884. {".js", 3, "application/javascript"},
  5885. {".json", 5, "application/json"},
  5886. {".pdf", 4, "application/pdf"},
  5887. {".ps", 3, "application/postscript"},
  5888. {".rtf", 4, "application/rtf"},
  5889. {".xhtml", 6, "application/xhtml+xml"},
  5890. {".xsl", 4, "application/xml"},
  5891. {".xslt", 5, "application/xml"},
  5892. /* fonts */
  5893. {".ttf", 4, "application/font-sfnt"},
  5894. {".cff", 4, "application/font-sfnt"},
  5895. {".otf", 4, "application/font-sfnt"},
  5896. {".aat", 4, "application/font-sfnt"},
  5897. {".sil", 4, "application/font-sfnt"},
  5898. {".pfr", 4, "application/font-tdpfr"},
  5899. {".woff", 5, "application/font-woff"},
  5900. /* audio */
  5901. {".mp3", 4, "audio/mpeg"},
  5902. {".oga", 4, "audio/ogg"},
  5903. {".ogg", 4, "audio/ogg"},
  5904. /* image */
  5905. {".gif", 4, "image/gif"},
  5906. {".ief", 4, "image/ief"},
  5907. {".jpeg", 5, "image/jpeg"},
  5908. {".jpg", 4, "image/jpeg"},
  5909. {".jpm", 4, "image/jpm"},
  5910. {".jpx", 4, "image/jpx"},
  5911. {".png", 4, "image/png"},
  5912. {".svg", 4, "image/svg+xml"},
  5913. {".tif", 4, "image/tiff"},
  5914. {".tiff", 5, "image/tiff"},
  5915. /* model */
  5916. {".wrl", 4, "model/vrml"},
  5917. /* text */
  5918. {".css", 4, "text/css"},
  5919. {".csv", 4, "text/csv"},
  5920. {".htm", 4, "text/html"},
  5921. {".html", 5, "text/html"},
  5922. {".sgm", 4, "text/sgml"},
  5923. {".shtm", 5, "text/html"},
  5924. {".shtml", 6, "text/html"},
  5925. {".txt", 4, "text/plain"},
  5926. {".xml", 4, "text/xml"},
  5927. /* video */
  5928. {".mov", 4, "video/quicktime"},
  5929. {".mp4", 4, "video/mp4"},
  5930. {".mpeg", 5, "video/mpeg"},
  5931. {".mpg", 4, "video/mpeg"},
  5932. {".ogv", 4, "video/ogg"},
  5933. {".qt", 3, "video/quicktime"},
  5934. /* not registered types
  5935. * (http://reference.sitepoint.com/html/mime-types-full,
  5936. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  5937. {".arj", 4, "application/x-arj-compressed"},
  5938. {".gz", 3, "application/x-gunzip"},
  5939. {".rar", 4, "application/x-arj-compressed"},
  5940. {".swf", 4, "application/x-shockwave-flash"},
  5941. {".tar", 4, "application/x-tar"},
  5942. {".tgz", 4, "application/x-tar-gz"},
  5943. {".torrent", 8, "application/x-bittorrent"},
  5944. {".ppt", 4, "application/x-mspowerpoint"},
  5945. {".xls", 4, "application/x-msexcel"},
  5946. {".zip", 4, "application/x-zip-compressed"},
  5947. {".aac",
  5948. 4,
  5949. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  5950. {".aif", 4, "audio/x-aif"},
  5951. {".m3u", 4, "audio/x-mpegurl"},
  5952. {".mid", 4, "audio/x-midi"},
  5953. {".ra", 3, "audio/x-pn-realaudio"},
  5954. {".ram", 4, "audio/x-pn-realaudio"},
  5955. {".wav", 4, "audio/x-wav"},
  5956. {".bmp", 4, "image/bmp"},
  5957. {".ico", 4, "image/x-icon"},
  5958. {".pct", 4, "image/x-pct"},
  5959. {".pict", 5, "image/pict"},
  5960. {".rgb", 4, "image/x-rgb"},
  5961. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  5962. {".asf", 4, "video/x-ms-asf"},
  5963. {".avi", 4, "video/x-msvideo"},
  5964. {".m4v", 4, "video/x-m4v"},
  5965. {NULL, 0, NULL}};
  5966. const char *
  5967. mg_get_builtin_mime_type(const char *path)
  5968. {
  5969. const char *ext;
  5970. size_t i, path_len;
  5971. path_len = strlen(path);
  5972. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  5973. ext = path + (path_len - builtin_mime_types[i].ext_len);
  5974. if ((path_len > builtin_mime_types[i].ext_len)
  5975. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  5976. return builtin_mime_types[i].mime_type;
  5977. }
  5978. }
  5979. return "text/plain";
  5980. }
  5981. /* Look at the "path" extension and figure what mime type it has.
  5982. * Store mime type in the vector. */
  5983. static void
  5984. get_mime_type(struct mg_context *ctx, const char *path, struct vec *vec)
  5985. {
  5986. struct vec ext_vec, mime_vec;
  5987. const char *list, *ext;
  5988. size_t path_len;
  5989. path_len = strlen(path);
  5990. if ((ctx == NULL) || (vec == NULL)) {
  5991. if (vec != NULL) {
  5992. memset(vec, '\0', sizeof(struct vec));
  5993. }
  5994. return;
  5995. }
  5996. /* Scan user-defined mime types first, in case user wants to
  5997. * override default mime types. */
  5998. list = ctx->config[EXTRA_MIME_TYPES];
  5999. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  6000. /* ext now points to the path suffix */
  6001. ext = path + path_len - ext_vec.len;
  6002. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  6003. *vec = mime_vec;
  6004. return;
  6005. }
  6006. }
  6007. vec->ptr = mg_get_builtin_mime_type(path);
  6008. vec->len = strlen(vec->ptr);
  6009. }
  6010. /* Stringify binary data. Output buffer must be twice as big as input,
  6011. * because each byte takes 2 bytes in string representation */
  6012. static void
  6013. bin2str(char *to, const unsigned char *p, size_t len)
  6014. {
  6015. static const char *hex = "0123456789abcdef";
  6016. for (; len--; p++) {
  6017. *to++ = hex[p[0] >> 4];
  6018. *to++ = hex[p[0] & 0x0f];
  6019. }
  6020. *to = '\0';
  6021. }
  6022. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  6023. */
  6024. char *
  6025. mg_md5(char buf[33], ...)
  6026. {
  6027. md5_byte_t hash[16];
  6028. const char *p;
  6029. va_list ap;
  6030. md5_state_t ctx;
  6031. md5_init(&ctx);
  6032. va_start(ap, buf);
  6033. while ((p = va_arg(ap, const char *)) != NULL) {
  6034. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  6035. }
  6036. va_end(ap);
  6037. md5_finish(&ctx, hash);
  6038. bin2str(buf, hash, sizeof(hash));
  6039. return buf;
  6040. }
  6041. /* Check the user's password, return 1 if OK */
  6042. static int
  6043. check_password(const char *method,
  6044. const char *ha1,
  6045. const char *uri,
  6046. const char *nonce,
  6047. const char *nc,
  6048. const char *cnonce,
  6049. const char *qop,
  6050. const char *response)
  6051. {
  6052. char ha2[32 + 1], expected_response[32 + 1];
  6053. /* Some of the parameters may be NULL */
  6054. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  6055. || (qop == NULL) || (response == NULL)) {
  6056. return 0;
  6057. }
  6058. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  6059. if (strlen(response) != 32) {
  6060. return 0;
  6061. }
  6062. mg_md5(ha2, method, ":", uri, NULL);
  6063. mg_md5(expected_response,
  6064. ha1,
  6065. ":",
  6066. nonce,
  6067. ":",
  6068. nc,
  6069. ":",
  6070. cnonce,
  6071. ":",
  6072. qop,
  6073. ":",
  6074. ha2,
  6075. NULL);
  6076. return mg_strcasecmp(response, expected_response) == 0;
  6077. }
  6078. /* Use the global passwords file, if specified by auth_gpass option,
  6079. * or search for .htpasswd in the requested directory. */
  6080. static void
  6081. open_auth_file(struct mg_connection *conn,
  6082. const char *path,
  6083. struct mg_file *filep)
  6084. {
  6085. if ((conn != NULL) && (conn->ctx != NULL)) {
  6086. char name[PATH_MAX];
  6087. const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
  6088. int truncated;
  6089. if (gpass != NULL) {
  6090. /* Use global passwords file */
  6091. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  6092. #ifdef DEBUG
  6093. /* Use mg_cry here, since gpass has been configured. */
  6094. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  6095. #endif
  6096. }
  6097. /* Important: using local struct mg_file to test path for
  6098. * is_directory flag. If filep is used, mg_stat() makes it
  6099. * appear as if auth file was opened.
  6100. * TODO(mid): Check if this is still required after rewriting
  6101. * mg_stat */
  6102. } else if (mg_stat(conn, path, &filep->stat)
  6103. && filep->stat.is_directory) {
  6104. mg_snprintf(conn,
  6105. &truncated,
  6106. name,
  6107. sizeof(name),
  6108. "%s/%s",
  6109. path,
  6110. PASSWORDS_FILE_NAME);
  6111. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  6112. #ifdef DEBUG
  6113. /* Don't use mg_cry here, but only a trace, since this is
  6114. * a typical case. It will occur for every directory
  6115. * without a password file. */
  6116. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  6117. #endif
  6118. }
  6119. } else {
  6120. /* Try to find .htpasswd in requested directory. */
  6121. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  6122. if (e[0] == '/') {
  6123. break;
  6124. }
  6125. }
  6126. mg_snprintf(conn,
  6127. &truncated,
  6128. name,
  6129. sizeof(name),
  6130. "%.*s/%s",
  6131. (int)(e - p),
  6132. p,
  6133. PASSWORDS_FILE_NAME);
  6134. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  6135. #ifdef DEBUG
  6136. /* Don't use mg_cry here, but only a trace, since this is
  6137. * a typical case. It will occur for every directory
  6138. * without a password file. */
  6139. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  6140. #endif
  6141. }
  6142. }
  6143. }
  6144. }
  6145. /* Parsed Authorization header */
  6146. struct ah {
  6147. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  6148. };
  6149. /* Return 1 on success. Always initializes the ah structure. */
  6150. static int
  6151. parse_auth_header(struct mg_connection *conn,
  6152. char *buf,
  6153. size_t buf_size,
  6154. struct ah *ah)
  6155. {
  6156. char *name, *value, *s;
  6157. const char *auth_header;
  6158. uint64_t nonce;
  6159. if (!ah || !conn) {
  6160. return 0;
  6161. }
  6162. (void)memset(ah, 0, sizeof(*ah));
  6163. if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
  6164. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  6165. return 0;
  6166. }
  6167. /* Make modifiable copy of the auth header */
  6168. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  6169. s = buf;
  6170. /* Parse authorization header */
  6171. for (;;) {
  6172. /* Gobble initial spaces */
  6173. while (isspace(*(unsigned char *)s)) {
  6174. s++;
  6175. }
  6176. name = skip_quoted(&s, "=", " ", 0);
  6177. /* Value is either quote-delimited, or ends at first comma or space.
  6178. */
  6179. if (s[0] == '\"') {
  6180. s++;
  6181. value = skip_quoted(&s, "\"", " ", '\\');
  6182. if (s[0] == ',') {
  6183. s++;
  6184. }
  6185. } else {
  6186. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  6187. * spaces */
  6188. }
  6189. if (*name == '\0') {
  6190. break;
  6191. }
  6192. if (!strcmp(name, "username")) {
  6193. ah->user = value;
  6194. } else if (!strcmp(name, "cnonce")) {
  6195. ah->cnonce = value;
  6196. } else if (!strcmp(name, "response")) {
  6197. ah->response = value;
  6198. } else if (!strcmp(name, "uri")) {
  6199. ah->uri = value;
  6200. } else if (!strcmp(name, "qop")) {
  6201. ah->qop = value;
  6202. } else if (!strcmp(name, "nc")) {
  6203. ah->nc = value;
  6204. } else if (!strcmp(name, "nonce")) {
  6205. ah->nonce = value;
  6206. }
  6207. }
  6208. #ifndef NO_NONCE_CHECK
  6209. /* Read the nonce from the response. */
  6210. if (ah->nonce == NULL) {
  6211. return 0;
  6212. }
  6213. s = NULL;
  6214. nonce = strtoull(ah->nonce, &s, 10);
  6215. if ((s == NULL) || (*s != 0)) {
  6216. return 0;
  6217. }
  6218. /* Convert the nonce from the client to a number. */
  6219. nonce ^= conn->ctx->auth_nonce_mask;
  6220. /* The converted number corresponds to the time the nounce has been
  6221. * created. This should not be earlier than the server start. */
  6222. /* Server side nonce check is valuable in all situations but one:
  6223. * if the server restarts frequently, but the client should not see
  6224. * that, so the server should accept nonces from previous starts. */
  6225. /* However, the reasonable default is to not accept a nonce from a
  6226. * previous start, so if anyone changed the access rights between
  6227. * two restarts, a new login is required. */
  6228. if (nonce < (uint64_t)conn->ctx->start_time) {
  6229. /* nonce is from a previous start of the server and no longer valid
  6230. * (replay attack?) */
  6231. return 0;
  6232. }
  6233. /* Check if the nonce is too high, so it has not (yet) been used by the
  6234. * server. */
  6235. if (nonce >= ((uint64_t)conn->ctx->start_time + conn->ctx->nonce_count)) {
  6236. return 0;
  6237. }
  6238. #else
  6239. (void)nonce;
  6240. #endif
  6241. /* CGI needs it as REMOTE_USER */
  6242. if (ah->user != NULL) {
  6243. conn->request_info.remote_user = mg_strdup(ah->user);
  6244. } else {
  6245. return 0;
  6246. }
  6247. return 1;
  6248. }
  6249. static const char *
  6250. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  6251. {
  6252. const char *eof;
  6253. size_t len;
  6254. const char *memend;
  6255. if (!filep) {
  6256. return NULL;
  6257. }
  6258. if ((filep->access.membuf != NULL) && (*p != NULL)) {
  6259. memend = (const char *)&filep->access.membuf[filep->stat.size];
  6260. /* Search for \n from p till the end of stream */
  6261. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  6262. if (eof != NULL) {
  6263. eof += 1; /* Include \n */
  6264. } else {
  6265. eof = memend; /* Copy remaining data */
  6266. }
  6267. len =
  6268. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  6269. memcpy(buf, *p, len);
  6270. buf[len] = '\0';
  6271. *p += len;
  6272. return len ? eof : NULL;
  6273. } else if (filep->access.fp != NULL) {
  6274. return fgets(buf, (int)size, filep->access.fp);
  6275. } else {
  6276. return NULL;
  6277. }
  6278. }
  6279. /* Define the initial recursion depth for procesesing htpasswd files that
  6280. * include other htpasswd
  6281. * (or even the same) files. It is not difficult to provide a file or files
  6282. * s.t. they force civetweb
  6283. * to infinitely recurse and then crash.
  6284. */
  6285. #define INITIAL_DEPTH 9
  6286. #if INITIAL_DEPTH <= 0
  6287. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  6288. #endif
  6289. struct read_auth_file_struct {
  6290. struct mg_connection *conn;
  6291. struct ah ah;
  6292. char *domain;
  6293. char buf[256 + 256 + 40];
  6294. char *f_user;
  6295. char *f_domain;
  6296. char *f_ha1;
  6297. };
  6298. static int
  6299. read_auth_file(struct mg_file *filep,
  6300. struct read_auth_file_struct *workdata,
  6301. int depth)
  6302. {
  6303. char *p;
  6304. int is_authorized = 0;
  6305. struct mg_file fp;
  6306. size_t l;
  6307. if (!filep || !workdata || (0 == depth)) {
  6308. return 0;
  6309. }
  6310. /* Loop over passwords file */
  6311. p = (char *)filep->access.membuf;
  6312. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  6313. l = strlen(workdata->buf);
  6314. while (l > 0) {
  6315. if (isspace(workdata->buf[l - 1])
  6316. || iscntrl(workdata->buf[l - 1])) {
  6317. l--;
  6318. workdata->buf[l] = 0;
  6319. } else
  6320. break;
  6321. }
  6322. if (l < 1) {
  6323. continue;
  6324. }
  6325. workdata->f_user = workdata->buf;
  6326. if (workdata->f_user[0] == ':') {
  6327. /* user names may not contain a ':' and may not be empty,
  6328. * so lines starting with ':' may be used for a special purpose
  6329. */
  6330. if (workdata->f_user[1] == '#') {
  6331. /* :# is a comment */
  6332. continue;
  6333. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  6334. if (mg_fopen(workdata->conn,
  6335. workdata->f_user + 9,
  6336. MG_FOPEN_MODE_READ,
  6337. &fp)) {
  6338. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  6339. (void)mg_fclose(
  6340. &fp.access); /* ignore error on read only file */
  6341. /* No need to continue processing files once we have a
  6342. * match, since nothing will reset it back
  6343. * to 0.
  6344. */
  6345. if (is_authorized) {
  6346. return is_authorized;
  6347. }
  6348. } else {
  6349. mg_cry(workdata->conn,
  6350. "%s: cannot open authorization file: %s",
  6351. __func__,
  6352. workdata->buf);
  6353. }
  6354. continue;
  6355. }
  6356. /* everything is invalid for the moment (might change in the
  6357. * future) */
  6358. mg_cry(workdata->conn,
  6359. "%s: syntax error in authorization file: %s",
  6360. __func__,
  6361. workdata->buf);
  6362. continue;
  6363. }
  6364. workdata->f_domain = strchr(workdata->f_user, ':');
  6365. if (workdata->f_domain == NULL) {
  6366. mg_cry(workdata->conn,
  6367. "%s: syntax error in authorization file: %s",
  6368. __func__,
  6369. workdata->buf);
  6370. continue;
  6371. }
  6372. *(workdata->f_domain) = 0;
  6373. (workdata->f_domain)++;
  6374. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  6375. if (workdata->f_ha1 == NULL) {
  6376. mg_cry(workdata->conn,
  6377. "%s: syntax error in authorization file: %s",
  6378. __func__,
  6379. workdata->buf);
  6380. continue;
  6381. }
  6382. *(workdata->f_ha1) = 0;
  6383. (workdata->f_ha1)++;
  6384. if (!strcmp(workdata->ah.user, workdata->f_user)
  6385. && !strcmp(workdata->domain, workdata->f_domain)) {
  6386. return check_password(workdata->conn->request_info.request_method,
  6387. workdata->f_ha1,
  6388. workdata->ah.uri,
  6389. workdata->ah.nonce,
  6390. workdata->ah.nc,
  6391. workdata->ah.cnonce,
  6392. workdata->ah.qop,
  6393. workdata->ah.response);
  6394. }
  6395. }
  6396. return is_authorized;
  6397. }
  6398. /* Authorize against the opened passwords file. Return 1 if authorized. */
  6399. static int
  6400. authorize(struct mg_connection *conn, struct mg_file *filep)
  6401. {
  6402. struct read_auth_file_struct workdata;
  6403. char buf[MG_BUF_LEN];
  6404. if (!conn || !conn->ctx) {
  6405. return 0;
  6406. }
  6407. memset(&workdata, 0, sizeof(workdata));
  6408. workdata.conn = conn;
  6409. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  6410. return 0;
  6411. }
  6412. workdata.domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  6413. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  6414. }
  6415. /* Return 1 if request is authorised, 0 otherwise. */
  6416. static int
  6417. check_authorization(struct mg_connection *conn, const char *path)
  6418. {
  6419. char fname[PATH_MAX];
  6420. struct vec uri_vec, filename_vec;
  6421. const char *list;
  6422. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6423. int authorized = 1, truncated;
  6424. if (!conn || !conn->ctx) {
  6425. return 0;
  6426. }
  6427. list = conn->ctx->config[PROTECT_URI];
  6428. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  6429. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  6430. mg_snprintf(conn,
  6431. &truncated,
  6432. fname,
  6433. sizeof(fname),
  6434. "%.*s",
  6435. (int)filename_vec.len,
  6436. filename_vec.ptr);
  6437. if (truncated
  6438. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  6439. mg_cry(conn,
  6440. "%s: cannot open %s: %s",
  6441. __func__,
  6442. fname,
  6443. strerror(errno));
  6444. }
  6445. break;
  6446. }
  6447. }
  6448. if (!is_file_opened(&file.access)) {
  6449. open_auth_file(conn, path, &file);
  6450. }
  6451. if (is_file_opened(&file.access)) {
  6452. authorized = authorize(conn, &file);
  6453. (void)mg_fclose(&file.access); /* ignore error on read only file */
  6454. }
  6455. return authorized;
  6456. }
  6457. static void
  6458. send_authorization_request(struct mg_connection *conn)
  6459. {
  6460. char date[64];
  6461. time_t curtime = time(NULL);
  6462. if (conn && conn->ctx) {
  6463. uint64_t nonce = (uint64_t)(conn->ctx->start_time);
  6464. (void)pthread_mutex_lock(&conn->ctx->nonce_mutex);
  6465. nonce += conn->ctx->nonce_count;
  6466. ++conn->ctx->nonce_count;
  6467. (void)pthread_mutex_unlock(&conn->ctx->nonce_mutex);
  6468. nonce ^= conn->ctx->auth_nonce_mask;
  6469. conn->status_code = 401;
  6470. conn->must_close = 1;
  6471. gmt_time_string(date, sizeof(date), &curtime);
  6472. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  6473. send_no_cache_header(conn);
  6474. send_additional_header(conn);
  6475. mg_printf(conn,
  6476. "Date: %s\r\n"
  6477. "Connection: %s\r\n"
  6478. "Content-Length: 0\r\n"
  6479. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  6480. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  6481. date,
  6482. suggest_connection_header(conn),
  6483. conn->ctx->config[AUTHENTICATION_DOMAIN],
  6484. nonce);
  6485. }
  6486. }
  6487. #if !defined(NO_FILES)
  6488. static int
  6489. is_authorized_for_put(struct mg_connection *conn)
  6490. {
  6491. if (conn) {
  6492. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6493. const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
  6494. int ret = 0;
  6495. if (passfile != NULL
  6496. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  6497. ret = authorize(conn, &file);
  6498. (void)mg_fclose(&file.access); /* ignore error on read only file */
  6499. }
  6500. return ret;
  6501. }
  6502. return 0;
  6503. }
  6504. #endif
  6505. int
  6506. mg_modify_passwords_file(const char *fname,
  6507. const char *domain,
  6508. const char *user,
  6509. const char *pass)
  6510. {
  6511. int found, i;
  6512. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  6513. FILE *fp, *fp2;
  6514. found = 0;
  6515. fp = fp2 = NULL;
  6516. /* Regard empty password as no password - remove user record. */
  6517. if ((pass != NULL) && (pass[0] == '\0')) {
  6518. pass = NULL;
  6519. }
  6520. /* Other arguments must not be empty */
  6521. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  6522. return 0;
  6523. }
  6524. /* Using the given file format, user name and domain must not contain
  6525. * ':'
  6526. */
  6527. if (strchr(user, ':') != NULL) {
  6528. return 0;
  6529. }
  6530. if (strchr(domain, ':') != NULL) {
  6531. return 0;
  6532. }
  6533. /* Do not allow control characters like newline in user name and domain.
  6534. * Do not allow excessively long names either. */
  6535. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  6536. if (iscntrl(user[i])) {
  6537. return 0;
  6538. }
  6539. }
  6540. if (user[i]) {
  6541. return 0;
  6542. }
  6543. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  6544. if (iscntrl(domain[i])) {
  6545. return 0;
  6546. }
  6547. }
  6548. if (domain[i]) {
  6549. return 0;
  6550. }
  6551. /* The maximum length of the path to the password file is limited */
  6552. if ((strlen(fname) + 4) >= PATH_MAX) {
  6553. return 0;
  6554. }
  6555. /* Create a temporary file name. Length has been checked before. */
  6556. strcpy(tmp, fname);
  6557. strcat(tmp, ".tmp");
  6558. /* Create the file if does not exist */
  6559. /* Use of fopen here is OK, since fname is only ASCII */
  6560. if ((fp = fopen(fname, "a+")) != NULL) {
  6561. (void)fclose(fp);
  6562. }
  6563. /* Open the given file and temporary file */
  6564. if ((fp = fopen(fname, "r")) == NULL) {
  6565. return 0;
  6566. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  6567. fclose(fp);
  6568. return 0;
  6569. }
  6570. /* Copy the stuff to temporary file */
  6571. while (fgets(line, sizeof(line), fp) != NULL) {
  6572. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  6573. continue;
  6574. }
  6575. u[255] = 0;
  6576. d[255] = 0;
  6577. if (!strcmp(u, user) && !strcmp(d, domain)) {
  6578. found++;
  6579. if (pass != NULL) {
  6580. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  6581. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  6582. }
  6583. } else {
  6584. fprintf(fp2, "%s", line);
  6585. }
  6586. }
  6587. /* If new user, just add it */
  6588. if (!found && (pass != NULL)) {
  6589. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  6590. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  6591. }
  6592. /* Close files */
  6593. fclose(fp);
  6594. fclose(fp2);
  6595. /* Put the temp file in place of real file */
  6596. IGNORE_UNUSED_RESULT(remove(fname));
  6597. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  6598. return 1;
  6599. }
  6600. static int
  6601. is_valid_port(unsigned long port)
  6602. {
  6603. return (port <= 0xffff);
  6604. }
  6605. static int
  6606. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  6607. {
  6608. struct addrinfo hints, *res, *ressave;
  6609. int func_ret = 0;
  6610. int gai_ret;
  6611. memset(&hints, 0, sizeof(struct addrinfo));
  6612. hints.ai_family = af;
  6613. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  6614. if (gai_ret != 0) {
  6615. /* gai_strerror could be used to convert gai_ret to a string */
  6616. /* POSIX return values: see
  6617. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  6618. */
  6619. /* Windows return values: see
  6620. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  6621. */
  6622. return 0;
  6623. }
  6624. ressave = res;
  6625. while (res) {
  6626. if (dstlen >= (size_t)res->ai_addrlen) {
  6627. memcpy(dst, res->ai_addr, res->ai_addrlen);
  6628. func_ret = 1;
  6629. }
  6630. res = res->ai_next;
  6631. }
  6632. freeaddrinfo(ressave);
  6633. return func_ret;
  6634. }
  6635. static int
  6636. connect_socket(struct mg_context *ctx /* may be NULL */,
  6637. const char *host,
  6638. int port,
  6639. int use_ssl,
  6640. char *ebuf,
  6641. size_t ebuf_len,
  6642. SOCKET *sock /* output: socket, must not be NULL */,
  6643. union usa *sa /* output: socket address, must not be NULL */
  6644. )
  6645. {
  6646. int ip_ver = 0;
  6647. *sock = INVALID_SOCKET;
  6648. memset(sa, 0, sizeof(*sa));
  6649. if (ebuf_len > 0) {
  6650. *ebuf = 0;
  6651. }
  6652. if (host == NULL) {
  6653. mg_snprintf(NULL,
  6654. NULL, /* No truncation check for ebuf */
  6655. ebuf,
  6656. ebuf_len,
  6657. "%s",
  6658. "NULL host");
  6659. return 0;
  6660. }
  6661. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  6662. mg_snprintf(NULL,
  6663. NULL, /* No truncation check for ebuf */
  6664. ebuf,
  6665. ebuf_len,
  6666. "%s",
  6667. "invalid port");
  6668. return 0;
  6669. }
  6670. #if !defined(NO_SSL)
  6671. #if !defined(NO_SSL_DL)
  6672. #ifdef OPENSSL_API_1_1
  6673. if (use_ssl && (TLS_client_method == NULL)) {
  6674. mg_snprintf(NULL,
  6675. NULL, /* No truncation check for ebuf */
  6676. ebuf,
  6677. ebuf_len,
  6678. "%s",
  6679. "SSL is not initialized");
  6680. return 0;
  6681. }
  6682. #else
  6683. if (use_ssl && (SSLv23_client_method == NULL)) {
  6684. mg_snprintf(NULL,
  6685. NULL, /* No truncation check for ebuf */
  6686. ebuf,
  6687. ebuf_len,
  6688. "%s",
  6689. "SSL is not initialized");
  6690. return 0;
  6691. }
  6692. #endif /* OPENSSL_API_1_1 */
  6693. #else
  6694. (void)use_ssl;
  6695. #endif /* NO_SSL_DL */
  6696. #else
  6697. (void)use_ssl;
  6698. #endif /* !defined(NO_SSL) */
  6699. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  6700. sa->sin.sin_family = AF_INET;
  6701. sa->sin.sin_port = htons((uint16_t)port);
  6702. ip_ver = 4;
  6703. #ifdef USE_IPV6
  6704. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  6705. sa->sin6.sin6_family = AF_INET6;
  6706. sa->sin6.sin6_port = htons((uint16_t)port);
  6707. ip_ver = 6;
  6708. } else if (host[0] == '[') {
  6709. /* While getaddrinfo on Windows will work with [::1],
  6710. * getaddrinfo on Linux only works with ::1 (without []). */
  6711. size_t l = strlen(host + 1);
  6712. char *h = (l > 1) ? mg_strdup(host + 1) : NULL;
  6713. if (h) {
  6714. h[l - 1] = 0;
  6715. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  6716. sa->sin6.sin6_family = AF_INET6;
  6717. sa->sin6.sin6_port = htons((uint16_t)port);
  6718. ip_ver = 6;
  6719. }
  6720. mg_free(h);
  6721. }
  6722. #endif
  6723. }
  6724. if (ip_ver == 0) {
  6725. mg_snprintf(NULL,
  6726. NULL, /* No truncation check for ebuf */
  6727. ebuf,
  6728. ebuf_len,
  6729. "%s",
  6730. "host not found");
  6731. return 0;
  6732. }
  6733. if (ip_ver == 4) {
  6734. *sock = socket(PF_INET, SOCK_STREAM, 0);
  6735. }
  6736. #ifdef USE_IPV6
  6737. else if (ip_ver == 6) {
  6738. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  6739. }
  6740. #endif
  6741. if (*sock == INVALID_SOCKET) {
  6742. mg_snprintf(NULL,
  6743. NULL, /* No truncation check for ebuf */
  6744. ebuf,
  6745. ebuf_len,
  6746. "socket(): %s",
  6747. strerror(ERRNO));
  6748. return 0;
  6749. }
  6750. set_close_on_exec(*sock, fc(ctx));
  6751. if ((ip_ver == 4)
  6752. && (connect(*sock, (struct sockaddr *)&sa->sin, sizeof(sa->sin))
  6753. == 0)) {
  6754. /* connected with IPv4 */
  6755. set_blocking_mode(*sock, 0);
  6756. return 1;
  6757. }
  6758. #ifdef USE_IPV6
  6759. if ((ip_ver == 6)
  6760. && (connect(*sock, (struct sockaddr *)&sa->sin6, sizeof(sa->sin6))
  6761. == 0)) {
  6762. /* connected with IPv6 */
  6763. set_blocking_mode(*sock, 0);
  6764. return 1;
  6765. }
  6766. #endif
  6767. /* Not connected */
  6768. mg_snprintf(NULL,
  6769. NULL, /* No truncation check for ebuf */
  6770. ebuf,
  6771. ebuf_len,
  6772. "connect(%s:%d): %s",
  6773. host,
  6774. port,
  6775. strerror(ERRNO));
  6776. closesocket(*sock);
  6777. *sock = INVALID_SOCKET;
  6778. return 0;
  6779. }
  6780. int
  6781. mg_url_encode(const char *src, char *dst, size_t dst_len)
  6782. {
  6783. static const char *dont_escape = "._-$,;~()";
  6784. static const char *hex = "0123456789abcdef";
  6785. char *pos = dst;
  6786. const char *end = dst + dst_len - 1;
  6787. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  6788. if (isalnum(*(const unsigned char *)src)
  6789. || (strchr(dont_escape, *(const unsigned char *)src) != NULL)) {
  6790. *pos = *src;
  6791. } else if (pos + 2 < end) {
  6792. pos[0] = '%';
  6793. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  6794. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  6795. pos += 2;
  6796. } else {
  6797. break;
  6798. }
  6799. }
  6800. *pos = '\0';
  6801. return (*src == '\0') ? (int)(pos - dst) : -1;
  6802. }
  6803. /* Return 0 on success, non-zero if an error occurs. */
  6804. static int
  6805. print_dir_entry(struct de *de)
  6806. {
  6807. size_t hrefsize;
  6808. char *href;
  6809. char size[64], mod[64];
  6810. struct tm *tm;
  6811. hrefsize = PATH_MAX * 3; /* worst case */
  6812. href = mg_malloc(hrefsize);
  6813. if (href == NULL) {
  6814. return -1;
  6815. }
  6816. if (de->file.is_directory) {
  6817. mg_snprintf(de->conn,
  6818. NULL, /* Buffer is big enough */
  6819. size,
  6820. sizeof(size),
  6821. "%s",
  6822. "[DIRECTORY]");
  6823. } else {
  6824. /* We use (signed) cast below because MSVC 6 compiler cannot
  6825. * convert unsigned __int64 to double. Sigh. */
  6826. if (de->file.size < 1024) {
  6827. mg_snprintf(de->conn,
  6828. NULL, /* Buffer is big enough */
  6829. size,
  6830. sizeof(size),
  6831. "%d",
  6832. (int)de->file.size);
  6833. } else if (de->file.size < 0x100000) {
  6834. mg_snprintf(de->conn,
  6835. NULL, /* Buffer is big enough */
  6836. size,
  6837. sizeof(size),
  6838. "%.1fk",
  6839. (double)de->file.size / 1024.0);
  6840. } else if (de->file.size < 0x40000000) {
  6841. mg_snprintf(de->conn,
  6842. NULL, /* Buffer is big enough */
  6843. size,
  6844. sizeof(size),
  6845. "%.1fM",
  6846. (double)de->file.size / 1048576);
  6847. } else {
  6848. mg_snprintf(de->conn,
  6849. NULL, /* Buffer is big enough */
  6850. size,
  6851. sizeof(size),
  6852. "%.1fG",
  6853. (double)de->file.size / 1073741824);
  6854. }
  6855. }
  6856. /* Note: mg_snprintf will not cause a buffer overflow above.
  6857. * So, string truncation checks are not required here. */
  6858. tm = localtime(&de->file.last_modified);
  6859. if (tm != NULL) {
  6860. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  6861. } else {
  6862. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  6863. mod[sizeof(mod) - 1] = '\0';
  6864. }
  6865. mg_url_encode(de->file_name, href, hrefsize);
  6866. mg_printf(de->conn,
  6867. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  6868. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  6869. de->conn->request_info.local_uri,
  6870. href,
  6871. de->file.is_directory ? "/" : "",
  6872. de->file_name,
  6873. de->file.is_directory ? "/" : "",
  6874. mod,
  6875. size);
  6876. mg_free(href);
  6877. return 0;
  6878. }
  6879. /* This function is called from send_directory() and used for
  6880. * sorting directory entries by size, or name, or modification time.
  6881. * On windows, __cdecl specification is needed in case if project is built
  6882. * with __stdcall convention. qsort always requires __cdels callback. */
  6883. static int WINCDECL
  6884. compare_dir_entries(const void *p1, const void *p2)
  6885. {
  6886. if (p1 && p2) {
  6887. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  6888. const char *query_string = a->conn->request_info.query_string;
  6889. int cmp_result = 0;
  6890. if (query_string == NULL) {
  6891. query_string = "na";
  6892. }
  6893. if (a->file.is_directory && !b->file.is_directory) {
  6894. return -1; /* Always put directories on top */
  6895. } else if (!a->file.is_directory && b->file.is_directory) {
  6896. return 1; /* Always put directories on top */
  6897. } else if (*query_string == 'n') {
  6898. cmp_result = strcmp(a->file_name, b->file_name);
  6899. } else if (*query_string == 's') {
  6900. cmp_result = (a->file.size == b->file.size)
  6901. ? 0
  6902. : ((a->file.size > b->file.size) ? 1 : -1);
  6903. } else if (*query_string == 'd') {
  6904. cmp_result =
  6905. (a->file.last_modified == b->file.last_modified)
  6906. ? 0
  6907. : ((a->file.last_modified > b->file.last_modified) ? 1
  6908. : -1);
  6909. }
  6910. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  6911. }
  6912. return 0;
  6913. }
  6914. static int
  6915. must_hide_file(struct mg_connection *conn, const char *path)
  6916. {
  6917. if (conn && conn->ctx) {
  6918. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  6919. const char *pattern = conn->ctx->config[HIDE_FILES];
  6920. return (match_prefix(pw_pattern, strlen(pw_pattern), path) > 0)
  6921. || ((pattern != NULL)
  6922. && (match_prefix(pattern, strlen(pattern), path) > 0));
  6923. }
  6924. return 0;
  6925. }
  6926. static int
  6927. scan_directory(struct mg_connection *conn,
  6928. const char *dir,
  6929. void *data,
  6930. int (*cb)(struct de *, void *))
  6931. {
  6932. char path[PATH_MAX];
  6933. struct dirent *dp;
  6934. DIR *dirp;
  6935. struct de de;
  6936. int truncated;
  6937. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  6938. return 0;
  6939. } else {
  6940. de.conn = conn;
  6941. while ((dp = mg_readdir(dirp)) != NULL) {
  6942. /* Do not show current dir and hidden files */
  6943. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  6944. || must_hide_file(conn, dp->d_name)) {
  6945. continue;
  6946. }
  6947. mg_snprintf(
  6948. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  6949. /* If we don't memset stat structure to zero, mtime will have
  6950. * garbage and strftime() will segfault later on in
  6951. * print_dir_entry(). memset is required only if mg_stat()
  6952. * fails. For more details, see
  6953. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  6954. memset(&de.file, 0, sizeof(de.file));
  6955. if (truncated) {
  6956. /* If the path is not complete, skip processing. */
  6957. continue;
  6958. }
  6959. if (!mg_stat(conn, path, &de.file)) {
  6960. mg_cry(conn,
  6961. "%s: mg_stat(%s) failed: %s",
  6962. __func__,
  6963. path,
  6964. strerror(ERRNO));
  6965. }
  6966. de.file_name = dp->d_name;
  6967. cb(&de, data);
  6968. }
  6969. (void)mg_closedir(dirp);
  6970. }
  6971. return 1;
  6972. }
  6973. #if !defined(NO_FILES)
  6974. static int
  6975. remove_directory(struct mg_connection *conn, const char *dir)
  6976. {
  6977. char path[PATH_MAX];
  6978. struct dirent *dp;
  6979. DIR *dirp;
  6980. struct de de;
  6981. int truncated;
  6982. int ok = 1;
  6983. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  6984. return 0;
  6985. } else {
  6986. de.conn = conn;
  6987. while ((dp = mg_readdir(dirp)) != NULL) {
  6988. /* Do not show current dir (but show hidden files as they will
  6989. * also be removed) */
  6990. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  6991. continue;
  6992. }
  6993. mg_snprintf(
  6994. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  6995. /* If we don't memset stat structure to zero, mtime will have
  6996. * garbage and strftime() will segfault later on in
  6997. * print_dir_entry(). memset is required only if mg_stat()
  6998. * fails. For more details, see
  6999. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  7000. memset(&de.file, 0, sizeof(de.file));
  7001. if (truncated) {
  7002. /* Do not delete anything shorter */
  7003. ok = 0;
  7004. continue;
  7005. }
  7006. if (!mg_stat(conn, path, &de.file)) {
  7007. mg_cry(conn,
  7008. "%s: mg_stat(%s) failed: %s",
  7009. __func__,
  7010. path,
  7011. strerror(ERRNO));
  7012. ok = 0;
  7013. }
  7014. if (de.file.is_directory) {
  7015. if (remove_directory(conn, path) == 0) {
  7016. ok = 0;
  7017. }
  7018. } else {
  7019. /* This will fail file is the file is in memory */
  7020. if (mg_remove(conn, path) == 0) {
  7021. ok = 0;
  7022. }
  7023. }
  7024. }
  7025. (void)mg_closedir(dirp);
  7026. IGNORE_UNUSED_RESULT(rmdir(dir));
  7027. }
  7028. return ok;
  7029. }
  7030. #endif
  7031. struct dir_scan_data {
  7032. struct de *entries;
  7033. unsigned int num_entries;
  7034. unsigned int arr_size;
  7035. };
  7036. /* Behaves like realloc(), but frees original pointer on failure */
  7037. static void *
  7038. realloc2(void *ptr, size_t size)
  7039. {
  7040. void *new_ptr = mg_realloc(ptr, size);
  7041. if (new_ptr == NULL) {
  7042. mg_free(ptr);
  7043. }
  7044. return new_ptr;
  7045. }
  7046. static int
  7047. dir_scan_callback(struct de *de, void *data)
  7048. {
  7049. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  7050. if ((dsd->entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  7051. dsd->arr_size *= 2;
  7052. dsd->entries =
  7053. (struct de *)realloc2(dsd->entries,
  7054. dsd->arr_size * sizeof(dsd->entries[0]));
  7055. }
  7056. if (dsd->entries == NULL) {
  7057. /* TODO(lsm, low): propagate an error to the caller */
  7058. dsd->num_entries = 0;
  7059. } else {
  7060. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  7061. dsd->entries[dsd->num_entries].file = de->file;
  7062. dsd->entries[dsd->num_entries].conn = de->conn;
  7063. dsd->num_entries++;
  7064. }
  7065. return 0;
  7066. }
  7067. static void
  7068. handle_directory_request(struct mg_connection *conn, const char *dir)
  7069. {
  7070. unsigned int i;
  7071. int sort_direction;
  7072. struct dir_scan_data data = {NULL, 0, 128};
  7073. char date[64];
  7074. time_t curtime = time(NULL);
  7075. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  7076. mg_send_http_error(conn,
  7077. 500,
  7078. "Error: Cannot open directory\nopendir(%s): %s",
  7079. dir,
  7080. strerror(ERRNO));
  7081. return;
  7082. }
  7083. gmt_time_string(date, sizeof(date), &curtime);
  7084. if (!conn) {
  7085. return;
  7086. }
  7087. sort_direction = ((conn->request_info.query_string != NULL)
  7088. && (conn->request_info.query_string[1] == 'd'))
  7089. ? 'a'
  7090. : 'd';
  7091. conn->must_close = 1;
  7092. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  7093. send_static_cache_header(conn);
  7094. send_additional_header(conn);
  7095. mg_printf(conn,
  7096. "Date: %s\r\n"
  7097. "Connection: close\r\n"
  7098. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  7099. date);
  7100. mg_printf(conn,
  7101. "<html><head><title>Index of %s</title>"
  7102. "<style>th {text-align: left;}</style></head>"
  7103. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  7104. "<tr><th><a href=\"?n%c\">Name</a></th>"
  7105. "<th><a href=\"?d%c\">Modified</a></th>"
  7106. "<th><a href=\"?s%c\">Size</a></th></tr>"
  7107. "<tr><td colspan=\"3\"><hr></td></tr>",
  7108. conn->request_info.local_uri,
  7109. conn->request_info.local_uri,
  7110. sort_direction,
  7111. sort_direction,
  7112. sort_direction);
  7113. /* Print first entry - link to a parent directory */
  7114. mg_printf(conn,
  7115. "<tr><td><a href=\"%s%s\">%s</a></td>"
  7116. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  7117. conn->request_info.local_uri,
  7118. "..",
  7119. "Parent directory",
  7120. "-",
  7121. "-");
  7122. /* Sort and print directory entries */
  7123. if (data.entries != NULL) {
  7124. qsort(data.entries,
  7125. (size_t)data.num_entries,
  7126. sizeof(data.entries[0]),
  7127. compare_dir_entries);
  7128. for (i = 0; i < data.num_entries; i++) {
  7129. print_dir_entry(&data.entries[i]);
  7130. mg_free(data.entries[i].file_name);
  7131. }
  7132. mg_free(data.entries);
  7133. }
  7134. mg_printf(conn, "%s", "</table></body></html>");
  7135. conn->status_code = 200;
  7136. }
  7137. /* Send len bytes from the opened file to the client. */
  7138. static void
  7139. send_file_data(struct mg_connection *conn,
  7140. struct mg_file *filep,
  7141. int64_t offset,
  7142. int64_t len)
  7143. {
  7144. char buf[MG_BUF_LEN];
  7145. int to_read, num_read, num_written;
  7146. int64_t size;
  7147. if (!filep || !conn) {
  7148. return;
  7149. }
  7150. /* Sanity check the offset */
  7151. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  7152. : (int64_t)(filep->stat.size);
  7153. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  7154. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  7155. /* file stored in memory */
  7156. if (len > size - offset) {
  7157. len = size - offset;
  7158. }
  7159. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  7160. } else if (len > 0 && filep->access.fp != NULL) {
  7161. /* file stored on disk */
  7162. #if defined(__linux__)
  7163. /* sendfile is only available for Linux */
  7164. if ((conn->ssl == 0) && (conn->throttle == 0)
  7165. && (!mg_strcasecmp(conn->ctx->config[ALLOW_SENDFILE_CALL],
  7166. "yes"))) {
  7167. off_t sf_offs = (off_t)offset;
  7168. ssize_t sf_sent;
  7169. int sf_file = fileno(filep->access.fp);
  7170. int loop_cnt = 0;
  7171. do {
  7172. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  7173. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  7174. size_t sf_tosend =
  7175. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  7176. sf_sent =
  7177. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  7178. if (sf_sent > 0) {
  7179. len -= sf_sent;
  7180. offset += sf_sent;
  7181. } else if (loop_cnt == 0) {
  7182. /* This file can not be sent using sendfile.
  7183. * This might be the case for pseudo-files in the
  7184. * /sys/ and /proc/ file system.
  7185. * Use the regular user mode copy code instead. */
  7186. break;
  7187. } else if (sf_sent == 0) {
  7188. /* No error, but 0 bytes sent. May be EOF? */
  7189. return;
  7190. }
  7191. loop_cnt++;
  7192. } while ((len > 0) && (sf_sent >= 0));
  7193. if (sf_sent > 0) {
  7194. return; /* OK */
  7195. }
  7196. /* sf_sent<0 means error, thus fall back to the classic way */
  7197. /* This is always the case, if sf_file is not a "normal" file,
  7198. * e.g., for sending data from the output of a CGI process. */
  7199. offset = (int64_t)sf_offs;
  7200. }
  7201. #endif
  7202. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  7203. mg_cry(conn, "%s: fseeko() failed: %s", __func__, strerror(ERRNO));
  7204. mg_send_http_error(
  7205. conn,
  7206. 500,
  7207. "%s",
  7208. "Error: Unable to access file at requested position.");
  7209. } else {
  7210. while (len > 0) {
  7211. /* Calculate how much to read from the file in the buffer */
  7212. to_read = sizeof(buf);
  7213. if ((int64_t)to_read > len) {
  7214. to_read = (int)len;
  7215. }
  7216. /* Read from file, exit the loop on error */
  7217. if ((num_read =
  7218. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  7219. <= 0) {
  7220. break;
  7221. }
  7222. /* Send read bytes to the client, exit the loop on error */
  7223. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  7224. != num_read) {
  7225. break;
  7226. }
  7227. /* Both read and were successful, adjust counters */
  7228. len -= num_written;
  7229. }
  7230. }
  7231. }
  7232. }
  7233. static int
  7234. parse_range_header(const char *header, int64_t *a, int64_t *b)
  7235. {
  7236. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  7237. }
  7238. static void
  7239. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  7240. {
  7241. if ((filestat != NULL) && (buf != NULL)) {
  7242. mg_snprintf(NULL,
  7243. NULL, /* All calls to construct_etag use 64 byte buffer */
  7244. buf,
  7245. buf_len,
  7246. "\"%lx.%" INT64_FMT "\"",
  7247. (unsigned long)filestat->last_modified,
  7248. filestat->size);
  7249. }
  7250. }
  7251. static void
  7252. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  7253. {
  7254. if (filep != NULL && filep->fp != NULL) {
  7255. #ifdef _WIN32
  7256. (void)conn; /* Unused. */
  7257. #else
  7258. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  7259. mg_cry(conn,
  7260. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  7261. __func__,
  7262. strerror(ERRNO));
  7263. }
  7264. #endif
  7265. }
  7266. }
  7267. static void
  7268. handle_static_file_request(struct mg_connection *conn,
  7269. const char *path,
  7270. struct mg_file *filep,
  7271. const char *mime_type,
  7272. const char *additional_headers)
  7273. {
  7274. char date[64], lm[64], etag[64];
  7275. char range[128]; /* large enough, so there will be no overflow */
  7276. const char *msg = "OK", *hdr;
  7277. time_t curtime = time(NULL);
  7278. int64_t cl, r1, r2;
  7279. struct vec mime_vec;
  7280. int n, truncated;
  7281. char gz_path[PATH_MAX];
  7282. const char *encoding = "";
  7283. const char *cors1, *cors2, *cors3;
  7284. if ((conn == NULL) || (conn->ctx == NULL) || (filep == NULL)) {
  7285. return;
  7286. }
  7287. if (mime_type == NULL) {
  7288. get_mime_type(conn->ctx, path, &mime_vec);
  7289. } else {
  7290. mime_vec.ptr = mime_type;
  7291. mime_vec.len = strlen(mime_type);
  7292. }
  7293. if (filep->stat.size > INT64_MAX) {
  7294. mg_send_http_error(conn,
  7295. 500,
  7296. "Error: File size is too large to send\n%" INT64_FMT,
  7297. filep->stat.size);
  7298. return;
  7299. }
  7300. cl = (int64_t)filep->stat.size;
  7301. conn->status_code = 200;
  7302. range[0] = '\0';
  7303. /* if this file is in fact a pre-gzipped file, rewrite its filename
  7304. * it's important to rewrite the filename after resolving
  7305. * the mime type from it, to preserve the actual file's type */
  7306. if (filep->stat.is_gzipped) {
  7307. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  7308. if (truncated) {
  7309. mg_send_http_error(conn,
  7310. 500,
  7311. "Error: Path of zipped file too long (%s)",
  7312. path);
  7313. return;
  7314. }
  7315. path = gz_path;
  7316. encoding = "Content-Encoding: gzip\r\n";
  7317. }
  7318. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  7319. mg_send_http_error(conn,
  7320. 500,
  7321. "Error: Cannot open file\nfopen(%s): %s",
  7322. path,
  7323. strerror(ERRNO));
  7324. return;
  7325. }
  7326. fclose_on_exec(&filep->access, conn);
  7327. /* If Range: header specified, act accordingly */
  7328. r1 = r2 = 0;
  7329. hdr = mg_get_header(conn, "Range");
  7330. if ((hdr != NULL) && ((n = parse_range_header(hdr, &r1, &r2)) > 0)
  7331. && (r1 >= 0) && (r2 >= 0)) {
  7332. /* actually, range requests don't play well with a pre-gzipped
  7333. * file (since the range is specified in the uncompressed space) */
  7334. if (filep->stat.is_gzipped) {
  7335. mg_send_http_error(
  7336. conn,
  7337. 416, /* 416 = Range Not Satisfiable */
  7338. "%s",
  7339. "Error: Range requests in gzipped files are not supported");
  7340. (void)mg_fclose(
  7341. &filep->access); /* ignore error on read only file */
  7342. return;
  7343. }
  7344. conn->status_code = 206;
  7345. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  7346. mg_snprintf(conn,
  7347. NULL, /* range buffer is big enough */
  7348. range,
  7349. sizeof(range),
  7350. "Content-Range: bytes "
  7351. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  7352. r1,
  7353. r1 + cl - 1,
  7354. filep->stat.size);
  7355. msg = "Partial Content";
  7356. }
  7357. hdr = mg_get_header(conn, "Origin");
  7358. if (hdr) {
  7359. /* Cross-origin resource sharing (CORS), see
  7360. * http://www.html5rocks.com/en/tutorials/cors/,
  7361. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  7362. * -
  7363. * preflight is not supported for files. */
  7364. cors1 = "Access-Control-Allow-Origin: ";
  7365. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  7366. cors3 = "\r\n";
  7367. } else {
  7368. cors1 = cors2 = cors3 = "";
  7369. }
  7370. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC, according
  7371. * to
  7372. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  7373. gmt_time_string(date, sizeof(date), &curtime);
  7374. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  7375. construct_etag(etag, sizeof(etag), &filep->stat);
  7376. (void)mg_printf(conn,
  7377. "HTTP/1.1 %d %s\r\n"
  7378. "%s%s%s"
  7379. "Date: %s\r\n",
  7380. conn->status_code,
  7381. msg,
  7382. cors1,
  7383. cors2,
  7384. cors3,
  7385. date);
  7386. send_static_cache_header(conn);
  7387. send_additional_header(conn);
  7388. (void)mg_printf(conn,
  7389. "Last-Modified: %s\r\n"
  7390. "Etag: %s\r\n"
  7391. "Content-Type: %.*s\r\n"
  7392. "Content-Length: %" INT64_FMT "\r\n"
  7393. "Connection: %s\r\n"
  7394. "Accept-Ranges: bytes\r\n"
  7395. "%s%s",
  7396. lm,
  7397. etag,
  7398. (int)mime_vec.len,
  7399. mime_vec.ptr,
  7400. cl,
  7401. suggest_connection_header(conn),
  7402. range,
  7403. encoding);
  7404. /* The previous code must not add any header starting with X- to make
  7405. * sure no one of the additional_headers is included twice */
  7406. if (additional_headers != NULL) {
  7407. (void)mg_printf(conn,
  7408. "%.*s\r\n\r\n",
  7409. (int)strlen(additional_headers),
  7410. additional_headers);
  7411. } else {
  7412. (void)mg_printf(conn, "\r\n");
  7413. }
  7414. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  7415. send_file_data(conn, filep, r1, cl);
  7416. }
  7417. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  7418. }
  7419. #if !defined(NO_CACHING)
  7420. static void
  7421. handle_not_modified_static_file_request(struct mg_connection *conn,
  7422. struct mg_file *filep)
  7423. {
  7424. char date[64], lm[64], etag[64];
  7425. time_t curtime = time(NULL);
  7426. if ((conn == NULL) || (filep == NULL)) {
  7427. return;
  7428. }
  7429. conn->status_code = 304;
  7430. gmt_time_string(date, sizeof(date), &curtime);
  7431. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  7432. construct_etag(etag, sizeof(etag), &filep->stat);
  7433. (void)mg_printf(conn,
  7434. "HTTP/1.1 %d %s\r\n"
  7435. "Date: %s\r\n",
  7436. conn->status_code,
  7437. mg_get_response_code_text(conn, conn->status_code),
  7438. date);
  7439. send_static_cache_header(conn);
  7440. send_additional_header(conn);
  7441. (void)mg_printf(conn,
  7442. "Last-Modified: %s\r\n"
  7443. "Etag: %s\r\n"
  7444. "Connection: %s\r\n"
  7445. "\r\n",
  7446. lm,
  7447. etag,
  7448. suggest_connection_header(conn));
  7449. }
  7450. #endif
  7451. void
  7452. mg_send_file(struct mg_connection *conn, const char *path)
  7453. {
  7454. mg_send_mime_file(conn, path, NULL);
  7455. }
  7456. void
  7457. mg_send_mime_file(struct mg_connection *conn,
  7458. const char *path,
  7459. const char *mime_type)
  7460. {
  7461. mg_send_mime_file2(conn, path, mime_type, NULL);
  7462. }
  7463. void
  7464. mg_send_mime_file2(struct mg_connection *conn,
  7465. const char *path,
  7466. const char *mime_type,
  7467. const char *additional_headers)
  7468. {
  7469. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7470. if (mg_stat(conn, path, &file.stat)) {
  7471. if (file.stat.is_directory) {
  7472. if (!conn) {
  7473. return;
  7474. }
  7475. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  7476. "yes")) {
  7477. handle_directory_request(conn, path);
  7478. } else {
  7479. mg_send_http_error(conn,
  7480. 403,
  7481. "%s",
  7482. "Error: Directory listing denied");
  7483. }
  7484. } else {
  7485. handle_static_file_request(
  7486. conn, path, &file, mime_type, additional_headers);
  7487. }
  7488. } else {
  7489. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  7490. }
  7491. }
  7492. /* For a given PUT path, create all intermediate subdirectories.
  7493. * Return 0 if the path itself is a directory.
  7494. * Return 1 if the path leads to a file.
  7495. * Return -1 for if the path is too long.
  7496. * Return -2 if path can not be created.
  7497. */
  7498. static int
  7499. put_dir(struct mg_connection *conn, const char *path)
  7500. {
  7501. char buf[PATH_MAX];
  7502. const char *s, *p;
  7503. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7504. size_t len;
  7505. int res = 1;
  7506. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  7507. len = (size_t)(p - path);
  7508. if (len >= sizeof(buf)) {
  7509. /* path too long */
  7510. res = -1;
  7511. break;
  7512. }
  7513. memcpy(buf, path, len);
  7514. buf[len] = '\0';
  7515. /* Try to create intermediate directory */
  7516. DEBUG_TRACE("mkdir(%s)", buf);
  7517. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  7518. /* path does not exixt and can not be created */
  7519. res = -2;
  7520. break;
  7521. }
  7522. /* Is path itself a directory? */
  7523. if (p[1] == '\0') {
  7524. res = 0;
  7525. }
  7526. }
  7527. return res;
  7528. }
  7529. static void
  7530. remove_bad_file(const struct mg_connection *conn, const char *path)
  7531. {
  7532. int r = mg_remove(conn, path);
  7533. if (r != 0) {
  7534. mg_cry(conn, "%s: Cannot remove invalid file %s", __func__, path);
  7535. }
  7536. }
  7537. long long
  7538. mg_store_body(struct mg_connection *conn, const char *path)
  7539. {
  7540. char buf[MG_BUF_LEN];
  7541. long long len = 0;
  7542. int ret, n;
  7543. struct mg_file fi;
  7544. if (conn->consumed_content != 0) {
  7545. mg_cry(conn, "%s: Contents already consumed", __func__);
  7546. return -11;
  7547. }
  7548. ret = put_dir(conn, path);
  7549. if (ret < 0) {
  7550. /* -1 for path too long,
  7551. * -2 for path can not be created. */
  7552. return ret;
  7553. }
  7554. if (ret != 1) {
  7555. /* Return 0 means, path itself is a directory. */
  7556. return 0;
  7557. }
  7558. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  7559. return -12;
  7560. }
  7561. ret = mg_read(conn, buf, sizeof(buf));
  7562. while (ret > 0) {
  7563. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  7564. if (n != ret) {
  7565. (void)mg_fclose(
  7566. &fi.access); /* File is bad and will be removed anyway. */
  7567. remove_bad_file(conn, path);
  7568. return -13;
  7569. }
  7570. len += ret;
  7571. ret = mg_read(conn, buf, sizeof(buf));
  7572. }
  7573. /* File is open for writing. If fclose fails, there was probably an
  7574. * error flushing the buffer to disk, so the file on disk might be
  7575. * broken. Delete it and return an error to the caller. */
  7576. if (mg_fclose(&fi.access) != 0) {
  7577. remove_bad_file(conn, path);
  7578. return -14;
  7579. }
  7580. return len;
  7581. }
  7582. /* Parse a buffer:
  7583. * Forward the string pointer till the end of a word, then
  7584. * terminate it and forward till the begin of the next word.
  7585. */
  7586. static int
  7587. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  7588. {
  7589. /* Forward until a space is found - use isgraph here */
  7590. /* See http://www.cplusplus.com/reference/cctype/ */
  7591. while (isgraph(**ppw)) {
  7592. (*ppw)++;
  7593. }
  7594. /* Check end of word */
  7595. if (eol) {
  7596. /* must be a end of line */
  7597. if ((**ppw != '\r') && (**ppw != '\n')) {
  7598. return -1;
  7599. }
  7600. } else {
  7601. /* must be a end of a word, but not a line */
  7602. if (**ppw != ' ') {
  7603. return -1;
  7604. }
  7605. }
  7606. /* Terminate and forward to the next word */
  7607. do {
  7608. **ppw = 0;
  7609. (*ppw)++;
  7610. } while ((**ppw) && isspace(**ppw));
  7611. /* Check after term */
  7612. if (!eol) {
  7613. /* if it's not the end of line, there must be a next word */
  7614. if (!isgraph(**ppw)) {
  7615. return -1;
  7616. }
  7617. }
  7618. /* ok */
  7619. return 1;
  7620. }
  7621. /* Parse HTTP headers from the given buffer, advance buf pointer
  7622. * to the point where parsing stopped.
  7623. * All parameters must be valid pointers (not NULL).
  7624. * Return <0 on error. */
  7625. static int
  7626. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  7627. {
  7628. int i;
  7629. int num_headers = 0;
  7630. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  7631. char *dp = *buf;
  7632. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  7633. dp++;
  7634. }
  7635. if (dp == *buf) {
  7636. /* End of headers reached. */
  7637. break;
  7638. }
  7639. if (*dp != ':') {
  7640. /* This is not a valid field. */
  7641. return -1;
  7642. }
  7643. /* End of header key (*dp == ':') */
  7644. /* Truncate here and set the key name */
  7645. *dp = 0;
  7646. hdr[i].name = *buf;
  7647. do {
  7648. dp++;
  7649. } while (*dp == ' ');
  7650. /* The rest of the line is the value */
  7651. hdr[i].value = dp;
  7652. *buf = dp + strcspn(dp, "\r\n");
  7653. if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) {
  7654. *buf = NULL;
  7655. }
  7656. num_headers = i + 1;
  7657. if (*buf) {
  7658. (*buf)[0] = 0;
  7659. (*buf)[1] = 0;
  7660. *buf += 2;
  7661. } else {
  7662. *buf = dp;
  7663. break;
  7664. }
  7665. if ((*buf)[0] == '\r') {
  7666. /* This is the end of the header */
  7667. break;
  7668. }
  7669. }
  7670. return num_headers;
  7671. }
  7672. static int
  7673. is_valid_http_method(const char *method)
  7674. {
  7675. /* Check if the method is known to the server. The list of all known
  7676. * HTTP methods can be found here at
  7677. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  7678. */
  7679. return !strcmp(method, "GET") /* HTTP (RFC 2616) */
  7680. || !strcmp(method, "POST") /* HTTP (RFC 2616) */
  7681. || !strcmp(method, "HEAD") /* HTTP (RFC 2616) */
  7682. || !strcmp(method, "PUT") /* HTTP (RFC 2616) */
  7683. || !strcmp(method, "DELETE") /* HTTP (RFC 2616) */
  7684. || !strcmp(method, "OPTIONS") /* HTTP (RFC 2616) */
  7685. /* TRACE method (RFC 2616) is not supported for security reasons
  7686. */
  7687. || !strcmp(method, "CONNECT") /* HTTP (RFC 2616) */
  7688. || !strcmp(method, "PROPFIND") /* WEBDAV (RFC 2518) */
  7689. || !strcmp(method, "MKCOL") /* WEBDAV (RFC 2518) */
  7690. /* Unsupported WEBDAV Methods: */
  7691. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  7692. /* + 11 methods from RFC 3253 */
  7693. /* ORDERPATCH (RFC 3648) */
  7694. /* ACL (RFC 3744) */
  7695. /* SEARCH (RFC 5323) */
  7696. /* + MicroSoft extensions
  7697. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  7698. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  7699. || !strcmp(method, "PATCH") /* PATCH method (RFC 5789) */
  7700. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  7701. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  7702. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  7703. * to be useful for REST in case a "GET request with body" is
  7704. * required. */
  7705. || !strcmp(method, "REPORT") /* REPORT method (RFC 3253) */
  7706. ;
  7707. }
  7708. /* Parse HTTP request, fill in mg_request_info structure.
  7709. * This function modifies the buffer by NUL-terminating
  7710. * HTTP request components, header names and header values.
  7711. * Parameters:
  7712. * buf (in/out): pointer to the HTTP header to parse and split
  7713. * len (in): length of HTTP header buffer
  7714. * re (out): parsed header as mg_request_info
  7715. * buf and ri must be valid pointers (not NULL), len>0.
  7716. * Returns <0 on error. */
  7717. static int
  7718. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  7719. {
  7720. int request_length;
  7721. int init_skip = 0;
  7722. /* Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_addr,
  7723. * remote_port */
  7724. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  7725. NULL;
  7726. ri->num_headers = 0;
  7727. /* RFC says that all initial whitespaces should be ingored */
  7728. /* This included all leading \r and \n (isspace) */
  7729. /* See table: http://www.cplusplus.com/reference/cctype/ */
  7730. while ((len > 0) && isspace(*(unsigned char *)buf)) {
  7731. buf++;
  7732. len--;
  7733. init_skip++;
  7734. }
  7735. if (len == 0) {
  7736. /* Incomplete request */
  7737. return 0;
  7738. }
  7739. /* Control characters are not allowed, including zero */
  7740. if (iscntrl(*(unsigned char *)buf)) {
  7741. return -1;
  7742. }
  7743. /* Find end of HTTP header */
  7744. request_length = get_http_header_len(buf, len);
  7745. if (request_length <= 0) {
  7746. return request_length;
  7747. }
  7748. buf[request_length - 1] = '\0';
  7749. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  7750. return -1;
  7751. }
  7752. /* The first word has to be the HTTP method */
  7753. ri->request_method = buf;
  7754. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  7755. return -1;
  7756. }
  7757. /* Check for a valid http method */
  7758. if (!is_valid_http_method(ri->request_method)) {
  7759. return -1;
  7760. }
  7761. /* The second word is the URI */
  7762. ri->request_uri = buf;
  7763. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  7764. return -1;
  7765. }
  7766. /* Next would be the HTTP version */
  7767. ri->http_version = buf;
  7768. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  7769. return -1;
  7770. }
  7771. /* Check for a valid HTTP version key */
  7772. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  7773. /* Invalid request */
  7774. return -1;
  7775. }
  7776. ri->http_version += 5;
  7777. /* Parse all HTTP headers */
  7778. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  7779. if (ri->num_headers < 0) {
  7780. /* Error while parsing headers */
  7781. return -1;
  7782. }
  7783. return request_length + init_skip;
  7784. }
  7785. static int
  7786. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  7787. {
  7788. int response_length;
  7789. int init_skip = 0;
  7790. char *tmp, *tmp2;
  7791. long l;
  7792. /* Initialize elements. */
  7793. ri->http_version = ri->status_text = NULL;
  7794. ri->num_headers = ri->status_code = 0;
  7795. /* RFC says that all initial whitespaces should be ingored */
  7796. /* This included all leading \r and \n (isspace) */
  7797. /* See table: http://www.cplusplus.com/reference/cctype/ */
  7798. while ((len > 0) && isspace(*(unsigned char *)buf)) {
  7799. buf++;
  7800. len--;
  7801. init_skip++;
  7802. }
  7803. if (len == 0) {
  7804. /* Incomplete request */
  7805. return 0;
  7806. }
  7807. /* Control characters are not allowed, including zero */
  7808. if (iscntrl(*(unsigned char *)buf)) {
  7809. return -1;
  7810. }
  7811. /* Find end of HTTP header */
  7812. response_length = get_http_header_len(buf, len);
  7813. if (response_length <= 0) {
  7814. return response_length;
  7815. }
  7816. buf[response_length - 1] = '\0';
  7817. /* TODO: Define mg_response_info and implement parsing */
  7818. (void)buf;
  7819. (void)len;
  7820. (void)ri;
  7821. /* RFC says that all initial whitespaces should be ingored */
  7822. while ((*buf != '\0') && isspace(*(unsigned char *)buf)) {
  7823. buf++;
  7824. }
  7825. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  7826. return -1;
  7827. }
  7828. /* The first word is the HTTP version */
  7829. /* Check for a valid HTTP version key */
  7830. if (strncmp(buf, "HTTP/", 5) != 0) {
  7831. /* Invalid request */
  7832. return -1;
  7833. }
  7834. buf += 5;
  7835. if (!isgraph(buf[0])) {
  7836. /* Invalid request */
  7837. return -1;
  7838. }
  7839. ri->http_version = buf;
  7840. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  7841. return -1;
  7842. }
  7843. /* The second word is the status as a number */
  7844. tmp = buf;
  7845. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  7846. return -1;
  7847. }
  7848. l = strtol(tmp, &tmp2, 10);
  7849. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  7850. /* Everything else but a 3 digit code is invalid */
  7851. return -1;
  7852. }
  7853. ri->status_code = (int)l;
  7854. /* The rest of the line is the status text */
  7855. ri->status_text = buf;
  7856. /* Find end of status text */
  7857. /* isgraph or isspace = isprint */
  7858. while (isprint(*buf)) {
  7859. buf++;
  7860. }
  7861. if ((*buf != '\r') && (*buf != '\n')) {
  7862. return -1;
  7863. }
  7864. /* Terminate string and forward buf to next line */
  7865. do {
  7866. *buf = 0;
  7867. buf++;
  7868. } while ((*buf) && isspace(*buf));
  7869. /* Parse all HTTP headers */
  7870. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  7871. if (ri->num_headers < 0) {
  7872. /* Error while parsing headers */
  7873. return -1;
  7874. }
  7875. return response_length + init_skip;
  7876. }
  7877. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  7878. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  7879. * buffer (which marks the end of HTTP request). Buffer buf may already
  7880. * have some data. The length of the data is stored in nread.
  7881. * Upon every read operation, increase nread by the number of bytes read. */
  7882. static int
  7883. read_message(FILE *fp,
  7884. struct mg_connection *conn,
  7885. char *buf,
  7886. int bufsiz,
  7887. int *nread)
  7888. {
  7889. int request_len, n = 0;
  7890. struct timespec last_action_time;
  7891. double request_timeout;
  7892. if (!conn) {
  7893. return 0;
  7894. }
  7895. memset(&last_action_time, 0, sizeof(last_action_time));
  7896. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  7897. /* value of request_timeout is in seconds, config in milliseconds */
  7898. request_timeout = atof(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  7899. } else {
  7900. request_timeout = -1.0;
  7901. }
  7902. if (conn->handled_requests > 0) {
  7903. if (conn->ctx->config[KEEP_ALIVE_TIMEOUT]) {
  7904. request_timeout =
  7905. atof(conn->ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  7906. }
  7907. }
  7908. request_len = get_http_header_len(buf, *nread);
  7909. /* first time reading from this connection */
  7910. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  7911. while (request_len == 0) {
  7912. /* Full request not yet received */
  7913. if (conn->ctx->stop_flag != 0) {
  7914. /* Server is to be stopped. */
  7915. return -1;
  7916. }
  7917. if (*nread >= bufsiz) {
  7918. /* Request too long */
  7919. return -2;
  7920. }
  7921. n = pull_inner(
  7922. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  7923. if (n == -2) {
  7924. /* Receive error */
  7925. return -1;
  7926. }
  7927. if (n > 0) {
  7928. *nread += n;
  7929. request_len = get_http_header_len(buf, *nread);
  7930. } else {
  7931. request_len = 0;
  7932. }
  7933. if ((request_len == 0) && (request_timeout >= 0)) {
  7934. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  7935. > request_timeout) {
  7936. /* Timeout */
  7937. return -1;
  7938. }
  7939. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  7940. }
  7941. }
  7942. return request_len;
  7943. }
  7944. #if !defined(NO_CACHING)
  7945. /* Return True if we should reply 304 Not Modified. */
  7946. static int
  7947. is_not_modified(const struct mg_connection *conn,
  7948. const struct mg_file_stat *filestat)
  7949. {
  7950. char etag[64];
  7951. const char *ims = mg_get_header(conn, "If-Modified-Since");
  7952. const char *inm = mg_get_header(conn, "If-None-Match");
  7953. construct_etag(etag, sizeof(etag), filestat);
  7954. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  7955. || ((ims != NULL)
  7956. && (filestat->last_modified <= parse_date_string(ims)));
  7957. }
  7958. #endif /* !NO_CACHING */
  7959. #if !defined(NO_CGI) || !defined(NO_FILES)
  7960. static int
  7961. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  7962. {
  7963. const char *expect, *body;
  7964. char buf[MG_BUF_LEN];
  7965. int to_read, nread, success = 0;
  7966. int64_t buffered_len;
  7967. double timeout = -1.0;
  7968. if (!conn) {
  7969. return 0;
  7970. }
  7971. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  7972. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  7973. }
  7974. expect = mg_get_header(conn, "Expect");
  7975. /* assert(fp != NULL); */
  7976. if (!fp) {
  7977. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  7978. return 0;
  7979. }
  7980. if ((conn->content_len == -1) && !conn->is_chunked) {
  7981. /* Content length is not specified by the client. */
  7982. mg_send_http_error(conn,
  7983. 411,
  7984. "%s",
  7985. "Error: Client did not specify content length");
  7986. } else if ((expect != NULL)
  7987. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  7988. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  7989. */
  7990. mg_send_http_error(conn,
  7991. 417,
  7992. "Error: Can not fulfill expectation %s",
  7993. expect);
  7994. } else {
  7995. if (expect != NULL) {
  7996. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  7997. conn->status_code = 100;
  7998. } else {
  7999. conn->status_code = 200;
  8000. }
  8001. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  8002. - conn->consumed_content;
  8003. /* assert(buffered_len >= 0); */
  8004. /* assert(conn->consumed_content == 0); */
  8005. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  8006. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  8007. return 0;
  8008. }
  8009. if (buffered_len > 0) {
  8010. if ((int64_t)buffered_len > conn->content_len) {
  8011. buffered_len = (int)conn->content_len;
  8012. }
  8013. body = conn->buf + conn->request_len + conn->consumed_content;
  8014. push_all(conn->ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  8015. conn->consumed_content += buffered_len;
  8016. }
  8017. nread = 0;
  8018. while (conn->consumed_content < conn->content_len) {
  8019. to_read = sizeof(buf);
  8020. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  8021. to_read = (int)(conn->content_len - conn->consumed_content);
  8022. }
  8023. nread = pull_inner(NULL, conn, buf, to_read, timeout);
  8024. if (nread == -2) {
  8025. /* error */
  8026. break;
  8027. }
  8028. if (nread > 0) {
  8029. if (push_all(conn->ctx, fp, sock, ssl, buf, nread) != nread) {
  8030. break;
  8031. }
  8032. }
  8033. conn->consumed_content += nread;
  8034. }
  8035. if (conn->consumed_content == conn->content_len) {
  8036. success = (nread >= 0);
  8037. }
  8038. /* Each error code path in this function must send an error */
  8039. if (!success) {
  8040. /* NOTE: Maybe some data has already been sent. */
  8041. /* TODO (low): If some data has been sent, a correct error
  8042. * reply can no longer be sent, so just close the connection */
  8043. mg_send_http_error(conn, 500, "%s", "");
  8044. }
  8045. }
  8046. return success;
  8047. }
  8048. #endif
  8049. #if !defined(NO_CGI)
  8050. /* This structure helps to create an environment for the spawned CGI
  8051. * program.
  8052. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  8053. * last element must be NULL.
  8054. * However, on Windows there is a requirement that all these
  8055. * VARIABLE=VALUE\0
  8056. * strings must reside in a contiguous buffer. The end of the buffer is
  8057. * marked by two '\0' characters.
  8058. * We satisfy both worlds: we create an envp array (which is vars), all
  8059. * entries are actually pointers inside buf. */
  8060. struct cgi_environment {
  8061. struct mg_connection *conn;
  8062. /* Data block */
  8063. char *buf; /* Environment buffer */
  8064. size_t buflen; /* Space available in buf */
  8065. size_t bufused; /* Space taken in buf */
  8066. /* Index block */
  8067. char **var; /* char **envp */
  8068. size_t varlen; /* Number of variables available in var */
  8069. size_t varused; /* Number of variables stored in var */
  8070. };
  8071. static void addenv(struct cgi_environment *env,
  8072. PRINTF_FORMAT_STRING(const char *fmt),
  8073. ...) PRINTF_ARGS(2, 3);
  8074. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  8075. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  8076. static void
  8077. addenv(struct cgi_environment *env, const char *fmt, ...)
  8078. {
  8079. size_t n, space;
  8080. int truncated = 0;
  8081. char *added;
  8082. va_list ap;
  8083. /* Calculate how much space is left in the buffer */
  8084. space = (env->buflen - env->bufused);
  8085. /* Calculate an estimate for the required space */
  8086. n = strlen(fmt) + 2 + 128;
  8087. do {
  8088. if (space <= n) {
  8089. /* Allocate new buffer */
  8090. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  8091. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->ctx);
  8092. if (!added) {
  8093. /* Out of memory */
  8094. mg_cry(env->conn,
  8095. "%s: Cannot allocate memory for CGI variable [%s]",
  8096. __func__,
  8097. fmt);
  8098. return;
  8099. }
  8100. env->buf = added;
  8101. env->buflen = n;
  8102. space = (env->buflen - env->bufused);
  8103. }
  8104. /* Make a pointer to the free space int the buffer */
  8105. added = env->buf + env->bufused;
  8106. /* Copy VARIABLE=VALUE\0 string into the free space */
  8107. va_start(ap, fmt);
  8108. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  8109. va_end(ap);
  8110. /* Do not add truncated strings to the environment */
  8111. if (truncated) {
  8112. /* Reallocate the buffer */
  8113. space = 0;
  8114. n = 1;
  8115. }
  8116. } while (truncated);
  8117. /* Calculate number of bytes added to the environment */
  8118. n = strlen(added) + 1;
  8119. env->bufused += n;
  8120. /* Now update the variable index */
  8121. space = (env->varlen - env->varused);
  8122. if (space < 2) {
  8123. mg_cry(env->conn,
  8124. "%s: Cannot register CGI variable [%s]",
  8125. __func__,
  8126. fmt);
  8127. return;
  8128. }
  8129. /* Append a pointer to the added string into the envp array */
  8130. env->var[env->varused] = added;
  8131. env->varused++;
  8132. }
  8133. /* Return 0 on success, non-zero if an error occurs. */
  8134. static int
  8135. prepare_cgi_environment(struct mg_connection *conn,
  8136. const char *prog,
  8137. struct cgi_environment *env)
  8138. {
  8139. const char *s;
  8140. struct vec var_vec;
  8141. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  8142. int i, truncated, uri_len;
  8143. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  8144. return -1;
  8145. }
  8146. env->conn = conn;
  8147. env->buflen = CGI_ENVIRONMENT_SIZE;
  8148. env->bufused = 0;
  8149. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->ctx);
  8150. if (env->buf == NULL) {
  8151. mg_cry(conn,
  8152. "%s: Not enough memory for environmental buffer",
  8153. __func__);
  8154. return -1;
  8155. }
  8156. env->varlen = MAX_CGI_ENVIR_VARS;
  8157. env->varused = 0;
  8158. env->var = (char **)mg_malloc_ctx(env->buflen * sizeof(char *), conn->ctx);
  8159. if (env->var == NULL) {
  8160. mg_cry(conn,
  8161. "%s: Not enough memory for environmental variables",
  8162. __func__);
  8163. mg_free(env->buf);
  8164. return -1;
  8165. }
  8166. addenv(env, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  8167. addenv(env, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  8168. addenv(env, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  8169. addenv(env, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  8170. /* Prepare the environment block */
  8171. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  8172. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  8173. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  8174. #if defined(USE_IPV6)
  8175. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  8176. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  8177. } else
  8178. #endif
  8179. {
  8180. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  8181. }
  8182. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  8183. addenv(env, "REMOTE_ADDR=%s", src_addr);
  8184. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  8185. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  8186. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  8187. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  8188. /* SCRIPT_NAME */
  8189. uri_len = (int)strlen(conn->request_info.local_uri);
  8190. if (conn->path_info == NULL) {
  8191. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  8192. /* URI: /path_to_script/script.cgi */
  8193. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  8194. } else {
  8195. /* URI: /path_to_script/ ... using index.cgi */
  8196. const char *index_file = strrchr(prog, '/');
  8197. if (index_file) {
  8198. addenv(env,
  8199. "SCRIPT_NAME=%s%s",
  8200. conn->request_info.local_uri,
  8201. index_file + 1);
  8202. }
  8203. }
  8204. } else {
  8205. /* URI: /path_to_script/script.cgi/path_info */
  8206. addenv(env,
  8207. "SCRIPT_NAME=%.*s",
  8208. uri_len - (int)strlen(conn->path_info),
  8209. conn->request_info.local_uri);
  8210. }
  8211. addenv(env, "SCRIPT_FILENAME=%s", prog);
  8212. if (conn->path_info == NULL) {
  8213. addenv(env, "PATH_TRANSLATED=%s", conn->ctx->config[DOCUMENT_ROOT]);
  8214. } else {
  8215. addenv(env,
  8216. "PATH_TRANSLATED=%s%s",
  8217. conn->ctx->config[DOCUMENT_ROOT],
  8218. conn->path_info);
  8219. }
  8220. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  8221. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  8222. addenv(env, "CONTENT_TYPE=%s", s);
  8223. }
  8224. if (conn->request_info.query_string != NULL) {
  8225. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  8226. }
  8227. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  8228. addenv(env, "CONTENT_LENGTH=%s", s);
  8229. }
  8230. if ((s = getenv("PATH")) != NULL) {
  8231. addenv(env, "PATH=%s", s);
  8232. }
  8233. if (conn->path_info != NULL) {
  8234. addenv(env, "PATH_INFO=%s", conn->path_info);
  8235. }
  8236. if (conn->status_code > 0) {
  8237. /* CGI error handler should show the status code */
  8238. addenv(env, "STATUS=%d", conn->status_code);
  8239. }
  8240. #if defined(_WIN32)
  8241. if ((s = getenv("COMSPEC")) != NULL) {
  8242. addenv(env, "COMSPEC=%s", s);
  8243. }
  8244. if ((s = getenv("SYSTEMROOT")) != NULL) {
  8245. addenv(env, "SYSTEMROOT=%s", s);
  8246. }
  8247. if ((s = getenv("SystemDrive")) != NULL) {
  8248. addenv(env, "SystemDrive=%s", s);
  8249. }
  8250. if ((s = getenv("ProgramFiles")) != NULL) {
  8251. addenv(env, "ProgramFiles=%s", s);
  8252. }
  8253. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  8254. addenv(env, "ProgramFiles(x86)=%s", s);
  8255. }
  8256. #else
  8257. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  8258. addenv(env, "LD_LIBRARY_PATH=%s", s);
  8259. }
  8260. #endif /* _WIN32 */
  8261. if ((s = getenv("PERLLIB")) != NULL) {
  8262. addenv(env, "PERLLIB=%s", s);
  8263. }
  8264. if (conn->request_info.remote_user != NULL) {
  8265. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  8266. addenv(env, "%s", "AUTH_TYPE=Digest");
  8267. }
  8268. /* Add all headers as HTTP_* variables */
  8269. for (i = 0; i < conn->request_info.num_headers; i++) {
  8270. (void)mg_snprintf(conn,
  8271. &truncated,
  8272. http_var_name,
  8273. sizeof(http_var_name),
  8274. "HTTP_%s",
  8275. conn->request_info.http_headers[i].name);
  8276. if (truncated) {
  8277. mg_cry(conn,
  8278. "%s: HTTP header variable too long [%s]",
  8279. __func__,
  8280. conn->request_info.http_headers[i].name);
  8281. continue;
  8282. }
  8283. /* Convert variable name into uppercase, and change - to _ */
  8284. for (p = http_var_name; *p != '\0'; p++) {
  8285. if (*p == '-') {
  8286. *p = '_';
  8287. }
  8288. *p = (char)toupper(*(unsigned char *)p);
  8289. }
  8290. addenv(env,
  8291. "%s=%s",
  8292. http_var_name,
  8293. conn->request_info.http_headers[i].value);
  8294. }
  8295. /* Add user-specified variables */
  8296. s = conn->ctx->config[CGI_ENVIRONMENT];
  8297. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  8298. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  8299. }
  8300. env->var[env->varused] = NULL;
  8301. env->buf[env->bufused] = '\0';
  8302. return 0;
  8303. }
  8304. static void
  8305. handle_cgi_request(struct mg_connection *conn, const char *prog)
  8306. {
  8307. char *buf;
  8308. size_t buflen;
  8309. int headers_len, data_len, i, truncated;
  8310. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  8311. const char *status, *status_text, *connection_state;
  8312. char *pbuf, dir[PATH_MAX], *p;
  8313. struct mg_request_info ri;
  8314. struct cgi_environment blk;
  8315. FILE *in = NULL, *out = NULL, *err = NULL;
  8316. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  8317. pid_t pid = (pid_t)-1;
  8318. if (conn == NULL) {
  8319. return;
  8320. }
  8321. buf = NULL;
  8322. buflen = 16384;
  8323. i = prepare_cgi_environment(conn, prog, &blk);
  8324. if (i != 0) {
  8325. blk.buf = NULL;
  8326. blk.var = NULL;
  8327. goto done;
  8328. }
  8329. /* CGI must be executed in its own directory. 'dir' must point to the
  8330. * directory containing executable program, 'p' must point to the
  8331. * executable program name relative to 'dir'. */
  8332. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  8333. if (truncated) {
  8334. mg_cry(conn, "Error: CGI program \"%s\": Path too long", prog);
  8335. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  8336. goto done;
  8337. }
  8338. if ((p = strrchr(dir, '/')) != NULL) {
  8339. *p++ = '\0';
  8340. } else {
  8341. dir[0] = '.', dir[1] = '\0';
  8342. p = (char *)prog;
  8343. }
  8344. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  8345. status = strerror(ERRNO);
  8346. mg_cry(conn,
  8347. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  8348. prog,
  8349. status);
  8350. mg_send_http_error(conn,
  8351. 500,
  8352. "Error: Cannot create CGI pipe: %s",
  8353. status);
  8354. goto done;
  8355. }
  8356. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  8357. if (pid == (pid_t)-1) {
  8358. status = strerror(ERRNO);
  8359. mg_cry(conn,
  8360. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  8361. prog,
  8362. status);
  8363. mg_send_http_error(conn,
  8364. 500,
  8365. "Error: Cannot spawn CGI process [%s]: %s",
  8366. prog,
  8367. status);
  8368. goto done;
  8369. }
  8370. /* Make sure child closes all pipe descriptors. It must dup them to 0,1
  8371. */
  8372. set_close_on_exec((SOCKET)fdin[0], conn); /* stdin read */
  8373. set_close_on_exec((SOCKET)fdout[1], conn); /* stdout write */
  8374. set_close_on_exec((SOCKET)fderr[1], conn); /* stderr write */
  8375. set_close_on_exec((SOCKET)fdin[1], conn); /* stdin write */
  8376. set_close_on_exec((SOCKET)fdout[0], conn); /* stdout read */
  8377. set_close_on_exec((SOCKET)fderr[0], conn); /* stderr read */
  8378. /* Parent closes only one side of the pipes.
  8379. * If we don't mark them as closed, close() attempt before
  8380. * return from this function throws an exception on Windows.
  8381. * Windows does not like when closed descriptor is closed again. */
  8382. (void)close(fdin[0]);
  8383. (void)close(fdout[1]);
  8384. (void)close(fderr[1]);
  8385. fdin[0] = fdout[1] = fderr[1] = -1;
  8386. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  8387. status = strerror(ERRNO);
  8388. mg_cry(conn,
  8389. "Error: CGI program \"%s\": Can not open stdin: %s",
  8390. prog,
  8391. status);
  8392. mg_send_http_error(conn,
  8393. 500,
  8394. "Error: CGI can not open fdin\nfopen: %s",
  8395. status);
  8396. goto done;
  8397. }
  8398. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  8399. status = strerror(ERRNO);
  8400. mg_cry(conn,
  8401. "Error: CGI program \"%s\": Can not open stdout: %s",
  8402. prog,
  8403. status);
  8404. mg_send_http_error(conn,
  8405. 500,
  8406. "Error: CGI can not open fdout\nfopen: %s",
  8407. status);
  8408. goto done;
  8409. }
  8410. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  8411. status = strerror(ERRNO);
  8412. mg_cry(conn,
  8413. "Error: CGI program \"%s\": Can not open stderr: %s",
  8414. prog,
  8415. status);
  8416. mg_send_http_error(conn,
  8417. 500,
  8418. "Error: CGI can not open fdout\nfopen: %s",
  8419. status);
  8420. goto done;
  8421. }
  8422. setbuf(in, NULL);
  8423. setbuf(out, NULL);
  8424. setbuf(err, NULL);
  8425. fout.access.fp = out;
  8426. if ((conn->request_info.content_length > 0) || conn->is_chunked) {
  8427. /* This is a POST/PUT request, or another request with body data. */
  8428. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  8429. /* Error sending the body data */
  8430. mg_cry(conn,
  8431. "Error: CGI program \"%s\": Forward body data failed",
  8432. prog);
  8433. goto done;
  8434. }
  8435. }
  8436. /* Close so child gets an EOF. */
  8437. fclose(in);
  8438. in = NULL;
  8439. fdin[1] = -1;
  8440. /* Now read CGI reply into a buffer. We need to set correct
  8441. * status code, thus we need to see all HTTP headers first.
  8442. * Do not send anything back to client, until we buffer in all
  8443. * HTTP headers. */
  8444. data_len = 0;
  8445. buf = (char *)mg_malloc_ctx(buflen, conn->ctx);
  8446. if (buf == NULL) {
  8447. mg_send_http_error(conn,
  8448. 500,
  8449. "Error: Not enough memory for CGI buffer (%u bytes)",
  8450. (unsigned int)buflen);
  8451. mg_cry(conn,
  8452. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  8453. "bytes)",
  8454. prog,
  8455. (unsigned int)buflen);
  8456. goto done;
  8457. }
  8458. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  8459. if (headers_len <= 0) {
  8460. /* Could not parse the CGI response. Check if some error message on
  8461. * stderr. */
  8462. i = pull_all(err, conn, buf, (int)buflen);
  8463. if (i > 0) {
  8464. mg_cry(conn,
  8465. "Error: CGI program \"%s\" sent error "
  8466. "message: [%.*s]",
  8467. prog,
  8468. i,
  8469. buf);
  8470. mg_send_http_error(conn,
  8471. 500,
  8472. "Error: CGI program \"%s\" sent error "
  8473. "message: [%.*s]",
  8474. prog,
  8475. i,
  8476. buf);
  8477. } else {
  8478. mg_cry(conn,
  8479. "Error: CGI program sent malformed or too big "
  8480. "(>%u bytes) HTTP headers: [%.*s]",
  8481. (unsigned)buflen,
  8482. data_len,
  8483. buf);
  8484. mg_send_http_error(conn,
  8485. 500,
  8486. "Error: CGI program sent malformed or too big "
  8487. "(>%u bytes) HTTP headers: [%.*s]",
  8488. (unsigned)buflen,
  8489. data_len,
  8490. buf);
  8491. }
  8492. goto done;
  8493. }
  8494. pbuf = buf;
  8495. buf[headers_len - 1] = '\0';
  8496. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  8497. /* Make up and send the status line */
  8498. status_text = "OK";
  8499. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  8500. != NULL) {
  8501. conn->status_code = atoi(status);
  8502. status_text = status;
  8503. while (isdigit(*(const unsigned char *)status_text)
  8504. || *status_text == ' ') {
  8505. status_text++;
  8506. }
  8507. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  8508. != NULL) {
  8509. conn->status_code = 302;
  8510. } else {
  8511. conn->status_code = 200;
  8512. }
  8513. connection_state =
  8514. get_header(ri.http_headers, ri.num_headers, "Connection");
  8515. if (!header_has_option(connection_state, "keep-alive")) {
  8516. conn->must_close = 1;
  8517. }
  8518. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  8519. /* Send headers */
  8520. for (i = 0; i < ri.num_headers; i++) {
  8521. mg_printf(conn,
  8522. "%s: %s\r\n",
  8523. ri.http_headers[i].name,
  8524. ri.http_headers[i].value);
  8525. }
  8526. mg_write(conn, "\r\n", 2);
  8527. /* Send chunk of data that may have been read after the headers */
  8528. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  8529. /* Read the rest of CGI output and send to the client */
  8530. send_file_data(conn, &fout, 0, INT64_MAX);
  8531. done:
  8532. mg_free(blk.var);
  8533. mg_free(blk.buf);
  8534. if (pid != (pid_t)-1) {
  8535. kill(pid, SIGKILL);
  8536. #if !defined(_WIN32)
  8537. {
  8538. int st;
  8539. while (waitpid(pid, &st, 0) != -1)
  8540. ; /* clean zombies */
  8541. }
  8542. #endif
  8543. }
  8544. if (fdin[0] != -1) {
  8545. close(fdin[0]);
  8546. }
  8547. if (fdout[1] != -1) {
  8548. close(fdout[1]);
  8549. }
  8550. if (in != NULL) {
  8551. fclose(in);
  8552. } else if (fdin[1] != -1) {
  8553. close(fdin[1]);
  8554. }
  8555. if (out != NULL) {
  8556. fclose(out);
  8557. } else if (fdout[0] != -1) {
  8558. close(fdout[0]);
  8559. }
  8560. if (err != NULL) {
  8561. fclose(err);
  8562. } else if (fderr[0] != -1) {
  8563. close(fderr[0]);
  8564. }
  8565. if (buf != NULL) {
  8566. mg_free(buf);
  8567. }
  8568. }
  8569. #endif /* !NO_CGI */
  8570. #if !defined(NO_FILES)
  8571. static void
  8572. mkcol(struct mg_connection *conn, const char *path)
  8573. {
  8574. int rc, body_len;
  8575. struct de de;
  8576. char date[64];
  8577. time_t curtime = time(NULL);
  8578. if (conn == NULL) {
  8579. return;
  8580. }
  8581. /* TODO (mid): Check the mg_send_http_error situations in this function
  8582. */
  8583. memset(&de.file, 0, sizeof(de.file));
  8584. if (!mg_stat(conn, path, &de.file)) {
  8585. mg_cry(conn,
  8586. "%s: mg_stat(%s) failed: %s",
  8587. __func__,
  8588. path,
  8589. strerror(ERRNO));
  8590. }
  8591. if (de.file.last_modified) {
  8592. /* TODO (mid): This check does not seem to make any sense ! */
  8593. /* TODO (mid): Add a webdav unit test first, before changing
  8594. * anything here. */
  8595. mg_send_http_error(
  8596. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  8597. return;
  8598. }
  8599. body_len = conn->data_len - conn->request_len;
  8600. if (body_len > 0) {
  8601. mg_send_http_error(
  8602. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  8603. return;
  8604. }
  8605. rc = mg_mkdir(conn, path, 0755);
  8606. if (rc == 0) {
  8607. conn->status_code = 201;
  8608. gmt_time_string(date, sizeof(date), &curtime);
  8609. mg_printf(conn,
  8610. "HTTP/1.1 %d Created\r\n"
  8611. "Date: %s\r\n",
  8612. conn->status_code,
  8613. date);
  8614. send_static_cache_header(conn);
  8615. send_additional_header(conn);
  8616. mg_printf(conn,
  8617. "Content-Length: 0\r\n"
  8618. "Connection: %s\r\n\r\n",
  8619. suggest_connection_header(conn));
  8620. } else if (rc == -1) {
  8621. if (errno == EEXIST) {
  8622. mg_send_http_error(
  8623. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  8624. } else if (errno == EACCES) {
  8625. mg_send_http_error(
  8626. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  8627. } else if (errno == ENOENT) {
  8628. mg_send_http_error(
  8629. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  8630. } else {
  8631. mg_send_http_error(
  8632. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  8633. }
  8634. }
  8635. }
  8636. static void
  8637. put_file(struct mg_connection *conn, const char *path)
  8638. {
  8639. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8640. const char *range;
  8641. int64_t r1, r2;
  8642. int rc;
  8643. char date[64];
  8644. time_t curtime = time(NULL);
  8645. if (conn == NULL) {
  8646. return;
  8647. }
  8648. if (mg_stat(conn, path, &file.stat)) {
  8649. /* File already exists */
  8650. conn->status_code = 200;
  8651. if (file.stat.is_directory) {
  8652. /* This is an already existing directory,
  8653. * so there is nothing to do for the server. */
  8654. rc = 0;
  8655. } else {
  8656. /* File exists and is not a directory. */
  8657. /* Can it be replaced? */
  8658. if (file.access.membuf != NULL) {
  8659. /* This is an "in-memory" file, that can not be replaced */
  8660. mg_send_http_error(conn,
  8661. 405,
  8662. "Error: Put not possible\nReplacing %s "
  8663. "is not supported",
  8664. path);
  8665. return;
  8666. }
  8667. /* Check if the server may write this file */
  8668. if (access(path, W_OK) == 0) {
  8669. /* Access granted */
  8670. conn->status_code = 200;
  8671. rc = 1;
  8672. } else {
  8673. mg_send_http_error(
  8674. conn,
  8675. 403,
  8676. "Error: Put not possible\nReplacing %s is not allowed",
  8677. path);
  8678. return;
  8679. }
  8680. }
  8681. } else {
  8682. /* File should be created */
  8683. conn->status_code = 201;
  8684. rc = put_dir(conn, path);
  8685. }
  8686. if (rc == 0) {
  8687. /* put_dir returns 0 if path is a directory */
  8688. gmt_time_string(date, sizeof(date), &curtime);
  8689. mg_printf(conn,
  8690. "HTTP/1.1 %d %s\r\n",
  8691. conn->status_code,
  8692. mg_get_response_code_text(NULL, conn->status_code));
  8693. send_no_cache_header(conn);
  8694. send_additional_header(conn);
  8695. mg_printf(conn,
  8696. "Date: %s\r\n"
  8697. "Content-Length: 0\r\n"
  8698. "Connection: %s\r\n\r\n",
  8699. date,
  8700. suggest_connection_header(conn));
  8701. /* Request to create a directory has been fulfilled successfully.
  8702. * No need to put a file. */
  8703. return;
  8704. }
  8705. if (rc == -1) {
  8706. /* put_dir returns -1 if the path is too long */
  8707. mg_send_http_error(conn,
  8708. 414,
  8709. "Error: Path too long\nput_dir(%s): %s",
  8710. path,
  8711. strerror(ERRNO));
  8712. return;
  8713. }
  8714. if (rc == -2) {
  8715. /* put_dir returns -2 if the directory can not be created */
  8716. mg_send_http_error(conn,
  8717. 500,
  8718. "Error: Can not create directory\nput_dir(%s): %s",
  8719. path,
  8720. strerror(ERRNO));
  8721. return;
  8722. }
  8723. /* A file should be created or overwritten. */
  8724. /* Currently CivetWeb does not nead read+write access. */
  8725. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  8726. || file.access.fp == NULL) {
  8727. (void)mg_fclose(&file.access);
  8728. mg_send_http_error(conn,
  8729. 500,
  8730. "Error: Can not create file\nfopen(%s): %s",
  8731. path,
  8732. strerror(ERRNO));
  8733. return;
  8734. }
  8735. fclose_on_exec(&file.access, conn);
  8736. range = mg_get_header(conn, "Content-Range");
  8737. r1 = r2 = 0;
  8738. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  8739. conn->status_code = 206; /* Partial content */
  8740. fseeko(file.access.fp, r1, SEEK_SET);
  8741. }
  8742. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  8743. /* forward_body_data failed.
  8744. * The error code has already been sent to the client,
  8745. * and conn->status_code is already set. */
  8746. (void)mg_fclose(&file.access);
  8747. return;
  8748. }
  8749. if (mg_fclose(&file.access) != 0) {
  8750. /* fclose failed. This might have different reasons, but a likely
  8751. * one is "no space on disk", http 507. */
  8752. conn->status_code = 507;
  8753. }
  8754. gmt_time_string(date, sizeof(date), &curtime);
  8755. mg_printf(conn,
  8756. "HTTP/1.1 %d %s\r\n",
  8757. conn->status_code,
  8758. mg_get_response_code_text(NULL, conn->status_code));
  8759. send_no_cache_header(conn);
  8760. send_additional_header(conn);
  8761. mg_printf(conn,
  8762. "Date: %s\r\n"
  8763. "Content-Length: 0\r\n"
  8764. "Connection: %s\r\n\r\n",
  8765. date,
  8766. suggest_connection_header(conn));
  8767. }
  8768. static void
  8769. delete_file(struct mg_connection *conn, const char *path)
  8770. {
  8771. struct de de;
  8772. memset(&de.file, 0, sizeof(de.file));
  8773. if (!mg_stat(conn, path, &de.file)) {
  8774. /* mg_stat returns 0 if the file does not exist */
  8775. mg_send_http_error(conn,
  8776. 404,
  8777. "Error: Cannot delete file\nFile %s not found",
  8778. path);
  8779. return;
  8780. }
  8781. #if 0 /* Ignore if a file in memory is inside a folder */
  8782. if (de.access.membuf != NULL) {
  8783. /* the file is cached in memory */
  8784. mg_send_http_error(
  8785. conn,
  8786. 405,
  8787. "Error: Delete not possible\nDeleting %s is not supported",
  8788. path);
  8789. return;
  8790. }
  8791. #endif
  8792. if (de.file.is_directory) {
  8793. if (remove_directory(conn, path)) {
  8794. /* Delete is successful: Return 204 without content. */
  8795. mg_send_http_error(conn, 204, "%s", "");
  8796. } else {
  8797. /* Delete is not successful: Return 500 (Server error). */
  8798. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  8799. }
  8800. return;
  8801. }
  8802. /* This is an existing file (not a directory).
  8803. * Check if write permission is granted. */
  8804. if (access(path, W_OK) != 0) {
  8805. /* File is read only */
  8806. mg_send_http_error(
  8807. conn,
  8808. 403,
  8809. "Error: Delete not possible\nDeleting %s is not allowed",
  8810. path);
  8811. return;
  8812. }
  8813. /* Try to delete it. */
  8814. if (mg_remove(conn, path) == 0) {
  8815. /* Delete was successful: Return 204 without content. */
  8816. mg_send_http_error(conn, 204, "%s", "");
  8817. } else {
  8818. /* Delete not successful (file locked). */
  8819. mg_send_http_error(conn,
  8820. 423,
  8821. "Error: Cannot delete file\nremove(%s): %s",
  8822. path,
  8823. strerror(ERRNO));
  8824. }
  8825. }
  8826. #endif /* !NO_FILES */
  8827. static void
  8828. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  8829. static void
  8830. do_ssi_include(struct mg_connection *conn,
  8831. const char *ssi,
  8832. char *tag,
  8833. int include_level)
  8834. {
  8835. char file_name[MG_BUF_LEN], path[512], *p;
  8836. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8837. size_t len;
  8838. int truncated = 0;
  8839. if (conn == NULL) {
  8840. return;
  8841. }
  8842. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  8843. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  8844. * always < MG_BUF_LEN. */
  8845. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  8846. /* File name is relative to the webserver root */
  8847. file_name[511] = 0;
  8848. (void)mg_snprintf(conn,
  8849. &truncated,
  8850. path,
  8851. sizeof(path),
  8852. "%s/%s",
  8853. conn->ctx->config[DOCUMENT_ROOT],
  8854. file_name);
  8855. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  8856. /* File name is relative to the webserver working directory
  8857. * or it is absolute system path */
  8858. file_name[511] = 0;
  8859. (void)
  8860. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  8861. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  8862. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  8863. /* File name is relative to the currect document */
  8864. file_name[511] = 0;
  8865. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  8866. if (!truncated) {
  8867. if ((p = strrchr(path, '/')) != NULL) {
  8868. p[1] = '\0';
  8869. }
  8870. len = strlen(path);
  8871. (void)mg_snprintf(conn,
  8872. &truncated,
  8873. path + len,
  8874. sizeof(path) - len,
  8875. "%s",
  8876. file_name);
  8877. }
  8878. } else {
  8879. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  8880. return;
  8881. }
  8882. if (truncated) {
  8883. mg_cry(conn, "SSI #include path length overflow: [%s]", tag);
  8884. return;
  8885. }
  8886. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  8887. mg_cry(conn,
  8888. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  8889. tag,
  8890. path,
  8891. strerror(ERRNO));
  8892. } else {
  8893. fclose_on_exec(&file.access, conn);
  8894. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  8895. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  8896. path) > 0) {
  8897. send_ssi_file(conn, path, &file, include_level + 1);
  8898. } else {
  8899. send_file_data(conn, &file, 0, INT64_MAX);
  8900. }
  8901. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  8902. }
  8903. }
  8904. #if !defined(NO_POPEN)
  8905. static void
  8906. do_ssi_exec(struct mg_connection *conn, char *tag)
  8907. {
  8908. char cmd[1024] = "";
  8909. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8910. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  8911. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  8912. } else {
  8913. cmd[1023] = 0;
  8914. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  8915. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  8916. } else {
  8917. send_file_data(conn, &file, 0, INT64_MAX);
  8918. pclose(file.access.fp);
  8919. }
  8920. }
  8921. }
  8922. #endif /* !NO_POPEN */
  8923. static int
  8924. mg_fgetc(struct mg_file *filep, int offset)
  8925. {
  8926. if (filep == NULL) {
  8927. return EOF;
  8928. }
  8929. if ((filep->access.membuf != NULL) && (offset >= 0)
  8930. && (((unsigned int)(offset)) < filep->stat.size)) {
  8931. return ((const unsigned char *)filep->access.membuf)[offset];
  8932. } else if (filep->access.fp != NULL) {
  8933. return fgetc(filep->access.fp);
  8934. } else {
  8935. return EOF;
  8936. }
  8937. }
  8938. static void
  8939. send_ssi_file(struct mg_connection *conn,
  8940. const char *path,
  8941. struct mg_file *filep,
  8942. int include_level)
  8943. {
  8944. char buf[MG_BUF_LEN];
  8945. int ch, offset, len, in_tag, in_ssi_tag;
  8946. if (include_level > 10) {
  8947. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  8948. return;
  8949. }
  8950. in_tag = in_ssi_tag = len = offset = 0;
  8951. /* Read file, byte by byte, and look for SSI include tags */
  8952. while ((ch = mg_fgetc(filep, offset++)) != EOF) {
  8953. if (in_tag) {
  8954. /* We are in a tag, either SSI tag or html tag */
  8955. if (ch == '>') {
  8956. /* Tag is closing */
  8957. buf[len++] = '>';
  8958. if (in_ssi_tag) {
  8959. /* Handle SSI tag */
  8960. buf[len] = 0;
  8961. if (!memcmp(buf + 5, "include", 7)) {
  8962. do_ssi_include(conn, path, buf + 12, include_level + 1);
  8963. #if !defined(NO_POPEN)
  8964. } else if (!memcmp(buf + 5, "exec", 4)) {
  8965. do_ssi_exec(conn, buf + 9);
  8966. #endif /* !NO_POPEN */
  8967. } else {
  8968. mg_cry(conn,
  8969. "%s: unknown SSI "
  8970. "command: \"%s\"",
  8971. path,
  8972. buf);
  8973. }
  8974. len = 0;
  8975. in_ssi_tag = in_tag = 0;
  8976. } else {
  8977. /* Not an SSI tag */
  8978. /* Flush buffer */
  8979. (void)mg_write(conn, buf, (size_t)len);
  8980. len = 0;
  8981. in_tag = 0;
  8982. }
  8983. } else {
  8984. /* Tag is still open */
  8985. buf[len++] = (char)(ch & 0xff);
  8986. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  8987. /* All SSI tags start with <!--# */
  8988. in_ssi_tag = 1;
  8989. }
  8990. if ((len + 2) > (int)sizeof(buf)) {
  8991. /* Tag to long for buffer */
  8992. mg_cry(conn, "%s: tag is too large", path);
  8993. len = 0;
  8994. return;
  8995. }
  8996. }
  8997. } else {
  8998. /* We are not in a tag yet. */
  8999. if (ch == '<') {
  9000. /* Tag is opening */
  9001. in_tag = 1;
  9002. /* Flush current buffer */
  9003. (void)mg_write(conn, buf, (size_t)len);
  9004. /* Store the < */
  9005. len = 1;
  9006. buf[0] = '<';
  9007. } else {
  9008. /* No Tag */
  9009. /* Add data to buffer */
  9010. buf[len++] = (char)(ch & 0xff);
  9011. /* Flush if buffer is full */
  9012. if (len == (int)sizeof(buf)) {
  9013. mg_write(conn, buf, (size_t)len);
  9014. len = 0;
  9015. }
  9016. }
  9017. }
  9018. }
  9019. /* Send the rest of buffered data */
  9020. if (len > 0) {
  9021. mg_write(conn, buf, (size_t)len);
  9022. }
  9023. }
  9024. static void
  9025. handle_ssi_file_request(struct mg_connection *conn,
  9026. const char *path,
  9027. struct mg_file *filep)
  9028. {
  9029. char date[64];
  9030. time_t curtime = time(NULL);
  9031. const char *cors1, *cors2, *cors3;
  9032. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  9033. return;
  9034. }
  9035. if (mg_get_header(conn, "Origin")) {
  9036. /* Cross-origin resource sharing (CORS). */
  9037. cors1 = "Access-Control-Allow-Origin: ";
  9038. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  9039. cors3 = "\r\n";
  9040. } else {
  9041. cors1 = cors2 = cors3 = "";
  9042. }
  9043. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  9044. /* File exists (precondition for calling this function),
  9045. * but can not be opened by the server. */
  9046. mg_send_http_error(conn,
  9047. 500,
  9048. "Error: Cannot read file\nfopen(%s): %s",
  9049. path,
  9050. strerror(ERRNO));
  9051. } else {
  9052. conn->must_close = 1;
  9053. gmt_time_string(date, sizeof(date), &curtime);
  9054. fclose_on_exec(&filep->access, conn);
  9055. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  9056. send_no_cache_header(conn);
  9057. send_additional_header(conn);
  9058. mg_printf(conn,
  9059. "%s%s%s"
  9060. "Date: %s\r\n"
  9061. "Content-Type: text/html\r\n"
  9062. "Connection: %s\r\n\r\n",
  9063. cors1,
  9064. cors2,
  9065. cors3,
  9066. date,
  9067. suggest_connection_header(conn));
  9068. send_ssi_file(conn, path, filep, 0);
  9069. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  9070. }
  9071. }
  9072. #if !defined(NO_FILES)
  9073. static void
  9074. send_options(struct mg_connection *conn)
  9075. {
  9076. char date[64];
  9077. time_t curtime = time(NULL);
  9078. if (!conn) {
  9079. return;
  9080. }
  9081. conn->status_code = 200;
  9082. conn->must_close = 1;
  9083. gmt_time_string(date, sizeof(date), &curtime);
  9084. /* We do not set a "Cache-Control" header here, but leave the default.
  9085. * Since browsers do not send an OPTIONS request, we can not test the
  9086. * effect anyway. */
  9087. mg_printf(conn,
  9088. "HTTP/1.1 200 OK\r\n"
  9089. "Date: %s\r\n"
  9090. "Connection: %s\r\n"
  9091. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  9092. "PROPFIND, MKCOL\r\n"
  9093. "DAV: 1\r\n",
  9094. date,
  9095. suggest_connection_header(conn));
  9096. send_additional_header(conn);
  9097. mg_printf(conn, "\r\n");
  9098. }
  9099. /* Writes PROPFIND properties for a collection element */
  9100. static void
  9101. print_props(struct mg_connection *conn,
  9102. const char *uri,
  9103. struct mg_file_stat *filep)
  9104. {
  9105. char mtime[64];
  9106. if ((conn == NULL) || (uri == NULL) || (filep == NULL)) {
  9107. return;
  9108. }
  9109. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  9110. mg_printf(conn,
  9111. "<d:response>"
  9112. "<d:href>%s</d:href>"
  9113. "<d:propstat>"
  9114. "<d:prop>"
  9115. "<d:resourcetype>%s</d:resourcetype>"
  9116. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  9117. "<d:getlastmodified>%s</d:getlastmodified>"
  9118. "</d:prop>"
  9119. "<d:status>HTTP/1.1 200 OK</d:status>"
  9120. "</d:propstat>"
  9121. "</d:response>\n",
  9122. uri,
  9123. filep->is_directory ? "<d:collection/>" : "",
  9124. filep->size,
  9125. mtime);
  9126. }
  9127. static int
  9128. print_dav_dir_entry(struct de *de, void *data)
  9129. {
  9130. char href[PATH_MAX];
  9131. int truncated;
  9132. struct mg_connection *conn = (struct mg_connection *)data;
  9133. if (!de || !conn) {
  9134. return -1;
  9135. }
  9136. mg_snprintf(conn,
  9137. &truncated,
  9138. href,
  9139. sizeof(href),
  9140. "%s%s",
  9141. conn->request_info.local_uri,
  9142. de->file_name);
  9143. if (!truncated) {
  9144. size_t href_encoded_size;
  9145. char *href_encoded;
  9146. href_encoded_size = PATH_MAX * 3; /* worst case */
  9147. href_encoded = mg_malloc(href_encoded_size);
  9148. if (href_encoded == NULL) {
  9149. return -1;
  9150. }
  9151. mg_url_encode(href, href_encoded, href_encoded_size);
  9152. print_props(conn, href_encoded, &de->file);
  9153. mg_free(href_encoded);
  9154. }
  9155. return 0;
  9156. }
  9157. static void
  9158. handle_propfind(struct mg_connection *conn,
  9159. const char *path,
  9160. struct mg_file_stat *filep)
  9161. {
  9162. const char *depth = mg_get_header(conn, "Depth");
  9163. char date[64];
  9164. time_t curtime = time(NULL);
  9165. gmt_time_string(date, sizeof(date), &curtime);
  9166. if (!conn || !path || !filep || !conn->ctx) {
  9167. return;
  9168. }
  9169. conn->must_close = 1;
  9170. conn->status_code = 207;
  9171. mg_printf(conn,
  9172. "HTTP/1.1 207 Multi-Status\r\n"
  9173. "Date: %s\r\n",
  9174. date);
  9175. send_static_cache_header(conn);
  9176. send_additional_header(conn);
  9177. mg_printf(conn,
  9178. "Connection: %s\r\n"
  9179. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  9180. suggest_connection_header(conn));
  9181. mg_printf(conn,
  9182. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  9183. "<d:multistatus xmlns:d='DAV:'>\n");
  9184. /* Print properties for the requested resource itself */
  9185. print_props(conn, conn->request_info.local_uri, filep);
  9186. /* If it is a directory, print directory entries too if Depth is not 0
  9187. */
  9188. if (filep && filep->is_directory
  9189. && !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")
  9190. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  9191. scan_directory(conn, path, conn, &print_dav_dir_entry);
  9192. }
  9193. mg_printf(conn, "%s\n", "</d:multistatus>");
  9194. }
  9195. #endif
  9196. void
  9197. mg_lock_connection(struct mg_connection *conn)
  9198. {
  9199. if (conn) {
  9200. (void)pthread_mutex_lock(&conn->mutex);
  9201. }
  9202. }
  9203. void
  9204. mg_unlock_connection(struct mg_connection *conn)
  9205. {
  9206. if (conn) {
  9207. (void)pthread_mutex_unlock(&conn->mutex);
  9208. }
  9209. }
  9210. void
  9211. mg_lock_context(struct mg_context *ctx)
  9212. {
  9213. if (ctx) {
  9214. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  9215. }
  9216. }
  9217. void
  9218. mg_unlock_context(struct mg_context *ctx)
  9219. {
  9220. if (ctx) {
  9221. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  9222. }
  9223. }
  9224. #if defined(USE_TIMERS)
  9225. #define TIMER_API static
  9226. #include "timer.inl"
  9227. #endif /* USE_TIMERS */
  9228. #ifdef USE_LUA
  9229. #include "mod_lua.inl"
  9230. #endif /* USE_LUA */
  9231. #ifdef USE_DUKTAPE
  9232. #include "mod_duktape.inl"
  9233. #endif /* USE_DUKTAPE */
  9234. #if defined(USE_WEBSOCKET)
  9235. #if !defined(NO_SSL_DL)
  9236. #define SHA_API static
  9237. #include "sha1.inl"
  9238. #endif
  9239. static int
  9240. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  9241. {
  9242. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  9243. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  9244. SHA_CTX sha_ctx;
  9245. int truncated;
  9246. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  9247. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  9248. if (truncated) {
  9249. conn->must_close = 1;
  9250. return 0;
  9251. }
  9252. SHA1_Init(&sha_ctx);
  9253. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  9254. SHA1_Final((unsigned char *)sha, &sha_ctx);
  9255. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  9256. mg_printf(conn,
  9257. "HTTP/1.1 101 Switching Protocols\r\n"
  9258. "Upgrade: websocket\r\n"
  9259. "Connection: Upgrade\r\n"
  9260. "Sec-WebSocket-Accept: %s\r\n",
  9261. b64_sha);
  9262. if (conn->request_info.acceptedWebSocketSubprotocol) {
  9263. mg_printf(conn,
  9264. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  9265. conn->request_info.acceptedWebSocketSubprotocol);
  9266. } else {
  9267. mg_printf(conn, "%s", "\r\n");
  9268. }
  9269. return 1;
  9270. }
  9271. static void
  9272. read_websocket(struct mg_connection *conn,
  9273. mg_websocket_data_handler ws_data_handler,
  9274. void *callback_data)
  9275. {
  9276. /* Pointer to the beginning of the portion of the incoming websocket
  9277. * message queue.
  9278. * The original websocket upgrade request is never removed, so the queue
  9279. * begins after it. */
  9280. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  9281. int n, error, exit_by_callback;
  9282. /* body_len is the length of the entire queue in bytes
  9283. * len is the length of the current message
  9284. * data_len is the length of the current message's data payload
  9285. * header_len is the length of the current message's header */
  9286. size_t i, len, mask_len = 0, data_len = 0, header_len, body_len;
  9287. /* "The masking key is a 32-bit value chosen at random by the client."
  9288. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  9289. */
  9290. unsigned char mask[4];
  9291. /* data points to the place where the message is stored when passed to
  9292. * the
  9293. * websocket_data callback. This is either mem on the stack, or a
  9294. * dynamically allocated buffer if it is too large. */
  9295. unsigned char mem[4096];
  9296. unsigned char *data = mem;
  9297. unsigned char mop; /* mask flag and opcode */
  9298. double timeout = -1.0;
  9299. if (conn->ctx->config[WEBSOCKET_TIMEOUT]) {
  9300. timeout = atoi(conn->ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  9301. }
  9302. if ((timeout <= 0.0) && (conn->ctx->config[REQUEST_TIMEOUT])) {
  9303. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  9304. }
  9305. mg_set_thread_name("wsock");
  9306. /* Loop continuously, reading messages from the socket, invoking the
  9307. * callback, and waiting repeatedly until an error occurs. */
  9308. while (!conn->ctx->stop_flag) {
  9309. header_len = 0;
  9310. assert(conn->data_len >= conn->request_len);
  9311. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  9312. len = buf[1] & 127;
  9313. mask_len = (buf[1] & 128) ? 4 : 0;
  9314. if ((len < 126) && (body_len >= mask_len)) {
  9315. /* inline 7-bit length field */
  9316. data_len = len;
  9317. header_len = 2 + mask_len;
  9318. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  9319. /* 16-bit length field */
  9320. header_len = 4 + mask_len;
  9321. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  9322. } else if (body_len >= (10 + mask_len)) {
  9323. /* 64-bit length field */
  9324. uint32_t l1, l2;
  9325. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  9326. memcpy(&l2, &buf[6], 4);
  9327. header_len = 10 + mask_len;
  9328. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  9329. if (data_len > (uint64_t)0x7FFF0000ul) {
  9330. /* no can do */
  9331. mg_cry(conn, "websocket out of memory; closing connection");
  9332. break;
  9333. }
  9334. }
  9335. }
  9336. if ((header_len > 0) && (body_len >= header_len)) {
  9337. /* Allocate space to hold websocket payload */
  9338. data = mem;
  9339. if (data_len > sizeof(mem)) {
  9340. data = (unsigned char *)mg_malloc_ctx(data_len, conn->ctx);
  9341. if (data == NULL) {
  9342. /* Allocation failed, exit the loop and then close the
  9343. * connection */
  9344. mg_cry(conn, "websocket out of memory; closing connection");
  9345. break;
  9346. }
  9347. }
  9348. /* Copy the mask before we shift the queue and destroy it */
  9349. if (mask_len > 0) {
  9350. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  9351. } else {
  9352. memset(mask, 0, sizeof(mask));
  9353. }
  9354. /* Read frame payload from the first message in the queue into
  9355. * data and advance the queue by moving the memory in place. */
  9356. assert(body_len >= header_len);
  9357. if (data_len + header_len > body_len) {
  9358. mop = buf[0]; /* current mask and opcode */
  9359. /* Overflow case */
  9360. len = body_len - header_len;
  9361. memcpy(data, buf + header_len, len);
  9362. error = 0;
  9363. while (len < data_len) {
  9364. n = pull_inner(NULL,
  9365. conn,
  9366. (char *)(data + len),
  9367. (int)(data_len - len),
  9368. timeout);
  9369. if (n <= -2) {
  9370. error = 1;
  9371. break;
  9372. } else if (n > 0) {
  9373. len += (size_t)n;
  9374. } else {
  9375. /* Timeout: should retry */
  9376. /* TODO: retry condition */
  9377. }
  9378. }
  9379. if (error) {
  9380. mg_cry(conn, "Websocket pull failed; closing connection");
  9381. break;
  9382. }
  9383. conn->data_len = conn->request_len;
  9384. } else {
  9385. mop = buf[0]; /* current mask and opcode, overwritten by
  9386. * memmove() */
  9387. /* Length of the message being read at the front of the
  9388. * queue */
  9389. len = data_len + header_len;
  9390. /* Copy the data payload into the data pointer for the
  9391. * callback */
  9392. memcpy(data, buf + header_len, data_len);
  9393. /* Move the queue forward len bytes */
  9394. memmove(buf, buf + len, body_len - len);
  9395. /* Mark the queue as advanced */
  9396. conn->data_len -= (int)len;
  9397. }
  9398. /* Apply mask if necessary */
  9399. if (mask_len > 0) {
  9400. for (i = 0; i < data_len; ++i) {
  9401. data[i] ^= mask[i & 3];
  9402. }
  9403. }
  9404. /* Exit the loop if callback signals to exit (server side),
  9405. * or "connection close" opcode received (client side). */
  9406. exit_by_callback = 0;
  9407. if ((ws_data_handler != NULL)
  9408. && !ws_data_handler(
  9409. conn, mop, (char *)data, data_len, callback_data)) {
  9410. exit_by_callback = 1;
  9411. }
  9412. if (data != mem) {
  9413. mg_free(data);
  9414. }
  9415. if (exit_by_callback
  9416. || ((mop & 0xf) == WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  9417. /* Opcode == 8, connection close */
  9418. break;
  9419. }
  9420. /* Not breaking the loop, process next websocket frame. */
  9421. } else {
  9422. /* Read from the socket into the next available location in the
  9423. * message queue. */
  9424. n = pull_inner(NULL,
  9425. conn,
  9426. conn->buf + conn->data_len,
  9427. conn->buf_size - conn->data_len,
  9428. timeout);
  9429. if (n <= -2) {
  9430. /* Error, no bytes read */
  9431. break;
  9432. }
  9433. if (n > 0) {
  9434. conn->data_len += n;
  9435. } else {
  9436. /* Timeout: should retry */
  9437. /* TODO: get timeout def */
  9438. }
  9439. }
  9440. }
  9441. mg_set_thread_name("worker");
  9442. }
  9443. static int
  9444. mg_websocket_write_exec(struct mg_connection *conn,
  9445. int opcode,
  9446. const char *data,
  9447. size_t dataLen,
  9448. uint32_t masking_key)
  9449. {
  9450. unsigned char header[14];
  9451. size_t headerLen = 1;
  9452. int retval = -1;
  9453. #if defined(__GNUC__) || defined(__MINGW32__)
  9454. /* Disable spurious conversion warning for GCC */
  9455. #pragma GCC diagnostic push
  9456. #pragma GCC diagnostic ignored "-Wconversion"
  9457. #endif
  9458. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  9459. #if defined(__GNUC__) || defined(__MINGW32__)
  9460. #pragma GCC diagnostic pop
  9461. #endif
  9462. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  9463. if (dataLen < 126) {
  9464. /* inline 7-bit length field */
  9465. header[1] = (unsigned char)dataLen;
  9466. headerLen = 2;
  9467. } else if (dataLen <= 0xFFFF) {
  9468. /* 16-bit length field */
  9469. uint16_t len = htons((uint16_t)dataLen);
  9470. header[1] = 126;
  9471. memcpy(header + 2, &len, 2);
  9472. headerLen = 4;
  9473. } else {
  9474. /* 64-bit length field */
  9475. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  9476. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  9477. header[1] = 127;
  9478. memcpy(header + 2, &len1, 4);
  9479. memcpy(header + 6, &len2, 4);
  9480. headerLen = 10;
  9481. }
  9482. if (masking_key) {
  9483. /* add mask */
  9484. header[1] |= 0x80;
  9485. memcpy(header + headerLen, &masking_key, 4);
  9486. headerLen += 4;
  9487. }
  9488. /* Note that POSIX/Winsock's send() is threadsafe
  9489. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  9490. * but mongoose's mg_printf/mg_write is not (because of the loop in
  9491. * push(), although that is only a problem if the packet is large or
  9492. * outgoing buffer is full). */
  9493. /* TODO: Check if this lock should be moved to user land.
  9494. * Currently the server sets this lock for websockets, but
  9495. * not for any other connection. It must be set for every
  9496. * conn read/written by more than one thread, no matter if
  9497. * it is a websocket or regular connection. */
  9498. (void)mg_lock_connection(conn);
  9499. retval = mg_write(conn, header, headerLen);
  9500. if (dataLen > 0) {
  9501. retval = mg_write(conn, data, dataLen);
  9502. }
  9503. /* TODO: Remove this unlock as well, when lock is moved. */
  9504. mg_unlock_connection(conn);
  9505. return retval;
  9506. }
  9507. int
  9508. mg_websocket_write(struct mg_connection *conn,
  9509. int opcode,
  9510. const char *data,
  9511. size_t dataLen)
  9512. {
  9513. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  9514. }
  9515. static void
  9516. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  9517. {
  9518. size_t i = 0;
  9519. i = 0;
  9520. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  9521. /* Convert in 32 bit words, if data is 4 byte aligned */
  9522. while (i < (in_len - 3)) {
  9523. *(uint32_t *)(void *)(out + i) =
  9524. *(uint32_t *)(void *)(in + i) ^ masking_key;
  9525. i += 4;
  9526. }
  9527. }
  9528. if (i != in_len) {
  9529. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  9530. while (i < in_len) {
  9531. *(uint8_t *)(void *)(out + i) =
  9532. *(uint8_t *)(void *)(in + i)
  9533. ^ *(((uint8_t *)&masking_key) + (i % 4));
  9534. i++;
  9535. }
  9536. }
  9537. }
  9538. int
  9539. mg_websocket_client_write(struct mg_connection *conn,
  9540. int opcode,
  9541. const char *data,
  9542. size_t dataLen)
  9543. {
  9544. int retval = -1;
  9545. char *masked_data =
  9546. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->ctx);
  9547. uint32_t masking_key = (uint32_t)get_random();
  9548. if (masked_data == NULL) {
  9549. /* Return -1 in an error case */
  9550. mg_cry(conn,
  9551. "Cannot allocate buffer for masked websocket response: "
  9552. "Out of memory");
  9553. return -1;
  9554. }
  9555. mask_data(data, dataLen, masking_key, masked_data);
  9556. retval = mg_websocket_write_exec(
  9557. conn, opcode, masked_data, dataLen, masking_key);
  9558. mg_free(masked_data);
  9559. return retval;
  9560. }
  9561. static void
  9562. handle_websocket_request(struct mg_connection *conn,
  9563. const char *path,
  9564. int is_callback_resource,
  9565. struct mg_websocket_subprotocols *subprotocols,
  9566. mg_websocket_connect_handler ws_connect_handler,
  9567. mg_websocket_ready_handler ws_ready_handler,
  9568. mg_websocket_data_handler ws_data_handler,
  9569. mg_websocket_close_handler ws_close_handler,
  9570. void *cbData)
  9571. {
  9572. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  9573. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  9574. int lua_websock = 0;
  9575. #if !defined(USE_LUA)
  9576. (void)path;
  9577. #endif
  9578. /* Step 1: Check websocket protocol version. */
  9579. /* Step 1.1: Check Sec-WebSocket-Key. */
  9580. if (!websock_key) {
  9581. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  9582. * requires a Sec-WebSocket-Key header.
  9583. */
  9584. /* It could be the hixie draft version
  9585. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  9586. */
  9587. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  9588. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  9589. char key3[8];
  9590. if ((key1 != NULL) && (key2 != NULL)) {
  9591. /* This version uses 8 byte body data in a GET request */
  9592. conn->content_len = 8;
  9593. if (8 == mg_read(conn, key3, 8)) {
  9594. /* This is the hixie version */
  9595. mg_send_http_error(conn,
  9596. 426,
  9597. "%s",
  9598. "Protocol upgrade to RFC 6455 required");
  9599. return;
  9600. }
  9601. }
  9602. /* This is an unknown version */
  9603. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  9604. return;
  9605. }
  9606. /* Step 1.2: Check websocket protocol version. */
  9607. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  9608. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  9609. /* Reject wrong versions */
  9610. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  9611. return;
  9612. }
  9613. /* Step 1.3: Could check for "Host", but we do not really nead this
  9614. * value for anything, so just ignore it. */
  9615. /* Step 2: If a callback is responsible, call it. */
  9616. if (is_callback_resource) {
  9617. /* Step 2.1 check and select subprotocol */
  9618. const char *protocols[64]; // max 64 headers
  9619. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  9620. "Sec-WebSocket-Protocol",
  9621. protocols,
  9622. 64);
  9623. if ((nbSubprotocolHeader > 0) && subprotocols) {
  9624. int cnt = 0;
  9625. int idx;
  9626. unsigned long len;
  9627. const char *sep, *curSubProtocol,
  9628. *acceptedWebSocketSubprotocol = NULL;
  9629. /* look for matching subprotocol */
  9630. do {
  9631. const char *protocol = protocols[cnt];
  9632. do {
  9633. sep = strchr(protocol, ',');
  9634. curSubProtocol = protocol;
  9635. len = sep ? (unsigned long)(sep - protocol)
  9636. : (unsigned long)strlen(protocol);
  9637. while (sep && isspace(*++sep))
  9638. ; // ignore leading whitespaces
  9639. protocol = sep;
  9640. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  9641. if ((strlen(subprotocols->subprotocols[idx]) == len)
  9642. && (strncmp(curSubProtocol,
  9643. subprotocols->subprotocols[idx],
  9644. len) == 0)) {
  9645. acceptedWebSocketSubprotocol =
  9646. subprotocols->subprotocols[idx];
  9647. break;
  9648. }
  9649. }
  9650. } while (sep && !acceptedWebSocketSubprotocol);
  9651. } while (++cnt < nbSubprotocolHeader
  9652. && !acceptedWebSocketSubprotocol);
  9653. conn->request_info.acceptedWebSocketSubprotocol =
  9654. acceptedWebSocketSubprotocol;
  9655. } else if (nbSubprotocolHeader > 0) {
  9656. /* keep legacy behavior */
  9657. const char *protocol = protocols[0];
  9658. /* The protocol is a comma separated list of names. */
  9659. /* The server must only return one value from this list. */
  9660. /* First check if it is a list or just a single value. */
  9661. const char *sep = strrchr(protocol, ',');
  9662. if (sep == NULL) {
  9663. /* Just a single protocol -> accept it. */
  9664. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  9665. } else {
  9666. /* Multiple protocols -> accept the last one. */
  9667. /* This is just a quick fix if the client offers multiple
  9668. * protocols. The handler should have a list of accepted
  9669. * protocols on his own
  9670. * and use it to select one protocol among those the client
  9671. * has
  9672. * offered.
  9673. */
  9674. while (isspace(*++sep)) {
  9675. ; /* ignore leading whitespaces */
  9676. }
  9677. conn->request_info.acceptedWebSocketSubprotocol = sep;
  9678. }
  9679. }
  9680. if ((ws_connect_handler != NULL)
  9681. && (ws_connect_handler(conn, cbData) != 0)) {
  9682. /* C callback has returned non-zero, do not proceed with
  9683. * handshake.
  9684. */
  9685. /* Note that C callbacks are no longer called when Lua is
  9686. * responsible, so C can no longer filter callbacks for Lua. */
  9687. return;
  9688. }
  9689. }
  9690. #if defined(USE_LUA)
  9691. /* Step 3: No callback. Check if Lua is responsible. */
  9692. else {
  9693. /* Step 3.1: Check if Lua is responsible. */
  9694. if (conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  9695. lua_websock =
  9696. match_prefix(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  9697. strlen(
  9698. conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  9699. path);
  9700. }
  9701. if (lua_websock) {
  9702. /* Step 3.2: Lua is responsible: call it. */
  9703. conn->lua_websocket_state = lua_websocket_new(path, conn);
  9704. if (!conn->lua_websocket_state) {
  9705. /* Lua rejected the new client */
  9706. return;
  9707. }
  9708. }
  9709. }
  9710. #endif
  9711. /* Step 4: Check if there is a responsible websocket handler. */
  9712. if (!is_callback_resource && !lua_websock) {
  9713. /* There is no callback, and Lua is not responsible either. */
  9714. /* Reply with a 404 Not Found. We are still at a standard
  9715. * HTTP request here, before the websocket handshake, so
  9716. * we can still send standard HTTP error replies. */
  9717. mg_send_http_error(conn, 404, "%s", "Not found");
  9718. return;
  9719. }
  9720. /* Step 5: The websocket connection has been accepted */
  9721. if (!send_websocket_handshake(conn, websock_key)) {
  9722. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  9723. return;
  9724. }
  9725. /* Step 6: Call the ready handler */
  9726. if (is_callback_resource) {
  9727. if (ws_ready_handler != NULL) {
  9728. ws_ready_handler(conn, cbData);
  9729. }
  9730. #if defined(USE_LUA)
  9731. } else if (lua_websock) {
  9732. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  9733. /* the ready handler returned false */
  9734. return;
  9735. }
  9736. #endif
  9737. }
  9738. /* Step 7: Enter the read loop */
  9739. if (is_callback_resource) {
  9740. read_websocket(conn, ws_data_handler, cbData);
  9741. #if defined(USE_LUA)
  9742. } else if (lua_websock) {
  9743. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  9744. #endif
  9745. }
  9746. /* Step 8: Call the close handler */
  9747. if (ws_close_handler) {
  9748. ws_close_handler(conn, cbData);
  9749. }
  9750. }
  9751. static int
  9752. is_websocket_protocol(const struct mg_connection *conn)
  9753. {
  9754. const char *upgrade, *connection;
  9755. /* A websocket protocoll has the following HTTP headers:
  9756. *
  9757. * Connection: Upgrade
  9758. * Upgrade: Websocket
  9759. */
  9760. upgrade = mg_get_header(conn, "Upgrade");
  9761. if (upgrade == NULL) {
  9762. return 0; /* fail early, don't waste time checking other header
  9763. * fields
  9764. */
  9765. }
  9766. if (!mg_strcasestr(upgrade, "websocket")) {
  9767. return 0;
  9768. }
  9769. connection = mg_get_header(conn, "Connection");
  9770. if (connection == NULL) {
  9771. return 0;
  9772. }
  9773. if (!mg_strcasestr(connection, "upgrade")) {
  9774. return 0;
  9775. }
  9776. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  9777. * "Sec-WebSocket-Version" are also required.
  9778. * Don't check them here, since even an unsupported websocket protocol
  9779. * request still IS a websocket request (in contrast to a standard HTTP
  9780. * request). It will fail later in handle_websocket_request.
  9781. */
  9782. return 1;
  9783. }
  9784. #endif /* !USE_WEBSOCKET */
  9785. static int
  9786. isbyte(int n)
  9787. {
  9788. return (n >= 0) && (n <= 255);
  9789. }
  9790. static int
  9791. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  9792. {
  9793. int n, a, b, c, d, slash = 32, len = 0;
  9794. if (((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5)
  9795. || (sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4))
  9796. && isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && (slash >= 0)
  9797. && (slash < 33)) {
  9798. len = n;
  9799. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  9800. | (uint32_t)d;
  9801. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  9802. }
  9803. return len;
  9804. }
  9805. static int
  9806. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  9807. {
  9808. int throttle = 0;
  9809. struct vec vec, val;
  9810. uint32_t net, mask;
  9811. char mult;
  9812. double v;
  9813. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  9814. mult = ',';
  9815. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  9816. || (v < 0) || ((lowercase(&mult) != 'k')
  9817. && (lowercase(&mult) != 'm') && (mult != ','))) {
  9818. continue;
  9819. }
  9820. v *= (lowercase(&mult) == 'k')
  9821. ? 1024
  9822. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  9823. if (vec.len == 1 && vec.ptr[0] == '*') {
  9824. throttle = (int)v;
  9825. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  9826. if ((remote_ip & mask) == net) {
  9827. throttle = (int)v;
  9828. }
  9829. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  9830. throttle = (int)v;
  9831. }
  9832. }
  9833. return throttle;
  9834. }
  9835. static uint32_t
  9836. get_remote_ip(const struct mg_connection *conn)
  9837. {
  9838. if (!conn) {
  9839. return 0;
  9840. }
  9841. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  9842. }
  9843. /* The mg_upload function is superseeded by mg_handle_form_request. */
  9844. #include "handle_form.inl"
  9845. #if defined(MG_LEGACY_INTERFACE)
  9846. /* Implement the deprecated mg_upload function by calling the new
  9847. * mg_handle_form_request function. While mg_upload could only handle
  9848. * HTML forms sent as POST request in multipart/form-data format
  9849. * containing only file input elements, mg_handle_form_request can
  9850. * handle all form input elements and all standard request methods. */
  9851. struct mg_upload_user_data {
  9852. struct mg_connection *conn;
  9853. const char *destination_dir;
  9854. int num_uploaded_files;
  9855. };
  9856. /* Helper function for deprecated mg_upload. */
  9857. static int
  9858. mg_upload_field_found(const char *key,
  9859. const char *filename,
  9860. char *path,
  9861. size_t pathlen,
  9862. void *user_data)
  9863. {
  9864. int truncated = 0;
  9865. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  9866. (void)key;
  9867. if (!filename) {
  9868. mg_cry(fud->conn, "%s: No filename set", __func__);
  9869. return FORM_FIELD_STORAGE_ABORT;
  9870. }
  9871. mg_snprintf(fud->conn,
  9872. &truncated,
  9873. path,
  9874. pathlen - 1,
  9875. "%s/%s",
  9876. fud->destination_dir,
  9877. filename);
  9878. if (!truncated) {
  9879. mg_cry(fud->conn, "%s: File path too long", __func__);
  9880. return FORM_FIELD_STORAGE_ABORT;
  9881. }
  9882. return FORM_FIELD_STORAGE_STORE;
  9883. }
  9884. /* Helper function for deprecated mg_upload. */
  9885. static int
  9886. mg_upload_field_get(const char *key,
  9887. const char *value,
  9888. size_t value_size,
  9889. void *user_data)
  9890. {
  9891. /* Function should never be called */
  9892. (void)key;
  9893. (void)value;
  9894. (void)value_size;
  9895. (void)user_data;
  9896. return 0;
  9897. }
  9898. /* Helper function for deprecated mg_upload. */
  9899. static int
  9900. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  9901. {
  9902. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  9903. (void)file_size;
  9904. fud->num_uploaded_files++;
  9905. fud->conn->ctx->callbacks.upload(fud->conn, path);
  9906. return 0;
  9907. }
  9908. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  9909. int
  9910. mg_upload(struct mg_connection *conn, const char *destination_dir)
  9911. {
  9912. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  9913. struct mg_form_data_handler fdh = {mg_upload_field_found,
  9914. mg_upload_field_get,
  9915. mg_upload_field_stored,
  9916. 0};
  9917. int ret;
  9918. fdh.user_data = (void *)&fud;
  9919. ret = mg_handle_form_request(conn, &fdh);
  9920. if (ret < 0) {
  9921. mg_cry(conn, "%s: Error while parsing the request", __func__);
  9922. }
  9923. return fud.num_uploaded_files;
  9924. }
  9925. #endif
  9926. static int
  9927. get_first_ssl_listener_index(const struct mg_context *ctx)
  9928. {
  9929. unsigned int i;
  9930. int idx = -1;
  9931. if (ctx) {
  9932. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  9933. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  9934. }
  9935. }
  9936. return idx;
  9937. }
  9938. static void
  9939. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  9940. {
  9941. char host[1025];
  9942. const char *host_header;
  9943. size_t hostlen;
  9944. host_header = mg_get_header(conn, "Host");
  9945. hostlen = sizeof(host);
  9946. if (host_header != NULL) {
  9947. char *pos;
  9948. mg_strlcpy(host, host_header, hostlen);
  9949. host[hostlen - 1] = '\0';
  9950. pos = strchr(host, ':');
  9951. if (pos != NULL) {
  9952. *pos = '\0';
  9953. }
  9954. } else {
  9955. /* Cannot get host from the Host: header.
  9956. * Fallback to our IP address. */
  9957. if (conn) {
  9958. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  9959. }
  9960. }
  9961. /* Send host, port, uri and (if it exists) ?query_string */
  9962. if (conn) {
  9963. mg_printf(conn,
  9964. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  9965. host,
  9966. #if defined(USE_IPV6)
  9967. (conn->ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  9968. == AF_INET6)
  9969. ? (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  9970. .lsa.sin6.sin6_port)
  9971. :
  9972. #endif
  9973. (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  9974. .lsa.sin.sin_port),
  9975. conn->request_info.local_uri,
  9976. (conn->request_info.query_string == NULL) ? "" : "?",
  9977. (conn->request_info.query_string == NULL)
  9978. ? ""
  9979. : conn->request_info.query_string);
  9980. }
  9981. }
  9982. static void
  9983. mg_set_handler_type(struct mg_context *ctx,
  9984. const char *uri,
  9985. int handler_type,
  9986. int is_delete_request,
  9987. mg_request_handler handler,
  9988. struct mg_websocket_subprotocols *subprotocols,
  9989. mg_websocket_connect_handler connect_handler,
  9990. mg_websocket_ready_handler ready_handler,
  9991. mg_websocket_data_handler data_handler,
  9992. mg_websocket_close_handler close_handler,
  9993. mg_authorization_handler auth_handler,
  9994. void *cbdata)
  9995. {
  9996. struct mg_handler_info *tmp_rh, **lastref;
  9997. size_t urilen = strlen(uri);
  9998. if (handler_type == WEBSOCKET_HANDLER) {
  9999. /* assert(handler == NULL); */
  10000. /* assert(is_delete_request || connect_handler!=NULL ||
  10001. * ready_handler!=NULL || data_handler!=NULL ||
  10002. * close_handler!=NULL);
  10003. */
  10004. /* assert(auth_handler == NULL); */
  10005. if (handler != NULL) {
  10006. return;
  10007. }
  10008. if (!is_delete_request && (connect_handler == NULL)
  10009. && (ready_handler == NULL) && (data_handler == NULL)
  10010. && (close_handler == NULL)) {
  10011. return;
  10012. }
  10013. if (auth_handler != NULL) {
  10014. return;
  10015. }
  10016. } else if (handler_type == REQUEST_HANDLER) {
  10017. /* assert(connect_handler==NULL && ready_handler==NULL &&
  10018. * data_handler==NULL && close_handler==NULL); */
  10019. /* assert(is_delete_request || (handler!=NULL));
  10020. */
  10021. /* assert(auth_handler == NULL); */
  10022. if ((connect_handler != NULL) || (ready_handler != NULL)
  10023. || (data_handler != NULL) || (close_handler != NULL)) {
  10024. return;
  10025. }
  10026. if (!is_delete_request && (handler == NULL)) {
  10027. return;
  10028. }
  10029. if (auth_handler != NULL) {
  10030. return;
  10031. }
  10032. } else { /* AUTH_HANDLER */
  10033. /* assert(handler == NULL); */
  10034. /* assert(connect_handler==NULL && ready_handler==NULL &&
  10035. * data_handler==NULL && close_handler==NULL); */
  10036. /* assert(auth_handler != NULL); */
  10037. if (handler != NULL) {
  10038. return;
  10039. }
  10040. if ((connect_handler != NULL) || (ready_handler != NULL)
  10041. || (data_handler != NULL) || (close_handler != NULL)) {
  10042. return;
  10043. }
  10044. if (!is_delete_request && (auth_handler == NULL)) {
  10045. return;
  10046. }
  10047. }
  10048. if (!ctx) {
  10049. return;
  10050. }
  10051. mg_lock_context(ctx);
  10052. /* first try to find an existing handler */
  10053. lastref = &(ctx->handlers);
  10054. for (tmp_rh = ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  10055. if (tmp_rh->handler_type == handler_type) {
  10056. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  10057. if (!is_delete_request) {
  10058. /* update existing handler */
  10059. if (handler_type == REQUEST_HANDLER) {
  10060. tmp_rh->handler = handler;
  10061. } else if (handler_type == WEBSOCKET_HANDLER) {
  10062. tmp_rh->subprotocols = subprotocols;
  10063. tmp_rh->connect_handler = connect_handler;
  10064. tmp_rh->ready_handler = ready_handler;
  10065. tmp_rh->data_handler = data_handler;
  10066. tmp_rh->close_handler = close_handler;
  10067. } else { /* AUTH_HANDLER */
  10068. tmp_rh->auth_handler = auth_handler;
  10069. }
  10070. tmp_rh->cbdata = cbdata;
  10071. } else {
  10072. /* remove existing handler */
  10073. *lastref = tmp_rh->next;
  10074. mg_free(tmp_rh->uri);
  10075. mg_free(tmp_rh);
  10076. }
  10077. mg_unlock_context(ctx);
  10078. return;
  10079. }
  10080. }
  10081. lastref = &(tmp_rh->next);
  10082. }
  10083. if (is_delete_request) {
  10084. /* no handler to set, this was a remove request to a non-existing
  10085. * handler */
  10086. mg_unlock_context(ctx);
  10087. return;
  10088. }
  10089. tmp_rh =
  10090. (struct mg_handler_info *)mg_calloc_ctx(sizeof(struct mg_handler_info),
  10091. 1,
  10092. ctx);
  10093. if (tmp_rh == NULL) {
  10094. mg_unlock_context(ctx);
  10095. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  10096. return;
  10097. }
  10098. tmp_rh->uri = mg_strdup(uri);
  10099. if (!tmp_rh->uri) {
  10100. mg_unlock_context(ctx);
  10101. mg_free(tmp_rh);
  10102. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  10103. return;
  10104. }
  10105. tmp_rh->uri_len = urilen;
  10106. if (handler_type == REQUEST_HANDLER) {
  10107. tmp_rh->handler = handler;
  10108. } else if (handler_type == WEBSOCKET_HANDLER) {
  10109. tmp_rh->subprotocols = subprotocols;
  10110. tmp_rh->connect_handler = connect_handler;
  10111. tmp_rh->ready_handler = ready_handler;
  10112. tmp_rh->data_handler = data_handler;
  10113. tmp_rh->close_handler = close_handler;
  10114. } else { /* AUTH_HANDLER */
  10115. tmp_rh->auth_handler = auth_handler;
  10116. }
  10117. tmp_rh->cbdata = cbdata;
  10118. tmp_rh->handler_type = handler_type;
  10119. tmp_rh->next = NULL;
  10120. *lastref = tmp_rh;
  10121. mg_unlock_context(ctx);
  10122. }
  10123. void
  10124. mg_set_request_handler(struct mg_context *ctx,
  10125. const char *uri,
  10126. mg_request_handler handler,
  10127. void *cbdata)
  10128. {
  10129. mg_set_handler_type(ctx,
  10130. uri,
  10131. REQUEST_HANDLER,
  10132. handler == NULL,
  10133. handler,
  10134. NULL,
  10135. NULL,
  10136. NULL,
  10137. NULL,
  10138. NULL,
  10139. NULL,
  10140. cbdata);
  10141. }
  10142. void
  10143. mg_set_websocket_handler(struct mg_context *ctx,
  10144. const char *uri,
  10145. mg_websocket_connect_handler connect_handler,
  10146. mg_websocket_ready_handler ready_handler,
  10147. mg_websocket_data_handler data_handler,
  10148. mg_websocket_close_handler close_handler,
  10149. void *cbdata)
  10150. {
  10151. mg_set_websocket_handler_with_subprotocols(ctx,
  10152. uri,
  10153. NULL,
  10154. connect_handler,
  10155. ready_handler,
  10156. data_handler,
  10157. close_handler,
  10158. cbdata);
  10159. }
  10160. void
  10161. mg_set_websocket_handler_with_subprotocols(
  10162. struct mg_context *ctx,
  10163. const char *uri,
  10164. struct mg_websocket_subprotocols *subprotocols,
  10165. mg_websocket_connect_handler connect_handler,
  10166. mg_websocket_ready_handler ready_handler,
  10167. mg_websocket_data_handler data_handler,
  10168. mg_websocket_close_handler close_handler,
  10169. void *cbdata)
  10170. {
  10171. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  10172. && (data_handler == NULL)
  10173. && (close_handler == NULL);
  10174. mg_set_handler_type(ctx,
  10175. uri,
  10176. WEBSOCKET_HANDLER,
  10177. is_delete_request,
  10178. NULL,
  10179. subprotocols,
  10180. connect_handler,
  10181. ready_handler,
  10182. data_handler,
  10183. close_handler,
  10184. NULL,
  10185. cbdata);
  10186. }
  10187. void
  10188. mg_set_auth_handler(struct mg_context *ctx,
  10189. const char *uri,
  10190. mg_request_handler handler,
  10191. void *cbdata)
  10192. {
  10193. mg_set_handler_type(ctx,
  10194. uri,
  10195. AUTH_HANDLER,
  10196. handler == NULL,
  10197. NULL,
  10198. NULL,
  10199. NULL,
  10200. NULL,
  10201. NULL,
  10202. NULL,
  10203. handler,
  10204. cbdata);
  10205. }
  10206. static int
  10207. get_request_handler(struct mg_connection *conn,
  10208. int handler_type,
  10209. mg_request_handler *handler,
  10210. struct mg_websocket_subprotocols **subprotocols,
  10211. mg_websocket_connect_handler *connect_handler,
  10212. mg_websocket_ready_handler *ready_handler,
  10213. mg_websocket_data_handler *data_handler,
  10214. mg_websocket_close_handler *close_handler,
  10215. mg_authorization_handler *auth_handler,
  10216. void **cbdata)
  10217. {
  10218. const struct mg_request_info *request_info = mg_get_request_info(conn);
  10219. if (request_info) {
  10220. const char *uri = request_info->local_uri;
  10221. size_t urilen = strlen(uri);
  10222. struct mg_handler_info *tmp_rh;
  10223. if (!conn || !conn->ctx) {
  10224. return 0;
  10225. }
  10226. mg_lock_context(conn->ctx);
  10227. /* first try for an exact match */
  10228. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  10229. tmp_rh = tmp_rh->next) {
  10230. if (tmp_rh->handler_type == handler_type) {
  10231. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  10232. if (handler_type == WEBSOCKET_HANDLER) {
  10233. *subprotocols = tmp_rh->subprotocols;
  10234. *connect_handler = tmp_rh->connect_handler;
  10235. *ready_handler = tmp_rh->ready_handler;
  10236. *data_handler = tmp_rh->data_handler;
  10237. *close_handler = tmp_rh->close_handler;
  10238. } else if (handler_type == REQUEST_HANDLER) {
  10239. *handler = tmp_rh->handler;
  10240. } else { /* AUTH_HANDLER */
  10241. *auth_handler = tmp_rh->auth_handler;
  10242. }
  10243. *cbdata = tmp_rh->cbdata;
  10244. mg_unlock_context(conn->ctx);
  10245. return 1;
  10246. }
  10247. }
  10248. }
  10249. /* next try for a partial match, we will accept uri/something */
  10250. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  10251. tmp_rh = tmp_rh->next) {
  10252. if (tmp_rh->handler_type == handler_type) {
  10253. if ((tmp_rh->uri_len < urilen) && (uri[tmp_rh->uri_len] == '/')
  10254. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0)) {
  10255. if (handler_type == WEBSOCKET_HANDLER) {
  10256. *subprotocols = tmp_rh->subprotocols;
  10257. *connect_handler = tmp_rh->connect_handler;
  10258. *ready_handler = tmp_rh->ready_handler;
  10259. *data_handler = tmp_rh->data_handler;
  10260. *close_handler = tmp_rh->close_handler;
  10261. } else if (handler_type == REQUEST_HANDLER) {
  10262. *handler = tmp_rh->handler;
  10263. } else { /* AUTH_HANDLER */
  10264. *auth_handler = tmp_rh->auth_handler;
  10265. }
  10266. *cbdata = tmp_rh->cbdata;
  10267. mg_unlock_context(conn->ctx);
  10268. return 1;
  10269. }
  10270. }
  10271. }
  10272. /* finally try for pattern match */
  10273. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  10274. tmp_rh = tmp_rh->next) {
  10275. if (tmp_rh->handler_type == handler_type) {
  10276. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  10277. if (handler_type == WEBSOCKET_HANDLER) {
  10278. *subprotocols = tmp_rh->subprotocols;
  10279. *connect_handler = tmp_rh->connect_handler;
  10280. *ready_handler = tmp_rh->ready_handler;
  10281. *data_handler = tmp_rh->data_handler;
  10282. *close_handler = tmp_rh->close_handler;
  10283. } else if (handler_type == REQUEST_HANDLER) {
  10284. *handler = tmp_rh->handler;
  10285. } else { /* AUTH_HANDLER */
  10286. *auth_handler = tmp_rh->auth_handler;
  10287. }
  10288. *cbdata = tmp_rh->cbdata;
  10289. mg_unlock_context(conn->ctx);
  10290. return 1;
  10291. }
  10292. }
  10293. }
  10294. mg_unlock_context(conn->ctx);
  10295. }
  10296. return 0; /* none found */
  10297. }
  10298. /* Check if the script file is in a path, allowed for script files.
  10299. * This can be used if uploading files is possible not only for the server
  10300. * admin, and the upload mechanism does not check the file extension.
  10301. */
  10302. static int
  10303. is_in_script_path(const struct mg_connection *conn, const char *path)
  10304. {
  10305. /* TODO (Feature): Add config value for allowed script path.
  10306. * Default: All allowed. */
  10307. (void)conn;
  10308. (void)path;
  10309. return 1;
  10310. }
  10311. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  10312. static int
  10313. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  10314. void *cbdata)
  10315. {
  10316. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  10317. if (pcallbacks->websocket_connect) {
  10318. return pcallbacks->websocket_connect(conn);
  10319. }
  10320. /* No handler set - assume "OK" */
  10321. return 0;
  10322. }
  10323. static void
  10324. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  10325. {
  10326. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  10327. if (pcallbacks->websocket_ready) {
  10328. pcallbacks->websocket_ready(conn);
  10329. }
  10330. }
  10331. static int
  10332. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  10333. int bits,
  10334. char *data,
  10335. size_t len,
  10336. void *cbdata)
  10337. {
  10338. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  10339. if (pcallbacks->websocket_data) {
  10340. return pcallbacks->websocket_data(conn, bits, data, len);
  10341. }
  10342. /* No handler set - assume "OK" */
  10343. return 1;
  10344. }
  10345. #endif
  10346. /* This is the heart of the Civetweb's logic.
  10347. * This function is called when the request is read, parsed and validated,
  10348. * and Civetweb must decide what action to take: serve a file, or
  10349. * a directory, or call embedded function, etcetera. */
  10350. static void
  10351. handle_request(struct mg_connection *conn)
  10352. {
  10353. struct mg_request_info *ri = &conn->request_info;
  10354. char path[PATH_MAX];
  10355. int uri_len, ssl_index;
  10356. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  10357. is_put_or_delete_request = 0, is_callback_resource = 0;
  10358. int i;
  10359. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10360. mg_request_handler callback_handler = NULL;
  10361. struct mg_websocket_subprotocols *subprotocols;
  10362. mg_websocket_connect_handler ws_connect_handler = NULL;
  10363. mg_websocket_ready_handler ws_ready_handler = NULL;
  10364. mg_websocket_data_handler ws_data_handler = NULL;
  10365. mg_websocket_close_handler ws_close_handler = NULL;
  10366. void *callback_data = NULL;
  10367. mg_authorization_handler auth_handler = NULL;
  10368. void *auth_callback_data = NULL;
  10369. int handler_type;
  10370. time_t curtime = time(NULL);
  10371. char date[64];
  10372. path[0] = 0;
  10373. /* 1. get the request url */
  10374. /* 1.1. split into url and query string */
  10375. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  10376. != NULL) {
  10377. *((char *)conn->request_info.query_string++) = '\0';
  10378. }
  10379. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  10380. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  10381. ssl_index = get_first_ssl_listener_index(conn->ctx);
  10382. if (ssl_index >= 0) {
  10383. redirect_to_https_port(conn, ssl_index);
  10384. } else {
  10385. /* A http to https forward port has been specified,
  10386. * but no https port to forward to. */
  10387. mg_send_http_error(conn,
  10388. 503,
  10389. "%s",
  10390. "Error: SSL forward not configured properly");
  10391. mg_cry(conn, "Can not redirect to SSL, no SSL port available");
  10392. }
  10393. return;
  10394. }
  10395. uri_len = (int)strlen(ri->local_uri);
  10396. /* 1.3. decode url (if config says so) */
  10397. if (should_decode_url(conn)) {
  10398. mg_url_decode(
  10399. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  10400. }
  10401. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  10402. * not possible */
  10403. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  10404. /* step 1. completed, the url is known now */
  10405. uri_len = (int)strlen(ri->local_uri);
  10406. DEBUG_TRACE("URL: %s", ri->local_uri);
  10407. /* 2. if this ip has limited speed, set it for this connection */
  10408. conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
  10409. get_remote_ip(conn),
  10410. ri->local_uri);
  10411. /* 3. call a "handle everything" callback, if registered */
  10412. if (conn->ctx->callbacks.begin_request != NULL) {
  10413. /* Note that since V1.7 the "begin_request" function is called
  10414. * before an authorization check. If an authorization check is
  10415. * required, use a request_handler instead. */
  10416. i = conn->ctx->callbacks.begin_request(conn);
  10417. if (i > 0) {
  10418. /* callback already processed the request. Store the
  10419. return value as a status code for the access log. */
  10420. conn->status_code = i;
  10421. discard_unread_request_data(conn);
  10422. return;
  10423. } else if (i == 0) {
  10424. /* civetweb should process the request */
  10425. } else {
  10426. /* unspecified - may change with the next version */
  10427. return;
  10428. }
  10429. }
  10430. /* request not yet handled by a handler or redirect, so the request
  10431. * is processed here */
  10432. /* 4. Check for CORS preflight requests and handle them (if configured).
  10433. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  10434. */
  10435. if (!strcmp(ri->request_method, "OPTIONS")) {
  10436. /* Send a response to CORS preflights only if
  10437. * access_control_allow_methods is not NULL and not an empty string.
  10438. * In this case, scripts can still handle CORS. */
  10439. const char *cors_meth_cfg =
  10440. conn->ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  10441. const char *cors_orig_cfg =
  10442. conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  10443. const char *cors_origin =
  10444. get_header(ri->http_headers, ri->num_headers, "Origin");
  10445. const char *cors_acrm = get_header(ri->http_headers,
  10446. ri->num_headers,
  10447. "Access-Control-Request-Method");
  10448. /* Todo: check if cors_origin is in cors_orig_cfg.
  10449. * Or, let the client check this. */
  10450. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  10451. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  10452. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  10453. /* This is a valid CORS preflight, and the server is configured
  10454. * to
  10455. * handle it automatically. */
  10456. const char *cors_acrh =
  10457. get_header(ri->http_headers,
  10458. ri->num_headers,
  10459. "Access-Control-Request-Headers");
  10460. gmt_time_string(date, sizeof(date), &curtime);
  10461. mg_printf(conn,
  10462. "HTTP/1.1 200 OK\r\n"
  10463. "Date: %s\r\n"
  10464. "Access-Control-Allow-Origin: %s\r\n"
  10465. "Access-Control-Allow-Methods: %s\r\n"
  10466. "Content-Length: 0\r\n"
  10467. "Connection: %s\r\n",
  10468. date,
  10469. cors_orig_cfg,
  10470. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  10471. suggest_connection_header(conn));
  10472. if (cors_acrh != NULL) {
  10473. /* CORS request is asking for additional headers */
  10474. const char *cors_hdr_cfg =
  10475. conn->ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  10476. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  10477. /* Allow only if access_control_allow_headers is
  10478. * not NULL and not an empty string. If this
  10479. * configuration is set to *, allow everything.
  10480. * Otherwise this configuration must be a list
  10481. * of allowed HTTP header names. */
  10482. mg_printf(conn,
  10483. "Access-Control-Allow-Headers: %s\r\n",
  10484. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  10485. : cors_hdr_cfg));
  10486. }
  10487. }
  10488. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  10489. mg_printf(conn, "\r\n");
  10490. return;
  10491. }
  10492. }
  10493. /* 5. interpret the url to find out how the request must be handled
  10494. */
  10495. /* 5.1. first test, if the request targets the regular http(s)://
  10496. * protocol namespace or the websocket ws(s):// protocol namespace.
  10497. */
  10498. is_websocket_request = is_websocket_protocol(conn);
  10499. #if defined(USE_WEBSOCKET)
  10500. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  10501. #else
  10502. handler_type = REQUEST_HANDLER;
  10503. #endif /* defined(USE_WEBSOCKET) */
  10504. /* 5.2. check if the request will be handled by a callback */
  10505. if (get_request_handler(conn,
  10506. handler_type,
  10507. &callback_handler,
  10508. &subprotocols,
  10509. &ws_connect_handler,
  10510. &ws_ready_handler,
  10511. &ws_data_handler,
  10512. &ws_close_handler,
  10513. NULL,
  10514. &callback_data)) {
  10515. /* 5.2.1. A callback will handle this request. All requests
  10516. * handled
  10517. * by a callback have to be considered as requests to a script
  10518. * resource. */
  10519. is_callback_resource = 1;
  10520. is_script_resource = 1;
  10521. is_put_or_delete_request = is_put_or_delete_method(conn);
  10522. } else {
  10523. no_callback_resource:
  10524. /* 5.2.2. No callback is responsible for this request. The URI
  10525. * addresses a file based resource (static content or Lua/cgi
  10526. * scripts in the file system). */
  10527. is_callback_resource = 0;
  10528. interpret_uri(conn,
  10529. path,
  10530. sizeof(path),
  10531. &file.stat,
  10532. &is_found,
  10533. &is_script_resource,
  10534. &is_websocket_request,
  10535. &is_put_or_delete_request);
  10536. }
  10537. /* 6. authorization check */
  10538. /* 6.1. a custom authorization handler is installed */
  10539. if (get_request_handler(conn,
  10540. AUTH_HANDLER,
  10541. NULL,
  10542. NULL,
  10543. NULL,
  10544. NULL,
  10545. NULL,
  10546. NULL,
  10547. &auth_handler,
  10548. &auth_callback_data)) {
  10549. if (!auth_handler(conn, auth_callback_data)) {
  10550. return;
  10551. }
  10552. } else if (is_put_or_delete_request && !is_script_resource
  10553. && !is_callback_resource) {
  10554. /* 6.2. this request is a PUT/DELETE to a real file */
  10555. /* 6.2.1. thus, the server must have real files */
  10556. #if defined(NO_FILES)
  10557. if (1) {
  10558. #else
  10559. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  10560. #endif
  10561. /* This server does not have any real files, thus the
  10562. * PUT/DELETE methods are not valid. */
  10563. mg_send_http_error(conn,
  10564. 405,
  10565. "%s method not allowed",
  10566. conn->request_info.request_method);
  10567. return;
  10568. }
  10569. #if !defined(NO_FILES)
  10570. /* 6.2.2. Check if put authorization for static files is
  10571. * available.
  10572. */
  10573. if (!is_authorized_for_put(conn)) {
  10574. send_authorization_request(conn);
  10575. return;
  10576. }
  10577. #endif
  10578. } else {
  10579. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  10580. * or it is a PUT or DELETE request to a resource that does not
  10581. * correspond to a file. Check authorization. */
  10582. if (!check_authorization(conn, path)) {
  10583. send_authorization_request(conn);
  10584. return;
  10585. }
  10586. }
  10587. /* request is authorized or does not need authorization */
  10588. /* 7. check if there are request handlers for this uri */
  10589. if (is_callback_resource) {
  10590. if (!is_websocket_request) {
  10591. i = callback_handler(conn, callback_data);
  10592. if (i > 0) {
  10593. /* Do nothing, callback has served the request. Store
  10594. * then return value as status code for the log and discard
  10595. * all data from the client not used by the callback. */
  10596. conn->status_code = i;
  10597. discard_unread_request_data(conn);
  10598. } else {
  10599. /* The handler did NOT handle the request. */
  10600. /* Some proper reactions would be:
  10601. * a) close the connections without sending anything
  10602. * b) send a 404 not found
  10603. * c) try if there is a file matching the URI
  10604. * It would be possible to do a, b or c in the callback
  10605. * implementation, and return 1 - we cannot do anything
  10606. * here, that is not possible in the callback.
  10607. *
  10608. * TODO: What would be the best reaction here?
  10609. * (Note: The reaction may change, if there is a better
  10610. *idea.)
  10611. */
  10612. /* For the moment, use option c: We look for a proper file,
  10613. * but since a file request is not always a script resource,
  10614. * the authorization check might be different. */
  10615. interpret_uri(conn,
  10616. path,
  10617. sizeof(path),
  10618. &file.stat,
  10619. &is_found,
  10620. &is_script_resource,
  10621. &is_websocket_request,
  10622. &is_put_or_delete_request);
  10623. callback_handler = NULL;
  10624. /* Here we are at a dead end:
  10625. * According to URI matching, a callback should be
  10626. * responsible for handling the request,
  10627. * we called it, but the callback declared itself
  10628. * not responsible.
  10629. * We use a goto here, to get out of this dead end,
  10630. * and continue with the default handling.
  10631. * A goto here is simpler and better to understand
  10632. * than some curious loop. */
  10633. goto no_callback_resource;
  10634. }
  10635. } else {
  10636. #if defined(USE_WEBSOCKET)
  10637. handle_websocket_request(conn,
  10638. path,
  10639. is_callback_resource,
  10640. subprotocols,
  10641. ws_connect_handler,
  10642. ws_ready_handler,
  10643. ws_data_handler,
  10644. ws_close_handler,
  10645. callback_data);
  10646. #endif
  10647. }
  10648. return;
  10649. }
  10650. /* 8. handle websocket requests */
  10651. #if defined(USE_WEBSOCKET)
  10652. if (is_websocket_request) {
  10653. if (is_script_resource) {
  10654. if (is_in_script_path(conn, path)) {
  10655. /* Websocket Lua script */
  10656. handle_websocket_request(conn,
  10657. path,
  10658. 0 /* Lua Script */,
  10659. NULL,
  10660. NULL,
  10661. NULL,
  10662. NULL,
  10663. NULL,
  10664. &conn->ctx->callbacks);
  10665. } else {
  10666. /* Script was in an illegal path */
  10667. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10668. }
  10669. } else {
  10670. #if defined(MG_LEGACY_INTERFACE)
  10671. handle_websocket_request(
  10672. conn,
  10673. path,
  10674. !is_script_resource /* could be deprecated global callback */,
  10675. NULL,
  10676. deprecated_websocket_connect_wrapper,
  10677. deprecated_websocket_ready_wrapper,
  10678. deprecated_websocket_data_wrapper,
  10679. NULL,
  10680. &conn->ctx->callbacks);
  10681. #else
  10682. mg_send_http_error(conn, 404, "%s", "Not found");
  10683. #endif
  10684. }
  10685. return;
  10686. } else
  10687. #endif
  10688. #if defined(NO_FILES)
  10689. /* 9a. In case the server uses only callbacks, this uri is
  10690. * unknown.
  10691. * Then, all request handling ends here. */
  10692. mg_send_http_error(conn, 404, "%s", "Not Found");
  10693. #else
  10694. /* 9b. This request is either for a static file or resource handled
  10695. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  10696. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  10697. mg_send_http_error(conn, 404, "%s", "Not Found");
  10698. return;
  10699. }
  10700. /* 10. Request is handled by a script */
  10701. if (is_script_resource) {
  10702. handle_file_based_request(conn, path, &file);
  10703. return;
  10704. }
  10705. /* 11. Handle put/delete/mkcol requests */
  10706. if (is_put_or_delete_request) {
  10707. /* 11.1. PUT method */
  10708. if (!strcmp(ri->request_method, "PUT")) {
  10709. put_file(conn, path);
  10710. return;
  10711. }
  10712. /* 11.2. DELETE method */
  10713. if (!strcmp(ri->request_method, "DELETE")) {
  10714. delete_file(conn, path);
  10715. return;
  10716. }
  10717. /* 11.3. MKCOL method */
  10718. if (!strcmp(ri->request_method, "MKCOL")) {
  10719. mkcol(conn, path);
  10720. return;
  10721. }
  10722. /* 11.4. PATCH method
  10723. * This method is not supported for static resources,
  10724. * only for scripts (Lua, CGI) and callbacks. */
  10725. mg_send_http_error(conn,
  10726. 405,
  10727. "%s method not allowed",
  10728. conn->request_info.request_method);
  10729. return;
  10730. }
  10731. /* 11. File does not exist, or it was configured that it should be
  10732. * hidden */
  10733. if (!is_found || (must_hide_file(conn, path))) {
  10734. mg_send_http_error(conn, 404, "%s", "Not found");
  10735. return;
  10736. }
  10737. /* 12. Directory uris should end with a slash */
  10738. if (file.stat.is_directory && (uri_len > 0)
  10739. && (ri->local_uri[uri_len - 1] != '/')) {
  10740. gmt_time_string(date, sizeof(date), &curtime);
  10741. mg_printf(conn,
  10742. "HTTP/1.1 301 Moved Permanently\r\n"
  10743. "Location: %s/\r\n"
  10744. "Date: %s\r\n"
  10745. /* "Cache-Control: private\r\n" (= default) */
  10746. "Content-Length: 0\r\n"
  10747. "Connection: %s\r\n",
  10748. ri->request_uri,
  10749. date,
  10750. suggest_connection_header(conn));
  10751. send_additional_header(conn);
  10752. mg_printf(conn, "\r\n");
  10753. return;
  10754. }
  10755. /* 13. Handle other methods than GET/HEAD */
  10756. /* 13.1. Handle PROPFIND */
  10757. if (!strcmp(ri->request_method, "PROPFIND")) {
  10758. handle_propfind(conn, path, &file.stat);
  10759. return;
  10760. }
  10761. /* 13.2. Handle OPTIONS for files */
  10762. if (!strcmp(ri->request_method, "OPTIONS")) {
  10763. /* This standard handler is only used for real files.
  10764. * Scripts should support the OPTIONS method themselves, to allow a
  10765. * maximum flexibility.
  10766. * Lua and CGI scripts may fully support CORS this way (including
  10767. * preflights). */
  10768. send_options(conn);
  10769. return;
  10770. }
  10771. /* 13.3. everything but GET and HEAD (e.g. POST) */
  10772. if ((0 != strcmp(ri->request_method, "GET"))
  10773. && (0 != strcmp(ri->request_method, "HEAD"))) {
  10774. mg_send_http_error(conn,
  10775. 405,
  10776. "%s method not allowed",
  10777. conn->request_info.request_method);
  10778. return;
  10779. }
  10780. /* 14. directories */
  10781. if (file.stat.is_directory) {
  10782. /* Substitute files have already been handled above. */
  10783. /* Here we can either generate and send a directory listing,
  10784. * or send an "access denied" error. */
  10785. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  10786. "yes")) {
  10787. handle_directory_request(conn, path);
  10788. } else {
  10789. mg_send_http_error(conn,
  10790. 403,
  10791. "%s",
  10792. "Error: Directory listing denied");
  10793. }
  10794. return;
  10795. }
  10796. handle_file_based_request(conn, path, &file);
  10797. #endif /* !defined(NO_FILES) */
  10798. #if 0
  10799. /* Perform redirect and auth checks before calling begin_request()
  10800. * handler.
  10801. * Otherwise, begin_request() would need to perform auth checks and
  10802. * redirects. */
  10803. #endif
  10804. }
  10805. static void
  10806. handle_file_based_request(struct mg_connection *conn,
  10807. const char *path,
  10808. struct mg_file *file)
  10809. {
  10810. if (!conn || !conn->ctx) {
  10811. return;
  10812. }
  10813. if (0) {
  10814. #ifdef USE_LUA
  10815. } else if (match_prefix(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  10816. strlen(
  10817. conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  10818. path) > 0) {
  10819. if (is_in_script_path(conn, path)) {
  10820. /* Lua server page: an SSI like page containing mostly plain
  10821. * html
  10822. * code
  10823. * plus some tags with server generated contents. */
  10824. handle_lsp_request(conn, path, file, NULL);
  10825. } else {
  10826. /* Script was in an illegal path */
  10827. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10828. }
  10829. } else if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  10830. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  10831. path) > 0) {
  10832. if (is_in_script_path(conn, path)) {
  10833. /* Lua in-server module script: a CGI like script used to
  10834. * generate
  10835. * the
  10836. * entire reply. */
  10837. mg_exec_lua_script(conn, path, NULL);
  10838. } else {
  10839. /* Script was in an illegal path */
  10840. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10841. }
  10842. #endif
  10843. #if defined(USE_DUKTAPE)
  10844. } else if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  10845. strlen(
  10846. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  10847. path) > 0) {
  10848. if (is_in_script_path(conn, path)) {
  10849. /* Call duktape to generate the page */
  10850. mg_exec_duktape_script(conn, path);
  10851. } else {
  10852. /* Script was in an illegal path */
  10853. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10854. }
  10855. #endif
  10856. #if !defined(NO_CGI)
  10857. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  10858. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  10859. path) > 0) {
  10860. if (is_in_script_path(conn, path)) {
  10861. /* CGI scripts may support all HTTP methods */
  10862. handle_cgi_request(conn, path);
  10863. } else {
  10864. /* Script was in an illegal path */
  10865. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10866. }
  10867. #endif /* !NO_CGI */
  10868. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  10869. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  10870. path) > 0) {
  10871. if (is_in_script_path(conn, path)) {
  10872. handle_ssi_file_request(conn, path, file);
  10873. } else {
  10874. /* Script was in an illegal path */
  10875. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10876. }
  10877. #if !defined(NO_CACHING)
  10878. } else if ((!conn->in_error_handler)
  10879. && is_not_modified(conn, &file->stat)) {
  10880. /* Send 304 "Not Modified" - this must not send any body data */
  10881. handle_not_modified_static_file_request(conn, file);
  10882. #endif /* !NO_CACHING */
  10883. } else {
  10884. handle_static_file_request(conn, path, file, NULL, NULL);
  10885. }
  10886. }
  10887. static void
  10888. close_all_listening_sockets(struct mg_context *ctx)
  10889. {
  10890. unsigned int i;
  10891. if (!ctx) {
  10892. return;
  10893. }
  10894. for (i = 0; i < ctx->num_listening_sockets; i++) {
  10895. closesocket(ctx->listening_sockets[i].sock);
  10896. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  10897. }
  10898. mg_free(ctx->listening_sockets);
  10899. ctx->listening_sockets = NULL;
  10900. mg_free(ctx->listening_socket_fds);
  10901. ctx->listening_socket_fds = NULL;
  10902. }
  10903. /* Valid listening port specification is: [ip_address:]port[s]
  10904. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  10905. * Examples for IPv6: [::]:80, [::1]:80,
  10906. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  10907. * see https://tools.ietf.org/html/rfc3513#section-2.2
  10908. * In order to bind to both, IPv4 and IPv6, you can either add
  10909. * both ports using 8080,[::]:8080, or the short form +8080.
  10910. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  10911. * one only accepting IPv4 the other only IPv6. +8080 creates
  10912. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  10913. * environment, they might work differently, or might not work
  10914. * at all - it must be tested what options work best in the
  10915. * relevant network environment.
  10916. */
  10917. static int
  10918. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  10919. {
  10920. unsigned int a, b, c, d, port;
  10921. int ch, len;
  10922. char *cb;
  10923. #if defined(USE_IPV6)
  10924. char buf[100] = {0};
  10925. #endif
  10926. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  10927. * Also, all-zeroes in the socket address means binding to all addresses
  10928. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  10929. memset(so, 0, sizeof(*so));
  10930. so->lsa.sin.sin_family = AF_INET;
  10931. *ip_version = 0;
  10932. /* Initialize port and len as invalid. */
  10933. port = 0;
  10934. len = 0;
  10935. /* Test for different ways to format this string */
  10936. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  10937. == 5) {
  10938. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  10939. so->lsa.sin.sin_addr.s_addr =
  10940. htonl((a << 24) | (b << 16) | (c << 8) | d);
  10941. so->lsa.sin.sin_port = htons((uint16_t)port);
  10942. *ip_version = 4;
  10943. #if defined(USE_IPV6)
  10944. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  10945. && mg_inet_pton(
  10946. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  10947. /* IPv6 address, examples: see above */
  10948. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  10949. */
  10950. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  10951. *ip_version = 6;
  10952. #endif
  10953. } else if ((vec->ptr[0] == '+')
  10954. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  10955. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  10956. /* Add 1 to len for the + character we skipped before */
  10957. len++;
  10958. #if defined(USE_IPV6)
  10959. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  10960. so->lsa.sin6.sin6_family = AF_INET6;
  10961. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  10962. *ip_version = 4 + 6;
  10963. #else
  10964. /* Bind to IPv4 only, since IPv6 is not built in. */
  10965. so->lsa.sin.sin_port = htons((uint16_t)port);
  10966. *ip_version = 4;
  10967. #endif
  10968. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  10969. /* If only port is specified, bind to IPv4, INADDR_ANY */
  10970. so->lsa.sin.sin_port = htons((uint16_t)port);
  10971. *ip_version = 4;
  10972. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  10973. /* Could be a hostname */
  10974. /* Will only work for RFC 952 compliant hostnames,
  10975. * starting with a letter, containing only letters,
  10976. * digits and hyphen ('-'). Newer specs may allow
  10977. * more, but this is not guaranteed here, since it
  10978. * may interfere with rules for port option lists. */
  10979. *cb = 0;
  10980. if (mg_inet_pton(
  10981. AF_INET, vec->ptr, &so->lsa.sin, sizeof(so->lsa.sin))) {
  10982. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  10983. *ip_version = 4;
  10984. so->lsa.sin.sin_family = AF_INET;
  10985. so->lsa.sin.sin_port = htons((uint16_t)port);
  10986. len += (int)(cb - vec->ptr) + 1;
  10987. } else {
  10988. port = 0;
  10989. len = 0;
  10990. }
  10991. #if defined(USE_IPV6)
  10992. } else if (mg_inet_pton(AF_INET6,
  10993. vec->ptr,
  10994. &so->lsa.sin6,
  10995. sizeof(so->lsa.sin6))) {
  10996. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  10997. *ip_version = 6;
  10998. so->lsa.sin6.sin6_family = AF_INET6;
  10999. so->lsa.sin.sin_port = htons((uint16_t)port);
  11000. len += (int)(cb - vec->ptr) + 1;
  11001. } else {
  11002. port = 0;
  11003. len = 0;
  11004. }
  11005. #endif
  11006. }
  11007. *cb = ':';
  11008. } else {
  11009. /* Parsing failure. */
  11010. }
  11011. /* sscanf and the option splitting code ensure the following condition
  11012. */
  11013. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  11014. *ip_version = 0;
  11015. return 0;
  11016. }
  11017. ch = vec->ptr[len]; /* Next character after the port number */
  11018. so->is_ssl = (ch == 's');
  11019. so->ssl_redir = (ch == 'r');
  11020. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  11021. if (is_valid_port(port)
  11022. && ((ch == '\0') || (ch == 's') || (ch == 'r') || (ch == ','))) {
  11023. return 1;
  11024. }
  11025. /* Reset ip_version to 0 of there is an error */
  11026. *ip_version = 0;
  11027. return 0;
  11028. }
  11029. static int
  11030. set_ports_option(struct mg_context *ctx)
  11031. {
  11032. const char *list;
  11033. int on = 1;
  11034. #if defined(USE_IPV6)
  11035. int off = 0;
  11036. #endif
  11037. struct vec vec;
  11038. struct socket so, *ptr;
  11039. struct pollfd *pfd;
  11040. union usa usa;
  11041. socklen_t len;
  11042. int ip_version;
  11043. int portsTotal = 0;
  11044. int portsOk = 0;
  11045. if (!ctx) {
  11046. return 0;
  11047. }
  11048. memset(&so, 0, sizeof(so));
  11049. memset(&usa, 0, sizeof(usa));
  11050. len = sizeof(usa);
  11051. list = ctx->config[LISTENING_PORTS];
  11052. while ((list = next_option(list, &vec, NULL)) != NULL) {
  11053. portsTotal++;
  11054. if (!parse_port_string(&vec, &so, &ip_version)) {
  11055. mg_cry(fc(ctx),
  11056. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  11057. (int)vec.len,
  11058. vec.ptr,
  11059. portsTotal,
  11060. "[IP_ADDRESS:]PORT[s|r]");
  11061. continue;
  11062. }
  11063. #if !defined(NO_SSL)
  11064. if (so.is_ssl && ctx->ssl_ctx == NULL) {
  11065. mg_cry(fc(ctx),
  11066. "Cannot add SSL socket (entry %i). Is -ssl_certificate "
  11067. "option set?",
  11068. portsTotal);
  11069. continue;
  11070. }
  11071. #endif
  11072. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  11073. == INVALID_SOCKET) {
  11074. mg_cry(fc(ctx), "cannot create socket (entry %i)", portsTotal);
  11075. continue;
  11076. }
  11077. #ifdef _WIN32
  11078. /* Windows SO_REUSEADDR lets many procs binds to a
  11079. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  11080. * if someone already has the socket -- DTL */
  11081. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  11082. * Windows might need a few seconds before
  11083. * the same port can be used again in the
  11084. * same process, so a short Sleep may be
  11085. * required between mg_stop and mg_start.
  11086. */
  11087. if (setsockopt(so.sock,
  11088. SOL_SOCKET,
  11089. SO_EXCLUSIVEADDRUSE,
  11090. (SOCK_OPT_TYPE)&on,
  11091. sizeof(on)) != 0) {
  11092. /* Set reuse option, but don't abort on errors. */
  11093. mg_cry(fc(ctx),
  11094. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  11095. portsTotal);
  11096. }
  11097. #else
  11098. if (setsockopt(so.sock,
  11099. SOL_SOCKET,
  11100. SO_REUSEADDR,
  11101. (SOCK_OPT_TYPE)&on,
  11102. sizeof(on)) != 0) {
  11103. /* Set reuse option, but don't abort on errors. */
  11104. mg_cry(fc(ctx),
  11105. "cannot set socket option SO_REUSEADDR (entry %i)",
  11106. portsTotal);
  11107. }
  11108. #endif
  11109. if (ip_version > 4) {
  11110. #if defined(USE_IPV6)
  11111. if (ip_version == 6) {
  11112. if (so.lsa.sa.sa_family == AF_INET6
  11113. && setsockopt(so.sock,
  11114. IPPROTO_IPV6,
  11115. IPV6_V6ONLY,
  11116. (void *)&off,
  11117. sizeof(off)) != 0) {
  11118. /* Set IPv6 only option, but don't abort on errors. */
  11119. mg_cry(fc(ctx),
  11120. "cannot set socket option IPV6_V6ONLY (entry %i)",
  11121. portsTotal);
  11122. }
  11123. }
  11124. #else
  11125. mg_cry(fc(ctx), "IPv6 not available");
  11126. closesocket(so.sock);
  11127. so.sock = INVALID_SOCKET;
  11128. continue;
  11129. #endif
  11130. }
  11131. if (so.lsa.sa.sa_family == AF_INET) {
  11132. len = sizeof(so.lsa.sin);
  11133. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  11134. mg_cry(fc(ctx),
  11135. "cannot bind to %.*s: %d (%s)",
  11136. (int)vec.len,
  11137. vec.ptr,
  11138. (int)ERRNO,
  11139. strerror(errno));
  11140. closesocket(so.sock);
  11141. so.sock = INVALID_SOCKET;
  11142. continue;
  11143. }
  11144. }
  11145. #if defined(USE_IPV6)
  11146. else if (so.lsa.sa.sa_family == AF_INET6) {
  11147. len = sizeof(so.lsa.sin6);
  11148. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  11149. mg_cry(fc(ctx),
  11150. "cannot bind to IPv6 %.*s: %d (%s)",
  11151. (int)vec.len,
  11152. vec.ptr,
  11153. (int)ERRNO,
  11154. strerror(errno));
  11155. closesocket(so.sock);
  11156. so.sock = INVALID_SOCKET;
  11157. continue;
  11158. }
  11159. }
  11160. #endif
  11161. else {
  11162. mg_cry(fc(ctx),
  11163. "cannot bind: address family not supported (entry %i)",
  11164. portsTotal);
  11165. closesocket(so.sock);
  11166. so.sock = INVALID_SOCKET;
  11167. continue;
  11168. }
  11169. if (listen(so.sock, SOMAXCONN) != 0) {
  11170. mg_cry(fc(ctx),
  11171. "cannot listen to %.*s: %d (%s)",
  11172. (int)vec.len,
  11173. vec.ptr,
  11174. (int)ERRNO,
  11175. strerror(errno));
  11176. closesocket(so.sock);
  11177. so.sock = INVALID_SOCKET;
  11178. continue;
  11179. }
  11180. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  11181. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  11182. int err = (int)ERRNO;
  11183. mg_cry(fc(ctx),
  11184. "call to getsockname failed %.*s: %d (%s)",
  11185. (int)vec.len,
  11186. vec.ptr,
  11187. err,
  11188. strerror(errno));
  11189. closesocket(so.sock);
  11190. so.sock = INVALID_SOCKET;
  11191. continue;
  11192. }
  11193. /* Update lsa port in case of random free ports */
  11194. #if defined(USE_IPV6)
  11195. if (so.lsa.sa.sa_family == AF_INET6) {
  11196. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  11197. } else
  11198. #endif
  11199. {
  11200. so.lsa.sin.sin_port = usa.sin.sin_port;
  11201. }
  11202. if ((ptr = (struct socket *)
  11203. mg_realloc_ctx(ctx->listening_sockets,
  11204. (ctx->num_listening_sockets + 1)
  11205. * sizeof(ctx->listening_sockets[0]),
  11206. ctx)) == NULL) {
  11207. mg_cry(fc(ctx), "%s", "Out of memory");
  11208. closesocket(so.sock);
  11209. so.sock = INVALID_SOCKET;
  11210. continue;
  11211. }
  11212. if ((pfd = (struct pollfd *)
  11213. mg_realloc_ctx(ctx->listening_socket_fds,
  11214. (ctx->num_listening_sockets + 1)
  11215. * sizeof(ctx->listening_socket_fds[0]),
  11216. ctx)) == NULL) {
  11217. mg_cry(fc(ctx), "%s", "Out of memory");
  11218. closesocket(so.sock);
  11219. so.sock = INVALID_SOCKET;
  11220. mg_free(ptr);
  11221. continue;
  11222. }
  11223. set_close_on_exec(so.sock, fc(ctx));
  11224. ctx->listening_sockets = ptr;
  11225. ctx->listening_sockets[ctx->num_listening_sockets] = so;
  11226. ctx->listening_socket_fds = pfd;
  11227. ctx->num_listening_sockets++;
  11228. portsOk++;
  11229. }
  11230. if (portsOk != portsTotal) {
  11231. close_all_listening_sockets(ctx);
  11232. portsOk = 0;
  11233. }
  11234. return portsOk;
  11235. }
  11236. static const char *
  11237. header_val(const struct mg_connection *conn, const char *header)
  11238. {
  11239. const char *header_value;
  11240. if ((header_value = mg_get_header(conn, header)) == NULL) {
  11241. return "-";
  11242. } else {
  11243. return header_value;
  11244. }
  11245. }
  11246. static void
  11247. log_access(const struct mg_connection *conn)
  11248. {
  11249. const struct mg_request_info *ri;
  11250. struct mg_file fi;
  11251. char date[64], src_addr[IP_ADDR_STR_LEN];
  11252. struct tm *tm;
  11253. const char *referer;
  11254. const char *user_agent;
  11255. char buf[4096];
  11256. if (!conn || !conn->ctx) {
  11257. return;
  11258. }
  11259. if (conn->ctx->config[ACCESS_LOG_FILE] != NULL) {
  11260. if (mg_fopen(conn,
  11261. conn->ctx->config[ACCESS_LOG_FILE],
  11262. MG_FOPEN_MODE_APPEND,
  11263. &fi) == 0) {
  11264. fi.access.fp = NULL;
  11265. }
  11266. } else {
  11267. fi.access.fp = NULL;
  11268. }
  11269. /* Log is written to a file and/or a callback. If both are not set,
  11270. * executing the rest of the function is pointless. */
  11271. if ((fi.access.fp == NULL) && (conn->ctx->callbacks.log_access == NULL)) {
  11272. return;
  11273. }
  11274. tm = localtime(&conn->conn_birth_time);
  11275. if (tm != NULL) {
  11276. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  11277. } else {
  11278. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  11279. date[sizeof(date) - 1] = '\0';
  11280. }
  11281. ri = &conn->request_info;
  11282. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  11283. referer = header_val(conn, "Referer");
  11284. user_agent = header_val(conn, "User-Agent");
  11285. mg_snprintf(conn,
  11286. NULL, /* Ignore truncation in access log */
  11287. buf,
  11288. sizeof(buf),
  11289. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  11290. src_addr,
  11291. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  11292. date,
  11293. ri->request_method ? ri->request_method : "-",
  11294. ri->request_uri ? ri->request_uri : "-",
  11295. ri->query_string ? "?" : "",
  11296. ri->query_string ? ri->query_string : "",
  11297. ri->http_version,
  11298. conn->status_code,
  11299. conn->num_bytes_sent,
  11300. referer,
  11301. user_agent);
  11302. if (conn->ctx->callbacks.log_access) {
  11303. conn->ctx->callbacks.log_access(conn, buf);
  11304. }
  11305. if (fi.access.fp) {
  11306. int ok = 1;
  11307. flockfile(fi.access.fp);
  11308. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  11309. ok = 0;
  11310. }
  11311. if (fflush(fi.access.fp) != 0) {
  11312. ok = 0;
  11313. }
  11314. funlockfile(fi.access.fp);
  11315. if (mg_fclose(&fi.access) != 0) {
  11316. ok = 0;
  11317. }
  11318. if (!ok) {
  11319. mg_cry(conn,
  11320. "Error writing log file %s",
  11321. conn->ctx->config[ACCESS_LOG_FILE]);
  11322. }
  11323. }
  11324. }
  11325. /* Verify given socket address against the ACL.
  11326. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  11327. */
  11328. static int
  11329. check_acl(struct mg_context *ctx, uint32_t remote_ip)
  11330. {
  11331. int allowed, flag;
  11332. uint32_t net, mask;
  11333. struct vec vec;
  11334. if (ctx) {
  11335. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  11336. /* If any ACL is set, deny by default */
  11337. allowed = (list == NULL) ? '+' : '-';
  11338. while ((list = next_option(list, &vec, NULL)) != NULL) {
  11339. flag = vec.ptr[0];
  11340. if ((flag != '+' && flag != '-')
  11341. || (parse_net(&vec.ptr[1], &net, &mask) == 0)) {
  11342. mg_cry(fc(ctx),
  11343. "%s: subnet must be [+|-]x.x.x.x[/x]",
  11344. __func__);
  11345. return -1;
  11346. }
  11347. if (net == (remote_ip & mask)) {
  11348. allowed = flag;
  11349. }
  11350. }
  11351. return allowed == '+';
  11352. }
  11353. return -1;
  11354. }
  11355. #if !defined(_WIN32)
  11356. static int
  11357. set_uid_option(struct mg_context *ctx)
  11358. {
  11359. struct passwd *pw;
  11360. if (ctx) {
  11361. const char *uid = ctx->config[RUN_AS_USER];
  11362. int success = 0;
  11363. if (uid == NULL) {
  11364. success = 1;
  11365. } else {
  11366. if ((pw = getpwnam(uid)) == NULL) {
  11367. mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  11368. } else if (setgid(pw->pw_gid) == -1) {
  11369. mg_cry(fc(ctx),
  11370. "%s: setgid(%s): %s",
  11371. __func__,
  11372. uid,
  11373. strerror(errno));
  11374. } else if (setgroups(0, NULL)) {
  11375. mg_cry(fc(ctx),
  11376. "%s: setgroups(): %s",
  11377. __func__,
  11378. strerror(errno));
  11379. } else if (setuid(pw->pw_uid) == -1) {
  11380. mg_cry(fc(ctx),
  11381. "%s: setuid(%s): %s",
  11382. __func__,
  11383. uid,
  11384. strerror(errno));
  11385. } else {
  11386. success = 1;
  11387. }
  11388. }
  11389. return success;
  11390. }
  11391. return 0;
  11392. }
  11393. #endif /* !_WIN32 */
  11394. static void
  11395. tls_dtor(void *key)
  11396. {
  11397. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  11398. /* key == pthread_getspecific(sTlsKey); */
  11399. if (tls) {
  11400. if (tls->is_master == 2) {
  11401. tls->is_master = -3; /* Mark memory as dead */
  11402. mg_free(tls);
  11403. }
  11404. }
  11405. pthread_setspecific(sTlsKey, NULL);
  11406. }
  11407. #if !defined(NO_SSL)
  11408. static int
  11409. ssl_use_pem_file(struct mg_context *ctx, const char *pem, const char *chain);
  11410. static const char *ssl_error(void);
  11411. static int
  11412. refresh_trust(struct mg_connection *conn)
  11413. {
  11414. static int reload_lock = 0;
  11415. static long int data_check = 0;
  11416. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  11417. struct stat cert_buf;
  11418. long int t;
  11419. const char *pem;
  11420. const char *chain;
  11421. int should_verify_peer;
  11422. if ((pem = conn->ctx->config[SSL_CERTIFICATE]) == NULL) {
  11423. /* If peem is NULL and conn->ctx->callbacks.init_ssl is not,
  11424. * refresh_trust still can not work. */
  11425. return 0;
  11426. }
  11427. chain = conn->ctx->config[SSL_CERTIFICATE_CHAIN];
  11428. if (chain == NULL) {
  11429. /* pem is not NULL here */
  11430. chain = pem;
  11431. }
  11432. if (*chain == 0) {
  11433. chain = NULL;
  11434. }
  11435. t = data_check;
  11436. if (stat(pem, &cert_buf) != -1) {
  11437. t = (long int)cert_buf.st_mtime;
  11438. }
  11439. if (data_check != t) {
  11440. data_check = t;
  11441. should_verify_peer = 0;
  11442. if (conn->ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  11443. if (mg_strcasecmp(conn->ctx->config[SSL_DO_VERIFY_PEER], "yes")
  11444. == 0) {
  11445. should_verify_peer = 1;
  11446. } else if (mg_strcasecmp(conn->ctx->config[SSL_DO_VERIFY_PEER],
  11447. "optional") == 0) {
  11448. should_verify_peer = 1;
  11449. }
  11450. }
  11451. if (should_verify_peer) {
  11452. char *ca_path = conn->ctx->config[SSL_CA_PATH];
  11453. char *ca_file = conn->ctx->config[SSL_CA_FILE];
  11454. if (SSL_CTX_load_verify_locations(conn->ctx->ssl_ctx,
  11455. ca_file,
  11456. ca_path) != 1) {
  11457. mg_cry(fc(conn->ctx),
  11458. "SSL_CTX_load_verify_locations error: %s "
  11459. "ssl_verify_peer requires setting "
  11460. "either ssl_ca_path or ssl_ca_file. Is any of them "
  11461. "present in "
  11462. "the .conf file?",
  11463. ssl_error());
  11464. return 0;
  11465. }
  11466. }
  11467. if (1 == mg_atomic_inc(p_reload_lock)) {
  11468. if (ssl_use_pem_file(conn->ctx, pem, chain) == 0) {
  11469. return 0;
  11470. }
  11471. *p_reload_lock = 0;
  11472. }
  11473. }
  11474. /* lock while cert is reloading */
  11475. while (*p_reload_lock) {
  11476. sleep(1);
  11477. }
  11478. return 1;
  11479. }
  11480. #ifdef OPENSSL_API_1_1
  11481. #else
  11482. static pthread_mutex_t *ssl_mutexes;
  11483. #endif /* OPENSSL_API_1_1 */
  11484. static int
  11485. sslize(struct mg_connection *conn,
  11486. SSL_CTX *s,
  11487. int (*func)(SSL *),
  11488. volatile int *stop_server)
  11489. {
  11490. int ret, err;
  11491. int short_trust;
  11492. unsigned i;
  11493. if (!conn) {
  11494. return 0;
  11495. }
  11496. short_trust =
  11497. (conn->ctx->config[SSL_SHORT_TRUST] != NULL)
  11498. && (mg_strcasecmp(conn->ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  11499. if (short_trust) {
  11500. int trust_ret = refresh_trust(conn);
  11501. if (!trust_ret) {
  11502. return trust_ret;
  11503. }
  11504. }
  11505. conn->ssl = SSL_new(s);
  11506. if (conn->ssl == NULL) {
  11507. return 0;
  11508. }
  11509. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  11510. if (ret != 1) {
  11511. err = SSL_get_error(conn->ssl, ret);
  11512. (void)err; /* TODO: set some error message */
  11513. SSL_free(conn->ssl);
  11514. conn->ssl = NULL;
  11515. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  11516. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  11517. #ifndef OPENSSL_API_1_1
  11518. ERR_remove_state(0);
  11519. #endif
  11520. return 0;
  11521. }
  11522. /* SSL functions may fail and require to be called again:
  11523. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  11524. * Here "func" could be SSL_connect or SSL_accept. */
  11525. for (i = 16; i <= 1024; i *= 2) {
  11526. ret = func(conn->ssl);
  11527. if (ret != 1) {
  11528. err = SSL_get_error(conn->ssl, ret);
  11529. if ((err == SSL_ERROR_WANT_CONNECT)
  11530. || (err == SSL_ERROR_WANT_ACCEPT)
  11531. || (err == SSL_ERROR_WANT_READ)
  11532. || (err == SSL_ERROR_WANT_WRITE)) {
  11533. /* Need to retry the function call "later".
  11534. * See https://linux.die.net/man/3/ssl_get_error
  11535. * This is typical for non-blocking sockets. */
  11536. if (*stop_server) {
  11537. /* Don't wait if the server is going to be stopped. */
  11538. break;
  11539. }
  11540. mg_sleep(i);
  11541. } else if (err == SSL_ERROR_SYSCALL) {
  11542. /* This is an IO error. Look at errno. */
  11543. err = errno;
  11544. /* TODO: set some error message */
  11545. (void)err;
  11546. break;
  11547. } else {
  11548. /* This is an SSL specific error */
  11549. /* TODO: set some error message */
  11550. break;
  11551. }
  11552. } else {
  11553. /* success */
  11554. break;
  11555. }
  11556. }
  11557. if (ret != 1) {
  11558. SSL_free(conn->ssl);
  11559. conn->ssl = NULL;
  11560. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  11561. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  11562. #ifndef OPENSSL_API_1_1
  11563. ERR_remove_state(0);
  11564. #endif
  11565. return 0;
  11566. }
  11567. return 1;
  11568. }
  11569. /* Return OpenSSL error message (from CRYPTO lib) */
  11570. static const char *
  11571. ssl_error(void)
  11572. {
  11573. unsigned long err;
  11574. err = ERR_get_error();
  11575. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  11576. }
  11577. static int
  11578. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  11579. {
  11580. int i;
  11581. const char hexdigit[] = "0123456789abcdef";
  11582. if ((memlen <= 0) || (buflen <= 0)) {
  11583. return 0;
  11584. }
  11585. if (buflen < (3 * memlen)) {
  11586. return 0;
  11587. }
  11588. for (i = 0; i < memlen; i++) {
  11589. if (i > 0) {
  11590. buf[3 * i - 1] = ' ';
  11591. }
  11592. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  11593. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  11594. }
  11595. buf[3 * memlen - 1] = 0;
  11596. return 1;
  11597. }
  11598. static void
  11599. ssl_get_client_cert_info(struct mg_connection *conn)
  11600. {
  11601. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  11602. if (cert) {
  11603. char str_subject[1024];
  11604. char str_issuer[1024];
  11605. char str_finger[1024];
  11606. unsigned char buf[256];
  11607. char *str_serial = NULL;
  11608. unsigned int ulen;
  11609. int ilen;
  11610. unsigned char *tmp_buf;
  11611. unsigned char *tmp_p;
  11612. /* Handle to algorithm used for fingerprint */
  11613. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  11614. /* Get Subject and issuer */
  11615. X509_NAME *subj = X509_get_subject_name(cert);
  11616. X509_NAME *iss = X509_get_issuer_name(cert);
  11617. /* Get serial number */
  11618. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  11619. /* Translate serial number to a hex string */
  11620. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  11621. str_serial = BN_bn2hex(serial_bn);
  11622. BN_free(serial_bn);
  11623. /* Translate subject and issuer to a string */
  11624. (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
  11625. (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
  11626. /* Calculate SHA1 fingerprint and store as a hex string */
  11627. ulen = 0;
  11628. /* ASN1_digest is deprecated. Do the calculation manually,
  11629. * using EVP_Digest. */
  11630. ilen = i2d_X509((void *)cert, NULL);
  11631. tmp_buf =
  11632. (ilen > 0)
  11633. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1, conn->ctx)
  11634. : NULL;
  11635. if (tmp_buf) {
  11636. tmp_p = tmp_buf;
  11637. (void)i2d_X509((void *)cert, &tmp_p);
  11638. if (!EVP_Digest(
  11639. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  11640. ulen = 0;
  11641. }
  11642. mg_free(tmp_buf);
  11643. }
  11644. if (!hexdump2string(
  11645. buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
  11646. *str_finger = 0;
  11647. }
  11648. conn->request_info.client_cert =
  11649. (struct client_cert *)mg_malloc_ctx(sizeof(struct client_cert),
  11650. conn->ctx);
  11651. if (conn->request_info.client_cert) {
  11652. conn->request_info.client_cert->subject = mg_strdup(str_subject);
  11653. conn->request_info.client_cert->issuer = mg_strdup(str_issuer);
  11654. conn->request_info.client_cert->serial = mg_strdup(str_serial);
  11655. conn->request_info.client_cert->finger = mg_strdup(str_finger);
  11656. } else {
  11657. mg_cry(conn,
  11658. "Out of memory: Cannot allocate memory for client "
  11659. "certificate");
  11660. }
  11661. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  11662. * see https://linux.die.net/man/3/bn_bn2hex */
  11663. OPENSSL_free(str_serial);
  11664. /* Free certificate memory */
  11665. X509_free(cert);
  11666. }
  11667. }
  11668. #ifdef OPENSSL_API_1_1
  11669. #else
  11670. static void
  11671. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  11672. {
  11673. (void)line;
  11674. (void)file;
  11675. if (mode & 1) {
  11676. /* 1 is CRYPTO_LOCK */
  11677. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  11678. } else {
  11679. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  11680. }
  11681. }
  11682. #endif /* OPENSSL_API_1_1 */
  11683. #if !defined(NO_SSL_DL)
  11684. static void *
  11685. load_dll(char *ebuf, size_t ebuf_len, const char *dll_name, struct ssl_func *sw)
  11686. {
  11687. union {
  11688. void *p;
  11689. void (*fp)(void);
  11690. } u;
  11691. void *dll_handle;
  11692. struct ssl_func *fp;
  11693. int ok;
  11694. int truncated = 0;
  11695. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  11696. mg_snprintf(NULL,
  11697. NULL, /* No truncation check for ebuf */
  11698. ebuf,
  11699. ebuf_len,
  11700. "%s: cannot load %s",
  11701. __func__,
  11702. dll_name);
  11703. return NULL;
  11704. }
  11705. ok = 1;
  11706. for (fp = sw; fp->name != NULL; fp++) {
  11707. #ifdef _WIN32
  11708. /* GetProcAddress() returns pointer to function */
  11709. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  11710. #else
  11711. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  11712. * pointers to function pointers. We need to use a union to make a
  11713. * cast. */
  11714. u.p = dlsym(dll_handle, fp->name);
  11715. #endif /* _WIN32 */
  11716. if (u.fp == NULL) {
  11717. if (ok) {
  11718. mg_snprintf(NULL,
  11719. &truncated,
  11720. ebuf,
  11721. ebuf_len,
  11722. "%s: %s: cannot find %s",
  11723. __func__,
  11724. dll_name,
  11725. fp->name);
  11726. ok = 0;
  11727. } else {
  11728. size_t cur_len = strlen(ebuf);
  11729. if (!truncated) {
  11730. mg_snprintf(NULL,
  11731. &truncated,
  11732. ebuf + cur_len,
  11733. ebuf_len - cur_len - 3,
  11734. ", %s",
  11735. fp->name);
  11736. if (truncated) {
  11737. /* If truncated, add "..." */
  11738. strcat(ebuf, "...");
  11739. }
  11740. }
  11741. }
  11742. /* Debug:
  11743. * printf("Missing function: %s\n", fp->name); */
  11744. } else {
  11745. fp->ptr = u.fp;
  11746. }
  11747. }
  11748. if (!ok) {
  11749. (void)dlclose(dll_handle);
  11750. return NULL;
  11751. }
  11752. return dll_handle;
  11753. }
  11754. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  11755. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  11756. #endif /* NO_SSL_DL */
  11757. #if defined(SSL_ALREADY_INITIALIZED)
  11758. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  11759. #else
  11760. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  11761. #endif
  11762. static int
  11763. initialize_ssl(char *ebuf, size_t ebuf_len)
  11764. {
  11765. #ifdef OPENSSL_API_1_1
  11766. if (ebuf_len > 0) {
  11767. ebuf[0] = 0;
  11768. }
  11769. #if !defined(NO_SSL_DL)
  11770. if (!cryptolib_dll_handle) {
  11771. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  11772. if (!cryptolib_dll_handle) {
  11773. return 0;
  11774. }
  11775. }
  11776. #endif /* NO_SSL_DL */
  11777. if (mg_atomic_inc(&cryptolib_users) > 1) {
  11778. return 1;
  11779. }
  11780. #else /* not OPENSSL_API_1_1 */
  11781. int i;
  11782. size_t size;
  11783. if (ebuf_len > 0) {
  11784. ebuf[0] = 0;
  11785. }
  11786. #if !defined(NO_SSL_DL)
  11787. if (!cryptolib_dll_handle) {
  11788. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  11789. if (!cryptolib_dll_handle) {
  11790. return 0;
  11791. }
  11792. }
  11793. #endif /* NO_SSL_DL */
  11794. if (mg_atomic_inc(&cryptolib_users) > 1) {
  11795. return 1;
  11796. }
  11797. /* Initialize locking callbacks, needed for thread safety.
  11798. * http://www.openssl.org/support/faq.html#PROG1
  11799. */
  11800. i = CRYPTO_num_locks();
  11801. if (i < 0) {
  11802. i = 0;
  11803. }
  11804. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  11805. if (size == 0) {
  11806. ssl_mutexes = NULL;
  11807. } else if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  11808. mg_snprintf(NULL,
  11809. NULL, /* No truncation check for ebuf */
  11810. ebuf,
  11811. ebuf_len,
  11812. "%s: cannot allocate mutexes: %s",
  11813. __func__,
  11814. ssl_error());
  11815. return 0;
  11816. }
  11817. for (i = 0; i < CRYPTO_num_locks(); i++) {
  11818. pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr);
  11819. }
  11820. CRYPTO_set_locking_callback(&ssl_locking_callback);
  11821. CRYPTO_set_id_callback(&mg_current_thread_id);
  11822. #endif /* OPENSSL_API_1_1 */
  11823. return 1;
  11824. }
  11825. static int
  11826. ssl_use_pem_file(struct mg_context *ctx, const char *pem, const char *chain)
  11827. {
  11828. if (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0) {
  11829. mg_cry(fc(ctx),
  11830. "%s: cannot open certificate file %s: %s",
  11831. __func__,
  11832. pem,
  11833. ssl_error());
  11834. return 0;
  11835. }
  11836. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  11837. if (SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0) {
  11838. mg_cry(fc(ctx),
  11839. "%s: cannot open private key file %s: %s",
  11840. __func__,
  11841. pem,
  11842. ssl_error());
  11843. return 0;
  11844. }
  11845. if (SSL_CTX_check_private_key(ctx->ssl_ctx) == 0) {
  11846. mg_cry(fc(ctx),
  11847. "%s: certificate and private key do not match: %s",
  11848. __func__,
  11849. pem);
  11850. return 0;
  11851. }
  11852. /* In contrast to OpenSSL, wolfSSL does not support certificate
  11853. * chain files that contain private keys and certificates in
  11854. * SSL_CTX_use_certificate_chain_file.
  11855. * The CivetWeb-Server used pem-Files that contained both information.
  11856. * In order to make wolfSSL work, it is split in two files.
  11857. * One file that contains key and certificate used by the server and
  11858. * an optional chain file for the ssl stack.
  11859. */
  11860. if (chain) {
  11861. if (SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, chain) == 0) {
  11862. mg_cry(fc(ctx),
  11863. "%s: cannot use certificate chain file %s: %s",
  11864. __func__,
  11865. pem,
  11866. ssl_error());
  11867. return 0;
  11868. }
  11869. }
  11870. return 1;
  11871. }
  11872. #ifdef OPENSSL_API_1_1
  11873. static unsigned long
  11874. ssl_get_protocol(int version_id)
  11875. {
  11876. long unsigned ret = SSL_OP_ALL;
  11877. if (version_id > 0)
  11878. ret |= SSL_OP_NO_SSLv2;
  11879. if (version_id > 1)
  11880. ret |= SSL_OP_NO_SSLv3;
  11881. if (version_id > 2)
  11882. ret |= SSL_OP_NO_TLSv1;
  11883. if (version_id > 3)
  11884. ret |= SSL_OP_NO_TLSv1_1;
  11885. return ret;
  11886. }
  11887. #else
  11888. static long
  11889. ssl_get_protocol(int version_id)
  11890. {
  11891. long ret = SSL_OP_ALL;
  11892. if (version_id > 0)
  11893. ret |= SSL_OP_NO_SSLv2;
  11894. if (version_id > 1)
  11895. ret |= SSL_OP_NO_SSLv3;
  11896. if (version_id > 2)
  11897. ret |= SSL_OP_NO_TLSv1;
  11898. if (version_id > 3)
  11899. ret |= SSL_OP_NO_TLSv1_1;
  11900. return ret;
  11901. }
  11902. #endif /* OPENSSL_API_1_1 */
  11903. /* Dynamically load SSL library. Set up ctx->ssl_ctx pointer. */
  11904. static int
  11905. set_ssl_option(struct mg_context *ctx)
  11906. {
  11907. const char *pem;
  11908. const char *chain;
  11909. int callback_ret;
  11910. int should_verify_peer;
  11911. int peer_certificate_optional;
  11912. const char *ca_path;
  11913. const char *ca_file;
  11914. int use_default_verify_paths;
  11915. int verify_depth;
  11916. time_t now_rt = time(NULL);
  11917. struct timespec now_mt;
  11918. md5_byte_t ssl_context_id[16];
  11919. md5_state_t md5state;
  11920. int protocol_ver;
  11921. char ebuf[128];
  11922. /* If PEM file is not specified and the init_ssl callback
  11923. * is not specified, skip SSL initialization. */
  11924. if (!ctx) {
  11925. return 0;
  11926. }
  11927. if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL
  11928. && ctx->callbacks.init_ssl == NULL) {
  11929. return 1;
  11930. }
  11931. chain = ctx->config[SSL_CERTIFICATE_CHAIN];
  11932. if (chain == NULL) {
  11933. chain = pem;
  11934. }
  11935. if ((chain != NULL) && (*chain == 0)) {
  11936. chain = NULL;
  11937. }
  11938. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  11939. mg_cry(fc(ctx), "%s", ebuf);
  11940. return 0;
  11941. }
  11942. #if !defined(NO_SSL_DL)
  11943. if (!ssllib_dll_handle) {
  11944. ssllib_dll_handle = load_dll(ebuf, sizeof(ebuf), SSL_LIB, ssl_sw);
  11945. if (!ssllib_dll_handle) {
  11946. mg_cry(fc(ctx), "%s", ebuf);
  11947. return 0;
  11948. }
  11949. }
  11950. #endif /* NO_SSL_DL */
  11951. #ifdef OPENSSL_API_1_1
  11952. /* Initialize SSL library */
  11953. OPENSSL_init_ssl(0, NULL);
  11954. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  11955. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  11956. NULL);
  11957. if ((ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  11958. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  11959. return 0;
  11960. }
  11961. #else
  11962. /* Initialize SSL library */
  11963. SSL_library_init();
  11964. SSL_load_error_strings();
  11965. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  11966. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  11967. return 0;
  11968. }
  11969. #endif /* OPENSSL_API_1_1 */
  11970. SSL_CTX_clear_options(ctx->ssl_ctx,
  11971. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  11972. | SSL_OP_NO_TLSv1_1);
  11973. protocol_ver = atoi(ctx->config[SSL_PROTOCOL_VERSION]);
  11974. SSL_CTX_set_options(ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  11975. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  11976. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  11977. #if !defined(NO_SSL_DL)
  11978. SSL_CTX_set_ecdh_auto(ctx->ssl_ctx, 1);
  11979. #endif /* NO_SSL_DL */
  11980. /* If a callback has been specified, call it. */
  11981. callback_ret =
  11982. (ctx->callbacks.init_ssl == NULL)
  11983. ? 0
  11984. : (ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data));
  11985. /* If callback returns 0, civetweb sets up the SSL certificate.
  11986. * If it returns 1, civetweb assumes the calback already did this.
  11987. * If it returns -1, initializing ssl fails. */
  11988. if (callback_ret < 0) {
  11989. mg_cry(fc(ctx), "SSL callback returned error: %i", callback_ret);
  11990. return 0;
  11991. }
  11992. if (callback_ret > 0) {
  11993. if (pem != NULL) {
  11994. (void)SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
  11995. }
  11996. return 1;
  11997. }
  11998. /* Use some UID as session context ID. */
  11999. md5_init(&md5state);
  12000. md5_append(&md5state, (const md5_byte_t *)&now_rt, sizeof(now_rt));
  12001. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  12002. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  12003. md5_append(&md5state,
  12004. (const md5_byte_t *)ctx->config[LISTENING_PORTS],
  12005. strlen(ctx->config[LISTENING_PORTS]));
  12006. md5_append(&md5state, (const md5_byte_t *)ctx, sizeof(*ctx));
  12007. md5_finish(&md5state, ssl_context_id);
  12008. SSL_CTX_set_session_id_context(ctx->ssl_ctx,
  12009. (const unsigned char *)&ssl_context_id,
  12010. sizeof(ssl_context_id));
  12011. if (pem != NULL) {
  12012. if (!ssl_use_pem_file(ctx, pem, chain)) {
  12013. return 0;
  12014. }
  12015. }
  12016. /* Should we support client certificates? */
  12017. /* Default is "no". */
  12018. should_verify_peer = 0;
  12019. peer_certificate_optional = 0;
  12020. if (ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  12021. if (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  12022. /* Yes, they are mandatory */
  12023. should_verify_peer = 1;
  12024. peer_certificate_optional = 0;
  12025. } else if (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "optional")
  12026. == 0) {
  12027. /* Yes, they are optional */
  12028. should_verify_peer = 1;
  12029. peer_certificate_optional = 1;
  12030. }
  12031. }
  12032. use_default_verify_paths =
  12033. (ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  12034. && (mg_strcasecmp(ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes") == 0);
  12035. if (should_verify_peer) {
  12036. ca_path = ctx->config[SSL_CA_PATH];
  12037. ca_file = ctx->config[SSL_CA_FILE];
  12038. if (SSL_CTX_load_verify_locations(ctx->ssl_ctx, ca_file, ca_path)
  12039. != 1) {
  12040. mg_cry(fc(ctx),
  12041. "SSL_CTX_load_verify_locations error: %s "
  12042. "ssl_verify_peer requires setting "
  12043. "either ssl_ca_path or ssl_ca_file. Is any of them "
  12044. "present in "
  12045. "the .conf file?",
  12046. ssl_error());
  12047. return 0;
  12048. }
  12049. if (peer_certificate_optional) {
  12050. SSL_CTX_set_verify(ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  12051. } else {
  12052. SSL_CTX_set_verify(ctx->ssl_ctx,
  12053. SSL_VERIFY_PEER
  12054. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  12055. NULL);
  12056. }
  12057. if (use_default_verify_paths
  12058. && (SSL_CTX_set_default_verify_paths(ctx->ssl_ctx) != 1)) {
  12059. mg_cry(fc(ctx),
  12060. "SSL_CTX_set_default_verify_paths error: %s",
  12061. ssl_error());
  12062. return 0;
  12063. }
  12064. if (ctx->config[SSL_VERIFY_DEPTH]) {
  12065. verify_depth = atoi(ctx->config[SSL_VERIFY_DEPTH]);
  12066. SSL_CTX_set_verify_depth(ctx->ssl_ctx, verify_depth);
  12067. }
  12068. }
  12069. if (ctx->config[SSL_CIPHER_LIST] != NULL) {
  12070. if (SSL_CTX_set_cipher_list(ctx->ssl_ctx, ctx->config[SSL_CIPHER_LIST])
  12071. != 1) {
  12072. mg_cry(fc(ctx), "SSL_CTX_set_cipher_list error: %s", ssl_error());
  12073. }
  12074. }
  12075. return 1;
  12076. }
  12077. static void
  12078. uninitialize_ssl(void)
  12079. {
  12080. #ifdef OPENSSL_API_1_1
  12081. if (mg_atomic_dec(&cryptolib_users) == 0) {
  12082. /* Shutdown according to
  12083. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  12084. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  12085. */
  12086. CONF_modules_unload(1);
  12087. #else
  12088. int i;
  12089. if (mg_atomic_dec(&cryptolib_users) == 0) {
  12090. /* Shutdown according to
  12091. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  12092. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  12093. */
  12094. CRYPTO_set_locking_callback(NULL);
  12095. CRYPTO_set_id_callback(NULL);
  12096. ENGINE_cleanup();
  12097. CONF_modules_unload(1);
  12098. ERR_free_strings();
  12099. EVP_cleanup();
  12100. CRYPTO_cleanup_all_ex_data();
  12101. ERR_remove_state(0);
  12102. for (i = 0; i < CRYPTO_num_locks(); i++) {
  12103. pthread_mutex_destroy(&ssl_mutexes[i]);
  12104. }
  12105. mg_free(ssl_mutexes);
  12106. ssl_mutexes = NULL;
  12107. #endif /* OPENSSL_API_1_1 */
  12108. }
  12109. }
  12110. #endif /* !NO_SSL */
  12111. static int
  12112. set_gpass_option(struct mg_context *ctx)
  12113. {
  12114. if (ctx) {
  12115. struct mg_file file = STRUCT_FILE_INITIALIZER;
  12116. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  12117. if ((path != NULL) && !mg_stat(fc(ctx), path, &file.stat)) {
  12118. mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  12119. return 0;
  12120. }
  12121. return 1;
  12122. }
  12123. return 0;
  12124. }
  12125. static int
  12126. set_acl_option(struct mg_context *ctx)
  12127. {
  12128. return check_acl(ctx, (uint32_t)0x7f000001UL) != -1;
  12129. }
  12130. static void
  12131. reset_per_request_attributes(struct mg_connection *conn)
  12132. {
  12133. if (!conn) {
  12134. return;
  12135. }
  12136. conn->connection_type = 0; /* Not yet a valid request/response */
  12137. conn->path_info = NULL;
  12138. conn->num_bytes_sent = conn->consumed_content = 0;
  12139. conn->status_code = -1;
  12140. conn->is_chunked = 0;
  12141. conn->must_close = 0;
  12142. conn->request_len = 0;
  12143. conn->throttle = 0;
  12144. conn->data_len = 0;
  12145. conn->chunk_remainder = 0;
  12146. conn->response_info.content_length = conn->request_info.content_length = -1;
  12147. conn->response_info.http_version = conn->request_info.http_version = NULL;
  12148. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  12149. conn->response_info.status_text = NULL;
  12150. conn->response_info.status_code = 0;
  12151. conn->request_info.remote_user = NULL;
  12152. conn->request_info.request_method = NULL;
  12153. conn->request_info.request_uri = NULL;
  12154. conn->request_info.local_uri = NULL;
  12155. #if defined(MG_LEGACY_INTERFACE)
  12156. /* Legacy before split into local_uri and request_uri */
  12157. conn->request_info.uri = NULL;
  12158. #endif
  12159. }
  12160. #if 0
  12161. /* Note: set_sock_timeout is not required for non-blocking sockets.
  12162. * Leave this function here (commented out) for reference until
  12163. * CivetWeb 1.9 is tested, and the tests confirme this function is
  12164. * no longer required.
  12165. */
  12166. static int
  12167. set_sock_timeout(SOCKET sock, int milliseconds)
  12168. {
  12169. int r0 = 0, r1, r2;
  12170. #ifdef _WIN32
  12171. /* Windows specific */
  12172. DWORD tv = (DWORD)milliseconds;
  12173. #else
  12174. /* Linux, ... (not Windows) */
  12175. struct timeval tv;
  12176. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  12177. * max. time waiting for the acknowledged of TCP data before the connection
  12178. * will be forcefully closed and ETIMEDOUT is returned to the application.
  12179. * If this option is not set, the default timeout of 20-30 minutes is used.
  12180. */
  12181. /* #define TCP_USER_TIMEOUT (18) */
  12182. #if defined(TCP_USER_TIMEOUT)
  12183. unsigned int uto = (unsigned int)milliseconds;
  12184. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  12185. #endif
  12186. memset(&tv, 0, sizeof(tv));
  12187. tv.tv_sec = milliseconds / 1000;
  12188. tv.tv_usec = (milliseconds * 1000) % 1000000;
  12189. #endif /* _WIN32 */
  12190. r1 = setsockopt(
  12191. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  12192. r2 = setsockopt(
  12193. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  12194. return r0 || r1 || r2;
  12195. }
  12196. #endif
  12197. static int
  12198. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  12199. {
  12200. if (setsockopt(sock,
  12201. IPPROTO_TCP,
  12202. TCP_NODELAY,
  12203. (SOCK_OPT_TYPE)&nodelay_on,
  12204. sizeof(nodelay_on)) != 0) {
  12205. /* Error */
  12206. return 1;
  12207. }
  12208. /* OK */
  12209. return 0;
  12210. }
  12211. static void
  12212. close_socket_gracefully(struct mg_connection *conn)
  12213. {
  12214. #if defined(_WIN32)
  12215. char buf[MG_BUF_LEN];
  12216. int n;
  12217. #endif
  12218. struct linger linger;
  12219. int error_code = 0;
  12220. int linger_timeout = -2;
  12221. socklen_t opt_len = sizeof(error_code);
  12222. if (!conn) {
  12223. return;
  12224. }
  12225. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  12226. * "Note that enabling a nonzero timeout on a nonblocking socket
  12227. * is not recommended.", so set it to blocking now */
  12228. set_blocking_mode(conn->client.sock, 1);
  12229. /* Send FIN to the client */
  12230. shutdown(conn->client.sock, SHUTDOWN_WR);
  12231. #if defined(_WIN32)
  12232. /* Read and discard pending incoming data. If we do not do that and
  12233. * close
  12234. * the socket, the data in the send buffer may be discarded. This
  12235. * behaviour is seen on Windows, when client keeps sending data
  12236. * when server decides to close the connection; then when client
  12237. * does recv() it gets no data back. */
  12238. do {
  12239. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  12240. } while (n > 0);
  12241. #endif
  12242. if (conn->ctx->config[LINGER_TIMEOUT]) {
  12243. linger_timeout = atoi(conn->ctx->config[LINGER_TIMEOUT]);
  12244. }
  12245. /* Set linger option according to configuration */
  12246. if (linger_timeout >= 0) {
  12247. /* Set linger option to avoid socket hanging out after close. This
  12248. * prevent ephemeral port exhaust problem under high QPS. */
  12249. linger.l_onoff = 1;
  12250. #if defined(_MSC_VER)
  12251. #pragma warning(push)
  12252. #pragma warning(disable : 4244)
  12253. #endif
  12254. linger.l_linger = (linger_timeout + 999) / 1000;
  12255. #if defined(_MSC_VER)
  12256. #pragma warning(pop)
  12257. #endif
  12258. } else {
  12259. linger.l_onoff = 0;
  12260. linger.l_linger = 0;
  12261. }
  12262. if (linger_timeout < -1) {
  12263. /* Default: don't configure any linger */
  12264. } else if (getsockopt(conn->client.sock,
  12265. SOL_SOCKET,
  12266. SO_ERROR,
  12267. (char *)&error_code,
  12268. &opt_len) != 0) {
  12269. /* Cannot determine if socket is already closed. This should
  12270. * not occur and never did in a test. Log an error message
  12271. * and continue. */
  12272. mg_cry(conn,
  12273. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  12274. __func__,
  12275. strerror(ERRNO));
  12276. } else if (error_code == ECONNRESET) {
  12277. /* Socket already closed by client/peer, close socket without linger
  12278. */
  12279. } else {
  12280. /* Set linger timeout */
  12281. if (setsockopt(conn->client.sock,
  12282. SOL_SOCKET,
  12283. SO_LINGER,
  12284. (char *)&linger,
  12285. sizeof(linger)) != 0) {
  12286. mg_cry(conn,
  12287. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  12288. __func__,
  12289. linger.l_onoff,
  12290. linger.l_linger,
  12291. strerror(ERRNO));
  12292. }
  12293. }
  12294. /* Now we know that our FIN is ACK-ed, safe to close */
  12295. closesocket(conn->client.sock);
  12296. conn->client.sock = INVALID_SOCKET;
  12297. }
  12298. static void
  12299. close_connection(struct mg_connection *conn)
  12300. {
  12301. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  12302. if (conn->lua_websocket_state) {
  12303. lua_websocket_close(conn, conn->lua_websocket_state);
  12304. conn->lua_websocket_state = NULL;
  12305. }
  12306. #endif
  12307. /* call the connection_close callback if assigned */
  12308. if ((conn->ctx->callbacks.connection_close != NULL)
  12309. && (conn->ctx->context_type == 1)) {
  12310. conn->ctx->callbacks.connection_close(conn);
  12311. }
  12312. /* Reset user data, after close callback is called.
  12313. * Do not reuse it. If the user needs a destructor,
  12314. * it must be done in the connection_close callback. */
  12315. mg_set_user_connection_data(conn, NULL);
  12316. mg_lock_connection(conn);
  12317. conn->must_close = 1;
  12318. #ifndef NO_SSL
  12319. if (conn->ssl != NULL) {
  12320. /* Run SSL_shutdown twice to ensure completly close SSL connection
  12321. */
  12322. SSL_shutdown(conn->ssl);
  12323. SSL_free(conn->ssl);
  12324. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  12325. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  12326. #ifndef OPENSSL_API_1_1
  12327. ERR_remove_state(0);
  12328. #endif
  12329. conn->ssl = NULL;
  12330. }
  12331. #endif
  12332. if (conn->client.sock != INVALID_SOCKET) {
  12333. close_socket_gracefully(conn);
  12334. conn->client.sock = INVALID_SOCKET;
  12335. }
  12336. mg_unlock_connection(conn);
  12337. }
  12338. void
  12339. mg_close_connection(struct mg_connection *conn)
  12340. {
  12341. #if defined(USE_WEBSOCKET)
  12342. struct mg_context *client_ctx = NULL;
  12343. #endif /* defined(USE_WEBSOCKET) */
  12344. if ((conn == NULL) || (conn->ctx == NULL)) {
  12345. return;
  12346. }
  12347. #if defined(USE_WEBSOCKET)
  12348. if (conn->ctx->context_type == 2) {
  12349. unsigned int i;
  12350. /* ws/wss client */
  12351. client_ctx = conn->ctx;
  12352. /* client context: loops must end */
  12353. conn->ctx->stop_flag = 1;
  12354. /* We need to get the client thread out of the select/recv call
  12355. * here. */
  12356. /* Since we use a sleep quantum of some seconds to check for recv
  12357. * timeouts, we will just wait a few seconds in mg_join_thread. */
  12358. /* join worker thread */
  12359. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  12360. if (client_ctx->worker_threadids[i] != 0) {
  12361. mg_join_thread(client_ctx->worker_threadids[i]);
  12362. }
  12363. }
  12364. }
  12365. #endif /* defined(USE_WEBSOCKET) */
  12366. close_connection(conn);
  12367. #ifndef NO_SSL
  12368. if (conn->client_ssl_ctx != NULL) {
  12369. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  12370. }
  12371. #endif
  12372. #if defined(USE_WEBSOCKET)
  12373. if (client_ctx != NULL) {
  12374. /* free context */
  12375. mg_free(client_ctx->worker_threadids);
  12376. mg_free(client_ctx);
  12377. (void)pthread_mutex_destroy(&conn->mutex);
  12378. mg_free(conn);
  12379. } else if (conn->ctx->context_type == 0) { /* Client */
  12380. mg_free(conn);
  12381. }
  12382. #else
  12383. if (conn->ctx->context_type == 0) { /* Client */
  12384. mg_free(conn);
  12385. }
  12386. #endif /* defined(USE_WEBSOCKET) */
  12387. }
  12388. static struct mg_context common_client_context;
  12389. static struct mg_connection *
  12390. mg_connect_client_impl(const struct mg_client_options *client_options,
  12391. int use_ssl,
  12392. char *ebuf,
  12393. size_t ebuf_len)
  12394. {
  12395. struct mg_connection *conn = NULL;
  12396. SOCKET sock;
  12397. union usa sa;
  12398. unsigned max_req_size =
  12399. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  12400. if (!connect_socket(&common_client_context,
  12401. client_options->host,
  12402. client_options->port,
  12403. use_ssl,
  12404. ebuf,
  12405. ebuf_len,
  12406. &sock,
  12407. &sa)) {
  12408. return NULL;
  12409. }
  12410. if ((conn = (struct mg_connection *)mg_calloc_ctx(
  12411. 1, sizeof(*conn) + max_req_size, &common_client_context))
  12412. == NULL) {
  12413. mg_snprintf(NULL,
  12414. NULL, /* No truncation check for ebuf */
  12415. ebuf,
  12416. ebuf_len,
  12417. "calloc(): %s",
  12418. strerror(ERRNO));
  12419. closesocket(sock);
  12420. return NULL;
  12421. }
  12422. #ifndef NO_SSL
  12423. #ifdef OPENSSL_API_1_1
  12424. if (use_ssl
  12425. && (conn->client_ssl_ctx = SSL_CTX_new(TLS_client_method())) == NULL) {
  12426. mg_snprintf(NULL,
  12427. NULL, /* No truncation check for ebuf */
  12428. ebuf,
  12429. ebuf_len,
  12430. "SSL_CTX_new error");
  12431. closesocket(sock);
  12432. mg_free(conn);
  12433. return NULL;
  12434. }
  12435. #else
  12436. if (use_ssl
  12437. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  12438. == NULL) {
  12439. mg_snprintf(NULL,
  12440. NULL, /* No truncation check for ebuf */
  12441. ebuf,
  12442. ebuf_len,
  12443. "SSL_CTX_new error");
  12444. closesocket(sock);
  12445. mg_free(conn);
  12446. return NULL;
  12447. }
  12448. #endif /* OPENSSL_API_1_1 */
  12449. #endif /* NO_SSL */
  12450. #ifdef USE_IPV6
  12451. socklen_t len = (sa.sa.sa_family == AF_INET)
  12452. ? sizeof(conn->client.rsa.sin)
  12453. : sizeof(conn->client.rsa.sin6);
  12454. struct sockaddr *psa = (sa.sa.sa_family == AF_INET)
  12455. ? (struct sockaddr *)&(conn->client.rsa.sin)
  12456. : (struct sockaddr *)&(conn->client.rsa.sin6);
  12457. #else
  12458. socklen_t len = sizeof(conn->client.rsa.sin);
  12459. struct sockaddr *psa = (struct sockaddr *)&(conn->client.rsa.sin);
  12460. #endif
  12461. conn->buf_size = (int)max_req_size;
  12462. conn->buf = (char *)(conn + 1);
  12463. conn->ctx = &common_client_context;
  12464. conn->client.sock = sock;
  12465. conn->client.lsa = sa;
  12466. if (getsockname(sock, psa, &len) != 0) {
  12467. mg_cry(conn, "%s: getsockname() failed: %s", __func__, strerror(ERRNO));
  12468. }
  12469. conn->client.is_ssl = use_ssl ? 1 : 0;
  12470. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  12471. #ifndef NO_SSL
  12472. if (use_ssl) {
  12473. common_client_context.ssl_ctx = conn->client_ssl_ctx;
  12474. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  12475. * SSL_CTX_set_verify call is needed to switch off server
  12476. * certificate checking, which is off by default in OpenSSL and
  12477. * on in yaSSL. */
  12478. /* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  12479. * SSL_VERIFY_PEER, verify_ssl_server); */
  12480. if (client_options->client_cert) {
  12481. if (!ssl_use_pem_file(&common_client_context,
  12482. client_options->client_cert,
  12483. NULL)) {
  12484. mg_snprintf(NULL,
  12485. NULL, /* No truncation check for ebuf */
  12486. ebuf,
  12487. ebuf_len,
  12488. "Can not use SSL client certificate");
  12489. SSL_CTX_free(conn->client_ssl_ctx);
  12490. closesocket(sock);
  12491. mg_free(conn);
  12492. return NULL;
  12493. }
  12494. }
  12495. if (client_options->server_cert) {
  12496. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  12497. client_options->server_cert,
  12498. NULL);
  12499. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  12500. } else {
  12501. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  12502. }
  12503. if (!sslize(conn,
  12504. conn->client_ssl_ctx,
  12505. SSL_connect,
  12506. &(conn->ctx->stop_flag))) {
  12507. mg_snprintf(NULL,
  12508. NULL, /* No truncation check for ebuf */
  12509. ebuf,
  12510. ebuf_len,
  12511. "SSL connection error");
  12512. SSL_CTX_free(conn->client_ssl_ctx);
  12513. closesocket(sock);
  12514. mg_free(conn);
  12515. return NULL;
  12516. }
  12517. }
  12518. #endif
  12519. set_blocking_mode(sock, 0);
  12520. return conn;
  12521. }
  12522. CIVETWEB_API struct mg_connection *
  12523. mg_connect_client_secure(const struct mg_client_options *client_options,
  12524. char *error_buffer,
  12525. size_t error_buffer_size)
  12526. {
  12527. return mg_connect_client_impl(client_options,
  12528. 1,
  12529. error_buffer,
  12530. error_buffer_size);
  12531. }
  12532. struct mg_connection *
  12533. mg_connect_client(const char *host,
  12534. int port,
  12535. int use_ssl,
  12536. char *error_buffer,
  12537. size_t error_buffer_size)
  12538. {
  12539. struct mg_client_options opts;
  12540. memset(&opts, 0, sizeof(opts));
  12541. opts.host = host;
  12542. opts.port = port;
  12543. return mg_connect_client_impl(&opts,
  12544. use_ssl,
  12545. error_buffer,
  12546. error_buffer_size);
  12547. }
  12548. static const struct {
  12549. const char *proto;
  12550. size_t proto_len;
  12551. unsigned default_port;
  12552. } abs_uri_protocols[] = {{"http://", 7, 80},
  12553. {"https://", 8, 443},
  12554. {"ws://", 5, 80},
  12555. {"wss://", 6, 443},
  12556. {NULL, 0, 0}};
  12557. /* Check if the uri is valid.
  12558. * return 0 for invalid uri,
  12559. * return 1 for *,
  12560. * return 2 for relative uri,
  12561. * return 3 for absolute uri without port,
  12562. * return 4 for absolute uri with port */
  12563. static int
  12564. get_uri_type(const char *uri)
  12565. {
  12566. int i;
  12567. const char *hostend, *portbegin;
  12568. char *portend;
  12569. unsigned long port;
  12570. /* According to the HTTP standard
  12571. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  12572. * URI can be an asterisk (*) or should start with slash (relative uri),
  12573. * or it should start with the protocol (absolute uri). */
  12574. if ((uri[0] == '*') && (uri[1] == '\0')) {
  12575. /* asterisk */
  12576. return 1;
  12577. }
  12578. /* Valid URIs according to RFC 3986
  12579. * (https://www.ietf.org/rfc/rfc3986.txt)
  12580. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  12581. * and unreserved characters A-Z a-z 0-9 and -._~
  12582. * and % encoded symbols.
  12583. */
  12584. for (i = 0; uri[i] != 0; i++) {
  12585. if (uri[i] < 33) {
  12586. /* control characters and spaces are invalid */
  12587. return 0;
  12588. }
  12589. if (uri[i] > 126) {
  12590. /* non-ascii characters must be % encoded */
  12591. return 0;
  12592. } else {
  12593. switch (uri[i]) {
  12594. case '"': /* 34 */
  12595. case '<': /* 60 */
  12596. case '>': /* 62 */
  12597. case '\\': /* 92 */
  12598. case '^': /* 94 */
  12599. case '`': /* 96 */
  12600. case '{': /* 123 */
  12601. case '|': /* 124 */
  12602. case '}': /* 125 */
  12603. return 0;
  12604. default:
  12605. /* character is ok */
  12606. break;
  12607. }
  12608. }
  12609. }
  12610. /* A relative uri starts with a / character */
  12611. if (uri[0] == '/') {
  12612. /* relative uri */
  12613. return 2;
  12614. }
  12615. /* It could be an absolute uri: */
  12616. /* This function only checks if the uri is valid, not if it is
  12617. * addressing the current server. So civetweb can also be used
  12618. * as a proxy server. */
  12619. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  12620. if (mg_strncasecmp(uri,
  12621. abs_uri_protocols[i].proto,
  12622. abs_uri_protocols[i].proto_len) == 0) {
  12623. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  12624. if (!hostend) {
  12625. return 0;
  12626. }
  12627. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  12628. if (!portbegin) {
  12629. return 3;
  12630. }
  12631. port = strtoul(portbegin + 1, &portend, 10);
  12632. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  12633. return 0;
  12634. }
  12635. return 4;
  12636. }
  12637. }
  12638. return 0;
  12639. }
  12640. /* Return NULL or the relative uri at the current server */
  12641. static const char *
  12642. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  12643. {
  12644. const char *server_domain;
  12645. size_t server_domain_len;
  12646. size_t request_domain_len = 0;
  12647. unsigned long port = 0;
  12648. int i, auth_domain_check_enabled;
  12649. const char *hostbegin = NULL;
  12650. const char *hostend = NULL;
  12651. const char *portbegin;
  12652. char *portend;
  12653. auth_domain_check_enabled =
  12654. !strcmp(conn->ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  12655. if (!auth_domain_check_enabled) {
  12656. return 0;
  12657. }
  12658. server_domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  12659. if (!server_domain) {
  12660. return 0;
  12661. }
  12662. server_domain_len = strlen(server_domain);
  12663. if (!server_domain_len) {
  12664. return 0;
  12665. }
  12666. /* DNS is case insensitive, so use case insensitive string compare here
  12667. */
  12668. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  12669. if (mg_strncasecmp(uri,
  12670. abs_uri_protocols[i].proto,
  12671. abs_uri_protocols[i].proto_len) == 0) {
  12672. hostbegin = uri + abs_uri_protocols[i].proto_len;
  12673. hostend = strchr(hostbegin, '/');
  12674. if (!hostend) {
  12675. return 0;
  12676. }
  12677. portbegin = strchr(hostbegin, ':');
  12678. if ((!portbegin) || (portbegin > hostend)) {
  12679. port = abs_uri_protocols[i].default_port;
  12680. request_domain_len = (size_t)(hostend - hostbegin);
  12681. } else {
  12682. port = strtoul(portbegin + 1, &portend, 10);
  12683. if ((portend != hostend) || (port <= 0)
  12684. || !is_valid_port(port)) {
  12685. return 0;
  12686. }
  12687. request_domain_len = (size_t)(portbegin - hostbegin);
  12688. }
  12689. /* protocol found, port set */
  12690. break;
  12691. }
  12692. }
  12693. if (!port) {
  12694. /* port remains 0 if the protocol is not found */
  12695. return 0;
  12696. }
  12697. /* Check if the request is directed to a different server. */
  12698. /* First check if the port is the same (IPv4 and IPv6). */
  12699. #if defined(USE_IPV6)
  12700. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  12701. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  12702. /* Request is directed to a different port */
  12703. return 0;
  12704. }
  12705. } else
  12706. #endif
  12707. {
  12708. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  12709. /* Request is directed to a different port */
  12710. return 0;
  12711. }
  12712. }
  12713. /* Finally check if the server corresponds to the authentication
  12714. * domain of the server (the server domain).
  12715. * Allow full matches (like http://mydomain.com/path/file.ext), and
  12716. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  12717. * but do not allow substrings (like
  12718. * http://notmydomain.com/path/file.ext
  12719. * or http://mydomain.com.fake/path/file.ext).
  12720. */
  12721. if (auth_domain_check_enabled) {
  12722. if ((request_domain_len == server_domain_len)
  12723. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  12724. /* Request is directed to this server - full name match. */
  12725. } else {
  12726. if (request_domain_len < (server_domain_len + 2)) {
  12727. /* Request is directed to another server: The server name is
  12728. * longer
  12729. * than
  12730. * the request name. Drop this case here to avoid overflows
  12731. * in
  12732. * the
  12733. * following checks. */
  12734. return 0;
  12735. }
  12736. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  12737. /* Request is directed to another server: It could be a
  12738. * substring
  12739. * like notmyserver.com */
  12740. return 0;
  12741. }
  12742. if (0 != memcmp(server_domain,
  12743. hostbegin + request_domain_len - server_domain_len,
  12744. server_domain_len)) {
  12745. /* Request is directed to another server:
  12746. * The server name is different. */
  12747. return 0;
  12748. }
  12749. }
  12750. }
  12751. return hostend;
  12752. }
  12753. static int
  12754. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  12755. {
  12756. if (ebuf_len > 0) {
  12757. ebuf[0] = '\0';
  12758. }
  12759. *err = 0;
  12760. reset_per_request_attributes(conn);
  12761. if (!conn) {
  12762. mg_snprintf(conn,
  12763. NULL, /* No truncation check for ebuf */
  12764. ebuf,
  12765. ebuf_len,
  12766. "%s",
  12767. "Internal error");
  12768. *err = 500;
  12769. return 0;
  12770. }
  12771. /* Set the time the request was received. This value should be used for
  12772. * timeouts. */
  12773. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  12774. conn->request_len =
  12775. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  12776. /* assert(conn->request_len < 0 || conn->data_len >= conn->request_len);
  12777. */
  12778. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  12779. mg_snprintf(conn,
  12780. NULL, /* No truncation check for ebuf */
  12781. ebuf,
  12782. ebuf_len,
  12783. "%s",
  12784. "Invalid message size");
  12785. *err = 500;
  12786. return 0;
  12787. }
  12788. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  12789. mg_snprintf(conn,
  12790. NULL, /* No truncation check for ebuf */
  12791. ebuf,
  12792. ebuf_len,
  12793. "%s",
  12794. "Message too large");
  12795. *err = 413;
  12796. return 0;
  12797. }
  12798. if (conn->request_len <= 0) {
  12799. if (conn->data_len > 0) {
  12800. mg_snprintf(conn,
  12801. NULL, /* No truncation check for ebuf */
  12802. ebuf,
  12803. ebuf_len,
  12804. "%s",
  12805. "Malformed message");
  12806. *err = 400;
  12807. } else {
  12808. /* Server did not recv anything -> just close the connection */
  12809. conn->must_close = 1;
  12810. mg_snprintf(conn,
  12811. NULL, /* No truncation check for ebuf */
  12812. ebuf,
  12813. ebuf_len,
  12814. "%s",
  12815. "No data received");
  12816. *err = 0;
  12817. }
  12818. return 0;
  12819. }
  12820. return 1;
  12821. }
  12822. static int
  12823. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  12824. {
  12825. const char *cl;
  12826. if (!get_message(conn, ebuf, ebuf_len, err)) {
  12827. return 0;
  12828. }
  12829. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  12830. <= 0) {
  12831. mg_snprintf(conn,
  12832. NULL, /* No truncation check for ebuf */
  12833. ebuf,
  12834. ebuf_len,
  12835. "%s",
  12836. "Bad request");
  12837. *err = 400;
  12838. return 0;
  12839. }
  12840. /* Message is a valid request */
  12841. if ((cl = get_header(conn->request_info.http_headers,
  12842. conn->request_info.num_headers,
  12843. "Content-Length")) != NULL) {
  12844. /* Request/response has content length set */
  12845. char *endptr = NULL;
  12846. conn->content_len = strtoll(cl, &endptr, 10);
  12847. if (endptr == cl) {
  12848. mg_snprintf(conn,
  12849. NULL, /* No truncation check for ebuf */
  12850. ebuf,
  12851. ebuf_len,
  12852. "%s",
  12853. "Bad request");
  12854. *err = 411;
  12855. return 0;
  12856. }
  12857. /* Publish the content length back to the request info. */
  12858. conn->request_info.content_length = conn->content_len;
  12859. } else if ((cl = get_header(conn->request_info.http_headers,
  12860. conn->request_info.num_headers,
  12861. "Transfer-Encoding")) != NULL
  12862. && !mg_strcasecmp(cl, "chunked")) {
  12863. conn->is_chunked = 1;
  12864. } else if (!mg_strcasecmp(conn->request_info.request_method, "POST")
  12865. || !mg_strcasecmp(conn->request_info.request_method, "PUT")) {
  12866. /* POST or PUT request without content length set */
  12867. conn->content_len = -1;
  12868. } else if (!mg_strncasecmp(conn->request_info.request_method, "HTTP/", 5)) {
  12869. /* Response without content length set */
  12870. conn->content_len = -1;
  12871. } else {
  12872. /* Other request */
  12873. conn->content_len = 0;
  12874. }
  12875. conn->connection_type = 1; /* Valid request */
  12876. return 1;
  12877. }
  12878. /* conn is assumed to be valid in this internal function */
  12879. static int
  12880. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  12881. {
  12882. const char *cl;
  12883. if (!get_message(conn, ebuf, ebuf_len, err)) {
  12884. return 0;
  12885. }
  12886. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  12887. <= 0) {
  12888. mg_snprintf(conn,
  12889. NULL, /* No truncation check for ebuf */
  12890. ebuf,
  12891. ebuf_len,
  12892. "%s",
  12893. "Bad response");
  12894. *err = 400;
  12895. return 0;
  12896. }
  12897. /* Message is a valid response */
  12898. if ((cl = get_header(conn->response_info.http_headers,
  12899. conn->response_info.num_headers,
  12900. "Content-Length")) != NULL) {
  12901. /* Request/response has content length set */
  12902. char *endptr = NULL;
  12903. conn->content_len = strtoll(cl, &endptr, 10);
  12904. if (endptr == cl) {
  12905. mg_snprintf(conn,
  12906. NULL, /* No truncation check for ebuf */
  12907. ebuf,
  12908. ebuf_len,
  12909. "%s",
  12910. "Bad request");
  12911. *err = 411;
  12912. return 0;
  12913. }
  12914. /* Publish the content length back to the response info. */
  12915. conn->response_info.content_length = conn->content_len;
  12916. /* TODO: check if it is still used in response_info */
  12917. conn->request_info.content_length = conn->content_len;
  12918. } else if ((cl = get_header(conn->response_info.http_headers,
  12919. conn->response_info.num_headers,
  12920. "Transfer-Encoding")) != NULL
  12921. && !mg_strcasecmp(cl, "chunked")) {
  12922. conn->is_chunked = 1;
  12923. } else {
  12924. conn->content_len = -1;
  12925. }
  12926. conn->connection_type = 2; /* Valid response */
  12927. return 1;
  12928. }
  12929. int
  12930. mg_get_response(struct mg_connection *conn,
  12931. char *ebuf,
  12932. size_t ebuf_len,
  12933. int timeout)
  12934. {
  12935. if (ebuf_len > 0) {
  12936. ebuf[0] = '\0';
  12937. }
  12938. if (!conn) {
  12939. mg_snprintf(conn,
  12940. NULL, /* No truncation check for ebuf */
  12941. ebuf,
  12942. ebuf_len,
  12943. "%s",
  12944. "Parameter error");
  12945. return -1;
  12946. }
  12947. /* Implementation of API function for HTTP clients */
  12948. int err, ret;
  12949. struct mg_context *octx = conn->ctx;
  12950. struct mg_context rctx = *(conn->ctx);
  12951. char txt[32]; /* will not overflow */
  12952. if (timeout >= 0) {
  12953. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  12954. rctx.config[REQUEST_TIMEOUT] = txt;
  12955. /* Not required for non-blocking sockets.
  12956. set_sock_timeout(conn->client.sock, timeout);
  12957. */
  12958. } else {
  12959. rctx.config[REQUEST_TIMEOUT] = NULL;
  12960. }
  12961. conn->ctx = &rctx;
  12962. ret = get_response(conn, ebuf, ebuf_len, &err);
  12963. conn->ctx = octx;
  12964. #if defined(MG_LEGACY_INTERFACE)
  12965. /* TODO: 1) uri is deprecated;
  12966. * 2) here, ri.uri is the http response code */
  12967. conn->request_info.uri = conn->request_info.request_uri;
  12968. #endif
  12969. conn->request_info.local_uri = conn->request_info.request_uri;
  12970. /* TODO (mid): Define proper return values - maybe return length?
  12971. * For the first test use <0 for error and >0 for OK */
  12972. return (ret == 0) ? -1 : +1;
  12973. }
  12974. struct mg_connection *
  12975. mg_download(const char *host,
  12976. int port,
  12977. int use_ssl,
  12978. char *ebuf,
  12979. size_t ebuf_len,
  12980. const char *fmt,
  12981. ...)
  12982. {
  12983. struct mg_connection *conn;
  12984. va_list ap;
  12985. int i;
  12986. int reqerr;
  12987. if (ebuf_len > 0) {
  12988. ebuf[0] = '\0';
  12989. }
  12990. va_start(ap, fmt);
  12991. /* open a connection */
  12992. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  12993. if (conn != NULL) {
  12994. i = mg_vprintf(conn, fmt, ap);
  12995. if (i <= 0) {
  12996. mg_snprintf(conn,
  12997. NULL, /* No truncation check for ebuf */
  12998. ebuf,
  12999. ebuf_len,
  13000. "%s",
  13001. "Error sending request");
  13002. } else {
  13003. get_response(conn, ebuf, ebuf_len, &reqerr);
  13004. #if defined(MG_LEGACY_INTERFACE)
  13005. /* TODO: 1) uri is deprecated;
  13006. * 2) here, ri.uri is the http response code */
  13007. conn->request_info.uri = conn->request_info.request_uri;
  13008. #endif
  13009. conn->request_info.local_uri = conn->request_info.request_uri;
  13010. }
  13011. }
  13012. /* if an error occured, close the connection */
  13013. if ((ebuf[0] != '\0') && (conn != NULL)) {
  13014. mg_close_connection(conn);
  13015. conn = NULL;
  13016. }
  13017. va_end(ap);
  13018. return conn;
  13019. }
  13020. struct websocket_client_thread_data {
  13021. struct mg_connection *conn;
  13022. mg_websocket_data_handler data_handler;
  13023. mg_websocket_close_handler close_handler;
  13024. void *callback_data;
  13025. };
  13026. #if defined(USE_WEBSOCKET)
  13027. #ifdef _WIN32
  13028. static unsigned __stdcall websocket_client_thread(void *data)
  13029. #else
  13030. static void *
  13031. websocket_client_thread(void *data)
  13032. #endif
  13033. {
  13034. struct websocket_client_thread_data *cdata =
  13035. (struct websocket_client_thread_data *)data;
  13036. mg_set_thread_name("ws-clnt");
  13037. if (cdata->conn->ctx) {
  13038. if (cdata->conn->ctx->callbacks.init_thread) {
  13039. /* 3 indicates a websocket client thread */
  13040. /* TODO: check if conn->ctx can be set */
  13041. cdata->conn->ctx->callbacks.init_thread(cdata->conn->ctx, 3);
  13042. }
  13043. }
  13044. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  13045. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  13046. if (cdata->close_handler != NULL) {
  13047. cdata->close_handler(cdata->conn, cdata->callback_data);
  13048. }
  13049. /* The websocket_client context has only this thread. If it runs out,
  13050. set the stop_flag to 2 (= "stopped"). */
  13051. cdata->conn->ctx->stop_flag = 2;
  13052. mg_free((void *)cdata);
  13053. #ifdef _WIN32
  13054. return 0;
  13055. #else
  13056. return NULL;
  13057. #endif
  13058. }
  13059. #endif
  13060. struct mg_connection *
  13061. mg_connect_websocket_client(const char *host,
  13062. int port,
  13063. int use_ssl,
  13064. char *error_buffer,
  13065. size_t error_buffer_size,
  13066. const char *path,
  13067. const char *origin,
  13068. mg_websocket_data_handler data_func,
  13069. mg_websocket_close_handler close_func,
  13070. void *user_data)
  13071. {
  13072. struct mg_connection *conn = NULL;
  13073. #if defined(USE_WEBSOCKET)
  13074. struct mg_context *newctx = NULL;
  13075. struct websocket_client_thread_data *thread_data;
  13076. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  13077. static const char *handshake_req;
  13078. if (origin != NULL) {
  13079. handshake_req = "GET %s HTTP/1.1\r\n"
  13080. "Host: %s\r\n"
  13081. "Upgrade: websocket\r\n"
  13082. "Connection: Upgrade\r\n"
  13083. "Sec-WebSocket-Key: %s\r\n"
  13084. "Sec-WebSocket-Version: 13\r\n"
  13085. "Origin: %s\r\n"
  13086. "\r\n";
  13087. } else {
  13088. handshake_req = "GET %s HTTP/1.1\r\n"
  13089. "Host: %s\r\n"
  13090. "Upgrade: websocket\r\n"
  13091. "Connection: Upgrade\r\n"
  13092. "Sec-WebSocket-Key: %s\r\n"
  13093. "Sec-WebSocket-Version: 13\r\n"
  13094. "\r\n";
  13095. }
  13096. /* Establish the client connection and request upgrade */
  13097. conn = mg_download(host,
  13098. port,
  13099. use_ssl,
  13100. error_buffer,
  13101. error_buffer_size,
  13102. handshake_req,
  13103. path,
  13104. host,
  13105. magic,
  13106. origin);
  13107. /* Connection object will be null if something goes wrong */
  13108. if (conn == NULL) {
  13109. if (!*error_buffer) {
  13110. /* There should be already an error message */
  13111. mg_snprintf(conn,
  13112. NULL, /* No truncation check for ebuf */
  13113. error_buffer,
  13114. error_buffer_size,
  13115. "Unexpected error");
  13116. }
  13117. return NULL;
  13118. }
  13119. if (conn->response_info.status_code != 101) {
  13120. /* We sent an "upgrade" request. For a correct websocket
  13121. * protocol handshake, we expect a "101 Continue" response.
  13122. * Otherwise it is a protocol violation. Maybe the HTTP
  13123. * Server does not know websockets. */
  13124. if (!*error_buffer) {
  13125. /* set an error, if not yet set */
  13126. mg_snprintf(conn,
  13127. NULL, /* No truncation check for ebuf */
  13128. error_buffer,
  13129. error_buffer_size,
  13130. "Unexpected server reply");
  13131. }
  13132. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  13133. mg_free(conn);
  13134. return conn;
  13135. }
  13136. /* For client connections, mg_context is fake. Since we need to set a
  13137. * callback function, we need to create a copy and modify it. */
  13138. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  13139. memcpy(newctx, conn->ctx, sizeof(struct mg_context));
  13140. newctx->user_data = user_data;
  13141. newctx->context_type = 2; /* ws/wss client context type */
  13142. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  13143. newctx->worker_threadids =
  13144. (pthread_t *)mg_calloc_ctx(newctx->cfg_worker_threads,
  13145. sizeof(pthread_t),
  13146. newctx);
  13147. conn->ctx = newctx;
  13148. thread_data = (struct websocket_client_thread_data *)
  13149. mg_calloc_ctx(sizeof(struct websocket_client_thread_data), 1, newctx);
  13150. thread_data->conn = conn;
  13151. thread_data->data_handler = data_func;
  13152. thread_data->close_handler = close_func;
  13153. thread_data->callback_data = user_data;
  13154. /* Start a thread to read the websocket client connection
  13155. * This thread will automatically stop when mg_disconnect is
  13156. * called on the client connection */
  13157. if (mg_start_thread_with_id(websocket_client_thread,
  13158. (void *)thread_data,
  13159. newctx->worker_threadids) != 0) {
  13160. mg_free((void *)thread_data);
  13161. mg_free((void *)newctx->worker_threadids);
  13162. mg_free((void *)newctx);
  13163. mg_free((void *)conn);
  13164. conn = NULL;
  13165. DEBUG_TRACE("%s",
  13166. "Websocket client connect thread could not be started\r\n");
  13167. }
  13168. #else
  13169. /* Appease "unused parameter" warnings */
  13170. (void)host;
  13171. (void)port;
  13172. (void)use_ssl;
  13173. (void)error_buffer;
  13174. (void)error_buffer_size;
  13175. (void)path;
  13176. (void)origin;
  13177. (void)user_data;
  13178. (void)data_func;
  13179. (void)close_func;
  13180. #endif
  13181. return conn;
  13182. }
  13183. /* Process a connection - may handle multiple requests
  13184. * using the same connection.
  13185. * Must be called with a valid connection (conn and
  13186. * conn->ctx must be valid).
  13187. */
  13188. static void
  13189. process_new_connection(struct mg_connection *conn)
  13190. {
  13191. struct mg_request_info *ri = &conn->request_info;
  13192. int keep_alive_enabled, keep_alive, discard_len;
  13193. char ebuf[100];
  13194. const char *hostend;
  13195. int reqerr, uri_type;
  13196. #if defined(USE_SERVER_STATS)
  13197. int mcon = mg_atomic_inc(&(conn->ctx->active_connections));
  13198. mg_atomic_add(&(conn->ctx->total_connections), 1);
  13199. if (mcon > (conn->ctx->max_connections)) {
  13200. /* could use atomic compare exchange, but this
  13201. * seems overkill for statistics data */
  13202. conn->ctx->max_connections = mcon;
  13203. }
  13204. #endif
  13205. /* Is keep alive allowed by the server */
  13206. keep_alive_enabled = !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  13207. if (!keep_alive_enabled) {
  13208. conn->must_close = 1;
  13209. }
  13210. /* Important: on new connection, reset the receiving buffer. Credit
  13211. * goes to crule42. */
  13212. conn->data_len = 0;
  13213. conn->handled_requests = 0;
  13214. mg_set_user_connection_data(conn, NULL);
  13215. DEBUG_TRACE("Start processing connection from %s",
  13216. conn->request_info.remote_addr);
  13217. /* Loop over multiple requests sent using the same connection
  13218. * (while "keep alive"). */
  13219. do {
  13220. DEBUG_TRACE("calling get_request (%i times for this connection)",
  13221. conn->handled_requests + 1);
  13222. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  13223. /* The request sent by the client could not be understood by
  13224. * the server, or it was incomplete or a timeout. Send an
  13225. * error message and close the connection. */
  13226. if (reqerr > 0) {
  13227. /*assert(ebuf[0] != '\0');*/
  13228. mg_send_http_error(conn, reqerr, "%s", ebuf);
  13229. }
  13230. } else if (strcmp(ri->http_version, "1.0")
  13231. && strcmp(ri->http_version, "1.1")) {
  13232. mg_snprintf(conn,
  13233. NULL, /* No truncation check for ebuf */
  13234. ebuf,
  13235. sizeof(ebuf),
  13236. "Bad HTTP version: [%s]",
  13237. ri->http_version);
  13238. mg_send_http_error(conn, 505, "%s", ebuf);
  13239. }
  13240. if (ebuf[0] == '\0') {
  13241. uri_type = get_uri_type(conn->request_info.request_uri);
  13242. switch (uri_type) {
  13243. case 1:
  13244. /* Asterisk */
  13245. conn->request_info.local_uri = NULL;
  13246. break;
  13247. case 2:
  13248. /* relative uri */
  13249. conn->request_info.local_uri = conn->request_info.request_uri;
  13250. break;
  13251. case 3:
  13252. case 4:
  13253. /* absolute uri (with/without port) */
  13254. hostend = get_rel_url_at_current_server(
  13255. conn->request_info.request_uri, conn);
  13256. if (hostend) {
  13257. conn->request_info.local_uri = hostend;
  13258. } else {
  13259. conn->request_info.local_uri = NULL;
  13260. }
  13261. break;
  13262. default:
  13263. mg_snprintf(conn,
  13264. NULL, /* No truncation check for ebuf */
  13265. ebuf,
  13266. sizeof(ebuf),
  13267. "Invalid URI");
  13268. mg_send_http_error(conn, 400, "%s", ebuf);
  13269. conn->request_info.local_uri = NULL;
  13270. break;
  13271. }
  13272. #if defined(MG_LEGACY_INTERFACE)
  13273. /* Legacy before split into local_uri and request_uri */
  13274. conn->request_info.uri = conn->request_info.local_uri;
  13275. #endif
  13276. }
  13277. DEBUG_TRACE("http: %s, error: %s",
  13278. (ri->http_version ? ri->http_version : "none"),
  13279. (ebuf[0] ? ebuf : "none"));
  13280. if (ebuf[0] == '\0') {
  13281. if (conn->request_info.local_uri) {
  13282. /* handle request to local server */
  13283. handle_request(conn);
  13284. DEBUG_TRACE("%s", "handle_request done");
  13285. if (conn->ctx->callbacks.end_request != NULL) {
  13286. conn->ctx->callbacks.end_request(conn, conn->status_code);
  13287. DEBUG_TRACE("%s", "end_request callback done");
  13288. }
  13289. log_access(conn);
  13290. } else {
  13291. /* TODO: handle non-local request (PROXY) */
  13292. conn->must_close = 1;
  13293. }
  13294. } else {
  13295. conn->must_close = 1;
  13296. }
  13297. if (ri->remote_user != NULL) {
  13298. mg_free((void *)ri->remote_user);
  13299. /* Important! When having connections with and without auth
  13300. * would cause double free and then crash */
  13301. ri->remote_user = NULL;
  13302. }
  13303. /* NOTE(lsm): order is important here. should_keep_alive() call
  13304. * is
  13305. * using parsed request, which will be invalid after memmove's
  13306. * below.
  13307. * Therefore, memorize should_keep_alive() result now for later
  13308. * use
  13309. * in loop exit condition. */
  13310. keep_alive = (conn->ctx->stop_flag == 0) && keep_alive_enabled
  13311. && (conn->content_len >= 0) && should_keep_alive(conn);
  13312. /* Discard all buffered data for this request */
  13313. discard_len = ((conn->content_len >= 0) && (conn->request_len > 0)
  13314. && ((conn->request_len + conn->content_len)
  13315. < (int64_t)conn->data_len))
  13316. ? (int)(conn->request_len + conn->content_len)
  13317. : conn->data_len;
  13318. /*assert(discard_len >= 0);*/
  13319. if (discard_len < 0) {
  13320. DEBUG_TRACE("internal error: discard_len = %li",
  13321. (long int)discard_len);
  13322. break;
  13323. }
  13324. conn->data_len -= discard_len;
  13325. if (conn->data_len > 0) {
  13326. DEBUG_TRACE("discard_len = %lu", (long unsigned)discard_len);
  13327. memmove(conn->buf, conn->buf + discard_len, (size_t)conn->data_len);
  13328. }
  13329. /* assert(conn->data_len >= 0); */
  13330. /* assert(conn->data_len <= conn->buf_size); */
  13331. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  13332. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  13333. (long int)conn->data_len,
  13334. (long int)conn->buf_size);
  13335. break;
  13336. }
  13337. conn->handled_requests++;
  13338. } while (keep_alive);
  13339. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  13340. conn->request_info.remote_addr,
  13341. difftime(time(NULL), conn->conn_birth_time));
  13342. close_connection(conn);
  13343. #if defined(USE_SERVER_STATS)
  13344. mg_atomic_add(&(conn->ctx->total_requests), conn->handled_requests);
  13345. mg_atomic_dec(&(conn->ctx->active_connections));
  13346. #endif
  13347. }
  13348. #if defined(ALTERNATIVE_QUEUE)
  13349. static void
  13350. produce_socket(struct mg_context *ctx, const struct socket *sp)
  13351. {
  13352. unsigned int i;
  13353. for (;;) {
  13354. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  13355. /* find a free worker slot and signal it */
  13356. if (ctx->client_socks[i].in_use == 0) {
  13357. ctx->client_socks[i] = *sp;
  13358. ctx->client_socks[i].in_use = 1;
  13359. event_signal(ctx->client_wait_events[i]);
  13360. return;
  13361. }
  13362. }
  13363. /* queue is full */
  13364. mg_sleep(1);
  13365. }
  13366. }
  13367. static int
  13368. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  13369. {
  13370. DEBUG_TRACE("%s", "going idle");
  13371. ctx->client_socks[thread_index].in_use = 0;
  13372. event_wait(ctx->client_wait_events[thread_index]);
  13373. *sp = ctx->client_socks[thread_index];
  13374. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  13375. return !ctx->stop_flag;
  13376. }
  13377. #else /* ALTERNATIVE_QUEUE */
  13378. /* Worker threads take accepted socket from the queue */
  13379. static int
  13380. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  13381. {
  13382. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  13383. (void)thread_index;
  13384. (void)pthread_mutex_lock(&ctx->thread_mutex);
  13385. DEBUG_TRACE("%s", "going idle");
  13386. /* If the queue is empty, wait. We're idle at this point. */
  13387. while ((ctx->sq_head == ctx->sq_tail) && (ctx->stop_flag == 0)) {
  13388. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  13389. }
  13390. /* If we're stopping, sq_head may be equal to sq_tail. */
  13391. if (ctx->sq_head > ctx->sq_tail) {
  13392. /* Copy socket from the queue and increment tail */
  13393. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  13394. ctx->sq_tail++;
  13395. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  13396. /* Wrap pointers if needed */
  13397. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  13398. ctx->sq_tail -= QUEUE_SIZE(ctx);
  13399. ctx->sq_head -= QUEUE_SIZE(ctx);
  13400. }
  13401. }
  13402. (void)pthread_cond_signal(&ctx->sq_empty);
  13403. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  13404. return !ctx->stop_flag;
  13405. #undef QUEUE_SIZE
  13406. }
  13407. /* Master thread adds accepted socket to a queue */
  13408. static void
  13409. produce_socket(struct mg_context *ctx, const struct socket *sp)
  13410. {
  13411. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  13412. if (!ctx) {
  13413. return;
  13414. }
  13415. (void)pthread_mutex_lock(&ctx->thread_mutex);
  13416. /* If the queue is full, wait */
  13417. while ((ctx->stop_flag == 0)
  13418. && (ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx))) {
  13419. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  13420. }
  13421. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  13422. /* Copy socket to the queue and increment head */
  13423. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  13424. ctx->sq_head++;
  13425. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  13426. }
  13427. (void)pthread_cond_signal(&ctx->sq_full);
  13428. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  13429. #undef QUEUE_SIZE
  13430. }
  13431. #endif /* ALTERNATIVE_QUEUE */
  13432. struct worker_thread_args {
  13433. struct mg_context *ctx;
  13434. int index;
  13435. };
  13436. static void *
  13437. worker_thread_run(struct worker_thread_args *thread_args)
  13438. {
  13439. struct mg_context *ctx = thread_args->ctx;
  13440. struct mg_connection *conn;
  13441. struct mg_workerTLS tls;
  13442. #if defined(MG_LEGACY_INTERFACE)
  13443. uint32_t addr;
  13444. #endif
  13445. mg_set_thread_name("worker");
  13446. tls.is_master = 0;
  13447. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  13448. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13449. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  13450. #endif
  13451. /* Initialize thread local storage before calling any callback */
  13452. pthread_setspecific(sTlsKey, &tls);
  13453. if (ctx->callbacks.init_thread) {
  13454. /* call init_thread for a worker thread (type 1) */
  13455. ctx->callbacks.init_thread(ctx, 1);
  13456. }
  13457. /* Connection structure has been pre-allocated */
  13458. if (((int)thread_args->index < 0)
  13459. || ((unsigned)thread_args->index
  13460. >= (unsigned)ctx->cfg_worker_threads)) {
  13461. mg_cry(fc(ctx),
  13462. "Internal error: Invalid worker index %i",
  13463. (int)thread_args->index);
  13464. return NULL;
  13465. }
  13466. conn = ctx->worker_connections + thread_args->index;
  13467. /* Request buffers are not pre-allocated. They are private to the
  13468. * request and do not contain any state information that might be
  13469. * of interest to anyone observing a server status. */
  13470. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->ctx);
  13471. if (conn->buf == NULL) {
  13472. mg_cry(fc(ctx),
  13473. "Out of memory: Cannot allocate buffer for worker %i",
  13474. (int)thread_args->index);
  13475. return NULL;
  13476. }
  13477. conn->buf_size = (int)ctx->max_request_size;
  13478. conn->ctx = ctx;
  13479. conn->thread_index = thread_args->index;
  13480. conn->request_info.user_data = ctx->user_data;
  13481. /* Allocate a mutex for this connection to allow communication both
  13482. * within the request handler and from elsewhere in the application
  13483. */
  13484. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  13485. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  13486. * signal sq_empty condvar to wake up the master waiting in
  13487. * produce_socket() */
  13488. while (consume_socket(ctx, &conn->client, conn->thread_index)) {
  13489. conn->conn_birth_time = time(NULL);
  13490. /* Fill in IP, port info early so even if SSL setup below fails,
  13491. * error handler would have the corresponding info.
  13492. * Thanks to Johannes Winkelmann for the patch.
  13493. */
  13494. #if defined(USE_IPV6)
  13495. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  13496. conn->request_info.remote_port =
  13497. ntohs(conn->client.rsa.sin6.sin6_port);
  13498. } else
  13499. #endif
  13500. {
  13501. conn->request_info.remote_port =
  13502. ntohs(conn->client.rsa.sin.sin_port);
  13503. }
  13504. sockaddr_to_string(conn->request_info.remote_addr,
  13505. sizeof(conn->request_info.remote_addr),
  13506. &conn->client.rsa);
  13507. DEBUG_TRACE("Start processing connection from %s",
  13508. conn->request_info.remote_addr);
  13509. #if defined(MG_LEGACY_INTERFACE)
  13510. /* This legacy interface only works for the IPv4 case */
  13511. addr = ntohl(conn->client.rsa.sin.sin_addr.s_addr);
  13512. memcpy(&conn->request_info.remote_ip, &addr, 4);
  13513. #endif
  13514. conn->request_info.is_ssl = conn->client.is_ssl;
  13515. if (conn->client.is_ssl) {
  13516. #ifndef NO_SSL
  13517. /* HTTPS connection */
  13518. if (sslize(conn,
  13519. conn->ctx->ssl_ctx,
  13520. SSL_accept,
  13521. &(conn->ctx->stop_flag))) {
  13522. /* Get SSL client certificate information (if set) */
  13523. ssl_get_client_cert_info(conn);
  13524. /* process HTTPS connection */
  13525. process_new_connection(conn);
  13526. /* Free client certificate info */
  13527. if (conn->request_info.client_cert) {
  13528. mg_free((void *)(conn->request_info.client_cert->subject));
  13529. mg_free((void *)(conn->request_info.client_cert->issuer));
  13530. mg_free((void *)(conn->request_info.client_cert->serial));
  13531. mg_free((void *)(conn->request_info.client_cert->finger));
  13532. conn->request_info.client_cert->subject = 0;
  13533. conn->request_info.client_cert->issuer = 0;
  13534. conn->request_info.client_cert->serial = 0;
  13535. conn->request_info.client_cert->finger = 0;
  13536. mg_free(conn->request_info.client_cert);
  13537. conn->request_info.client_cert = 0;
  13538. }
  13539. }
  13540. #endif
  13541. } else {
  13542. /* process HTTP connection */
  13543. process_new_connection(conn);
  13544. }
  13545. DEBUG_TRACE("%s", "Connection closed");
  13546. }
  13547. pthread_setspecific(sTlsKey, NULL);
  13548. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13549. CloseHandle(tls.pthread_cond_helper_mutex);
  13550. #endif
  13551. pthread_mutex_destroy(&conn->mutex);
  13552. /* Free the request buffer. */
  13553. conn->buf_size = 0;
  13554. mg_free(conn->buf);
  13555. conn->buf = NULL;
  13556. DEBUG_TRACE("%s", "exiting");
  13557. return NULL;
  13558. }
  13559. /* Threads have different return types on Windows and Unix. */
  13560. #ifdef _WIN32
  13561. static unsigned __stdcall worker_thread(void *thread_func_param)
  13562. {
  13563. struct worker_thread_args *pwta =
  13564. (struct worker_thread_args *)thread_func_param;
  13565. worker_thread_run(pwta);
  13566. mg_free(thread_func_param);
  13567. return 0;
  13568. }
  13569. #else
  13570. static void *
  13571. worker_thread(void *thread_func_param)
  13572. {
  13573. struct worker_thread_args *pwta =
  13574. (struct worker_thread_args *)thread_func_param;
  13575. worker_thread_run(pwta);
  13576. mg_free(thread_func_param);
  13577. return NULL;
  13578. }
  13579. #endif /* _WIN32 */
  13580. static void
  13581. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  13582. {
  13583. struct socket so;
  13584. char src_addr[IP_ADDR_STR_LEN];
  13585. socklen_t len = sizeof(so.rsa);
  13586. int on = 1;
  13587. if (!listener) {
  13588. return;
  13589. }
  13590. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  13591. == INVALID_SOCKET) {
  13592. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  13593. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  13594. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  13595. closesocket(so.sock);
  13596. } else {
  13597. /* Put so socket structure into the queue */
  13598. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  13599. set_close_on_exec(so.sock, fc(ctx));
  13600. so.is_ssl = listener->is_ssl;
  13601. so.ssl_redir = listener->ssl_redir;
  13602. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  13603. mg_cry(fc(ctx),
  13604. "%s: getsockname() failed: %s",
  13605. __func__,
  13606. strerror(ERRNO));
  13607. }
  13608. /* Set TCP keep-alive. This is needed because if HTTP-level
  13609. * keep-alive
  13610. * is enabled, and client resets the connection, server won't get
  13611. * TCP FIN or RST and will keep the connection open forever. With
  13612. * TCP keep-alive, next keep-alive handshake will figure out that
  13613. * the client is down and will close the server end.
  13614. * Thanks to Igor Klopov who suggested the patch. */
  13615. if (setsockopt(so.sock,
  13616. SOL_SOCKET,
  13617. SO_KEEPALIVE,
  13618. (SOCK_OPT_TYPE)&on,
  13619. sizeof(on)) != 0) {
  13620. mg_cry(fc(ctx),
  13621. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  13622. __func__,
  13623. strerror(ERRNO));
  13624. }
  13625. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  13626. * to effectively fill up the underlying IP packet payload and
  13627. * reduce the overhead of sending lots of small buffers. However
  13628. * this hurts the server's throughput (ie. operations per second)
  13629. * when HTTP 1.1 persistent connections are used and the responses
  13630. * are relatively small (eg. less than 1400 bytes).
  13631. */
  13632. if ((ctx != NULL) && (ctx->config[CONFIG_TCP_NODELAY] != NULL)
  13633. && (!strcmp(ctx->config[CONFIG_TCP_NODELAY], "1"))) {
  13634. if (set_tcp_nodelay(so.sock, 1) != 0) {
  13635. mg_cry(fc(ctx),
  13636. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  13637. __func__,
  13638. strerror(ERRNO));
  13639. }
  13640. }
  13641. /* We are using non-blocking sockets. Thus, the
  13642. * set_sock_timeout(so.sock, timeout);
  13643. * call is no longer required. */
  13644. set_blocking_mode(so.sock, 0);
  13645. so.in_use = 0;
  13646. produce_socket(ctx, &so);
  13647. }
  13648. }
  13649. static void
  13650. master_thread_run(void *thread_func_param)
  13651. {
  13652. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  13653. struct mg_workerTLS tls;
  13654. struct pollfd *pfd;
  13655. unsigned int i;
  13656. unsigned int workerthreadcount;
  13657. if (!ctx) {
  13658. return;
  13659. }
  13660. mg_set_thread_name("master");
  13661. /* Increase priority of the master thread */
  13662. #if defined(_WIN32)
  13663. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  13664. #elif defined(USE_MASTER_THREAD_PRIORITY)
  13665. int min_prio = sched_get_priority_min(SCHED_RR);
  13666. int max_prio = sched_get_priority_max(SCHED_RR);
  13667. if ((min_prio >= 0) && (max_prio >= 0)
  13668. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  13669. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  13670. struct sched_param sched_param = {0};
  13671. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  13672. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  13673. }
  13674. #endif
  13675. /* Initialize thread local storage */
  13676. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13677. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  13678. #endif
  13679. tls.is_master = 1;
  13680. pthread_setspecific(sTlsKey, &tls);
  13681. if (ctx->callbacks.init_thread) {
  13682. /* Callback for the master thread (type 0) */
  13683. ctx->callbacks.init_thread(ctx, 0);
  13684. }
  13685. /* Server starts *now* */
  13686. ctx->start_time = time(NULL);
  13687. /* Start the server */
  13688. pfd = ctx->listening_socket_fds;
  13689. while (ctx->stop_flag == 0) {
  13690. for (i = 0; i < ctx->num_listening_sockets; i++) {
  13691. pfd[i].fd = ctx->listening_sockets[i].sock;
  13692. pfd[i].events = POLLIN;
  13693. }
  13694. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  13695. for (i = 0; i < ctx->num_listening_sockets; i++) {
  13696. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  13697. * successful poll, and POLLIN is defined as
  13698. * (POLLRDNORM | POLLRDBAND)
  13699. * Therefore, we're checking pfd[i].revents & POLLIN, not
  13700. * pfd[i].revents == POLLIN. */
  13701. if ((ctx->stop_flag == 0) && (pfd[i].revents & POLLIN)) {
  13702. accept_new_connection(&ctx->listening_sockets[i], ctx);
  13703. }
  13704. }
  13705. }
  13706. }
  13707. /* Here stop_flag is 1 - Initiate shutdown. */
  13708. DEBUG_TRACE("%s", "stopping workers");
  13709. /* Stop signal received: somebody called mg_stop. Quit. */
  13710. close_all_listening_sockets(ctx);
  13711. /* Wakeup workers that are waiting for connections to handle. */
  13712. (void)pthread_mutex_lock(&ctx->thread_mutex);
  13713. #if defined(ALTERNATIVE_QUEUE)
  13714. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  13715. event_signal(ctx->client_wait_events[i]);
  13716. /* Since we know all sockets, we can shutdown the connections. */
  13717. if (ctx->client_socks[i].in_use) {
  13718. shutdown(ctx->client_socks[i].sock, SHUTDOWN_BOTH);
  13719. }
  13720. }
  13721. #else
  13722. pthread_cond_broadcast(&ctx->sq_full);
  13723. #endif
  13724. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  13725. /* Join all worker threads to avoid leaking threads. */
  13726. workerthreadcount = ctx->cfg_worker_threads;
  13727. for (i = 0; i < workerthreadcount; i++) {
  13728. if (ctx->worker_threadids[i] != 0) {
  13729. mg_join_thread(ctx->worker_threadids[i]);
  13730. }
  13731. }
  13732. #if defined(USE_LUA)
  13733. /* Free Lua state of lua background task */
  13734. if (ctx->lua_background_state) {
  13735. lua_close((lua_State *)ctx->lua_background_state);
  13736. ctx->lua_background_state = 0;
  13737. }
  13738. #endif
  13739. DEBUG_TRACE("%s", "exiting");
  13740. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13741. CloseHandle(tls.pthread_cond_helper_mutex);
  13742. #endif
  13743. pthread_setspecific(sTlsKey, NULL);
  13744. /* Signal mg_stop() that we're done.
  13745. * WARNING: This must be the very last thing this
  13746. * thread does, as ctx becomes invalid after this line. */
  13747. ctx->stop_flag = 2;
  13748. }
  13749. /* Threads have different return types on Windows and Unix. */
  13750. #ifdef _WIN32
  13751. static unsigned __stdcall master_thread(void *thread_func_param)
  13752. {
  13753. master_thread_run(thread_func_param);
  13754. return 0;
  13755. }
  13756. #else
  13757. static void *
  13758. master_thread(void *thread_func_param)
  13759. {
  13760. master_thread_run(thread_func_param);
  13761. return NULL;
  13762. }
  13763. #endif /* _WIN32 */
  13764. static void
  13765. free_context(struct mg_context *ctx)
  13766. {
  13767. int i;
  13768. struct mg_handler_info *tmp_rh;
  13769. if (ctx == NULL) {
  13770. return;
  13771. }
  13772. if (ctx->callbacks.exit_context) {
  13773. ctx->callbacks.exit_context(ctx);
  13774. }
  13775. /* All threads exited, no sync is needed. Destroy thread mutex and
  13776. * condvars
  13777. */
  13778. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  13779. #if defined(ALTERNATIVE_QUEUE)
  13780. mg_free(ctx->client_socks);
  13781. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  13782. event_destroy(ctx->client_wait_events[i]);
  13783. }
  13784. mg_free(ctx->client_wait_events);
  13785. #else
  13786. (void)pthread_cond_destroy(&ctx->sq_empty);
  13787. (void)pthread_cond_destroy(&ctx->sq_full);
  13788. #endif
  13789. /* Destroy other context global data structures mutex */
  13790. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  13791. #if defined(USE_TIMERS)
  13792. timers_exit(ctx);
  13793. #endif
  13794. /* Deallocate config parameters */
  13795. for (i = 0; i < NUM_OPTIONS; i++) {
  13796. if (ctx->config[i] != NULL) {
  13797. #if defined(_MSC_VER)
  13798. #pragma warning(suppress : 6001)
  13799. #endif
  13800. mg_free(ctx->config[i]);
  13801. }
  13802. }
  13803. /* Deallocate request handlers */
  13804. while (ctx->handlers) {
  13805. tmp_rh = ctx->handlers;
  13806. ctx->handlers = tmp_rh->next;
  13807. mg_free(tmp_rh->uri);
  13808. mg_free(tmp_rh);
  13809. }
  13810. #ifndef NO_SSL
  13811. /* Deallocate SSL context */
  13812. if (ctx->ssl_ctx != NULL) {
  13813. SSL_CTX_free(ctx->ssl_ctx);
  13814. }
  13815. #endif /* !NO_SSL */
  13816. /* Deallocate worker thread ID array */
  13817. if (ctx->worker_threadids != NULL) {
  13818. mg_free(ctx->worker_threadids);
  13819. }
  13820. /* Deallocate worker thread ID array */
  13821. if (ctx->worker_connections != NULL) {
  13822. mg_free(ctx->worker_connections);
  13823. }
  13824. /* deallocate system name string */
  13825. mg_free(ctx->systemName);
  13826. /* Deallocate context itself */
  13827. mg_free(ctx);
  13828. }
  13829. void
  13830. mg_stop(struct mg_context *ctx)
  13831. {
  13832. pthread_t mt;
  13833. if (!ctx) {
  13834. return;
  13835. }
  13836. /* We don't use a lock here. Calling mg_stop with the same ctx from
  13837. * two threads is not allowed. */
  13838. mt = ctx->masterthreadid;
  13839. if (mt == 0) {
  13840. return;
  13841. }
  13842. ctx->masterthreadid = 0;
  13843. /* Set stop flag, so all threads know they have to exit. */
  13844. ctx->stop_flag = 1;
  13845. /* Wait until everything has stopped. */
  13846. while (ctx->stop_flag != 2) {
  13847. (void)mg_sleep(10);
  13848. }
  13849. mg_join_thread(mt);
  13850. free_context(ctx);
  13851. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13852. (void)WSACleanup();
  13853. #endif /* _WIN32 && !__SYMBIAN32__ */
  13854. }
  13855. static void
  13856. get_system_name(char **sysName)
  13857. {
  13858. #if defined(_WIN32)
  13859. #if !defined(__SYMBIAN32__)
  13860. #if defined(_WIN32_WCE)
  13861. *sysName = mg_strdup("WinCE");
  13862. #else
  13863. char name[128];
  13864. DWORD dwVersion = 0;
  13865. DWORD dwMajorVersion = 0;
  13866. DWORD dwMinorVersion = 0;
  13867. DWORD dwBuild = 0;
  13868. BOOL wowRet, isWoW = FALSE;
  13869. #ifdef _MSC_VER
  13870. #pragma warning(push)
  13871. /* GetVersion was declared deprecated */
  13872. #pragma warning(disable : 4996)
  13873. #endif
  13874. dwVersion = GetVersion();
  13875. #ifdef _MSC_VER
  13876. #pragma warning(pop)
  13877. #endif
  13878. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  13879. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  13880. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  13881. (void)dwBuild;
  13882. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  13883. sprintf(name,
  13884. "Windows %u.%u%s",
  13885. (unsigned)dwMajorVersion,
  13886. (unsigned)dwMinorVersion,
  13887. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  13888. *sysName = mg_strdup(name);
  13889. #endif
  13890. #else
  13891. *sysName = mg_strdup("Symbian");
  13892. #endif
  13893. #else
  13894. struct utsname name;
  13895. memset(&name, 0, sizeof(name));
  13896. uname(&name);
  13897. *sysName = mg_strdup(name.sysname);
  13898. #endif
  13899. }
  13900. struct mg_context *
  13901. mg_start(const struct mg_callbacks *callbacks,
  13902. void *user_data,
  13903. const char **options)
  13904. {
  13905. struct mg_context *ctx;
  13906. const char *name, *value, *default_value;
  13907. int idx, ok, workerthreadcount;
  13908. unsigned int i;
  13909. int itmp;
  13910. void (*exit_callback)(const struct mg_context *ctx) = 0;
  13911. struct mg_workerTLS tls;
  13912. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13913. WSADATA data;
  13914. WSAStartup(MAKEWORD(2, 2), &data);
  13915. #endif /* _WIN32 && !__SYMBIAN32__ */
  13916. /* Allocate context and initialize reasonable general case defaults. */
  13917. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  13918. return NULL;
  13919. }
  13920. /* Random number generator will initialize at the first call */
  13921. ctx->auth_nonce_mask =
  13922. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  13923. if (mg_init_library_called == 0) {
  13924. /* Legacy INIT, if mg_start is called without mg_init_library.
  13925. * Note: This may cause a memory leak */
  13926. mg_init_library(0);
  13927. }
  13928. tls.is_master = -1;
  13929. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  13930. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13931. tls.pthread_cond_helper_mutex = NULL;
  13932. #endif
  13933. pthread_setspecific(sTlsKey, &tls);
  13934. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr);
  13935. #if !defined(ALTERNATIVE_QUEUE)
  13936. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  13937. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  13938. #endif
  13939. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr);
  13940. if (!ok) {
  13941. /* Fatal error - abort start. However, this situation should never
  13942. * occur in practice. */
  13943. mg_cry(fc(ctx), "Cannot initialize thread synchronization objects");
  13944. mg_free(ctx);
  13945. pthread_setspecific(sTlsKey, NULL);
  13946. return NULL;
  13947. }
  13948. if (callbacks) {
  13949. ctx->callbacks = *callbacks;
  13950. exit_callback = callbacks->exit_context;
  13951. ctx->callbacks.exit_context = 0;
  13952. }
  13953. ctx->user_data = user_data;
  13954. ctx->handlers = NULL;
  13955. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  13956. ctx->shared_lua_websockets = 0;
  13957. #endif
  13958. while (options && (name = *options++) != NULL) {
  13959. if ((idx = get_option_index(name)) == -1) {
  13960. mg_cry(fc(ctx), "Invalid option: %s", name);
  13961. free_context(ctx);
  13962. pthread_setspecific(sTlsKey, NULL);
  13963. return NULL;
  13964. } else if ((value = *options++) == NULL) {
  13965. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  13966. free_context(ctx);
  13967. pthread_setspecific(sTlsKey, NULL);
  13968. return NULL;
  13969. }
  13970. if (ctx->config[idx] != NULL) {
  13971. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  13972. mg_free(ctx->config[idx]);
  13973. }
  13974. ctx->config[idx] = mg_strdup(value);
  13975. DEBUG_TRACE("[%s] -> [%s]", name, value);
  13976. }
  13977. /* Set default value if needed */
  13978. for (i = 0; config_options[i].name != NULL; i++) {
  13979. default_value = config_options[i].default_value;
  13980. if ((ctx->config[i] == NULL) && (default_value != NULL)) {
  13981. ctx->config[i] = mg_strdup(default_value);
  13982. }
  13983. }
  13984. itmp = atoi(ctx->config[MAX_REQUEST_SIZE]);
  13985. if (itmp < 1024) {
  13986. mg_cry(fc(ctx), "max_request_size too small");
  13987. free_context(ctx);
  13988. pthread_setspecific(sTlsKey, NULL);
  13989. return NULL;
  13990. }
  13991. ctx->max_request_size = (unsigned)itmp;
  13992. workerthreadcount = atoi(ctx->config[NUM_THREADS]);
  13993. if (workerthreadcount > MAX_WORKER_THREADS) {
  13994. mg_cry(fc(ctx), "Too many worker threads");
  13995. free_context(ctx);
  13996. pthread_setspecific(sTlsKey, NULL);
  13997. return NULL;
  13998. }
  13999. if (workerthreadcount <= 0) {
  14000. mg_cry(fc(ctx), "Invalid number of worker threads");
  14001. free_context(ctx);
  14002. pthread_setspecific(sTlsKey, NULL);
  14003. return NULL;
  14004. }
  14005. #if defined(NO_FILES)
  14006. if (ctx->config[DOCUMENT_ROOT] != NULL) {
  14007. mg_cry(fc(ctx), "%s", "Document root must not be set");
  14008. free_context(ctx);
  14009. pthread_setspecific(sTlsKey, NULL);
  14010. return NULL;
  14011. }
  14012. #endif
  14013. get_system_name(&ctx->systemName);
  14014. #if defined(USE_LUA)
  14015. /* If a Lua background script has been configured, start it. */
  14016. if (ctx->config[LUA_BACKGROUND_SCRIPT] != NULL) {
  14017. char ebuf[256];
  14018. void *state = (void *)mg_prepare_lua_context_script(
  14019. ctx->config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  14020. if (!state) {
  14021. mg_cry(fc(ctx), "lua_background_script error: %s", ebuf);
  14022. free_context(ctx);
  14023. pthread_setspecific(sTlsKey, NULL);
  14024. return NULL;
  14025. }
  14026. ctx->lua_background_state = state;
  14027. } else {
  14028. ctx->lua_background_state = 0;
  14029. }
  14030. #endif
  14031. /* NOTE(lsm): order is important here. SSL certificates must
  14032. * be initialized before listening ports. UID must be set last. */
  14033. if (!set_gpass_option(ctx) ||
  14034. #if !defined(NO_SSL)
  14035. !set_ssl_option(ctx) ||
  14036. #endif
  14037. !set_ports_option(ctx) ||
  14038. #if !defined(_WIN32)
  14039. !set_uid_option(ctx) ||
  14040. #endif
  14041. !set_acl_option(ctx)) {
  14042. free_context(ctx);
  14043. pthread_setspecific(sTlsKey, NULL);
  14044. return NULL;
  14045. }
  14046. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  14047. /* Ignore SIGPIPE signal, so if browser cancels the request, it
  14048. * won't kill the whole process. */
  14049. (void)signal(SIGPIPE, SIG_IGN);
  14050. #endif /* !_WIN32 && !__SYMBIAN32__ */
  14051. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  14052. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  14053. sizeof(pthread_t),
  14054. ctx);
  14055. if (ctx->worker_threadids == NULL) {
  14056. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  14057. free_context(ctx);
  14058. pthread_setspecific(sTlsKey, NULL);
  14059. return NULL;
  14060. }
  14061. ctx->worker_connections =
  14062. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  14063. sizeof(struct mg_connection),
  14064. ctx);
  14065. if (ctx->worker_connections == NULL) {
  14066. mg_cry(fc(ctx), "Not enough memory for worker thread connection array");
  14067. free_context(ctx);
  14068. pthread_setspecific(sTlsKey, NULL);
  14069. return NULL;
  14070. }
  14071. #if defined(ALTERNATIVE_QUEUE)
  14072. ctx->client_wait_events = mg_calloc_ctx(sizeof(ctx->client_wait_events[0]),
  14073. ctx->cfg_worker_threads,
  14074. ctx);
  14075. if (ctx->client_wait_events == NULL) {
  14076. mg_cry(fc(ctx), "Not enough memory for worker event array");
  14077. mg_free(ctx->worker_threadids);
  14078. free_context(ctx);
  14079. pthread_setspecific(sTlsKey, NULL);
  14080. return NULL;
  14081. }
  14082. ctx->client_socks = mg_calloc_ctx(sizeof(ctx->client_socks[0]),
  14083. ctx->cfg_worker_threads,
  14084. ctx);
  14085. if (ctx->client_wait_events == NULL) {
  14086. mg_cry(fc(ctx), "Not enough memory for worker socket array");
  14087. mg_free(ctx->client_socks);
  14088. mg_free(ctx->worker_threadids);
  14089. free_context(ctx);
  14090. pthread_setspecific(sTlsKey, NULL);
  14091. return NULL;
  14092. }
  14093. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  14094. ctx->client_wait_events[i] = event_create();
  14095. if (ctx->client_wait_events[i] == 0) {
  14096. mg_cry(fc(ctx), "Error creating worker event %i", i);
  14097. while (i > 0) {
  14098. i--;
  14099. event_destroy(ctx->client_wait_events[i]);
  14100. }
  14101. mg_free(ctx->client_socks);
  14102. mg_free(ctx->worker_threadids);
  14103. free_context(ctx);
  14104. pthread_setspecific(sTlsKey, NULL);
  14105. return NULL;
  14106. }
  14107. }
  14108. #endif
  14109. #if defined(USE_TIMERS)
  14110. if (timers_init(ctx) != 0) {
  14111. mg_cry(fc(ctx), "Error creating timers");
  14112. free_context(ctx);
  14113. pthread_setspecific(sTlsKey, NULL);
  14114. return NULL;
  14115. }
  14116. #endif
  14117. /* Context has been created - init user libraries */
  14118. if (ctx->callbacks.init_context) {
  14119. ctx->callbacks.init_context(ctx);
  14120. }
  14121. ctx->callbacks.exit_context = exit_callback;
  14122. ctx->context_type = 1; /* server context */
  14123. /* Start master (listening) thread */
  14124. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  14125. /* Start worker threads */
  14126. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  14127. struct worker_thread_args *wta = (struct worker_thread_args *)
  14128. mg_malloc_ctx(sizeof(struct worker_thread_args), ctx);
  14129. if (wta) {
  14130. wta->ctx = ctx;
  14131. wta->index = (int)i;
  14132. }
  14133. if ((wta == NULL)
  14134. || (mg_start_thread_with_id(worker_thread,
  14135. wta,
  14136. &ctx->worker_threadids[i]) != 0)) {
  14137. /* thread was not created */
  14138. if (wta != NULL) {
  14139. mg_free(wta);
  14140. }
  14141. if (i > 0) {
  14142. mg_cry(fc(ctx),
  14143. "Cannot start worker thread %i: error %ld",
  14144. i + 1,
  14145. (long)ERRNO);
  14146. } else {
  14147. mg_cry(fc(ctx),
  14148. "Cannot create threads: error %ld",
  14149. (long)ERRNO);
  14150. free_context(ctx);
  14151. pthread_setspecific(sTlsKey, NULL);
  14152. return NULL;
  14153. }
  14154. break;
  14155. }
  14156. }
  14157. pthread_setspecific(sTlsKey, NULL);
  14158. return ctx;
  14159. }
  14160. /* Feature check API function */
  14161. unsigned
  14162. mg_check_feature(unsigned feature)
  14163. {
  14164. static const unsigned feature_set = 0
  14165. /* Set bits for available features according to API documentation.
  14166. * This bit mask is created at compile time, according to the active
  14167. * preprocessor defines. It is a single const value at runtime. */
  14168. #if !defined(NO_FILES)
  14169. | 0x0001u
  14170. #endif
  14171. #if !defined(NO_SSL)
  14172. | 0x0002u
  14173. #endif
  14174. #if !defined(NO_CGI)
  14175. | 0x0004u
  14176. #endif
  14177. #if defined(USE_IPV6)
  14178. | 0x0008u
  14179. #endif
  14180. #if defined(USE_WEBSOCKET)
  14181. | 0x0010u
  14182. #endif
  14183. #if defined(USE_LUA)
  14184. | 0x0020u
  14185. #endif
  14186. #if defined(USE_DUKTAPE)
  14187. | 0x0040u
  14188. #endif
  14189. #if !defined(NO_CACHING)
  14190. | 0x0080u
  14191. #endif
  14192. #if defined(USE_SERVER_STATS)
  14193. | 0x0100u
  14194. #endif
  14195. /* Set some extra bits not defined in the API documentation.
  14196. * These bits may change without further notice. */
  14197. #if defined(MG_LEGACY_INTERFACE)
  14198. | 0x8000u
  14199. #endif
  14200. #if defined(MEMORY_DEBUGGING)
  14201. | 0x0100u
  14202. #endif
  14203. #if defined(USE_TIMERS)
  14204. | 0x0200u
  14205. #endif
  14206. #if !defined(NO_NONCE_CHECK)
  14207. | 0x0400u
  14208. #endif
  14209. #if !defined(NO_POPEN)
  14210. | 0x0800u
  14211. #endif
  14212. ;
  14213. return (feature & feature_set);
  14214. }
  14215. /* Get system information. It can be printed or stored by the caller.
  14216. * Return the size of available information. */
  14217. static int
  14218. mg_get_system_info_impl(char *buffer, int buflen)
  14219. {
  14220. char block[256];
  14221. int system_info_length = 0;
  14222. #if defined(_WIN32)
  14223. const char *eol = "\r\n";
  14224. #else
  14225. const char *eol = "\n";
  14226. #endif
  14227. if (buffer == NULL) {
  14228. /* Avoid some warning (although, if some dillweed supplies
  14229. * buffer==NULL combined with buflen>0, he deserves a crash).
  14230. */
  14231. buflen = 0;
  14232. }
  14233. /* Server version */
  14234. {
  14235. const char *version = mg_version();
  14236. mg_snprintf(NULL,
  14237. NULL,
  14238. block,
  14239. sizeof(block),
  14240. "Server Version: %s%s",
  14241. version,
  14242. eol);
  14243. system_info_length += (int)strlen(block);
  14244. if (system_info_length < buflen) {
  14245. strcat(buffer, block);
  14246. }
  14247. }
  14248. /* System info */
  14249. {
  14250. #if defined(_WIN32)
  14251. #if !defined(__SYMBIAN32__)
  14252. DWORD dwVersion = 0;
  14253. DWORD dwMajorVersion = 0;
  14254. DWORD dwMinorVersion = 0;
  14255. SYSTEM_INFO si;
  14256. GetSystemInfo(&si);
  14257. #ifdef _MSC_VER
  14258. #pragma warning(push)
  14259. /* GetVersion was declared deprecated */
  14260. #pragma warning(disable : 4996)
  14261. #endif
  14262. dwVersion = GetVersion();
  14263. #ifdef _MSC_VER
  14264. #pragma warning(pop)
  14265. #endif
  14266. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  14267. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  14268. mg_snprintf(NULL,
  14269. NULL,
  14270. block,
  14271. sizeof(block),
  14272. "Windows %u.%u%s",
  14273. (unsigned)dwMajorVersion,
  14274. (unsigned)dwMinorVersion,
  14275. eol);
  14276. system_info_length += (int)strlen(block);
  14277. if (system_info_length < buflen) {
  14278. strcat(buffer, block);
  14279. }
  14280. mg_snprintf(NULL,
  14281. NULL,
  14282. block,
  14283. sizeof(block),
  14284. "CPU: type %u, cores %u, mask %x%s",
  14285. (unsigned)si.wProcessorArchitecture,
  14286. (unsigned)si.dwNumberOfProcessors,
  14287. (unsigned)si.dwActiveProcessorMask,
  14288. eol);
  14289. system_info_length += (int)strlen(block);
  14290. if (system_info_length < buflen) {
  14291. strcat(buffer, block);
  14292. }
  14293. #else
  14294. mg_snprintf(NULL, NULL, block, sizeof(block), "%s - Symbian%s", eol);
  14295. system_info_length += (int)strlen(block);
  14296. if (system_info_length < buflen) {
  14297. strcat(buffer, block);
  14298. }
  14299. #endif
  14300. #else
  14301. struct utsname name;
  14302. memset(&name, 0, sizeof(name));
  14303. uname(&name);
  14304. mg_snprintf(NULL,
  14305. NULL,
  14306. block,
  14307. sizeof(block),
  14308. "%s %s (%s) - %s%s",
  14309. name.sysname,
  14310. name.version,
  14311. name.release,
  14312. name.machine,
  14313. eol);
  14314. system_info_length += (int)strlen(block);
  14315. if (system_info_length < buflen) {
  14316. strcat(buffer, block);
  14317. }
  14318. #endif
  14319. }
  14320. /* Features */
  14321. {
  14322. mg_snprintf(NULL,
  14323. NULL,
  14324. block,
  14325. sizeof(block),
  14326. "Features: %X%s%s%s%s%s%s%s%s%s%s",
  14327. mg_check_feature(0xFFFFFFFFu),
  14328. eol,
  14329. mg_check_feature(1) ? " Files" : "",
  14330. mg_check_feature(2) ? " HTTPS" : "",
  14331. mg_check_feature(4) ? " CGI" : "",
  14332. mg_check_feature(8) ? " IPv6" : "",
  14333. mg_check_feature(16) ? " WebSockets" : "",
  14334. mg_check_feature(32) ? " Lua" : "",
  14335. mg_check_feature(64) ? " JavaScript" : "",
  14336. mg_check_feature(128) ? " Cache" : "",
  14337. eol);
  14338. system_info_length += (int)strlen(block);
  14339. if (system_info_length < buflen) {
  14340. strcat(buffer, block);
  14341. }
  14342. #ifdef USE_LUA
  14343. mg_snprintf(NULL,
  14344. NULL,
  14345. block,
  14346. sizeof(block),
  14347. "Lua Version: %u (%s)%s",
  14348. (unsigned)LUA_VERSION_NUM,
  14349. LUA_RELEASE,
  14350. eol);
  14351. system_info_length += (int)strlen(block);
  14352. if (system_info_length < buflen) {
  14353. strcat(buffer, block);
  14354. }
  14355. #endif
  14356. #if defined(USE_DUKTAPE)
  14357. mg_snprintf(NULL,
  14358. NULL,
  14359. block,
  14360. sizeof(block),
  14361. "JavaScript: Duktape %u.%u.%u%s",
  14362. (unsigned)DUK_VERSION / 10000,
  14363. ((unsigned)DUK_VERSION / 100) % 100,
  14364. (unsigned)DUK_VERSION % 100,
  14365. eol);
  14366. system_info_length += (int)strlen(block);
  14367. if (system_info_length < buflen) {
  14368. strcat(buffer, block);
  14369. }
  14370. #endif
  14371. }
  14372. /* Build date */
  14373. {
  14374. mg_snprintf(
  14375. NULL, NULL, block, sizeof(block), "Build: %s%s", __DATE__, eol);
  14376. system_info_length += (int)strlen(block);
  14377. if (system_info_length < buflen) {
  14378. strcat(buffer, block);
  14379. }
  14380. }
  14381. /* Compiler information */
  14382. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  14383. {
  14384. #if defined(_MSC_VER)
  14385. mg_snprintf(NULL,
  14386. NULL,
  14387. block,
  14388. sizeof(block),
  14389. "MSC: %u (%u)%s",
  14390. (unsigned)_MSC_VER,
  14391. (unsigned)_MSC_FULL_VER,
  14392. eol);
  14393. system_info_length += (int)strlen(block);
  14394. if (system_info_length < buflen) {
  14395. strcat(buffer, block);
  14396. }
  14397. #elif defined(__MINGW64__)
  14398. mg_snprintf(NULL,
  14399. NULL,
  14400. block,
  14401. sizeof(block),
  14402. "MinGW64: %u.%u%s",
  14403. (unsigned)__MINGW64_VERSION_MAJOR,
  14404. (unsigned)__MINGW64_VERSION_MINOR,
  14405. eol);
  14406. system_info_length += (int)strlen(block);
  14407. if (system_info_length < buflen) {
  14408. strcat(buffer, block);
  14409. }
  14410. mg_snprintf(NULL,
  14411. NULL,
  14412. block,
  14413. sizeof(block),
  14414. "MinGW32: %u.%u%s",
  14415. (unsigned)__MINGW32_MAJOR_VERSION,
  14416. (unsigned)__MINGW32_MINOR_VERSION,
  14417. eol);
  14418. system_info_length += (int)strlen(block);
  14419. if (system_info_length < buflen) {
  14420. strcat(buffer, block);
  14421. }
  14422. #elif defined(__MINGW32__)
  14423. mg_snprintf(NULL,
  14424. NULL,
  14425. block,
  14426. sizeof(block),
  14427. "MinGW32: %u.%u%s",
  14428. (unsigned)__MINGW32_MAJOR_VERSION,
  14429. (unsigned)__MINGW32_MINOR_VERSION,
  14430. eol);
  14431. system_info_length += (int)strlen(block);
  14432. if (system_info_length < buflen) {
  14433. strcat(buffer, block);
  14434. }
  14435. #elif defined(__clang__)
  14436. mg_snprintf(NULL,
  14437. NULL,
  14438. block,
  14439. sizeof(block),
  14440. "clang: %u.%u.%u (%s)%s",
  14441. __clang_major__,
  14442. __clang_minor__,
  14443. __clang_patchlevel__,
  14444. __clang_version__,
  14445. eol);
  14446. system_info_length += (int)strlen(block);
  14447. if (system_info_length < buflen) {
  14448. strcat(buffer, block);
  14449. }
  14450. #elif defined(__GNUC__)
  14451. mg_snprintf(NULL,
  14452. NULL,
  14453. block,
  14454. sizeof(block),
  14455. "gcc: %u.%u.%u%s",
  14456. (unsigned)__GNUC__,
  14457. (unsigned)__GNUC_MINOR__,
  14458. (unsigned)__GNUC_PATCHLEVEL__,
  14459. eol);
  14460. system_info_length += (int)strlen(block);
  14461. if (system_info_length < buflen) {
  14462. strcat(buffer, block);
  14463. }
  14464. #elif defined(__INTEL_COMPILER)
  14465. mg_snprintf(NULL,
  14466. NULL,
  14467. block,
  14468. sizeof(block),
  14469. "Intel C/C++: %u%s",
  14470. (unsigned)__INTEL_COMPILER,
  14471. eol);
  14472. system_info_length += (int)strlen(block);
  14473. if (system_info_length < buflen) {
  14474. strcat(buffer, block);
  14475. }
  14476. #elif defined(__BORLANDC__)
  14477. mg_snprintf(NULL,
  14478. NULL,
  14479. block,
  14480. sizeof(block),
  14481. "Borland C: 0x%x%s",
  14482. (unsigned)__BORLANDC__,
  14483. eol);
  14484. system_info_length += (int)strlen(block);
  14485. if (system_info_length < buflen) {
  14486. strcat(buffer, block);
  14487. }
  14488. #elif defined(__SUNPRO_C)
  14489. mg_snprintf(NULL,
  14490. NULL,
  14491. block,
  14492. sizeof(block),
  14493. "Solaris: 0x%x%s",
  14494. (unsigned)__SUNPRO_C,
  14495. eol);
  14496. system_info_length += (int)strlen(block);
  14497. if (system_info_length < buflen) {
  14498. strcat(buffer, block);
  14499. }
  14500. #else
  14501. mg_snprintf(NULL, NULL, block, sizeof(block), "Other compiler%s", eol);
  14502. system_info_length += (int)strlen(block);
  14503. if (system_info_length < buflen) {
  14504. strcat(buffer, block);
  14505. }
  14506. #endif
  14507. }
  14508. /* Determine 32/64 bit data mode.
  14509. * see https://en.wikipedia.org/wiki/64-bit_computing */
  14510. {
  14511. mg_snprintf(NULL,
  14512. NULL,
  14513. block,
  14514. sizeof(block),
  14515. "Data model: int:%u/%u/%u/%u, float:%u/%u/%u, char:%u/%u, "
  14516. "ptr:%u, size:%u, time:%u%s",
  14517. (unsigned)sizeof(short),
  14518. (unsigned)sizeof(int),
  14519. (unsigned)sizeof(long),
  14520. (unsigned)sizeof(long long),
  14521. (unsigned)sizeof(float),
  14522. (unsigned)sizeof(double),
  14523. (unsigned)sizeof(long double),
  14524. (unsigned)sizeof(char),
  14525. (unsigned)sizeof(wchar_t),
  14526. (unsigned)sizeof(void *),
  14527. (unsigned)sizeof(size_t),
  14528. (unsigned)sizeof(time_t),
  14529. eol);
  14530. system_info_length += (int)strlen(block);
  14531. if (system_info_length < buflen) {
  14532. strcat(buffer, block);
  14533. }
  14534. }
  14535. return system_info_length;
  14536. }
  14537. #if defined(USE_SERVER_STATS)
  14538. /* Get context information. It can be printed or stored by the caller.
  14539. * Return the size of available information. */
  14540. static int
  14541. mg_get_context_info_impl(const struct mg_context *ctx, char *buffer, int buflen)
  14542. {
  14543. char block[256];
  14544. int context_info_length = 0;
  14545. #if defined(_WIN32)
  14546. const char *eol = "\r\n";
  14547. #else
  14548. const char *eol = "\n";
  14549. #endif
  14550. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  14551. const char *eoobj = "}";
  14552. int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
  14553. if ((buffer == NULL) || (buflen < 10)) {
  14554. buflen = 0;
  14555. }
  14556. mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
  14557. context_info_length += (int)strlen(block);
  14558. if (context_info_length < buflen) {
  14559. strcat(buffer, block);
  14560. }
  14561. /* Memory information */
  14562. if (ms) {
  14563. mg_snprintf(NULL,
  14564. NULL,
  14565. block,
  14566. sizeof(block),
  14567. "\"memory\" : {%s"
  14568. "\"blocks\" : %i,%s"
  14569. "\"used\" : %" INT64_FMT ",%s"
  14570. "\"maxUsed\" : %" INT64_FMT "%s"
  14571. "}%s%s",
  14572. eol,
  14573. ms->blockCount,
  14574. eol,
  14575. ms->totalMemUsed,
  14576. eol,
  14577. ms->maxMemUsed,
  14578. eol,
  14579. (ctx ? "," : ""),
  14580. eol);
  14581. context_info_length += (int)strlen(block);
  14582. if (context_info_length + reserved_len < buflen) {
  14583. strcat(buffer, block);
  14584. }
  14585. }
  14586. /* Connections information */
  14587. if (ctx) {
  14588. mg_snprintf(NULL,
  14589. NULL,
  14590. block,
  14591. sizeof(block),
  14592. "\"connections\" : {%s"
  14593. "\"active\" : %i,%s"
  14594. "\"maxActive\" : %i,%s"
  14595. "\"total\" : %" INT64_FMT "%s"
  14596. "},%s",
  14597. eol,
  14598. ctx->active_connections,
  14599. eol,
  14600. ctx->max_connections,
  14601. eol,
  14602. ctx->total_connections,
  14603. eol,
  14604. eol);
  14605. context_info_length += (int)strlen(block);
  14606. if (context_info_length + reserved_len < buflen) {
  14607. strcat(buffer, block);
  14608. }
  14609. }
  14610. /* Requests information */
  14611. if (ctx) {
  14612. mg_snprintf(NULL,
  14613. NULL,
  14614. block,
  14615. sizeof(block),
  14616. "\"requests\" : {%s"
  14617. "\"total\" : %" INT64_FMT "%s"
  14618. "},%s",
  14619. eol,
  14620. ctx->total_requests,
  14621. eol,
  14622. eol);
  14623. context_info_length += (int)strlen(block);
  14624. if (context_info_length + reserved_len < buflen) {
  14625. strcat(buffer, block);
  14626. }
  14627. }
  14628. /* Execution time information */
  14629. if (ctx) {
  14630. char start_time_str[64] = {0};
  14631. char now_str[64] = {0};
  14632. time_t start_time = ctx->start_time;
  14633. time_t now = time(NULL);
  14634. gmt_time_string(start_time_str,
  14635. sizeof(start_time_str) - 1,
  14636. &start_time);
  14637. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  14638. mg_snprintf(NULL,
  14639. NULL,
  14640. block,
  14641. sizeof(block),
  14642. "\"time\" : {%s"
  14643. "\"uptime\" : %.0f,%s"
  14644. "\"start\" : \"%s\",%s"
  14645. "\"now\" : \"%s\"%s"
  14646. "}%s",
  14647. eol,
  14648. difftime(now, start_time),
  14649. eol,
  14650. start_time_str,
  14651. eol,
  14652. now_str,
  14653. eol,
  14654. eol);
  14655. context_info_length += (int)strlen(block);
  14656. if (context_info_length + reserved_len < buflen) {
  14657. strcat(buffer, block);
  14658. }
  14659. }
  14660. /* Terminate string */
  14661. if ((buflen > 0) && buffer && buffer[0]) {
  14662. if (context_info_length < buflen) {
  14663. strcat(buffer, eoobj);
  14664. strcat(buffer, eol);
  14665. context_info_length += reserved_len;
  14666. }
  14667. }
  14668. return context_info_length;
  14669. }
  14670. #endif
  14671. /* Get system information. It can be printed or stored by the caller.
  14672. * Return the size of available information. */
  14673. int
  14674. mg_get_system_info(char *buffer, int buflen)
  14675. {
  14676. if ((buffer == NULL) || (buflen < 1)) {
  14677. return mg_get_system_info_impl(NULL, 0);
  14678. } else {
  14679. /* Reset buffer, so we can always use strcat. */
  14680. buffer[0] = 0;
  14681. return mg_get_system_info_impl(buffer, buflen);
  14682. }
  14683. }
  14684. /* Get context information. It can be printed or stored by the caller.
  14685. * Return the size of available information. */
  14686. int
  14687. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  14688. {
  14689. #if defined(USE_SERVER_STATS)
  14690. if ((buffer == NULL) || (buflen < 1)) {
  14691. return mg_get_context_info_impl(ctx, NULL, 0);
  14692. } else {
  14693. /* Reset buffer, so we can always use strcat. */
  14694. buffer[0] = 0;
  14695. return mg_get_context_info_impl(ctx, buffer, buflen);
  14696. }
  14697. #else
  14698. (void)ctx;
  14699. if ((buffer != NULL) && (buflen > 0)) {
  14700. buffer[0] = 0;
  14701. }
  14702. return 0;
  14703. #endif
  14704. }
  14705. /* Initialize this library. This function does not need to be thread safe.
  14706. */
  14707. unsigned
  14708. mg_init_library(unsigned features)
  14709. {
  14710. #if !defined(NO_SSL)
  14711. char ebuf[128];
  14712. #endif
  14713. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  14714. unsigned features_inited = features_to_init;
  14715. if (mg_init_library_called <= 0) {
  14716. /* Not initialized yet */
  14717. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  14718. return 0;
  14719. }
  14720. }
  14721. mg_global_lock();
  14722. if (mg_init_library_called <= 0) {
  14723. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  14724. /* Fatal error - abort start. However, this situation should
  14725. * never occur in practice. */
  14726. return 0;
  14727. }
  14728. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14729. InitializeCriticalSection(&global_log_file_lock);
  14730. #endif /* _WIN32 && !__SYMBIAN32__ */
  14731. #if !defined(_WIN32)
  14732. pthread_mutexattr_init(&pthread_mutex_attr);
  14733. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  14734. #endif
  14735. #if defined(USE_LUA)
  14736. lua_init_optional_libraries();
  14737. #endif
  14738. }
  14739. #if !defined(NO_SSL)
  14740. if (features_to_init & 2) {
  14741. if (!mg_ssl_initialized) {
  14742. if (initialize_ssl(ebuf, sizeof(ebuf))) {
  14743. mg_ssl_initialized = 1;
  14744. } else {
  14745. (void)ebuf;
  14746. /* TODO: print error */
  14747. features_inited &= ~(2u);
  14748. }
  14749. } else {
  14750. /* ssl already initialized */
  14751. }
  14752. }
  14753. #endif
  14754. /* Start WinSock for Windows */
  14755. if (mg_init_library_called <= 0) {
  14756. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14757. WSADATA data;
  14758. WSAStartup(MAKEWORD(2, 2), &data);
  14759. #endif /* _WIN32 && !__SYMBIAN32__ */
  14760. mg_init_library_called = 1;
  14761. } else {
  14762. mg_init_library_called++;
  14763. }
  14764. mg_global_unlock();
  14765. return features_inited;
  14766. }
  14767. /* Un-initialize this library. */
  14768. unsigned
  14769. mg_exit_library(void)
  14770. {
  14771. if (mg_init_library_called <= 0) {
  14772. return 0;
  14773. }
  14774. mg_global_lock();
  14775. mg_init_library_called--;
  14776. if (mg_init_library_called == 0) {
  14777. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14778. (void)WSACleanup();
  14779. #endif /* _WIN32 && !__SYMBIAN32__ */
  14780. #if !defined(NO_SSL)
  14781. if (mg_ssl_initialized) {
  14782. uninitialize_ssl();
  14783. mg_ssl_initialized = 0;
  14784. }
  14785. #endif
  14786. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14787. (void)DeleteCriticalSection(&global_log_file_lock);
  14788. #endif /* _WIN32 && !__SYMBIAN32__ */
  14789. #if !defined(_WIN32)
  14790. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  14791. #endif
  14792. (void)pthread_key_delete(sTlsKey);
  14793. #if defined(USE_LUA)
  14794. lua_exit_optional_libraries();
  14795. #endif
  14796. mg_global_unlock();
  14797. (void)pthread_mutex_destroy(&global_lock_mutex);
  14798. return 1;
  14799. }
  14800. mg_global_unlock();
  14801. return 1;
  14802. }
  14803. /* End of civetweb.c */