civetweb.c 451 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165
  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 accept_gzip; /* 1 if gzip encoding is accepted */
  1989. int in_error_handler; /* 1 if in handler for user defined error
  1990. * pages */
  1991. int handled_requests; /* Number of requests handled by this connection
  1992. */
  1993. int buf_size; /* Buffer size */
  1994. int request_len; /* Size of the request + headers in a buffer */
  1995. int data_len; /* Total size of data in a buffer */
  1996. int status_code; /* HTTP reply status code, e.g. 200 */
  1997. int throttle; /* Throttling, bytes/sec. <= 0 means no
  1998. * throttle */
  1999. time_t last_throttle_time; /* Last time throttled data was sent */
  2000. int64_t last_throttle_bytes; /* Bytes sent this second */
  2001. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2002. * atomic transmissions for websockets */
  2003. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2004. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2005. #endif
  2006. int thread_index; /* Thread index within ctx */
  2007. };
  2008. /* Directory entry */
  2009. struct de {
  2010. struct mg_connection *conn;
  2011. char *file_name;
  2012. struct mg_file_stat file;
  2013. };
  2014. #if defined(USE_WEBSOCKET)
  2015. static int is_websocket_protocol(const struct mg_connection *conn);
  2016. #else
  2017. #define is_websocket_protocol(conn) (0)
  2018. #endif
  2019. #if !defined(NO_THREAD_NAME)
  2020. #if defined(_WIN32) && defined(_MSC_VER)
  2021. /* Set the thread name for debugging purposes in Visual Studio
  2022. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2023. */
  2024. #pragma pack(push, 8)
  2025. typedef struct tagTHREADNAME_INFO {
  2026. DWORD dwType; /* Must be 0x1000. */
  2027. LPCSTR szName; /* Pointer to name (in user addr space). */
  2028. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2029. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2030. } THREADNAME_INFO;
  2031. #pragma pack(pop)
  2032. #elif defined(__linux__)
  2033. #include <sys/prctl.h>
  2034. #include <sys/sendfile.h>
  2035. #ifdef ALTERNATIVE_QUEUE
  2036. #include <sys/eventfd.h>
  2037. #endif /* ALTERNATIVE_QUEUE */
  2038. #if defined(ALTERNATIVE_QUEUE)
  2039. static void *
  2040. event_create(void)
  2041. {
  2042. int ret = eventfd(0, EFD_CLOEXEC);
  2043. if (ret == -1) {
  2044. /* Linux uses -1 on error, Windows NULL. */
  2045. /* However, Linux does not return 0 on success either. */
  2046. return 0;
  2047. }
  2048. return (void *)ret;
  2049. }
  2050. static int
  2051. event_wait(void *eventhdl)
  2052. {
  2053. uint64_t u;
  2054. int s = (int)read((int)eventhdl, &u, sizeof(u));
  2055. if (s != sizeof(uint64_t)) {
  2056. /* error */
  2057. return 0;
  2058. }
  2059. (void)u; /* the value is not required */
  2060. return 1;
  2061. }
  2062. static int
  2063. event_signal(void *eventhdl)
  2064. {
  2065. uint64_t u = 1;
  2066. int s = (int)write((int)eventhdl, &u, sizeof(u));
  2067. if (s != sizeof(uint64_t)) {
  2068. /* error */
  2069. return 0;
  2070. }
  2071. return 1;
  2072. }
  2073. static void
  2074. event_destroy(void *eventhdl)
  2075. {
  2076. close((int)eventhdl);
  2077. }
  2078. #endif
  2079. #endif
  2080. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2081. struct posix_event {
  2082. pthread_mutex_t mutex;
  2083. pthread_cond_t cond;
  2084. };
  2085. static void *
  2086. event_create(void)
  2087. {
  2088. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2089. if (ret == 0) {
  2090. /* out of memory */
  2091. return 0;
  2092. }
  2093. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2094. /* pthread mutex not available */
  2095. mg_free(ret);
  2096. return 0;
  2097. }
  2098. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2099. /* pthread cond not available */
  2100. pthread_mutex_destroy(&(ret->mutex));
  2101. mg_free(ret);
  2102. return 0;
  2103. }
  2104. return (void *)ret;
  2105. }
  2106. static int
  2107. event_wait(void *eventhdl)
  2108. {
  2109. struct posix_event *ev = (struct posix_event *)eventhdl;
  2110. pthread_mutex_lock(&(ev->mutex));
  2111. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2112. pthread_mutex_unlock(&(ev->mutex));
  2113. return 1;
  2114. }
  2115. static int
  2116. event_signal(void *eventhdl)
  2117. {
  2118. struct posix_event *ev = (struct posix_event *)eventhdl;
  2119. pthread_mutex_lock(&(ev->mutex));
  2120. pthread_cond_signal(&(ev->cond));
  2121. pthread_mutex_unlock(&(ev->mutex));
  2122. return 1;
  2123. }
  2124. static void
  2125. event_destroy(void *eventhdl)
  2126. {
  2127. struct posix_event *ev = (struct posix_event *)eventhdl;
  2128. pthread_cond_destroy(&(ev->cond));
  2129. pthread_mutex_destroy(&(ev->mutex));
  2130. mg_free(ev);
  2131. }
  2132. #endif
  2133. static void
  2134. mg_set_thread_name(const char *name)
  2135. {
  2136. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2137. mg_snprintf(
  2138. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2139. #if defined(_WIN32)
  2140. #if defined(_MSC_VER)
  2141. /* Windows and Visual Studio Compiler */
  2142. __try
  2143. {
  2144. THREADNAME_INFO info;
  2145. info.dwType = 0x1000;
  2146. info.szName = threadName;
  2147. info.dwThreadID = ~0U;
  2148. info.dwFlags = 0;
  2149. RaiseException(0x406D1388,
  2150. 0,
  2151. sizeof(info) / sizeof(ULONG_PTR),
  2152. (ULONG_PTR *)&info);
  2153. }
  2154. __except(EXCEPTION_EXECUTE_HANDLER)
  2155. {
  2156. }
  2157. #elif defined(__MINGW32__)
  2158. /* No option known to set thread name for MinGW */
  2159. #endif
  2160. #elif defined(__GLIBC__) \
  2161. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2162. /* pthread_setname_np first appeared in glibc in version 2.12*/
  2163. (void)pthread_setname_np(pthread_self(), threadName);
  2164. #elif defined(__linux__)
  2165. /* on linux we can use the old prctl function */
  2166. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2167. #endif
  2168. }
  2169. #else /* !defined(NO_THREAD_NAME) */
  2170. void
  2171. mg_set_thread_name(const char *threadName)
  2172. {
  2173. }
  2174. #endif
  2175. #if defined(MG_LEGACY_INTERFACE)
  2176. const char **
  2177. mg_get_valid_option_names(void)
  2178. {
  2179. /* This function is deprecated. Use mg_get_valid_options instead. */
  2180. static const char *
  2181. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  2182. int i;
  2183. for (i = 0; config_options[i].name != NULL; i++) {
  2184. data[i * 2] = config_options[i].name;
  2185. data[i * 2 + 1] = config_options[i].default_value;
  2186. }
  2187. return data;
  2188. }
  2189. #endif
  2190. const struct mg_option *
  2191. mg_get_valid_options(void)
  2192. {
  2193. return config_options;
  2194. }
  2195. /* Do not open file (used in is_file_in_memory) */
  2196. #define MG_FOPEN_MODE_NONE (0)
  2197. /* Open file for read only access */
  2198. #define MG_FOPEN_MODE_READ (1)
  2199. /* Open file for writing, create and overwrite */
  2200. #define MG_FOPEN_MODE_WRITE (2)
  2201. /* Open file for writing, create and append */
  2202. #define MG_FOPEN_MODE_APPEND (4)
  2203. /* If a file is in memory, set all "stat" members and the membuf pointer of
  2204. * output filep and return 1, otherwise return 0 and don't modify anything.
  2205. */
  2206. static int
  2207. open_file_in_memory(const struct mg_connection *conn,
  2208. const char *path,
  2209. struct mg_file *filep,
  2210. int mode)
  2211. {
  2212. #if defined(MG_USE_OPEN_FILE)
  2213. size_t size = 0;
  2214. const char *buf = NULL;
  2215. if (!conn) {
  2216. return 0;
  2217. }
  2218. if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
  2219. return 0;
  2220. }
  2221. if (conn->ctx->callbacks.open_file) {
  2222. buf = conn->ctx->callbacks.open_file(conn, path, &size);
  2223. if (buf != NULL) {
  2224. if (filep == NULL) {
  2225. /* This is a file in memory, but we cannot store the
  2226. * properties
  2227. * now.
  2228. * Called from "is_file_in_memory" function. */
  2229. return 1;
  2230. }
  2231. /* NOTE: override filep->size only on success. Otherwise, it
  2232. * might
  2233. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  2234. filep->access.membuf = buf;
  2235. filep->access.fp = NULL;
  2236. /* Size was set by the callback */
  2237. filep->stat.size = size;
  2238. /* Assume the data may change during runtime by setting
  2239. * last_modified = now */
  2240. filep->stat.last_modified = time(NULL);
  2241. filep->stat.is_directory = 0;
  2242. filep->stat.is_gzipped = 0;
  2243. }
  2244. }
  2245. return (buf != NULL);
  2246. #else
  2247. (void)conn;
  2248. (void)path;
  2249. (void)filep;
  2250. (void)mode;
  2251. return 0;
  2252. #endif
  2253. }
  2254. static int
  2255. is_file_in_memory(const struct mg_connection *conn, const char *path)
  2256. {
  2257. return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
  2258. }
  2259. static int
  2260. is_file_opened(const struct mg_file_access *fileacc)
  2261. {
  2262. if (!fileacc) {
  2263. return 0;
  2264. }
  2265. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  2266. }
  2267. static int mg_stat(const struct mg_connection *conn,
  2268. const char *path,
  2269. struct mg_file_stat *filep);
  2270. /* mg_fopen will open a file either in memory or on the disk.
  2271. * The input parameter path is a string in UTF-8 encoding.
  2272. * The input parameter mode is MG_FOPEN_MODE_*
  2273. * On success, either fp or membuf will be set in the output
  2274. * struct file. All status members will also be set.
  2275. * The function returns 1 on success, 0 on error. */
  2276. static int
  2277. mg_fopen(const struct mg_connection *conn,
  2278. const char *path,
  2279. int mode,
  2280. struct mg_file *filep)
  2281. {
  2282. int found;
  2283. if (!filep) {
  2284. return 0;
  2285. }
  2286. filep->access.fp = NULL;
  2287. filep->access.membuf = NULL;
  2288. if (!is_file_in_memory(conn, path)) {
  2289. /* filep is initialized in mg_stat: all fields with memset to,
  2290. * some fields like size and modification date with values */
  2291. found = mg_stat(conn, path, &(filep->stat));
  2292. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2293. /* file does not exist and will not be created */
  2294. return 0;
  2295. }
  2296. #ifdef _WIN32
  2297. {
  2298. wchar_t wbuf[PATH_MAX];
  2299. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2300. switch (mode) {
  2301. case MG_FOPEN_MODE_READ:
  2302. filep->access.fp = _wfopen(wbuf, L"rb");
  2303. break;
  2304. case MG_FOPEN_MODE_WRITE:
  2305. filep->access.fp = _wfopen(wbuf, L"wb");
  2306. break;
  2307. case MG_FOPEN_MODE_APPEND:
  2308. filep->access.fp = _wfopen(wbuf, L"ab");
  2309. break;
  2310. }
  2311. }
  2312. #else
  2313. /* Linux et al already use unicode. No need to convert. */
  2314. switch (mode) {
  2315. case MG_FOPEN_MODE_READ:
  2316. filep->access.fp = fopen(path, "r");
  2317. break;
  2318. case MG_FOPEN_MODE_WRITE:
  2319. filep->access.fp = fopen(path, "w");
  2320. break;
  2321. case MG_FOPEN_MODE_APPEND:
  2322. filep->access.fp = fopen(path, "a");
  2323. break;
  2324. }
  2325. #endif
  2326. if (!found) {
  2327. /* File did not exist before fopen was called.
  2328. * Maybe it has been created now. Get stat info
  2329. * like creation time now. */
  2330. found = mg_stat(conn, path, &(filep->stat));
  2331. (void)found;
  2332. }
  2333. /* file is on disk */
  2334. return (filep->access.fp != NULL);
  2335. } else {
  2336. /* is_file_in_memory returned true */
  2337. if (open_file_in_memory(conn, path, filep, mode)) {
  2338. /* file is in memory */
  2339. return (filep->access.membuf != NULL);
  2340. }
  2341. }
  2342. /* Open failed */
  2343. return 0;
  2344. }
  2345. /* return 0 on success, just like fclose */
  2346. static int
  2347. mg_fclose(struct mg_file_access *fileacc)
  2348. {
  2349. int ret = -1;
  2350. if (fileacc != NULL) {
  2351. if (fileacc->fp != NULL) {
  2352. ret = fclose(fileacc->fp);
  2353. } else if (fileacc->membuf != NULL) {
  2354. ret = 0;
  2355. }
  2356. /* reset all members of fileacc */
  2357. memset(fileacc, 0, sizeof(*fileacc));
  2358. }
  2359. return ret;
  2360. }
  2361. static void
  2362. mg_strlcpy(register char *dst, register const char *src, size_t n)
  2363. {
  2364. for (; *src != '\0' && n > 1; n--) {
  2365. *dst++ = *src++;
  2366. }
  2367. *dst = '\0';
  2368. }
  2369. static int
  2370. lowercase(const char *s)
  2371. {
  2372. return tolower(*(const unsigned char *)s);
  2373. }
  2374. int
  2375. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2376. {
  2377. int diff = 0;
  2378. if (len > 0) {
  2379. do {
  2380. diff = lowercase(s1++) - lowercase(s2++);
  2381. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2382. }
  2383. return diff;
  2384. }
  2385. int
  2386. mg_strcasecmp(const char *s1, const char *s2)
  2387. {
  2388. int diff;
  2389. do {
  2390. diff = lowercase(s1++) - lowercase(s2++);
  2391. } while (diff == 0 && s1[-1] != '\0');
  2392. return diff;
  2393. }
  2394. static char *
  2395. mg_strndup(const char *ptr, size_t len)
  2396. {
  2397. char *p;
  2398. if ((p = (char *)mg_malloc(len + 1)) != NULL) {
  2399. mg_strlcpy(p, ptr, len + 1);
  2400. }
  2401. return p;
  2402. }
  2403. static char *
  2404. mg_strdup(const char *str)
  2405. {
  2406. return mg_strndup(str, strlen(str));
  2407. }
  2408. static const char *
  2409. mg_strcasestr(const char *big_str, const char *small_str)
  2410. {
  2411. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2412. if (big_len >= small_len) {
  2413. for (i = 0; i <= (big_len - small_len); i++) {
  2414. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2415. return big_str + i;
  2416. }
  2417. }
  2418. }
  2419. return NULL;
  2420. }
  2421. /* Return null terminated string of given maximum length.
  2422. * Report errors if length is exceeded. */
  2423. static void
  2424. mg_vsnprintf(const struct mg_connection *conn,
  2425. int *truncated,
  2426. char *buf,
  2427. size_t buflen,
  2428. const char *fmt,
  2429. va_list ap)
  2430. {
  2431. int n, ok;
  2432. if (buflen == 0) {
  2433. if (truncated) {
  2434. *truncated = 1;
  2435. }
  2436. return;
  2437. }
  2438. #ifdef __clang__
  2439. #pragma clang diagnostic push
  2440. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2441. /* Using fmt as a non-literal is intended here, since it is mostly called
  2442. * indirectly by mg_snprintf */
  2443. #endif
  2444. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2445. ok = (n >= 0) && ((size_t)n < buflen);
  2446. #ifdef __clang__
  2447. #pragma clang diagnostic pop
  2448. #endif
  2449. if (ok) {
  2450. if (truncated) {
  2451. *truncated = 0;
  2452. }
  2453. } else {
  2454. if (truncated) {
  2455. *truncated = 1;
  2456. }
  2457. mg_cry(conn,
  2458. "truncating vsnprintf buffer: [%.*s]",
  2459. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2460. buf);
  2461. n = (int)buflen - 1;
  2462. }
  2463. buf[n] = '\0';
  2464. }
  2465. static void
  2466. mg_snprintf(const struct mg_connection *conn,
  2467. int *truncated,
  2468. char *buf,
  2469. size_t buflen,
  2470. const char *fmt,
  2471. ...)
  2472. {
  2473. va_list ap;
  2474. va_start(ap, fmt);
  2475. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2476. va_end(ap);
  2477. }
  2478. static int
  2479. get_option_index(const char *name)
  2480. {
  2481. int i;
  2482. for (i = 0; config_options[i].name != NULL; i++) {
  2483. if (strcmp(config_options[i].name, name) == 0) {
  2484. return i;
  2485. }
  2486. }
  2487. return -1;
  2488. }
  2489. const char *
  2490. mg_get_option(const struct mg_context *ctx, const char *name)
  2491. {
  2492. int i;
  2493. if ((i = get_option_index(name)) == -1) {
  2494. return NULL;
  2495. } else if (!ctx || ctx->config[i] == NULL) {
  2496. return "";
  2497. } else {
  2498. return ctx->config[i];
  2499. }
  2500. }
  2501. struct mg_context *
  2502. mg_get_context(const struct mg_connection *conn)
  2503. {
  2504. return (conn == NULL) ? (struct mg_context *)NULL : (conn->ctx);
  2505. }
  2506. void *
  2507. mg_get_user_data(const struct mg_context *ctx)
  2508. {
  2509. return (ctx == NULL) ? NULL : ctx->user_data;
  2510. }
  2511. void
  2512. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  2513. {
  2514. if (conn != NULL) {
  2515. conn->request_info.conn_data = data;
  2516. }
  2517. }
  2518. void *
  2519. mg_get_user_connection_data(const struct mg_connection *conn)
  2520. {
  2521. if (conn != NULL) {
  2522. return conn->request_info.conn_data;
  2523. }
  2524. return NULL;
  2525. }
  2526. #if defined(MG_LEGACY_INTERFACE)
  2527. /* Deprecated: Use mg_get_server_ports instead. */
  2528. size_t
  2529. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  2530. {
  2531. size_t i;
  2532. if (!ctx) {
  2533. return 0;
  2534. }
  2535. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  2536. ssl[i] = ctx->listening_sockets[i].is_ssl;
  2537. ports[i] =
  2538. #if defined(USE_IPV6)
  2539. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2540. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2541. :
  2542. #endif
  2543. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2544. }
  2545. return i;
  2546. }
  2547. #endif
  2548. int
  2549. mg_get_server_ports(const struct mg_context *ctx,
  2550. int size,
  2551. struct mg_server_ports *ports)
  2552. {
  2553. int i, cnt = 0;
  2554. if (size <= 0) {
  2555. return -1;
  2556. }
  2557. memset(ports, 0, sizeof(*ports) * (size_t)size);
  2558. if (!ctx) {
  2559. return -1;
  2560. }
  2561. if (!ctx->listening_sockets) {
  2562. return -1;
  2563. }
  2564. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  2565. ports[cnt].port =
  2566. #if defined(USE_IPV6)
  2567. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2568. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2569. :
  2570. #endif
  2571. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2572. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  2573. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  2574. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  2575. /* IPv4 */
  2576. ports[cnt].protocol = 1;
  2577. cnt++;
  2578. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  2579. /* IPv6 */
  2580. ports[cnt].protocol = 3;
  2581. cnt++;
  2582. }
  2583. }
  2584. return cnt;
  2585. }
  2586. static void
  2587. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  2588. {
  2589. buf[0] = '\0';
  2590. if (!usa) {
  2591. return;
  2592. }
  2593. if (usa->sa.sa_family == AF_INET) {
  2594. getnameinfo(&usa->sa,
  2595. sizeof(usa->sin),
  2596. buf,
  2597. (unsigned)len,
  2598. NULL,
  2599. 0,
  2600. NI_NUMERICHOST);
  2601. }
  2602. #if defined(USE_IPV6)
  2603. else if (usa->sa.sa_family == AF_INET6) {
  2604. getnameinfo(&usa->sa,
  2605. sizeof(usa->sin6),
  2606. buf,
  2607. (unsigned)len,
  2608. NULL,
  2609. 0,
  2610. NI_NUMERICHOST);
  2611. }
  2612. #endif
  2613. }
  2614. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  2615. * included in all responses other than 100, 101, 5xx. */
  2616. static void
  2617. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  2618. {
  2619. struct tm *tm;
  2620. tm = ((t != NULL) ? gmtime(t) : NULL);
  2621. if (tm != NULL) {
  2622. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  2623. } else {
  2624. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  2625. buf[buf_len - 1] = '\0';
  2626. }
  2627. }
  2628. /* difftime for struct timespec. Return value is in seconds. */
  2629. static double
  2630. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  2631. {
  2632. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  2633. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  2634. }
  2635. /* Print error message to the opened error log stream. */
  2636. void
  2637. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  2638. {
  2639. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  2640. va_list ap;
  2641. struct mg_file fi;
  2642. time_t timestamp;
  2643. va_start(ap, fmt);
  2644. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  2645. va_end(ap);
  2646. buf[sizeof(buf) - 1] = 0;
  2647. if (!conn) {
  2648. puts(buf);
  2649. return;
  2650. }
  2651. /* Do not lock when getting the callback value, here and below.
  2652. * I suppose this is fine, since function cannot disappear in the
  2653. * same way string option can. */
  2654. if ((conn->ctx->callbacks.log_message == NULL)
  2655. || (conn->ctx->callbacks.log_message(conn, buf) == 0)) {
  2656. if (conn->ctx->config[ERROR_LOG_FILE] != NULL) {
  2657. if (mg_fopen(conn,
  2658. conn->ctx->config[ERROR_LOG_FILE],
  2659. MG_FOPEN_MODE_APPEND,
  2660. &fi) == 0) {
  2661. fi.access.fp = NULL;
  2662. }
  2663. } else {
  2664. fi.access.fp = NULL;
  2665. }
  2666. if (fi.access.fp != NULL) {
  2667. flockfile(fi.access.fp);
  2668. timestamp = time(NULL);
  2669. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  2670. fprintf(fi.access.fp,
  2671. "[%010lu] [error] [client %s] ",
  2672. (unsigned long)timestamp,
  2673. src_addr);
  2674. if (conn->request_info.request_method != NULL) {
  2675. fprintf(fi.access.fp,
  2676. "%s %s: ",
  2677. conn->request_info.request_method,
  2678. conn->request_info.request_uri
  2679. ? conn->request_info.request_uri
  2680. : "");
  2681. }
  2682. fprintf(fi.access.fp, "%s", buf);
  2683. fputc('\n', fi.access.fp);
  2684. fflush(fi.access.fp);
  2685. funlockfile(fi.access.fp);
  2686. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  2687. * mg_cry here anyway ;-) */
  2688. }
  2689. }
  2690. }
  2691. /* Return fake connection structure. Used for logging, if connection
  2692. * is not applicable at the moment of logging. */
  2693. static struct mg_connection *
  2694. fc(struct mg_context *ctx)
  2695. {
  2696. static struct mg_connection fake_connection;
  2697. fake_connection.ctx = ctx;
  2698. return &fake_connection;
  2699. }
  2700. const char *
  2701. mg_version(void)
  2702. {
  2703. return CIVETWEB_VERSION;
  2704. }
  2705. const struct mg_request_info *
  2706. mg_get_request_info(const struct mg_connection *conn)
  2707. {
  2708. if (!conn) {
  2709. return NULL;
  2710. }
  2711. #if 1 /* TODO: deal with legacy */
  2712. if (conn->connection_type == 2) {
  2713. static char txt[16];
  2714. sprintf(txt, "%03i", conn->response_info.status_code);
  2715. ((struct mg_connection *)conn)->request_info.local_uri =
  2716. ((struct mg_connection *)conn)->request_info.request_uri =
  2717. txt; /* TODO: not thread safe */
  2718. ((struct mg_connection *)conn)->request_info.num_headers =
  2719. conn->response_info.num_headers;
  2720. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  2721. conn->response_info.http_headers,
  2722. sizeof(conn->response_info.http_headers));
  2723. } else
  2724. #endif
  2725. if (conn->connection_type != 1) {
  2726. return NULL;
  2727. }
  2728. return &conn->request_info;
  2729. }
  2730. const struct mg_response_info *
  2731. mg_get_response_info(const struct mg_connection *conn)
  2732. {
  2733. if (!conn) {
  2734. return NULL;
  2735. }
  2736. if (conn->connection_type != 2) {
  2737. return NULL;
  2738. }
  2739. return &conn->response_info;
  2740. }
  2741. int
  2742. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  2743. {
  2744. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  2745. return -1;
  2746. } else {
  2747. int truncated = 0;
  2748. const struct mg_request_info *ri = &conn->request_info;
  2749. #ifdef __clang__
  2750. #pragma clang diagnostic push
  2751. #pragma clang diagnostic ignored "-Wunreachable-code"
  2752. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  2753. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  2754. * unreachable, but splitting into four different #ifdef clauses here is more
  2755. * complicated.
  2756. */
  2757. #endif
  2758. const char *proto =
  2759. (is_websocket_protocol(conn) ? (ri->is_ssl ? "wss" : "ws")
  2760. : (ri->is_ssl ? "https" : "http"));
  2761. #ifdef __clang__
  2762. #pragma clang diagnostic pop
  2763. #endif
  2764. if (ri->local_uri == NULL) {
  2765. return -1;
  2766. }
  2767. if ((ri->request_uri != NULL)
  2768. && strcmp(ri->local_uri, ri->request_uri)) {
  2769. mg_snprintf(conn,
  2770. &truncated,
  2771. buf,
  2772. buflen,
  2773. "%s://%s",
  2774. proto,
  2775. ri->request_uri);
  2776. if (truncated) {
  2777. return -1;
  2778. }
  2779. return 0;
  2780. } else {
  2781. #if defined(USE_IPV6)
  2782. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  2783. int port = is_ipv6 ? htons(conn->client.lsa.sin6.sin6_port)
  2784. : htons(conn->client.lsa.sin.sin_port);
  2785. #else
  2786. int port = htons(conn->client.lsa.sin.sin_port);
  2787. #endif
  2788. int def_port = ri->is_ssl ? 443 : 80;
  2789. int auth_domain_check_enabled =
  2790. conn->ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  2791. && (!strcmp(conn->ctx->config[ENABLE_AUTH_DOMAIN_CHECK],
  2792. "yes"));
  2793. const char *server_domain =
  2794. conn->ctx->config[AUTHENTICATION_DOMAIN];
  2795. char portstr[16];
  2796. char server_ip[48];
  2797. if (port != def_port) {
  2798. sprintf(portstr, ":%u", (unsigned)port);
  2799. } else {
  2800. portstr[0] = 0;
  2801. }
  2802. if (!auth_domain_check_enabled || !server_domain) {
  2803. sockaddr_to_string(server_ip,
  2804. sizeof(server_ip),
  2805. &conn->client.lsa);
  2806. server_domain = server_ip;
  2807. }
  2808. mg_snprintf(conn,
  2809. &truncated,
  2810. buf,
  2811. buflen,
  2812. "%s://%s%s%s",
  2813. proto,
  2814. server_domain,
  2815. portstr,
  2816. ri->local_uri);
  2817. if (truncated) {
  2818. return -1;
  2819. }
  2820. return 0;
  2821. }
  2822. }
  2823. }
  2824. /* Skip the characters until one of the delimiters characters found.
  2825. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  2826. * Advance pointer to buffer to the next word. Return found 0-terminated
  2827. * word.
  2828. * Delimiters can be quoted with quotechar. */
  2829. static char *
  2830. skip_quoted(char **buf,
  2831. const char *delimiters,
  2832. const char *whitespace,
  2833. char quotechar)
  2834. {
  2835. char *p, *begin_word, *end_word, *end_whitespace;
  2836. begin_word = *buf;
  2837. end_word = begin_word + strcspn(begin_word, delimiters);
  2838. /* Check for quotechar */
  2839. if (end_word > begin_word) {
  2840. p = end_word - 1;
  2841. while (*p == quotechar) {
  2842. /* While the delimiter is quoted, look for the next delimiter.
  2843. */
  2844. /* This happens, e.g., in calls from parse_auth_header,
  2845. * if the user name contains a " character. */
  2846. /* If there is anything beyond end_word, copy it. */
  2847. if (*end_word != '\0') {
  2848. size_t end_off = strcspn(end_word + 1, delimiters);
  2849. memmove(p, end_word, end_off + 1);
  2850. p += end_off; /* p must correspond to end_word - 1 */
  2851. end_word += end_off + 1;
  2852. } else {
  2853. *p = '\0';
  2854. break;
  2855. }
  2856. }
  2857. for (p++; p < end_word; p++) {
  2858. *p = '\0';
  2859. }
  2860. }
  2861. if (*end_word == '\0') {
  2862. *buf = end_word;
  2863. } else {
  2864. #if defined(__GNUC__) || defined(__MINGW32__)
  2865. /* Disable spurious conversion warning for GCC */
  2866. #if GCC_VERSION >= 40500
  2867. #pragma GCC diagnostic push
  2868. #pragma GCC diagnostic ignored "-Wsign-conversion"
  2869. #endif /* GCC_VERSION >= 40500 */
  2870. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  2871. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  2872. #if defined(__GNUC__) || defined(__MINGW32__)
  2873. #if GCC_VERSION >= 40500
  2874. #pragma GCC diagnostic pop
  2875. #endif /* GCC_VERSION >= 40500 */
  2876. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  2877. for (p = end_word; p < end_whitespace; p++) {
  2878. *p = '\0';
  2879. }
  2880. *buf = end_whitespace;
  2881. }
  2882. return begin_word;
  2883. }
  2884. /* Return HTTP header value, or NULL if not found. */
  2885. static const char *
  2886. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  2887. {
  2888. int i;
  2889. for (i = 0; i < num_hdr; i++) {
  2890. if (!mg_strcasecmp(name, hdr[i].name)) {
  2891. return hdr[i].value;
  2892. }
  2893. }
  2894. return NULL;
  2895. }
  2896. #if defined(USE_WEBSOCKET)
  2897. /* Retrieve requested HTTP header multiple values, and return the number of
  2898. * found occurences */
  2899. static int
  2900. get_req_headers(const struct mg_request_info *ri,
  2901. const char *name,
  2902. const char **output,
  2903. int output_max_size)
  2904. {
  2905. int i;
  2906. int cnt = 0;
  2907. if (ri) {
  2908. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  2909. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  2910. output[cnt++] = ri->http_headers[i].value;
  2911. }
  2912. }
  2913. }
  2914. return cnt;
  2915. }
  2916. #endif
  2917. const char *
  2918. mg_get_header(const struct mg_connection *conn, const char *name)
  2919. {
  2920. if (!conn) {
  2921. return NULL;
  2922. }
  2923. if (conn->connection_type == 1) {
  2924. return get_header(conn->request_info.http_headers,
  2925. conn->request_info.num_headers,
  2926. name);
  2927. }
  2928. if (conn->connection_type == 2) {
  2929. return get_header(conn->response_info.http_headers,
  2930. conn->request_info.num_headers,
  2931. name);
  2932. }
  2933. return NULL;
  2934. }
  2935. static const char *
  2936. get_http_version(const struct mg_connection *conn)
  2937. {
  2938. if (!conn) {
  2939. return NULL;
  2940. }
  2941. if (conn->connection_type == 1) {
  2942. return conn->request_info.http_version;
  2943. }
  2944. if (conn->connection_type == 2) {
  2945. return conn->response_info.http_version;
  2946. }
  2947. return NULL;
  2948. }
  2949. /* A helper function for traversing a comma separated list of values.
  2950. * It returns a list pointer shifted to the next value, or NULL if the end
  2951. * of the list found.
  2952. * Value is stored in val vector. If value has form "x=y", then eq_val
  2953. * vector is initialized to point to the "y" part, and val vector length
  2954. * is adjusted to point only to "x". */
  2955. static const char *
  2956. next_option(const char *list, struct vec *val, struct vec *eq_val)
  2957. {
  2958. int end;
  2959. reparse:
  2960. if (val == NULL || list == NULL || *list == '\0') {
  2961. /* End of the list */
  2962. list = NULL;
  2963. } else {
  2964. /* Skip over leading LWS */
  2965. while (*list == ' ' || *list == '\t')
  2966. list++;
  2967. val->ptr = list;
  2968. if ((list = strchr(val->ptr, ',')) != NULL) {
  2969. /* Comma found. Store length and shift the list ptr */
  2970. val->len = ((size_t)(list - val->ptr));
  2971. list++;
  2972. } else {
  2973. /* This value is the last one */
  2974. list = val->ptr + strlen(val->ptr);
  2975. val->len = ((size_t)(list - val->ptr));
  2976. }
  2977. /* Adjust length for trailing LWS */
  2978. end = (int)val->len - 1;
  2979. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  2980. end--;
  2981. val->len = (size_t)(end + 1);
  2982. if (val->len == 0) {
  2983. /* Ignore any empty entries. */
  2984. goto reparse;
  2985. }
  2986. if (eq_val != NULL) {
  2987. /* Value has form "x=y", adjust pointers and lengths
  2988. * so that val points to "x", and eq_val points to "y". */
  2989. eq_val->len = 0;
  2990. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  2991. if (eq_val->ptr != NULL) {
  2992. eq_val->ptr++; /* Skip over '=' character */
  2993. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  2994. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  2995. }
  2996. }
  2997. }
  2998. return list;
  2999. }
  3000. /* A helper function for checking if a comma separated list of values
  3001. * contains
  3002. * the given option (case insensitvely).
  3003. * 'header' can be NULL, in which case false is returned. */
  3004. static int
  3005. header_has_option(const char *header, const char *option)
  3006. {
  3007. struct vec opt_vec;
  3008. struct vec eq_vec;
  3009. /*
  3010. assert(option != NULL);
  3011. assert(option[0] != '\0');
  3012. */
  3013. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3014. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3015. return 1;
  3016. }
  3017. return 0;
  3018. }
  3019. /* Perform case-insensitive match of string against pattern */
  3020. static int
  3021. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  3022. {
  3023. const char *or_str;
  3024. size_t i;
  3025. int j, len, res;
  3026. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  3027. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  3028. return (res > 0) ? res : match_prefix(or_str + 1,
  3029. (size_t)((pattern + pattern_len)
  3030. - (or_str + 1)),
  3031. str);
  3032. }
  3033. for (i = 0, j = 0; (i < pattern_len); i++, j++) {
  3034. if ((pattern[i] == '?') && (str[j] != '\0')) {
  3035. continue;
  3036. } else if (pattern[i] == '$') {
  3037. return (str[j] == '\0') ? j : -1;
  3038. } else if (pattern[i] == '*') {
  3039. i++;
  3040. if (pattern[i] == '*') {
  3041. i++;
  3042. len = (int)strlen(str + j);
  3043. } else {
  3044. len = (int)strcspn(str + j, "/");
  3045. }
  3046. if (i == pattern_len) {
  3047. return j + len;
  3048. }
  3049. do {
  3050. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  3051. } while (res == -1 && len-- > 0);
  3052. return (res == -1) ? -1 : j + res + len;
  3053. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  3054. return -1;
  3055. }
  3056. }
  3057. return j;
  3058. }
  3059. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3060. * This function must tolerate situations when connection info is not
  3061. * set up, for example if request parsing failed. */
  3062. static int
  3063. should_keep_alive(const struct mg_connection *conn)
  3064. {
  3065. const char *http_version;
  3066. const char *header;
  3067. /* First satisfy needs of the server */
  3068. if ((conn == NULL) || conn->must_close) {
  3069. /* Close, if civetweb framework needs to close */
  3070. return 0;
  3071. }
  3072. if (mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3073. /* Close, if keep alive is not enabled */
  3074. return 0;
  3075. }
  3076. /* Check explicit wish of the client */
  3077. header = mg_get_header(conn, "Connection");
  3078. if (header) {
  3079. /* If there is a connection header from the client, obey */
  3080. if (header_has_option(header, "keep-alive")) {
  3081. return 1;
  3082. }
  3083. return 0;
  3084. }
  3085. /* Use default of the standard */
  3086. http_version = get_http_version(conn);
  3087. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3088. /* HTTP 1.1 default is keep alive */
  3089. return 1;
  3090. }
  3091. /* HTTP 1.0 (and earlier) default is to close the connection */
  3092. return 0;
  3093. }
  3094. static int
  3095. should_decode_url(const struct mg_connection *conn)
  3096. {
  3097. if (!conn || !conn->ctx) {
  3098. return 0;
  3099. }
  3100. return (mg_strcasecmp(conn->ctx->config[DECODE_URL], "yes") == 0);
  3101. }
  3102. static const char *
  3103. suggest_connection_header(const struct mg_connection *conn)
  3104. {
  3105. return should_keep_alive(conn) ? "keep-alive" : "close";
  3106. }
  3107. static int
  3108. send_no_cache_header(struct mg_connection *conn)
  3109. {
  3110. /* Send all current and obsolete cache opt-out directives. */
  3111. return mg_printf(conn,
  3112. "Cache-Control: no-cache, no-store, "
  3113. "must-revalidate, private, max-age=0\r\n"
  3114. "Pragma: no-cache\r\n"
  3115. "Expires: 0\r\n");
  3116. }
  3117. static int
  3118. send_static_cache_header(struct mg_connection *conn)
  3119. {
  3120. #if !defined(NO_CACHING)
  3121. /* Read the server config to check how long a file may be cached.
  3122. * The configuration is in seconds. */
  3123. int max_age = atoi(conn->ctx->config[STATIC_FILE_MAX_AGE]);
  3124. if (max_age <= 0) {
  3125. /* 0 means "do not cache". All values <0 are reserved
  3126. * and may be used differently in the future. */
  3127. /* If a file should not be cached, do not only send
  3128. * max-age=0, but also pragmas and Expires headers. */
  3129. return send_no_cache_header(conn);
  3130. }
  3131. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3132. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3133. /* See also https://www.mnot.net/cache_docs/ */
  3134. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3135. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3136. * leap
  3137. * year to 31622400 seconds. For the moment, we just send whatever has
  3138. * been configured, still the behavior for >1 year should be considered
  3139. * as undefined. */
  3140. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  3141. #else /* NO_CACHING */
  3142. return send_no_cache_header(conn);
  3143. #endif /* !NO_CACHING */
  3144. }
  3145. static int
  3146. send_additional_header(struct mg_connection *conn)
  3147. {
  3148. int i = 0;
  3149. const char *header = conn->ctx->config[ADDITIONAL_HEADER];
  3150. #if !defined(NO_SSL)
  3151. if (conn->ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3152. int max_age = atoi(conn->ctx->config[STRICT_HTTPS_MAX_AGE]);
  3153. if (max_age >= 0) {
  3154. i += mg_printf(conn,
  3155. "Strict-Transport-Security: max-age=%u\r\n",
  3156. (unsigned)max_age);
  3157. }
  3158. }
  3159. #endif
  3160. if (header && header[0]) {
  3161. i += mg_printf(conn, "%s\r\n", header);
  3162. }
  3163. return i;
  3164. }
  3165. static void handle_file_based_request(struct mg_connection *conn,
  3166. const char *path,
  3167. struct mg_file *filep);
  3168. const char *
  3169. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3170. {
  3171. /* See IANA HTTP status code assignment:
  3172. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3173. */
  3174. switch (response_code) {
  3175. /* RFC2616 Section 10.1 - Informational 1xx */
  3176. case 100:
  3177. return "Continue"; /* RFC2616 Section 10.1.1 */
  3178. case 101:
  3179. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3180. case 102:
  3181. return "Processing"; /* RFC2518 Section 10.1 */
  3182. /* RFC2616 Section 10.2 - Successful 2xx */
  3183. case 200:
  3184. return "OK"; /* RFC2616 Section 10.2.1 */
  3185. case 201:
  3186. return "Created"; /* RFC2616 Section 10.2.2 */
  3187. case 202:
  3188. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3189. case 203:
  3190. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3191. case 204:
  3192. return "No Content"; /* RFC2616 Section 10.2.5 */
  3193. case 205:
  3194. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3195. case 206:
  3196. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3197. case 207:
  3198. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3199. */
  3200. case 208:
  3201. return "Already Reported"; /* RFC5842 Section 7.1 */
  3202. case 226:
  3203. return "IM used"; /* RFC3229 Section 10.4.1 */
  3204. /* RFC2616 Section 10.3 - Redirection 3xx */
  3205. case 300:
  3206. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3207. case 301:
  3208. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3209. case 302:
  3210. return "Found"; /* RFC2616 Section 10.3.3 */
  3211. case 303:
  3212. return "See Other"; /* RFC2616 Section 10.3.4 */
  3213. case 304:
  3214. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3215. case 305:
  3216. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3217. case 307:
  3218. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3219. case 308:
  3220. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3221. /* RFC2616 Section 10.4 - Client Error 4xx */
  3222. case 400:
  3223. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3224. case 401:
  3225. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3226. case 402:
  3227. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3228. case 403:
  3229. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3230. case 404:
  3231. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3232. case 405:
  3233. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3234. case 406:
  3235. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3236. case 407:
  3237. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3238. case 408:
  3239. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3240. case 409:
  3241. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3242. case 410:
  3243. return "Gone"; /* RFC2616 Section 10.4.11 */
  3244. case 411:
  3245. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3246. case 412:
  3247. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3248. case 413:
  3249. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3250. case 414:
  3251. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3252. case 415:
  3253. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3254. case 416:
  3255. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3256. */
  3257. case 417:
  3258. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3259. case 421:
  3260. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3261. case 422:
  3262. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3263. * Section 11.2 */
  3264. case 423:
  3265. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3266. case 424:
  3267. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3268. * Section 11.4 */
  3269. case 426:
  3270. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3271. case 428:
  3272. return "Precondition Required"; /* RFC 6585, Section 3 */
  3273. case 429:
  3274. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3275. case 431:
  3276. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3277. case 451:
  3278. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3279. * Section 3 */
  3280. /* RFC2616 Section 10.5 - Server Error 5xx */
  3281. case 500:
  3282. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3283. case 501:
  3284. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3285. case 502:
  3286. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3287. case 503:
  3288. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3289. case 504:
  3290. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3291. case 505:
  3292. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3293. case 506:
  3294. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3295. case 507:
  3296. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3297. * Section 11.5 */
  3298. case 508:
  3299. return "Loop Detected"; /* RFC5842 Section 7.1 */
  3300. case 510:
  3301. return "Not Extended"; /* RFC 2774, Section 7 */
  3302. case 511:
  3303. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  3304. /* Other status codes, not shown in the IANA HTTP status code
  3305. * assignment.
  3306. * E.g., "de facto" standards due to common use, ... */
  3307. case 418:
  3308. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  3309. case 419:
  3310. return "Authentication Timeout"; /* common use */
  3311. case 420:
  3312. return "Enhance Your Calm"; /* common use */
  3313. case 440:
  3314. return "Login Timeout"; /* common use */
  3315. case 509:
  3316. return "Bandwidth Limit Exceeded"; /* common use */
  3317. default:
  3318. /* This error code is unknown. This should not happen. */
  3319. if (conn) {
  3320. mg_cry(conn, "Unknown HTTP response code: %u", response_code);
  3321. }
  3322. /* Return at least a category according to RFC 2616 Section 10. */
  3323. if (response_code >= 100 && response_code < 200) {
  3324. /* Unknown informational status code */
  3325. return "Information";
  3326. }
  3327. if (response_code >= 200 && response_code < 300) {
  3328. /* Unknown success code */
  3329. return "Success";
  3330. }
  3331. if (response_code >= 300 && response_code < 400) {
  3332. /* Unknown redirection code */
  3333. return "Redirection";
  3334. }
  3335. if (response_code >= 400 && response_code < 500) {
  3336. /* Unknown request error code */
  3337. return "Client Error";
  3338. }
  3339. if (response_code >= 500 && response_code < 600) {
  3340. /* Unknown server error code */
  3341. return "Server Error";
  3342. }
  3343. /* Response code not even within reasonable range */
  3344. return "";
  3345. }
  3346. }
  3347. void
  3348. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  3349. {
  3350. char buf[MG_BUF_LEN];
  3351. va_list ap;
  3352. int len, i, page_handler_found, scope, truncated, has_body;
  3353. char date[64];
  3354. time_t curtime = time(NULL);
  3355. const char *error_handler = NULL;
  3356. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  3357. const char *error_page_file_ext, *tstr;
  3358. const char *status_text = mg_get_response_code_text(conn, status);
  3359. if (conn == NULL) {
  3360. return;
  3361. }
  3362. conn->status_code = status;
  3363. if (conn->in_error_handler || (conn->ctx->callbacks.http_error == NULL)
  3364. || conn->ctx->callbacks.http_error(conn, status)) {
  3365. if (!conn->in_error_handler) {
  3366. /* Send user defined error pages, if defined */
  3367. error_handler = conn->ctx->config[ERROR_PAGES];
  3368. error_page_file_ext = conn->ctx->config[INDEX_FILES];
  3369. page_handler_found = 0;
  3370. if (error_handler != NULL) {
  3371. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  3372. switch (scope) {
  3373. case 1: /* Handler for specific error, e.g. 404 error */
  3374. mg_snprintf(conn,
  3375. &truncated,
  3376. buf,
  3377. sizeof(buf) - 32,
  3378. "%serror%03u.",
  3379. error_handler,
  3380. status);
  3381. break;
  3382. case 2: /* Handler for error group, e.g., 5xx error
  3383. * handler
  3384. * for all server errors (500-599) */
  3385. mg_snprintf(conn,
  3386. &truncated,
  3387. buf,
  3388. sizeof(buf) - 32,
  3389. "%serror%01uxx.",
  3390. error_handler,
  3391. status / 100);
  3392. break;
  3393. default: /* Handler for all errors */
  3394. mg_snprintf(conn,
  3395. &truncated,
  3396. buf,
  3397. sizeof(buf) - 32,
  3398. "%serror.",
  3399. error_handler);
  3400. break;
  3401. }
  3402. /* String truncation in buf may only occur if
  3403. * error_handler
  3404. * is too long. This string is from the config, not from
  3405. * a
  3406. * client. */
  3407. (void)truncated;
  3408. len = (int)strlen(buf);
  3409. tstr = strchr(error_page_file_ext, '.');
  3410. while (tstr) {
  3411. for (i = 1;
  3412. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  3413. i++)
  3414. buf[len + i - 1] = tstr[i];
  3415. buf[len + i - 1] = 0;
  3416. if (mg_stat(conn, buf, &error_page_file.stat)) {
  3417. page_handler_found = 1;
  3418. break;
  3419. }
  3420. tstr = strchr(tstr + i, '.');
  3421. }
  3422. }
  3423. }
  3424. if (page_handler_found) {
  3425. conn->in_error_handler = 1;
  3426. handle_file_based_request(conn, buf, &error_page_file);
  3427. conn->in_error_handler = 0;
  3428. return;
  3429. }
  3430. }
  3431. /* No custom error page. Send default error page. */
  3432. gmt_time_string(date, sizeof(date), &curtime);
  3433. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3434. has_body = ((status > 199) && (status != 204) && (status != 304));
  3435. conn->must_close = 1;
  3436. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  3437. send_no_cache_header(conn);
  3438. send_additional_header(conn);
  3439. if (has_body) {
  3440. mg_printf(conn,
  3441. "%s",
  3442. "Content-Type: text/plain; charset=utf-8\r\n");
  3443. }
  3444. mg_printf(conn,
  3445. "Date: %s\r\n"
  3446. "Connection: close\r\n\r\n",
  3447. date);
  3448. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3449. if (has_body) {
  3450. mg_printf(conn, "Error %d: %s\n", status, status_text);
  3451. if (fmt != NULL) {
  3452. va_start(ap, fmt);
  3453. mg_vsnprintf(conn, NULL, buf, sizeof(buf), fmt, ap);
  3454. va_end(ap);
  3455. mg_write(conn, buf, strlen(buf));
  3456. DEBUG_TRACE("Error %i - [%s]", status, buf);
  3457. }
  3458. } else {
  3459. /* No body allowed. Close the connection. */
  3460. DEBUG_TRACE("Error %i", status);
  3461. }
  3462. }
  3463. }
  3464. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  3465. /* Create substitutes for POSIX functions in Win32. */
  3466. #if defined(__MINGW32__)
  3467. /* Show no warning in case system functions are not used. */
  3468. #pragma GCC diagnostic push
  3469. #pragma GCC diagnostic ignored "-Wunused-function"
  3470. #endif
  3471. FUNCTION_MAY_BE_UNUSED
  3472. static int
  3473. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  3474. {
  3475. (void)unused;
  3476. *mutex = CreateMutex(NULL, FALSE, NULL);
  3477. return (*mutex == NULL) ? -1 : 0;
  3478. }
  3479. FUNCTION_MAY_BE_UNUSED
  3480. static int
  3481. pthread_mutex_destroy(pthread_mutex_t *mutex)
  3482. {
  3483. return (CloseHandle(*mutex) == 0) ? -1 : 0;
  3484. }
  3485. FUNCTION_MAY_BE_UNUSED
  3486. static int
  3487. pthread_mutex_lock(pthread_mutex_t *mutex)
  3488. {
  3489. return (WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0) ? 0 : -1;
  3490. }
  3491. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  3492. FUNCTION_MAY_BE_UNUSED
  3493. static int
  3494. pthread_mutex_trylock(pthread_mutex_t *mutex)
  3495. {
  3496. switch (WaitForSingleObject(*mutex, 0)) {
  3497. case WAIT_OBJECT_0:
  3498. return 0;
  3499. case WAIT_TIMEOUT:
  3500. return -2; /* EBUSY */
  3501. }
  3502. return -1;
  3503. }
  3504. #endif
  3505. FUNCTION_MAY_BE_UNUSED
  3506. static int
  3507. pthread_mutex_unlock(pthread_mutex_t *mutex)
  3508. {
  3509. return (ReleaseMutex(*mutex) == 0) ? -1 : 0;
  3510. }
  3511. FUNCTION_MAY_BE_UNUSED
  3512. static int
  3513. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  3514. {
  3515. (void)unused;
  3516. InitializeCriticalSection(&cv->threadIdSec);
  3517. cv->waiting_thread = NULL;
  3518. return 0;
  3519. }
  3520. FUNCTION_MAY_BE_UNUSED
  3521. static int
  3522. pthread_cond_timedwait(pthread_cond_t *cv,
  3523. pthread_mutex_t *mutex,
  3524. const struct timespec *abstime)
  3525. {
  3526. struct mg_workerTLS **ptls,
  3527. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3528. int ok;
  3529. int64_t nsnow, nswaitabs, nswaitrel;
  3530. DWORD mswaitrel;
  3531. EnterCriticalSection(&cv->threadIdSec);
  3532. /* Add this thread to cv's waiting list */
  3533. ptls = &cv->waiting_thread;
  3534. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  3535. ;
  3536. tls->next_waiting_thread = NULL;
  3537. *ptls = tls;
  3538. LeaveCriticalSection(&cv->threadIdSec);
  3539. if (abstime) {
  3540. nsnow = mg_get_current_time_ns();
  3541. nswaitabs =
  3542. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  3543. nswaitrel = nswaitabs - nsnow;
  3544. if (nswaitrel < 0) {
  3545. nswaitrel = 0;
  3546. }
  3547. mswaitrel = (DWORD)(nswaitrel / 1000000);
  3548. } else {
  3549. mswaitrel = INFINITE;
  3550. }
  3551. pthread_mutex_unlock(mutex);
  3552. ok = (WAIT_OBJECT_0
  3553. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  3554. if (!ok) {
  3555. ok = 1;
  3556. EnterCriticalSection(&cv->threadIdSec);
  3557. ptls = &cv->waiting_thread;
  3558. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  3559. if (*ptls == tls) {
  3560. *ptls = tls->next_waiting_thread;
  3561. ok = 0;
  3562. break;
  3563. }
  3564. }
  3565. LeaveCriticalSection(&cv->threadIdSec);
  3566. if (ok) {
  3567. WaitForSingleObject(tls->pthread_cond_helper_mutex, INFINITE);
  3568. }
  3569. }
  3570. /* This thread has been removed from cv's waiting list */
  3571. pthread_mutex_lock(mutex);
  3572. return ok ? 0 : -1;
  3573. }
  3574. FUNCTION_MAY_BE_UNUSED
  3575. static int
  3576. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  3577. {
  3578. return pthread_cond_timedwait(cv, mutex, NULL);
  3579. }
  3580. FUNCTION_MAY_BE_UNUSED
  3581. static int
  3582. pthread_cond_signal(pthread_cond_t *cv)
  3583. {
  3584. HANDLE wkup = NULL;
  3585. BOOL ok = FALSE;
  3586. EnterCriticalSection(&cv->threadIdSec);
  3587. if (cv->waiting_thread) {
  3588. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  3589. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  3590. ok = SetEvent(wkup);
  3591. assert(ok);
  3592. }
  3593. LeaveCriticalSection(&cv->threadIdSec);
  3594. return ok ? 0 : 1;
  3595. }
  3596. FUNCTION_MAY_BE_UNUSED
  3597. static int
  3598. pthread_cond_broadcast(pthread_cond_t *cv)
  3599. {
  3600. EnterCriticalSection(&cv->threadIdSec);
  3601. while (cv->waiting_thread) {
  3602. pthread_cond_signal(cv);
  3603. }
  3604. LeaveCriticalSection(&cv->threadIdSec);
  3605. return 0;
  3606. }
  3607. FUNCTION_MAY_BE_UNUSED
  3608. static int
  3609. pthread_cond_destroy(pthread_cond_t *cv)
  3610. {
  3611. EnterCriticalSection(&cv->threadIdSec);
  3612. assert(cv->waiting_thread == NULL);
  3613. LeaveCriticalSection(&cv->threadIdSec);
  3614. DeleteCriticalSection(&cv->threadIdSec);
  3615. return 0;
  3616. }
  3617. #ifdef ALTERNATIVE_QUEUE
  3618. FUNCTION_MAY_BE_UNUSED
  3619. static void *
  3620. event_create(void)
  3621. {
  3622. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  3623. }
  3624. FUNCTION_MAY_BE_UNUSED
  3625. static int
  3626. event_wait(void *eventhdl)
  3627. {
  3628. int res = WaitForSingleObject((HANDLE)eventhdl, INFINITE);
  3629. return (res == WAIT_OBJECT_0);
  3630. }
  3631. FUNCTION_MAY_BE_UNUSED
  3632. static int
  3633. event_signal(void *eventhdl)
  3634. {
  3635. return (int)SetEvent((HANDLE)eventhdl);
  3636. }
  3637. FUNCTION_MAY_BE_UNUSED
  3638. static void
  3639. event_destroy(void *eventhdl)
  3640. {
  3641. CloseHandle((HANDLE)eventhdl);
  3642. }
  3643. #endif
  3644. #if defined(__MINGW32__)
  3645. /* Enable unused function warning again */
  3646. #pragma GCC diagnostic pop
  3647. #endif
  3648. /* For Windows, change all slashes to backslashes in path names. */
  3649. static void
  3650. change_slashes_to_backslashes(char *path)
  3651. {
  3652. int i;
  3653. for (i = 0; path[i] != '\0'; i++) {
  3654. if (path[i] == '/') {
  3655. path[i] = '\\';
  3656. }
  3657. /* remove double backslash (check i > 0 to preserve UNC paths,
  3658. * like \\server\file.txt) */
  3659. if ((path[i] == '\\') && (i > 0)) {
  3660. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  3661. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  3662. }
  3663. }
  3664. }
  3665. }
  3666. static int
  3667. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  3668. {
  3669. int diff;
  3670. do {
  3671. diff = tolower(*s1) - tolower(*s2);
  3672. s1++;
  3673. s2++;
  3674. } while ((diff == 0) && (s1[-1] != '\0'));
  3675. return diff;
  3676. }
  3677. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  3678. * wbuf and wbuf_len is a target buffer and its length. */
  3679. static void
  3680. path_to_unicode(const struct mg_connection *conn,
  3681. const char *path,
  3682. wchar_t *wbuf,
  3683. size_t wbuf_len)
  3684. {
  3685. char buf[PATH_MAX], buf2[PATH_MAX];
  3686. wchar_t wbuf2[MAX_PATH + 1];
  3687. DWORD long_len, err;
  3688. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  3689. mg_strlcpy(buf, path, sizeof(buf));
  3690. change_slashes_to_backslashes(buf);
  3691. /* Convert to Unicode and back. If doubly-converted string does not
  3692. * match the original, something is fishy, reject. */
  3693. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  3694. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  3695. WideCharToMultiByte(
  3696. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  3697. if (strcmp(buf, buf2) != 0) {
  3698. wbuf[0] = L'\0';
  3699. }
  3700. /* Windows file systems are not case sensitive, but you can still use
  3701. * uppercase and lowercase letters (on all modern file systems).
  3702. * The server can check if the URI uses the same upper/lowercase
  3703. * letters an the file system, effectively making Windows servers
  3704. * case sensitive (like Linux servers are). It is still not possible
  3705. * to use two files with the same name in different cases on Windows
  3706. * (like /a and /A) - this would be possible in Linux.
  3707. * As a default, Windows is not case sensitive, but the case sensitive
  3708. * file name check can be activated by an additional configuration. */
  3709. if (conn) {
  3710. if (conn->ctx->config[CASE_SENSITIVE_FILES]
  3711. && !mg_strcasecmp(conn->ctx->config[CASE_SENSITIVE_FILES], "yes")) {
  3712. /* Use case sensitive compare function */
  3713. fcompare = wcscmp;
  3714. }
  3715. }
  3716. (void)conn; /* conn is currently unused */
  3717. #if !defined(_WIN32_WCE)
  3718. /* Only accept a full file path, not a Windows short (8.3) path. */
  3719. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  3720. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  3721. if (long_len == 0) {
  3722. err = GetLastError();
  3723. if (err == ERROR_FILE_NOT_FOUND) {
  3724. /* File does not exist. This is not always a problem here. */
  3725. return;
  3726. }
  3727. }
  3728. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  3729. /* Short name is used. */
  3730. wbuf[0] = L'\0';
  3731. }
  3732. #else
  3733. (void)long_len;
  3734. (void)wbuf2;
  3735. (void)err;
  3736. if (strchr(path, '~')) {
  3737. wbuf[0] = L'\0';
  3738. }
  3739. #endif
  3740. }
  3741. /* Windows happily opens files with some garbage at the end of file name.
  3742. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  3743. * "a.cgi", despite one would expect an error back.
  3744. * This function returns non-0 if path ends with some garbage. */
  3745. static int
  3746. path_cannot_disclose_cgi(const char *path)
  3747. {
  3748. static const char *allowed_last_characters = "_-";
  3749. int last = path[strlen(path) - 1];
  3750. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  3751. }
  3752. static int
  3753. mg_stat(const struct mg_connection *conn,
  3754. const char *path,
  3755. struct mg_file_stat *filep)
  3756. {
  3757. wchar_t wbuf[PATH_MAX];
  3758. WIN32_FILE_ATTRIBUTE_DATA info;
  3759. time_t creation_time;
  3760. if (!filep) {
  3761. return 0;
  3762. }
  3763. memset(filep, 0, sizeof(*filep));
  3764. if (conn && is_file_in_memory(conn, path)) {
  3765. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  3766. * memset */
  3767. /* Quick fix (for 1.9.x): */
  3768. /* mg_stat must fill all fields, also for files in memory */
  3769. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  3770. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  3771. filep->size = tmp_file.stat.size;
  3772. filep->location = 2;
  3773. /* TODO: for 1.10: restructure how files in memory are handled */
  3774. /* The "file in memory" feature is a candidate for deletion.
  3775. * Please join the discussion at
  3776. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  3777. */
  3778. filep->last_modified = time(NULL); /* TODO */
  3779. /* last_modified = now ... assumes the file may change during
  3780. * runtime,
  3781. * so every mg_fopen call may return different data */
  3782. /* last_modified = conn->ctx.start_time;
  3783. * May be used it the data does not change during runtime. This
  3784. * allows
  3785. * browser caching. Since we do not know, we have to assume the file
  3786. * in memory may change. */
  3787. return 1;
  3788. }
  3789. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3790. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  3791. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  3792. filep->last_modified =
  3793. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  3794. info.ftLastWriteTime.dwHighDateTime);
  3795. /* On Windows, the file creation time can be higher than the
  3796. * modification time, e.g. when a file is copied.
  3797. * Since the Last-Modified timestamp is used for caching
  3798. * it should be based on the most recent timestamp. */
  3799. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  3800. info.ftCreationTime.dwHighDateTime);
  3801. if (creation_time > filep->last_modified) {
  3802. filep->last_modified = creation_time;
  3803. }
  3804. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  3805. /* If file name is fishy, reset the file structure and return
  3806. * error.
  3807. * Note it is important to reset, not just return the error, cause
  3808. * functions like is_file_opened() check the struct. */
  3809. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  3810. memset(filep, 0, sizeof(*filep));
  3811. return 0;
  3812. }
  3813. return 1;
  3814. }
  3815. return 0;
  3816. }
  3817. static int
  3818. mg_remove(const struct mg_connection *conn, const char *path)
  3819. {
  3820. wchar_t wbuf[PATH_MAX];
  3821. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3822. return DeleteFileW(wbuf) ? 0 : -1;
  3823. }
  3824. static int
  3825. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  3826. {
  3827. wchar_t wbuf[PATH_MAX];
  3828. (void)mode;
  3829. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3830. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  3831. }
  3832. /* Create substitutes for POSIX functions in Win32. */
  3833. #if defined(__MINGW32__)
  3834. /* Show no warning in case system functions are not used. */
  3835. #pragma GCC diagnostic push
  3836. #pragma GCC diagnostic ignored "-Wunused-function"
  3837. #endif
  3838. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  3839. FUNCTION_MAY_BE_UNUSED
  3840. static DIR *
  3841. mg_opendir(const struct mg_connection *conn, const char *name)
  3842. {
  3843. DIR *dir = NULL;
  3844. wchar_t wpath[PATH_MAX];
  3845. DWORD attrs;
  3846. if (name == NULL) {
  3847. SetLastError(ERROR_BAD_ARGUMENTS);
  3848. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  3849. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  3850. } else {
  3851. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  3852. attrs = GetFileAttributesW(wpath);
  3853. if (attrs != 0xFFFFFFFF && ((attrs & FILE_ATTRIBUTE_DIRECTORY)
  3854. == FILE_ATTRIBUTE_DIRECTORY)) {
  3855. (void)wcscat(wpath, L"\\*");
  3856. dir->handle = FindFirstFileW(wpath, &dir->info);
  3857. dir->result.d_name[0] = '\0';
  3858. } else {
  3859. mg_free(dir);
  3860. dir = NULL;
  3861. }
  3862. }
  3863. return dir;
  3864. }
  3865. FUNCTION_MAY_BE_UNUSED
  3866. static int
  3867. mg_closedir(DIR *dir)
  3868. {
  3869. int result = 0;
  3870. if (dir != NULL) {
  3871. if (dir->handle != INVALID_HANDLE_VALUE)
  3872. result = FindClose(dir->handle) ? 0 : -1;
  3873. mg_free(dir);
  3874. } else {
  3875. result = -1;
  3876. SetLastError(ERROR_BAD_ARGUMENTS);
  3877. }
  3878. return result;
  3879. }
  3880. FUNCTION_MAY_BE_UNUSED
  3881. static struct dirent *
  3882. mg_readdir(DIR *dir)
  3883. {
  3884. struct dirent *result = 0;
  3885. if (dir) {
  3886. if (dir->handle != INVALID_HANDLE_VALUE) {
  3887. result = &dir->result;
  3888. (void)WideCharToMultiByte(CP_UTF8,
  3889. 0,
  3890. dir->info.cFileName,
  3891. -1,
  3892. result->d_name,
  3893. sizeof(result->d_name),
  3894. NULL,
  3895. NULL);
  3896. if (!FindNextFileW(dir->handle, &dir->info)) {
  3897. (void)FindClose(dir->handle);
  3898. dir->handle = INVALID_HANDLE_VALUE;
  3899. }
  3900. } else {
  3901. SetLastError(ERROR_FILE_NOT_FOUND);
  3902. }
  3903. } else {
  3904. SetLastError(ERROR_BAD_ARGUMENTS);
  3905. }
  3906. return result;
  3907. }
  3908. #ifndef HAVE_POLL
  3909. FUNCTION_MAY_BE_UNUSED
  3910. static int
  3911. poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  3912. {
  3913. struct timeval tv;
  3914. fd_set set;
  3915. unsigned int i;
  3916. int result;
  3917. SOCKET maxfd = 0;
  3918. memset(&tv, 0, sizeof(tv));
  3919. tv.tv_sec = milliseconds / 1000;
  3920. tv.tv_usec = (milliseconds % 1000) * 1000;
  3921. FD_ZERO(&set);
  3922. for (i = 0; i < n; i++) {
  3923. FD_SET((SOCKET)pfd[i].fd, &set);
  3924. pfd[i].revents = 0;
  3925. if (pfd[i].fd > maxfd) {
  3926. maxfd = pfd[i].fd;
  3927. }
  3928. }
  3929. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  3930. for (i = 0; i < n; i++) {
  3931. if (FD_ISSET(pfd[i].fd, &set)) {
  3932. pfd[i].revents = POLLIN;
  3933. }
  3934. }
  3935. }
  3936. /* We should subtract the time used in select from remaining
  3937. * "milliseconds", in particular if called from mg_poll with a
  3938. * timeout quantum.
  3939. * Unfortunately, the remaining time is not stored in "tv" in all
  3940. * implementations, so the result in "tv" must be considered undefined.
  3941. * See http://man7.org/linux/man-pages/man2/select.2.html */
  3942. return result;
  3943. }
  3944. #endif /* HAVE_POLL */
  3945. #if defined(__MINGW32__)
  3946. /* Enable unused function warning again */
  3947. #pragma GCC diagnostic pop
  3948. #endif
  3949. static void
  3950. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  3951. {
  3952. (void)conn; /* Unused. */
  3953. #if defined(_WIN32_WCE)
  3954. (void)sock;
  3955. #else
  3956. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  3957. #endif
  3958. }
  3959. int
  3960. mg_start_thread(mg_thread_func_t f, void *p)
  3961. {
  3962. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3963. /* Compile-time option to control stack size, e.g.
  3964. * -DUSE_STACK_SIZE=16384
  3965. */
  3966. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  3967. == ((uintptr_t)(-1L)))
  3968. ? -1
  3969. : 0);
  3970. #else
  3971. return (
  3972. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  3973. ? -1
  3974. : 0);
  3975. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3976. }
  3977. /* Start a thread storing the thread context. */
  3978. static int
  3979. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  3980. void *p,
  3981. pthread_t *threadidptr)
  3982. {
  3983. uintptr_t uip;
  3984. HANDLE threadhandle;
  3985. int result = -1;
  3986. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  3987. threadhandle = (HANDLE)uip;
  3988. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  3989. *threadidptr = threadhandle;
  3990. result = 0;
  3991. }
  3992. return result;
  3993. }
  3994. /* Wait for a thread to finish. */
  3995. static int
  3996. mg_join_thread(pthread_t threadid)
  3997. {
  3998. int result;
  3999. DWORD dwevent;
  4000. result = -1;
  4001. dwevent = WaitForSingleObject(threadid, INFINITE);
  4002. if (dwevent == WAIT_FAILED) {
  4003. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4004. } else {
  4005. if (dwevent == WAIT_OBJECT_0) {
  4006. CloseHandle(threadid);
  4007. result = 0;
  4008. }
  4009. }
  4010. return result;
  4011. }
  4012. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4013. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4014. /* Create substitutes for POSIX functions in Win32. */
  4015. #if defined(__MINGW32__)
  4016. /* Show no warning in case system functions are not used. */
  4017. #pragma GCC diagnostic push
  4018. #pragma GCC diagnostic ignored "-Wunused-function"
  4019. #endif
  4020. FUNCTION_MAY_BE_UNUSED
  4021. static HANDLE
  4022. dlopen(const char *dll_name, int flags)
  4023. {
  4024. wchar_t wbuf[PATH_MAX];
  4025. (void)flags;
  4026. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4027. return LoadLibraryW(wbuf);
  4028. }
  4029. FUNCTION_MAY_BE_UNUSED
  4030. static int
  4031. dlclose(void *handle)
  4032. {
  4033. int result;
  4034. if (FreeLibrary((HMODULE)handle) != 0) {
  4035. result = 0;
  4036. } else {
  4037. result = -1;
  4038. }
  4039. return result;
  4040. }
  4041. #if defined(__MINGW32__)
  4042. /* Enable unused function warning again */
  4043. #pragma GCC diagnostic pop
  4044. #endif
  4045. #endif
  4046. #if !defined(NO_CGI)
  4047. #define SIGKILL (0)
  4048. static int
  4049. kill(pid_t pid, int sig_num)
  4050. {
  4051. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4052. (void)CloseHandle((HANDLE)pid);
  4053. return 0;
  4054. }
  4055. static void
  4056. trim_trailing_whitespaces(char *s)
  4057. {
  4058. char *e = s + strlen(s) - 1;
  4059. while ((e > s) && isspace(*(unsigned char *)e)) {
  4060. *e-- = '\0';
  4061. }
  4062. }
  4063. static pid_t
  4064. spawn_process(struct mg_connection *conn,
  4065. const char *prog,
  4066. char *envblk,
  4067. char *envp[],
  4068. int fdin[2],
  4069. int fdout[2],
  4070. int fderr[2],
  4071. const char *dir)
  4072. {
  4073. HANDLE me;
  4074. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  4075. cmdline[PATH_MAX], buf[PATH_MAX];
  4076. int truncated;
  4077. struct mg_file file = STRUCT_FILE_INITIALIZER;
  4078. STARTUPINFOA si;
  4079. PROCESS_INFORMATION pi = {0};
  4080. (void)envp;
  4081. memset(&si, 0, sizeof(si));
  4082. si.cb = sizeof(si);
  4083. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  4084. si.wShowWindow = SW_HIDE;
  4085. me = GetCurrentProcess();
  4086. DuplicateHandle(me,
  4087. (HANDLE)_get_osfhandle(fdin[0]),
  4088. me,
  4089. &si.hStdInput,
  4090. 0,
  4091. TRUE,
  4092. DUPLICATE_SAME_ACCESS);
  4093. DuplicateHandle(me,
  4094. (HANDLE)_get_osfhandle(fdout[1]),
  4095. me,
  4096. &si.hStdOutput,
  4097. 0,
  4098. TRUE,
  4099. DUPLICATE_SAME_ACCESS);
  4100. DuplicateHandle(me,
  4101. (HANDLE)_get_osfhandle(fderr[1]),
  4102. me,
  4103. &si.hStdError,
  4104. 0,
  4105. TRUE,
  4106. DUPLICATE_SAME_ACCESS);
  4107. /* Mark handles that should not be inherited. See
  4108. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  4109. */
  4110. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  4111. HANDLE_FLAG_INHERIT,
  4112. 0);
  4113. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  4114. HANDLE_FLAG_INHERIT,
  4115. 0);
  4116. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  4117. HANDLE_FLAG_INHERIT,
  4118. 0);
  4119. /* If CGI file is a script, try to read the interpreter line */
  4120. interp = conn->ctx->config[CGI_INTERPRETER];
  4121. if (interp == NULL) {
  4122. buf[0] = buf[1] = '\0';
  4123. /* Read the first line of the script into the buffer */
  4124. mg_snprintf(
  4125. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  4126. if (truncated) {
  4127. pi.hProcess = (pid_t)-1;
  4128. goto spawn_cleanup;
  4129. }
  4130. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  4131. p = (char *)file.access.membuf;
  4132. mg_fgets(buf, sizeof(buf), &file, &p);
  4133. (void)mg_fclose(&file.access); /* ignore error on read only file */
  4134. buf[sizeof(buf) - 1] = '\0';
  4135. }
  4136. if ((buf[0] == '#') && (buf[1] == '!')) {
  4137. trim_trailing_whitespaces(buf + 2);
  4138. } else {
  4139. buf[2] = '\0';
  4140. }
  4141. interp = buf + 2;
  4142. }
  4143. if (interp[0] != '\0') {
  4144. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  4145. interp = full_interp;
  4146. }
  4147. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  4148. if (interp[0] != '\0') {
  4149. mg_snprintf(conn,
  4150. &truncated,
  4151. cmdline,
  4152. sizeof(cmdline),
  4153. "\"%s\" \"%s\\%s\"",
  4154. interp,
  4155. full_dir,
  4156. prog);
  4157. } else {
  4158. mg_snprintf(conn,
  4159. &truncated,
  4160. cmdline,
  4161. sizeof(cmdline),
  4162. "\"%s\\%s\"",
  4163. full_dir,
  4164. prog);
  4165. }
  4166. if (truncated) {
  4167. pi.hProcess = (pid_t)-1;
  4168. goto spawn_cleanup;
  4169. }
  4170. DEBUG_TRACE("Running [%s]", cmdline);
  4171. if (CreateProcessA(NULL,
  4172. cmdline,
  4173. NULL,
  4174. NULL,
  4175. TRUE,
  4176. CREATE_NEW_PROCESS_GROUP,
  4177. envblk,
  4178. NULL,
  4179. &si,
  4180. &pi) == 0) {
  4181. mg_cry(
  4182. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  4183. pi.hProcess = (pid_t)-1;
  4184. /* goto spawn_cleanup; */
  4185. }
  4186. spawn_cleanup:
  4187. (void)CloseHandle(si.hStdOutput);
  4188. (void)CloseHandle(si.hStdError);
  4189. (void)CloseHandle(si.hStdInput);
  4190. if (pi.hThread != NULL) {
  4191. (void)CloseHandle(pi.hThread);
  4192. }
  4193. return (pid_t)pi.hProcess;
  4194. }
  4195. #endif /* !NO_CGI */
  4196. static int
  4197. set_blocking_mode(SOCKET sock, int blocking)
  4198. {
  4199. unsigned long non_blocking = !blocking;
  4200. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4201. }
  4202. #else
  4203. static int
  4204. mg_stat(const struct mg_connection *conn,
  4205. const char *path,
  4206. struct mg_file_stat *filep)
  4207. {
  4208. struct stat st;
  4209. if (!filep) {
  4210. return 0;
  4211. }
  4212. memset(filep, 0, sizeof(*filep));
  4213. if (conn && is_file_in_memory(conn, path)) {
  4214. /* Quick fix (for 1.9.x): */
  4215. /* mg_stat must fill all fields, also for files in memory */
  4216. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4217. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4218. filep->size = tmp_file.stat.size;
  4219. filep->last_modified = time(NULL);
  4220. filep->location = 2;
  4221. /* TODO: for 1.10: restructure how files in memory are handled */
  4222. return 1;
  4223. }
  4224. if (0 == stat(path, &st)) {
  4225. filep->size = (uint64_t)(st.st_size);
  4226. filep->last_modified = st.st_mtime;
  4227. filep->is_directory = S_ISDIR(st.st_mode);
  4228. return 1;
  4229. }
  4230. return 0;
  4231. }
  4232. static void
  4233. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  4234. {
  4235. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  4236. if (conn) {
  4237. mg_cry(conn,
  4238. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  4239. __func__,
  4240. strerror(ERRNO));
  4241. }
  4242. }
  4243. }
  4244. int
  4245. mg_start_thread(mg_thread_func_t func, void *param)
  4246. {
  4247. pthread_t thread_id;
  4248. pthread_attr_t attr;
  4249. int result;
  4250. (void)pthread_attr_init(&attr);
  4251. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  4252. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4253. /* Compile-time option to control stack size,
  4254. * e.g. -DUSE_STACK_SIZE=16384 */
  4255. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4256. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4257. result = pthread_create(&thread_id, &attr, func, param);
  4258. pthread_attr_destroy(&attr);
  4259. return result;
  4260. }
  4261. /* Start a thread storing the thread context. */
  4262. static int
  4263. mg_start_thread_with_id(mg_thread_func_t func,
  4264. void *param,
  4265. pthread_t *threadidptr)
  4266. {
  4267. pthread_t thread_id;
  4268. pthread_attr_t attr;
  4269. int result;
  4270. (void)pthread_attr_init(&attr);
  4271. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4272. /* Compile-time option to control stack size,
  4273. * e.g. -DUSE_STACK_SIZE=16384 */
  4274. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4275. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  4276. result = pthread_create(&thread_id, &attr, func, param);
  4277. pthread_attr_destroy(&attr);
  4278. if ((result == 0) && (threadidptr != NULL)) {
  4279. *threadidptr = thread_id;
  4280. }
  4281. return result;
  4282. }
  4283. /* Wait for a thread to finish. */
  4284. static int
  4285. mg_join_thread(pthread_t threadid)
  4286. {
  4287. int result;
  4288. result = pthread_join(threadid, NULL);
  4289. return result;
  4290. }
  4291. #ifndef NO_CGI
  4292. static pid_t
  4293. spawn_process(struct mg_connection *conn,
  4294. const char *prog,
  4295. char *envblk,
  4296. char *envp[],
  4297. int fdin[2],
  4298. int fdout[2],
  4299. int fderr[2],
  4300. const char *dir)
  4301. {
  4302. pid_t pid;
  4303. const char *interp;
  4304. (void)envblk;
  4305. if (conn == NULL) {
  4306. return 0;
  4307. }
  4308. if ((pid = fork()) == -1) {
  4309. /* Parent */
  4310. mg_send_http_error(conn,
  4311. 500,
  4312. "Error: Creating CGI process\nfork(): %s",
  4313. strerror(ERRNO));
  4314. } else if (pid == 0) {
  4315. /* Child */
  4316. if (chdir(dir) != 0) {
  4317. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  4318. } else if (dup2(fdin[0], 0) == -1) {
  4319. mg_cry(conn,
  4320. "%s: dup2(%d, 0): %s",
  4321. __func__,
  4322. fdin[0],
  4323. strerror(ERRNO));
  4324. } else if (dup2(fdout[1], 1) == -1) {
  4325. mg_cry(conn,
  4326. "%s: dup2(%d, 1): %s",
  4327. __func__,
  4328. fdout[1],
  4329. strerror(ERRNO));
  4330. } else if (dup2(fderr[1], 2) == -1) {
  4331. mg_cry(conn,
  4332. "%s: dup2(%d, 2): %s",
  4333. __func__,
  4334. fderr[1],
  4335. strerror(ERRNO));
  4336. } else {
  4337. /* Keep stderr and stdout in two different pipes.
  4338. * Stdout will be sent back to the client,
  4339. * stderr should go into a server error log. */
  4340. (void)close(fdin[0]);
  4341. (void)close(fdout[1]);
  4342. (void)close(fderr[1]);
  4343. /* Close write end fdin and read end fdout and fderr */
  4344. (void)close(fdin[1]);
  4345. (void)close(fdout[0]);
  4346. (void)close(fderr[0]);
  4347. /* After exec, all signal handlers are restored to their default
  4348. * values, with one exception of SIGCHLD. According to
  4349. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler will
  4350. * leave unchanged after exec if it was set to be ignored. Restore
  4351. * it to default action. */
  4352. signal(SIGCHLD, SIG_DFL);
  4353. interp = conn->ctx->config[CGI_INTERPRETER];
  4354. if (interp == NULL) {
  4355. (void)execle(prog, prog, NULL, envp);
  4356. mg_cry(conn,
  4357. "%s: execle(%s): %s",
  4358. __func__,
  4359. prog,
  4360. strerror(ERRNO));
  4361. } else {
  4362. (void)execle(interp, interp, prog, NULL, envp);
  4363. mg_cry(conn,
  4364. "%s: execle(%s %s): %s",
  4365. __func__,
  4366. interp,
  4367. prog,
  4368. strerror(ERRNO));
  4369. }
  4370. }
  4371. exit(EXIT_FAILURE);
  4372. }
  4373. return pid;
  4374. }
  4375. #endif /* !NO_CGI */
  4376. static int
  4377. set_blocking_mode(SOCKET sock, int blocking)
  4378. {
  4379. int flags;
  4380. flags = fcntl(sock, F_GETFL, 0);
  4381. if (blocking) {
  4382. (void)fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  4383. } else {
  4384. (void)fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK)));
  4385. }
  4386. return 0;
  4387. }
  4388. #endif /* _WIN32 */
  4389. /* End of initial operating system specific define block. */
  4390. /* Get a random number (independent of C rand function) */
  4391. static uint64_t
  4392. get_random(void)
  4393. {
  4394. static uint64_t lfsr = 0; /* Linear feedback shift register */
  4395. static uint64_t lcg = 0; /* Linear congruential generator */
  4396. uint64_t now = mg_get_current_time_ns();
  4397. if (lfsr == 0) {
  4398. /* lfsr will be only 0 if has not been initialized,
  4399. * so this code is called only once. */
  4400. lfsr = mg_get_current_time_ns();
  4401. lcg = mg_get_current_time_ns();
  4402. } else {
  4403. /* Get the next step of both random number generators. */
  4404. lfsr = (lfsr >> 1)
  4405. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  4406. << 63);
  4407. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  4408. }
  4409. /* Combining two pseudo-random number generators and a high resolution
  4410. * part
  4411. * of the current server time will make it hard (impossible?) to guess
  4412. * the
  4413. * next number. */
  4414. return (lfsr ^ lcg ^ now);
  4415. }
  4416. static int
  4417. mg_poll(struct pollfd *pfd,
  4418. unsigned int n,
  4419. int milliseconds,
  4420. volatile int *stop_server)
  4421. {
  4422. int ms_now, result;
  4423. /* Call poll, but only for a maximum time of a few seconds.
  4424. * This will allow to stop the server after some seconds, instead
  4425. * of having to wait for a long socket timeout. */
  4426. ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  4427. do {
  4428. if (*stop_server) {
  4429. /* Shut down signal */
  4430. return -2;
  4431. }
  4432. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  4433. ms_now = milliseconds;
  4434. }
  4435. result = poll(pfd, n, ms_now);
  4436. if (result != 0) {
  4437. /* Poll returned either success (1) or error (-1).
  4438. * Forward both to the caller. */
  4439. return result;
  4440. }
  4441. /* Poll returned timeout (0). */
  4442. if (milliseconds > 0) {
  4443. milliseconds -= ms_now;
  4444. }
  4445. } while (milliseconds != 0);
  4446. return result;
  4447. }
  4448. /* Write data to the IO channel - opened file descriptor, socket or SSL
  4449. * descriptor.
  4450. * Return value:
  4451. * >=0 .. number of bytes successfully written
  4452. * -1 .. timeout
  4453. * -2 .. error
  4454. */
  4455. static int
  4456. push_inner(struct mg_context *ctx,
  4457. FILE *fp,
  4458. SOCKET sock,
  4459. SSL *ssl,
  4460. const char *buf,
  4461. int len,
  4462. double timeout)
  4463. {
  4464. uint64_t start = 0, now = 0, timeout_ns = 0;
  4465. int n, err;
  4466. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  4467. #ifdef _WIN32
  4468. typedef int len_t;
  4469. #else
  4470. typedef size_t len_t;
  4471. #endif
  4472. if (timeout > 0) {
  4473. now = mg_get_current_time_ns();
  4474. start = now;
  4475. timeout_ns = (uint64_t)(timeout * 1.0E9);
  4476. }
  4477. if (ctx == NULL) {
  4478. return -2;
  4479. }
  4480. #ifdef NO_SSL
  4481. if (ssl) {
  4482. return -2;
  4483. }
  4484. #endif
  4485. /* Try to read until it succeeds, fails, times out, or the server
  4486. * shuts down. */
  4487. for (;;) {
  4488. #ifndef NO_SSL
  4489. if (ssl != NULL) {
  4490. n = SSL_write(ssl, buf, len);
  4491. if (n <= 0) {
  4492. err = SSL_get_error(ssl, n);
  4493. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  4494. err = ERRNO;
  4495. } else if ((err == SSL_ERROR_WANT_READ)
  4496. || (err == SSL_ERROR_WANT_WRITE)) {
  4497. n = 0;
  4498. } else {
  4499. DEBUG_TRACE("SSL_write() failed, error %d", err);
  4500. return -2;
  4501. }
  4502. } else {
  4503. err = 0;
  4504. }
  4505. } else
  4506. #endif
  4507. if (fp != NULL) {
  4508. n = (int)fwrite(buf, 1, (size_t)len, fp);
  4509. if (ferror(fp)) {
  4510. n = -1;
  4511. err = ERRNO;
  4512. } else {
  4513. err = 0;
  4514. }
  4515. } else {
  4516. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  4517. err = (n < 0) ? ERRNO : 0;
  4518. #ifdef _WIN32
  4519. if (err == WSAEWOULDBLOCK) {
  4520. err = 0;
  4521. n = 0;
  4522. }
  4523. #else
  4524. if (err == EWOULDBLOCK) {
  4525. err = 0;
  4526. n = 0;
  4527. }
  4528. #endif
  4529. if (n < 0) {
  4530. /* shutdown of the socket at client side */
  4531. return -2;
  4532. }
  4533. }
  4534. if (ctx->stop_flag) {
  4535. return -2;
  4536. }
  4537. if ((n > 0) || ((n == 0) && (len == 0))) {
  4538. /* some data has been read, or no data was requested */
  4539. return n;
  4540. }
  4541. if (n < 0) {
  4542. /* socket error - check errno */
  4543. DEBUG_TRACE("send() failed, error %d", err);
  4544. /* TODO (mid): error handling depending on the error code.
  4545. * These codes are different between Windows and Linux.
  4546. * Currently there is no problem with failing send calls,
  4547. * if there is a reproducible situation, it should be
  4548. * investigated in detail.
  4549. */
  4550. return -2;
  4551. }
  4552. /* Only in case n=0 (timeout), repeat calling the write function */
  4553. /* If send failed, wait before retry */
  4554. if (fp != NULL) {
  4555. /* For files, just wait a fixed time,
  4556. * maybe an average disk seek time. */
  4557. mg_sleep(ms_wait > 10 ? 10 : ms_wait);
  4558. } else {
  4559. /* For sockets, wait for the socket using select */
  4560. fd_set wfds;
  4561. struct timeval tv;
  4562. int sret;
  4563. #if defined(__GNUC__) || defined(__MINGW32__)
  4564. /* GCC seems to have a flaw with it's own socket macros:
  4565. * http://www.linuxquestions.org/questions/programming-9/impossible-to-use-gcc-with-wconversion-and-standard-socket-macros-841935/
  4566. */
  4567. #pragma GCC diagnostic push
  4568. #pragma GCC diagnostic ignored "-Wsign-conversion"
  4569. #endif
  4570. FD_ZERO(&wfds);
  4571. FD_SET(sock, &wfds);
  4572. tv.tv_sec = (time_t)(ms_wait / 1000);
  4573. tv.tv_usec = (long)((ms_wait % 1000) * 1000);
  4574. sret = select((int)sock + 1, NULL, &wfds, NULL, &tv);
  4575. #if defined(__GNUC__) || defined(__MINGW32__)
  4576. #pragma GCC diagnostic pop
  4577. #endif
  4578. if (sret > 0) {
  4579. /* We got ready to write. Don't check the timeout
  4580. * but directly go back to write again. */
  4581. continue;
  4582. }
  4583. }
  4584. if (timeout > 0) {
  4585. now = mg_get_current_time_ns();
  4586. if ((now - start) > timeout_ns) {
  4587. /* Timeout */
  4588. break;
  4589. }
  4590. }
  4591. }
  4592. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  4593. used */
  4594. return -1;
  4595. }
  4596. static int64_t
  4597. push_all(struct mg_context *ctx,
  4598. FILE *fp,
  4599. SOCKET sock,
  4600. SSL *ssl,
  4601. const char *buf,
  4602. int64_t len)
  4603. {
  4604. double timeout = -1.0;
  4605. int64_t n, nwritten = 0;
  4606. if (ctx == NULL) {
  4607. return -1;
  4608. }
  4609. if (ctx->config[REQUEST_TIMEOUT]) {
  4610. timeout = atoi(ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  4611. }
  4612. while ((len > 0) && (ctx->stop_flag == 0)) {
  4613. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  4614. if (n < 0) {
  4615. if (nwritten == 0) {
  4616. nwritten = n; /* Propagate the error */
  4617. }
  4618. break;
  4619. } else if (n == 0) {
  4620. break; /* No more data to write */
  4621. } else {
  4622. nwritten += n;
  4623. len -= n;
  4624. }
  4625. }
  4626. return nwritten;
  4627. }
  4628. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  4629. * Return value:
  4630. * >=0 .. number of bytes successfully read
  4631. * -1 .. timeout
  4632. * -2 .. error
  4633. */
  4634. static int
  4635. pull_inner(FILE *fp,
  4636. struct mg_connection *conn,
  4637. char *buf,
  4638. int len,
  4639. double timeout)
  4640. {
  4641. int nread, err = 0;
  4642. #ifdef _WIN32
  4643. typedef int len_t;
  4644. #else
  4645. typedef size_t len_t;
  4646. #endif
  4647. #ifndef NO_SSL
  4648. int ssl_pending;
  4649. #endif
  4650. /* We need an additional wait loop around this, because in some cases
  4651. * with TLSwe may get data from the socket but not from SSL_read.
  4652. * In this case we need to repeat at least once.
  4653. */
  4654. if (fp != NULL) {
  4655. #if !defined(_WIN32_WCE)
  4656. /* Use read() instead of fread(), because if we're reading from the
  4657. * CGI pipe, fread() may block until IO buffer is filled up. We
  4658. * cannot afford to block and must pass all read bytes immediately
  4659. * to the client. */
  4660. nread = (int)read(fileno(fp), buf, (size_t)len);
  4661. #else
  4662. /* WinCE does not support CGI pipes */
  4663. nread = (int)fread(buf, 1, (size_t)len, fp);
  4664. #endif
  4665. err = (nread < 0) ? ERRNO : 0;
  4666. #ifndef NO_SSL
  4667. } else if ((conn->ssl != NULL)
  4668. && ((ssl_pending = SSL_pending(conn->ssl)) > 0)) {
  4669. /* We already know there is no more data buffered in conn->buf
  4670. * but there is more available in the SSL layer. So don't poll
  4671. * conn->client.sock yet. */
  4672. if (ssl_pending > len) {
  4673. ssl_pending = len;
  4674. }
  4675. nread = SSL_read(conn->ssl, buf, ssl_pending);
  4676. if (nread <= 0) {
  4677. err = SSL_get_error(conn->ssl, nread);
  4678. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  4679. err = ERRNO;
  4680. } else if ((err == SSL_ERROR_WANT_READ)
  4681. || (err == SSL_ERROR_WANT_WRITE)) {
  4682. nread = 0;
  4683. } else {
  4684. DEBUG_TRACE("SSL_read() failed, error %d", err);
  4685. return -1;
  4686. }
  4687. } else {
  4688. err = 0;
  4689. }
  4690. } else if (conn->ssl != NULL) {
  4691. struct pollfd pfd[1];
  4692. int pollres;
  4693. pfd[0].fd = conn->client.sock;
  4694. pfd[0].events = POLLIN;
  4695. pollres =
  4696. mg_poll(pfd, 1, (int)(timeout * 1000.0), &(conn->ctx->stop_flag));
  4697. if (conn->ctx->stop_flag) {
  4698. return -2;
  4699. }
  4700. if (pollres > 0) {
  4701. nread = SSL_read(conn->ssl, buf, len);
  4702. if (nread <= 0) {
  4703. err = SSL_get_error(conn->ssl, nread);
  4704. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  4705. err = ERRNO;
  4706. } else if ((err == SSL_ERROR_WANT_READ)
  4707. || (err == SSL_ERROR_WANT_WRITE)) {
  4708. nread = 0;
  4709. } else {
  4710. DEBUG_TRACE("SSL_read() failed, error %d", err);
  4711. return -2;
  4712. }
  4713. } else {
  4714. err = 0;
  4715. }
  4716. } else if (pollres < 0) {
  4717. /* Error */
  4718. return -2;
  4719. } else {
  4720. /* pollres = 0 means timeout */
  4721. nread = 0;
  4722. }
  4723. #endif
  4724. } else {
  4725. struct pollfd pfd[1];
  4726. int pollres;
  4727. pfd[0].fd = conn->client.sock;
  4728. pfd[0].events = POLLIN;
  4729. pollres =
  4730. mg_poll(pfd, 1, (int)(timeout * 1000.0), &(conn->ctx->stop_flag));
  4731. if (conn->ctx->stop_flag) {
  4732. return -2;
  4733. }
  4734. if (pollres > 0) {
  4735. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  4736. err = (nread < 0) ? ERRNO : 0;
  4737. if (nread <= 0) {
  4738. /* shutdown of the socket at client side */
  4739. return -2;
  4740. }
  4741. } else if (pollres < 0) {
  4742. /* error callint poll */
  4743. return -2;
  4744. } else {
  4745. /* pollres = 0 means timeout */
  4746. nread = 0;
  4747. }
  4748. }
  4749. if (conn->ctx->stop_flag) {
  4750. return -2;
  4751. }
  4752. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  4753. /* some data has been read, or no data was requested */
  4754. return nread;
  4755. }
  4756. if (nread < 0) {
  4757. /* socket error - check errno */
  4758. #ifdef _WIN32
  4759. if (err == WSAEWOULDBLOCK) {
  4760. /* TODO (low): check if this is still required */
  4761. /* standard case if called from close_socket_gracefully */
  4762. return -2;
  4763. } else if (err == WSAETIMEDOUT) {
  4764. /* TODO (low): check if this is still required */
  4765. /* timeout is handled by the while loop */
  4766. return 0;
  4767. } else if (err == WSAECONNABORTED) {
  4768. /* See https://www.chilkatsoft.com/p/p_299.asp */
  4769. return -2;
  4770. } else {
  4771. DEBUG_TRACE("recv() failed, error %d", err);
  4772. return -2;
  4773. }
  4774. #else
  4775. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  4776. * if the timeout is reached and if the socket was set to non-
  4777. * blocking in close_socket_gracefully, so we can not distinguish
  4778. * here. We have to wait for the timeout in both cases for now.
  4779. */
  4780. if ((err == EAGAIN) || (err == EWOULDBLOCK) || (err == EINTR)) {
  4781. /* TODO (low): check if this is still required */
  4782. /* EAGAIN/EWOULDBLOCK:
  4783. * standard case if called from close_socket_gracefully
  4784. * => should return -1 */
  4785. /* or timeout occured
  4786. * => the code must stay in the while loop */
  4787. /* EINTR can be generated on a socket with a timeout set even
  4788. * when SA_RESTART is effective for all relevant signals
  4789. * (see signal(7)).
  4790. * => stay in the while loop */
  4791. } else {
  4792. DEBUG_TRACE("recv() failed, error %d", err);
  4793. return -2;
  4794. }
  4795. #endif
  4796. }
  4797. /* Timeout occured, but no data available. */
  4798. return -1;
  4799. }
  4800. static int
  4801. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  4802. {
  4803. int n, nread = 0;
  4804. double timeout = -1.0;
  4805. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  4806. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  4807. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  4808. }
  4809. if (timeout >= 0.0) {
  4810. start_time = mg_get_current_time_ns();
  4811. timeout_ns = (uint64_t)(timeout * 1.0E9);
  4812. }
  4813. while ((len > 0) && (conn->ctx->stop_flag == 0)) {
  4814. n = pull_inner(fp, conn, buf + nread, len, timeout);
  4815. if (n == -2) {
  4816. if (nread == 0) {
  4817. nread = -1; /* Propagate the error */
  4818. }
  4819. break;
  4820. } else if (n == -1) {
  4821. /* timeout */
  4822. if (timeout >= 0.0) {
  4823. now = mg_get_current_time_ns();
  4824. if ((now - start_time) <= timeout_ns) {
  4825. continue;
  4826. }
  4827. }
  4828. break;
  4829. } else if (n == 0) {
  4830. break; /* No more data to read */
  4831. } else {
  4832. conn->consumed_content += n;
  4833. nread += n;
  4834. len -= n;
  4835. }
  4836. }
  4837. return nread;
  4838. }
  4839. static void
  4840. discard_unread_request_data(struct mg_connection *conn)
  4841. {
  4842. char buf[MG_BUF_LEN];
  4843. size_t to_read;
  4844. int nread;
  4845. if (conn == NULL) {
  4846. return;
  4847. }
  4848. to_read = sizeof(buf);
  4849. if (conn->is_chunked) {
  4850. /* Chunked encoding: 1=chunk not read completely, 2=chunk read
  4851. * completely */
  4852. while (conn->is_chunked == 1) {
  4853. nread = mg_read(conn, buf, to_read);
  4854. if (nread <= 0) {
  4855. break;
  4856. }
  4857. }
  4858. } else {
  4859. /* Not chunked: content length is known */
  4860. while (conn->consumed_content < conn->content_len) {
  4861. if (to_read
  4862. > (size_t)(conn->content_len - conn->consumed_content)) {
  4863. to_read = (size_t)(conn->content_len - conn->consumed_content);
  4864. }
  4865. nread = mg_read(conn, buf, to_read);
  4866. if (nread <= 0) {
  4867. break;
  4868. }
  4869. }
  4870. }
  4871. }
  4872. static int
  4873. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  4874. {
  4875. int64_t n, buffered_len, nread;
  4876. int64_t len64 =
  4877. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  4878. * int, we may not read more
  4879. * bytes */
  4880. const char *body;
  4881. if (conn == NULL) {
  4882. return 0;
  4883. }
  4884. /* If Content-Length is not set for a PUT or POST request, read until
  4885. * socket is closed */
  4886. if ((conn->consumed_content) == 0 && (conn->content_len == -1)) {
  4887. conn->content_len = INT64_MAX;
  4888. conn->must_close = 1;
  4889. }
  4890. nread = 0;
  4891. if (conn->consumed_content < conn->content_len) {
  4892. /* Adjust number of bytes to read. */
  4893. int64_t left_to_read = conn->content_len - conn->consumed_content;
  4894. if (left_to_read < len64) {
  4895. /* Do not read more than the total content length of the
  4896. * request.
  4897. */
  4898. len64 = left_to_read;
  4899. }
  4900. /* Return buffered data */
  4901. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  4902. - conn->consumed_content;
  4903. if (buffered_len > 0) {
  4904. if (len64 < buffered_len) {
  4905. buffered_len = len64;
  4906. }
  4907. body = conn->buf + conn->request_len + conn->consumed_content;
  4908. memcpy(buf, body, (size_t)buffered_len);
  4909. len64 -= buffered_len;
  4910. conn->consumed_content += buffered_len;
  4911. nread += buffered_len;
  4912. buf = (char *)buf + buffered_len;
  4913. }
  4914. /* We have returned all buffered data. Read new data from the remote
  4915. * socket.
  4916. */
  4917. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  4918. nread += n;
  4919. } else {
  4920. nread = ((nread > 0) ? nread : n);
  4921. }
  4922. }
  4923. return (int)nread;
  4924. }
  4925. static char
  4926. mg_getc(struct mg_connection *conn)
  4927. {
  4928. char c;
  4929. if (conn == NULL) {
  4930. return 0;
  4931. }
  4932. conn->content_len++;
  4933. if (mg_read_inner(conn, &c, 1) <= 0) {
  4934. return (char)0;
  4935. }
  4936. return c;
  4937. }
  4938. int
  4939. mg_read(struct mg_connection *conn, void *buf, size_t len)
  4940. {
  4941. if (len > INT_MAX) {
  4942. len = INT_MAX;
  4943. }
  4944. if (conn == NULL) {
  4945. return 0;
  4946. }
  4947. if (conn->is_chunked) {
  4948. size_t all_read = 0;
  4949. while (len > 0) {
  4950. if (conn->is_chunked == 2) {
  4951. /* No more data left to read */
  4952. return 0;
  4953. }
  4954. if (conn->chunk_remainder) {
  4955. /* copy from the remainder of the last received chunk */
  4956. long read_ret;
  4957. size_t read_now =
  4958. ((conn->chunk_remainder > len) ? (len)
  4959. : (conn->chunk_remainder));
  4960. conn->content_len += (int)read_now;
  4961. read_ret =
  4962. mg_read_inner(conn, (char *)buf + all_read, read_now);
  4963. if (read_ret < 1) {
  4964. /* read error */
  4965. return -1;
  4966. }
  4967. all_read += (size_t)read_ret;
  4968. conn->chunk_remainder -= (size_t)read_ret;
  4969. len -= (size_t)read_ret;
  4970. if (conn->chunk_remainder == 0) {
  4971. /* Add data bytes in the current chunk have been read,
  4972. * so we are expecting \r\n now. */
  4973. char x1 = mg_getc(conn);
  4974. char x2 = mg_getc(conn);
  4975. if ((x1 != '\r') || (x2 != '\n')) {
  4976. /* Protocol violation */
  4977. return -1;
  4978. }
  4979. }
  4980. } else {
  4981. /* fetch a new chunk */
  4982. int i = 0;
  4983. char lenbuf[64];
  4984. char *end = 0;
  4985. unsigned long chunkSize = 0;
  4986. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  4987. lenbuf[i] = mg_getc(conn);
  4988. if ((i > 0) && (lenbuf[i] == '\r')
  4989. && (lenbuf[i - 1] != '\r')) {
  4990. continue;
  4991. }
  4992. if ((i > 1) && (lenbuf[i] == '\n')
  4993. && (lenbuf[i - 1] == '\r')) {
  4994. lenbuf[i + 1] = 0;
  4995. chunkSize = strtoul(lenbuf, &end, 16);
  4996. if (chunkSize == 0) {
  4997. /* regular end of content */
  4998. conn->is_chunked = 2;
  4999. }
  5000. break;
  5001. }
  5002. if (!isxdigit(lenbuf[i])) {
  5003. /* illegal character for chunk length */
  5004. return -1;
  5005. }
  5006. }
  5007. if ((end == NULL) || (*end != '\r')) {
  5008. /* chunksize not set correctly */
  5009. return -1;
  5010. }
  5011. if (chunkSize == 0) {
  5012. break;
  5013. }
  5014. conn->chunk_remainder = chunkSize;
  5015. }
  5016. }
  5017. return (int)all_read;
  5018. }
  5019. return mg_read_inner(conn, buf, len);
  5020. }
  5021. int
  5022. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5023. {
  5024. time_t now;
  5025. int64_t n, total, allowed;
  5026. if (conn == NULL) {
  5027. return 0;
  5028. }
  5029. if (conn->throttle > 0) {
  5030. if ((now = time(NULL)) != conn->last_throttle_time) {
  5031. conn->last_throttle_time = now;
  5032. conn->last_throttle_bytes = 0;
  5033. }
  5034. allowed = conn->throttle - conn->last_throttle_bytes;
  5035. if (allowed > (int64_t)len) {
  5036. allowed = (int64_t)len;
  5037. }
  5038. if ((total = push_all(conn->ctx,
  5039. NULL,
  5040. conn->client.sock,
  5041. conn->ssl,
  5042. (const char *)buf,
  5043. (int64_t)allowed)) == allowed) {
  5044. buf = (const char *)buf + total;
  5045. conn->last_throttle_bytes += total;
  5046. while ((total < (int64_t)len) && (conn->ctx->stop_flag == 0)) {
  5047. allowed = (conn->throttle > ((int64_t)len - total))
  5048. ? (int64_t)len - total
  5049. : conn->throttle;
  5050. if ((n = push_all(conn->ctx,
  5051. NULL,
  5052. conn->client.sock,
  5053. conn->ssl,
  5054. (const char *)buf,
  5055. (int64_t)allowed)) != allowed) {
  5056. break;
  5057. }
  5058. sleep(1);
  5059. conn->last_throttle_bytes = allowed;
  5060. conn->last_throttle_time = time(NULL);
  5061. buf = (const char *)buf + n;
  5062. total += n;
  5063. }
  5064. }
  5065. } else {
  5066. total = push_all(conn->ctx,
  5067. NULL,
  5068. conn->client.sock,
  5069. conn->ssl,
  5070. (const char *)buf,
  5071. (int64_t)len);
  5072. }
  5073. if (total > 0) {
  5074. conn->num_bytes_sent += total;
  5075. }
  5076. return (int)total;
  5077. }
  5078. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  5079. int
  5080. mg_send_chunk(struct mg_connection *conn,
  5081. const char *chunk,
  5082. unsigned int chunk_len)
  5083. {
  5084. char lenbuf[16];
  5085. size_t lenbuf_len;
  5086. int ret;
  5087. int t;
  5088. /* First store the length information in a text buffer. */
  5089. sprintf(lenbuf, "%x\r\n", chunk_len);
  5090. lenbuf_len = strlen(lenbuf);
  5091. /* Then send length information, chunk and terminating \r\n. */
  5092. ret = mg_write(conn, lenbuf, lenbuf_len);
  5093. if (ret != (int)lenbuf_len) {
  5094. return -1;
  5095. }
  5096. t = ret;
  5097. ret = mg_write(conn, chunk, chunk_len);
  5098. if (ret != (int)chunk_len) {
  5099. return -1;
  5100. }
  5101. t += ret;
  5102. ret = mg_write(conn, "\r\n", 2);
  5103. if (ret != 2) {
  5104. return -1;
  5105. }
  5106. t += ret;
  5107. return t;
  5108. }
  5109. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  5110. static int
  5111. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  5112. {
  5113. va_list ap_copy;
  5114. size_t size = MG_BUF_LEN / 4;
  5115. int len = -1;
  5116. *buf = NULL;
  5117. while (len < 0) {
  5118. if (*buf) {
  5119. mg_free(*buf);
  5120. }
  5121. size *= 4;
  5122. *buf = (char *)mg_malloc(size);
  5123. if (!*buf) {
  5124. break;
  5125. }
  5126. va_copy(ap_copy, ap);
  5127. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  5128. va_end(ap_copy);
  5129. (*buf)[size - 1] = 0;
  5130. }
  5131. return len;
  5132. }
  5133. /* Print message to buffer. If buffer is large enough to hold the message,
  5134. * return buffer. If buffer is to small, allocate large enough buffer on
  5135. * heap,
  5136. * and return allocated buffer. */
  5137. static int
  5138. alloc_vprintf(char **out_buf,
  5139. char *prealloc_buf,
  5140. size_t prealloc_size,
  5141. const char *fmt,
  5142. va_list ap)
  5143. {
  5144. va_list ap_copy;
  5145. int len;
  5146. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  5147. * buffer is too small. Also, older versions of msvcrt.dll do not have
  5148. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  5149. * Therefore, we make two passes: on first pass, get required message
  5150. * length.
  5151. * On second pass, actually print the message. */
  5152. va_copy(ap_copy, ap);
  5153. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  5154. va_end(ap_copy);
  5155. if (len < 0) {
  5156. /* C runtime is not standard compliant, vsnprintf() returned -1.
  5157. * Switch to alternative code path that uses incremental
  5158. * allocations.
  5159. */
  5160. va_copy(ap_copy, ap);
  5161. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  5162. va_end(ap_copy);
  5163. } else if ((size_t)(len) >= prealloc_size) {
  5164. /* The pre-allocated buffer not large enough. */
  5165. /* Allocate a new buffer. */
  5166. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  5167. if (!*out_buf) {
  5168. /* Allocation failed. Return -1 as "out of memory" error. */
  5169. return -1;
  5170. }
  5171. /* Buffer allocation successful. Store the string there. */
  5172. va_copy(ap_copy, ap);
  5173. IGNORE_UNUSED_RESULT(
  5174. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  5175. va_end(ap_copy);
  5176. } else {
  5177. /* The pre-allocated buffer is large enough.
  5178. * Use it to store the string and return the address. */
  5179. va_copy(ap_copy, ap);
  5180. IGNORE_UNUSED_RESULT(
  5181. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  5182. va_end(ap_copy);
  5183. *out_buf = prealloc_buf;
  5184. }
  5185. return len;
  5186. }
  5187. static int
  5188. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  5189. {
  5190. char mem[MG_BUF_LEN];
  5191. char *buf = NULL;
  5192. int len;
  5193. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  5194. len = mg_write(conn, buf, (size_t)len);
  5195. }
  5196. if ((buf != mem) && (buf != NULL)) {
  5197. mg_free(buf);
  5198. }
  5199. return len;
  5200. }
  5201. int
  5202. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  5203. {
  5204. va_list ap;
  5205. int result;
  5206. va_start(ap, fmt);
  5207. result = mg_vprintf(conn, fmt, ap);
  5208. va_end(ap);
  5209. return result;
  5210. }
  5211. int
  5212. mg_url_decode(const char *src,
  5213. int src_len,
  5214. char *dst,
  5215. int dst_len,
  5216. int is_form_url_encoded)
  5217. {
  5218. int i, j, a, b;
  5219. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  5220. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  5221. if ((i < src_len - 2) && (src[i] == '%')
  5222. && isxdigit(*(const unsigned char *)(src + i + 1))
  5223. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  5224. a = tolower(*(const unsigned char *)(src + i + 1));
  5225. b = tolower(*(const unsigned char *)(src + i + 2));
  5226. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  5227. i += 2;
  5228. } else if (is_form_url_encoded && (src[i] == '+')) {
  5229. dst[j] = ' ';
  5230. } else {
  5231. dst[j] = src[i];
  5232. }
  5233. }
  5234. dst[j] = '\0'; /* Null-terminate the destination */
  5235. return (i >= src_len) ? j : -1;
  5236. }
  5237. int
  5238. mg_get_var(const char *data,
  5239. size_t data_len,
  5240. const char *name,
  5241. char *dst,
  5242. size_t dst_len)
  5243. {
  5244. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  5245. }
  5246. int
  5247. mg_get_var2(const char *data,
  5248. size_t data_len,
  5249. const char *name,
  5250. char *dst,
  5251. size_t dst_len,
  5252. size_t occurrence)
  5253. {
  5254. const char *p, *e, *s;
  5255. size_t name_len;
  5256. int len;
  5257. if ((dst == NULL) || (dst_len == 0)) {
  5258. len = -2;
  5259. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  5260. len = -1;
  5261. dst[0] = '\0';
  5262. } else {
  5263. name_len = strlen(name);
  5264. e = data + data_len;
  5265. len = -1;
  5266. dst[0] = '\0';
  5267. /* data is "var1=val1&var2=val2...". Find variable first */
  5268. for (p = data; p + name_len < e; p++) {
  5269. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  5270. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  5271. /* Point p to variable value */
  5272. p += name_len + 1;
  5273. /* Point s to the end of the value */
  5274. s = (const char *)memchr(p, '&', (size_t)(e - p));
  5275. if (s == NULL) {
  5276. s = e;
  5277. }
  5278. /* assert(s >= p); */
  5279. if (s < p) {
  5280. return -3;
  5281. }
  5282. /* Decode variable into destination buffer */
  5283. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  5284. /* Redirect error code from -1 to -2 (destination buffer too
  5285. * small). */
  5286. if (len == -1) {
  5287. len = -2;
  5288. }
  5289. break;
  5290. }
  5291. }
  5292. }
  5293. return len;
  5294. }
  5295. /* HCP24: some changes to compare hole var_name */
  5296. int
  5297. mg_get_cookie(const char *cookie_header,
  5298. const char *var_name,
  5299. char *dst,
  5300. size_t dst_size)
  5301. {
  5302. const char *s, *p, *end;
  5303. int name_len, len = -1;
  5304. if ((dst == NULL) || (dst_size == 0)) {
  5305. return -2;
  5306. }
  5307. dst[0] = '\0';
  5308. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  5309. return -1;
  5310. }
  5311. name_len = (int)strlen(var_name);
  5312. end = s + strlen(s);
  5313. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  5314. if (s[name_len] == '=') {
  5315. /* HCP24: now check is it a substring or a full cookie name */
  5316. if ((s == cookie_header) || (s[-1] == ' ')) {
  5317. s += name_len + 1;
  5318. if ((p = strchr(s, ' ')) == NULL) {
  5319. p = end;
  5320. }
  5321. if (p[-1] == ';') {
  5322. p--;
  5323. }
  5324. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  5325. s++;
  5326. p--;
  5327. }
  5328. if ((size_t)(p - s) < dst_size) {
  5329. len = (int)(p - s);
  5330. mg_strlcpy(dst, s, (size_t)len + 1);
  5331. } else {
  5332. len = -3;
  5333. }
  5334. break;
  5335. }
  5336. }
  5337. }
  5338. return len;
  5339. }
  5340. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  5341. static void
  5342. base64_encode(const unsigned char *src, int src_len, char *dst)
  5343. {
  5344. static const char *b64 =
  5345. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  5346. int i, j, a, b, c;
  5347. for (i = j = 0; i < src_len; i += 3) {
  5348. a = src[i];
  5349. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  5350. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  5351. dst[j++] = b64[a >> 2];
  5352. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  5353. if (i + 1 < src_len) {
  5354. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  5355. }
  5356. if (i + 2 < src_len) {
  5357. dst[j++] = b64[c & 63];
  5358. }
  5359. }
  5360. while (j % 4 != 0) {
  5361. dst[j++] = '=';
  5362. }
  5363. dst[j++] = '\0';
  5364. }
  5365. #endif
  5366. #if defined(USE_LUA)
  5367. static unsigned char
  5368. b64reverse(char letter)
  5369. {
  5370. if ((letter >= 'A') && (letter <= 'Z')) {
  5371. return letter - 'A';
  5372. }
  5373. if ((letter >= 'a') && (letter <= 'z')) {
  5374. return letter - 'a' + 26;
  5375. }
  5376. if ((letter >= '0') && (letter <= '9')) {
  5377. return letter - '0' + 52;
  5378. }
  5379. if (letter == '+') {
  5380. return 62;
  5381. }
  5382. if (letter == '/') {
  5383. return 63;
  5384. }
  5385. if (letter == '=') {
  5386. return 255; /* normal end */
  5387. }
  5388. return 254; /* error */
  5389. }
  5390. static int
  5391. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  5392. {
  5393. int i;
  5394. unsigned char a, b, c, d;
  5395. *dst_len = 0;
  5396. for (i = 0; i < src_len; i += 4) {
  5397. a = b64reverse(src[i]);
  5398. if (a >= 254) {
  5399. return i;
  5400. }
  5401. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  5402. if (b >= 254) {
  5403. return i + 1;
  5404. }
  5405. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  5406. if (c == 254) {
  5407. return i + 2;
  5408. }
  5409. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  5410. if (d == 254) {
  5411. return i + 3;
  5412. }
  5413. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  5414. if (c != 255) {
  5415. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  5416. if (d != 255) {
  5417. dst[(*dst_len)++] = (c << 6) + d;
  5418. }
  5419. }
  5420. }
  5421. return -1;
  5422. }
  5423. #endif
  5424. static int
  5425. is_put_or_delete_method(const struct mg_connection *conn)
  5426. {
  5427. if (conn) {
  5428. const char *s = conn->request_info.request_method;
  5429. return (s != NULL) && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  5430. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  5431. }
  5432. return 0;
  5433. }
  5434. #if !defined(NO_FILES)
  5435. static int
  5436. extention_matches_script(
  5437. struct mg_connection *conn, /* in: request (must be valid) */
  5438. const char *filename /* in: filename (must be valid) */
  5439. )
  5440. {
  5441. #if !defined(NO_CGI)
  5442. if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  5443. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  5444. filename) > 0) {
  5445. return 1;
  5446. }
  5447. #endif
  5448. #if defined(USE_LUA)
  5449. if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  5450. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  5451. filename) > 0) {
  5452. return 1;
  5453. }
  5454. #endif
  5455. #if defined(USE_DUKTAPE)
  5456. if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  5457. strlen(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  5458. filename) > 0) {
  5459. return 1;
  5460. }
  5461. #endif
  5462. /* filename and conn could be unused, if all preocessor conditions
  5463. * are false (no script language supported). */
  5464. (void)filename;
  5465. (void)conn;
  5466. return 0;
  5467. }
  5468. /* For given directory path, substitute it to valid index file.
  5469. * Return 1 if index file has been found, 0 if not found.
  5470. * If the file is found, it's stats is returned in stp. */
  5471. static int
  5472. substitute_index_file(struct mg_connection *conn,
  5473. char *path,
  5474. size_t path_len,
  5475. struct mg_file_stat *filestat)
  5476. {
  5477. const char *list = conn->ctx->config[INDEX_FILES];
  5478. struct vec filename_vec;
  5479. size_t n = strlen(path);
  5480. int found = 0;
  5481. /* The 'path' given to us points to the directory. Remove all trailing
  5482. * directory separator characters from the end of the path, and
  5483. * then append single directory separator character. */
  5484. while ((n > 0) && (path[n - 1] == '/')) {
  5485. n--;
  5486. }
  5487. path[n] = '/';
  5488. /* Traverse index files list. For each entry, append it to the given
  5489. * path and see if the file exists. If it exists, break the loop */
  5490. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  5491. /* Ignore too long entries that may overflow path buffer */
  5492. if (filename_vec.len > (path_len - (n + 2))) {
  5493. continue;
  5494. }
  5495. /* Prepare full path to the index file */
  5496. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  5497. /* Does it exist? */
  5498. if (mg_stat(conn, path, filestat)) {
  5499. /* Yes it does, break the loop */
  5500. found = 1;
  5501. break;
  5502. }
  5503. }
  5504. /* If no index file exists, restore directory path */
  5505. if (!found) {
  5506. path[n] = '\0';
  5507. }
  5508. return found;
  5509. }
  5510. #endif
  5511. static void
  5512. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  5513. char *filename, /* out: filename */
  5514. size_t filename_buf_len, /* in: size of filename buffer */
  5515. struct mg_file_stat *filestat, /* out: file status structure */
  5516. int *is_found, /* out: file found (directly) */
  5517. int *is_script_resource, /* out: handled by a script? */
  5518. int *is_websocket_request, /* out: websocket connetion? */
  5519. int *is_put_or_delete_request /* out: put/delete a file? */
  5520. )
  5521. {
  5522. #if !defined(NO_FILES)
  5523. const char *uri = conn->request_info.local_uri;
  5524. const char *root = conn->ctx->config[DOCUMENT_ROOT];
  5525. const char *rewrite;
  5526. struct vec a, b;
  5527. int match_len;
  5528. char gz_path[PATH_MAX];
  5529. char const *accept_encoding;
  5530. int truncated;
  5531. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  5532. char *tmp_str;
  5533. size_t tmp_str_len, sep_pos;
  5534. #endif
  5535. #else
  5536. (void)filename_buf_len; /* unused if NO_FILES is defined */
  5537. #endif
  5538. /* Step 1: Set all initially unknown outputs to zero */
  5539. memset(filestat, 0, sizeof(*filestat));
  5540. *filename = 0;
  5541. *is_found = 0;
  5542. *is_script_resource = 0;
  5543. /* Step 2: Check if the request attempts to modify the file system */
  5544. *is_put_or_delete_request = is_put_or_delete_method(conn);
  5545. /* Step 3: Check if it is a websocket request, and modify the document
  5546. * root if required */
  5547. #if defined(USE_WEBSOCKET)
  5548. *is_websocket_request = is_websocket_protocol(conn);
  5549. #if !defined(NO_FILES)
  5550. if (*is_websocket_request && conn->ctx->config[WEBSOCKET_ROOT]) {
  5551. root = conn->ctx->config[WEBSOCKET_ROOT];
  5552. }
  5553. #endif /* !NO_FILES */
  5554. #else /* USE_WEBSOCKET */
  5555. *is_websocket_request = 0;
  5556. #endif /* USE_WEBSOCKET */
  5557. /* Step 4: Check if gzip encoded response is allowed */
  5558. conn->accept_gzip = 0;
  5559. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  5560. if (strstr(accept_encoding, "gzip") != NULL) {
  5561. conn->accept_gzip = 1;
  5562. }
  5563. }
  5564. #if !defined(NO_FILES)
  5565. /* Step 5: If there is no root directory, don't look for files. */
  5566. /* Note that root == NULL is a regular use case here. This occurs,
  5567. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  5568. * config is not required. */
  5569. if (root == NULL) {
  5570. /* all file related outputs have already been set to 0, just return
  5571. */
  5572. return;
  5573. }
  5574. /* Step 6: Determine the local file path from the root path and the
  5575. * request uri. */
  5576. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  5577. * part of the path one byte on the right. */
  5578. mg_snprintf(
  5579. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  5580. if (truncated) {
  5581. goto interpret_cleanup;
  5582. }
  5583. /* Step 7: URI rewriting */
  5584. rewrite = conn->ctx->config[URL_REWRITE_PATTERN];
  5585. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  5586. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  5587. mg_snprintf(conn,
  5588. &truncated,
  5589. filename,
  5590. filename_buf_len - 1,
  5591. "%.*s%s",
  5592. (int)b.len,
  5593. b.ptr,
  5594. uri + match_len);
  5595. break;
  5596. }
  5597. }
  5598. if (truncated) {
  5599. goto interpret_cleanup;
  5600. }
  5601. /* Step 8: Check if the file exists at the server */
  5602. /* Local file path and name, corresponding to requested URI
  5603. * is now stored in "filename" variable. */
  5604. if (mg_stat(conn, filename, filestat)) {
  5605. /* 8.1: File exists. */
  5606. *is_found = 1;
  5607. /* 8.2: Check if it is a script type. */
  5608. if (extention_matches_script(conn, filename)) {
  5609. /* The request addresses a CGI resource, Lua script or
  5610. * server-side javascript.
  5611. * The URI corresponds to the script itself (like
  5612. * /path/script.cgi), and there is no additional resource
  5613. * path (like /path/script.cgi/something).
  5614. * Requests that modify (replace or delete) a resource, like
  5615. * PUT and DELETE requests, should replace/delete the script
  5616. * file.
  5617. * Requests that read or write from/to a resource, like GET and
  5618. * POST requests, should call the script and return the
  5619. * generated response. */
  5620. *is_script_resource = (!*is_put_or_delete_request);
  5621. }
  5622. /* 8.3: If the request target is a directory, there could be
  5623. * a substitute file (index.html, index.cgi, ...). */
  5624. if (filestat->is_directory) {
  5625. /* Use a local copy here, since substitute_index_file will
  5626. * change the content of the file status */
  5627. struct mg_file_stat tmp_filestat;
  5628. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  5629. if (substitute_index_file(
  5630. conn, filename, filename_buf_len, &tmp_filestat)) {
  5631. /* Substitute file found. Copy stat to the output, then
  5632. * check if the file is a script file */
  5633. *filestat = tmp_filestat;
  5634. if (extention_matches_script(conn, filename)) {
  5635. /* Substitute file is a script file */
  5636. *is_script_resource = 1;
  5637. } else {
  5638. /* Substitute file is a regular file */
  5639. *is_script_resource = 0;
  5640. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  5641. }
  5642. }
  5643. /* If there is no substitute file, the server could return
  5644. * a directory listing in a later step */
  5645. }
  5646. return;
  5647. }
  5648. /* Step 9: Check for zipped files: */
  5649. /* If we can't find the actual file, look for the file
  5650. * with the same name but a .gz extension. If we find it,
  5651. * use that and set the gzipped flag in the file struct
  5652. * to indicate that the response need to have the content-
  5653. * encoding: gzip header.
  5654. * We can only do this if the browser declares support. */
  5655. if (conn->accept_gzip) {
  5656. mg_snprintf(
  5657. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  5658. if (truncated) {
  5659. goto interpret_cleanup;
  5660. }
  5661. if (mg_stat(conn, gz_path, filestat)) {
  5662. if (filestat) {
  5663. filestat->is_gzipped = 1;
  5664. *is_found = 1;
  5665. }
  5666. /* Currently gz files can not be scripts. */
  5667. return;
  5668. }
  5669. }
  5670. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  5671. /* Step 10: Script resources may handle sub-resources */
  5672. /* Support PATH_INFO for CGI scripts. */
  5673. tmp_str_len = strlen(filename);
  5674. tmp_str = mg_malloc_ctx(tmp_str_len + PATH_MAX + 1, conn->ctx);
  5675. if (!tmp_str) {
  5676. /* Out of memory */
  5677. goto interpret_cleanup;
  5678. }
  5679. memcpy(tmp_str, filename, tmp_str_len + 1);
  5680. sep_pos = tmp_str_len;
  5681. while (sep_pos > 0) {
  5682. sep_pos--;
  5683. if (tmp_str[sep_pos] == '/') {
  5684. int is_script = 0, does_exist = 0;
  5685. tmp_str[sep_pos] = 0;
  5686. if (tmp_str[0]) {
  5687. is_script = extention_matches_script(conn, tmp_str);
  5688. does_exist = mg_stat(conn, tmp_str, filestat);
  5689. }
  5690. if (does_exist && is_script) {
  5691. filename[sep_pos] = 0;
  5692. memmove(filename + sep_pos + 2,
  5693. filename + sep_pos + 1,
  5694. strlen(filename + sep_pos + 1) + 1);
  5695. conn->path_info = filename + sep_pos + 1;
  5696. filename[sep_pos + 1] = '/';
  5697. *is_script_resource = 1;
  5698. *is_found = 1;
  5699. break;
  5700. }
  5701. if (substitute_index_file(
  5702. conn, tmp_str, tmp_str_len + PATH_MAX, filestat)) {
  5703. /* some intermediate directory has an index file */
  5704. if (extention_matches_script(conn, tmp_str)) {
  5705. /* this index file is a script */
  5706. char *tmp_str2 = mg_strdup(filename + sep_pos + 1);
  5707. mg_snprintf(conn,
  5708. &truncated,
  5709. filename,
  5710. filename_buf_len,
  5711. "%s//%s",
  5712. tmp_str,
  5713. tmp_str2);
  5714. mg_free(tmp_str2);
  5715. if (truncated) {
  5716. mg_free(tmp_str);
  5717. goto interpret_cleanup;
  5718. }
  5719. sep_pos = strlen(tmp_str);
  5720. filename[sep_pos] = 0;
  5721. conn->path_info = filename + sep_pos + 1;
  5722. *is_script_resource = 1;
  5723. *is_found = 1;
  5724. break;
  5725. } else {
  5726. /* non-script files will not have sub-resources */
  5727. filename[sep_pos] = 0;
  5728. conn->path_info = 0;
  5729. *is_script_resource = 0;
  5730. *is_found = 0;
  5731. break;
  5732. }
  5733. }
  5734. tmp_str[sep_pos] = '/';
  5735. }
  5736. }
  5737. mg_free(tmp_str);
  5738. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  5739. #endif /* !defined(NO_FILES) */
  5740. return;
  5741. #if !defined(NO_FILES)
  5742. /* Reset all outputs */
  5743. interpret_cleanup:
  5744. memset(filestat, 0, sizeof(*filestat));
  5745. *filename = 0;
  5746. *is_found = 0;
  5747. *is_script_resource = 0;
  5748. *is_websocket_request = 0;
  5749. *is_put_or_delete_request = 0;
  5750. #endif /* !defined(NO_FILES) */
  5751. }
  5752. /* Check whether full request is buffered. Return:
  5753. * -1 if request or response is malformed
  5754. * 0 if request or response is not yet fully buffered
  5755. * >0 actual request length, including last \r\n\r\n */
  5756. static int
  5757. get_http_header_len(const char *buf, int buflen)
  5758. {
  5759. int i;
  5760. for (i = 0; i < buflen; i++) {
  5761. /* Do an unsigned comparison in some conditions below */
  5762. const unsigned char c = ((const unsigned char *)buf)[i];
  5763. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  5764. && !isprint(c)) {
  5765. /* abort scan as soon as one malformed character is found */
  5766. return -1;
  5767. }
  5768. if (i < buflen - 1) {
  5769. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  5770. /* Two newline, no carriage return - not standard compliant,
  5771. * but
  5772. * it
  5773. * should be accepted */
  5774. return i + 2;
  5775. }
  5776. }
  5777. if (i < buflen - 3) {
  5778. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  5779. && (buf[i + 3] == '\n')) {
  5780. /* Two \r\n - standard compliant */
  5781. return i + 4;
  5782. }
  5783. }
  5784. }
  5785. return 0;
  5786. }
  5787. #if !defined(NO_CACHING)
  5788. /* Convert month to the month number. Return -1 on error, or month number */
  5789. static int
  5790. get_month_index(const char *s)
  5791. {
  5792. size_t i;
  5793. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  5794. if (!strcmp(s, month_names[i])) {
  5795. return (int)i;
  5796. }
  5797. }
  5798. return -1;
  5799. }
  5800. /* Parse UTC date-time string, and return the corresponding time_t value. */
  5801. static time_t
  5802. parse_date_string(const char *datetime)
  5803. {
  5804. char month_str[32] = {0};
  5805. int second, minute, hour, day, month, year;
  5806. time_t result = (time_t)0;
  5807. struct tm tm;
  5808. if ((sscanf(datetime,
  5809. "%d/%3s/%d %d:%d:%d",
  5810. &day,
  5811. month_str,
  5812. &year,
  5813. &hour,
  5814. &minute,
  5815. &second) == 6) || (sscanf(datetime,
  5816. "%d %3s %d %d:%d:%d",
  5817. &day,
  5818. month_str,
  5819. &year,
  5820. &hour,
  5821. &minute,
  5822. &second) == 6)
  5823. || (sscanf(datetime,
  5824. "%*3s, %d %3s %d %d:%d:%d",
  5825. &day,
  5826. month_str,
  5827. &year,
  5828. &hour,
  5829. &minute,
  5830. &second) == 6) || (sscanf(datetime,
  5831. "%d-%3s-%d %d:%d:%d",
  5832. &day,
  5833. month_str,
  5834. &year,
  5835. &hour,
  5836. &minute,
  5837. &second) == 6)) {
  5838. month = get_month_index(month_str);
  5839. if ((month >= 0) && (year >= 1970)) {
  5840. memset(&tm, 0, sizeof(tm));
  5841. tm.tm_year = year - 1900;
  5842. tm.tm_mon = month;
  5843. tm.tm_mday = day;
  5844. tm.tm_hour = hour;
  5845. tm.tm_min = minute;
  5846. tm.tm_sec = second;
  5847. result = timegm(&tm);
  5848. }
  5849. }
  5850. return result;
  5851. }
  5852. #endif /* !NO_CACHING */
  5853. /* Protect against directory disclosure attack by removing '..',
  5854. * excessive '/' and '\' characters */
  5855. static void
  5856. remove_double_dots_and_double_slashes(char *s)
  5857. {
  5858. char *p = s;
  5859. while ((s[0] == '.') && (s[1] == '.')) {
  5860. s++;
  5861. }
  5862. while (*s != '\0') {
  5863. *p++ = *s++;
  5864. if ((s[-1] == '/') || (s[-1] == '\\')) {
  5865. /* Skip all following slashes, backslashes and double-dots */
  5866. while (s[0] != '\0') {
  5867. if ((s[0] == '/') || (s[0] == '\\')) {
  5868. s++;
  5869. } else if ((s[0] == '.') && (s[1] == '.')) {
  5870. s += 2;
  5871. } else {
  5872. break;
  5873. }
  5874. }
  5875. }
  5876. }
  5877. *p = '\0';
  5878. }
  5879. static const struct {
  5880. const char *extension;
  5881. size_t ext_len;
  5882. const char *mime_type;
  5883. } builtin_mime_types[] = {
  5884. /* IANA registered MIME types
  5885. * (http://www.iana.org/assignments/media-types)
  5886. * application types */
  5887. {".doc", 4, "application/msword"},
  5888. {".eps", 4, "application/postscript"},
  5889. {".exe", 4, "application/octet-stream"},
  5890. {".js", 3, "application/javascript"},
  5891. {".json", 5, "application/json"},
  5892. {".pdf", 4, "application/pdf"},
  5893. {".ps", 3, "application/postscript"},
  5894. {".rtf", 4, "application/rtf"},
  5895. {".xhtml", 6, "application/xhtml+xml"},
  5896. {".xsl", 4, "application/xml"},
  5897. {".xslt", 5, "application/xml"},
  5898. /* fonts */
  5899. {".ttf", 4, "application/font-sfnt"},
  5900. {".cff", 4, "application/font-sfnt"},
  5901. {".otf", 4, "application/font-sfnt"},
  5902. {".aat", 4, "application/font-sfnt"},
  5903. {".sil", 4, "application/font-sfnt"},
  5904. {".pfr", 4, "application/font-tdpfr"},
  5905. {".woff", 5, "application/font-woff"},
  5906. /* audio */
  5907. {".mp3", 4, "audio/mpeg"},
  5908. {".oga", 4, "audio/ogg"},
  5909. {".ogg", 4, "audio/ogg"},
  5910. /* image */
  5911. {".gif", 4, "image/gif"},
  5912. {".ief", 4, "image/ief"},
  5913. {".jpeg", 5, "image/jpeg"},
  5914. {".jpg", 4, "image/jpeg"},
  5915. {".jpm", 4, "image/jpm"},
  5916. {".jpx", 4, "image/jpx"},
  5917. {".png", 4, "image/png"},
  5918. {".svg", 4, "image/svg+xml"},
  5919. {".tif", 4, "image/tiff"},
  5920. {".tiff", 5, "image/tiff"},
  5921. /* model */
  5922. {".wrl", 4, "model/vrml"},
  5923. /* text */
  5924. {".css", 4, "text/css"},
  5925. {".csv", 4, "text/csv"},
  5926. {".htm", 4, "text/html"},
  5927. {".html", 5, "text/html"},
  5928. {".sgm", 4, "text/sgml"},
  5929. {".shtm", 5, "text/html"},
  5930. {".shtml", 6, "text/html"},
  5931. {".txt", 4, "text/plain"},
  5932. {".xml", 4, "text/xml"},
  5933. /* video */
  5934. {".mov", 4, "video/quicktime"},
  5935. {".mp4", 4, "video/mp4"},
  5936. {".mpeg", 5, "video/mpeg"},
  5937. {".mpg", 4, "video/mpeg"},
  5938. {".ogv", 4, "video/ogg"},
  5939. {".qt", 3, "video/quicktime"},
  5940. /* not registered types
  5941. * (http://reference.sitepoint.com/html/mime-types-full,
  5942. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  5943. {".arj", 4, "application/x-arj-compressed"},
  5944. {".gz", 3, "application/x-gunzip"},
  5945. {".rar", 4, "application/x-arj-compressed"},
  5946. {".swf", 4, "application/x-shockwave-flash"},
  5947. {".tar", 4, "application/x-tar"},
  5948. {".tgz", 4, "application/x-tar-gz"},
  5949. {".torrent", 8, "application/x-bittorrent"},
  5950. {".ppt", 4, "application/x-mspowerpoint"},
  5951. {".xls", 4, "application/x-msexcel"},
  5952. {".zip", 4, "application/x-zip-compressed"},
  5953. {".aac",
  5954. 4,
  5955. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  5956. {".aif", 4, "audio/x-aif"},
  5957. {".m3u", 4, "audio/x-mpegurl"},
  5958. {".mid", 4, "audio/x-midi"},
  5959. {".ra", 3, "audio/x-pn-realaudio"},
  5960. {".ram", 4, "audio/x-pn-realaudio"},
  5961. {".wav", 4, "audio/x-wav"},
  5962. {".bmp", 4, "image/bmp"},
  5963. {".ico", 4, "image/x-icon"},
  5964. {".pct", 4, "image/x-pct"},
  5965. {".pict", 5, "image/pict"},
  5966. {".rgb", 4, "image/x-rgb"},
  5967. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  5968. {".asf", 4, "video/x-ms-asf"},
  5969. {".avi", 4, "video/x-msvideo"},
  5970. {".m4v", 4, "video/x-m4v"},
  5971. {NULL, 0, NULL}};
  5972. const char *
  5973. mg_get_builtin_mime_type(const char *path)
  5974. {
  5975. const char *ext;
  5976. size_t i, path_len;
  5977. path_len = strlen(path);
  5978. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  5979. ext = path + (path_len - builtin_mime_types[i].ext_len);
  5980. if ((path_len > builtin_mime_types[i].ext_len)
  5981. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  5982. return builtin_mime_types[i].mime_type;
  5983. }
  5984. }
  5985. return "text/plain";
  5986. }
  5987. /* Look at the "path" extension and figure what mime type it has.
  5988. * Store mime type in the vector. */
  5989. static void
  5990. get_mime_type(struct mg_context *ctx, const char *path, struct vec *vec)
  5991. {
  5992. struct vec ext_vec, mime_vec;
  5993. const char *list, *ext;
  5994. size_t path_len;
  5995. path_len = strlen(path);
  5996. if ((ctx == NULL) || (vec == NULL)) {
  5997. if (vec != NULL) {
  5998. memset(vec, '\0', sizeof(struct vec));
  5999. }
  6000. return;
  6001. }
  6002. /* Scan user-defined mime types first, in case user wants to
  6003. * override default mime types. */
  6004. list = ctx->config[EXTRA_MIME_TYPES];
  6005. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  6006. /* ext now points to the path suffix */
  6007. ext = path + path_len - ext_vec.len;
  6008. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  6009. *vec = mime_vec;
  6010. return;
  6011. }
  6012. }
  6013. vec->ptr = mg_get_builtin_mime_type(path);
  6014. vec->len = strlen(vec->ptr);
  6015. }
  6016. /* Stringify binary data. Output buffer must be twice as big as input,
  6017. * because each byte takes 2 bytes in string representation */
  6018. static void
  6019. bin2str(char *to, const unsigned char *p, size_t len)
  6020. {
  6021. static const char *hex = "0123456789abcdef";
  6022. for (; len--; p++) {
  6023. *to++ = hex[p[0] >> 4];
  6024. *to++ = hex[p[0] & 0x0f];
  6025. }
  6026. *to = '\0';
  6027. }
  6028. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  6029. */
  6030. char *
  6031. mg_md5(char buf[33], ...)
  6032. {
  6033. md5_byte_t hash[16];
  6034. const char *p;
  6035. va_list ap;
  6036. md5_state_t ctx;
  6037. md5_init(&ctx);
  6038. va_start(ap, buf);
  6039. while ((p = va_arg(ap, const char *)) != NULL) {
  6040. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  6041. }
  6042. va_end(ap);
  6043. md5_finish(&ctx, hash);
  6044. bin2str(buf, hash, sizeof(hash));
  6045. return buf;
  6046. }
  6047. /* Check the user's password, return 1 if OK */
  6048. static int
  6049. check_password(const char *method,
  6050. const char *ha1,
  6051. const char *uri,
  6052. const char *nonce,
  6053. const char *nc,
  6054. const char *cnonce,
  6055. const char *qop,
  6056. const char *response)
  6057. {
  6058. char ha2[32 + 1], expected_response[32 + 1];
  6059. /* Some of the parameters may be NULL */
  6060. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  6061. || (qop == NULL) || (response == NULL)) {
  6062. return 0;
  6063. }
  6064. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  6065. if (strlen(response) != 32) {
  6066. return 0;
  6067. }
  6068. mg_md5(ha2, method, ":", uri, NULL);
  6069. mg_md5(expected_response,
  6070. ha1,
  6071. ":",
  6072. nonce,
  6073. ":",
  6074. nc,
  6075. ":",
  6076. cnonce,
  6077. ":",
  6078. qop,
  6079. ":",
  6080. ha2,
  6081. NULL);
  6082. return mg_strcasecmp(response, expected_response) == 0;
  6083. }
  6084. /* Use the global passwords file, if specified by auth_gpass option,
  6085. * or search for .htpasswd in the requested directory. */
  6086. static void
  6087. open_auth_file(struct mg_connection *conn,
  6088. const char *path,
  6089. struct mg_file *filep)
  6090. {
  6091. if ((conn != NULL) && (conn->ctx != NULL)) {
  6092. char name[PATH_MAX];
  6093. const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
  6094. int truncated;
  6095. if (gpass != NULL) {
  6096. /* Use global passwords file */
  6097. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  6098. #ifdef DEBUG
  6099. /* Use mg_cry here, since gpass has been configured. */
  6100. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  6101. #endif
  6102. }
  6103. /* Important: using local struct mg_file to test path for
  6104. * is_directory flag. If filep is used, mg_stat() makes it
  6105. * appear as if auth file was opened.
  6106. * TODO(mid): Check if this is still required after rewriting
  6107. * mg_stat */
  6108. } else if (mg_stat(conn, path, &filep->stat)
  6109. && filep->stat.is_directory) {
  6110. mg_snprintf(conn,
  6111. &truncated,
  6112. name,
  6113. sizeof(name),
  6114. "%s/%s",
  6115. path,
  6116. PASSWORDS_FILE_NAME);
  6117. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  6118. #ifdef DEBUG
  6119. /* Don't use mg_cry here, but only a trace, since this is
  6120. * a typical case. It will occur for every directory
  6121. * without a password file. */
  6122. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  6123. #endif
  6124. }
  6125. } else {
  6126. /* Try to find .htpasswd in requested directory. */
  6127. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  6128. if (e[0] == '/') {
  6129. break;
  6130. }
  6131. }
  6132. mg_snprintf(conn,
  6133. &truncated,
  6134. name,
  6135. sizeof(name),
  6136. "%.*s/%s",
  6137. (int)(e - p),
  6138. p,
  6139. PASSWORDS_FILE_NAME);
  6140. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  6141. #ifdef DEBUG
  6142. /* Don't use mg_cry here, but only a trace, since this is
  6143. * a typical case. It will occur for every directory
  6144. * without a password file. */
  6145. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  6146. #endif
  6147. }
  6148. }
  6149. }
  6150. }
  6151. /* Parsed Authorization header */
  6152. struct ah {
  6153. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  6154. };
  6155. /* Return 1 on success. Always initializes the ah structure. */
  6156. static int
  6157. parse_auth_header(struct mg_connection *conn,
  6158. char *buf,
  6159. size_t buf_size,
  6160. struct ah *ah)
  6161. {
  6162. char *name, *value, *s;
  6163. const char *auth_header;
  6164. uint64_t nonce;
  6165. if (!ah || !conn) {
  6166. return 0;
  6167. }
  6168. (void)memset(ah, 0, sizeof(*ah));
  6169. if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
  6170. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  6171. return 0;
  6172. }
  6173. /* Make modifiable copy of the auth header */
  6174. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  6175. s = buf;
  6176. /* Parse authorization header */
  6177. for (;;) {
  6178. /* Gobble initial spaces */
  6179. while (isspace(*(unsigned char *)s)) {
  6180. s++;
  6181. }
  6182. name = skip_quoted(&s, "=", " ", 0);
  6183. /* Value is either quote-delimited, or ends at first comma or space.
  6184. */
  6185. if (s[0] == '\"') {
  6186. s++;
  6187. value = skip_quoted(&s, "\"", " ", '\\');
  6188. if (s[0] == ',') {
  6189. s++;
  6190. }
  6191. } else {
  6192. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  6193. * spaces */
  6194. }
  6195. if (*name == '\0') {
  6196. break;
  6197. }
  6198. if (!strcmp(name, "username")) {
  6199. ah->user = value;
  6200. } else if (!strcmp(name, "cnonce")) {
  6201. ah->cnonce = value;
  6202. } else if (!strcmp(name, "response")) {
  6203. ah->response = value;
  6204. } else if (!strcmp(name, "uri")) {
  6205. ah->uri = value;
  6206. } else if (!strcmp(name, "qop")) {
  6207. ah->qop = value;
  6208. } else if (!strcmp(name, "nc")) {
  6209. ah->nc = value;
  6210. } else if (!strcmp(name, "nonce")) {
  6211. ah->nonce = value;
  6212. }
  6213. }
  6214. #ifndef NO_NONCE_CHECK
  6215. /* Read the nonce from the response. */
  6216. if (ah->nonce == NULL) {
  6217. return 0;
  6218. }
  6219. s = NULL;
  6220. nonce = strtoull(ah->nonce, &s, 10);
  6221. if ((s == NULL) || (*s != 0)) {
  6222. return 0;
  6223. }
  6224. /* Convert the nonce from the client to a number. */
  6225. nonce ^= conn->ctx->auth_nonce_mask;
  6226. /* The converted number corresponds to the time the nounce has been
  6227. * created. This should not be earlier than the server start. */
  6228. /* Server side nonce check is valuable in all situations but one:
  6229. * if the server restarts frequently, but the client should not see
  6230. * that, so the server should accept nonces from previous starts. */
  6231. /* However, the reasonable default is to not accept a nonce from a
  6232. * previous start, so if anyone changed the access rights between
  6233. * two restarts, a new login is required. */
  6234. if (nonce < (uint64_t)conn->ctx->start_time) {
  6235. /* nonce is from a previous start of the server and no longer valid
  6236. * (replay attack?) */
  6237. return 0;
  6238. }
  6239. /* Check if the nonce is too high, so it has not (yet) been used by the
  6240. * server. */
  6241. if (nonce >= ((uint64_t)conn->ctx->start_time + conn->ctx->nonce_count)) {
  6242. return 0;
  6243. }
  6244. #else
  6245. (void)nonce;
  6246. #endif
  6247. /* CGI needs it as REMOTE_USER */
  6248. if (ah->user != NULL) {
  6249. conn->request_info.remote_user = mg_strdup(ah->user);
  6250. } else {
  6251. return 0;
  6252. }
  6253. return 1;
  6254. }
  6255. static const char *
  6256. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  6257. {
  6258. const char *eof;
  6259. size_t len;
  6260. const char *memend;
  6261. if (!filep) {
  6262. return NULL;
  6263. }
  6264. if ((filep->access.membuf != NULL) && (*p != NULL)) {
  6265. memend = (const char *)&filep->access.membuf[filep->stat.size];
  6266. /* Search for \n from p till the end of stream */
  6267. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  6268. if (eof != NULL) {
  6269. eof += 1; /* Include \n */
  6270. } else {
  6271. eof = memend; /* Copy remaining data */
  6272. }
  6273. len =
  6274. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  6275. memcpy(buf, *p, len);
  6276. buf[len] = '\0';
  6277. *p += len;
  6278. return len ? eof : NULL;
  6279. } else if (filep->access.fp != NULL) {
  6280. return fgets(buf, (int)size, filep->access.fp);
  6281. } else {
  6282. return NULL;
  6283. }
  6284. }
  6285. /* Define the initial recursion depth for procesesing htpasswd files that
  6286. * include other htpasswd
  6287. * (or even the same) files. It is not difficult to provide a file or files
  6288. * s.t. they force civetweb
  6289. * to infinitely recurse and then crash.
  6290. */
  6291. #define INITIAL_DEPTH 9
  6292. #if INITIAL_DEPTH <= 0
  6293. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  6294. #endif
  6295. struct read_auth_file_struct {
  6296. struct mg_connection *conn;
  6297. struct ah ah;
  6298. char *domain;
  6299. char buf[256 + 256 + 40];
  6300. char *f_user;
  6301. char *f_domain;
  6302. char *f_ha1;
  6303. };
  6304. static int
  6305. read_auth_file(struct mg_file *filep,
  6306. struct read_auth_file_struct *workdata,
  6307. int depth)
  6308. {
  6309. char *p;
  6310. int is_authorized = 0;
  6311. struct mg_file fp;
  6312. size_t l;
  6313. if (!filep || !workdata || (0 == depth)) {
  6314. return 0;
  6315. }
  6316. /* Loop over passwords file */
  6317. p = (char *)filep->access.membuf;
  6318. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  6319. l = strlen(workdata->buf);
  6320. while (l > 0) {
  6321. if (isspace(workdata->buf[l - 1])
  6322. || iscntrl(workdata->buf[l - 1])) {
  6323. l--;
  6324. workdata->buf[l] = 0;
  6325. } else
  6326. break;
  6327. }
  6328. if (l < 1) {
  6329. continue;
  6330. }
  6331. workdata->f_user = workdata->buf;
  6332. if (workdata->f_user[0] == ':') {
  6333. /* user names may not contain a ':' and may not be empty,
  6334. * so lines starting with ':' may be used for a special purpose
  6335. */
  6336. if (workdata->f_user[1] == '#') {
  6337. /* :# is a comment */
  6338. continue;
  6339. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  6340. if (mg_fopen(workdata->conn,
  6341. workdata->f_user + 9,
  6342. MG_FOPEN_MODE_READ,
  6343. &fp)) {
  6344. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  6345. (void)mg_fclose(
  6346. &fp.access); /* ignore error on read only file */
  6347. /* No need to continue processing files once we have a
  6348. * match, since nothing will reset it back
  6349. * to 0.
  6350. */
  6351. if (is_authorized) {
  6352. return is_authorized;
  6353. }
  6354. } else {
  6355. mg_cry(workdata->conn,
  6356. "%s: cannot open authorization file: %s",
  6357. __func__,
  6358. workdata->buf);
  6359. }
  6360. continue;
  6361. }
  6362. /* everything is invalid for the moment (might change in the
  6363. * future) */
  6364. mg_cry(workdata->conn,
  6365. "%s: syntax error in authorization file: %s",
  6366. __func__,
  6367. workdata->buf);
  6368. continue;
  6369. }
  6370. workdata->f_domain = strchr(workdata->f_user, ':');
  6371. if (workdata->f_domain == NULL) {
  6372. mg_cry(workdata->conn,
  6373. "%s: syntax error in authorization file: %s",
  6374. __func__,
  6375. workdata->buf);
  6376. continue;
  6377. }
  6378. *(workdata->f_domain) = 0;
  6379. (workdata->f_domain)++;
  6380. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  6381. if (workdata->f_ha1 == NULL) {
  6382. mg_cry(workdata->conn,
  6383. "%s: syntax error in authorization file: %s",
  6384. __func__,
  6385. workdata->buf);
  6386. continue;
  6387. }
  6388. *(workdata->f_ha1) = 0;
  6389. (workdata->f_ha1)++;
  6390. if (!strcmp(workdata->ah.user, workdata->f_user)
  6391. && !strcmp(workdata->domain, workdata->f_domain)) {
  6392. return check_password(workdata->conn->request_info.request_method,
  6393. workdata->f_ha1,
  6394. workdata->ah.uri,
  6395. workdata->ah.nonce,
  6396. workdata->ah.nc,
  6397. workdata->ah.cnonce,
  6398. workdata->ah.qop,
  6399. workdata->ah.response);
  6400. }
  6401. }
  6402. return is_authorized;
  6403. }
  6404. /* Authorize against the opened passwords file. Return 1 if authorized. */
  6405. static int
  6406. authorize(struct mg_connection *conn, struct mg_file *filep)
  6407. {
  6408. struct read_auth_file_struct workdata;
  6409. char buf[MG_BUF_LEN];
  6410. if (!conn || !conn->ctx) {
  6411. return 0;
  6412. }
  6413. memset(&workdata, 0, sizeof(workdata));
  6414. workdata.conn = conn;
  6415. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  6416. return 0;
  6417. }
  6418. workdata.domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  6419. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  6420. }
  6421. /* Return 1 if request is authorised, 0 otherwise. */
  6422. static int
  6423. check_authorization(struct mg_connection *conn, const char *path)
  6424. {
  6425. char fname[PATH_MAX];
  6426. struct vec uri_vec, filename_vec;
  6427. const char *list;
  6428. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6429. int authorized = 1, truncated;
  6430. if (!conn || !conn->ctx) {
  6431. return 0;
  6432. }
  6433. list = conn->ctx->config[PROTECT_URI];
  6434. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  6435. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  6436. mg_snprintf(conn,
  6437. &truncated,
  6438. fname,
  6439. sizeof(fname),
  6440. "%.*s",
  6441. (int)filename_vec.len,
  6442. filename_vec.ptr);
  6443. if (truncated
  6444. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  6445. mg_cry(conn,
  6446. "%s: cannot open %s: %s",
  6447. __func__,
  6448. fname,
  6449. strerror(errno));
  6450. }
  6451. break;
  6452. }
  6453. }
  6454. if (!is_file_opened(&file.access)) {
  6455. open_auth_file(conn, path, &file);
  6456. }
  6457. if (is_file_opened(&file.access)) {
  6458. authorized = authorize(conn, &file);
  6459. (void)mg_fclose(&file.access); /* ignore error on read only file */
  6460. }
  6461. return authorized;
  6462. }
  6463. static void
  6464. send_authorization_request(struct mg_connection *conn)
  6465. {
  6466. char date[64];
  6467. time_t curtime = time(NULL);
  6468. if (conn && conn->ctx) {
  6469. uint64_t nonce = (uint64_t)(conn->ctx->start_time);
  6470. (void)pthread_mutex_lock(&conn->ctx->nonce_mutex);
  6471. nonce += conn->ctx->nonce_count;
  6472. ++conn->ctx->nonce_count;
  6473. (void)pthread_mutex_unlock(&conn->ctx->nonce_mutex);
  6474. nonce ^= conn->ctx->auth_nonce_mask;
  6475. conn->status_code = 401;
  6476. conn->must_close = 1;
  6477. gmt_time_string(date, sizeof(date), &curtime);
  6478. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  6479. send_no_cache_header(conn);
  6480. send_additional_header(conn);
  6481. mg_printf(conn,
  6482. "Date: %s\r\n"
  6483. "Connection: %s\r\n"
  6484. "Content-Length: 0\r\n"
  6485. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  6486. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  6487. date,
  6488. suggest_connection_header(conn),
  6489. conn->ctx->config[AUTHENTICATION_DOMAIN],
  6490. nonce);
  6491. }
  6492. }
  6493. #if !defined(NO_FILES)
  6494. static int
  6495. is_authorized_for_put(struct mg_connection *conn)
  6496. {
  6497. if (conn) {
  6498. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6499. const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
  6500. int ret = 0;
  6501. if (passfile != NULL
  6502. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  6503. ret = authorize(conn, &file);
  6504. (void)mg_fclose(&file.access); /* ignore error on read only file */
  6505. }
  6506. return ret;
  6507. }
  6508. return 0;
  6509. }
  6510. #endif
  6511. int
  6512. mg_modify_passwords_file(const char *fname,
  6513. const char *domain,
  6514. const char *user,
  6515. const char *pass)
  6516. {
  6517. int found, i;
  6518. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  6519. FILE *fp, *fp2;
  6520. found = 0;
  6521. fp = fp2 = NULL;
  6522. /* Regard empty password as no password - remove user record. */
  6523. if ((pass != NULL) && (pass[0] == '\0')) {
  6524. pass = NULL;
  6525. }
  6526. /* Other arguments must not be empty */
  6527. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  6528. return 0;
  6529. }
  6530. /* Using the given file format, user name and domain must not contain
  6531. * ':'
  6532. */
  6533. if (strchr(user, ':') != NULL) {
  6534. return 0;
  6535. }
  6536. if (strchr(domain, ':') != NULL) {
  6537. return 0;
  6538. }
  6539. /* Do not allow control characters like newline in user name and domain.
  6540. * Do not allow excessively long names either. */
  6541. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  6542. if (iscntrl(user[i])) {
  6543. return 0;
  6544. }
  6545. }
  6546. if (user[i]) {
  6547. return 0;
  6548. }
  6549. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  6550. if (iscntrl(domain[i])) {
  6551. return 0;
  6552. }
  6553. }
  6554. if (domain[i]) {
  6555. return 0;
  6556. }
  6557. /* The maximum length of the path to the password file is limited */
  6558. if ((strlen(fname) + 4) >= PATH_MAX) {
  6559. return 0;
  6560. }
  6561. /* Create a temporary file name. Length has been checked before. */
  6562. strcpy(tmp, fname);
  6563. strcat(tmp, ".tmp");
  6564. /* Create the file if does not exist */
  6565. /* Use of fopen here is OK, since fname is only ASCII */
  6566. if ((fp = fopen(fname, "a+")) != NULL) {
  6567. (void)fclose(fp);
  6568. }
  6569. /* Open the given file and temporary file */
  6570. if ((fp = fopen(fname, "r")) == NULL) {
  6571. return 0;
  6572. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  6573. fclose(fp);
  6574. return 0;
  6575. }
  6576. /* Copy the stuff to temporary file */
  6577. while (fgets(line, sizeof(line), fp) != NULL) {
  6578. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  6579. continue;
  6580. }
  6581. u[255] = 0;
  6582. d[255] = 0;
  6583. if (!strcmp(u, user) && !strcmp(d, domain)) {
  6584. found++;
  6585. if (pass != NULL) {
  6586. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  6587. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  6588. }
  6589. } else {
  6590. fprintf(fp2, "%s", line);
  6591. }
  6592. }
  6593. /* If new user, just add it */
  6594. if (!found && (pass != NULL)) {
  6595. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  6596. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  6597. }
  6598. /* Close files */
  6599. fclose(fp);
  6600. fclose(fp2);
  6601. /* Put the temp file in place of real file */
  6602. IGNORE_UNUSED_RESULT(remove(fname));
  6603. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  6604. return 1;
  6605. }
  6606. static int
  6607. is_valid_port(unsigned long port)
  6608. {
  6609. return (port <= 0xffff);
  6610. }
  6611. static int
  6612. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  6613. {
  6614. struct addrinfo hints, *res, *ressave;
  6615. int func_ret = 0;
  6616. int gai_ret;
  6617. memset(&hints, 0, sizeof(struct addrinfo));
  6618. hints.ai_family = af;
  6619. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  6620. if (gai_ret != 0) {
  6621. /* gai_strerror could be used to convert gai_ret to a string */
  6622. /* POSIX return values: see
  6623. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  6624. */
  6625. /* Windows return values: see
  6626. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  6627. */
  6628. return 0;
  6629. }
  6630. ressave = res;
  6631. while (res) {
  6632. if (dstlen >= (size_t)res->ai_addrlen) {
  6633. memcpy(dst, res->ai_addr, res->ai_addrlen);
  6634. func_ret = 1;
  6635. }
  6636. res = res->ai_next;
  6637. }
  6638. freeaddrinfo(ressave);
  6639. return func_ret;
  6640. }
  6641. static int
  6642. connect_socket(struct mg_context *ctx /* may be NULL */,
  6643. const char *host,
  6644. int port,
  6645. int use_ssl,
  6646. char *ebuf,
  6647. size_t ebuf_len,
  6648. SOCKET *sock /* output: socket, must not be NULL */,
  6649. union usa *sa /* output: socket address, must not be NULL */
  6650. )
  6651. {
  6652. int ip_ver = 0;
  6653. *sock = INVALID_SOCKET;
  6654. memset(sa, 0, sizeof(*sa));
  6655. if (ebuf_len > 0) {
  6656. *ebuf = 0;
  6657. }
  6658. if (host == NULL) {
  6659. mg_snprintf(NULL,
  6660. NULL, /* No truncation check for ebuf */
  6661. ebuf,
  6662. ebuf_len,
  6663. "%s",
  6664. "NULL host");
  6665. return 0;
  6666. }
  6667. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  6668. mg_snprintf(NULL,
  6669. NULL, /* No truncation check for ebuf */
  6670. ebuf,
  6671. ebuf_len,
  6672. "%s",
  6673. "invalid port");
  6674. return 0;
  6675. }
  6676. #if !defined(NO_SSL)
  6677. #if !defined(NO_SSL_DL)
  6678. #ifdef OPENSSL_API_1_1
  6679. if (use_ssl && (TLS_client_method == NULL)) {
  6680. mg_snprintf(NULL,
  6681. NULL, /* No truncation check for ebuf */
  6682. ebuf,
  6683. ebuf_len,
  6684. "%s",
  6685. "SSL is not initialized");
  6686. return 0;
  6687. }
  6688. #else
  6689. if (use_ssl && (SSLv23_client_method == NULL)) {
  6690. mg_snprintf(NULL,
  6691. NULL, /* No truncation check for ebuf */
  6692. ebuf,
  6693. ebuf_len,
  6694. "%s",
  6695. "SSL is not initialized");
  6696. return 0;
  6697. }
  6698. #endif /* OPENSSL_API_1_1 */
  6699. #else
  6700. (void)use_ssl;
  6701. #endif /* NO_SSL_DL */
  6702. #else
  6703. (void)use_ssl;
  6704. #endif /* !defined(NO_SSL) */
  6705. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  6706. sa->sin.sin_family = AF_INET;
  6707. sa->sin.sin_port = htons((uint16_t)port);
  6708. ip_ver = 4;
  6709. #ifdef USE_IPV6
  6710. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  6711. sa->sin6.sin6_family = AF_INET6;
  6712. sa->sin6.sin6_port = htons((uint16_t)port);
  6713. ip_ver = 6;
  6714. } else if (host[0] == '[') {
  6715. /* While getaddrinfo on Windows will work with [::1],
  6716. * getaddrinfo on Linux only works with ::1 (without []). */
  6717. size_t l = strlen(host + 1);
  6718. char *h = (l > 1) ? mg_strdup(host + 1) : NULL;
  6719. if (h) {
  6720. h[l - 1] = 0;
  6721. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  6722. sa->sin6.sin6_family = AF_INET6;
  6723. sa->sin6.sin6_port = htons((uint16_t)port);
  6724. ip_ver = 6;
  6725. }
  6726. mg_free(h);
  6727. }
  6728. #endif
  6729. }
  6730. if (ip_ver == 0) {
  6731. mg_snprintf(NULL,
  6732. NULL, /* No truncation check for ebuf */
  6733. ebuf,
  6734. ebuf_len,
  6735. "%s",
  6736. "host not found");
  6737. return 0;
  6738. }
  6739. if (ip_ver == 4) {
  6740. *sock = socket(PF_INET, SOCK_STREAM, 0);
  6741. }
  6742. #ifdef USE_IPV6
  6743. else if (ip_ver == 6) {
  6744. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  6745. }
  6746. #endif
  6747. if (*sock == INVALID_SOCKET) {
  6748. mg_snprintf(NULL,
  6749. NULL, /* No truncation check for ebuf */
  6750. ebuf,
  6751. ebuf_len,
  6752. "socket(): %s",
  6753. strerror(ERRNO));
  6754. return 0;
  6755. }
  6756. set_close_on_exec(*sock, fc(ctx));
  6757. if ((ip_ver == 4)
  6758. && (connect(*sock, (struct sockaddr *)&sa->sin, sizeof(sa->sin))
  6759. == 0)) {
  6760. /* connected with IPv4 */
  6761. set_blocking_mode(*sock, 0);
  6762. return 1;
  6763. }
  6764. #ifdef USE_IPV6
  6765. if ((ip_ver == 6)
  6766. && (connect(*sock, (struct sockaddr *)&sa->sin6, sizeof(sa->sin6))
  6767. == 0)) {
  6768. /* connected with IPv6 */
  6769. set_blocking_mode(*sock, 0);
  6770. return 1;
  6771. }
  6772. #endif
  6773. /* Not connected */
  6774. mg_snprintf(NULL,
  6775. NULL, /* No truncation check for ebuf */
  6776. ebuf,
  6777. ebuf_len,
  6778. "connect(%s:%d): %s",
  6779. host,
  6780. port,
  6781. strerror(ERRNO));
  6782. closesocket(*sock);
  6783. *sock = INVALID_SOCKET;
  6784. return 0;
  6785. }
  6786. int
  6787. mg_url_encode(const char *src, char *dst, size_t dst_len)
  6788. {
  6789. static const char *dont_escape = "._-$,;~()";
  6790. static const char *hex = "0123456789abcdef";
  6791. char *pos = dst;
  6792. const char *end = dst + dst_len - 1;
  6793. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  6794. if (isalnum(*(const unsigned char *)src)
  6795. || (strchr(dont_escape, *(const unsigned char *)src) != NULL)) {
  6796. *pos = *src;
  6797. } else if (pos + 2 < end) {
  6798. pos[0] = '%';
  6799. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  6800. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  6801. pos += 2;
  6802. } else {
  6803. break;
  6804. }
  6805. }
  6806. *pos = '\0';
  6807. return (*src == '\0') ? (int)(pos - dst) : -1;
  6808. }
  6809. /* Return 0 on success, non-zero if an error occurs. */
  6810. static int
  6811. print_dir_entry(struct de *de)
  6812. {
  6813. size_t hrefsize;
  6814. char *href;
  6815. char size[64], mod[64];
  6816. struct tm *tm;
  6817. hrefsize = PATH_MAX * 3; /* worst case */
  6818. href = mg_malloc(hrefsize);
  6819. if (href == NULL) {
  6820. return -1;
  6821. }
  6822. if (de->file.is_directory) {
  6823. mg_snprintf(de->conn,
  6824. NULL, /* Buffer is big enough */
  6825. size,
  6826. sizeof(size),
  6827. "%s",
  6828. "[DIRECTORY]");
  6829. } else {
  6830. /* We use (signed) cast below because MSVC 6 compiler cannot
  6831. * convert unsigned __int64 to double. Sigh. */
  6832. if (de->file.size < 1024) {
  6833. mg_snprintf(de->conn,
  6834. NULL, /* Buffer is big enough */
  6835. size,
  6836. sizeof(size),
  6837. "%d",
  6838. (int)de->file.size);
  6839. } else if (de->file.size < 0x100000) {
  6840. mg_snprintf(de->conn,
  6841. NULL, /* Buffer is big enough */
  6842. size,
  6843. sizeof(size),
  6844. "%.1fk",
  6845. (double)de->file.size / 1024.0);
  6846. } else if (de->file.size < 0x40000000) {
  6847. mg_snprintf(de->conn,
  6848. NULL, /* Buffer is big enough */
  6849. size,
  6850. sizeof(size),
  6851. "%.1fM",
  6852. (double)de->file.size / 1048576);
  6853. } else {
  6854. mg_snprintf(de->conn,
  6855. NULL, /* Buffer is big enough */
  6856. size,
  6857. sizeof(size),
  6858. "%.1fG",
  6859. (double)de->file.size / 1073741824);
  6860. }
  6861. }
  6862. /* Note: mg_snprintf will not cause a buffer overflow above.
  6863. * So, string truncation checks are not required here. */
  6864. tm = localtime(&de->file.last_modified);
  6865. if (tm != NULL) {
  6866. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  6867. } else {
  6868. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  6869. mod[sizeof(mod) - 1] = '\0';
  6870. }
  6871. mg_url_encode(de->file_name, href, hrefsize);
  6872. mg_printf(de->conn,
  6873. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  6874. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  6875. de->conn->request_info.local_uri,
  6876. href,
  6877. de->file.is_directory ? "/" : "",
  6878. de->file_name,
  6879. de->file.is_directory ? "/" : "",
  6880. mod,
  6881. size);
  6882. mg_free(href);
  6883. return 0;
  6884. }
  6885. /* This function is called from send_directory() and used for
  6886. * sorting directory entries by size, or name, or modification time.
  6887. * On windows, __cdecl specification is needed in case if project is built
  6888. * with __stdcall convention. qsort always requires __cdels callback. */
  6889. static int WINCDECL
  6890. compare_dir_entries(const void *p1, const void *p2)
  6891. {
  6892. if (p1 && p2) {
  6893. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  6894. const char *query_string = a->conn->request_info.query_string;
  6895. int cmp_result = 0;
  6896. if (query_string == NULL) {
  6897. query_string = "na";
  6898. }
  6899. if (a->file.is_directory && !b->file.is_directory) {
  6900. return -1; /* Always put directories on top */
  6901. } else if (!a->file.is_directory && b->file.is_directory) {
  6902. return 1; /* Always put directories on top */
  6903. } else if (*query_string == 'n') {
  6904. cmp_result = strcmp(a->file_name, b->file_name);
  6905. } else if (*query_string == 's') {
  6906. cmp_result = (a->file.size == b->file.size)
  6907. ? 0
  6908. : ((a->file.size > b->file.size) ? 1 : -1);
  6909. } else if (*query_string == 'd') {
  6910. cmp_result =
  6911. (a->file.last_modified == b->file.last_modified)
  6912. ? 0
  6913. : ((a->file.last_modified > b->file.last_modified) ? 1
  6914. : -1);
  6915. }
  6916. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  6917. }
  6918. return 0;
  6919. }
  6920. static int
  6921. must_hide_file(struct mg_connection *conn, const char *path)
  6922. {
  6923. if (conn && conn->ctx) {
  6924. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  6925. const char *pattern = conn->ctx->config[HIDE_FILES];
  6926. return (match_prefix(pw_pattern, strlen(pw_pattern), path) > 0)
  6927. || ((pattern != NULL)
  6928. && (match_prefix(pattern, strlen(pattern), path) > 0));
  6929. }
  6930. return 0;
  6931. }
  6932. static int
  6933. scan_directory(struct mg_connection *conn,
  6934. const char *dir,
  6935. void *data,
  6936. int (*cb)(struct de *, void *))
  6937. {
  6938. char path[PATH_MAX];
  6939. struct dirent *dp;
  6940. DIR *dirp;
  6941. struct de de;
  6942. int truncated;
  6943. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  6944. return 0;
  6945. } else {
  6946. de.conn = conn;
  6947. while ((dp = mg_readdir(dirp)) != NULL) {
  6948. /* Do not show current dir and hidden files */
  6949. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  6950. || must_hide_file(conn, dp->d_name)) {
  6951. continue;
  6952. }
  6953. mg_snprintf(
  6954. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  6955. /* If we don't memset stat structure to zero, mtime will have
  6956. * garbage and strftime() will segfault later on in
  6957. * print_dir_entry(). memset is required only if mg_stat()
  6958. * fails. For more details, see
  6959. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  6960. memset(&de.file, 0, sizeof(de.file));
  6961. if (truncated) {
  6962. /* If the path is not complete, skip processing. */
  6963. continue;
  6964. }
  6965. if (!mg_stat(conn, path, &de.file)) {
  6966. mg_cry(conn,
  6967. "%s: mg_stat(%s) failed: %s",
  6968. __func__,
  6969. path,
  6970. strerror(ERRNO));
  6971. }
  6972. de.file_name = dp->d_name;
  6973. cb(&de, data);
  6974. }
  6975. (void)mg_closedir(dirp);
  6976. }
  6977. return 1;
  6978. }
  6979. #if !defined(NO_FILES)
  6980. static int
  6981. remove_directory(struct mg_connection *conn, const char *dir)
  6982. {
  6983. char path[PATH_MAX];
  6984. struct dirent *dp;
  6985. DIR *dirp;
  6986. struct de de;
  6987. int truncated;
  6988. int ok = 1;
  6989. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  6990. return 0;
  6991. } else {
  6992. de.conn = conn;
  6993. while ((dp = mg_readdir(dirp)) != NULL) {
  6994. /* Do not show current dir (but show hidden files as they will
  6995. * also be removed) */
  6996. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  6997. continue;
  6998. }
  6999. mg_snprintf(
  7000. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  7001. /* If we don't memset stat structure to zero, mtime will have
  7002. * garbage and strftime() will segfault later on in
  7003. * print_dir_entry(). memset is required only if mg_stat()
  7004. * fails. For more details, see
  7005. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  7006. memset(&de.file, 0, sizeof(de.file));
  7007. if (truncated) {
  7008. /* Do not delete anything shorter */
  7009. ok = 0;
  7010. continue;
  7011. }
  7012. if (!mg_stat(conn, path, &de.file)) {
  7013. mg_cry(conn,
  7014. "%s: mg_stat(%s) failed: %s",
  7015. __func__,
  7016. path,
  7017. strerror(ERRNO));
  7018. ok = 0;
  7019. }
  7020. if (de.file.is_directory) {
  7021. if (remove_directory(conn, path) == 0) {
  7022. ok = 0;
  7023. }
  7024. } else {
  7025. /* This will fail file is the file is in memory */
  7026. if (mg_remove(conn, path) == 0) {
  7027. ok = 0;
  7028. }
  7029. }
  7030. }
  7031. (void)mg_closedir(dirp);
  7032. IGNORE_UNUSED_RESULT(rmdir(dir));
  7033. }
  7034. return ok;
  7035. }
  7036. #endif
  7037. struct dir_scan_data {
  7038. struct de *entries;
  7039. unsigned int num_entries;
  7040. unsigned int arr_size;
  7041. };
  7042. /* Behaves like realloc(), but frees original pointer on failure */
  7043. static void *
  7044. realloc2(void *ptr, size_t size)
  7045. {
  7046. void *new_ptr = mg_realloc(ptr, size);
  7047. if (new_ptr == NULL) {
  7048. mg_free(ptr);
  7049. }
  7050. return new_ptr;
  7051. }
  7052. static int
  7053. dir_scan_callback(struct de *de, void *data)
  7054. {
  7055. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  7056. if ((dsd->entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  7057. dsd->arr_size *= 2;
  7058. dsd->entries =
  7059. (struct de *)realloc2(dsd->entries,
  7060. dsd->arr_size * sizeof(dsd->entries[0]));
  7061. }
  7062. if (dsd->entries == NULL) {
  7063. /* TODO(lsm, low): propagate an error to the caller */
  7064. dsd->num_entries = 0;
  7065. } else {
  7066. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  7067. dsd->entries[dsd->num_entries].file = de->file;
  7068. dsd->entries[dsd->num_entries].conn = de->conn;
  7069. dsd->num_entries++;
  7070. }
  7071. return 0;
  7072. }
  7073. static void
  7074. handle_directory_request(struct mg_connection *conn, const char *dir)
  7075. {
  7076. unsigned int i;
  7077. int sort_direction;
  7078. struct dir_scan_data data = {NULL, 0, 128};
  7079. char date[64];
  7080. time_t curtime = time(NULL);
  7081. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  7082. mg_send_http_error(conn,
  7083. 500,
  7084. "Error: Cannot open directory\nopendir(%s): %s",
  7085. dir,
  7086. strerror(ERRNO));
  7087. return;
  7088. }
  7089. gmt_time_string(date, sizeof(date), &curtime);
  7090. if (!conn) {
  7091. return;
  7092. }
  7093. sort_direction = ((conn->request_info.query_string != NULL)
  7094. && (conn->request_info.query_string[1] == 'd'))
  7095. ? 'a'
  7096. : 'd';
  7097. conn->must_close = 1;
  7098. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  7099. send_static_cache_header(conn);
  7100. send_additional_header(conn);
  7101. mg_printf(conn,
  7102. "Date: %s\r\n"
  7103. "Connection: close\r\n"
  7104. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  7105. date);
  7106. mg_printf(conn,
  7107. "<html><head><title>Index of %s</title>"
  7108. "<style>th {text-align: left;}</style></head>"
  7109. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  7110. "<tr><th><a href=\"?n%c\">Name</a></th>"
  7111. "<th><a href=\"?d%c\">Modified</a></th>"
  7112. "<th><a href=\"?s%c\">Size</a></th></tr>"
  7113. "<tr><td colspan=\"3\"><hr></td></tr>",
  7114. conn->request_info.local_uri,
  7115. conn->request_info.local_uri,
  7116. sort_direction,
  7117. sort_direction,
  7118. sort_direction);
  7119. /* Print first entry - link to a parent directory */
  7120. mg_printf(conn,
  7121. "<tr><td><a href=\"%s%s\">%s</a></td>"
  7122. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  7123. conn->request_info.local_uri,
  7124. "..",
  7125. "Parent directory",
  7126. "-",
  7127. "-");
  7128. /* Sort and print directory entries */
  7129. if (data.entries != NULL) {
  7130. qsort(data.entries,
  7131. (size_t)data.num_entries,
  7132. sizeof(data.entries[0]),
  7133. compare_dir_entries);
  7134. for (i = 0; i < data.num_entries; i++) {
  7135. print_dir_entry(&data.entries[i]);
  7136. mg_free(data.entries[i].file_name);
  7137. }
  7138. mg_free(data.entries);
  7139. }
  7140. mg_printf(conn, "%s", "</table></body></html>");
  7141. conn->status_code = 200;
  7142. }
  7143. /* Send len bytes from the opened file to the client. */
  7144. static void
  7145. send_file_data(struct mg_connection *conn,
  7146. struct mg_file *filep,
  7147. int64_t offset,
  7148. int64_t len)
  7149. {
  7150. char buf[MG_BUF_LEN];
  7151. int to_read, num_read, num_written;
  7152. int64_t size;
  7153. if (!filep || !conn) {
  7154. return;
  7155. }
  7156. /* Sanity check the offset */
  7157. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  7158. : (int64_t)(filep->stat.size);
  7159. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  7160. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  7161. /* file stored in memory */
  7162. if (len > size - offset) {
  7163. len = size - offset;
  7164. }
  7165. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  7166. } else if (len > 0 && filep->access.fp != NULL) {
  7167. /* file stored on disk */
  7168. #if defined(__linux__)
  7169. /* sendfile is only available for Linux */
  7170. if ((conn->ssl == 0) && (conn->throttle == 0)
  7171. && (!mg_strcasecmp(conn->ctx->config[ALLOW_SENDFILE_CALL],
  7172. "yes"))) {
  7173. off_t sf_offs = (off_t)offset;
  7174. ssize_t sf_sent;
  7175. int sf_file = fileno(filep->access.fp);
  7176. int loop_cnt = 0;
  7177. do {
  7178. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  7179. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  7180. size_t sf_tosend =
  7181. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  7182. sf_sent =
  7183. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  7184. if (sf_sent > 0) {
  7185. len -= sf_sent;
  7186. offset += sf_sent;
  7187. } else if (loop_cnt == 0) {
  7188. /* This file can not be sent using sendfile.
  7189. * This might be the case for pseudo-files in the
  7190. * /sys/ and /proc/ file system.
  7191. * Use the regular user mode copy code instead. */
  7192. break;
  7193. } else if (sf_sent == 0) {
  7194. /* No error, but 0 bytes sent. May be EOF? */
  7195. return;
  7196. }
  7197. loop_cnt++;
  7198. } while ((len > 0) && (sf_sent >= 0));
  7199. if (sf_sent > 0) {
  7200. return; /* OK */
  7201. }
  7202. /* sf_sent<0 means error, thus fall back to the classic way */
  7203. /* This is always the case, if sf_file is not a "normal" file,
  7204. * e.g., for sending data from the output of a CGI process. */
  7205. offset = (int64_t)sf_offs;
  7206. }
  7207. #endif
  7208. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  7209. mg_cry(conn, "%s: fseeko() failed: %s", __func__, strerror(ERRNO));
  7210. mg_send_http_error(
  7211. conn,
  7212. 500,
  7213. "%s",
  7214. "Error: Unable to access file at requested position.");
  7215. } else {
  7216. while (len > 0) {
  7217. /* Calculate how much to read from the file in the buffer */
  7218. to_read = sizeof(buf);
  7219. if ((int64_t)to_read > len) {
  7220. to_read = (int)len;
  7221. }
  7222. /* Read from file, exit the loop on error */
  7223. if ((num_read =
  7224. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  7225. <= 0) {
  7226. break;
  7227. }
  7228. /* Send read bytes to the client, exit the loop on error */
  7229. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  7230. != num_read) {
  7231. break;
  7232. }
  7233. /* Both read and were successful, adjust counters */
  7234. len -= num_written;
  7235. }
  7236. }
  7237. }
  7238. }
  7239. static int
  7240. parse_range_header(const char *header, int64_t *a, int64_t *b)
  7241. {
  7242. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  7243. }
  7244. static void
  7245. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  7246. {
  7247. if ((filestat != NULL) && (buf != NULL)) {
  7248. mg_snprintf(NULL,
  7249. NULL, /* All calls to construct_etag use 64 byte buffer */
  7250. buf,
  7251. buf_len,
  7252. "\"%lx.%" INT64_FMT "\"",
  7253. (unsigned long)filestat->last_modified,
  7254. filestat->size);
  7255. }
  7256. }
  7257. static void
  7258. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  7259. {
  7260. if (filep != NULL && filep->fp != NULL) {
  7261. #ifdef _WIN32
  7262. (void)conn; /* Unused. */
  7263. #else
  7264. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  7265. mg_cry(conn,
  7266. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  7267. __func__,
  7268. strerror(ERRNO));
  7269. }
  7270. #endif
  7271. }
  7272. }
  7273. static void
  7274. handle_static_file_request(struct mg_connection *conn,
  7275. const char *path,
  7276. struct mg_file *filep,
  7277. const char *mime_type,
  7278. const char *additional_headers)
  7279. {
  7280. char date[64], lm[64], etag[64];
  7281. char range[128]; /* large enough, so there will be no overflow */
  7282. const char *msg = "OK", *hdr;
  7283. time_t curtime = time(NULL);
  7284. int64_t cl, r1, r2;
  7285. struct vec mime_vec;
  7286. int n, truncated;
  7287. char gz_path[PATH_MAX];
  7288. const char *encoding = "";
  7289. const char *cors1, *cors2, *cors3;
  7290. int allow_on_the_fly_compression = conn->accept_gzip;
  7291. if ((conn == NULL) || (conn->ctx == NULL) || (filep == NULL)) {
  7292. return;
  7293. }
  7294. if (mime_type == NULL) {
  7295. get_mime_type(conn->ctx, path, &mime_vec);
  7296. } else {
  7297. mime_vec.ptr = mime_type;
  7298. mime_vec.len = strlen(mime_type);
  7299. }
  7300. if (filep->stat.size > INT64_MAX) {
  7301. mg_send_http_error(conn,
  7302. 500,
  7303. "Error: File size is too large to send\n%" INT64_FMT,
  7304. filep->stat.size);
  7305. return;
  7306. }
  7307. cl = (int64_t)filep->stat.size;
  7308. conn->status_code = 200;
  7309. range[0] = '\0';
  7310. /* if this file is in fact a pre-gzipped file, rewrite its filename
  7311. * it's important to rewrite the filename after resolving
  7312. * the mime type from it, to preserve the actual file's type */
  7313. if (filep->stat.is_gzipped) {
  7314. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  7315. if (truncated) {
  7316. mg_send_http_error(conn,
  7317. 500,
  7318. "Error: Path of zipped file too long (%s)",
  7319. path);
  7320. return;
  7321. }
  7322. path = gz_path;
  7323. encoding = "Content-Encoding: gzip\r\n";
  7324. /* File is already compressed. No "on the fly" compression. */
  7325. allow_on_the_fly_compression = 0;
  7326. }
  7327. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  7328. mg_send_http_error(conn,
  7329. 500,
  7330. "Error: Cannot open file\nfopen(%s): %s",
  7331. path,
  7332. strerror(ERRNO));
  7333. return;
  7334. }
  7335. fclose_on_exec(&filep->access, conn);
  7336. /* If Range: header specified, act accordingly */
  7337. r1 = r2 = 0;
  7338. hdr = mg_get_header(conn, "Range");
  7339. if ((hdr != NULL) && ((n = parse_range_header(hdr, &r1, &r2)) > 0)
  7340. && (r1 >= 0) && (r2 >= 0)) {
  7341. /* actually, range requests don't play well with a pre-gzipped
  7342. * file (since the range is specified in the uncompressed space) */
  7343. if (filep->stat.is_gzipped) {
  7344. mg_send_http_error(
  7345. conn,
  7346. 416, /* 416 = Range Not Satisfiable */
  7347. "%s",
  7348. "Error: Range requests in gzipped files are not supported");
  7349. (void)mg_fclose(
  7350. &filep->access); /* ignore error on read only file */
  7351. return;
  7352. }
  7353. conn->status_code = 206;
  7354. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  7355. mg_snprintf(conn,
  7356. NULL, /* range buffer is big enough */
  7357. range,
  7358. sizeof(range),
  7359. "Content-Range: bytes "
  7360. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  7361. r1,
  7362. r1 + cl - 1,
  7363. filep->stat.size);
  7364. msg = "Partial Content";
  7365. /* Do not compress ranges. */
  7366. allow_on_the_fly_compression = 0;
  7367. }
  7368. hdr = mg_get_header(conn, "Origin");
  7369. if (hdr) {
  7370. /* Cross-origin resource sharing (CORS), see
  7371. * http://www.html5rocks.com/en/tutorials/cors/,
  7372. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  7373. * -
  7374. * preflight is not supported for files. */
  7375. cors1 = "Access-Control-Allow-Origin: ";
  7376. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  7377. cors3 = "\r\n";
  7378. } else {
  7379. cors1 = cors2 = cors3 = "";
  7380. }
  7381. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC,
  7382. * according to
  7383. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  7384. gmt_time_string(date, sizeof(date), &curtime);
  7385. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  7386. construct_etag(etag, sizeof(etag), &filep->stat);
  7387. /* On the fly compression allowed */
  7388. if (allow_on_the_fly_compression) {
  7389. ;
  7390. /* TODO: add interface to compression module */
  7391. /* e.g., def from https://zlib.net/zlib_how.html */
  7392. /* Check license (zlib has a permissive license, but */
  7393. /* is still not MIT) and use dynamic binding like */
  7394. /* done with OpenSSL */
  7395. /* See #199 (https://github.com/civetweb/civetweb/issues/199) */
  7396. }
  7397. /* Send header */
  7398. (void)mg_printf(conn,
  7399. "HTTP/1.1 %d %s\r\n"
  7400. "%s%s%s"
  7401. "Date: %s\r\n",
  7402. conn->status_code,
  7403. msg,
  7404. cors1,
  7405. cors2,
  7406. cors3,
  7407. date);
  7408. send_static_cache_header(conn);
  7409. send_additional_header(conn);
  7410. (void)mg_printf(conn,
  7411. "Last-Modified: %s\r\n"
  7412. "Etag: %s\r\n"
  7413. "Content-Type: %.*s\r\n"
  7414. "Content-Length: %" INT64_FMT "\r\n"
  7415. "Connection: %s\r\n"
  7416. "Accept-Ranges: bytes\r\n"
  7417. "%s%s",
  7418. lm,
  7419. etag,
  7420. (int)mime_vec.len,
  7421. mime_vec.ptr,
  7422. cl,
  7423. suggest_connection_header(conn),
  7424. range,
  7425. encoding);
  7426. /* The previous code must not add any header starting with X- to make
  7427. * sure no one of the additional_headers is included twice */
  7428. if (additional_headers != NULL) {
  7429. (void)mg_printf(conn,
  7430. "%.*s\r\n\r\n",
  7431. (int)strlen(additional_headers),
  7432. additional_headers);
  7433. } else {
  7434. (void)mg_printf(conn, "\r\n");
  7435. }
  7436. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  7437. send_file_data(conn, filep, r1, cl);
  7438. }
  7439. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  7440. }
  7441. #if !defined(NO_CACHING)
  7442. static void
  7443. handle_not_modified_static_file_request(struct mg_connection *conn,
  7444. struct mg_file *filep)
  7445. {
  7446. char date[64], lm[64], etag[64];
  7447. time_t curtime = time(NULL);
  7448. if ((conn == NULL) || (filep == NULL)) {
  7449. return;
  7450. }
  7451. conn->status_code = 304;
  7452. gmt_time_string(date, sizeof(date), &curtime);
  7453. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  7454. construct_etag(etag, sizeof(etag), &filep->stat);
  7455. (void)mg_printf(conn,
  7456. "HTTP/1.1 %d %s\r\n"
  7457. "Date: %s\r\n",
  7458. conn->status_code,
  7459. mg_get_response_code_text(conn, conn->status_code),
  7460. date);
  7461. send_static_cache_header(conn);
  7462. send_additional_header(conn);
  7463. (void)mg_printf(conn,
  7464. "Last-Modified: %s\r\n"
  7465. "Etag: %s\r\n"
  7466. "Connection: %s\r\n"
  7467. "\r\n",
  7468. lm,
  7469. etag,
  7470. suggest_connection_header(conn));
  7471. }
  7472. #endif
  7473. void
  7474. mg_send_file(struct mg_connection *conn, const char *path)
  7475. {
  7476. mg_send_mime_file(conn, path, NULL);
  7477. }
  7478. void
  7479. mg_send_mime_file(struct mg_connection *conn,
  7480. const char *path,
  7481. const char *mime_type)
  7482. {
  7483. mg_send_mime_file2(conn, path, mime_type, NULL);
  7484. }
  7485. void
  7486. mg_send_mime_file2(struct mg_connection *conn,
  7487. const char *path,
  7488. const char *mime_type,
  7489. const char *additional_headers)
  7490. {
  7491. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7492. if (mg_stat(conn, path, &file.stat)) {
  7493. if (file.stat.is_directory) {
  7494. if (!conn) {
  7495. return;
  7496. }
  7497. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  7498. "yes")) {
  7499. handle_directory_request(conn, path);
  7500. } else {
  7501. mg_send_http_error(conn,
  7502. 403,
  7503. "%s",
  7504. "Error: Directory listing denied");
  7505. }
  7506. } else {
  7507. handle_static_file_request(
  7508. conn, path, &file, mime_type, additional_headers);
  7509. }
  7510. } else {
  7511. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  7512. }
  7513. }
  7514. /* For a given PUT path, create all intermediate subdirectories.
  7515. * Return 0 if the path itself is a directory.
  7516. * Return 1 if the path leads to a file.
  7517. * Return -1 for if the path is too long.
  7518. * Return -2 if path can not be created.
  7519. */
  7520. static int
  7521. put_dir(struct mg_connection *conn, const char *path)
  7522. {
  7523. char buf[PATH_MAX];
  7524. const char *s, *p;
  7525. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7526. size_t len;
  7527. int res = 1;
  7528. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  7529. len = (size_t)(p - path);
  7530. if (len >= sizeof(buf)) {
  7531. /* path too long */
  7532. res = -1;
  7533. break;
  7534. }
  7535. memcpy(buf, path, len);
  7536. buf[len] = '\0';
  7537. /* Try to create intermediate directory */
  7538. DEBUG_TRACE("mkdir(%s)", buf);
  7539. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  7540. /* path does not exixt and can not be created */
  7541. res = -2;
  7542. break;
  7543. }
  7544. /* Is path itself a directory? */
  7545. if (p[1] == '\0') {
  7546. res = 0;
  7547. }
  7548. }
  7549. return res;
  7550. }
  7551. static void
  7552. remove_bad_file(const struct mg_connection *conn, const char *path)
  7553. {
  7554. int r = mg_remove(conn, path);
  7555. if (r != 0) {
  7556. mg_cry(conn, "%s: Cannot remove invalid file %s", __func__, path);
  7557. }
  7558. }
  7559. long long
  7560. mg_store_body(struct mg_connection *conn, const char *path)
  7561. {
  7562. char buf[MG_BUF_LEN];
  7563. long long len = 0;
  7564. int ret, n;
  7565. struct mg_file fi;
  7566. if (conn->consumed_content != 0) {
  7567. mg_cry(conn, "%s: Contents already consumed", __func__);
  7568. return -11;
  7569. }
  7570. ret = put_dir(conn, path);
  7571. if (ret < 0) {
  7572. /* -1 for path too long,
  7573. * -2 for path can not be created. */
  7574. return ret;
  7575. }
  7576. if (ret != 1) {
  7577. /* Return 0 means, path itself is a directory. */
  7578. return 0;
  7579. }
  7580. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  7581. return -12;
  7582. }
  7583. ret = mg_read(conn, buf, sizeof(buf));
  7584. while (ret > 0) {
  7585. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  7586. if (n != ret) {
  7587. (void)mg_fclose(
  7588. &fi.access); /* File is bad and will be removed anyway. */
  7589. remove_bad_file(conn, path);
  7590. return -13;
  7591. }
  7592. len += ret;
  7593. ret = mg_read(conn, buf, sizeof(buf));
  7594. }
  7595. /* File is open for writing. If fclose fails, there was probably an
  7596. * error flushing the buffer to disk, so the file on disk might be
  7597. * broken. Delete it and return an error to the caller. */
  7598. if (mg_fclose(&fi.access) != 0) {
  7599. remove_bad_file(conn, path);
  7600. return -14;
  7601. }
  7602. return len;
  7603. }
  7604. /* Parse a buffer:
  7605. * Forward the string pointer till the end of a word, then
  7606. * terminate it and forward till the begin of the next word.
  7607. */
  7608. static int
  7609. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  7610. {
  7611. /* Forward until a space is found - use isgraph here */
  7612. /* See http://www.cplusplus.com/reference/cctype/ */
  7613. while (isgraph(**ppw)) {
  7614. (*ppw)++;
  7615. }
  7616. /* Check end of word */
  7617. if (eol) {
  7618. /* must be a end of line */
  7619. if ((**ppw != '\r') && (**ppw != '\n')) {
  7620. return -1;
  7621. }
  7622. } else {
  7623. /* must be a end of a word, but not a line */
  7624. if (**ppw != ' ') {
  7625. return -1;
  7626. }
  7627. }
  7628. /* Terminate and forward to the next word */
  7629. do {
  7630. **ppw = 0;
  7631. (*ppw)++;
  7632. } while ((**ppw) && isspace(**ppw));
  7633. /* Check after term */
  7634. if (!eol) {
  7635. /* if it's not the end of line, there must be a next word */
  7636. if (!isgraph(**ppw)) {
  7637. return -1;
  7638. }
  7639. }
  7640. /* ok */
  7641. return 1;
  7642. }
  7643. /* Parse HTTP headers from the given buffer, advance buf pointer
  7644. * to the point where parsing stopped.
  7645. * All parameters must be valid pointers (not NULL).
  7646. * Return <0 on error. */
  7647. static int
  7648. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  7649. {
  7650. int i;
  7651. int num_headers = 0;
  7652. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  7653. char *dp = *buf;
  7654. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  7655. dp++;
  7656. }
  7657. if (dp == *buf) {
  7658. /* End of headers reached. */
  7659. break;
  7660. }
  7661. if (*dp != ':') {
  7662. /* This is not a valid field. */
  7663. return -1;
  7664. }
  7665. /* End of header key (*dp == ':') */
  7666. /* Truncate here and set the key name */
  7667. *dp = 0;
  7668. hdr[i].name = *buf;
  7669. do {
  7670. dp++;
  7671. } while (*dp == ' ');
  7672. /* The rest of the line is the value */
  7673. hdr[i].value = dp;
  7674. *buf = dp + strcspn(dp, "\r\n");
  7675. if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) {
  7676. *buf = NULL;
  7677. }
  7678. num_headers = i + 1;
  7679. if (*buf) {
  7680. (*buf)[0] = 0;
  7681. (*buf)[1] = 0;
  7682. *buf += 2;
  7683. } else {
  7684. *buf = dp;
  7685. break;
  7686. }
  7687. if ((*buf)[0] == '\r') {
  7688. /* This is the end of the header */
  7689. break;
  7690. }
  7691. }
  7692. return num_headers;
  7693. }
  7694. static int
  7695. is_valid_http_method(const char *method)
  7696. {
  7697. /* Check if the method is known to the server. The list of all known
  7698. * HTTP methods can be found here at
  7699. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  7700. */
  7701. return !strcmp(method, "GET") /* HTTP (RFC 2616) */
  7702. || !strcmp(method, "POST") /* HTTP (RFC 2616) */
  7703. || !strcmp(method, "HEAD") /* HTTP (RFC 2616) */
  7704. || !strcmp(method, "PUT") /* HTTP (RFC 2616) */
  7705. || !strcmp(method, "DELETE") /* HTTP (RFC 2616) */
  7706. || !strcmp(method, "OPTIONS") /* HTTP (RFC 2616) */
  7707. /* TRACE method (RFC 2616) is not supported for security reasons
  7708. */
  7709. || !strcmp(method, "CONNECT") /* HTTP (RFC 2616) */
  7710. || !strcmp(method, "PROPFIND") /* WEBDAV (RFC 2518) */
  7711. || !strcmp(method, "MKCOL") /* WEBDAV (RFC 2518) */
  7712. /* Unsupported WEBDAV Methods: */
  7713. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  7714. /* + 11 methods from RFC 3253 */
  7715. /* ORDERPATCH (RFC 3648) */
  7716. /* ACL (RFC 3744) */
  7717. /* SEARCH (RFC 5323) */
  7718. /* + MicroSoft extensions
  7719. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  7720. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  7721. || !strcmp(method, "PATCH") /* PATCH method (RFC 5789) */
  7722. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  7723. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  7724. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  7725. * to be useful for REST in case a "GET request with body" is
  7726. * required. */
  7727. || !strcmp(method, "REPORT") /* REPORT method (RFC 3253) */
  7728. ;
  7729. }
  7730. /* Parse HTTP request, fill in mg_request_info structure.
  7731. * This function modifies the buffer by NUL-terminating
  7732. * HTTP request components, header names and header values.
  7733. * Parameters:
  7734. * buf (in/out): pointer to the HTTP header to parse and split
  7735. * len (in): length of HTTP header buffer
  7736. * re (out): parsed header as mg_request_info
  7737. * buf and ri must be valid pointers (not NULL), len>0.
  7738. * Returns <0 on error. */
  7739. static int
  7740. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  7741. {
  7742. int request_length;
  7743. int init_skip = 0;
  7744. /* Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_addr,
  7745. * remote_port */
  7746. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  7747. NULL;
  7748. ri->num_headers = 0;
  7749. /* RFC says that all initial whitespaces should be ingored */
  7750. /* This included all leading \r and \n (isspace) */
  7751. /* See table: http://www.cplusplus.com/reference/cctype/ */
  7752. while ((len > 0) && isspace(*(unsigned char *)buf)) {
  7753. buf++;
  7754. len--;
  7755. init_skip++;
  7756. }
  7757. if (len == 0) {
  7758. /* Incomplete request */
  7759. return 0;
  7760. }
  7761. /* Control characters are not allowed, including zero */
  7762. if (iscntrl(*(unsigned char *)buf)) {
  7763. return -1;
  7764. }
  7765. /* Find end of HTTP header */
  7766. request_length = get_http_header_len(buf, len);
  7767. if (request_length <= 0) {
  7768. return request_length;
  7769. }
  7770. buf[request_length - 1] = '\0';
  7771. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  7772. return -1;
  7773. }
  7774. /* The first word has to be the HTTP method */
  7775. ri->request_method = buf;
  7776. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  7777. return -1;
  7778. }
  7779. /* Check for a valid http method */
  7780. if (!is_valid_http_method(ri->request_method)) {
  7781. return -1;
  7782. }
  7783. /* The second word is the URI */
  7784. ri->request_uri = buf;
  7785. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  7786. return -1;
  7787. }
  7788. /* Next would be the HTTP version */
  7789. ri->http_version = buf;
  7790. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  7791. return -1;
  7792. }
  7793. /* Check for a valid HTTP version key */
  7794. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  7795. /* Invalid request */
  7796. return -1;
  7797. }
  7798. ri->http_version += 5;
  7799. /* Parse all HTTP headers */
  7800. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  7801. if (ri->num_headers < 0) {
  7802. /* Error while parsing headers */
  7803. return -1;
  7804. }
  7805. return request_length + init_skip;
  7806. }
  7807. static int
  7808. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  7809. {
  7810. int response_length;
  7811. int init_skip = 0;
  7812. char *tmp, *tmp2;
  7813. long l;
  7814. /* Initialize elements. */
  7815. ri->http_version = ri->status_text = NULL;
  7816. ri->num_headers = ri->status_code = 0;
  7817. /* RFC says that all initial whitespaces should be ingored */
  7818. /* This included all leading \r and \n (isspace) */
  7819. /* See table: http://www.cplusplus.com/reference/cctype/ */
  7820. while ((len > 0) && isspace(*(unsigned char *)buf)) {
  7821. buf++;
  7822. len--;
  7823. init_skip++;
  7824. }
  7825. if (len == 0) {
  7826. /* Incomplete request */
  7827. return 0;
  7828. }
  7829. /* Control characters are not allowed, including zero */
  7830. if (iscntrl(*(unsigned char *)buf)) {
  7831. return -1;
  7832. }
  7833. /* Find end of HTTP header */
  7834. response_length = get_http_header_len(buf, len);
  7835. if (response_length <= 0) {
  7836. return response_length;
  7837. }
  7838. buf[response_length - 1] = '\0';
  7839. /* TODO: Define mg_response_info and implement parsing */
  7840. (void)buf;
  7841. (void)len;
  7842. (void)ri;
  7843. /* RFC says that all initial whitespaces should be ingored */
  7844. while ((*buf != '\0') && isspace(*(unsigned char *)buf)) {
  7845. buf++;
  7846. }
  7847. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  7848. return -1;
  7849. }
  7850. /* The first word is the HTTP version */
  7851. /* Check for a valid HTTP version key */
  7852. if (strncmp(buf, "HTTP/", 5) != 0) {
  7853. /* Invalid request */
  7854. return -1;
  7855. }
  7856. buf += 5;
  7857. if (!isgraph(buf[0])) {
  7858. /* Invalid request */
  7859. return -1;
  7860. }
  7861. ri->http_version = buf;
  7862. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  7863. return -1;
  7864. }
  7865. /* The second word is the status as a number */
  7866. tmp = buf;
  7867. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  7868. return -1;
  7869. }
  7870. l = strtol(tmp, &tmp2, 10);
  7871. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  7872. /* Everything else but a 3 digit code is invalid */
  7873. return -1;
  7874. }
  7875. ri->status_code = (int)l;
  7876. /* The rest of the line is the status text */
  7877. ri->status_text = buf;
  7878. /* Find end of status text */
  7879. /* isgraph or isspace = isprint */
  7880. while (isprint(*buf)) {
  7881. buf++;
  7882. }
  7883. if ((*buf != '\r') && (*buf != '\n')) {
  7884. return -1;
  7885. }
  7886. /* Terminate string and forward buf to next line */
  7887. do {
  7888. *buf = 0;
  7889. buf++;
  7890. } while ((*buf) && isspace(*buf));
  7891. /* Parse all HTTP headers */
  7892. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  7893. if (ri->num_headers < 0) {
  7894. /* Error while parsing headers */
  7895. return -1;
  7896. }
  7897. return response_length + init_skip;
  7898. }
  7899. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  7900. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  7901. * buffer (which marks the end of HTTP request). Buffer buf may already
  7902. * have some data. The length of the data is stored in nread.
  7903. * Upon every read operation, increase nread by the number of bytes read. */
  7904. static int
  7905. read_message(FILE *fp,
  7906. struct mg_connection *conn,
  7907. char *buf,
  7908. int bufsiz,
  7909. int *nread)
  7910. {
  7911. int request_len, n = 0;
  7912. struct timespec last_action_time;
  7913. double request_timeout;
  7914. if (!conn) {
  7915. return 0;
  7916. }
  7917. memset(&last_action_time, 0, sizeof(last_action_time));
  7918. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  7919. /* value of request_timeout is in seconds, config in milliseconds */
  7920. request_timeout = atof(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  7921. } else {
  7922. request_timeout = -1.0;
  7923. }
  7924. if (conn->handled_requests > 0) {
  7925. if (conn->ctx->config[KEEP_ALIVE_TIMEOUT]) {
  7926. request_timeout =
  7927. atof(conn->ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  7928. }
  7929. }
  7930. request_len = get_http_header_len(buf, *nread);
  7931. /* first time reading from this connection */
  7932. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  7933. while (request_len == 0) {
  7934. /* Full request not yet received */
  7935. if (conn->ctx->stop_flag != 0) {
  7936. /* Server is to be stopped. */
  7937. return -1;
  7938. }
  7939. if (*nread >= bufsiz) {
  7940. /* Request too long */
  7941. return -2;
  7942. }
  7943. n = pull_inner(
  7944. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  7945. if (n == -2) {
  7946. /* Receive error */
  7947. return -1;
  7948. }
  7949. if (n > 0) {
  7950. *nread += n;
  7951. request_len = get_http_header_len(buf, *nread);
  7952. } else {
  7953. request_len = 0;
  7954. }
  7955. if ((request_len == 0) && (request_timeout >= 0)) {
  7956. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  7957. > request_timeout) {
  7958. /* Timeout */
  7959. return -1;
  7960. }
  7961. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  7962. }
  7963. }
  7964. return request_len;
  7965. }
  7966. #if !defined(NO_CACHING)
  7967. /* Return True if we should reply 304 Not Modified. */
  7968. static int
  7969. is_not_modified(const struct mg_connection *conn,
  7970. const struct mg_file_stat *filestat)
  7971. {
  7972. char etag[64];
  7973. const char *ims = mg_get_header(conn, "If-Modified-Since");
  7974. const char *inm = mg_get_header(conn, "If-None-Match");
  7975. construct_etag(etag, sizeof(etag), filestat);
  7976. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  7977. || ((ims != NULL)
  7978. && (filestat->last_modified <= parse_date_string(ims)));
  7979. }
  7980. #endif /* !NO_CACHING */
  7981. #if !defined(NO_CGI) || !defined(NO_FILES)
  7982. static int
  7983. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  7984. {
  7985. const char *expect, *body;
  7986. char buf[MG_BUF_LEN];
  7987. int to_read, nread, success = 0;
  7988. int64_t buffered_len;
  7989. double timeout = -1.0;
  7990. if (!conn) {
  7991. return 0;
  7992. }
  7993. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  7994. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  7995. }
  7996. expect = mg_get_header(conn, "Expect");
  7997. /* assert(fp != NULL); */
  7998. if (!fp) {
  7999. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  8000. return 0;
  8001. }
  8002. if ((conn->content_len == -1) && !conn->is_chunked) {
  8003. /* Content length is not specified by the client. */
  8004. mg_send_http_error(conn,
  8005. 411,
  8006. "%s",
  8007. "Error: Client did not specify content length");
  8008. } else if ((expect != NULL)
  8009. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  8010. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  8011. */
  8012. mg_send_http_error(conn,
  8013. 417,
  8014. "Error: Can not fulfill expectation %s",
  8015. expect);
  8016. } else {
  8017. if (expect != NULL) {
  8018. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  8019. conn->status_code = 100;
  8020. } else {
  8021. conn->status_code = 200;
  8022. }
  8023. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  8024. - conn->consumed_content;
  8025. /* assert(buffered_len >= 0); */
  8026. /* assert(conn->consumed_content == 0); */
  8027. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  8028. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  8029. return 0;
  8030. }
  8031. if (buffered_len > 0) {
  8032. if ((int64_t)buffered_len > conn->content_len) {
  8033. buffered_len = (int)conn->content_len;
  8034. }
  8035. body = conn->buf + conn->request_len + conn->consumed_content;
  8036. push_all(conn->ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  8037. conn->consumed_content += buffered_len;
  8038. }
  8039. nread = 0;
  8040. while (conn->consumed_content < conn->content_len) {
  8041. to_read = sizeof(buf);
  8042. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  8043. to_read = (int)(conn->content_len - conn->consumed_content);
  8044. }
  8045. nread = pull_inner(NULL, conn, buf, to_read, timeout);
  8046. if (nread == -2) {
  8047. /* error */
  8048. break;
  8049. }
  8050. if (nread > 0) {
  8051. if (push_all(conn->ctx, fp, sock, ssl, buf, nread) != nread) {
  8052. break;
  8053. }
  8054. }
  8055. conn->consumed_content += nread;
  8056. }
  8057. if (conn->consumed_content == conn->content_len) {
  8058. success = (nread >= 0);
  8059. }
  8060. /* Each error code path in this function must send an error */
  8061. if (!success) {
  8062. /* NOTE: Maybe some data has already been sent. */
  8063. /* TODO (low): If some data has been sent, a correct error
  8064. * reply can no longer be sent, so just close the connection */
  8065. mg_send_http_error(conn, 500, "%s", "");
  8066. }
  8067. }
  8068. return success;
  8069. }
  8070. #endif
  8071. #if !defined(NO_CGI)
  8072. /* This structure helps to create an environment for the spawned CGI
  8073. * program.
  8074. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  8075. * last element must be NULL.
  8076. * However, on Windows there is a requirement that all these
  8077. * VARIABLE=VALUE\0
  8078. * strings must reside in a contiguous buffer. The end of the buffer is
  8079. * marked by two '\0' characters.
  8080. * We satisfy both worlds: we create an envp array (which is vars), all
  8081. * entries are actually pointers inside buf. */
  8082. struct cgi_environment {
  8083. struct mg_connection *conn;
  8084. /* Data block */
  8085. char *buf; /* Environment buffer */
  8086. size_t buflen; /* Space available in buf */
  8087. size_t bufused; /* Space taken in buf */
  8088. /* Index block */
  8089. char **var; /* char **envp */
  8090. size_t varlen; /* Number of variables available in var */
  8091. size_t varused; /* Number of variables stored in var */
  8092. };
  8093. static void addenv(struct cgi_environment *env,
  8094. PRINTF_FORMAT_STRING(const char *fmt),
  8095. ...) PRINTF_ARGS(2, 3);
  8096. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  8097. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  8098. static void
  8099. addenv(struct cgi_environment *env, const char *fmt, ...)
  8100. {
  8101. size_t n, space;
  8102. int truncated = 0;
  8103. char *added;
  8104. va_list ap;
  8105. /* Calculate how much space is left in the buffer */
  8106. space = (env->buflen - env->bufused);
  8107. /* Calculate an estimate for the required space */
  8108. n = strlen(fmt) + 2 + 128;
  8109. do {
  8110. if (space <= n) {
  8111. /* Allocate new buffer */
  8112. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  8113. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->ctx);
  8114. if (!added) {
  8115. /* Out of memory */
  8116. mg_cry(env->conn,
  8117. "%s: Cannot allocate memory for CGI variable [%s]",
  8118. __func__,
  8119. fmt);
  8120. return;
  8121. }
  8122. env->buf = added;
  8123. env->buflen = n;
  8124. space = (env->buflen - env->bufused);
  8125. }
  8126. /* Make a pointer to the free space int the buffer */
  8127. added = env->buf + env->bufused;
  8128. /* Copy VARIABLE=VALUE\0 string into the free space */
  8129. va_start(ap, fmt);
  8130. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  8131. va_end(ap);
  8132. /* Do not add truncated strings to the environment */
  8133. if (truncated) {
  8134. /* Reallocate the buffer */
  8135. space = 0;
  8136. n = 1;
  8137. }
  8138. } while (truncated);
  8139. /* Calculate number of bytes added to the environment */
  8140. n = strlen(added) + 1;
  8141. env->bufused += n;
  8142. /* Now update the variable index */
  8143. space = (env->varlen - env->varused);
  8144. if (space < 2) {
  8145. mg_cry(env->conn,
  8146. "%s: Cannot register CGI variable [%s]",
  8147. __func__,
  8148. fmt);
  8149. return;
  8150. }
  8151. /* Append a pointer to the added string into the envp array */
  8152. env->var[env->varused] = added;
  8153. env->varused++;
  8154. }
  8155. /* Return 0 on success, non-zero if an error occurs. */
  8156. static int
  8157. prepare_cgi_environment(struct mg_connection *conn,
  8158. const char *prog,
  8159. struct cgi_environment *env)
  8160. {
  8161. const char *s;
  8162. struct vec var_vec;
  8163. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  8164. int i, truncated, uri_len;
  8165. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  8166. return -1;
  8167. }
  8168. env->conn = conn;
  8169. env->buflen = CGI_ENVIRONMENT_SIZE;
  8170. env->bufused = 0;
  8171. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->ctx);
  8172. if (env->buf == NULL) {
  8173. mg_cry(conn,
  8174. "%s: Not enough memory for environmental buffer",
  8175. __func__);
  8176. return -1;
  8177. }
  8178. env->varlen = MAX_CGI_ENVIR_VARS;
  8179. env->varused = 0;
  8180. env->var = (char **)mg_malloc_ctx(env->buflen * sizeof(char *), conn->ctx);
  8181. if (env->var == NULL) {
  8182. mg_cry(conn,
  8183. "%s: Not enough memory for environmental variables",
  8184. __func__);
  8185. mg_free(env->buf);
  8186. return -1;
  8187. }
  8188. addenv(env, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  8189. addenv(env, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  8190. addenv(env, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  8191. addenv(env, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  8192. /* Prepare the environment block */
  8193. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  8194. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  8195. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  8196. #if defined(USE_IPV6)
  8197. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  8198. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  8199. } else
  8200. #endif
  8201. {
  8202. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  8203. }
  8204. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  8205. addenv(env, "REMOTE_ADDR=%s", src_addr);
  8206. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  8207. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  8208. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  8209. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  8210. /* SCRIPT_NAME */
  8211. uri_len = (int)strlen(conn->request_info.local_uri);
  8212. if (conn->path_info == NULL) {
  8213. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  8214. /* URI: /path_to_script/script.cgi */
  8215. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  8216. } else {
  8217. /* URI: /path_to_script/ ... using index.cgi */
  8218. const char *index_file = strrchr(prog, '/');
  8219. if (index_file) {
  8220. addenv(env,
  8221. "SCRIPT_NAME=%s%s",
  8222. conn->request_info.local_uri,
  8223. index_file + 1);
  8224. }
  8225. }
  8226. } else {
  8227. /* URI: /path_to_script/script.cgi/path_info */
  8228. addenv(env,
  8229. "SCRIPT_NAME=%.*s",
  8230. uri_len - (int)strlen(conn->path_info),
  8231. conn->request_info.local_uri);
  8232. }
  8233. addenv(env, "SCRIPT_FILENAME=%s", prog);
  8234. if (conn->path_info == NULL) {
  8235. addenv(env, "PATH_TRANSLATED=%s", conn->ctx->config[DOCUMENT_ROOT]);
  8236. } else {
  8237. addenv(env,
  8238. "PATH_TRANSLATED=%s%s",
  8239. conn->ctx->config[DOCUMENT_ROOT],
  8240. conn->path_info);
  8241. }
  8242. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  8243. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  8244. addenv(env, "CONTENT_TYPE=%s", s);
  8245. }
  8246. if (conn->request_info.query_string != NULL) {
  8247. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  8248. }
  8249. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  8250. addenv(env, "CONTENT_LENGTH=%s", s);
  8251. }
  8252. if ((s = getenv("PATH")) != NULL) {
  8253. addenv(env, "PATH=%s", s);
  8254. }
  8255. if (conn->path_info != NULL) {
  8256. addenv(env, "PATH_INFO=%s", conn->path_info);
  8257. }
  8258. if (conn->status_code > 0) {
  8259. /* CGI error handler should show the status code */
  8260. addenv(env, "STATUS=%d", conn->status_code);
  8261. }
  8262. #if defined(_WIN32)
  8263. if ((s = getenv("COMSPEC")) != NULL) {
  8264. addenv(env, "COMSPEC=%s", s);
  8265. }
  8266. if ((s = getenv("SYSTEMROOT")) != NULL) {
  8267. addenv(env, "SYSTEMROOT=%s", s);
  8268. }
  8269. if ((s = getenv("SystemDrive")) != NULL) {
  8270. addenv(env, "SystemDrive=%s", s);
  8271. }
  8272. if ((s = getenv("ProgramFiles")) != NULL) {
  8273. addenv(env, "ProgramFiles=%s", s);
  8274. }
  8275. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  8276. addenv(env, "ProgramFiles(x86)=%s", s);
  8277. }
  8278. #else
  8279. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  8280. addenv(env, "LD_LIBRARY_PATH=%s", s);
  8281. }
  8282. #endif /* _WIN32 */
  8283. if ((s = getenv("PERLLIB")) != NULL) {
  8284. addenv(env, "PERLLIB=%s", s);
  8285. }
  8286. if (conn->request_info.remote_user != NULL) {
  8287. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  8288. addenv(env, "%s", "AUTH_TYPE=Digest");
  8289. }
  8290. /* Add all headers as HTTP_* variables */
  8291. for (i = 0; i < conn->request_info.num_headers; i++) {
  8292. (void)mg_snprintf(conn,
  8293. &truncated,
  8294. http_var_name,
  8295. sizeof(http_var_name),
  8296. "HTTP_%s",
  8297. conn->request_info.http_headers[i].name);
  8298. if (truncated) {
  8299. mg_cry(conn,
  8300. "%s: HTTP header variable too long [%s]",
  8301. __func__,
  8302. conn->request_info.http_headers[i].name);
  8303. continue;
  8304. }
  8305. /* Convert variable name into uppercase, and change - to _ */
  8306. for (p = http_var_name; *p != '\0'; p++) {
  8307. if (*p == '-') {
  8308. *p = '_';
  8309. }
  8310. *p = (char)toupper(*(unsigned char *)p);
  8311. }
  8312. addenv(env,
  8313. "%s=%s",
  8314. http_var_name,
  8315. conn->request_info.http_headers[i].value);
  8316. }
  8317. /* Add user-specified variables */
  8318. s = conn->ctx->config[CGI_ENVIRONMENT];
  8319. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  8320. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  8321. }
  8322. env->var[env->varused] = NULL;
  8323. env->buf[env->bufused] = '\0';
  8324. return 0;
  8325. }
  8326. static void
  8327. handle_cgi_request(struct mg_connection *conn, const char *prog)
  8328. {
  8329. char *buf;
  8330. size_t buflen;
  8331. int headers_len, data_len, i, truncated;
  8332. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  8333. const char *status, *status_text, *connection_state;
  8334. char *pbuf, dir[PATH_MAX], *p;
  8335. struct mg_request_info ri;
  8336. struct cgi_environment blk;
  8337. FILE *in = NULL, *out = NULL, *err = NULL;
  8338. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  8339. pid_t pid = (pid_t)-1;
  8340. if (conn == NULL) {
  8341. return;
  8342. }
  8343. buf = NULL;
  8344. buflen = 16384;
  8345. i = prepare_cgi_environment(conn, prog, &blk);
  8346. if (i != 0) {
  8347. blk.buf = NULL;
  8348. blk.var = NULL;
  8349. goto done;
  8350. }
  8351. /* CGI must be executed in its own directory. 'dir' must point to the
  8352. * directory containing executable program, 'p' must point to the
  8353. * executable program name relative to 'dir'. */
  8354. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  8355. if (truncated) {
  8356. mg_cry(conn, "Error: CGI program \"%s\": Path too long", prog);
  8357. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  8358. goto done;
  8359. }
  8360. if ((p = strrchr(dir, '/')) != NULL) {
  8361. *p++ = '\0';
  8362. } else {
  8363. dir[0] = '.', dir[1] = '\0';
  8364. p = (char *)prog;
  8365. }
  8366. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  8367. status = strerror(ERRNO);
  8368. mg_cry(conn,
  8369. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  8370. prog,
  8371. status);
  8372. mg_send_http_error(conn,
  8373. 500,
  8374. "Error: Cannot create CGI pipe: %s",
  8375. status);
  8376. goto done;
  8377. }
  8378. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  8379. if (pid == (pid_t)-1) {
  8380. status = strerror(ERRNO);
  8381. mg_cry(conn,
  8382. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  8383. prog,
  8384. status);
  8385. mg_send_http_error(conn,
  8386. 500,
  8387. "Error: Cannot spawn CGI process [%s]: %s",
  8388. prog,
  8389. status);
  8390. goto done;
  8391. }
  8392. /* Make sure child closes all pipe descriptors. It must dup them to 0,1
  8393. */
  8394. set_close_on_exec((SOCKET)fdin[0], conn); /* stdin read */
  8395. set_close_on_exec((SOCKET)fdout[1], conn); /* stdout write */
  8396. set_close_on_exec((SOCKET)fderr[1], conn); /* stderr write */
  8397. set_close_on_exec((SOCKET)fdin[1], conn); /* stdin write */
  8398. set_close_on_exec((SOCKET)fdout[0], conn); /* stdout read */
  8399. set_close_on_exec((SOCKET)fderr[0], conn); /* stderr read */
  8400. /* Parent closes only one side of the pipes.
  8401. * If we don't mark them as closed, close() attempt before
  8402. * return from this function throws an exception on Windows.
  8403. * Windows does not like when closed descriptor is closed again. */
  8404. (void)close(fdin[0]);
  8405. (void)close(fdout[1]);
  8406. (void)close(fderr[1]);
  8407. fdin[0] = fdout[1] = fderr[1] = -1;
  8408. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  8409. status = strerror(ERRNO);
  8410. mg_cry(conn,
  8411. "Error: CGI program \"%s\": Can not open stdin: %s",
  8412. prog,
  8413. status);
  8414. mg_send_http_error(conn,
  8415. 500,
  8416. "Error: CGI can not open fdin\nfopen: %s",
  8417. status);
  8418. goto done;
  8419. }
  8420. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  8421. status = strerror(ERRNO);
  8422. mg_cry(conn,
  8423. "Error: CGI program \"%s\": Can not open stdout: %s",
  8424. prog,
  8425. status);
  8426. mg_send_http_error(conn,
  8427. 500,
  8428. "Error: CGI can not open fdout\nfopen: %s",
  8429. status);
  8430. goto done;
  8431. }
  8432. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  8433. status = strerror(ERRNO);
  8434. mg_cry(conn,
  8435. "Error: CGI program \"%s\": Can not open stderr: %s",
  8436. prog,
  8437. status);
  8438. mg_send_http_error(conn,
  8439. 500,
  8440. "Error: CGI can not open fdout\nfopen: %s",
  8441. status);
  8442. goto done;
  8443. }
  8444. setbuf(in, NULL);
  8445. setbuf(out, NULL);
  8446. setbuf(err, NULL);
  8447. fout.access.fp = out;
  8448. if ((conn->request_info.content_length > 0) || conn->is_chunked) {
  8449. /* This is a POST/PUT request, or another request with body data. */
  8450. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  8451. /* Error sending the body data */
  8452. mg_cry(conn,
  8453. "Error: CGI program \"%s\": Forward body data failed",
  8454. prog);
  8455. goto done;
  8456. }
  8457. }
  8458. /* Close so child gets an EOF. */
  8459. fclose(in);
  8460. in = NULL;
  8461. fdin[1] = -1;
  8462. /* Now read CGI reply into a buffer. We need to set correct
  8463. * status code, thus we need to see all HTTP headers first.
  8464. * Do not send anything back to client, until we buffer in all
  8465. * HTTP headers. */
  8466. data_len = 0;
  8467. buf = (char *)mg_malloc_ctx(buflen, conn->ctx);
  8468. if (buf == NULL) {
  8469. mg_send_http_error(conn,
  8470. 500,
  8471. "Error: Not enough memory for CGI buffer (%u bytes)",
  8472. (unsigned int)buflen);
  8473. mg_cry(conn,
  8474. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  8475. "bytes)",
  8476. prog,
  8477. (unsigned int)buflen);
  8478. goto done;
  8479. }
  8480. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  8481. if (headers_len <= 0) {
  8482. /* Could not parse the CGI response. Check if some error message on
  8483. * stderr. */
  8484. i = pull_all(err, conn, buf, (int)buflen);
  8485. if (i > 0) {
  8486. mg_cry(conn,
  8487. "Error: CGI program \"%s\" sent error "
  8488. "message: [%.*s]",
  8489. prog,
  8490. i,
  8491. buf);
  8492. mg_send_http_error(conn,
  8493. 500,
  8494. "Error: CGI program \"%s\" sent error "
  8495. "message: [%.*s]",
  8496. prog,
  8497. i,
  8498. buf);
  8499. } else {
  8500. mg_cry(conn,
  8501. "Error: CGI program sent malformed or too big "
  8502. "(>%u bytes) HTTP headers: [%.*s]",
  8503. (unsigned)buflen,
  8504. data_len,
  8505. buf);
  8506. mg_send_http_error(conn,
  8507. 500,
  8508. "Error: CGI program sent malformed or too big "
  8509. "(>%u bytes) HTTP headers: [%.*s]",
  8510. (unsigned)buflen,
  8511. data_len,
  8512. buf);
  8513. }
  8514. goto done;
  8515. }
  8516. pbuf = buf;
  8517. buf[headers_len - 1] = '\0';
  8518. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  8519. /* Make up and send the status line */
  8520. status_text = "OK";
  8521. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  8522. != NULL) {
  8523. conn->status_code = atoi(status);
  8524. status_text = status;
  8525. while (isdigit(*(const unsigned char *)status_text)
  8526. || *status_text == ' ') {
  8527. status_text++;
  8528. }
  8529. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  8530. != NULL) {
  8531. conn->status_code = 302;
  8532. } else {
  8533. conn->status_code = 200;
  8534. }
  8535. connection_state =
  8536. get_header(ri.http_headers, ri.num_headers, "Connection");
  8537. if (!header_has_option(connection_state, "keep-alive")) {
  8538. conn->must_close = 1;
  8539. }
  8540. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  8541. /* Send headers */
  8542. for (i = 0; i < ri.num_headers; i++) {
  8543. mg_printf(conn,
  8544. "%s: %s\r\n",
  8545. ri.http_headers[i].name,
  8546. ri.http_headers[i].value);
  8547. }
  8548. mg_write(conn, "\r\n", 2);
  8549. /* Send chunk of data that may have been read after the headers */
  8550. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  8551. /* Read the rest of CGI output and send to the client */
  8552. send_file_data(conn, &fout, 0, INT64_MAX);
  8553. done:
  8554. mg_free(blk.var);
  8555. mg_free(blk.buf);
  8556. if (pid != (pid_t)-1) {
  8557. kill(pid, SIGKILL);
  8558. #if !defined(_WIN32)
  8559. {
  8560. int st;
  8561. while (waitpid(pid, &st, 0) != -1)
  8562. ; /* clean zombies */
  8563. }
  8564. #endif
  8565. }
  8566. if (fdin[0] != -1) {
  8567. close(fdin[0]);
  8568. }
  8569. if (fdout[1] != -1) {
  8570. close(fdout[1]);
  8571. }
  8572. if (in != NULL) {
  8573. fclose(in);
  8574. } else if (fdin[1] != -1) {
  8575. close(fdin[1]);
  8576. }
  8577. if (out != NULL) {
  8578. fclose(out);
  8579. } else if (fdout[0] != -1) {
  8580. close(fdout[0]);
  8581. }
  8582. if (err != NULL) {
  8583. fclose(err);
  8584. } else if (fderr[0] != -1) {
  8585. close(fderr[0]);
  8586. }
  8587. if (buf != NULL) {
  8588. mg_free(buf);
  8589. }
  8590. }
  8591. #endif /* !NO_CGI */
  8592. #if !defined(NO_FILES)
  8593. static void
  8594. mkcol(struct mg_connection *conn, const char *path)
  8595. {
  8596. int rc, body_len;
  8597. struct de de;
  8598. char date[64];
  8599. time_t curtime = time(NULL);
  8600. if (conn == NULL) {
  8601. return;
  8602. }
  8603. /* TODO (mid): Check the mg_send_http_error situations in this function
  8604. */
  8605. memset(&de.file, 0, sizeof(de.file));
  8606. if (!mg_stat(conn, path, &de.file)) {
  8607. mg_cry(conn,
  8608. "%s: mg_stat(%s) failed: %s",
  8609. __func__,
  8610. path,
  8611. strerror(ERRNO));
  8612. }
  8613. if (de.file.last_modified) {
  8614. /* TODO (mid): This check does not seem to make any sense ! */
  8615. /* TODO (mid): Add a webdav unit test first, before changing
  8616. * anything here. */
  8617. mg_send_http_error(
  8618. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  8619. return;
  8620. }
  8621. body_len = conn->data_len - conn->request_len;
  8622. if (body_len > 0) {
  8623. mg_send_http_error(
  8624. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  8625. return;
  8626. }
  8627. rc = mg_mkdir(conn, path, 0755);
  8628. if (rc == 0) {
  8629. conn->status_code = 201;
  8630. gmt_time_string(date, sizeof(date), &curtime);
  8631. mg_printf(conn,
  8632. "HTTP/1.1 %d Created\r\n"
  8633. "Date: %s\r\n",
  8634. conn->status_code,
  8635. date);
  8636. send_static_cache_header(conn);
  8637. send_additional_header(conn);
  8638. mg_printf(conn,
  8639. "Content-Length: 0\r\n"
  8640. "Connection: %s\r\n\r\n",
  8641. suggest_connection_header(conn));
  8642. } else if (rc == -1) {
  8643. if (errno == EEXIST) {
  8644. mg_send_http_error(
  8645. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  8646. } else if (errno == EACCES) {
  8647. mg_send_http_error(
  8648. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  8649. } else if (errno == ENOENT) {
  8650. mg_send_http_error(
  8651. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  8652. } else {
  8653. mg_send_http_error(
  8654. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  8655. }
  8656. }
  8657. }
  8658. static void
  8659. put_file(struct mg_connection *conn, const char *path)
  8660. {
  8661. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8662. const char *range;
  8663. int64_t r1, r2;
  8664. int rc;
  8665. char date[64];
  8666. time_t curtime = time(NULL);
  8667. if (conn == NULL) {
  8668. return;
  8669. }
  8670. if (mg_stat(conn, path, &file.stat)) {
  8671. /* File already exists */
  8672. conn->status_code = 200;
  8673. if (file.stat.is_directory) {
  8674. /* This is an already existing directory,
  8675. * so there is nothing to do for the server. */
  8676. rc = 0;
  8677. } else {
  8678. /* File exists and is not a directory. */
  8679. /* Can it be replaced? */
  8680. if (file.access.membuf != NULL) {
  8681. /* This is an "in-memory" file, that can not be replaced */
  8682. mg_send_http_error(conn,
  8683. 405,
  8684. "Error: Put not possible\nReplacing %s "
  8685. "is not supported",
  8686. path);
  8687. return;
  8688. }
  8689. /* Check if the server may write this file */
  8690. if (access(path, W_OK) == 0) {
  8691. /* Access granted */
  8692. conn->status_code = 200;
  8693. rc = 1;
  8694. } else {
  8695. mg_send_http_error(
  8696. conn,
  8697. 403,
  8698. "Error: Put not possible\nReplacing %s is not allowed",
  8699. path);
  8700. return;
  8701. }
  8702. }
  8703. } else {
  8704. /* File should be created */
  8705. conn->status_code = 201;
  8706. rc = put_dir(conn, path);
  8707. }
  8708. if (rc == 0) {
  8709. /* put_dir returns 0 if path is a directory */
  8710. gmt_time_string(date, sizeof(date), &curtime);
  8711. mg_printf(conn,
  8712. "HTTP/1.1 %d %s\r\n",
  8713. conn->status_code,
  8714. mg_get_response_code_text(NULL, conn->status_code));
  8715. send_no_cache_header(conn);
  8716. send_additional_header(conn);
  8717. mg_printf(conn,
  8718. "Date: %s\r\n"
  8719. "Content-Length: 0\r\n"
  8720. "Connection: %s\r\n\r\n",
  8721. date,
  8722. suggest_connection_header(conn));
  8723. /* Request to create a directory has been fulfilled successfully.
  8724. * No need to put a file. */
  8725. return;
  8726. }
  8727. if (rc == -1) {
  8728. /* put_dir returns -1 if the path is too long */
  8729. mg_send_http_error(conn,
  8730. 414,
  8731. "Error: Path too long\nput_dir(%s): %s",
  8732. path,
  8733. strerror(ERRNO));
  8734. return;
  8735. }
  8736. if (rc == -2) {
  8737. /* put_dir returns -2 if the directory can not be created */
  8738. mg_send_http_error(conn,
  8739. 500,
  8740. "Error: Can not create directory\nput_dir(%s): %s",
  8741. path,
  8742. strerror(ERRNO));
  8743. return;
  8744. }
  8745. /* A file should be created or overwritten. */
  8746. /* Currently CivetWeb does not nead read+write access. */
  8747. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  8748. || file.access.fp == NULL) {
  8749. (void)mg_fclose(&file.access);
  8750. mg_send_http_error(conn,
  8751. 500,
  8752. "Error: Can not create file\nfopen(%s): %s",
  8753. path,
  8754. strerror(ERRNO));
  8755. return;
  8756. }
  8757. fclose_on_exec(&file.access, conn);
  8758. range = mg_get_header(conn, "Content-Range");
  8759. r1 = r2 = 0;
  8760. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  8761. conn->status_code = 206; /* Partial content */
  8762. fseeko(file.access.fp, r1, SEEK_SET);
  8763. }
  8764. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  8765. /* forward_body_data failed.
  8766. * The error code has already been sent to the client,
  8767. * and conn->status_code is already set. */
  8768. (void)mg_fclose(&file.access);
  8769. return;
  8770. }
  8771. if (mg_fclose(&file.access) != 0) {
  8772. /* fclose failed. This might have different reasons, but a likely
  8773. * one is "no space on disk", http 507. */
  8774. conn->status_code = 507;
  8775. }
  8776. gmt_time_string(date, sizeof(date), &curtime);
  8777. mg_printf(conn,
  8778. "HTTP/1.1 %d %s\r\n",
  8779. conn->status_code,
  8780. mg_get_response_code_text(NULL, conn->status_code));
  8781. send_no_cache_header(conn);
  8782. send_additional_header(conn);
  8783. mg_printf(conn,
  8784. "Date: %s\r\n"
  8785. "Content-Length: 0\r\n"
  8786. "Connection: %s\r\n\r\n",
  8787. date,
  8788. suggest_connection_header(conn));
  8789. }
  8790. static void
  8791. delete_file(struct mg_connection *conn, const char *path)
  8792. {
  8793. struct de de;
  8794. memset(&de.file, 0, sizeof(de.file));
  8795. if (!mg_stat(conn, path, &de.file)) {
  8796. /* mg_stat returns 0 if the file does not exist */
  8797. mg_send_http_error(conn,
  8798. 404,
  8799. "Error: Cannot delete file\nFile %s not found",
  8800. path);
  8801. return;
  8802. }
  8803. #if 0 /* Ignore if a file in memory is inside a folder */
  8804. if (de.access.membuf != NULL) {
  8805. /* the file is cached in memory */
  8806. mg_send_http_error(
  8807. conn,
  8808. 405,
  8809. "Error: Delete not possible\nDeleting %s is not supported",
  8810. path);
  8811. return;
  8812. }
  8813. #endif
  8814. if (de.file.is_directory) {
  8815. if (remove_directory(conn, path)) {
  8816. /* Delete is successful: Return 204 without content. */
  8817. mg_send_http_error(conn, 204, "%s", "");
  8818. } else {
  8819. /* Delete is not successful: Return 500 (Server error). */
  8820. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  8821. }
  8822. return;
  8823. }
  8824. /* This is an existing file (not a directory).
  8825. * Check if write permission is granted. */
  8826. if (access(path, W_OK) != 0) {
  8827. /* File is read only */
  8828. mg_send_http_error(
  8829. conn,
  8830. 403,
  8831. "Error: Delete not possible\nDeleting %s is not allowed",
  8832. path);
  8833. return;
  8834. }
  8835. /* Try to delete it. */
  8836. if (mg_remove(conn, path) == 0) {
  8837. /* Delete was successful: Return 204 without content. */
  8838. mg_send_http_error(conn, 204, "%s", "");
  8839. } else {
  8840. /* Delete not successful (file locked). */
  8841. mg_send_http_error(conn,
  8842. 423,
  8843. "Error: Cannot delete file\nremove(%s): %s",
  8844. path,
  8845. strerror(ERRNO));
  8846. }
  8847. }
  8848. #endif /* !NO_FILES */
  8849. static void
  8850. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  8851. static void
  8852. do_ssi_include(struct mg_connection *conn,
  8853. const char *ssi,
  8854. char *tag,
  8855. int include_level)
  8856. {
  8857. char file_name[MG_BUF_LEN], path[512], *p;
  8858. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8859. size_t len;
  8860. int truncated = 0;
  8861. if (conn == NULL) {
  8862. return;
  8863. }
  8864. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  8865. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  8866. * always < MG_BUF_LEN. */
  8867. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  8868. /* File name is relative to the webserver root */
  8869. file_name[511] = 0;
  8870. (void)mg_snprintf(conn,
  8871. &truncated,
  8872. path,
  8873. sizeof(path),
  8874. "%s/%s",
  8875. conn->ctx->config[DOCUMENT_ROOT],
  8876. file_name);
  8877. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  8878. /* File name is relative to the webserver working directory
  8879. * or it is absolute system path */
  8880. file_name[511] = 0;
  8881. (void)
  8882. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  8883. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  8884. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  8885. /* File name is relative to the currect document */
  8886. file_name[511] = 0;
  8887. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  8888. if (!truncated) {
  8889. if ((p = strrchr(path, '/')) != NULL) {
  8890. p[1] = '\0';
  8891. }
  8892. len = strlen(path);
  8893. (void)mg_snprintf(conn,
  8894. &truncated,
  8895. path + len,
  8896. sizeof(path) - len,
  8897. "%s",
  8898. file_name);
  8899. }
  8900. } else {
  8901. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  8902. return;
  8903. }
  8904. if (truncated) {
  8905. mg_cry(conn, "SSI #include path length overflow: [%s]", tag);
  8906. return;
  8907. }
  8908. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  8909. mg_cry(conn,
  8910. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  8911. tag,
  8912. path,
  8913. strerror(ERRNO));
  8914. } else {
  8915. fclose_on_exec(&file.access, conn);
  8916. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  8917. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  8918. path) > 0) {
  8919. send_ssi_file(conn, path, &file, include_level + 1);
  8920. } else {
  8921. send_file_data(conn, &file, 0, INT64_MAX);
  8922. }
  8923. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  8924. }
  8925. }
  8926. #if !defined(NO_POPEN)
  8927. static void
  8928. do_ssi_exec(struct mg_connection *conn, char *tag)
  8929. {
  8930. char cmd[1024] = "";
  8931. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8932. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  8933. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  8934. } else {
  8935. cmd[1023] = 0;
  8936. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  8937. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  8938. } else {
  8939. send_file_data(conn, &file, 0, INT64_MAX);
  8940. pclose(file.access.fp);
  8941. }
  8942. }
  8943. }
  8944. #endif /* !NO_POPEN */
  8945. static int
  8946. mg_fgetc(struct mg_file *filep, int offset)
  8947. {
  8948. if (filep == NULL) {
  8949. return EOF;
  8950. }
  8951. if ((filep->access.membuf != NULL) && (offset >= 0)
  8952. && (((unsigned int)(offset)) < filep->stat.size)) {
  8953. return ((const unsigned char *)filep->access.membuf)[offset];
  8954. } else if (filep->access.fp != NULL) {
  8955. return fgetc(filep->access.fp);
  8956. } else {
  8957. return EOF;
  8958. }
  8959. }
  8960. static void
  8961. send_ssi_file(struct mg_connection *conn,
  8962. const char *path,
  8963. struct mg_file *filep,
  8964. int include_level)
  8965. {
  8966. char buf[MG_BUF_LEN];
  8967. int ch, offset, len, in_tag, in_ssi_tag;
  8968. if (include_level > 10) {
  8969. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  8970. return;
  8971. }
  8972. in_tag = in_ssi_tag = len = offset = 0;
  8973. /* Read file, byte by byte, and look for SSI include tags */
  8974. while ((ch = mg_fgetc(filep, offset++)) != EOF) {
  8975. if (in_tag) {
  8976. /* We are in a tag, either SSI tag or html tag */
  8977. if (ch == '>') {
  8978. /* Tag is closing */
  8979. buf[len++] = '>';
  8980. if (in_ssi_tag) {
  8981. /* Handle SSI tag */
  8982. buf[len] = 0;
  8983. if (!memcmp(buf + 5, "include", 7)) {
  8984. do_ssi_include(conn, path, buf + 12, include_level + 1);
  8985. #if !defined(NO_POPEN)
  8986. } else if (!memcmp(buf + 5, "exec", 4)) {
  8987. do_ssi_exec(conn, buf + 9);
  8988. #endif /* !NO_POPEN */
  8989. } else {
  8990. mg_cry(conn,
  8991. "%s: unknown SSI "
  8992. "command: \"%s\"",
  8993. path,
  8994. buf);
  8995. }
  8996. len = 0;
  8997. in_ssi_tag = in_tag = 0;
  8998. } else {
  8999. /* Not an SSI tag */
  9000. /* Flush buffer */
  9001. (void)mg_write(conn, buf, (size_t)len);
  9002. len = 0;
  9003. in_tag = 0;
  9004. }
  9005. } else {
  9006. /* Tag is still open */
  9007. buf[len++] = (char)(ch & 0xff);
  9008. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  9009. /* All SSI tags start with <!--# */
  9010. in_ssi_tag = 1;
  9011. }
  9012. if ((len + 2) > (int)sizeof(buf)) {
  9013. /* Tag to long for buffer */
  9014. mg_cry(conn, "%s: tag is too large", path);
  9015. len = 0;
  9016. return;
  9017. }
  9018. }
  9019. } else {
  9020. /* We are not in a tag yet. */
  9021. if (ch == '<') {
  9022. /* Tag is opening */
  9023. in_tag = 1;
  9024. /* Flush current buffer */
  9025. (void)mg_write(conn, buf, (size_t)len);
  9026. /* Store the < */
  9027. len = 1;
  9028. buf[0] = '<';
  9029. } else {
  9030. /* No Tag */
  9031. /* Add data to buffer */
  9032. buf[len++] = (char)(ch & 0xff);
  9033. /* Flush if buffer is full */
  9034. if (len == (int)sizeof(buf)) {
  9035. mg_write(conn, buf, (size_t)len);
  9036. len = 0;
  9037. }
  9038. }
  9039. }
  9040. }
  9041. /* Send the rest of buffered data */
  9042. if (len > 0) {
  9043. mg_write(conn, buf, (size_t)len);
  9044. }
  9045. }
  9046. static void
  9047. handle_ssi_file_request(struct mg_connection *conn,
  9048. const char *path,
  9049. struct mg_file *filep)
  9050. {
  9051. char date[64];
  9052. time_t curtime = time(NULL);
  9053. const char *cors1, *cors2, *cors3;
  9054. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  9055. return;
  9056. }
  9057. if (mg_get_header(conn, "Origin")) {
  9058. /* Cross-origin resource sharing (CORS). */
  9059. cors1 = "Access-Control-Allow-Origin: ";
  9060. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  9061. cors3 = "\r\n";
  9062. } else {
  9063. cors1 = cors2 = cors3 = "";
  9064. }
  9065. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  9066. /* File exists (precondition for calling this function),
  9067. * but can not be opened by the server. */
  9068. mg_send_http_error(conn,
  9069. 500,
  9070. "Error: Cannot read file\nfopen(%s): %s",
  9071. path,
  9072. strerror(ERRNO));
  9073. } else {
  9074. conn->must_close = 1;
  9075. gmt_time_string(date, sizeof(date), &curtime);
  9076. fclose_on_exec(&filep->access, conn);
  9077. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  9078. send_no_cache_header(conn);
  9079. send_additional_header(conn);
  9080. mg_printf(conn,
  9081. "%s%s%s"
  9082. "Date: %s\r\n"
  9083. "Content-Type: text/html\r\n"
  9084. "Connection: %s\r\n\r\n",
  9085. cors1,
  9086. cors2,
  9087. cors3,
  9088. date,
  9089. suggest_connection_header(conn));
  9090. send_ssi_file(conn, path, filep, 0);
  9091. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  9092. }
  9093. }
  9094. #if !defined(NO_FILES)
  9095. static void
  9096. send_options(struct mg_connection *conn)
  9097. {
  9098. char date[64];
  9099. time_t curtime = time(NULL);
  9100. if (!conn) {
  9101. return;
  9102. }
  9103. conn->status_code = 200;
  9104. conn->must_close = 1;
  9105. gmt_time_string(date, sizeof(date), &curtime);
  9106. /* We do not set a "Cache-Control" header here, but leave the default.
  9107. * Since browsers do not send an OPTIONS request, we can not test the
  9108. * effect anyway. */
  9109. mg_printf(conn,
  9110. "HTTP/1.1 200 OK\r\n"
  9111. "Date: %s\r\n"
  9112. "Connection: %s\r\n"
  9113. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  9114. "PROPFIND, MKCOL\r\n"
  9115. "DAV: 1\r\n",
  9116. date,
  9117. suggest_connection_header(conn));
  9118. send_additional_header(conn);
  9119. mg_printf(conn, "\r\n");
  9120. }
  9121. /* Writes PROPFIND properties for a collection element */
  9122. static void
  9123. print_props(struct mg_connection *conn,
  9124. const char *uri,
  9125. struct mg_file_stat *filep)
  9126. {
  9127. char mtime[64];
  9128. if ((conn == NULL) || (uri == NULL) || (filep == NULL)) {
  9129. return;
  9130. }
  9131. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  9132. mg_printf(conn,
  9133. "<d:response>"
  9134. "<d:href>%s</d:href>"
  9135. "<d:propstat>"
  9136. "<d:prop>"
  9137. "<d:resourcetype>%s</d:resourcetype>"
  9138. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  9139. "<d:getlastmodified>%s</d:getlastmodified>"
  9140. "</d:prop>"
  9141. "<d:status>HTTP/1.1 200 OK</d:status>"
  9142. "</d:propstat>"
  9143. "</d:response>\n",
  9144. uri,
  9145. filep->is_directory ? "<d:collection/>" : "",
  9146. filep->size,
  9147. mtime);
  9148. }
  9149. static int
  9150. print_dav_dir_entry(struct de *de, void *data)
  9151. {
  9152. char href[PATH_MAX];
  9153. int truncated;
  9154. struct mg_connection *conn = (struct mg_connection *)data;
  9155. if (!de || !conn) {
  9156. return -1;
  9157. }
  9158. mg_snprintf(conn,
  9159. &truncated,
  9160. href,
  9161. sizeof(href),
  9162. "%s%s",
  9163. conn->request_info.local_uri,
  9164. de->file_name);
  9165. if (!truncated) {
  9166. size_t href_encoded_size;
  9167. char *href_encoded;
  9168. href_encoded_size = PATH_MAX * 3; /* worst case */
  9169. href_encoded = mg_malloc(href_encoded_size);
  9170. if (href_encoded == NULL) {
  9171. return -1;
  9172. }
  9173. mg_url_encode(href, href_encoded, href_encoded_size);
  9174. print_props(conn, href_encoded, &de->file);
  9175. mg_free(href_encoded);
  9176. }
  9177. return 0;
  9178. }
  9179. static void
  9180. handle_propfind(struct mg_connection *conn,
  9181. const char *path,
  9182. struct mg_file_stat *filep)
  9183. {
  9184. const char *depth = mg_get_header(conn, "Depth");
  9185. char date[64];
  9186. time_t curtime = time(NULL);
  9187. gmt_time_string(date, sizeof(date), &curtime);
  9188. if (!conn || !path || !filep || !conn->ctx) {
  9189. return;
  9190. }
  9191. conn->must_close = 1;
  9192. conn->status_code = 207;
  9193. mg_printf(conn,
  9194. "HTTP/1.1 207 Multi-Status\r\n"
  9195. "Date: %s\r\n",
  9196. date);
  9197. send_static_cache_header(conn);
  9198. send_additional_header(conn);
  9199. mg_printf(conn,
  9200. "Connection: %s\r\n"
  9201. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  9202. suggest_connection_header(conn));
  9203. mg_printf(conn,
  9204. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  9205. "<d:multistatus xmlns:d='DAV:'>\n");
  9206. /* Print properties for the requested resource itself */
  9207. print_props(conn, conn->request_info.local_uri, filep);
  9208. /* If it is a directory, print directory entries too if Depth is not 0
  9209. */
  9210. if (filep && filep->is_directory
  9211. && !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")
  9212. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  9213. scan_directory(conn, path, conn, &print_dav_dir_entry);
  9214. }
  9215. mg_printf(conn, "%s\n", "</d:multistatus>");
  9216. }
  9217. #endif
  9218. void
  9219. mg_lock_connection(struct mg_connection *conn)
  9220. {
  9221. if (conn) {
  9222. (void)pthread_mutex_lock(&conn->mutex);
  9223. }
  9224. }
  9225. void
  9226. mg_unlock_connection(struct mg_connection *conn)
  9227. {
  9228. if (conn) {
  9229. (void)pthread_mutex_unlock(&conn->mutex);
  9230. }
  9231. }
  9232. void
  9233. mg_lock_context(struct mg_context *ctx)
  9234. {
  9235. if (ctx) {
  9236. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  9237. }
  9238. }
  9239. void
  9240. mg_unlock_context(struct mg_context *ctx)
  9241. {
  9242. if (ctx) {
  9243. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  9244. }
  9245. }
  9246. #if defined(USE_TIMERS)
  9247. #define TIMER_API static
  9248. #include "timer.inl"
  9249. #endif /* USE_TIMERS */
  9250. #ifdef USE_LUA
  9251. #include "mod_lua.inl"
  9252. #endif /* USE_LUA */
  9253. #ifdef USE_DUKTAPE
  9254. #include "mod_duktape.inl"
  9255. #endif /* USE_DUKTAPE */
  9256. #if defined(USE_WEBSOCKET)
  9257. #if !defined(NO_SSL_DL)
  9258. #define SHA_API static
  9259. #include "sha1.inl"
  9260. #endif
  9261. static int
  9262. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  9263. {
  9264. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  9265. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  9266. SHA_CTX sha_ctx;
  9267. int truncated;
  9268. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  9269. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  9270. if (truncated) {
  9271. conn->must_close = 1;
  9272. return 0;
  9273. }
  9274. SHA1_Init(&sha_ctx);
  9275. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  9276. SHA1_Final((unsigned char *)sha, &sha_ctx);
  9277. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  9278. mg_printf(conn,
  9279. "HTTP/1.1 101 Switching Protocols\r\n"
  9280. "Upgrade: websocket\r\n"
  9281. "Connection: Upgrade\r\n"
  9282. "Sec-WebSocket-Accept: %s\r\n",
  9283. b64_sha);
  9284. if (conn->request_info.acceptedWebSocketSubprotocol) {
  9285. mg_printf(conn,
  9286. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  9287. conn->request_info.acceptedWebSocketSubprotocol);
  9288. } else {
  9289. mg_printf(conn, "%s", "\r\n");
  9290. }
  9291. return 1;
  9292. }
  9293. static void
  9294. read_websocket(struct mg_connection *conn,
  9295. mg_websocket_data_handler ws_data_handler,
  9296. void *callback_data)
  9297. {
  9298. /* Pointer to the beginning of the portion of the incoming websocket
  9299. * message queue.
  9300. * The original websocket upgrade request is never removed, so the queue
  9301. * begins after it. */
  9302. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  9303. int n, error, exit_by_callback;
  9304. /* body_len is the length of the entire queue in bytes
  9305. * len is the length of the current message
  9306. * data_len is the length of the current message's data payload
  9307. * header_len is the length of the current message's header */
  9308. size_t i, len, mask_len = 0, data_len = 0, header_len, body_len;
  9309. /* "The masking key is a 32-bit value chosen at random by the client."
  9310. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  9311. */
  9312. unsigned char mask[4];
  9313. /* data points to the place where the message is stored when passed to
  9314. * the
  9315. * websocket_data callback. This is either mem on the stack, or a
  9316. * dynamically allocated buffer if it is too large. */
  9317. unsigned char mem[4096];
  9318. unsigned char *data = mem;
  9319. unsigned char mop; /* mask flag and opcode */
  9320. double timeout = -1.0;
  9321. if (conn->ctx->config[WEBSOCKET_TIMEOUT]) {
  9322. timeout = atoi(conn->ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  9323. }
  9324. if ((timeout <= 0.0) && (conn->ctx->config[REQUEST_TIMEOUT])) {
  9325. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  9326. }
  9327. mg_set_thread_name("wsock");
  9328. /* Loop continuously, reading messages from the socket, invoking the
  9329. * callback, and waiting repeatedly until an error occurs. */
  9330. while (!conn->ctx->stop_flag) {
  9331. header_len = 0;
  9332. assert(conn->data_len >= conn->request_len);
  9333. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  9334. len = buf[1] & 127;
  9335. mask_len = (buf[1] & 128) ? 4 : 0;
  9336. if ((len < 126) && (body_len >= mask_len)) {
  9337. /* inline 7-bit length field */
  9338. data_len = len;
  9339. header_len = 2 + mask_len;
  9340. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  9341. /* 16-bit length field */
  9342. header_len = 4 + mask_len;
  9343. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  9344. } else if (body_len >= (10 + mask_len)) {
  9345. /* 64-bit length field */
  9346. uint32_t l1, l2;
  9347. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  9348. memcpy(&l2, &buf[6], 4);
  9349. header_len = 10 + mask_len;
  9350. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  9351. if (data_len > (uint64_t)0x7FFF0000ul) {
  9352. /* no can do */
  9353. mg_cry(conn, "websocket out of memory; closing connection");
  9354. break;
  9355. }
  9356. }
  9357. }
  9358. if ((header_len > 0) && (body_len >= header_len)) {
  9359. /* Allocate space to hold websocket payload */
  9360. data = mem;
  9361. if (data_len > sizeof(mem)) {
  9362. data = (unsigned char *)mg_malloc_ctx(data_len, conn->ctx);
  9363. if (data == NULL) {
  9364. /* Allocation failed, exit the loop and then close the
  9365. * connection */
  9366. mg_cry(conn, "websocket out of memory; closing connection");
  9367. break;
  9368. }
  9369. }
  9370. /* Copy the mask before we shift the queue and destroy it */
  9371. if (mask_len > 0) {
  9372. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  9373. } else {
  9374. memset(mask, 0, sizeof(mask));
  9375. }
  9376. /* Read frame payload from the first message in the queue into
  9377. * data and advance the queue by moving the memory in place. */
  9378. assert(body_len >= header_len);
  9379. if (data_len + header_len > body_len) {
  9380. mop = buf[0]; /* current mask and opcode */
  9381. /* Overflow case */
  9382. len = body_len - header_len;
  9383. memcpy(data, buf + header_len, len);
  9384. error = 0;
  9385. while (len < data_len) {
  9386. n = pull_inner(NULL,
  9387. conn,
  9388. (char *)(data + len),
  9389. (int)(data_len - len),
  9390. timeout);
  9391. if (n <= -2) {
  9392. error = 1;
  9393. break;
  9394. } else if (n > 0) {
  9395. len += (size_t)n;
  9396. } else {
  9397. /* Timeout: should retry */
  9398. /* TODO: retry condition */
  9399. }
  9400. }
  9401. if (error) {
  9402. mg_cry(conn, "Websocket pull failed; closing connection");
  9403. break;
  9404. }
  9405. conn->data_len = conn->request_len;
  9406. } else {
  9407. mop = buf[0]; /* current mask and opcode, overwritten by
  9408. * memmove() */
  9409. /* Length of the message being read at the front of the
  9410. * queue */
  9411. len = data_len + header_len;
  9412. /* Copy the data payload into the data pointer for the
  9413. * callback */
  9414. memcpy(data, buf + header_len, data_len);
  9415. /* Move the queue forward len bytes */
  9416. memmove(buf, buf + len, body_len - len);
  9417. /* Mark the queue as advanced */
  9418. conn->data_len -= (int)len;
  9419. }
  9420. /* Apply mask if necessary */
  9421. if (mask_len > 0) {
  9422. for (i = 0; i < data_len; ++i) {
  9423. data[i] ^= mask[i & 3];
  9424. }
  9425. }
  9426. /* Exit the loop if callback signals to exit (server side),
  9427. * or "connection close" opcode received (client side). */
  9428. exit_by_callback = 0;
  9429. if ((ws_data_handler != NULL)
  9430. && !ws_data_handler(
  9431. conn, mop, (char *)data, data_len, callback_data)) {
  9432. exit_by_callback = 1;
  9433. }
  9434. if (data != mem) {
  9435. mg_free(data);
  9436. }
  9437. if (exit_by_callback
  9438. || ((mop & 0xf) == WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  9439. /* Opcode == 8, connection close */
  9440. break;
  9441. }
  9442. /* Not breaking the loop, process next websocket frame. */
  9443. } else {
  9444. /* Read from the socket into the next available location in the
  9445. * message queue. */
  9446. n = pull_inner(NULL,
  9447. conn,
  9448. conn->buf + conn->data_len,
  9449. conn->buf_size - conn->data_len,
  9450. timeout);
  9451. if (n <= -2) {
  9452. /* Error, no bytes read */
  9453. break;
  9454. }
  9455. if (n > 0) {
  9456. conn->data_len += n;
  9457. } else {
  9458. /* Timeout: should retry */
  9459. /* TODO: get timeout def */
  9460. }
  9461. }
  9462. }
  9463. mg_set_thread_name("worker");
  9464. }
  9465. static int
  9466. mg_websocket_write_exec(struct mg_connection *conn,
  9467. int opcode,
  9468. const char *data,
  9469. size_t dataLen,
  9470. uint32_t masking_key)
  9471. {
  9472. unsigned char header[14];
  9473. size_t headerLen = 1;
  9474. int retval = -1;
  9475. #if defined(__GNUC__) || defined(__MINGW32__)
  9476. /* Disable spurious conversion warning for GCC */
  9477. #pragma GCC diagnostic push
  9478. #pragma GCC diagnostic ignored "-Wconversion"
  9479. #endif
  9480. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  9481. #if defined(__GNUC__) || defined(__MINGW32__)
  9482. #pragma GCC diagnostic pop
  9483. #endif
  9484. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  9485. if (dataLen < 126) {
  9486. /* inline 7-bit length field */
  9487. header[1] = (unsigned char)dataLen;
  9488. headerLen = 2;
  9489. } else if (dataLen <= 0xFFFF) {
  9490. /* 16-bit length field */
  9491. uint16_t len = htons((uint16_t)dataLen);
  9492. header[1] = 126;
  9493. memcpy(header + 2, &len, 2);
  9494. headerLen = 4;
  9495. } else {
  9496. /* 64-bit length field */
  9497. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  9498. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  9499. header[1] = 127;
  9500. memcpy(header + 2, &len1, 4);
  9501. memcpy(header + 6, &len2, 4);
  9502. headerLen = 10;
  9503. }
  9504. if (masking_key) {
  9505. /* add mask */
  9506. header[1] |= 0x80;
  9507. memcpy(header + headerLen, &masking_key, 4);
  9508. headerLen += 4;
  9509. }
  9510. /* Note that POSIX/Winsock's send() is threadsafe
  9511. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  9512. * but mongoose's mg_printf/mg_write is not (because of the loop in
  9513. * push(), although that is only a problem if the packet is large or
  9514. * outgoing buffer is full). */
  9515. /* TODO: Check if this lock should be moved to user land.
  9516. * Currently the server sets this lock for websockets, but
  9517. * not for any other connection. It must be set for every
  9518. * conn read/written by more than one thread, no matter if
  9519. * it is a websocket or regular connection. */
  9520. (void)mg_lock_connection(conn);
  9521. retval = mg_write(conn, header, headerLen);
  9522. if (dataLen > 0) {
  9523. retval = mg_write(conn, data, dataLen);
  9524. }
  9525. /* TODO: Remove this unlock as well, when lock is moved. */
  9526. mg_unlock_connection(conn);
  9527. return retval;
  9528. }
  9529. int
  9530. mg_websocket_write(struct mg_connection *conn,
  9531. int opcode,
  9532. const char *data,
  9533. size_t dataLen)
  9534. {
  9535. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  9536. }
  9537. static void
  9538. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  9539. {
  9540. size_t i = 0;
  9541. i = 0;
  9542. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  9543. /* Convert in 32 bit words, if data is 4 byte aligned */
  9544. while (i < (in_len - 3)) {
  9545. *(uint32_t *)(void *)(out + i) =
  9546. *(uint32_t *)(void *)(in + i) ^ masking_key;
  9547. i += 4;
  9548. }
  9549. }
  9550. if (i != in_len) {
  9551. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  9552. while (i < in_len) {
  9553. *(uint8_t *)(void *)(out + i) =
  9554. *(uint8_t *)(void *)(in + i)
  9555. ^ *(((uint8_t *)&masking_key) + (i % 4));
  9556. i++;
  9557. }
  9558. }
  9559. }
  9560. int
  9561. mg_websocket_client_write(struct mg_connection *conn,
  9562. int opcode,
  9563. const char *data,
  9564. size_t dataLen)
  9565. {
  9566. int retval = -1;
  9567. char *masked_data =
  9568. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->ctx);
  9569. uint32_t masking_key = (uint32_t)get_random();
  9570. if (masked_data == NULL) {
  9571. /* Return -1 in an error case */
  9572. mg_cry(conn,
  9573. "Cannot allocate buffer for masked websocket response: "
  9574. "Out of memory");
  9575. return -1;
  9576. }
  9577. mask_data(data, dataLen, masking_key, masked_data);
  9578. retval = mg_websocket_write_exec(
  9579. conn, opcode, masked_data, dataLen, masking_key);
  9580. mg_free(masked_data);
  9581. return retval;
  9582. }
  9583. static void
  9584. handle_websocket_request(struct mg_connection *conn,
  9585. const char *path,
  9586. int is_callback_resource,
  9587. struct mg_websocket_subprotocols *subprotocols,
  9588. mg_websocket_connect_handler ws_connect_handler,
  9589. mg_websocket_ready_handler ws_ready_handler,
  9590. mg_websocket_data_handler ws_data_handler,
  9591. mg_websocket_close_handler ws_close_handler,
  9592. void *cbData)
  9593. {
  9594. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  9595. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  9596. int lua_websock = 0;
  9597. #if !defined(USE_LUA)
  9598. (void)path;
  9599. #endif
  9600. /* Step 1: Check websocket protocol version. */
  9601. /* Step 1.1: Check Sec-WebSocket-Key. */
  9602. if (!websock_key) {
  9603. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  9604. * requires a Sec-WebSocket-Key header.
  9605. */
  9606. /* It could be the hixie draft version
  9607. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  9608. */
  9609. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  9610. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  9611. char key3[8];
  9612. if ((key1 != NULL) && (key2 != NULL)) {
  9613. /* This version uses 8 byte body data in a GET request */
  9614. conn->content_len = 8;
  9615. if (8 == mg_read(conn, key3, 8)) {
  9616. /* This is the hixie version */
  9617. mg_send_http_error(conn,
  9618. 426,
  9619. "%s",
  9620. "Protocol upgrade to RFC 6455 required");
  9621. return;
  9622. }
  9623. }
  9624. /* This is an unknown version */
  9625. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  9626. return;
  9627. }
  9628. /* Step 1.2: Check websocket protocol version. */
  9629. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  9630. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  9631. /* Reject wrong versions */
  9632. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  9633. return;
  9634. }
  9635. /* Step 1.3: Could check for "Host", but we do not really nead this
  9636. * value for anything, so just ignore it. */
  9637. /* Step 2: If a callback is responsible, call it. */
  9638. if (is_callback_resource) {
  9639. /* Step 2.1 check and select subprotocol */
  9640. const char *protocols[64]; // max 64 headers
  9641. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  9642. "Sec-WebSocket-Protocol",
  9643. protocols,
  9644. 64);
  9645. if ((nbSubprotocolHeader > 0) && subprotocols) {
  9646. int cnt = 0;
  9647. int idx;
  9648. unsigned long len;
  9649. const char *sep, *curSubProtocol,
  9650. *acceptedWebSocketSubprotocol = NULL;
  9651. /* look for matching subprotocol */
  9652. do {
  9653. const char *protocol = protocols[cnt];
  9654. do {
  9655. sep = strchr(protocol, ',');
  9656. curSubProtocol = protocol;
  9657. len = sep ? (unsigned long)(sep - protocol)
  9658. : (unsigned long)strlen(protocol);
  9659. while (sep && isspace(*++sep))
  9660. ; // ignore leading whitespaces
  9661. protocol = sep;
  9662. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  9663. if ((strlen(subprotocols->subprotocols[idx]) == len)
  9664. && (strncmp(curSubProtocol,
  9665. subprotocols->subprotocols[idx],
  9666. len) == 0)) {
  9667. acceptedWebSocketSubprotocol =
  9668. subprotocols->subprotocols[idx];
  9669. break;
  9670. }
  9671. }
  9672. } while (sep && !acceptedWebSocketSubprotocol);
  9673. } while (++cnt < nbSubprotocolHeader
  9674. && !acceptedWebSocketSubprotocol);
  9675. conn->request_info.acceptedWebSocketSubprotocol =
  9676. acceptedWebSocketSubprotocol;
  9677. } else if (nbSubprotocolHeader > 0) {
  9678. /* keep legacy behavior */
  9679. const char *protocol = protocols[0];
  9680. /* The protocol is a comma separated list of names. */
  9681. /* The server must only return one value from this list. */
  9682. /* First check if it is a list or just a single value. */
  9683. const char *sep = strrchr(protocol, ',');
  9684. if (sep == NULL) {
  9685. /* Just a single protocol -> accept it. */
  9686. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  9687. } else {
  9688. /* Multiple protocols -> accept the last one. */
  9689. /* This is just a quick fix if the client offers multiple
  9690. * protocols. The handler should have a list of accepted
  9691. * protocols on his own
  9692. * and use it to select one protocol among those the client
  9693. * has
  9694. * offered.
  9695. */
  9696. while (isspace(*++sep)) {
  9697. ; /* ignore leading whitespaces */
  9698. }
  9699. conn->request_info.acceptedWebSocketSubprotocol = sep;
  9700. }
  9701. }
  9702. if ((ws_connect_handler != NULL)
  9703. && (ws_connect_handler(conn, cbData) != 0)) {
  9704. /* C callback has returned non-zero, do not proceed with
  9705. * handshake.
  9706. */
  9707. /* Note that C callbacks are no longer called when Lua is
  9708. * responsible, so C can no longer filter callbacks for Lua. */
  9709. return;
  9710. }
  9711. }
  9712. #if defined(USE_LUA)
  9713. /* Step 3: No callback. Check if Lua is responsible. */
  9714. else {
  9715. /* Step 3.1: Check if Lua is responsible. */
  9716. if (conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  9717. lua_websock =
  9718. match_prefix(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  9719. strlen(
  9720. conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  9721. path);
  9722. }
  9723. if (lua_websock) {
  9724. /* Step 3.2: Lua is responsible: call it. */
  9725. conn->lua_websocket_state = lua_websocket_new(path, conn);
  9726. if (!conn->lua_websocket_state) {
  9727. /* Lua rejected the new client */
  9728. return;
  9729. }
  9730. }
  9731. }
  9732. #endif
  9733. /* Step 4: Check if there is a responsible websocket handler. */
  9734. if (!is_callback_resource && !lua_websock) {
  9735. /* There is no callback, and Lua is not responsible either. */
  9736. /* Reply with a 404 Not Found. We are still at a standard
  9737. * HTTP request here, before the websocket handshake, so
  9738. * we can still send standard HTTP error replies. */
  9739. mg_send_http_error(conn, 404, "%s", "Not found");
  9740. return;
  9741. }
  9742. /* Step 5: The websocket connection has been accepted */
  9743. if (!send_websocket_handshake(conn, websock_key)) {
  9744. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  9745. return;
  9746. }
  9747. /* Step 6: Call the ready handler */
  9748. if (is_callback_resource) {
  9749. if (ws_ready_handler != NULL) {
  9750. ws_ready_handler(conn, cbData);
  9751. }
  9752. #if defined(USE_LUA)
  9753. } else if (lua_websock) {
  9754. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  9755. /* the ready handler returned false */
  9756. return;
  9757. }
  9758. #endif
  9759. }
  9760. /* Step 7: Enter the read loop */
  9761. if (is_callback_resource) {
  9762. read_websocket(conn, ws_data_handler, cbData);
  9763. #if defined(USE_LUA)
  9764. } else if (lua_websock) {
  9765. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  9766. #endif
  9767. }
  9768. /* Step 8: Call the close handler */
  9769. if (ws_close_handler) {
  9770. ws_close_handler(conn, cbData);
  9771. }
  9772. }
  9773. static int
  9774. is_websocket_protocol(const struct mg_connection *conn)
  9775. {
  9776. const char *upgrade, *connection;
  9777. /* A websocket protocoll has the following HTTP headers:
  9778. *
  9779. * Connection: Upgrade
  9780. * Upgrade: Websocket
  9781. */
  9782. upgrade = mg_get_header(conn, "Upgrade");
  9783. if (upgrade == NULL) {
  9784. return 0; /* fail early, don't waste time checking other header
  9785. * fields
  9786. */
  9787. }
  9788. if (!mg_strcasestr(upgrade, "websocket")) {
  9789. return 0;
  9790. }
  9791. connection = mg_get_header(conn, "Connection");
  9792. if (connection == NULL) {
  9793. return 0;
  9794. }
  9795. if (!mg_strcasestr(connection, "upgrade")) {
  9796. return 0;
  9797. }
  9798. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  9799. * "Sec-WebSocket-Version" are also required.
  9800. * Don't check them here, since even an unsupported websocket protocol
  9801. * request still IS a websocket request (in contrast to a standard HTTP
  9802. * request). It will fail later in handle_websocket_request.
  9803. */
  9804. return 1;
  9805. }
  9806. #endif /* !USE_WEBSOCKET */
  9807. static int
  9808. isbyte(int n)
  9809. {
  9810. return (n >= 0) && (n <= 255);
  9811. }
  9812. static int
  9813. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  9814. {
  9815. int n, a, b, c, d, slash = 32, len = 0;
  9816. if (((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5)
  9817. || (sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4))
  9818. && isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && (slash >= 0)
  9819. && (slash < 33)) {
  9820. len = n;
  9821. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  9822. | (uint32_t)d;
  9823. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  9824. }
  9825. return len;
  9826. }
  9827. static int
  9828. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  9829. {
  9830. int throttle = 0;
  9831. struct vec vec, val;
  9832. uint32_t net, mask;
  9833. char mult;
  9834. double v;
  9835. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  9836. mult = ',';
  9837. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  9838. || (v < 0) || ((lowercase(&mult) != 'k')
  9839. && (lowercase(&mult) != 'm') && (mult != ','))) {
  9840. continue;
  9841. }
  9842. v *= (lowercase(&mult) == 'k')
  9843. ? 1024
  9844. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  9845. if (vec.len == 1 && vec.ptr[0] == '*') {
  9846. throttle = (int)v;
  9847. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  9848. if ((remote_ip & mask) == net) {
  9849. throttle = (int)v;
  9850. }
  9851. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  9852. throttle = (int)v;
  9853. }
  9854. }
  9855. return throttle;
  9856. }
  9857. static uint32_t
  9858. get_remote_ip(const struct mg_connection *conn)
  9859. {
  9860. if (!conn) {
  9861. return 0;
  9862. }
  9863. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  9864. }
  9865. /* The mg_upload function is superseeded by mg_handle_form_request. */
  9866. #include "handle_form.inl"
  9867. #if defined(MG_LEGACY_INTERFACE)
  9868. /* Implement the deprecated mg_upload function by calling the new
  9869. * mg_handle_form_request function. While mg_upload could only handle
  9870. * HTML forms sent as POST request in multipart/form-data format
  9871. * containing only file input elements, mg_handle_form_request can
  9872. * handle all form input elements and all standard request methods. */
  9873. struct mg_upload_user_data {
  9874. struct mg_connection *conn;
  9875. const char *destination_dir;
  9876. int num_uploaded_files;
  9877. };
  9878. /* Helper function for deprecated mg_upload. */
  9879. static int
  9880. mg_upload_field_found(const char *key,
  9881. const char *filename,
  9882. char *path,
  9883. size_t pathlen,
  9884. void *user_data)
  9885. {
  9886. int truncated = 0;
  9887. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  9888. (void)key;
  9889. if (!filename) {
  9890. mg_cry(fud->conn, "%s: No filename set", __func__);
  9891. return FORM_FIELD_STORAGE_ABORT;
  9892. }
  9893. mg_snprintf(fud->conn,
  9894. &truncated,
  9895. path,
  9896. pathlen - 1,
  9897. "%s/%s",
  9898. fud->destination_dir,
  9899. filename);
  9900. if (!truncated) {
  9901. mg_cry(fud->conn, "%s: File path too long", __func__);
  9902. return FORM_FIELD_STORAGE_ABORT;
  9903. }
  9904. return FORM_FIELD_STORAGE_STORE;
  9905. }
  9906. /* Helper function for deprecated mg_upload. */
  9907. static int
  9908. mg_upload_field_get(const char *key,
  9909. const char *value,
  9910. size_t value_size,
  9911. void *user_data)
  9912. {
  9913. /* Function should never be called */
  9914. (void)key;
  9915. (void)value;
  9916. (void)value_size;
  9917. (void)user_data;
  9918. return 0;
  9919. }
  9920. /* Helper function for deprecated mg_upload. */
  9921. static int
  9922. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  9923. {
  9924. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  9925. (void)file_size;
  9926. fud->num_uploaded_files++;
  9927. fud->conn->ctx->callbacks.upload(fud->conn, path);
  9928. return 0;
  9929. }
  9930. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  9931. int
  9932. mg_upload(struct mg_connection *conn, const char *destination_dir)
  9933. {
  9934. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  9935. struct mg_form_data_handler fdh = {mg_upload_field_found,
  9936. mg_upload_field_get,
  9937. mg_upload_field_stored,
  9938. 0};
  9939. int ret;
  9940. fdh.user_data = (void *)&fud;
  9941. ret = mg_handle_form_request(conn, &fdh);
  9942. if (ret < 0) {
  9943. mg_cry(conn, "%s: Error while parsing the request", __func__);
  9944. }
  9945. return fud.num_uploaded_files;
  9946. }
  9947. #endif
  9948. static int
  9949. get_first_ssl_listener_index(const struct mg_context *ctx)
  9950. {
  9951. unsigned int i;
  9952. int idx = -1;
  9953. if (ctx) {
  9954. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  9955. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  9956. }
  9957. }
  9958. return idx;
  9959. }
  9960. static void
  9961. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  9962. {
  9963. char host[1025];
  9964. const char *host_header;
  9965. size_t hostlen;
  9966. host_header = mg_get_header(conn, "Host");
  9967. hostlen = sizeof(host);
  9968. if (host_header != NULL) {
  9969. char *pos;
  9970. mg_strlcpy(host, host_header, hostlen);
  9971. host[hostlen - 1] = '\0';
  9972. pos = strchr(host, ':');
  9973. if (pos != NULL) {
  9974. *pos = '\0';
  9975. }
  9976. } else {
  9977. /* Cannot get host from the Host: header.
  9978. * Fallback to our IP address. */
  9979. if (conn) {
  9980. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  9981. }
  9982. }
  9983. /* Send host, port, uri and (if it exists) ?query_string */
  9984. if (conn) {
  9985. mg_printf(conn,
  9986. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  9987. host,
  9988. #if defined(USE_IPV6)
  9989. (conn->ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  9990. == AF_INET6)
  9991. ? (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  9992. .lsa.sin6.sin6_port)
  9993. :
  9994. #endif
  9995. (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  9996. .lsa.sin.sin_port),
  9997. conn->request_info.local_uri,
  9998. (conn->request_info.query_string == NULL) ? "" : "?",
  9999. (conn->request_info.query_string == NULL)
  10000. ? ""
  10001. : conn->request_info.query_string);
  10002. }
  10003. }
  10004. static void
  10005. mg_set_handler_type(struct mg_context *ctx,
  10006. const char *uri,
  10007. int handler_type,
  10008. int is_delete_request,
  10009. mg_request_handler handler,
  10010. struct mg_websocket_subprotocols *subprotocols,
  10011. mg_websocket_connect_handler connect_handler,
  10012. mg_websocket_ready_handler ready_handler,
  10013. mg_websocket_data_handler data_handler,
  10014. mg_websocket_close_handler close_handler,
  10015. mg_authorization_handler auth_handler,
  10016. void *cbdata)
  10017. {
  10018. struct mg_handler_info *tmp_rh, **lastref;
  10019. size_t urilen = strlen(uri);
  10020. if (handler_type == WEBSOCKET_HANDLER) {
  10021. /* assert(handler == NULL); */
  10022. /* assert(is_delete_request || connect_handler!=NULL ||
  10023. * ready_handler!=NULL || data_handler!=NULL ||
  10024. * close_handler!=NULL);
  10025. */
  10026. /* assert(auth_handler == NULL); */
  10027. if (handler != NULL) {
  10028. return;
  10029. }
  10030. if (!is_delete_request && (connect_handler == NULL)
  10031. && (ready_handler == NULL) && (data_handler == NULL)
  10032. && (close_handler == NULL)) {
  10033. return;
  10034. }
  10035. if (auth_handler != NULL) {
  10036. return;
  10037. }
  10038. } else if (handler_type == REQUEST_HANDLER) {
  10039. /* assert(connect_handler==NULL && ready_handler==NULL &&
  10040. * data_handler==NULL && close_handler==NULL); */
  10041. /* assert(is_delete_request || (handler!=NULL));
  10042. */
  10043. /* assert(auth_handler == NULL); */
  10044. if ((connect_handler != NULL) || (ready_handler != NULL)
  10045. || (data_handler != NULL) || (close_handler != NULL)) {
  10046. return;
  10047. }
  10048. if (!is_delete_request && (handler == NULL)) {
  10049. return;
  10050. }
  10051. if (auth_handler != NULL) {
  10052. return;
  10053. }
  10054. } else { /* AUTH_HANDLER */
  10055. /* assert(handler == NULL); */
  10056. /* assert(connect_handler==NULL && ready_handler==NULL &&
  10057. * data_handler==NULL && close_handler==NULL); */
  10058. /* assert(auth_handler != NULL); */
  10059. if (handler != NULL) {
  10060. return;
  10061. }
  10062. if ((connect_handler != NULL) || (ready_handler != NULL)
  10063. || (data_handler != NULL) || (close_handler != NULL)) {
  10064. return;
  10065. }
  10066. if (!is_delete_request && (auth_handler == NULL)) {
  10067. return;
  10068. }
  10069. }
  10070. if (!ctx) {
  10071. return;
  10072. }
  10073. mg_lock_context(ctx);
  10074. /* first try to find an existing handler */
  10075. lastref = &(ctx->handlers);
  10076. for (tmp_rh = ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  10077. if (tmp_rh->handler_type == handler_type) {
  10078. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  10079. if (!is_delete_request) {
  10080. /* update existing handler */
  10081. if (handler_type == REQUEST_HANDLER) {
  10082. tmp_rh->handler = handler;
  10083. } else if (handler_type == WEBSOCKET_HANDLER) {
  10084. tmp_rh->subprotocols = subprotocols;
  10085. tmp_rh->connect_handler = connect_handler;
  10086. tmp_rh->ready_handler = ready_handler;
  10087. tmp_rh->data_handler = data_handler;
  10088. tmp_rh->close_handler = close_handler;
  10089. } else { /* AUTH_HANDLER */
  10090. tmp_rh->auth_handler = auth_handler;
  10091. }
  10092. tmp_rh->cbdata = cbdata;
  10093. } else {
  10094. /* remove existing handler */
  10095. *lastref = tmp_rh->next;
  10096. mg_free(tmp_rh->uri);
  10097. mg_free(tmp_rh);
  10098. }
  10099. mg_unlock_context(ctx);
  10100. return;
  10101. }
  10102. }
  10103. lastref = &(tmp_rh->next);
  10104. }
  10105. if (is_delete_request) {
  10106. /* no handler to set, this was a remove request to a non-existing
  10107. * handler */
  10108. mg_unlock_context(ctx);
  10109. return;
  10110. }
  10111. tmp_rh =
  10112. (struct mg_handler_info *)mg_calloc_ctx(sizeof(struct mg_handler_info),
  10113. 1,
  10114. ctx);
  10115. if (tmp_rh == NULL) {
  10116. mg_unlock_context(ctx);
  10117. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  10118. return;
  10119. }
  10120. tmp_rh->uri = mg_strdup(uri);
  10121. if (!tmp_rh->uri) {
  10122. mg_unlock_context(ctx);
  10123. mg_free(tmp_rh);
  10124. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  10125. return;
  10126. }
  10127. tmp_rh->uri_len = urilen;
  10128. if (handler_type == REQUEST_HANDLER) {
  10129. tmp_rh->handler = handler;
  10130. } else if (handler_type == WEBSOCKET_HANDLER) {
  10131. tmp_rh->subprotocols = subprotocols;
  10132. tmp_rh->connect_handler = connect_handler;
  10133. tmp_rh->ready_handler = ready_handler;
  10134. tmp_rh->data_handler = data_handler;
  10135. tmp_rh->close_handler = close_handler;
  10136. } else { /* AUTH_HANDLER */
  10137. tmp_rh->auth_handler = auth_handler;
  10138. }
  10139. tmp_rh->cbdata = cbdata;
  10140. tmp_rh->handler_type = handler_type;
  10141. tmp_rh->next = NULL;
  10142. *lastref = tmp_rh;
  10143. mg_unlock_context(ctx);
  10144. }
  10145. void
  10146. mg_set_request_handler(struct mg_context *ctx,
  10147. const char *uri,
  10148. mg_request_handler handler,
  10149. void *cbdata)
  10150. {
  10151. mg_set_handler_type(ctx,
  10152. uri,
  10153. REQUEST_HANDLER,
  10154. handler == NULL,
  10155. handler,
  10156. NULL,
  10157. NULL,
  10158. NULL,
  10159. NULL,
  10160. NULL,
  10161. NULL,
  10162. cbdata);
  10163. }
  10164. void
  10165. mg_set_websocket_handler(struct mg_context *ctx,
  10166. const char *uri,
  10167. mg_websocket_connect_handler connect_handler,
  10168. mg_websocket_ready_handler ready_handler,
  10169. mg_websocket_data_handler data_handler,
  10170. mg_websocket_close_handler close_handler,
  10171. void *cbdata)
  10172. {
  10173. mg_set_websocket_handler_with_subprotocols(ctx,
  10174. uri,
  10175. NULL,
  10176. connect_handler,
  10177. ready_handler,
  10178. data_handler,
  10179. close_handler,
  10180. cbdata);
  10181. }
  10182. void
  10183. mg_set_websocket_handler_with_subprotocols(
  10184. struct mg_context *ctx,
  10185. const char *uri,
  10186. struct mg_websocket_subprotocols *subprotocols,
  10187. mg_websocket_connect_handler connect_handler,
  10188. mg_websocket_ready_handler ready_handler,
  10189. mg_websocket_data_handler data_handler,
  10190. mg_websocket_close_handler close_handler,
  10191. void *cbdata)
  10192. {
  10193. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  10194. && (data_handler == NULL)
  10195. && (close_handler == NULL);
  10196. mg_set_handler_type(ctx,
  10197. uri,
  10198. WEBSOCKET_HANDLER,
  10199. is_delete_request,
  10200. NULL,
  10201. subprotocols,
  10202. connect_handler,
  10203. ready_handler,
  10204. data_handler,
  10205. close_handler,
  10206. NULL,
  10207. cbdata);
  10208. }
  10209. void
  10210. mg_set_auth_handler(struct mg_context *ctx,
  10211. const char *uri,
  10212. mg_request_handler handler,
  10213. void *cbdata)
  10214. {
  10215. mg_set_handler_type(ctx,
  10216. uri,
  10217. AUTH_HANDLER,
  10218. handler == NULL,
  10219. NULL,
  10220. NULL,
  10221. NULL,
  10222. NULL,
  10223. NULL,
  10224. NULL,
  10225. handler,
  10226. cbdata);
  10227. }
  10228. static int
  10229. get_request_handler(struct mg_connection *conn,
  10230. int handler_type,
  10231. mg_request_handler *handler,
  10232. struct mg_websocket_subprotocols **subprotocols,
  10233. mg_websocket_connect_handler *connect_handler,
  10234. mg_websocket_ready_handler *ready_handler,
  10235. mg_websocket_data_handler *data_handler,
  10236. mg_websocket_close_handler *close_handler,
  10237. mg_authorization_handler *auth_handler,
  10238. void **cbdata)
  10239. {
  10240. const struct mg_request_info *request_info = mg_get_request_info(conn);
  10241. if (request_info) {
  10242. const char *uri = request_info->local_uri;
  10243. size_t urilen = strlen(uri);
  10244. struct mg_handler_info *tmp_rh;
  10245. if (!conn || !conn->ctx) {
  10246. return 0;
  10247. }
  10248. mg_lock_context(conn->ctx);
  10249. /* first try for an exact match */
  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 ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  10254. if (handler_type == WEBSOCKET_HANDLER) {
  10255. *subprotocols = tmp_rh->subprotocols;
  10256. *connect_handler = tmp_rh->connect_handler;
  10257. *ready_handler = tmp_rh->ready_handler;
  10258. *data_handler = tmp_rh->data_handler;
  10259. *close_handler = tmp_rh->close_handler;
  10260. } else if (handler_type == REQUEST_HANDLER) {
  10261. *handler = tmp_rh->handler;
  10262. } else { /* AUTH_HANDLER */
  10263. *auth_handler = tmp_rh->auth_handler;
  10264. }
  10265. *cbdata = tmp_rh->cbdata;
  10266. mg_unlock_context(conn->ctx);
  10267. return 1;
  10268. }
  10269. }
  10270. }
  10271. /* next try for a partial match, we will accept uri/something */
  10272. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  10273. tmp_rh = tmp_rh->next) {
  10274. if (tmp_rh->handler_type == handler_type) {
  10275. if ((tmp_rh->uri_len < urilen) && (uri[tmp_rh->uri_len] == '/')
  10276. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 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. /* finally try for pattern match */
  10295. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  10296. tmp_rh = tmp_rh->next) {
  10297. if (tmp_rh->handler_type == handler_type) {
  10298. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  10299. if (handler_type == WEBSOCKET_HANDLER) {
  10300. *subprotocols = tmp_rh->subprotocols;
  10301. *connect_handler = tmp_rh->connect_handler;
  10302. *ready_handler = tmp_rh->ready_handler;
  10303. *data_handler = tmp_rh->data_handler;
  10304. *close_handler = tmp_rh->close_handler;
  10305. } else if (handler_type == REQUEST_HANDLER) {
  10306. *handler = tmp_rh->handler;
  10307. } else { /* AUTH_HANDLER */
  10308. *auth_handler = tmp_rh->auth_handler;
  10309. }
  10310. *cbdata = tmp_rh->cbdata;
  10311. mg_unlock_context(conn->ctx);
  10312. return 1;
  10313. }
  10314. }
  10315. }
  10316. mg_unlock_context(conn->ctx);
  10317. }
  10318. return 0; /* none found */
  10319. }
  10320. /* Check if the script file is in a path, allowed for script files.
  10321. * This can be used if uploading files is possible not only for the server
  10322. * admin, and the upload mechanism does not check the file extension.
  10323. */
  10324. static int
  10325. is_in_script_path(const struct mg_connection *conn, const char *path)
  10326. {
  10327. /* TODO (Feature): Add config value for allowed script path.
  10328. * Default: All allowed. */
  10329. (void)conn;
  10330. (void)path;
  10331. return 1;
  10332. }
  10333. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  10334. static int
  10335. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  10336. void *cbdata)
  10337. {
  10338. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  10339. if (pcallbacks->websocket_connect) {
  10340. return pcallbacks->websocket_connect(conn);
  10341. }
  10342. /* No handler set - assume "OK" */
  10343. return 0;
  10344. }
  10345. static void
  10346. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  10347. {
  10348. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  10349. if (pcallbacks->websocket_ready) {
  10350. pcallbacks->websocket_ready(conn);
  10351. }
  10352. }
  10353. static int
  10354. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  10355. int bits,
  10356. char *data,
  10357. size_t len,
  10358. void *cbdata)
  10359. {
  10360. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  10361. if (pcallbacks->websocket_data) {
  10362. return pcallbacks->websocket_data(conn, bits, data, len);
  10363. }
  10364. /* No handler set - assume "OK" */
  10365. return 1;
  10366. }
  10367. #endif
  10368. /* This is the heart of the Civetweb's logic.
  10369. * This function is called when the request is read, parsed and validated,
  10370. * and Civetweb must decide what action to take: serve a file, or
  10371. * a directory, or call embedded function, etcetera. */
  10372. static void
  10373. handle_request(struct mg_connection *conn)
  10374. {
  10375. struct mg_request_info *ri = &conn->request_info;
  10376. char path[PATH_MAX];
  10377. int uri_len, ssl_index;
  10378. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  10379. is_put_or_delete_request = 0, is_callback_resource = 0;
  10380. int i;
  10381. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10382. mg_request_handler callback_handler = NULL;
  10383. struct mg_websocket_subprotocols *subprotocols;
  10384. mg_websocket_connect_handler ws_connect_handler = NULL;
  10385. mg_websocket_ready_handler ws_ready_handler = NULL;
  10386. mg_websocket_data_handler ws_data_handler = NULL;
  10387. mg_websocket_close_handler ws_close_handler = NULL;
  10388. void *callback_data = NULL;
  10389. mg_authorization_handler auth_handler = NULL;
  10390. void *auth_callback_data = NULL;
  10391. int handler_type;
  10392. time_t curtime = time(NULL);
  10393. char date[64];
  10394. path[0] = 0;
  10395. /* 1. get the request url */
  10396. /* 1.1. split into url and query string */
  10397. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  10398. != NULL) {
  10399. *((char *)conn->request_info.query_string++) = '\0';
  10400. }
  10401. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  10402. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  10403. ssl_index = get_first_ssl_listener_index(conn->ctx);
  10404. if (ssl_index >= 0) {
  10405. redirect_to_https_port(conn, ssl_index);
  10406. } else {
  10407. /* A http to https forward port has been specified,
  10408. * but no https port to forward to. */
  10409. mg_send_http_error(conn,
  10410. 503,
  10411. "%s",
  10412. "Error: SSL forward not configured properly");
  10413. mg_cry(conn, "Can not redirect to SSL, no SSL port available");
  10414. }
  10415. return;
  10416. }
  10417. uri_len = (int)strlen(ri->local_uri);
  10418. /* 1.3. decode url (if config says so) */
  10419. if (should_decode_url(conn)) {
  10420. mg_url_decode(
  10421. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  10422. }
  10423. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  10424. * not possible */
  10425. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  10426. /* step 1. completed, the url is known now */
  10427. uri_len = (int)strlen(ri->local_uri);
  10428. DEBUG_TRACE("URL: %s", ri->local_uri);
  10429. /* 2. if this ip has limited speed, set it for this connection */
  10430. conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
  10431. get_remote_ip(conn),
  10432. ri->local_uri);
  10433. /* 3. call a "handle everything" callback, if registered */
  10434. if (conn->ctx->callbacks.begin_request != NULL) {
  10435. /* Note that since V1.7 the "begin_request" function is called
  10436. * before an authorization check. If an authorization check is
  10437. * required, use a request_handler instead. */
  10438. i = conn->ctx->callbacks.begin_request(conn);
  10439. if (i > 0) {
  10440. /* callback already processed the request. Store the
  10441. return value as a status code for the access log. */
  10442. conn->status_code = i;
  10443. discard_unread_request_data(conn);
  10444. return;
  10445. } else if (i == 0) {
  10446. /* civetweb should process the request */
  10447. } else {
  10448. /* unspecified - may change with the next version */
  10449. return;
  10450. }
  10451. }
  10452. /* request not yet handled by a handler or redirect, so the request
  10453. * is processed here */
  10454. /* 4. Check for CORS preflight requests and handle them (if configured).
  10455. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  10456. */
  10457. if (!strcmp(ri->request_method, "OPTIONS")) {
  10458. /* Send a response to CORS preflights only if
  10459. * access_control_allow_methods is not NULL and not an empty string.
  10460. * In this case, scripts can still handle CORS. */
  10461. const char *cors_meth_cfg =
  10462. conn->ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  10463. const char *cors_orig_cfg =
  10464. conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  10465. const char *cors_origin =
  10466. get_header(ri->http_headers, ri->num_headers, "Origin");
  10467. const char *cors_acrm = get_header(ri->http_headers,
  10468. ri->num_headers,
  10469. "Access-Control-Request-Method");
  10470. /* Todo: check if cors_origin is in cors_orig_cfg.
  10471. * Or, let the client check this. */
  10472. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  10473. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  10474. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  10475. /* This is a valid CORS preflight, and the server is configured
  10476. * to
  10477. * handle it automatically. */
  10478. const char *cors_acrh =
  10479. get_header(ri->http_headers,
  10480. ri->num_headers,
  10481. "Access-Control-Request-Headers");
  10482. gmt_time_string(date, sizeof(date), &curtime);
  10483. mg_printf(conn,
  10484. "HTTP/1.1 200 OK\r\n"
  10485. "Date: %s\r\n"
  10486. "Access-Control-Allow-Origin: %s\r\n"
  10487. "Access-Control-Allow-Methods: %s\r\n"
  10488. "Content-Length: 0\r\n"
  10489. "Connection: %s\r\n",
  10490. date,
  10491. cors_orig_cfg,
  10492. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  10493. suggest_connection_header(conn));
  10494. if (cors_acrh != NULL) {
  10495. /* CORS request is asking for additional headers */
  10496. const char *cors_hdr_cfg =
  10497. conn->ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  10498. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  10499. /* Allow only if access_control_allow_headers is
  10500. * not NULL and not an empty string. If this
  10501. * configuration is set to *, allow everything.
  10502. * Otherwise this configuration must be a list
  10503. * of allowed HTTP header names. */
  10504. mg_printf(conn,
  10505. "Access-Control-Allow-Headers: %s\r\n",
  10506. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  10507. : cors_hdr_cfg));
  10508. }
  10509. }
  10510. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  10511. mg_printf(conn, "\r\n");
  10512. return;
  10513. }
  10514. }
  10515. /* 5. interpret the url to find out how the request must be handled
  10516. */
  10517. /* 5.1. first test, if the request targets the regular http(s)://
  10518. * protocol namespace or the websocket ws(s):// protocol namespace.
  10519. */
  10520. is_websocket_request = is_websocket_protocol(conn);
  10521. #if defined(USE_WEBSOCKET)
  10522. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  10523. #else
  10524. handler_type = REQUEST_HANDLER;
  10525. #endif /* defined(USE_WEBSOCKET) */
  10526. /* 5.2. check if the request will be handled by a callback */
  10527. if (get_request_handler(conn,
  10528. handler_type,
  10529. &callback_handler,
  10530. &subprotocols,
  10531. &ws_connect_handler,
  10532. &ws_ready_handler,
  10533. &ws_data_handler,
  10534. &ws_close_handler,
  10535. NULL,
  10536. &callback_data)) {
  10537. /* 5.2.1. A callback will handle this request. All requests
  10538. * handled
  10539. * by a callback have to be considered as requests to a script
  10540. * resource. */
  10541. is_callback_resource = 1;
  10542. is_script_resource = 1;
  10543. is_put_or_delete_request = is_put_or_delete_method(conn);
  10544. } else {
  10545. no_callback_resource:
  10546. /* 5.2.2. No callback is responsible for this request. The URI
  10547. * addresses a file based resource (static content or Lua/cgi
  10548. * scripts in the file system). */
  10549. is_callback_resource = 0;
  10550. interpret_uri(conn,
  10551. path,
  10552. sizeof(path),
  10553. &file.stat,
  10554. &is_found,
  10555. &is_script_resource,
  10556. &is_websocket_request,
  10557. &is_put_or_delete_request);
  10558. }
  10559. /* 6. authorization check */
  10560. /* 6.1. a custom authorization handler is installed */
  10561. if (get_request_handler(conn,
  10562. AUTH_HANDLER,
  10563. NULL,
  10564. NULL,
  10565. NULL,
  10566. NULL,
  10567. NULL,
  10568. NULL,
  10569. &auth_handler,
  10570. &auth_callback_data)) {
  10571. if (!auth_handler(conn, auth_callback_data)) {
  10572. return;
  10573. }
  10574. } else if (is_put_or_delete_request && !is_script_resource
  10575. && !is_callback_resource) {
  10576. /* 6.2. this request is a PUT/DELETE to a real file */
  10577. /* 6.2.1. thus, the server must have real files */
  10578. #if defined(NO_FILES)
  10579. if (1) {
  10580. #else
  10581. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  10582. #endif
  10583. /* This server does not have any real files, thus the
  10584. * PUT/DELETE methods are not valid. */
  10585. mg_send_http_error(conn,
  10586. 405,
  10587. "%s method not allowed",
  10588. conn->request_info.request_method);
  10589. return;
  10590. }
  10591. #if !defined(NO_FILES)
  10592. /* 6.2.2. Check if put authorization for static files is
  10593. * available.
  10594. */
  10595. if (!is_authorized_for_put(conn)) {
  10596. send_authorization_request(conn);
  10597. return;
  10598. }
  10599. #endif
  10600. } else {
  10601. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  10602. * or it is a PUT or DELETE request to a resource that does not
  10603. * correspond to a file. Check authorization. */
  10604. if (!check_authorization(conn, path)) {
  10605. send_authorization_request(conn);
  10606. return;
  10607. }
  10608. }
  10609. /* request is authorized or does not need authorization */
  10610. /* 7. check if there are request handlers for this uri */
  10611. if (is_callback_resource) {
  10612. if (!is_websocket_request) {
  10613. i = callback_handler(conn, callback_data);
  10614. if (i > 0) {
  10615. /* Do nothing, callback has served the request. Store
  10616. * then return value as status code for the log and discard
  10617. * all data from the client not used by the callback. */
  10618. conn->status_code = i;
  10619. discard_unread_request_data(conn);
  10620. } else {
  10621. /* The handler did NOT handle the request. */
  10622. /* Some proper reactions would be:
  10623. * a) close the connections without sending anything
  10624. * b) send a 404 not found
  10625. * c) try if there is a file matching the URI
  10626. * It would be possible to do a, b or c in the callback
  10627. * implementation, and return 1 - we cannot do anything
  10628. * here, that is not possible in the callback.
  10629. *
  10630. * TODO: What would be the best reaction here?
  10631. * (Note: The reaction may change, if there is a better
  10632. *idea.)
  10633. */
  10634. /* For the moment, use option c: We look for a proper file,
  10635. * but since a file request is not always a script resource,
  10636. * the authorization check might be different. */
  10637. interpret_uri(conn,
  10638. path,
  10639. sizeof(path),
  10640. &file.stat,
  10641. &is_found,
  10642. &is_script_resource,
  10643. &is_websocket_request,
  10644. &is_put_or_delete_request);
  10645. callback_handler = NULL;
  10646. /* Here we are at a dead end:
  10647. * According to URI matching, a callback should be
  10648. * responsible for handling the request,
  10649. * we called it, but the callback declared itself
  10650. * not responsible.
  10651. * We use a goto here, to get out of this dead end,
  10652. * and continue with the default handling.
  10653. * A goto here is simpler and better to understand
  10654. * than some curious loop. */
  10655. goto no_callback_resource;
  10656. }
  10657. } else {
  10658. #if defined(USE_WEBSOCKET)
  10659. handle_websocket_request(conn,
  10660. path,
  10661. is_callback_resource,
  10662. subprotocols,
  10663. ws_connect_handler,
  10664. ws_ready_handler,
  10665. ws_data_handler,
  10666. ws_close_handler,
  10667. callback_data);
  10668. #endif
  10669. }
  10670. return;
  10671. }
  10672. /* 8. handle websocket requests */
  10673. #if defined(USE_WEBSOCKET)
  10674. if (is_websocket_request) {
  10675. if (is_script_resource) {
  10676. if (is_in_script_path(conn, path)) {
  10677. /* Websocket Lua script */
  10678. handle_websocket_request(conn,
  10679. path,
  10680. 0 /* Lua Script */,
  10681. NULL,
  10682. NULL,
  10683. NULL,
  10684. NULL,
  10685. NULL,
  10686. &conn->ctx->callbacks);
  10687. } else {
  10688. /* Script was in an illegal path */
  10689. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10690. }
  10691. } else {
  10692. #if defined(MG_LEGACY_INTERFACE)
  10693. handle_websocket_request(
  10694. conn,
  10695. path,
  10696. !is_script_resource /* could be deprecated global callback */,
  10697. NULL,
  10698. deprecated_websocket_connect_wrapper,
  10699. deprecated_websocket_ready_wrapper,
  10700. deprecated_websocket_data_wrapper,
  10701. NULL,
  10702. &conn->ctx->callbacks);
  10703. #else
  10704. mg_send_http_error(conn, 404, "%s", "Not found");
  10705. #endif
  10706. }
  10707. return;
  10708. } else
  10709. #endif
  10710. #if defined(NO_FILES)
  10711. /* 9a. In case the server uses only callbacks, this uri is
  10712. * unknown.
  10713. * Then, all request handling ends here. */
  10714. mg_send_http_error(conn, 404, "%s", "Not Found");
  10715. #else
  10716. /* 9b. This request is either for a static file or resource handled
  10717. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  10718. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  10719. mg_send_http_error(conn, 404, "%s", "Not Found");
  10720. return;
  10721. }
  10722. /* 10. Request is handled by a script */
  10723. if (is_script_resource) {
  10724. handle_file_based_request(conn, path, &file);
  10725. return;
  10726. }
  10727. /* 11. Handle put/delete/mkcol requests */
  10728. if (is_put_or_delete_request) {
  10729. /* 11.1. PUT method */
  10730. if (!strcmp(ri->request_method, "PUT")) {
  10731. put_file(conn, path);
  10732. return;
  10733. }
  10734. /* 11.2. DELETE method */
  10735. if (!strcmp(ri->request_method, "DELETE")) {
  10736. delete_file(conn, path);
  10737. return;
  10738. }
  10739. /* 11.3. MKCOL method */
  10740. if (!strcmp(ri->request_method, "MKCOL")) {
  10741. mkcol(conn, path);
  10742. return;
  10743. }
  10744. /* 11.4. PATCH method
  10745. * This method is not supported for static resources,
  10746. * only for scripts (Lua, CGI) and callbacks. */
  10747. mg_send_http_error(conn,
  10748. 405,
  10749. "%s method not allowed",
  10750. conn->request_info.request_method);
  10751. return;
  10752. }
  10753. /* 11. File does not exist, or it was configured that it should be
  10754. * hidden */
  10755. if (!is_found || (must_hide_file(conn, path))) {
  10756. mg_send_http_error(conn, 404, "%s", "Not found");
  10757. return;
  10758. }
  10759. /* 12. Directory uris should end with a slash */
  10760. if (file.stat.is_directory && (uri_len > 0)
  10761. && (ri->local_uri[uri_len - 1] != '/')) {
  10762. gmt_time_string(date, sizeof(date), &curtime);
  10763. mg_printf(conn,
  10764. "HTTP/1.1 301 Moved Permanently\r\n"
  10765. "Location: %s/\r\n"
  10766. "Date: %s\r\n"
  10767. /* "Cache-Control: private\r\n" (= default) */
  10768. "Content-Length: 0\r\n"
  10769. "Connection: %s\r\n",
  10770. ri->request_uri,
  10771. date,
  10772. suggest_connection_header(conn));
  10773. send_additional_header(conn);
  10774. mg_printf(conn, "\r\n");
  10775. return;
  10776. }
  10777. /* 13. Handle other methods than GET/HEAD */
  10778. /* 13.1. Handle PROPFIND */
  10779. if (!strcmp(ri->request_method, "PROPFIND")) {
  10780. handle_propfind(conn, path, &file.stat);
  10781. return;
  10782. }
  10783. /* 13.2. Handle OPTIONS for files */
  10784. if (!strcmp(ri->request_method, "OPTIONS")) {
  10785. /* This standard handler is only used for real files.
  10786. * Scripts should support the OPTIONS method themselves, to allow a
  10787. * maximum flexibility.
  10788. * Lua and CGI scripts may fully support CORS this way (including
  10789. * preflights). */
  10790. send_options(conn);
  10791. return;
  10792. }
  10793. /* 13.3. everything but GET and HEAD (e.g. POST) */
  10794. if ((0 != strcmp(ri->request_method, "GET"))
  10795. && (0 != strcmp(ri->request_method, "HEAD"))) {
  10796. mg_send_http_error(conn,
  10797. 405,
  10798. "%s method not allowed",
  10799. conn->request_info.request_method);
  10800. return;
  10801. }
  10802. /* 14. directories */
  10803. if (file.stat.is_directory) {
  10804. /* Substitute files have already been handled above. */
  10805. /* Here we can either generate and send a directory listing,
  10806. * or send an "access denied" error. */
  10807. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  10808. "yes")) {
  10809. handle_directory_request(conn, path);
  10810. } else {
  10811. mg_send_http_error(conn,
  10812. 403,
  10813. "%s",
  10814. "Error: Directory listing denied");
  10815. }
  10816. return;
  10817. }
  10818. handle_file_based_request(conn, path, &file);
  10819. #endif /* !defined(NO_FILES) */
  10820. #if 0
  10821. /* Perform redirect and auth checks before calling begin_request()
  10822. * handler.
  10823. * Otherwise, begin_request() would need to perform auth checks and
  10824. * redirects. */
  10825. #endif
  10826. }
  10827. static void
  10828. handle_file_based_request(struct mg_connection *conn,
  10829. const char *path,
  10830. struct mg_file *file)
  10831. {
  10832. if (!conn || !conn->ctx) {
  10833. return;
  10834. }
  10835. if (0) {
  10836. #ifdef USE_LUA
  10837. } else if (match_prefix(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  10838. strlen(
  10839. conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  10840. path) > 0) {
  10841. if (is_in_script_path(conn, path)) {
  10842. /* Lua server page: an SSI like page containing mostly plain
  10843. * html
  10844. * code
  10845. * plus some tags with server generated contents. */
  10846. handle_lsp_request(conn, path, file, NULL);
  10847. } else {
  10848. /* Script was in an illegal path */
  10849. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10850. }
  10851. } else if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  10852. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  10853. path) > 0) {
  10854. if (is_in_script_path(conn, path)) {
  10855. /* Lua in-server module script: a CGI like script used to
  10856. * generate
  10857. * the
  10858. * entire reply. */
  10859. mg_exec_lua_script(conn, path, NULL);
  10860. } else {
  10861. /* Script was in an illegal path */
  10862. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10863. }
  10864. #endif
  10865. #if defined(USE_DUKTAPE)
  10866. } else if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  10867. strlen(
  10868. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  10869. path) > 0) {
  10870. if (is_in_script_path(conn, path)) {
  10871. /* Call duktape to generate the page */
  10872. mg_exec_duktape_script(conn, path);
  10873. } else {
  10874. /* Script was in an illegal path */
  10875. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10876. }
  10877. #endif
  10878. #if !defined(NO_CGI)
  10879. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  10880. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  10881. path) > 0) {
  10882. if (is_in_script_path(conn, path)) {
  10883. /* CGI scripts may support all HTTP methods */
  10884. handle_cgi_request(conn, path);
  10885. } else {
  10886. /* Script was in an illegal path */
  10887. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10888. }
  10889. #endif /* !NO_CGI */
  10890. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  10891. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  10892. path) > 0) {
  10893. if (is_in_script_path(conn, path)) {
  10894. handle_ssi_file_request(conn, path, file);
  10895. } else {
  10896. /* Script was in an illegal path */
  10897. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10898. }
  10899. #if !defined(NO_CACHING)
  10900. } else if ((!conn->in_error_handler)
  10901. && is_not_modified(conn, &file->stat)) {
  10902. /* Send 304 "Not Modified" - this must not send any body data */
  10903. handle_not_modified_static_file_request(conn, file);
  10904. #endif /* !NO_CACHING */
  10905. } else {
  10906. handle_static_file_request(conn, path, file, NULL, NULL);
  10907. }
  10908. }
  10909. static void
  10910. close_all_listening_sockets(struct mg_context *ctx)
  10911. {
  10912. unsigned int i;
  10913. if (!ctx) {
  10914. return;
  10915. }
  10916. for (i = 0; i < ctx->num_listening_sockets; i++) {
  10917. closesocket(ctx->listening_sockets[i].sock);
  10918. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  10919. }
  10920. mg_free(ctx->listening_sockets);
  10921. ctx->listening_sockets = NULL;
  10922. mg_free(ctx->listening_socket_fds);
  10923. ctx->listening_socket_fds = NULL;
  10924. }
  10925. /* Valid listening port specification is: [ip_address:]port[s]
  10926. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  10927. * Examples for IPv6: [::]:80, [::1]:80,
  10928. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  10929. * see https://tools.ietf.org/html/rfc3513#section-2.2
  10930. * In order to bind to both, IPv4 and IPv6, you can either add
  10931. * both ports using 8080,[::]:8080, or the short form +8080.
  10932. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  10933. * one only accepting IPv4 the other only IPv6. +8080 creates
  10934. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  10935. * environment, they might work differently, or might not work
  10936. * at all - it must be tested what options work best in the
  10937. * relevant network environment.
  10938. */
  10939. static int
  10940. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  10941. {
  10942. unsigned int a, b, c, d, port;
  10943. int ch, len;
  10944. char *cb;
  10945. #if defined(USE_IPV6)
  10946. char buf[100] = {0};
  10947. #endif
  10948. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  10949. * Also, all-zeroes in the socket address means binding to all addresses
  10950. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  10951. memset(so, 0, sizeof(*so));
  10952. so->lsa.sin.sin_family = AF_INET;
  10953. *ip_version = 0;
  10954. /* Initialize port and len as invalid. */
  10955. port = 0;
  10956. len = 0;
  10957. /* Test for different ways to format this string */
  10958. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  10959. == 5) {
  10960. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  10961. so->lsa.sin.sin_addr.s_addr =
  10962. htonl((a << 24) | (b << 16) | (c << 8) | d);
  10963. so->lsa.sin.sin_port = htons((uint16_t)port);
  10964. *ip_version = 4;
  10965. #if defined(USE_IPV6)
  10966. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  10967. && mg_inet_pton(
  10968. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  10969. /* IPv6 address, examples: see above */
  10970. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  10971. */
  10972. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  10973. *ip_version = 6;
  10974. #endif
  10975. } else if ((vec->ptr[0] == '+')
  10976. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  10977. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  10978. /* Add 1 to len for the + character we skipped before */
  10979. len++;
  10980. #if defined(USE_IPV6)
  10981. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  10982. so->lsa.sin6.sin6_family = AF_INET6;
  10983. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  10984. *ip_version = 4 + 6;
  10985. #else
  10986. /* Bind to IPv4 only, since IPv6 is not built in. */
  10987. so->lsa.sin.sin_port = htons((uint16_t)port);
  10988. *ip_version = 4;
  10989. #endif
  10990. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  10991. /* If only port is specified, bind to IPv4, INADDR_ANY */
  10992. so->lsa.sin.sin_port = htons((uint16_t)port);
  10993. *ip_version = 4;
  10994. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  10995. /* Could be a hostname */
  10996. /* Will only work for RFC 952 compliant hostnames,
  10997. * starting with a letter, containing only letters,
  10998. * digits and hyphen ('-'). Newer specs may allow
  10999. * more, but this is not guaranteed here, since it
  11000. * may interfere with rules for port option lists. */
  11001. *cb = 0;
  11002. if (mg_inet_pton(
  11003. AF_INET, vec->ptr, &so->lsa.sin, sizeof(so->lsa.sin))) {
  11004. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  11005. *ip_version = 4;
  11006. so->lsa.sin.sin_family = AF_INET;
  11007. so->lsa.sin.sin_port = htons((uint16_t)port);
  11008. len += (int)(cb - vec->ptr) + 1;
  11009. } else {
  11010. port = 0;
  11011. len = 0;
  11012. }
  11013. #if defined(USE_IPV6)
  11014. } else if (mg_inet_pton(AF_INET6,
  11015. vec->ptr,
  11016. &so->lsa.sin6,
  11017. sizeof(so->lsa.sin6))) {
  11018. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  11019. *ip_version = 6;
  11020. so->lsa.sin6.sin6_family = AF_INET6;
  11021. so->lsa.sin.sin_port = htons((uint16_t)port);
  11022. len += (int)(cb - vec->ptr) + 1;
  11023. } else {
  11024. port = 0;
  11025. len = 0;
  11026. }
  11027. #endif
  11028. }
  11029. *cb = ':';
  11030. } else {
  11031. /* Parsing failure. */
  11032. }
  11033. /* sscanf and the option splitting code ensure the following condition
  11034. */
  11035. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  11036. *ip_version = 0;
  11037. return 0;
  11038. }
  11039. ch = vec->ptr[len]; /* Next character after the port number */
  11040. so->is_ssl = (ch == 's');
  11041. so->ssl_redir = (ch == 'r');
  11042. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  11043. if (is_valid_port(port)
  11044. && ((ch == '\0') || (ch == 's') || (ch == 'r') || (ch == ','))) {
  11045. return 1;
  11046. }
  11047. /* Reset ip_version to 0 of there is an error */
  11048. *ip_version = 0;
  11049. return 0;
  11050. }
  11051. static int
  11052. set_ports_option(struct mg_context *ctx)
  11053. {
  11054. const char *list;
  11055. int on = 1;
  11056. #if defined(USE_IPV6)
  11057. int off = 0;
  11058. #endif
  11059. struct vec vec;
  11060. struct socket so, *ptr;
  11061. struct pollfd *pfd;
  11062. union usa usa;
  11063. socklen_t len;
  11064. int ip_version;
  11065. int portsTotal = 0;
  11066. int portsOk = 0;
  11067. if (!ctx) {
  11068. return 0;
  11069. }
  11070. memset(&so, 0, sizeof(so));
  11071. memset(&usa, 0, sizeof(usa));
  11072. len = sizeof(usa);
  11073. list = ctx->config[LISTENING_PORTS];
  11074. while ((list = next_option(list, &vec, NULL)) != NULL) {
  11075. portsTotal++;
  11076. if (!parse_port_string(&vec, &so, &ip_version)) {
  11077. mg_cry(fc(ctx),
  11078. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  11079. (int)vec.len,
  11080. vec.ptr,
  11081. portsTotal,
  11082. "[IP_ADDRESS:]PORT[s|r]");
  11083. continue;
  11084. }
  11085. #if !defined(NO_SSL)
  11086. if (so.is_ssl && ctx->ssl_ctx == NULL) {
  11087. mg_cry(fc(ctx),
  11088. "Cannot add SSL socket (entry %i). Is -ssl_certificate "
  11089. "option set?",
  11090. portsTotal);
  11091. continue;
  11092. }
  11093. #endif
  11094. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  11095. == INVALID_SOCKET) {
  11096. mg_cry(fc(ctx), "cannot create socket (entry %i)", portsTotal);
  11097. continue;
  11098. }
  11099. #ifdef _WIN32
  11100. /* Windows SO_REUSEADDR lets many procs binds to a
  11101. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  11102. * if someone already has the socket -- DTL */
  11103. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  11104. * Windows might need a few seconds before
  11105. * the same port can be used again in the
  11106. * same process, so a short Sleep may be
  11107. * required between mg_stop and mg_start.
  11108. */
  11109. if (setsockopt(so.sock,
  11110. SOL_SOCKET,
  11111. SO_EXCLUSIVEADDRUSE,
  11112. (SOCK_OPT_TYPE)&on,
  11113. sizeof(on)) != 0) {
  11114. /* Set reuse option, but don't abort on errors. */
  11115. mg_cry(fc(ctx),
  11116. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  11117. portsTotal);
  11118. }
  11119. #else
  11120. if (setsockopt(so.sock,
  11121. SOL_SOCKET,
  11122. SO_REUSEADDR,
  11123. (SOCK_OPT_TYPE)&on,
  11124. sizeof(on)) != 0) {
  11125. /* Set reuse option, but don't abort on errors. */
  11126. mg_cry(fc(ctx),
  11127. "cannot set socket option SO_REUSEADDR (entry %i)",
  11128. portsTotal);
  11129. }
  11130. #endif
  11131. if (ip_version > 4) {
  11132. #if defined(USE_IPV6)
  11133. if (ip_version == 6) {
  11134. if (so.lsa.sa.sa_family == AF_INET6
  11135. && setsockopt(so.sock,
  11136. IPPROTO_IPV6,
  11137. IPV6_V6ONLY,
  11138. (void *)&off,
  11139. sizeof(off)) != 0) {
  11140. /* Set IPv6 only option, but don't abort on errors. */
  11141. mg_cry(fc(ctx),
  11142. "cannot set socket option IPV6_V6ONLY (entry %i)",
  11143. portsTotal);
  11144. }
  11145. }
  11146. #else
  11147. mg_cry(fc(ctx), "IPv6 not available");
  11148. closesocket(so.sock);
  11149. so.sock = INVALID_SOCKET;
  11150. continue;
  11151. #endif
  11152. }
  11153. if (so.lsa.sa.sa_family == AF_INET) {
  11154. len = sizeof(so.lsa.sin);
  11155. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  11156. mg_cry(fc(ctx),
  11157. "cannot bind to %.*s: %d (%s)",
  11158. (int)vec.len,
  11159. vec.ptr,
  11160. (int)ERRNO,
  11161. strerror(errno));
  11162. closesocket(so.sock);
  11163. so.sock = INVALID_SOCKET;
  11164. continue;
  11165. }
  11166. }
  11167. #if defined(USE_IPV6)
  11168. else if (so.lsa.sa.sa_family == AF_INET6) {
  11169. len = sizeof(so.lsa.sin6);
  11170. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  11171. mg_cry(fc(ctx),
  11172. "cannot bind to IPv6 %.*s: %d (%s)",
  11173. (int)vec.len,
  11174. vec.ptr,
  11175. (int)ERRNO,
  11176. strerror(errno));
  11177. closesocket(so.sock);
  11178. so.sock = INVALID_SOCKET;
  11179. continue;
  11180. }
  11181. }
  11182. #endif
  11183. else {
  11184. mg_cry(fc(ctx),
  11185. "cannot bind: address family not supported (entry %i)",
  11186. portsTotal);
  11187. closesocket(so.sock);
  11188. so.sock = INVALID_SOCKET;
  11189. continue;
  11190. }
  11191. if (listen(so.sock, SOMAXCONN) != 0) {
  11192. mg_cry(fc(ctx),
  11193. "cannot listen to %.*s: %d (%s)",
  11194. (int)vec.len,
  11195. vec.ptr,
  11196. (int)ERRNO,
  11197. strerror(errno));
  11198. closesocket(so.sock);
  11199. so.sock = INVALID_SOCKET;
  11200. continue;
  11201. }
  11202. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  11203. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  11204. int err = (int)ERRNO;
  11205. mg_cry(fc(ctx),
  11206. "call to getsockname failed %.*s: %d (%s)",
  11207. (int)vec.len,
  11208. vec.ptr,
  11209. err,
  11210. strerror(errno));
  11211. closesocket(so.sock);
  11212. so.sock = INVALID_SOCKET;
  11213. continue;
  11214. }
  11215. /* Update lsa port in case of random free ports */
  11216. #if defined(USE_IPV6)
  11217. if (so.lsa.sa.sa_family == AF_INET6) {
  11218. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  11219. } else
  11220. #endif
  11221. {
  11222. so.lsa.sin.sin_port = usa.sin.sin_port;
  11223. }
  11224. if ((ptr = (struct socket *)
  11225. mg_realloc_ctx(ctx->listening_sockets,
  11226. (ctx->num_listening_sockets + 1)
  11227. * sizeof(ctx->listening_sockets[0]),
  11228. ctx)) == NULL) {
  11229. mg_cry(fc(ctx), "%s", "Out of memory");
  11230. closesocket(so.sock);
  11231. so.sock = INVALID_SOCKET;
  11232. continue;
  11233. }
  11234. if ((pfd = (struct pollfd *)
  11235. mg_realloc_ctx(ctx->listening_socket_fds,
  11236. (ctx->num_listening_sockets + 1)
  11237. * sizeof(ctx->listening_socket_fds[0]),
  11238. ctx)) == NULL) {
  11239. mg_cry(fc(ctx), "%s", "Out of memory");
  11240. closesocket(so.sock);
  11241. so.sock = INVALID_SOCKET;
  11242. mg_free(ptr);
  11243. continue;
  11244. }
  11245. set_close_on_exec(so.sock, fc(ctx));
  11246. ctx->listening_sockets = ptr;
  11247. ctx->listening_sockets[ctx->num_listening_sockets] = so;
  11248. ctx->listening_socket_fds = pfd;
  11249. ctx->num_listening_sockets++;
  11250. portsOk++;
  11251. }
  11252. if (portsOk != portsTotal) {
  11253. close_all_listening_sockets(ctx);
  11254. portsOk = 0;
  11255. }
  11256. return portsOk;
  11257. }
  11258. static const char *
  11259. header_val(const struct mg_connection *conn, const char *header)
  11260. {
  11261. const char *header_value;
  11262. if ((header_value = mg_get_header(conn, header)) == NULL) {
  11263. return "-";
  11264. } else {
  11265. return header_value;
  11266. }
  11267. }
  11268. static void
  11269. log_access(const struct mg_connection *conn)
  11270. {
  11271. const struct mg_request_info *ri;
  11272. struct mg_file fi;
  11273. char date[64], src_addr[IP_ADDR_STR_LEN];
  11274. struct tm *tm;
  11275. const char *referer;
  11276. const char *user_agent;
  11277. char buf[4096];
  11278. if (!conn || !conn->ctx) {
  11279. return;
  11280. }
  11281. if (conn->ctx->config[ACCESS_LOG_FILE] != NULL) {
  11282. if (mg_fopen(conn,
  11283. conn->ctx->config[ACCESS_LOG_FILE],
  11284. MG_FOPEN_MODE_APPEND,
  11285. &fi) == 0) {
  11286. fi.access.fp = NULL;
  11287. }
  11288. } else {
  11289. fi.access.fp = NULL;
  11290. }
  11291. /* Log is written to a file and/or a callback. If both are not set,
  11292. * executing the rest of the function is pointless. */
  11293. if ((fi.access.fp == NULL) && (conn->ctx->callbacks.log_access == NULL)) {
  11294. return;
  11295. }
  11296. tm = localtime(&conn->conn_birth_time);
  11297. if (tm != NULL) {
  11298. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  11299. } else {
  11300. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  11301. date[sizeof(date) - 1] = '\0';
  11302. }
  11303. ri = &conn->request_info;
  11304. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  11305. referer = header_val(conn, "Referer");
  11306. user_agent = header_val(conn, "User-Agent");
  11307. mg_snprintf(conn,
  11308. NULL, /* Ignore truncation in access log */
  11309. buf,
  11310. sizeof(buf),
  11311. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  11312. src_addr,
  11313. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  11314. date,
  11315. ri->request_method ? ri->request_method : "-",
  11316. ri->request_uri ? ri->request_uri : "-",
  11317. ri->query_string ? "?" : "",
  11318. ri->query_string ? ri->query_string : "",
  11319. ri->http_version,
  11320. conn->status_code,
  11321. conn->num_bytes_sent,
  11322. referer,
  11323. user_agent);
  11324. if (conn->ctx->callbacks.log_access) {
  11325. conn->ctx->callbacks.log_access(conn, buf);
  11326. }
  11327. if (fi.access.fp) {
  11328. int ok = 1;
  11329. flockfile(fi.access.fp);
  11330. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  11331. ok = 0;
  11332. }
  11333. if (fflush(fi.access.fp) != 0) {
  11334. ok = 0;
  11335. }
  11336. funlockfile(fi.access.fp);
  11337. if (mg_fclose(&fi.access) != 0) {
  11338. ok = 0;
  11339. }
  11340. if (!ok) {
  11341. mg_cry(conn,
  11342. "Error writing log file %s",
  11343. conn->ctx->config[ACCESS_LOG_FILE]);
  11344. }
  11345. }
  11346. }
  11347. /* Verify given socket address against the ACL.
  11348. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  11349. */
  11350. static int
  11351. check_acl(struct mg_context *ctx, uint32_t remote_ip)
  11352. {
  11353. int allowed, flag;
  11354. uint32_t net, mask;
  11355. struct vec vec;
  11356. if (ctx) {
  11357. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  11358. /* If any ACL is set, deny by default */
  11359. allowed = (list == NULL) ? '+' : '-';
  11360. while ((list = next_option(list, &vec, NULL)) != NULL) {
  11361. flag = vec.ptr[0];
  11362. if ((flag != '+' && flag != '-')
  11363. || (parse_net(&vec.ptr[1], &net, &mask) == 0)) {
  11364. mg_cry(fc(ctx),
  11365. "%s: subnet must be [+|-]x.x.x.x[/x]",
  11366. __func__);
  11367. return -1;
  11368. }
  11369. if (net == (remote_ip & mask)) {
  11370. allowed = flag;
  11371. }
  11372. }
  11373. return allowed == '+';
  11374. }
  11375. return -1;
  11376. }
  11377. #if !defined(_WIN32)
  11378. static int
  11379. set_uid_option(struct mg_context *ctx)
  11380. {
  11381. struct passwd *pw;
  11382. if (ctx) {
  11383. const char *uid = ctx->config[RUN_AS_USER];
  11384. int success = 0;
  11385. if (uid == NULL) {
  11386. success = 1;
  11387. } else {
  11388. if ((pw = getpwnam(uid)) == NULL) {
  11389. mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  11390. } else if (setgid(pw->pw_gid) == -1) {
  11391. mg_cry(fc(ctx),
  11392. "%s: setgid(%s): %s",
  11393. __func__,
  11394. uid,
  11395. strerror(errno));
  11396. } else if (setgroups(0, NULL)) {
  11397. mg_cry(fc(ctx),
  11398. "%s: setgroups(): %s",
  11399. __func__,
  11400. strerror(errno));
  11401. } else if (setuid(pw->pw_uid) == -1) {
  11402. mg_cry(fc(ctx),
  11403. "%s: setuid(%s): %s",
  11404. __func__,
  11405. uid,
  11406. strerror(errno));
  11407. } else {
  11408. success = 1;
  11409. }
  11410. }
  11411. return success;
  11412. }
  11413. return 0;
  11414. }
  11415. #endif /* !_WIN32 */
  11416. static void
  11417. tls_dtor(void *key)
  11418. {
  11419. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  11420. /* key == pthread_getspecific(sTlsKey); */
  11421. if (tls) {
  11422. if (tls->is_master == 2) {
  11423. tls->is_master = -3; /* Mark memory as dead */
  11424. mg_free(tls);
  11425. }
  11426. }
  11427. pthread_setspecific(sTlsKey, NULL);
  11428. }
  11429. #if !defined(NO_SSL)
  11430. static int
  11431. ssl_use_pem_file(struct mg_context *ctx, const char *pem, const char *chain);
  11432. static const char *ssl_error(void);
  11433. static int
  11434. refresh_trust(struct mg_connection *conn)
  11435. {
  11436. static int reload_lock = 0;
  11437. static long int data_check = 0;
  11438. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  11439. struct stat cert_buf;
  11440. long int t;
  11441. const char *pem;
  11442. const char *chain;
  11443. int should_verify_peer;
  11444. if ((pem = conn->ctx->config[SSL_CERTIFICATE]) == NULL) {
  11445. /* If peem is NULL and conn->ctx->callbacks.init_ssl is not,
  11446. * refresh_trust still can not work. */
  11447. return 0;
  11448. }
  11449. chain = conn->ctx->config[SSL_CERTIFICATE_CHAIN];
  11450. if (chain == NULL) {
  11451. /* pem is not NULL here */
  11452. chain = pem;
  11453. }
  11454. if (*chain == 0) {
  11455. chain = NULL;
  11456. }
  11457. t = data_check;
  11458. if (stat(pem, &cert_buf) != -1) {
  11459. t = (long int)cert_buf.st_mtime;
  11460. }
  11461. if (data_check != t) {
  11462. data_check = t;
  11463. should_verify_peer = 0;
  11464. if (conn->ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  11465. if (mg_strcasecmp(conn->ctx->config[SSL_DO_VERIFY_PEER], "yes")
  11466. == 0) {
  11467. should_verify_peer = 1;
  11468. } else if (mg_strcasecmp(conn->ctx->config[SSL_DO_VERIFY_PEER],
  11469. "optional") == 0) {
  11470. should_verify_peer = 1;
  11471. }
  11472. }
  11473. if (should_verify_peer) {
  11474. char *ca_path = conn->ctx->config[SSL_CA_PATH];
  11475. char *ca_file = conn->ctx->config[SSL_CA_FILE];
  11476. if (SSL_CTX_load_verify_locations(conn->ctx->ssl_ctx,
  11477. ca_file,
  11478. ca_path) != 1) {
  11479. mg_cry(fc(conn->ctx),
  11480. "SSL_CTX_load_verify_locations error: %s "
  11481. "ssl_verify_peer requires setting "
  11482. "either ssl_ca_path or ssl_ca_file. Is any of them "
  11483. "present in "
  11484. "the .conf file?",
  11485. ssl_error());
  11486. return 0;
  11487. }
  11488. }
  11489. if (1 == mg_atomic_inc(p_reload_lock)) {
  11490. if (ssl_use_pem_file(conn->ctx, pem, chain) == 0) {
  11491. return 0;
  11492. }
  11493. *p_reload_lock = 0;
  11494. }
  11495. }
  11496. /* lock while cert is reloading */
  11497. while (*p_reload_lock) {
  11498. sleep(1);
  11499. }
  11500. return 1;
  11501. }
  11502. #ifdef OPENSSL_API_1_1
  11503. #else
  11504. static pthread_mutex_t *ssl_mutexes;
  11505. #endif /* OPENSSL_API_1_1 */
  11506. static int
  11507. sslize(struct mg_connection *conn,
  11508. SSL_CTX *s,
  11509. int (*func)(SSL *),
  11510. volatile int *stop_server)
  11511. {
  11512. int ret, err;
  11513. int short_trust;
  11514. unsigned i;
  11515. if (!conn) {
  11516. return 0;
  11517. }
  11518. short_trust =
  11519. (conn->ctx->config[SSL_SHORT_TRUST] != NULL)
  11520. && (mg_strcasecmp(conn->ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  11521. if (short_trust) {
  11522. int trust_ret = refresh_trust(conn);
  11523. if (!trust_ret) {
  11524. return trust_ret;
  11525. }
  11526. }
  11527. conn->ssl = SSL_new(s);
  11528. if (conn->ssl == NULL) {
  11529. return 0;
  11530. }
  11531. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  11532. if (ret != 1) {
  11533. err = SSL_get_error(conn->ssl, ret);
  11534. (void)err; /* TODO: set some error message */
  11535. SSL_free(conn->ssl);
  11536. conn->ssl = NULL;
  11537. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  11538. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  11539. #ifndef OPENSSL_API_1_1
  11540. ERR_remove_state(0);
  11541. #endif
  11542. return 0;
  11543. }
  11544. /* SSL functions may fail and require to be called again:
  11545. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  11546. * Here "func" could be SSL_connect or SSL_accept. */
  11547. for (i = 16; i <= 1024; i *= 2) {
  11548. ret = func(conn->ssl);
  11549. if (ret != 1) {
  11550. err = SSL_get_error(conn->ssl, ret);
  11551. if ((err == SSL_ERROR_WANT_CONNECT)
  11552. || (err == SSL_ERROR_WANT_ACCEPT)
  11553. || (err == SSL_ERROR_WANT_READ)
  11554. || (err == SSL_ERROR_WANT_WRITE)) {
  11555. /* Need to retry the function call "later".
  11556. * See https://linux.die.net/man/3/ssl_get_error
  11557. * This is typical for non-blocking sockets. */
  11558. if (*stop_server) {
  11559. /* Don't wait if the server is going to be stopped. */
  11560. break;
  11561. }
  11562. mg_sleep(i);
  11563. } else if (err == SSL_ERROR_SYSCALL) {
  11564. /* This is an IO error. Look at errno. */
  11565. err = errno;
  11566. /* TODO: set some error message */
  11567. (void)err;
  11568. break;
  11569. } else {
  11570. /* This is an SSL specific error */
  11571. /* TODO: set some error message */
  11572. break;
  11573. }
  11574. } else {
  11575. /* success */
  11576. break;
  11577. }
  11578. }
  11579. if (ret != 1) {
  11580. SSL_free(conn->ssl);
  11581. conn->ssl = NULL;
  11582. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  11583. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  11584. #ifndef OPENSSL_API_1_1
  11585. ERR_remove_state(0);
  11586. #endif
  11587. return 0;
  11588. }
  11589. return 1;
  11590. }
  11591. /* Return OpenSSL error message (from CRYPTO lib) */
  11592. static const char *
  11593. ssl_error(void)
  11594. {
  11595. unsigned long err;
  11596. err = ERR_get_error();
  11597. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  11598. }
  11599. static int
  11600. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  11601. {
  11602. int i;
  11603. const char hexdigit[] = "0123456789abcdef";
  11604. if ((memlen <= 0) || (buflen <= 0)) {
  11605. return 0;
  11606. }
  11607. if (buflen < (3 * memlen)) {
  11608. return 0;
  11609. }
  11610. for (i = 0; i < memlen; i++) {
  11611. if (i > 0) {
  11612. buf[3 * i - 1] = ' ';
  11613. }
  11614. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  11615. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  11616. }
  11617. buf[3 * memlen - 1] = 0;
  11618. return 1;
  11619. }
  11620. static void
  11621. ssl_get_client_cert_info(struct mg_connection *conn)
  11622. {
  11623. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  11624. if (cert) {
  11625. char str_subject[1024];
  11626. char str_issuer[1024];
  11627. char str_finger[1024];
  11628. unsigned char buf[256];
  11629. char *str_serial = NULL;
  11630. unsigned int ulen;
  11631. int ilen;
  11632. unsigned char *tmp_buf;
  11633. unsigned char *tmp_p;
  11634. /* Handle to algorithm used for fingerprint */
  11635. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  11636. /* Get Subject and issuer */
  11637. X509_NAME *subj = X509_get_subject_name(cert);
  11638. X509_NAME *iss = X509_get_issuer_name(cert);
  11639. /* Get serial number */
  11640. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  11641. /* Translate serial number to a hex string */
  11642. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  11643. str_serial = BN_bn2hex(serial_bn);
  11644. BN_free(serial_bn);
  11645. /* Translate subject and issuer to a string */
  11646. (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
  11647. (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
  11648. /* Calculate SHA1 fingerprint and store as a hex string */
  11649. ulen = 0;
  11650. /* ASN1_digest is deprecated. Do the calculation manually,
  11651. * using EVP_Digest. */
  11652. ilen = i2d_X509((void *)cert, NULL);
  11653. tmp_buf =
  11654. (ilen > 0)
  11655. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1, conn->ctx)
  11656. : NULL;
  11657. if (tmp_buf) {
  11658. tmp_p = tmp_buf;
  11659. (void)i2d_X509((void *)cert, &tmp_p);
  11660. if (!EVP_Digest(
  11661. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  11662. ulen = 0;
  11663. }
  11664. mg_free(tmp_buf);
  11665. }
  11666. if (!hexdump2string(
  11667. buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
  11668. *str_finger = 0;
  11669. }
  11670. conn->request_info.client_cert =
  11671. (struct client_cert *)mg_malloc_ctx(sizeof(struct client_cert),
  11672. conn->ctx);
  11673. if (conn->request_info.client_cert) {
  11674. conn->request_info.client_cert->subject = mg_strdup(str_subject);
  11675. conn->request_info.client_cert->issuer = mg_strdup(str_issuer);
  11676. conn->request_info.client_cert->serial = mg_strdup(str_serial);
  11677. conn->request_info.client_cert->finger = mg_strdup(str_finger);
  11678. } else {
  11679. mg_cry(conn,
  11680. "Out of memory: Cannot allocate memory for client "
  11681. "certificate");
  11682. }
  11683. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  11684. * see https://linux.die.net/man/3/bn_bn2hex */
  11685. OPENSSL_free(str_serial);
  11686. /* Free certificate memory */
  11687. X509_free(cert);
  11688. }
  11689. }
  11690. #ifdef OPENSSL_API_1_1
  11691. #else
  11692. static void
  11693. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  11694. {
  11695. (void)line;
  11696. (void)file;
  11697. if (mode & 1) {
  11698. /* 1 is CRYPTO_LOCK */
  11699. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  11700. } else {
  11701. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  11702. }
  11703. }
  11704. #endif /* OPENSSL_API_1_1 */
  11705. #if !defined(NO_SSL_DL)
  11706. static void *
  11707. load_dll(char *ebuf, size_t ebuf_len, const char *dll_name, struct ssl_func *sw)
  11708. {
  11709. union {
  11710. void *p;
  11711. void (*fp)(void);
  11712. } u;
  11713. void *dll_handle;
  11714. struct ssl_func *fp;
  11715. int ok;
  11716. int truncated = 0;
  11717. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  11718. mg_snprintf(NULL,
  11719. NULL, /* No truncation check for ebuf */
  11720. ebuf,
  11721. ebuf_len,
  11722. "%s: cannot load %s",
  11723. __func__,
  11724. dll_name);
  11725. return NULL;
  11726. }
  11727. ok = 1;
  11728. for (fp = sw; fp->name != NULL; fp++) {
  11729. #ifdef _WIN32
  11730. /* GetProcAddress() returns pointer to function */
  11731. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  11732. #else
  11733. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  11734. * pointers to function pointers. We need to use a union to make a
  11735. * cast. */
  11736. u.p = dlsym(dll_handle, fp->name);
  11737. #endif /* _WIN32 */
  11738. if (u.fp == NULL) {
  11739. if (ok) {
  11740. mg_snprintf(NULL,
  11741. &truncated,
  11742. ebuf,
  11743. ebuf_len,
  11744. "%s: %s: cannot find %s",
  11745. __func__,
  11746. dll_name,
  11747. fp->name);
  11748. ok = 0;
  11749. } else {
  11750. size_t cur_len = strlen(ebuf);
  11751. if (!truncated) {
  11752. mg_snprintf(NULL,
  11753. &truncated,
  11754. ebuf + cur_len,
  11755. ebuf_len - cur_len - 3,
  11756. ", %s",
  11757. fp->name);
  11758. if (truncated) {
  11759. /* If truncated, add "..." */
  11760. strcat(ebuf, "...");
  11761. }
  11762. }
  11763. }
  11764. /* Debug:
  11765. * printf("Missing function: %s\n", fp->name); */
  11766. } else {
  11767. fp->ptr = u.fp;
  11768. }
  11769. }
  11770. if (!ok) {
  11771. (void)dlclose(dll_handle);
  11772. return NULL;
  11773. }
  11774. return dll_handle;
  11775. }
  11776. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  11777. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  11778. #endif /* NO_SSL_DL */
  11779. #if defined(SSL_ALREADY_INITIALIZED)
  11780. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  11781. #else
  11782. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  11783. #endif
  11784. static int
  11785. initialize_ssl(char *ebuf, size_t ebuf_len)
  11786. {
  11787. #ifdef OPENSSL_API_1_1
  11788. if (ebuf_len > 0) {
  11789. ebuf[0] = 0;
  11790. }
  11791. #if !defined(NO_SSL_DL)
  11792. if (!cryptolib_dll_handle) {
  11793. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  11794. if (!cryptolib_dll_handle) {
  11795. return 0;
  11796. }
  11797. }
  11798. #endif /* NO_SSL_DL */
  11799. if (mg_atomic_inc(&cryptolib_users) > 1) {
  11800. return 1;
  11801. }
  11802. #else /* not OPENSSL_API_1_1 */
  11803. int i;
  11804. size_t size;
  11805. if (ebuf_len > 0) {
  11806. ebuf[0] = 0;
  11807. }
  11808. #if !defined(NO_SSL_DL)
  11809. if (!cryptolib_dll_handle) {
  11810. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  11811. if (!cryptolib_dll_handle) {
  11812. return 0;
  11813. }
  11814. }
  11815. #endif /* NO_SSL_DL */
  11816. if (mg_atomic_inc(&cryptolib_users) > 1) {
  11817. return 1;
  11818. }
  11819. /* Initialize locking callbacks, needed for thread safety.
  11820. * http://www.openssl.org/support/faq.html#PROG1
  11821. */
  11822. i = CRYPTO_num_locks();
  11823. if (i < 0) {
  11824. i = 0;
  11825. }
  11826. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  11827. if (size == 0) {
  11828. ssl_mutexes = NULL;
  11829. } else if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  11830. mg_snprintf(NULL,
  11831. NULL, /* No truncation check for ebuf */
  11832. ebuf,
  11833. ebuf_len,
  11834. "%s: cannot allocate mutexes: %s",
  11835. __func__,
  11836. ssl_error());
  11837. return 0;
  11838. }
  11839. for (i = 0; i < CRYPTO_num_locks(); i++) {
  11840. pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr);
  11841. }
  11842. CRYPTO_set_locking_callback(&ssl_locking_callback);
  11843. CRYPTO_set_id_callback(&mg_current_thread_id);
  11844. #endif /* OPENSSL_API_1_1 */
  11845. return 1;
  11846. }
  11847. static int
  11848. ssl_use_pem_file(struct mg_context *ctx, const char *pem, const char *chain)
  11849. {
  11850. if (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0) {
  11851. mg_cry(fc(ctx),
  11852. "%s: cannot open certificate file %s: %s",
  11853. __func__,
  11854. pem,
  11855. ssl_error());
  11856. return 0;
  11857. }
  11858. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  11859. if (SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0) {
  11860. mg_cry(fc(ctx),
  11861. "%s: cannot open private key file %s: %s",
  11862. __func__,
  11863. pem,
  11864. ssl_error());
  11865. return 0;
  11866. }
  11867. if (SSL_CTX_check_private_key(ctx->ssl_ctx) == 0) {
  11868. mg_cry(fc(ctx),
  11869. "%s: certificate and private key do not match: %s",
  11870. __func__,
  11871. pem);
  11872. return 0;
  11873. }
  11874. /* In contrast to OpenSSL, wolfSSL does not support certificate
  11875. * chain files that contain private keys and certificates in
  11876. * SSL_CTX_use_certificate_chain_file.
  11877. * The CivetWeb-Server used pem-Files that contained both information.
  11878. * In order to make wolfSSL work, it is split in two files.
  11879. * One file that contains key and certificate used by the server and
  11880. * an optional chain file for the ssl stack.
  11881. */
  11882. if (chain) {
  11883. if (SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, chain) == 0) {
  11884. mg_cry(fc(ctx),
  11885. "%s: cannot use certificate chain file %s: %s",
  11886. __func__,
  11887. pem,
  11888. ssl_error());
  11889. return 0;
  11890. }
  11891. }
  11892. return 1;
  11893. }
  11894. #ifdef OPENSSL_API_1_1
  11895. static unsigned long
  11896. ssl_get_protocol(int version_id)
  11897. {
  11898. long unsigned ret = SSL_OP_ALL;
  11899. if (version_id > 0)
  11900. ret |= SSL_OP_NO_SSLv2;
  11901. if (version_id > 1)
  11902. ret |= SSL_OP_NO_SSLv3;
  11903. if (version_id > 2)
  11904. ret |= SSL_OP_NO_TLSv1;
  11905. if (version_id > 3)
  11906. ret |= SSL_OP_NO_TLSv1_1;
  11907. return ret;
  11908. }
  11909. #else
  11910. static long
  11911. ssl_get_protocol(int version_id)
  11912. {
  11913. long ret = SSL_OP_ALL;
  11914. if (version_id > 0)
  11915. ret |= SSL_OP_NO_SSLv2;
  11916. if (version_id > 1)
  11917. ret |= SSL_OP_NO_SSLv3;
  11918. if (version_id > 2)
  11919. ret |= SSL_OP_NO_TLSv1;
  11920. if (version_id > 3)
  11921. ret |= SSL_OP_NO_TLSv1_1;
  11922. return ret;
  11923. }
  11924. #endif /* OPENSSL_API_1_1 */
  11925. /* Dynamically load SSL library. Set up ctx->ssl_ctx pointer. */
  11926. static int
  11927. set_ssl_option(struct mg_context *ctx)
  11928. {
  11929. const char *pem;
  11930. const char *chain;
  11931. int callback_ret;
  11932. int should_verify_peer;
  11933. int peer_certificate_optional;
  11934. const char *ca_path;
  11935. const char *ca_file;
  11936. int use_default_verify_paths;
  11937. int verify_depth;
  11938. time_t now_rt = time(NULL);
  11939. struct timespec now_mt;
  11940. md5_byte_t ssl_context_id[16];
  11941. md5_state_t md5state;
  11942. int protocol_ver;
  11943. char ebuf[128];
  11944. /* If PEM file is not specified and the init_ssl callback
  11945. * is not specified, skip SSL initialization. */
  11946. if (!ctx) {
  11947. return 0;
  11948. }
  11949. if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL
  11950. && ctx->callbacks.init_ssl == NULL) {
  11951. return 1;
  11952. }
  11953. chain = ctx->config[SSL_CERTIFICATE_CHAIN];
  11954. if (chain == NULL) {
  11955. chain = pem;
  11956. }
  11957. if ((chain != NULL) && (*chain == 0)) {
  11958. chain = NULL;
  11959. }
  11960. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  11961. mg_cry(fc(ctx), "%s", ebuf);
  11962. return 0;
  11963. }
  11964. #if !defined(NO_SSL_DL)
  11965. if (!ssllib_dll_handle) {
  11966. ssllib_dll_handle = load_dll(ebuf, sizeof(ebuf), SSL_LIB, ssl_sw);
  11967. if (!ssllib_dll_handle) {
  11968. mg_cry(fc(ctx), "%s", ebuf);
  11969. return 0;
  11970. }
  11971. }
  11972. #endif /* NO_SSL_DL */
  11973. #ifdef OPENSSL_API_1_1
  11974. /* Initialize SSL library */
  11975. OPENSSL_init_ssl(0, NULL);
  11976. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  11977. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  11978. NULL);
  11979. if ((ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  11980. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  11981. return 0;
  11982. }
  11983. #else
  11984. /* Initialize SSL library */
  11985. SSL_library_init();
  11986. SSL_load_error_strings();
  11987. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  11988. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  11989. return 0;
  11990. }
  11991. #endif /* OPENSSL_API_1_1 */
  11992. SSL_CTX_clear_options(ctx->ssl_ctx,
  11993. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  11994. | SSL_OP_NO_TLSv1_1);
  11995. protocol_ver = atoi(ctx->config[SSL_PROTOCOL_VERSION]);
  11996. SSL_CTX_set_options(ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  11997. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  11998. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  11999. #if !defined(NO_SSL_DL)
  12000. SSL_CTX_set_ecdh_auto(ctx->ssl_ctx, 1);
  12001. #endif /* NO_SSL_DL */
  12002. /* If a callback has been specified, call it. */
  12003. callback_ret =
  12004. (ctx->callbacks.init_ssl == NULL)
  12005. ? 0
  12006. : (ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data));
  12007. /* If callback returns 0, civetweb sets up the SSL certificate.
  12008. * If it returns 1, civetweb assumes the calback already did this.
  12009. * If it returns -1, initializing ssl fails. */
  12010. if (callback_ret < 0) {
  12011. mg_cry(fc(ctx), "SSL callback returned error: %i", callback_ret);
  12012. return 0;
  12013. }
  12014. if (callback_ret > 0) {
  12015. if (pem != NULL) {
  12016. (void)SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
  12017. }
  12018. return 1;
  12019. }
  12020. /* Use some UID as session context ID. */
  12021. md5_init(&md5state);
  12022. md5_append(&md5state, (const md5_byte_t *)&now_rt, sizeof(now_rt));
  12023. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  12024. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  12025. md5_append(&md5state,
  12026. (const md5_byte_t *)ctx->config[LISTENING_PORTS],
  12027. strlen(ctx->config[LISTENING_PORTS]));
  12028. md5_append(&md5state, (const md5_byte_t *)ctx, sizeof(*ctx));
  12029. md5_finish(&md5state, ssl_context_id);
  12030. SSL_CTX_set_session_id_context(ctx->ssl_ctx,
  12031. (const unsigned char *)&ssl_context_id,
  12032. sizeof(ssl_context_id));
  12033. if (pem != NULL) {
  12034. if (!ssl_use_pem_file(ctx, pem, chain)) {
  12035. return 0;
  12036. }
  12037. }
  12038. /* Should we support client certificates? */
  12039. /* Default is "no". */
  12040. should_verify_peer = 0;
  12041. peer_certificate_optional = 0;
  12042. if (ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  12043. if (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  12044. /* Yes, they are mandatory */
  12045. should_verify_peer = 1;
  12046. peer_certificate_optional = 0;
  12047. } else if (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "optional")
  12048. == 0) {
  12049. /* Yes, they are optional */
  12050. should_verify_peer = 1;
  12051. peer_certificate_optional = 1;
  12052. }
  12053. }
  12054. use_default_verify_paths =
  12055. (ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  12056. && (mg_strcasecmp(ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes") == 0);
  12057. if (should_verify_peer) {
  12058. ca_path = ctx->config[SSL_CA_PATH];
  12059. ca_file = ctx->config[SSL_CA_FILE];
  12060. if (SSL_CTX_load_verify_locations(ctx->ssl_ctx, ca_file, ca_path)
  12061. != 1) {
  12062. mg_cry(fc(ctx),
  12063. "SSL_CTX_load_verify_locations error: %s "
  12064. "ssl_verify_peer requires setting "
  12065. "either ssl_ca_path or ssl_ca_file. Is any of them "
  12066. "present in "
  12067. "the .conf file?",
  12068. ssl_error());
  12069. return 0;
  12070. }
  12071. if (peer_certificate_optional) {
  12072. SSL_CTX_set_verify(ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  12073. } else {
  12074. SSL_CTX_set_verify(ctx->ssl_ctx,
  12075. SSL_VERIFY_PEER
  12076. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  12077. NULL);
  12078. }
  12079. if (use_default_verify_paths
  12080. && (SSL_CTX_set_default_verify_paths(ctx->ssl_ctx) != 1)) {
  12081. mg_cry(fc(ctx),
  12082. "SSL_CTX_set_default_verify_paths error: %s",
  12083. ssl_error());
  12084. return 0;
  12085. }
  12086. if (ctx->config[SSL_VERIFY_DEPTH]) {
  12087. verify_depth = atoi(ctx->config[SSL_VERIFY_DEPTH]);
  12088. SSL_CTX_set_verify_depth(ctx->ssl_ctx, verify_depth);
  12089. }
  12090. }
  12091. if (ctx->config[SSL_CIPHER_LIST] != NULL) {
  12092. if (SSL_CTX_set_cipher_list(ctx->ssl_ctx, ctx->config[SSL_CIPHER_LIST])
  12093. != 1) {
  12094. mg_cry(fc(ctx), "SSL_CTX_set_cipher_list error: %s", ssl_error());
  12095. }
  12096. }
  12097. return 1;
  12098. }
  12099. static void
  12100. uninitialize_ssl(void)
  12101. {
  12102. #ifdef OPENSSL_API_1_1
  12103. if (mg_atomic_dec(&cryptolib_users) == 0) {
  12104. /* Shutdown according to
  12105. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  12106. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  12107. */
  12108. CONF_modules_unload(1);
  12109. #else
  12110. int i;
  12111. if (mg_atomic_dec(&cryptolib_users) == 0) {
  12112. /* Shutdown according to
  12113. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  12114. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  12115. */
  12116. CRYPTO_set_locking_callback(NULL);
  12117. CRYPTO_set_id_callback(NULL);
  12118. ENGINE_cleanup();
  12119. CONF_modules_unload(1);
  12120. ERR_free_strings();
  12121. EVP_cleanup();
  12122. CRYPTO_cleanup_all_ex_data();
  12123. ERR_remove_state(0);
  12124. for (i = 0; i < CRYPTO_num_locks(); i++) {
  12125. pthread_mutex_destroy(&ssl_mutexes[i]);
  12126. }
  12127. mg_free(ssl_mutexes);
  12128. ssl_mutexes = NULL;
  12129. #endif /* OPENSSL_API_1_1 */
  12130. }
  12131. }
  12132. #endif /* !NO_SSL */
  12133. static int
  12134. set_gpass_option(struct mg_context *ctx)
  12135. {
  12136. if (ctx) {
  12137. struct mg_file file = STRUCT_FILE_INITIALIZER;
  12138. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  12139. if ((path != NULL) && !mg_stat(fc(ctx), path, &file.stat)) {
  12140. mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  12141. return 0;
  12142. }
  12143. return 1;
  12144. }
  12145. return 0;
  12146. }
  12147. static int
  12148. set_acl_option(struct mg_context *ctx)
  12149. {
  12150. return check_acl(ctx, (uint32_t)0x7f000001UL) != -1;
  12151. }
  12152. static void
  12153. reset_per_request_attributes(struct mg_connection *conn)
  12154. {
  12155. if (!conn) {
  12156. return;
  12157. }
  12158. conn->connection_type = 0; /* Not yet a valid request/response */
  12159. conn->path_info = NULL;
  12160. conn->num_bytes_sent = conn->consumed_content = 0;
  12161. conn->status_code = -1;
  12162. conn->is_chunked = 0;
  12163. conn->must_close = 0;
  12164. conn->request_len = 0;
  12165. conn->throttle = 0;
  12166. conn->data_len = 0;
  12167. conn->chunk_remainder = 0;
  12168. conn->accept_gzip = 0;
  12169. conn->response_info.content_length = conn->request_info.content_length = -1;
  12170. conn->response_info.http_version = conn->request_info.http_version = NULL;
  12171. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  12172. conn->response_info.status_text = NULL;
  12173. conn->response_info.status_code = 0;
  12174. conn->request_info.remote_user = NULL;
  12175. conn->request_info.request_method = NULL;
  12176. conn->request_info.request_uri = NULL;
  12177. conn->request_info.local_uri = NULL;
  12178. #if defined(MG_LEGACY_INTERFACE)
  12179. /* Legacy before split into local_uri and request_uri */
  12180. conn->request_info.uri = NULL;
  12181. #endif
  12182. }
  12183. #if 0
  12184. /* Note: set_sock_timeout is not required for non-blocking sockets.
  12185. * Leave this function here (commented out) for reference until
  12186. * CivetWeb 1.9 is tested, and the tests confirme this function is
  12187. * no longer required.
  12188. */
  12189. static int
  12190. set_sock_timeout(SOCKET sock, int milliseconds)
  12191. {
  12192. int r0 = 0, r1, r2;
  12193. #ifdef _WIN32
  12194. /* Windows specific */
  12195. DWORD tv = (DWORD)milliseconds;
  12196. #else
  12197. /* Linux, ... (not Windows) */
  12198. struct timeval tv;
  12199. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  12200. * max. time waiting for the acknowledged of TCP data before the connection
  12201. * will be forcefully closed and ETIMEDOUT is returned to the application.
  12202. * If this option is not set, the default timeout of 20-30 minutes is used.
  12203. */
  12204. /* #define TCP_USER_TIMEOUT (18) */
  12205. #if defined(TCP_USER_TIMEOUT)
  12206. unsigned int uto = (unsigned int)milliseconds;
  12207. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  12208. #endif
  12209. memset(&tv, 0, sizeof(tv));
  12210. tv.tv_sec = milliseconds / 1000;
  12211. tv.tv_usec = (milliseconds * 1000) % 1000000;
  12212. #endif /* _WIN32 */
  12213. r1 = setsockopt(
  12214. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  12215. r2 = setsockopt(
  12216. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  12217. return r0 || r1 || r2;
  12218. }
  12219. #endif
  12220. static int
  12221. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  12222. {
  12223. if (setsockopt(sock,
  12224. IPPROTO_TCP,
  12225. TCP_NODELAY,
  12226. (SOCK_OPT_TYPE)&nodelay_on,
  12227. sizeof(nodelay_on)) != 0) {
  12228. /* Error */
  12229. return 1;
  12230. }
  12231. /* OK */
  12232. return 0;
  12233. }
  12234. static void
  12235. close_socket_gracefully(struct mg_connection *conn)
  12236. {
  12237. #if defined(_WIN32)
  12238. char buf[MG_BUF_LEN];
  12239. int n;
  12240. #endif
  12241. struct linger linger;
  12242. int error_code = 0;
  12243. int linger_timeout = -2;
  12244. socklen_t opt_len = sizeof(error_code);
  12245. if (!conn) {
  12246. return;
  12247. }
  12248. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  12249. * "Note that enabling a nonzero timeout on a nonblocking socket
  12250. * is not recommended.", so set it to blocking now */
  12251. set_blocking_mode(conn->client.sock, 1);
  12252. /* Send FIN to the client */
  12253. shutdown(conn->client.sock, SHUTDOWN_WR);
  12254. #if defined(_WIN32)
  12255. /* Read and discard pending incoming data. If we do not do that and
  12256. * close
  12257. * the socket, the data in the send buffer may be discarded. This
  12258. * behaviour is seen on Windows, when client keeps sending data
  12259. * when server decides to close the connection; then when client
  12260. * does recv() it gets no data back. */
  12261. do {
  12262. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  12263. } while (n > 0);
  12264. #endif
  12265. if (conn->ctx->config[LINGER_TIMEOUT]) {
  12266. linger_timeout = atoi(conn->ctx->config[LINGER_TIMEOUT]);
  12267. }
  12268. /* Set linger option according to configuration */
  12269. if (linger_timeout >= 0) {
  12270. /* Set linger option to avoid socket hanging out after close. This
  12271. * prevent ephemeral port exhaust problem under high QPS. */
  12272. linger.l_onoff = 1;
  12273. #if defined(_MSC_VER)
  12274. #pragma warning(push)
  12275. #pragma warning(disable : 4244)
  12276. #endif
  12277. linger.l_linger = (linger_timeout + 999) / 1000;
  12278. #if defined(_MSC_VER)
  12279. #pragma warning(pop)
  12280. #endif
  12281. } else {
  12282. linger.l_onoff = 0;
  12283. linger.l_linger = 0;
  12284. }
  12285. if (linger_timeout < -1) {
  12286. /* Default: don't configure any linger */
  12287. } else if (getsockopt(conn->client.sock,
  12288. SOL_SOCKET,
  12289. SO_ERROR,
  12290. (char *)&error_code,
  12291. &opt_len) != 0) {
  12292. /* Cannot determine if socket is already closed. This should
  12293. * not occur and never did in a test. Log an error message
  12294. * and continue. */
  12295. mg_cry(conn,
  12296. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  12297. __func__,
  12298. strerror(ERRNO));
  12299. } else if (error_code == ECONNRESET) {
  12300. /* Socket already closed by client/peer, close socket without linger
  12301. */
  12302. } else {
  12303. /* Set linger timeout */
  12304. if (setsockopt(conn->client.sock,
  12305. SOL_SOCKET,
  12306. SO_LINGER,
  12307. (char *)&linger,
  12308. sizeof(linger)) != 0) {
  12309. mg_cry(conn,
  12310. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  12311. __func__,
  12312. linger.l_onoff,
  12313. linger.l_linger,
  12314. strerror(ERRNO));
  12315. }
  12316. }
  12317. /* Now we know that our FIN is ACK-ed, safe to close */
  12318. closesocket(conn->client.sock);
  12319. conn->client.sock = INVALID_SOCKET;
  12320. }
  12321. static void
  12322. close_connection(struct mg_connection *conn)
  12323. {
  12324. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  12325. if (conn->lua_websocket_state) {
  12326. lua_websocket_close(conn, conn->lua_websocket_state);
  12327. conn->lua_websocket_state = NULL;
  12328. }
  12329. #endif
  12330. mg_lock_connection(conn);
  12331. conn->must_close = 1;
  12332. /* call the connection_close callback if assigned */
  12333. if ((conn->ctx->callbacks.connection_close != NULL)
  12334. && (conn->ctx->context_type == 1)) {
  12335. conn->ctx->callbacks.connection_close(conn);
  12336. }
  12337. /* Reset user data, after close callback is called.
  12338. * Do not reuse it. If the user needs a destructor,
  12339. * it must be done in the connection_close callback. */
  12340. mg_set_user_connection_data(conn, NULL);
  12341. #ifndef NO_SSL
  12342. if (conn->ssl != NULL) {
  12343. /* Run SSL_shutdown twice to ensure completly close SSL connection
  12344. */
  12345. SSL_shutdown(conn->ssl);
  12346. SSL_free(conn->ssl);
  12347. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  12348. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  12349. #ifndef OPENSSL_API_1_1
  12350. ERR_remove_state(0);
  12351. #endif
  12352. conn->ssl = NULL;
  12353. }
  12354. #endif
  12355. if (conn->client.sock != INVALID_SOCKET) {
  12356. close_socket_gracefully(conn);
  12357. conn->client.sock = INVALID_SOCKET;
  12358. }
  12359. mg_unlock_connection(conn);
  12360. }
  12361. void
  12362. mg_close_connection(struct mg_connection *conn)
  12363. {
  12364. #if defined(USE_WEBSOCKET)
  12365. struct mg_context *client_ctx = NULL;
  12366. #endif /* defined(USE_WEBSOCKET) */
  12367. if ((conn == NULL) || (conn->ctx == NULL)) {
  12368. return;
  12369. }
  12370. #if defined(USE_WEBSOCKET)
  12371. if (conn->ctx->context_type == 2) {
  12372. unsigned int i;
  12373. /* ws/wss client */
  12374. client_ctx = conn->ctx;
  12375. /* client context: loops must end */
  12376. conn->ctx->stop_flag = 1;
  12377. /* We need to get the client thread out of the select/recv call
  12378. * here. */
  12379. /* Since we use a sleep quantum of some seconds to check for recv
  12380. * timeouts, we will just wait a few seconds in mg_join_thread. */
  12381. /* join worker thread */
  12382. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  12383. if (client_ctx->worker_threadids[i] != 0) {
  12384. mg_join_thread(client_ctx->worker_threadids[i]);
  12385. }
  12386. }
  12387. }
  12388. #endif /* defined(USE_WEBSOCKET) */
  12389. close_connection(conn);
  12390. #ifndef NO_SSL
  12391. if (conn->client_ssl_ctx != NULL) {
  12392. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  12393. }
  12394. #endif
  12395. #if defined(USE_WEBSOCKET)
  12396. if (client_ctx != NULL) {
  12397. /* free context */
  12398. mg_free(client_ctx->worker_threadids);
  12399. mg_free(client_ctx);
  12400. (void)pthread_mutex_destroy(&conn->mutex);
  12401. mg_free(conn);
  12402. } else if (conn->ctx->context_type == 0) { /* Client */
  12403. mg_free(conn);
  12404. }
  12405. #else
  12406. if (conn->ctx->context_type == 0) { /* Client */
  12407. mg_free(conn);
  12408. }
  12409. #endif /* defined(USE_WEBSOCKET) */
  12410. }
  12411. static struct mg_context common_client_context;
  12412. static struct mg_connection *
  12413. mg_connect_client_impl(const struct mg_client_options *client_options,
  12414. int use_ssl,
  12415. char *ebuf,
  12416. size_t ebuf_len)
  12417. {
  12418. struct mg_connection *conn = NULL;
  12419. SOCKET sock;
  12420. union usa sa;
  12421. unsigned max_req_size =
  12422. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  12423. if (!connect_socket(&common_client_context,
  12424. client_options->host,
  12425. client_options->port,
  12426. use_ssl,
  12427. ebuf,
  12428. ebuf_len,
  12429. &sock,
  12430. &sa)) {
  12431. return NULL;
  12432. }
  12433. if ((conn = (struct mg_connection *)mg_calloc_ctx(
  12434. 1, sizeof(*conn) + max_req_size, &common_client_context))
  12435. == NULL) {
  12436. mg_snprintf(NULL,
  12437. NULL, /* No truncation check for ebuf */
  12438. ebuf,
  12439. ebuf_len,
  12440. "calloc(): %s",
  12441. strerror(ERRNO));
  12442. closesocket(sock);
  12443. return NULL;
  12444. }
  12445. #ifndef NO_SSL
  12446. #ifdef OPENSSL_API_1_1
  12447. if (use_ssl
  12448. && (conn->client_ssl_ctx = SSL_CTX_new(TLS_client_method())) == NULL) {
  12449. mg_snprintf(NULL,
  12450. NULL, /* No truncation check for ebuf */
  12451. ebuf,
  12452. ebuf_len,
  12453. "SSL_CTX_new error");
  12454. closesocket(sock);
  12455. mg_free(conn);
  12456. return NULL;
  12457. }
  12458. #else
  12459. if (use_ssl
  12460. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  12461. == NULL) {
  12462. mg_snprintf(NULL,
  12463. NULL, /* No truncation check for ebuf */
  12464. ebuf,
  12465. ebuf_len,
  12466. "SSL_CTX_new error");
  12467. closesocket(sock);
  12468. mg_free(conn);
  12469. return NULL;
  12470. }
  12471. #endif /* OPENSSL_API_1_1 */
  12472. #endif /* NO_SSL */
  12473. #ifdef USE_IPV6
  12474. socklen_t len = (sa.sa.sa_family == AF_INET)
  12475. ? sizeof(conn->client.rsa.sin)
  12476. : sizeof(conn->client.rsa.sin6);
  12477. struct sockaddr *psa = (sa.sa.sa_family == AF_INET)
  12478. ? (struct sockaddr *)&(conn->client.rsa.sin)
  12479. : (struct sockaddr *)&(conn->client.rsa.sin6);
  12480. #else
  12481. socklen_t len = sizeof(conn->client.rsa.sin);
  12482. struct sockaddr *psa = (struct sockaddr *)&(conn->client.rsa.sin);
  12483. #endif
  12484. conn->buf_size = (int)max_req_size;
  12485. conn->buf = (char *)(conn + 1);
  12486. conn->ctx = &common_client_context;
  12487. conn->client.sock = sock;
  12488. conn->client.lsa = sa;
  12489. if (getsockname(sock, psa, &len) != 0) {
  12490. mg_cry(conn, "%s: getsockname() failed: %s", __func__, strerror(ERRNO));
  12491. }
  12492. conn->client.is_ssl = use_ssl ? 1 : 0;
  12493. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  12494. #ifndef NO_SSL
  12495. if (use_ssl) {
  12496. common_client_context.ssl_ctx = conn->client_ssl_ctx;
  12497. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  12498. * SSL_CTX_set_verify call is needed to switch off server
  12499. * certificate checking, which is off by default in OpenSSL and
  12500. * on in yaSSL. */
  12501. /* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  12502. * SSL_VERIFY_PEER, verify_ssl_server); */
  12503. if (client_options->client_cert) {
  12504. if (!ssl_use_pem_file(&common_client_context,
  12505. client_options->client_cert,
  12506. NULL)) {
  12507. mg_snprintf(NULL,
  12508. NULL, /* No truncation check for ebuf */
  12509. ebuf,
  12510. ebuf_len,
  12511. "Can not use SSL client certificate");
  12512. SSL_CTX_free(conn->client_ssl_ctx);
  12513. closesocket(sock);
  12514. mg_free(conn);
  12515. return NULL;
  12516. }
  12517. }
  12518. if (client_options->server_cert) {
  12519. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  12520. client_options->server_cert,
  12521. NULL);
  12522. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  12523. } else {
  12524. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  12525. }
  12526. if (!sslize(conn,
  12527. conn->client_ssl_ctx,
  12528. SSL_connect,
  12529. &(conn->ctx->stop_flag))) {
  12530. mg_snprintf(NULL,
  12531. NULL, /* No truncation check for ebuf */
  12532. ebuf,
  12533. ebuf_len,
  12534. "SSL connection error");
  12535. SSL_CTX_free(conn->client_ssl_ctx);
  12536. closesocket(sock);
  12537. mg_free(conn);
  12538. return NULL;
  12539. }
  12540. }
  12541. #endif
  12542. set_blocking_mode(sock, 0);
  12543. return conn;
  12544. }
  12545. CIVETWEB_API struct mg_connection *
  12546. mg_connect_client_secure(const struct mg_client_options *client_options,
  12547. char *error_buffer,
  12548. size_t error_buffer_size)
  12549. {
  12550. return mg_connect_client_impl(client_options,
  12551. 1,
  12552. error_buffer,
  12553. error_buffer_size);
  12554. }
  12555. struct mg_connection *
  12556. mg_connect_client(const char *host,
  12557. int port,
  12558. int use_ssl,
  12559. char *error_buffer,
  12560. size_t error_buffer_size)
  12561. {
  12562. struct mg_client_options opts;
  12563. memset(&opts, 0, sizeof(opts));
  12564. opts.host = host;
  12565. opts.port = port;
  12566. return mg_connect_client_impl(&opts,
  12567. use_ssl,
  12568. error_buffer,
  12569. error_buffer_size);
  12570. }
  12571. static const struct {
  12572. const char *proto;
  12573. size_t proto_len;
  12574. unsigned default_port;
  12575. } abs_uri_protocols[] = {{"http://", 7, 80},
  12576. {"https://", 8, 443},
  12577. {"ws://", 5, 80},
  12578. {"wss://", 6, 443},
  12579. {NULL, 0, 0}};
  12580. /* Check if the uri is valid.
  12581. * return 0 for invalid uri,
  12582. * return 1 for *,
  12583. * return 2 for relative uri,
  12584. * return 3 for absolute uri without port,
  12585. * return 4 for absolute uri with port */
  12586. static int
  12587. get_uri_type(const char *uri)
  12588. {
  12589. int i;
  12590. const char *hostend, *portbegin;
  12591. char *portend;
  12592. unsigned long port;
  12593. /* According to the HTTP standard
  12594. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  12595. * URI can be an asterisk (*) or should start with slash (relative uri),
  12596. * or it should start with the protocol (absolute uri). */
  12597. if ((uri[0] == '*') && (uri[1] == '\0')) {
  12598. /* asterisk */
  12599. return 1;
  12600. }
  12601. /* Valid URIs according to RFC 3986
  12602. * (https://www.ietf.org/rfc/rfc3986.txt)
  12603. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  12604. * and unreserved characters A-Z a-z 0-9 and -._~
  12605. * and % encoded symbols.
  12606. */
  12607. for (i = 0; uri[i] != 0; i++) {
  12608. if (uri[i] < 33) {
  12609. /* control characters and spaces are invalid */
  12610. return 0;
  12611. }
  12612. if (uri[i] > 126) {
  12613. /* non-ascii characters must be % encoded */
  12614. return 0;
  12615. } else {
  12616. switch (uri[i]) {
  12617. case '"': /* 34 */
  12618. case '<': /* 60 */
  12619. case '>': /* 62 */
  12620. case '\\': /* 92 */
  12621. case '^': /* 94 */
  12622. case '`': /* 96 */
  12623. case '{': /* 123 */
  12624. case '|': /* 124 */
  12625. case '}': /* 125 */
  12626. return 0;
  12627. default:
  12628. /* character is ok */
  12629. break;
  12630. }
  12631. }
  12632. }
  12633. /* A relative uri starts with a / character */
  12634. if (uri[0] == '/') {
  12635. /* relative uri */
  12636. return 2;
  12637. }
  12638. /* It could be an absolute uri: */
  12639. /* This function only checks if the uri is valid, not if it is
  12640. * addressing the current server. So civetweb can also be used
  12641. * as a proxy server. */
  12642. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  12643. if (mg_strncasecmp(uri,
  12644. abs_uri_protocols[i].proto,
  12645. abs_uri_protocols[i].proto_len) == 0) {
  12646. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  12647. if (!hostend) {
  12648. return 0;
  12649. }
  12650. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  12651. if (!portbegin) {
  12652. return 3;
  12653. }
  12654. port = strtoul(portbegin + 1, &portend, 10);
  12655. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  12656. return 0;
  12657. }
  12658. return 4;
  12659. }
  12660. }
  12661. return 0;
  12662. }
  12663. /* Return NULL or the relative uri at the current server */
  12664. static const char *
  12665. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  12666. {
  12667. const char *server_domain;
  12668. size_t server_domain_len;
  12669. size_t request_domain_len = 0;
  12670. unsigned long port = 0;
  12671. int i, auth_domain_check_enabled;
  12672. const char *hostbegin = NULL;
  12673. const char *hostend = NULL;
  12674. const char *portbegin;
  12675. char *portend;
  12676. auth_domain_check_enabled =
  12677. !strcmp(conn->ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  12678. if (!auth_domain_check_enabled) {
  12679. return 0;
  12680. }
  12681. server_domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  12682. if (!server_domain) {
  12683. return 0;
  12684. }
  12685. server_domain_len = strlen(server_domain);
  12686. if (!server_domain_len) {
  12687. return 0;
  12688. }
  12689. /* DNS is case insensitive, so use case insensitive string compare here
  12690. */
  12691. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  12692. if (mg_strncasecmp(uri,
  12693. abs_uri_protocols[i].proto,
  12694. abs_uri_protocols[i].proto_len) == 0) {
  12695. hostbegin = uri + abs_uri_protocols[i].proto_len;
  12696. hostend = strchr(hostbegin, '/');
  12697. if (!hostend) {
  12698. return 0;
  12699. }
  12700. portbegin = strchr(hostbegin, ':');
  12701. if ((!portbegin) || (portbegin > hostend)) {
  12702. port = abs_uri_protocols[i].default_port;
  12703. request_domain_len = (size_t)(hostend - hostbegin);
  12704. } else {
  12705. port = strtoul(portbegin + 1, &portend, 10);
  12706. if ((portend != hostend) || (port <= 0)
  12707. || !is_valid_port(port)) {
  12708. return 0;
  12709. }
  12710. request_domain_len = (size_t)(portbegin - hostbegin);
  12711. }
  12712. /* protocol found, port set */
  12713. break;
  12714. }
  12715. }
  12716. if (!port) {
  12717. /* port remains 0 if the protocol is not found */
  12718. return 0;
  12719. }
  12720. /* Check if the request is directed to a different server. */
  12721. /* First check if the port is the same (IPv4 and IPv6). */
  12722. #if defined(USE_IPV6)
  12723. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  12724. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  12725. /* Request is directed to a different port */
  12726. return 0;
  12727. }
  12728. } else
  12729. #endif
  12730. {
  12731. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  12732. /* Request is directed to a different port */
  12733. return 0;
  12734. }
  12735. }
  12736. /* Finally check if the server corresponds to the authentication
  12737. * domain of the server (the server domain).
  12738. * Allow full matches (like http://mydomain.com/path/file.ext), and
  12739. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  12740. * but do not allow substrings (like
  12741. * http://notmydomain.com/path/file.ext
  12742. * or http://mydomain.com.fake/path/file.ext).
  12743. */
  12744. if (auth_domain_check_enabled) {
  12745. if ((request_domain_len == server_domain_len)
  12746. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  12747. /* Request is directed to this server - full name match. */
  12748. } else {
  12749. if (request_domain_len < (server_domain_len + 2)) {
  12750. /* Request is directed to another server: The server name is
  12751. * longer
  12752. * than
  12753. * the request name. Drop this case here to avoid overflows
  12754. * in
  12755. * the
  12756. * following checks. */
  12757. return 0;
  12758. }
  12759. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  12760. /* Request is directed to another server: It could be a
  12761. * substring
  12762. * like notmyserver.com */
  12763. return 0;
  12764. }
  12765. if (0 != memcmp(server_domain,
  12766. hostbegin + request_domain_len - server_domain_len,
  12767. server_domain_len)) {
  12768. /* Request is directed to another server:
  12769. * The server name is different. */
  12770. return 0;
  12771. }
  12772. }
  12773. }
  12774. return hostend;
  12775. }
  12776. static int
  12777. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  12778. {
  12779. if (ebuf_len > 0) {
  12780. ebuf[0] = '\0';
  12781. }
  12782. *err = 0;
  12783. reset_per_request_attributes(conn);
  12784. if (!conn) {
  12785. mg_snprintf(conn,
  12786. NULL, /* No truncation check for ebuf */
  12787. ebuf,
  12788. ebuf_len,
  12789. "%s",
  12790. "Internal error");
  12791. *err = 500;
  12792. return 0;
  12793. }
  12794. /* Set the time the request was received. This value should be used for
  12795. * timeouts. */
  12796. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  12797. conn->request_len =
  12798. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  12799. /* assert(conn->request_len < 0 || conn->data_len >= conn->request_len);
  12800. */
  12801. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  12802. mg_snprintf(conn,
  12803. NULL, /* No truncation check for ebuf */
  12804. ebuf,
  12805. ebuf_len,
  12806. "%s",
  12807. "Invalid message size");
  12808. *err = 500;
  12809. return 0;
  12810. }
  12811. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  12812. mg_snprintf(conn,
  12813. NULL, /* No truncation check for ebuf */
  12814. ebuf,
  12815. ebuf_len,
  12816. "%s",
  12817. "Message too large");
  12818. *err = 413;
  12819. return 0;
  12820. }
  12821. if (conn->request_len <= 0) {
  12822. if (conn->data_len > 0) {
  12823. mg_snprintf(conn,
  12824. NULL, /* No truncation check for ebuf */
  12825. ebuf,
  12826. ebuf_len,
  12827. "%s",
  12828. "Malformed message");
  12829. *err = 400;
  12830. } else {
  12831. /* Server did not recv anything -> just close the connection */
  12832. conn->must_close = 1;
  12833. mg_snprintf(conn,
  12834. NULL, /* No truncation check for ebuf */
  12835. ebuf,
  12836. ebuf_len,
  12837. "%s",
  12838. "No data received");
  12839. *err = 0;
  12840. }
  12841. return 0;
  12842. }
  12843. return 1;
  12844. }
  12845. static int
  12846. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  12847. {
  12848. const char *cl;
  12849. if (!get_message(conn, ebuf, ebuf_len, err)) {
  12850. return 0;
  12851. }
  12852. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  12853. <= 0) {
  12854. mg_snprintf(conn,
  12855. NULL, /* No truncation check for ebuf */
  12856. ebuf,
  12857. ebuf_len,
  12858. "%s",
  12859. "Bad request");
  12860. *err = 400;
  12861. return 0;
  12862. }
  12863. /* Message is a valid request */
  12864. if ((cl = get_header(conn->request_info.http_headers,
  12865. conn->request_info.num_headers,
  12866. "Content-Length")) != NULL) {
  12867. /* Request/response has content length set */
  12868. char *endptr = NULL;
  12869. conn->content_len = strtoll(cl, &endptr, 10);
  12870. if (endptr == cl) {
  12871. mg_snprintf(conn,
  12872. NULL, /* No truncation check for ebuf */
  12873. ebuf,
  12874. ebuf_len,
  12875. "%s",
  12876. "Bad request");
  12877. *err = 411;
  12878. return 0;
  12879. }
  12880. /* Publish the content length back to the request info. */
  12881. conn->request_info.content_length = conn->content_len;
  12882. } else if ((cl = get_header(conn->request_info.http_headers,
  12883. conn->request_info.num_headers,
  12884. "Transfer-Encoding")) != NULL
  12885. && !mg_strcasecmp(cl, "chunked")) {
  12886. conn->is_chunked = 1;
  12887. } else if (!mg_strcasecmp(conn->request_info.request_method, "POST")
  12888. || !mg_strcasecmp(conn->request_info.request_method, "PUT")) {
  12889. /* POST or PUT request without content length set */
  12890. conn->content_len = -1;
  12891. } else if (!mg_strncasecmp(conn->request_info.request_method, "HTTP/", 5)) {
  12892. /* Response without content length set */
  12893. conn->content_len = -1;
  12894. } else {
  12895. /* Other request */
  12896. conn->content_len = 0;
  12897. }
  12898. conn->connection_type = 1; /* Valid request */
  12899. return 1;
  12900. }
  12901. /* conn is assumed to be valid in this internal function */
  12902. static int
  12903. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  12904. {
  12905. const char *cl;
  12906. if (!get_message(conn, ebuf, ebuf_len, err)) {
  12907. return 0;
  12908. }
  12909. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  12910. <= 0) {
  12911. mg_snprintf(conn,
  12912. NULL, /* No truncation check for ebuf */
  12913. ebuf,
  12914. ebuf_len,
  12915. "%s",
  12916. "Bad response");
  12917. *err = 400;
  12918. return 0;
  12919. }
  12920. /* Message is a valid response */
  12921. if ((cl = get_header(conn->response_info.http_headers,
  12922. conn->response_info.num_headers,
  12923. "Content-Length")) != NULL) {
  12924. /* Request/response has content length set */
  12925. char *endptr = NULL;
  12926. conn->content_len = strtoll(cl, &endptr, 10);
  12927. if (endptr == cl) {
  12928. mg_snprintf(conn,
  12929. NULL, /* No truncation check for ebuf */
  12930. ebuf,
  12931. ebuf_len,
  12932. "%s",
  12933. "Bad request");
  12934. *err = 411;
  12935. return 0;
  12936. }
  12937. /* Publish the content length back to the response info. */
  12938. conn->response_info.content_length = conn->content_len;
  12939. /* TODO: check if it is still used in response_info */
  12940. conn->request_info.content_length = conn->content_len;
  12941. } else if ((cl = get_header(conn->response_info.http_headers,
  12942. conn->response_info.num_headers,
  12943. "Transfer-Encoding")) != NULL
  12944. && !mg_strcasecmp(cl, "chunked")) {
  12945. conn->is_chunked = 1;
  12946. } else {
  12947. conn->content_len = -1;
  12948. }
  12949. conn->connection_type = 2; /* Valid response */
  12950. return 1;
  12951. }
  12952. int
  12953. mg_get_response(struct mg_connection *conn,
  12954. char *ebuf,
  12955. size_t ebuf_len,
  12956. int timeout)
  12957. {
  12958. if (ebuf_len > 0) {
  12959. ebuf[0] = '\0';
  12960. }
  12961. if (!conn) {
  12962. mg_snprintf(conn,
  12963. NULL, /* No truncation check for ebuf */
  12964. ebuf,
  12965. ebuf_len,
  12966. "%s",
  12967. "Parameter error");
  12968. return -1;
  12969. }
  12970. /* Implementation of API function for HTTP clients */
  12971. int err, ret;
  12972. struct mg_context *octx = conn->ctx;
  12973. struct mg_context rctx = *(conn->ctx);
  12974. char txt[32]; /* will not overflow */
  12975. if (timeout >= 0) {
  12976. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  12977. rctx.config[REQUEST_TIMEOUT] = txt;
  12978. /* Not required for non-blocking sockets.
  12979. set_sock_timeout(conn->client.sock, timeout);
  12980. */
  12981. } else {
  12982. rctx.config[REQUEST_TIMEOUT] = NULL;
  12983. }
  12984. conn->ctx = &rctx;
  12985. ret = get_response(conn, ebuf, ebuf_len, &err);
  12986. conn->ctx = octx;
  12987. #if defined(MG_LEGACY_INTERFACE)
  12988. /* TODO: 1) uri is deprecated;
  12989. * 2) here, ri.uri is the http response code */
  12990. conn->request_info.uri = conn->request_info.request_uri;
  12991. #endif
  12992. conn->request_info.local_uri = conn->request_info.request_uri;
  12993. /* TODO (mid): Define proper return values - maybe return length?
  12994. * For the first test use <0 for error and >0 for OK */
  12995. return (ret == 0) ? -1 : +1;
  12996. }
  12997. struct mg_connection *
  12998. mg_download(const char *host,
  12999. int port,
  13000. int use_ssl,
  13001. char *ebuf,
  13002. size_t ebuf_len,
  13003. const char *fmt,
  13004. ...)
  13005. {
  13006. struct mg_connection *conn;
  13007. va_list ap;
  13008. int i;
  13009. int reqerr;
  13010. if (ebuf_len > 0) {
  13011. ebuf[0] = '\0';
  13012. }
  13013. va_start(ap, fmt);
  13014. /* open a connection */
  13015. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  13016. if (conn != NULL) {
  13017. i = mg_vprintf(conn, fmt, ap);
  13018. if (i <= 0) {
  13019. mg_snprintf(conn,
  13020. NULL, /* No truncation check for ebuf */
  13021. ebuf,
  13022. ebuf_len,
  13023. "%s",
  13024. "Error sending request");
  13025. } else {
  13026. get_response(conn, ebuf, ebuf_len, &reqerr);
  13027. #if defined(MG_LEGACY_INTERFACE)
  13028. /* TODO: 1) uri is deprecated;
  13029. * 2) here, ri.uri is the http response code */
  13030. conn->request_info.uri = conn->request_info.request_uri;
  13031. #endif
  13032. conn->request_info.local_uri = conn->request_info.request_uri;
  13033. }
  13034. }
  13035. /* if an error occured, close the connection */
  13036. if ((ebuf[0] != '\0') && (conn != NULL)) {
  13037. mg_close_connection(conn);
  13038. conn = NULL;
  13039. }
  13040. va_end(ap);
  13041. return conn;
  13042. }
  13043. struct websocket_client_thread_data {
  13044. struct mg_connection *conn;
  13045. mg_websocket_data_handler data_handler;
  13046. mg_websocket_close_handler close_handler;
  13047. void *callback_data;
  13048. };
  13049. #if defined(USE_WEBSOCKET)
  13050. #ifdef _WIN32
  13051. static unsigned __stdcall websocket_client_thread(void *data)
  13052. #else
  13053. static void *
  13054. websocket_client_thread(void *data)
  13055. #endif
  13056. {
  13057. struct websocket_client_thread_data *cdata =
  13058. (struct websocket_client_thread_data *)data;
  13059. mg_set_thread_name("ws-clnt");
  13060. if (cdata->conn->ctx) {
  13061. if (cdata->conn->ctx->callbacks.init_thread) {
  13062. /* 3 indicates a websocket client thread */
  13063. /* TODO: check if conn->ctx can be set */
  13064. cdata->conn->ctx->callbacks.init_thread(cdata->conn->ctx, 3);
  13065. }
  13066. }
  13067. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  13068. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  13069. if (cdata->close_handler != NULL) {
  13070. cdata->close_handler(cdata->conn, cdata->callback_data);
  13071. }
  13072. /* The websocket_client context has only this thread. If it runs out,
  13073. set the stop_flag to 2 (= "stopped"). */
  13074. cdata->conn->ctx->stop_flag = 2;
  13075. mg_free((void *)cdata);
  13076. #ifdef _WIN32
  13077. return 0;
  13078. #else
  13079. return NULL;
  13080. #endif
  13081. }
  13082. #endif
  13083. struct mg_connection *
  13084. mg_connect_websocket_client(const char *host,
  13085. int port,
  13086. int use_ssl,
  13087. char *error_buffer,
  13088. size_t error_buffer_size,
  13089. const char *path,
  13090. const char *origin,
  13091. mg_websocket_data_handler data_func,
  13092. mg_websocket_close_handler close_func,
  13093. void *user_data)
  13094. {
  13095. struct mg_connection *conn = NULL;
  13096. #if defined(USE_WEBSOCKET)
  13097. struct mg_context *newctx = NULL;
  13098. struct websocket_client_thread_data *thread_data;
  13099. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  13100. static const char *handshake_req;
  13101. if (origin != NULL) {
  13102. handshake_req = "GET %s HTTP/1.1\r\n"
  13103. "Host: %s\r\n"
  13104. "Upgrade: websocket\r\n"
  13105. "Connection: Upgrade\r\n"
  13106. "Sec-WebSocket-Key: %s\r\n"
  13107. "Sec-WebSocket-Version: 13\r\n"
  13108. "Origin: %s\r\n"
  13109. "\r\n";
  13110. } else {
  13111. handshake_req = "GET %s HTTP/1.1\r\n"
  13112. "Host: %s\r\n"
  13113. "Upgrade: websocket\r\n"
  13114. "Connection: Upgrade\r\n"
  13115. "Sec-WebSocket-Key: %s\r\n"
  13116. "Sec-WebSocket-Version: 13\r\n"
  13117. "\r\n";
  13118. }
  13119. /* Establish the client connection and request upgrade */
  13120. conn = mg_download(host,
  13121. port,
  13122. use_ssl,
  13123. error_buffer,
  13124. error_buffer_size,
  13125. handshake_req,
  13126. path,
  13127. host,
  13128. magic,
  13129. origin);
  13130. /* Connection object will be null if something goes wrong */
  13131. if (conn == NULL) {
  13132. if (!*error_buffer) {
  13133. /* There should be already an error message */
  13134. mg_snprintf(conn,
  13135. NULL, /* No truncation check for ebuf */
  13136. error_buffer,
  13137. error_buffer_size,
  13138. "Unexpected error");
  13139. }
  13140. return NULL;
  13141. }
  13142. if (conn->response_info.status_code != 101) {
  13143. /* We sent an "upgrade" request. For a correct websocket
  13144. * protocol handshake, we expect a "101 Continue" response.
  13145. * Otherwise it is a protocol violation. Maybe the HTTP
  13146. * Server does not know websockets. */
  13147. if (!*error_buffer) {
  13148. /* set an error, if not yet set */
  13149. mg_snprintf(conn,
  13150. NULL, /* No truncation check for ebuf */
  13151. error_buffer,
  13152. error_buffer_size,
  13153. "Unexpected server reply");
  13154. }
  13155. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  13156. mg_free(conn);
  13157. return conn;
  13158. }
  13159. /* For client connections, mg_context is fake. Since we need to set a
  13160. * callback function, we need to create a copy and modify it. */
  13161. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  13162. memcpy(newctx, conn->ctx, sizeof(struct mg_context));
  13163. newctx->user_data = user_data;
  13164. newctx->context_type = 2; /* ws/wss client context type */
  13165. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  13166. newctx->worker_threadids =
  13167. (pthread_t *)mg_calloc_ctx(newctx->cfg_worker_threads,
  13168. sizeof(pthread_t),
  13169. newctx);
  13170. conn->ctx = newctx;
  13171. thread_data = (struct websocket_client_thread_data *)
  13172. mg_calloc_ctx(sizeof(struct websocket_client_thread_data), 1, newctx);
  13173. thread_data->conn = conn;
  13174. thread_data->data_handler = data_func;
  13175. thread_data->close_handler = close_func;
  13176. thread_data->callback_data = user_data;
  13177. /* Start a thread to read the websocket client connection
  13178. * This thread will automatically stop when mg_disconnect is
  13179. * called on the client connection */
  13180. if (mg_start_thread_with_id(websocket_client_thread,
  13181. (void *)thread_data,
  13182. newctx->worker_threadids) != 0) {
  13183. mg_free((void *)thread_data);
  13184. mg_free((void *)newctx->worker_threadids);
  13185. mg_free((void *)newctx);
  13186. mg_free((void *)conn);
  13187. conn = NULL;
  13188. DEBUG_TRACE("%s",
  13189. "Websocket client connect thread could not be started\r\n");
  13190. }
  13191. #else
  13192. /* Appease "unused parameter" warnings */
  13193. (void)host;
  13194. (void)port;
  13195. (void)use_ssl;
  13196. (void)error_buffer;
  13197. (void)error_buffer_size;
  13198. (void)path;
  13199. (void)origin;
  13200. (void)user_data;
  13201. (void)data_func;
  13202. (void)close_func;
  13203. #endif
  13204. return conn;
  13205. }
  13206. /* Prepare connection data structure */
  13207. static void
  13208. init_connection(struct mg_connection *conn)
  13209. {
  13210. /* Is keep alive allowed by the server */
  13211. int keep_alive_enabled =
  13212. !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  13213. if (!keep_alive_enabled) {
  13214. conn->must_close = 1;
  13215. }
  13216. /* Important: on new connection, reset the receiving buffer. Credit
  13217. * goes to crule42. */
  13218. conn->data_len = 0;
  13219. conn->handled_requests = 0;
  13220. mg_set_user_connection_data(conn, NULL);
  13221. /* call the connection_close callback if assigned */
  13222. if ((conn->ctx->callbacks.init_connection != NULL)
  13223. && (conn->ctx->context_type == 1)) {
  13224. void *conn_data = NULL;
  13225. conn->ctx->callbacks.init_connection(conn, &conn_data);
  13226. mg_set_user_connection_data(conn, conn_data);
  13227. }
  13228. }
  13229. /* Process a connection - may handle multiple requests
  13230. * using the same connection.
  13231. * Must be called with a valid connection (conn and
  13232. * conn->ctx must be valid).
  13233. */
  13234. static void
  13235. process_new_connection(struct mg_connection *conn)
  13236. {
  13237. struct mg_request_info *ri = &conn->request_info;
  13238. int keep_alive, discard_len;
  13239. char ebuf[100];
  13240. const char *hostend;
  13241. int reqerr, uri_type;
  13242. #if defined(USE_SERVER_STATS)
  13243. int mcon = mg_atomic_inc(&(conn->ctx->active_connections));
  13244. mg_atomic_add(&(conn->ctx->total_connections), 1);
  13245. if (mcon > (conn->ctx->max_connections)) {
  13246. /* could use atomic compare exchange, but this
  13247. * seems overkill for statistics data */
  13248. conn->ctx->max_connections = mcon;
  13249. }
  13250. #endif
  13251. init_connection(conn);
  13252. DEBUG_TRACE("Start processing connection from %s",
  13253. conn->request_info.remote_addr);
  13254. /* Loop over multiple requests sent using the same connection
  13255. * (while "keep alive"). */
  13256. do {
  13257. DEBUG_TRACE("calling get_request (%i times for this connection)",
  13258. conn->handled_requests + 1);
  13259. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  13260. /* The request sent by the client could not be understood by
  13261. * the server, or it was incomplete or a timeout. Send an
  13262. * error message and close the connection. */
  13263. if (reqerr > 0) {
  13264. /*assert(ebuf[0] != '\0');*/
  13265. mg_send_http_error(conn, reqerr, "%s", ebuf);
  13266. }
  13267. } else if (strcmp(ri->http_version, "1.0")
  13268. && strcmp(ri->http_version, "1.1")) {
  13269. mg_snprintf(conn,
  13270. NULL, /* No truncation check for ebuf */
  13271. ebuf,
  13272. sizeof(ebuf),
  13273. "Bad HTTP version: [%s]",
  13274. ri->http_version);
  13275. mg_send_http_error(conn, 505, "%s", ebuf);
  13276. }
  13277. if (ebuf[0] == '\0') {
  13278. uri_type = get_uri_type(conn->request_info.request_uri);
  13279. switch (uri_type) {
  13280. case 1:
  13281. /* Asterisk */
  13282. conn->request_info.local_uri = NULL;
  13283. break;
  13284. case 2:
  13285. /* relative uri */
  13286. conn->request_info.local_uri = conn->request_info.request_uri;
  13287. break;
  13288. case 3:
  13289. case 4:
  13290. /* absolute uri (with/without port) */
  13291. hostend = get_rel_url_at_current_server(
  13292. conn->request_info.request_uri, conn);
  13293. if (hostend) {
  13294. conn->request_info.local_uri = hostend;
  13295. } else {
  13296. conn->request_info.local_uri = NULL;
  13297. }
  13298. break;
  13299. default:
  13300. mg_snprintf(conn,
  13301. NULL, /* No truncation check for ebuf */
  13302. ebuf,
  13303. sizeof(ebuf),
  13304. "Invalid URI");
  13305. mg_send_http_error(conn, 400, "%s", ebuf);
  13306. conn->request_info.local_uri = NULL;
  13307. break;
  13308. }
  13309. #if defined(MG_LEGACY_INTERFACE)
  13310. /* Legacy before split into local_uri and request_uri */
  13311. conn->request_info.uri = conn->request_info.local_uri;
  13312. #endif
  13313. }
  13314. DEBUG_TRACE("http: %s, error: %s",
  13315. (ri->http_version ? ri->http_version : "none"),
  13316. (ebuf[0] ? ebuf : "none"));
  13317. if (ebuf[0] == '\0') {
  13318. if (conn->request_info.local_uri) {
  13319. /* handle request to local server */
  13320. handle_request(conn);
  13321. DEBUG_TRACE("%s", "handle_request done");
  13322. if (conn->ctx->callbacks.end_request != NULL) {
  13323. conn->ctx->callbacks.end_request(conn, conn->status_code);
  13324. DEBUG_TRACE("%s", "end_request callback done");
  13325. }
  13326. log_access(conn);
  13327. } else {
  13328. /* TODO: handle non-local request (PROXY) */
  13329. conn->must_close = 1;
  13330. }
  13331. } else {
  13332. conn->must_close = 1;
  13333. }
  13334. if (ri->remote_user != NULL) {
  13335. mg_free((void *)ri->remote_user);
  13336. /* Important! When having connections with and without auth
  13337. * would cause double free and then crash */
  13338. ri->remote_user = NULL;
  13339. }
  13340. /* NOTE(lsm): order is important here. should_keep_alive() call
  13341. * is using parsed request, which will be invalid after
  13342. * memmove's below.
  13343. * Therefore, memorize should_keep_alive() result now for later
  13344. * use in loop exit condition. */
  13345. keep_alive = (conn->ctx->stop_flag == 0) && should_keep_alive(conn)
  13346. && (conn->content_len >= 0);
  13347. /* Discard all buffered data for this request */
  13348. discard_len = ((conn->content_len >= 0) && (conn->request_len > 0)
  13349. && ((conn->request_len + conn->content_len)
  13350. < (int64_t)conn->data_len))
  13351. ? (int)(conn->request_len + conn->content_len)
  13352. : conn->data_len;
  13353. /*assert(discard_len >= 0);*/
  13354. if (discard_len < 0) {
  13355. DEBUG_TRACE("internal error: discard_len = %li",
  13356. (long int)discard_len);
  13357. break;
  13358. }
  13359. conn->data_len -= discard_len;
  13360. if (conn->data_len > 0) {
  13361. DEBUG_TRACE("discard_len = %lu", (long unsigned)discard_len);
  13362. memmove(conn->buf, conn->buf + discard_len, (size_t)conn->data_len);
  13363. }
  13364. /* assert(conn->data_len >= 0); */
  13365. /* assert(conn->data_len <= conn->buf_size); */
  13366. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  13367. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  13368. (long int)conn->data_len,
  13369. (long int)conn->buf_size);
  13370. break;
  13371. }
  13372. conn->handled_requests++;
  13373. } while (keep_alive);
  13374. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  13375. conn->request_info.remote_addr,
  13376. difftime(time(NULL), conn->conn_birth_time));
  13377. close_connection(conn);
  13378. #if defined(USE_SERVER_STATS)
  13379. mg_atomic_add(&(conn->ctx->total_requests), conn->handled_requests);
  13380. mg_atomic_dec(&(conn->ctx->active_connections));
  13381. #endif
  13382. }
  13383. #if defined(ALTERNATIVE_QUEUE)
  13384. static void
  13385. produce_socket(struct mg_context *ctx, const struct socket *sp)
  13386. {
  13387. unsigned int i;
  13388. for (;;) {
  13389. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  13390. /* find a free worker slot and signal it */
  13391. if (ctx->client_socks[i].in_use == 0) {
  13392. ctx->client_socks[i] = *sp;
  13393. ctx->client_socks[i].in_use = 1;
  13394. event_signal(ctx->client_wait_events[i]);
  13395. return;
  13396. }
  13397. }
  13398. /* queue is full */
  13399. mg_sleep(1);
  13400. }
  13401. }
  13402. static int
  13403. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  13404. {
  13405. DEBUG_TRACE("%s", "going idle");
  13406. ctx->client_socks[thread_index].in_use = 0;
  13407. event_wait(ctx->client_wait_events[thread_index]);
  13408. *sp = ctx->client_socks[thread_index];
  13409. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  13410. return !ctx->stop_flag;
  13411. }
  13412. #else /* ALTERNATIVE_QUEUE */
  13413. /* Worker threads take accepted socket from the queue */
  13414. static int
  13415. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  13416. {
  13417. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  13418. (void)thread_index;
  13419. (void)pthread_mutex_lock(&ctx->thread_mutex);
  13420. DEBUG_TRACE("%s", "going idle");
  13421. /* If the queue is empty, wait. We're idle at this point. */
  13422. while ((ctx->sq_head == ctx->sq_tail) && (ctx->stop_flag == 0)) {
  13423. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  13424. }
  13425. /* If we're stopping, sq_head may be equal to sq_tail. */
  13426. if (ctx->sq_head > ctx->sq_tail) {
  13427. /* Copy socket from the queue and increment tail */
  13428. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  13429. ctx->sq_tail++;
  13430. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  13431. /* Wrap pointers if needed */
  13432. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  13433. ctx->sq_tail -= QUEUE_SIZE(ctx);
  13434. ctx->sq_head -= QUEUE_SIZE(ctx);
  13435. }
  13436. }
  13437. (void)pthread_cond_signal(&ctx->sq_empty);
  13438. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  13439. return !ctx->stop_flag;
  13440. #undef QUEUE_SIZE
  13441. }
  13442. /* Master thread adds accepted socket to a queue */
  13443. static void
  13444. produce_socket(struct mg_context *ctx, const struct socket *sp)
  13445. {
  13446. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  13447. if (!ctx) {
  13448. return;
  13449. }
  13450. (void)pthread_mutex_lock(&ctx->thread_mutex);
  13451. /* If the queue is full, wait */
  13452. while ((ctx->stop_flag == 0)
  13453. && (ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx))) {
  13454. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  13455. }
  13456. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  13457. /* Copy socket to the queue and increment head */
  13458. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  13459. ctx->sq_head++;
  13460. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  13461. }
  13462. (void)pthread_cond_signal(&ctx->sq_full);
  13463. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  13464. #undef QUEUE_SIZE
  13465. }
  13466. #endif /* ALTERNATIVE_QUEUE */
  13467. struct worker_thread_args {
  13468. struct mg_context *ctx;
  13469. int index;
  13470. };
  13471. static void *
  13472. worker_thread_run(struct worker_thread_args *thread_args)
  13473. {
  13474. struct mg_context *ctx = thread_args->ctx;
  13475. struct mg_connection *conn;
  13476. struct mg_workerTLS tls;
  13477. #if defined(MG_LEGACY_INTERFACE)
  13478. uint32_t addr;
  13479. #endif
  13480. mg_set_thread_name("worker");
  13481. tls.is_master = 0;
  13482. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  13483. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13484. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  13485. #endif
  13486. /* Initialize thread local storage before calling any callback */
  13487. pthread_setspecific(sTlsKey, &tls);
  13488. if (ctx->callbacks.init_thread) {
  13489. /* call init_thread for a worker thread (type 1) */
  13490. ctx->callbacks.init_thread(ctx, 1);
  13491. }
  13492. /* Connection structure has been pre-allocated */
  13493. if (((int)thread_args->index < 0)
  13494. || ((unsigned)thread_args->index
  13495. >= (unsigned)ctx->cfg_worker_threads)) {
  13496. mg_cry(fc(ctx),
  13497. "Internal error: Invalid worker index %i",
  13498. (int)thread_args->index);
  13499. return NULL;
  13500. }
  13501. conn = ctx->worker_connections + thread_args->index;
  13502. /* Request buffers are not pre-allocated. They are private to the
  13503. * request and do not contain any state information that might be
  13504. * of interest to anyone observing a server status. */
  13505. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->ctx);
  13506. if (conn->buf == NULL) {
  13507. mg_cry(fc(ctx),
  13508. "Out of memory: Cannot allocate buffer for worker %i",
  13509. (int)thread_args->index);
  13510. return NULL;
  13511. }
  13512. conn->buf_size = (int)ctx->max_request_size;
  13513. conn->ctx = ctx;
  13514. conn->thread_index = thread_args->index;
  13515. conn->request_info.user_data = ctx->user_data;
  13516. /* Allocate a mutex for this connection to allow communication both
  13517. * within the request handler and from elsewhere in the application
  13518. */
  13519. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  13520. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  13521. * signal sq_empty condvar to wake up the master waiting in
  13522. * produce_socket() */
  13523. while (consume_socket(ctx, &conn->client, conn->thread_index)) {
  13524. conn->conn_birth_time = time(NULL);
  13525. /* Fill in IP, port info early so even if SSL setup below fails,
  13526. * error handler would have the corresponding info.
  13527. * Thanks to Johannes Winkelmann for the patch.
  13528. */
  13529. #if defined(USE_IPV6)
  13530. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  13531. conn->request_info.remote_port =
  13532. ntohs(conn->client.rsa.sin6.sin6_port);
  13533. } else
  13534. #endif
  13535. {
  13536. conn->request_info.remote_port =
  13537. ntohs(conn->client.rsa.sin.sin_port);
  13538. }
  13539. sockaddr_to_string(conn->request_info.remote_addr,
  13540. sizeof(conn->request_info.remote_addr),
  13541. &conn->client.rsa);
  13542. DEBUG_TRACE("Start processing connection from %s",
  13543. conn->request_info.remote_addr);
  13544. #if defined(MG_LEGACY_INTERFACE)
  13545. /* This legacy interface only works for the IPv4 case */
  13546. addr = ntohl(conn->client.rsa.sin.sin_addr.s_addr);
  13547. memcpy(&conn->request_info.remote_ip, &addr, 4);
  13548. #endif
  13549. conn->request_info.is_ssl = conn->client.is_ssl;
  13550. if (conn->client.is_ssl) {
  13551. #ifndef NO_SSL
  13552. /* HTTPS connection */
  13553. if (sslize(conn,
  13554. conn->ctx->ssl_ctx,
  13555. SSL_accept,
  13556. &(conn->ctx->stop_flag))) {
  13557. /* Get SSL client certificate information (if set) */
  13558. ssl_get_client_cert_info(conn);
  13559. /* process HTTPS connection */
  13560. process_new_connection(conn);
  13561. /* Free client certificate info */
  13562. if (conn->request_info.client_cert) {
  13563. mg_free((void *)(conn->request_info.client_cert->subject));
  13564. mg_free((void *)(conn->request_info.client_cert->issuer));
  13565. mg_free((void *)(conn->request_info.client_cert->serial));
  13566. mg_free((void *)(conn->request_info.client_cert->finger));
  13567. conn->request_info.client_cert->subject = 0;
  13568. conn->request_info.client_cert->issuer = 0;
  13569. conn->request_info.client_cert->serial = 0;
  13570. conn->request_info.client_cert->finger = 0;
  13571. mg_free(conn->request_info.client_cert);
  13572. conn->request_info.client_cert = 0;
  13573. }
  13574. }
  13575. #endif
  13576. } else {
  13577. /* process HTTP connection */
  13578. process_new_connection(conn);
  13579. }
  13580. DEBUG_TRACE("%s", "Connection closed");
  13581. }
  13582. pthread_setspecific(sTlsKey, NULL);
  13583. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13584. CloseHandle(tls.pthread_cond_helper_mutex);
  13585. #endif
  13586. pthread_mutex_destroy(&conn->mutex);
  13587. /* Free the request buffer. */
  13588. conn->buf_size = 0;
  13589. mg_free(conn->buf);
  13590. conn->buf = NULL;
  13591. DEBUG_TRACE("%s", "exiting");
  13592. return NULL;
  13593. }
  13594. /* Threads have different return types on Windows and Unix. */
  13595. #ifdef _WIN32
  13596. static unsigned __stdcall worker_thread(void *thread_func_param)
  13597. {
  13598. struct worker_thread_args *pwta =
  13599. (struct worker_thread_args *)thread_func_param;
  13600. worker_thread_run(pwta);
  13601. mg_free(thread_func_param);
  13602. return 0;
  13603. }
  13604. #else
  13605. static void *
  13606. worker_thread(void *thread_func_param)
  13607. {
  13608. struct worker_thread_args *pwta =
  13609. (struct worker_thread_args *)thread_func_param;
  13610. worker_thread_run(pwta);
  13611. mg_free(thread_func_param);
  13612. return NULL;
  13613. }
  13614. #endif /* _WIN32 */
  13615. static void
  13616. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  13617. {
  13618. struct socket so;
  13619. char src_addr[IP_ADDR_STR_LEN];
  13620. socklen_t len = sizeof(so.rsa);
  13621. int on = 1;
  13622. if (!listener) {
  13623. return;
  13624. }
  13625. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  13626. == INVALID_SOCKET) {
  13627. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  13628. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  13629. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  13630. closesocket(so.sock);
  13631. } else {
  13632. /* Put so socket structure into the queue */
  13633. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  13634. set_close_on_exec(so.sock, fc(ctx));
  13635. so.is_ssl = listener->is_ssl;
  13636. so.ssl_redir = listener->ssl_redir;
  13637. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  13638. mg_cry(fc(ctx),
  13639. "%s: getsockname() failed: %s",
  13640. __func__,
  13641. strerror(ERRNO));
  13642. }
  13643. /* Set TCP keep-alive. This is needed because if HTTP-level
  13644. * keep-alive
  13645. * is enabled, and client resets the connection, server won't get
  13646. * TCP FIN or RST and will keep the connection open forever. With
  13647. * TCP keep-alive, next keep-alive handshake will figure out that
  13648. * the client is down and will close the server end.
  13649. * Thanks to Igor Klopov who suggested the patch. */
  13650. if (setsockopt(so.sock,
  13651. SOL_SOCKET,
  13652. SO_KEEPALIVE,
  13653. (SOCK_OPT_TYPE)&on,
  13654. sizeof(on)) != 0) {
  13655. mg_cry(fc(ctx),
  13656. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  13657. __func__,
  13658. strerror(ERRNO));
  13659. }
  13660. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  13661. * to effectively fill up the underlying IP packet payload and
  13662. * reduce the overhead of sending lots of small buffers. However
  13663. * this hurts the server's throughput (ie. operations per second)
  13664. * when HTTP 1.1 persistent connections are used and the responses
  13665. * are relatively small (eg. less than 1400 bytes).
  13666. */
  13667. if ((ctx != NULL) && (ctx->config[CONFIG_TCP_NODELAY] != NULL)
  13668. && (!strcmp(ctx->config[CONFIG_TCP_NODELAY], "1"))) {
  13669. if (set_tcp_nodelay(so.sock, 1) != 0) {
  13670. mg_cry(fc(ctx),
  13671. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  13672. __func__,
  13673. strerror(ERRNO));
  13674. }
  13675. }
  13676. /* We are using non-blocking sockets. Thus, the
  13677. * set_sock_timeout(so.sock, timeout);
  13678. * call is no longer required. */
  13679. set_blocking_mode(so.sock, 0);
  13680. so.in_use = 0;
  13681. produce_socket(ctx, &so);
  13682. }
  13683. }
  13684. static void
  13685. master_thread_run(void *thread_func_param)
  13686. {
  13687. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  13688. struct mg_workerTLS tls;
  13689. struct pollfd *pfd;
  13690. unsigned int i;
  13691. unsigned int workerthreadcount;
  13692. if (!ctx) {
  13693. return;
  13694. }
  13695. mg_set_thread_name("master");
  13696. /* Increase priority of the master thread */
  13697. #if defined(_WIN32)
  13698. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  13699. #elif defined(USE_MASTER_THREAD_PRIORITY)
  13700. int min_prio = sched_get_priority_min(SCHED_RR);
  13701. int max_prio = sched_get_priority_max(SCHED_RR);
  13702. if ((min_prio >= 0) && (max_prio >= 0)
  13703. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  13704. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  13705. struct sched_param sched_param = {0};
  13706. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  13707. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  13708. }
  13709. #endif
  13710. /* Initialize thread local storage */
  13711. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13712. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  13713. #endif
  13714. tls.is_master = 1;
  13715. pthread_setspecific(sTlsKey, &tls);
  13716. if (ctx->callbacks.init_thread) {
  13717. /* Callback for the master thread (type 0) */
  13718. ctx->callbacks.init_thread(ctx, 0);
  13719. }
  13720. /* Server starts *now* */
  13721. ctx->start_time = time(NULL);
  13722. /* Start the server */
  13723. pfd = ctx->listening_socket_fds;
  13724. while (ctx->stop_flag == 0) {
  13725. for (i = 0; i < ctx->num_listening_sockets; i++) {
  13726. pfd[i].fd = ctx->listening_sockets[i].sock;
  13727. pfd[i].events = POLLIN;
  13728. }
  13729. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  13730. for (i = 0; i < ctx->num_listening_sockets; i++) {
  13731. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  13732. * successful poll, and POLLIN is defined as
  13733. * (POLLRDNORM | POLLRDBAND)
  13734. * Therefore, we're checking pfd[i].revents & POLLIN, not
  13735. * pfd[i].revents == POLLIN. */
  13736. if ((ctx->stop_flag == 0) && (pfd[i].revents & POLLIN)) {
  13737. accept_new_connection(&ctx->listening_sockets[i], ctx);
  13738. }
  13739. }
  13740. }
  13741. }
  13742. /* Here stop_flag is 1 - Initiate shutdown. */
  13743. DEBUG_TRACE("%s", "stopping workers");
  13744. /* Stop signal received: somebody called mg_stop. Quit. */
  13745. close_all_listening_sockets(ctx);
  13746. /* Wakeup workers that are waiting for connections to handle. */
  13747. (void)pthread_mutex_lock(&ctx->thread_mutex);
  13748. #if defined(ALTERNATIVE_QUEUE)
  13749. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  13750. event_signal(ctx->client_wait_events[i]);
  13751. /* Since we know all sockets, we can shutdown the connections. */
  13752. if (ctx->client_socks[i].in_use) {
  13753. shutdown(ctx->client_socks[i].sock, SHUTDOWN_BOTH);
  13754. }
  13755. }
  13756. #else
  13757. pthread_cond_broadcast(&ctx->sq_full);
  13758. #endif
  13759. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  13760. /* Join all worker threads to avoid leaking threads. */
  13761. workerthreadcount = ctx->cfg_worker_threads;
  13762. for (i = 0; i < workerthreadcount; i++) {
  13763. if (ctx->worker_threadids[i] != 0) {
  13764. mg_join_thread(ctx->worker_threadids[i]);
  13765. }
  13766. }
  13767. #if defined(USE_LUA)
  13768. /* Free Lua state of lua background task */
  13769. if (ctx->lua_background_state) {
  13770. lua_close((lua_State *)ctx->lua_background_state);
  13771. ctx->lua_background_state = 0;
  13772. }
  13773. #endif
  13774. DEBUG_TRACE("%s", "exiting");
  13775. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13776. CloseHandle(tls.pthread_cond_helper_mutex);
  13777. #endif
  13778. pthread_setspecific(sTlsKey, NULL);
  13779. /* Signal mg_stop() that we're done.
  13780. * WARNING: This must be the very last thing this
  13781. * thread does, as ctx becomes invalid after this line. */
  13782. ctx->stop_flag = 2;
  13783. }
  13784. /* Threads have different return types on Windows and Unix. */
  13785. #ifdef _WIN32
  13786. static unsigned __stdcall master_thread(void *thread_func_param)
  13787. {
  13788. master_thread_run(thread_func_param);
  13789. return 0;
  13790. }
  13791. #else
  13792. static void *
  13793. master_thread(void *thread_func_param)
  13794. {
  13795. master_thread_run(thread_func_param);
  13796. return NULL;
  13797. }
  13798. #endif /* _WIN32 */
  13799. static void
  13800. free_context(struct mg_context *ctx)
  13801. {
  13802. int i;
  13803. struct mg_handler_info *tmp_rh;
  13804. if (ctx == NULL) {
  13805. return;
  13806. }
  13807. if (ctx->callbacks.exit_context) {
  13808. ctx->callbacks.exit_context(ctx);
  13809. }
  13810. /* All threads exited, no sync is needed. Destroy thread mutex and
  13811. * condvars
  13812. */
  13813. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  13814. #if defined(ALTERNATIVE_QUEUE)
  13815. mg_free(ctx->client_socks);
  13816. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  13817. event_destroy(ctx->client_wait_events[i]);
  13818. }
  13819. mg_free(ctx->client_wait_events);
  13820. #else
  13821. (void)pthread_cond_destroy(&ctx->sq_empty);
  13822. (void)pthread_cond_destroy(&ctx->sq_full);
  13823. #endif
  13824. /* Destroy other context global data structures mutex */
  13825. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  13826. #if defined(USE_TIMERS)
  13827. timers_exit(ctx);
  13828. #endif
  13829. /* Deallocate config parameters */
  13830. for (i = 0; i < NUM_OPTIONS; i++) {
  13831. if (ctx->config[i] != NULL) {
  13832. #if defined(_MSC_VER)
  13833. #pragma warning(suppress : 6001)
  13834. #endif
  13835. mg_free(ctx->config[i]);
  13836. }
  13837. }
  13838. /* Deallocate request handlers */
  13839. while (ctx->handlers) {
  13840. tmp_rh = ctx->handlers;
  13841. ctx->handlers = tmp_rh->next;
  13842. mg_free(tmp_rh->uri);
  13843. mg_free(tmp_rh);
  13844. }
  13845. #ifndef NO_SSL
  13846. /* Deallocate SSL context */
  13847. if (ctx->ssl_ctx != NULL) {
  13848. SSL_CTX_free(ctx->ssl_ctx);
  13849. }
  13850. #endif /* !NO_SSL */
  13851. /* Deallocate worker thread ID array */
  13852. if (ctx->worker_threadids != NULL) {
  13853. mg_free(ctx->worker_threadids);
  13854. }
  13855. /* Deallocate worker thread ID array */
  13856. if (ctx->worker_connections != NULL) {
  13857. mg_free(ctx->worker_connections);
  13858. }
  13859. /* deallocate system name string */
  13860. mg_free(ctx->systemName);
  13861. /* Deallocate context itself */
  13862. mg_free(ctx);
  13863. }
  13864. void
  13865. mg_stop(struct mg_context *ctx)
  13866. {
  13867. pthread_t mt;
  13868. if (!ctx) {
  13869. return;
  13870. }
  13871. /* We don't use a lock here. Calling mg_stop with the same ctx from
  13872. * two threads is not allowed. */
  13873. mt = ctx->masterthreadid;
  13874. if (mt == 0) {
  13875. return;
  13876. }
  13877. ctx->masterthreadid = 0;
  13878. /* Set stop flag, so all threads know they have to exit. */
  13879. ctx->stop_flag = 1;
  13880. /* Wait until everything has stopped. */
  13881. while (ctx->stop_flag != 2) {
  13882. (void)mg_sleep(10);
  13883. }
  13884. mg_join_thread(mt);
  13885. free_context(ctx);
  13886. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13887. (void)WSACleanup();
  13888. #endif /* _WIN32 && !__SYMBIAN32__ */
  13889. }
  13890. static void
  13891. get_system_name(char **sysName)
  13892. {
  13893. #if defined(_WIN32)
  13894. #if !defined(__SYMBIAN32__)
  13895. #if defined(_WIN32_WCE)
  13896. *sysName = mg_strdup("WinCE");
  13897. #else
  13898. char name[128];
  13899. DWORD dwVersion = 0;
  13900. DWORD dwMajorVersion = 0;
  13901. DWORD dwMinorVersion = 0;
  13902. DWORD dwBuild = 0;
  13903. BOOL wowRet, isWoW = FALSE;
  13904. #ifdef _MSC_VER
  13905. #pragma warning(push)
  13906. /* GetVersion was declared deprecated */
  13907. #pragma warning(disable : 4996)
  13908. #endif
  13909. dwVersion = GetVersion();
  13910. #ifdef _MSC_VER
  13911. #pragma warning(pop)
  13912. #endif
  13913. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  13914. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  13915. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  13916. (void)dwBuild;
  13917. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  13918. sprintf(name,
  13919. "Windows %u.%u%s",
  13920. (unsigned)dwMajorVersion,
  13921. (unsigned)dwMinorVersion,
  13922. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  13923. *sysName = mg_strdup(name);
  13924. #endif
  13925. #else
  13926. *sysName = mg_strdup("Symbian");
  13927. #endif
  13928. #else
  13929. struct utsname name;
  13930. memset(&name, 0, sizeof(name));
  13931. uname(&name);
  13932. *sysName = mg_strdup(name.sysname);
  13933. #endif
  13934. }
  13935. struct mg_context *
  13936. mg_start(const struct mg_callbacks *callbacks,
  13937. void *user_data,
  13938. const char **options)
  13939. {
  13940. struct mg_context *ctx;
  13941. const char *name, *value, *default_value;
  13942. int idx, ok, workerthreadcount;
  13943. unsigned int i;
  13944. int itmp;
  13945. void (*exit_callback)(const struct mg_context *ctx) = 0;
  13946. struct mg_workerTLS tls;
  13947. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13948. WSADATA data;
  13949. WSAStartup(MAKEWORD(2, 2), &data);
  13950. #endif /* _WIN32 && !__SYMBIAN32__ */
  13951. /* Allocate context and initialize reasonable general case defaults. */
  13952. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  13953. return NULL;
  13954. }
  13955. /* Random number generator will initialize at the first call */
  13956. ctx->auth_nonce_mask =
  13957. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  13958. if (mg_init_library_called == 0) {
  13959. /* Legacy INIT, if mg_start is called without mg_init_library.
  13960. * Note: This may cause a memory leak */
  13961. mg_init_library(0);
  13962. }
  13963. tls.is_master = -1;
  13964. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  13965. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13966. tls.pthread_cond_helper_mutex = NULL;
  13967. #endif
  13968. pthread_setspecific(sTlsKey, &tls);
  13969. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr);
  13970. #if !defined(ALTERNATIVE_QUEUE)
  13971. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  13972. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  13973. #endif
  13974. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr);
  13975. if (!ok) {
  13976. /* Fatal error - abort start. However, this situation should never
  13977. * occur in practice. */
  13978. mg_cry(fc(ctx), "Cannot initialize thread synchronization objects");
  13979. mg_free(ctx);
  13980. pthread_setspecific(sTlsKey, NULL);
  13981. return NULL;
  13982. }
  13983. if (callbacks) {
  13984. ctx->callbacks = *callbacks;
  13985. exit_callback = callbacks->exit_context;
  13986. ctx->callbacks.exit_context = 0;
  13987. }
  13988. ctx->user_data = user_data;
  13989. ctx->handlers = NULL;
  13990. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  13991. ctx->shared_lua_websockets = 0;
  13992. #endif
  13993. while (options && (name = *options++) != NULL) {
  13994. if ((idx = get_option_index(name)) == -1) {
  13995. mg_cry(fc(ctx), "Invalid option: %s", name);
  13996. free_context(ctx);
  13997. pthread_setspecific(sTlsKey, NULL);
  13998. return NULL;
  13999. } else if ((value = *options++) == NULL) {
  14000. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  14001. free_context(ctx);
  14002. pthread_setspecific(sTlsKey, NULL);
  14003. return NULL;
  14004. }
  14005. if (ctx->config[idx] != NULL) {
  14006. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  14007. mg_free(ctx->config[idx]);
  14008. }
  14009. ctx->config[idx] = mg_strdup(value);
  14010. DEBUG_TRACE("[%s] -> [%s]", name, value);
  14011. }
  14012. /* Set default value if needed */
  14013. for (i = 0; config_options[i].name != NULL; i++) {
  14014. default_value = config_options[i].default_value;
  14015. if ((ctx->config[i] == NULL) && (default_value != NULL)) {
  14016. ctx->config[i] = mg_strdup(default_value);
  14017. }
  14018. }
  14019. itmp = atoi(ctx->config[MAX_REQUEST_SIZE]);
  14020. if (itmp < 1024) {
  14021. mg_cry(fc(ctx), "max_request_size too small");
  14022. free_context(ctx);
  14023. pthread_setspecific(sTlsKey, NULL);
  14024. return NULL;
  14025. }
  14026. ctx->max_request_size = (unsigned)itmp;
  14027. workerthreadcount = atoi(ctx->config[NUM_THREADS]);
  14028. if (workerthreadcount > MAX_WORKER_THREADS) {
  14029. mg_cry(fc(ctx), "Too many worker threads");
  14030. free_context(ctx);
  14031. pthread_setspecific(sTlsKey, NULL);
  14032. return NULL;
  14033. }
  14034. if (workerthreadcount <= 0) {
  14035. mg_cry(fc(ctx), "Invalid number of worker threads");
  14036. free_context(ctx);
  14037. pthread_setspecific(sTlsKey, NULL);
  14038. return NULL;
  14039. }
  14040. #if defined(NO_FILES)
  14041. if (ctx->config[DOCUMENT_ROOT] != NULL) {
  14042. mg_cry(fc(ctx), "%s", "Document root must not be set");
  14043. free_context(ctx);
  14044. pthread_setspecific(sTlsKey, NULL);
  14045. return NULL;
  14046. }
  14047. #endif
  14048. get_system_name(&ctx->systemName);
  14049. #if defined(USE_LUA)
  14050. /* If a Lua background script has been configured, start it. */
  14051. if (ctx->config[LUA_BACKGROUND_SCRIPT] != NULL) {
  14052. char ebuf[256];
  14053. void *state = (void *)mg_prepare_lua_context_script(
  14054. ctx->config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  14055. if (!state) {
  14056. mg_cry(fc(ctx), "lua_background_script error: %s", ebuf);
  14057. free_context(ctx);
  14058. pthread_setspecific(sTlsKey, NULL);
  14059. return NULL;
  14060. }
  14061. ctx->lua_background_state = state;
  14062. } else {
  14063. ctx->lua_background_state = 0;
  14064. }
  14065. #endif
  14066. /* NOTE(lsm): order is important here. SSL certificates must
  14067. * be initialized before listening ports. UID must be set last. */
  14068. if (!set_gpass_option(ctx) ||
  14069. #if !defined(NO_SSL)
  14070. !set_ssl_option(ctx) ||
  14071. #endif
  14072. !set_ports_option(ctx) ||
  14073. #if !defined(_WIN32)
  14074. !set_uid_option(ctx) ||
  14075. #endif
  14076. !set_acl_option(ctx)) {
  14077. free_context(ctx);
  14078. pthread_setspecific(sTlsKey, NULL);
  14079. return NULL;
  14080. }
  14081. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  14082. /* Ignore SIGPIPE signal, so if browser cancels the request, it
  14083. * won't kill the whole process. */
  14084. (void)signal(SIGPIPE, SIG_IGN);
  14085. #endif /* !_WIN32 && !__SYMBIAN32__ */
  14086. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  14087. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  14088. sizeof(pthread_t),
  14089. ctx);
  14090. if (ctx->worker_threadids == NULL) {
  14091. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  14092. free_context(ctx);
  14093. pthread_setspecific(sTlsKey, NULL);
  14094. return NULL;
  14095. }
  14096. ctx->worker_connections =
  14097. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  14098. sizeof(struct mg_connection),
  14099. ctx);
  14100. if (ctx->worker_connections == NULL) {
  14101. mg_cry(fc(ctx), "Not enough memory for worker thread connection array");
  14102. free_context(ctx);
  14103. pthread_setspecific(sTlsKey, NULL);
  14104. return NULL;
  14105. }
  14106. #if defined(ALTERNATIVE_QUEUE)
  14107. ctx->client_wait_events = mg_calloc_ctx(sizeof(ctx->client_wait_events[0]),
  14108. ctx->cfg_worker_threads,
  14109. ctx);
  14110. if (ctx->client_wait_events == NULL) {
  14111. mg_cry(fc(ctx), "Not enough memory for worker event array");
  14112. mg_free(ctx->worker_threadids);
  14113. free_context(ctx);
  14114. pthread_setspecific(sTlsKey, NULL);
  14115. return NULL;
  14116. }
  14117. ctx->client_socks = mg_calloc_ctx(sizeof(ctx->client_socks[0]),
  14118. ctx->cfg_worker_threads,
  14119. ctx);
  14120. if (ctx->client_wait_events == NULL) {
  14121. mg_cry(fc(ctx), "Not enough memory for worker socket array");
  14122. mg_free(ctx->client_socks);
  14123. mg_free(ctx->worker_threadids);
  14124. free_context(ctx);
  14125. pthread_setspecific(sTlsKey, NULL);
  14126. return NULL;
  14127. }
  14128. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  14129. ctx->client_wait_events[i] = event_create();
  14130. if (ctx->client_wait_events[i] == 0) {
  14131. mg_cry(fc(ctx), "Error creating worker event %i", i);
  14132. while (i > 0) {
  14133. i--;
  14134. event_destroy(ctx->client_wait_events[i]);
  14135. }
  14136. mg_free(ctx->client_socks);
  14137. mg_free(ctx->worker_threadids);
  14138. free_context(ctx);
  14139. pthread_setspecific(sTlsKey, NULL);
  14140. return NULL;
  14141. }
  14142. }
  14143. #endif
  14144. #if defined(USE_TIMERS)
  14145. if (timers_init(ctx) != 0) {
  14146. mg_cry(fc(ctx), "Error creating timers");
  14147. free_context(ctx);
  14148. pthread_setspecific(sTlsKey, NULL);
  14149. return NULL;
  14150. }
  14151. #endif
  14152. /* Context has been created - init user libraries */
  14153. if (ctx->callbacks.init_context) {
  14154. ctx->callbacks.init_context(ctx);
  14155. }
  14156. ctx->callbacks.exit_context = exit_callback;
  14157. ctx->context_type = 1; /* server context */
  14158. /* Start master (listening) thread */
  14159. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  14160. /* Start worker threads */
  14161. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  14162. struct worker_thread_args *wta = (struct worker_thread_args *)
  14163. mg_malloc_ctx(sizeof(struct worker_thread_args), ctx);
  14164. if (wta) {
  14165. wta->ctx = ctx;
  14166. wta->index = (int)i;
  14167. }
  14168. if ((wta == NULL)
  14169. || (mg_start_thread_with_id(worker_thread,
  14170. wta,
  14171. &ctx->worker_threadids[i]) != 0)) {
  14172. /* thread was not created */
  14173. if (wta != NULL) {
  14174. mg_free(wta);
  14175. }
  14176. if (i > 0) {
  14177. mg_cry(fc(ctx),
  14178. "Cannot start worker thread %i: error %ld",
  14179. i + 1,
  14180. (long)ERRNO);
  14181. } else {
  14182. mg_cry(fc(ctx),
  14183. "Cannot create threads: error %ld",
  14184. (long)ERRNO);
  14185. free_context(ctx);
  14186. pthread_setspecific(sTlsKey, NULL);
  14187. return NULL;
  14188. }
  14189. break;
  14190. }
  14191. }
  14192. pthread_setspecific(sTlsKey, NULL);
  14193. return ctx;
  14194. }
  14195. /* Feature check API function */
  14196. unsigned
  14197. mg_check_feature(unsigned feature)
  14198. {
  14199. static const unsigned feature_set = 0
  14200. /* Set bits for available features according to API documentation.
  14201. * This bit mask is created at compile time, according to the active
  14202. * preprocessor defines. It is a single const value at runtime. */
  14203. #if !defined(NO_FILES)
  14204. | 0x0001u
  14205. #endif
  14206. #if !defined(NO_SSL)
  14207. | 0x0002u
  14208. #endif
  14209. #if !defined(NO_CGI)
  14210. | 0x0004u
  14211. #endif
  14212. #if defined(USE_IPV6)
  14213. | 0x0008u
  14214. #endif
  14215. #if defined(USE_WEBSOCKET)
  14216. | 0x0010u
  14217. #endif
  14218. #if defined(USE_LUA)
  14219. | 0x0020u
  14220. #endif
  14221. #if defined(USE_DUKTAPE)
  14222. | 0x0040u
  14223. #endif
  14224. #if !defined(NO_CACHING)
  14225. | 0x0080u
  14226. #endif
  14227. #if defined(USE_SERVER_STATS)
  14228. | 0x0100u
  14229. #endif
  14230. /* Set some extra bits not defined in the API documentation.
  14231. * These bits may change without further notice. */
  14232. #if defined(MG_LEGACY_INTERFACE)
  14233. | 0x8000u
  14234. #endif
  14235. #if defined(MEMORY_DEBUGGING)
  14236. | 0x0100u
  14237. #endif
  14238. #if defined(USE_TIMERS)
  14239. | 0x0200u
  14240. #endif
  14241. #if !defined(NO_NONCE_CHECK)
  14242. | 0x0400u
  14243. #endif
  14244. #if !defined(NO_POPEN)
  14245. | 0x0800u
  14246. #endif
  14247. ;
  14248. return (feature & feature_set);
  14249. }
  14250. /* Get system information. It can be printed or stored by the caller.
  14251. * Return the size of available information. */
  14252. static int
  14253. mg_get_system_info_impl(char *buffer, int buflen)
  14254. {
  14255. char block[256];
  14256. int system_info_length = 0;
  14257. #if defined(_WIN32)
  14258. const char *eol = "\r\n";
  14259. #else
  14260. const char *eol = "\n";
  14261. #endif
  14262. if (buffer == NULL) {
  14263. /* Avoid some warning (although, if some dillweed supplies
  14264. * buffer==NULL combined with buflen>0, he deserves a crash).
  14265. */
  14266. buflen = 0;
  14267. }
  14268. /* Server version */
  14269. {
  14270. const char *version = mg_version();
  14271. mg_snprintf(NULL,
  14272. NULL,
  14273. block,
  14274. sizeof(block),
  14275. "Server Version: %s%s",
  14276. version,
  14277. eol);
  14278. system_info_length += (int)strlen(block);
  14279. if (system_info_length < buflen) {
  14280. strcat(buffer, block);
  14281. }
  14282. }
  14283. /* System info */
  14284. {
  14285. #if defined(_WIN32)
  14286. #if !defined(__SYMBIAN32__)
  14287. DWORD dwVersion = 0;
  14288. DWORD dwMajorVersion = 0;
  14289. DWORD dwMinorVersion = 0;
  14290. SYSTEM_INFO si;
  14291. GetSystemInfo(&si);
  14292. #ifdef _MSC_VER
  14293. #pragma warning(push)
  14294. /* GetVersion was declared deprecated */
  14295. #pragma warning(disable : 4996)
  14296. #endif
  14297. dwVersion = GetVersion();
  14298. #ifdef _MSC_VER
  14299. #pragma warning(pop)
  14300. #endif
  14301. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  14302. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  14303. mg_snprintf(NULL,
  14304. NULL,
  14305. block,
  14306. sizeof(block),
  14307. "Windows %u.%u%s",
  14308. (unsigned)dwMajorVersion,
  14309. (unsigned)dwMinorVersion,
  14310. eol);
  14311. system_info_length += (int)strlen(block);
  14312. if (system_info_length < buflen) {
  14313. strcat(buffer, block);
  14314. }
  14315. mg_snprintf(NULL,
  14316. NULL,
  14317. block,
  14318. sizeof(block),
  14319. "CPU: type %u, cores %u, mask %x%s",
  14320. (unsigned)si.wProcessorArchitecture,
  14321. (unsigned)si.dwNumberOfProcessors,
  14322. (unsigned)si.dwActiveProcessorMask,
  14323. eol);
  14324. system_info_length += (int)strlen(block);
  14325. if (system_info_length < buflen) {
  14326. strcat(buffer, block);
  14327. }
  14328. #else
  14329. mg_snprintf(NULL, NULL, block, sizeof(block), "%s - Symbian%s", eol);
  14330. system_info_length += (int)strlen(block);
  14331. if (system_info_length < buflen) {
  14332. strcat(buffer, block);
  14333. }
  14334. #endif
  14335. #else
  14336. struct utsname name;
  14337. memset(&name, 0, sizeof(name));
  14338. uname(&name);
  14339. mg_snprintf(NULL,
  14340. NULL,
  14341. block,
  14342. sizeof(block),
  14343. "%s %s (%s) - %s%s",
  14344. name.sysname,
  14345. name.version,
  14346. name.release,
  14347. name.machine,
  14348. eol);
  14349. system_info_length += (int)strlen(block);
  14350. if (system_info_length < buflen) {
  14351. strcat(buffer, block);
  14352. }
  14353. #endif
  14354. }
  14355. /* Features */
  14356. {
  14357. mg_snprintf(NULL,
  14358. NULL,
  14359. block,
  14360. sizeof(block),
  14361. "Features: %X%s%s%s%s%s%s%s%s%s%s",
  14362. mg_check_feature(0xFFFFFFFFu),
  14363. eol,
  14364. mg_check_feature(1) ? " Files" : "",
  14365. mg_check_feature(2) ? " HTTPS" : "",
  14366. mg_check_feature(4) ? " CGI" : "",
  14367. mg_check_feature(8) ? " IPv6" : "",
  14368. mg_check_feature(16) ? " WebSockets" : "",
  14369. mg_check_feature(32) ? " Lua" : "",
  14370. mg_check_feature(64) ? " JavaScript" : "",
  14371. mg_check_feature(128) ? " Cache" : "",
  14372. eol);
  14373. system_info_length += (int)strlen(block);
  14374. if (system_info_length < buflen) {
  14375. strcat(buffer, block);
  14376. }
  14377. #ifdef USE_LUA
  14378. mg_snprintf(NULL,
  14379. NULL,
  14380. block,
  14381. sizeof(block),
  14382. "Lua Version: %u (%s)%s",
  14383. (unsigned)LUA_VERSION_NUM,
  14384. LUA_RELEASE,
  14385. eol);
  14386. system_info_length += (int)strlen(block);
  14387. if (system_info_length < buflen) {
  14388. strcat(buffer, block);
  14389. }
  14390. #endif
  14391. #if defined(USE_DUKTAPE)
  14392. mg_snprintf(NULL,
  14393. NULL,
  14394. block,
  14395. sizeof(block),
  14396. "JavaScript: Duktape %u.%u.%u%s",
  14397. (unsigned)DUK_VERSION / 10000,
  14398. ((unsigned)DUK_VERSION / 100) % 100,
  14399. (unsigned)DUK_VERSION % 100,
  14400. eol);
  14401. system_info_length += (int)strlen(block);
  14402. if (system_info_length < buflen) {
  14403. strcat(buffer, block);
  14404. }
  14405. #endif
  14406. }
  14407. /* Build date */
  14408. {
  14409. mg_snprintf(
  14410. NULL, NULL, block, sizeof(block), "Build: %s%s", __DATE__, eol);
  14411. system_info_length += (int)strlen(block);
  14412. if (system_info_length < buflen) {
  14413. strcat(buffer, block);
  14414. }
  14415. }
  14416. /* Compiler information */
  14417. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  14418. {
  14419. #if defined(_MSC_VER)
  14420. mg_snprintf(NULL,
  14421. NULL,
  14422. block,
  14423. sizeof(block),
  14424. "MSC: %u (%u)%s",
  14425. (unsigned)_MSC_VER,
  14426. (unsigned)_MSC_FULL_VER,
  14427. eol);
  14428. system_info_length += (int)strlen(block);
  14429. if (system_info_length < buflen) {
  14430. strcat(buffer, block);
  14431. }
  14432. #elif defined(__MINGW64__)
  14433. mg_snprintf(NULL,
  14434. NULL,
  14435. block,
  14436. sizeof(block),
  14437. "MinGW64: %u.%u%s",
  14438. (unsigned)__MINGW64_VERSION_MAJOR,
  14439. (unsigned)__MINGW64_VERSION_MINOR,
  14440. eol);
  14441. system_info_length += (int)strlen(block);
  14442. if (system_info_length < buflen) {
  14443. strcat(buffer, block);
  14444. }
  14445. mg_snprintf(NULL,
  14446. NULL,
  14447. block,
  14448. sizeof(block),
  14449. "MinGW32: %u.%u%s",
  14450. (unsigned)__MINGW32_MAJOR_VERSION,
  14451. (unsigned)__MINGW32_MINOR_VERSION,
  14452. eol);
  14453. system_info_length += (int)strlen(block);
  14454. if (system_info_length < buflen) {
  14455. strcat(buffer, block);
  14456. }
  14457. #elif defined(__MINGW32__)
  14458. mg_snprintf(NULL,
  14459. NULL,
  14460. block,
  14461. sizeof(block),
  14462. "MinGW32: %u.%u%s",
  14463. (unsigned)__MINGW32_MAJOR_VERSION,
  14464. (unsigned)__MINGW32_MINOR_VERSION,
  14465. eol);
  14466. system_info_length += (int)strlen(block);
  14467. if (system_info_length < buflen) {
  14468. strcat(buffer, block);
  14469. }
  14470. #elif defined(__clang__)
  14471. mg_snprintf(NULL,
  14472. NULL,
  14473. block,
  14474. sizeof(block),
  14475. "clang: %u.%u.%u (%s)%s",
  14476. __clang_major__,
  14477. __clang_minor__,
  14478. __clang_patchlevel__,
  14479. __clang_version__,
  14480. eol);
  14481. system_info_length += (int)strlen(block);
  14482. if (system_info_length < buflen) {
  14483. strcat(buffer, block);
  14484. }
  14485. #elif defined(__GNUC__)
  14486. mg_snprintf(NULL,
  14487. NULL,
  14488. block,
  14489. sizeof(block),
  14490. "gcc: %u.%u.%u%s",
  14491. (unsigned)__GNUC__,
  14492. (unsigned)__GNUC_MINOR__,
  14493. (unsigned)__GNUC_PATCHLEVEL__,
  14494. eol);
  14495. system_info_length += (int)strlen(block);
  14496. if (system_info_length < buflen) {
  14497. strcat(buffer, block);
  14498. }
  14499. #elif defined(__INTEL_COMPILER)
  14500. mg_snprintf(NULL,
  14501. NULL,
  14502. block,
  14503. sizeof(block),
  14504. "Intel C/C++: %u%s",
  14505. (unsigned)__INTEL_COMPILER,
  14506. eol);
  14507. system_info_length += (int)strlen(block);
  14508. if (system_info_length < buflen) {
  14509. strcat(buffer, block);
  14510. }
  14511. #elif defined(__BORLANDC__)
  14512. mg_snprintf(NULL,
  14513. NULL,
  14514. block,
  14515. sizeof(block),
  14516. "Borland C: 0x%x%s",
  14517. (unsigned)__BORLANDC__,
  14518. eol);
  14519. system_info_length += (int)strlen(block);
  14520. if (system_info_length < buflen) {
  14521. strcat(buffer, block);
  14522. }
  14523. #elif defined(__SUNPRO_C)
  14524. mg_snprintf(NULL,
  14525. NULL,
  14526. block,
  14527. sizeof(block),
  14528. "Solaris: 0x%x%s",
  14529. (unsigned)__SUNPRO_C,
  14530. eol);
  14531. system_info_length += (int)strlen(block);
  14532. if (system_info_length < buflen) {
  14533. strcat(buffer, block);
  14534. }
  14535. #else
  14536. mg_snprintf(NULL, NULL, block, sizeof(block), "Other compiler%s", eol);
  14537. system_info_length += (int)strlen(block);
  14538. if (system_info_length < buflen) {
  14539. strcat(buffer, block);
  14540. }
  14541. #endif
  14542. }
  14543. /* Determine 32/64 bit data mode.
  14544. * see https://en.wikipedia.org/wiki/64-bit_computing */
  14545. {
  14546. mg_snprintf(NULL,
  14547. NULL,
  14548. block,
  14549. sizeof(block),
  14550. "Data model: int:%u/%u/%u/%u, float:%u/%u/%u, char:%u/%u, "
  14551. "ptr:%u, size:%u, time:%u%s",
  14552. (unsigned)sizeof(short),
  14553. (unsigned)sizeof(int),
  14554. (unsigned)sizeof(long),
  14555. (unsigned)sizeof(long long),
  14556. (unsigned)sizeof(float),
  14557. (unsigned)sizeof(double),
  14558. (unsigned)sizeof(long double),
  14559. (unsigned)sizeof(char),
  14560. (unsigned)sizeof(wchar_t),
  14561. (unsigned)sizeof(void *),
  14562. (unsigned)sizeof(size_t),
  14563. (unsigned)sizeof(time_t),
  14564. eol);
  14565. system_info_length += (int)strlen(block);
  14566. if (system_info_length < buflen) {
  14567. strcat(buffer, block);
  14568. }
  14569. }
  14570. return system_info_length;
  14571. }
  14572. #if defined(USE_SERVER_STATS)
  14573. /* Get context information. It can be printed or stored by the caller.
  14574. * Return the size of available information. */
  14575. static int
  14576. mg_get_context_info_impl(const struct mg_context *ctx, char *buffer, int buflen)
  14577. {
  14578. char block[256];
  14579. int context_info_length = 0;
  14580. #if defined(_WIN32)
  14581. const char *eol = "\r\n";
  14582. #else
  14583. const char *eol = "\n";
  14584. #endif
  14585. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  14586. const char *eoobj = "}";
  14587. int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
  14588. if ((buffer == NULL) || (buflen < 10)) {
  14589. buflen = 0;
  14590. }
  14591. mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
  14592. context_info_length += (int)strlen(block);
  14593. if (context_info_length < buflen) {
  14594. strcat(buffer, block);
  14595. }
  14596. /* Memory information */
  14597. if (ms) {
  14598. mg_snprintf(NULL,
  14599. NULL,
  14600. block,
  14601. sizeof(block),
  14602. "\"memory\" : {%s"
  14603. "\"blocks\" : %i,%s"
  14604. "\"used\" : %" INT64_FMT ",%s"
  14605. "\"maxUsed\" : %" INT64_FMT "%s"
  14606. "}%s%s",
  14607. eol,
  14608. ms->blockCount,
  14609. eol,
  14610. ms->totalMemUsed,
  14611. eol,
  14612. ms->maxMemUsed,
  14613. eol,
  14614. (ctx ? "," : ""),
  14615. eol);
  14616. context_info_length += (int)strlen(block);
  14617. if (context_info_length + reserved_len < buflen) {
  14618. strcat(buffer, block);
  14619. }
  14620. }
  14621. /* Connections information */
  14622. if (ctx) {
  14623. mg_snprintf(NULL,
  14624. NULL,
  14625. block,
  14626. sizeof(block),
  14627. "\"connections\" : {%s"
  14628. "\"active\" : %i,%s"
  14629. "\"maxActive\" : %i,%s"
  14630. "\"total\" : %" INT64_FMT "%s"
  14631. "},%s",
  14632. eol,
  14633. ctx->active_connections,
  14634. eol,
  14635. ctx->max_connections,
  14636. eol,
  14637. ctx->total_connections,
  14638. eol,
  14639. eol);
  14640. context_info_length += (int)strlen(block);
  14641. if (context_info_length + reserved_len < buflen) {
  14642. strcat(buffer, block);
  14643. }
  14644. }
  14645. /* Requests information */
  14646. if (ctx) {
  14647. mg_snprintf(NULL,
  14648. NULL,
  14649. block,
  14650. sizeof(block),
  14651. "\"requests\" : {%s"
  14652. "\"total\" : %" INT64_FMT "%s"
  14653. "},%s",
  14654. eol,
  14655. ctx->total_requests,
  14656. eol,
  14657. eol);
  14658. context_info_length += (int)strlen(block);
  14659. if (context_info_length + reserved_len < buflen) {
  14660. strcat(buffer, block);
  14661. }
  14662. }
  14663. /* Execution time information */
  14664. if (ctx) {
  14665. char start_time_str[64] = {0};
  14666. char now_str[64] = {0};
  14667. time_t start_time = ctx->start_time;
  14668. time_t now = time(NULL);
  14669. gmt_time_string(start_time_str,
  14670. sizeof(start_time_str) - 1,
  14671. &start_time);
  14672. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  14673. mg_snprintf(NULL,
  14674. NULL,
  14675. block,
  14676. sizeof(block),
  14677. "\"time\" : {%s"
  14678. "\"uptime\" : %.0f,%s"
  14679. "\"start\" : \"%s\",%s"
  14680. "\"now\" : \"%s\"%s"
  14681. "}%s",
  14682. eol,
  14683. difftime(now, start_time),
  14684. eol,
  14685. start_time_str,
  14686. eol,
  14687. now_str,
  14688. eol,
  14689. eol);
  14690. context_info_length += (int)strlen(block);
  14691. if (context_info_length + reserved_len < buflen) {
  14692. strcat(buffer, block);
  14693. }
  14694. }
  14695. /* Terminate string */
  14696. if ((buflen > 0) && buffer && buffer[0]) {
  14697. if (context_info_length < buflen) {
  14698. strcat(buffer, eoobj);
  14699. strcat(buffer, eol);
  14700. context_info_length += reserved_len;
  14701. }
  14702. }
  14703. return context_info_length;
  14704. }
  14705. #endif
  14706. /* Get system information. It can be printed or stored by the caller.
  14707. * Return the size of available information. */
  14708. int
  14709. mg_get_system_info(char *buffer, int buflen)
  14710. {
  14711. if ((buffer == NULL) || (buflen < 1)) {
  14712. return mg_get_system_info_impl(NULL, 0);
  14713. } else {
  14714. /* Reset buffer, so we can always use strcat. */
  14715. buffer[0] = 0;
  14716. return mg_get_system_info_impl(buffer, buflen);
  14717. }
  14718. }
  14719. /* Get context information. It can be printed or stored by the caller.
  14720. * Return the size of available information. */
  14721. int
  14722. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  14723. {
  14724. #if defined(USE_SERVER_STATS)
  14725. if ((buffer == NULL) || (buflen < 1)) {
  14726. return mg_get_context_info_impl(ctx, NULL, 0);
  14727. } else {
  14728. /* Reset buffer, so we can always use strcat. */
  14729. buffer[0] = 0;
  14730. return mg_get_context_info_impl(ctx, buffer, buflen);
  14731. }
  14732. #else
  14733. (void)ctx;
  14734. if ((buffer != NULL) && (buflen > 0)) {
  14735. buffer[0] = 0;
  14736. }
  14737. return 0;
  14738. #endif
  14739. }
  14740. /* Initialize this library. This function does not need to be thread safe.
  14741. */
  14742. unsigned
  14743. mg_init_library(unsigned features)
  14744. {
  14745. #if !defined(NO_SSL)
  14746. char ebuf[128];
  14747. #endif
  14748. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  14749. unsigned features_inited = features_to_init;
  14750. if (mg_init_library_called <= 0) {
  14751. /* Not initialized yet */
  14752. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  14753. return 0;
  14754. }
  14755. }
  14756. mg_global_lock();
  14757. if (mg_init_library_called <= 0) {
  14758. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  14759. /* Fatal error - abort start. However, this situation should
  14760. * never occur in practice. */
  14761. return 0;
  14762. }
  14763. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14764. InitializeCriticalSection(&global_log_file_lock);
  14765. #endif /* _WIN32 && !__SYMBIAN32__ */
  14766. #if !defined(_WIN32)
  14767. pthread_mutexattr_init(&pthread_mutex_attr);
  14768. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  14769. #endif
  14770. #if defined(USE_LUA)
  14771. lua_init_optional_libraries();
  14772. #endif
  14773. }
  14774. #if !defined(NO_SSL)
  14775. if (features_to_init & 2) {
  14776. if (!mg_ssl_initialized) {
  14777. if (initialize_ssl(ebuf, sizeof(ebuf))) {
  14778. mg_ssl_initialized = 1;
  14779. } else {
  14780. (void)ebuf;
  14781. /* TODO: print error */
  14782. features_inited &= ~(2u);
  14783. }
  14784. } else {
  14785. /* ssl already initialized */
  14786. }
  14787. }
  14788. #endif
  14789. /* Start WinSock for Windows */
  14790. if (mg_init_library_called <= 0) {
  14791. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14792. WSADATA data;
  14793. WSAStartup(MAKEWORD(2, 2), &data);
  14794. #endif /* _WIN32 && !__SYMBIAN32__ */
  14795. mg_init_library_called = 1;
  14796. } else {
  14797. mg_init_library_called++;
  14798. }
  14799. mg_global_unlock();
  14800. return features_inited;
  14801. }
  14802. /* Un-initialize this library. */
  14803. unsigned
  14804. mg_exit_library(void)
  14805. {
  14806. if (mg_init_library_called <= 0) {
  14807. return 0;
  14808. }
  14809. mg_global_lock();
  14810. mg_init_library_called--;
  14811. if (mg_init_library_called == 0) {
  14812. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14813. (void)WSACleanup();
  14814. #endif /* _WIN32 && !__SYMBIAN32__ */
  14815. #if !defined(NO_SSL)
  14816. if (mg_ssl_initialized) {
  14817. uninitialize_ssl();
  14818. mg_ssl_initialized = 0;
  14819. }
  14820. #endif
  14821. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14822. (void)DeleteCriticalSection(&global_log_file_lock);
  14823. #endif /* _WIN32 && !__SYMBIAN32__ */
  14824. #if !defined(_WIN32)
  14825. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  14826. #endif
  14827. (void)pthread_key_delete(sTlsKey);
  14828. #if defined(USE_LUA)
  14829. lua_exit_optional_libraries();
  14830. #endif
  14831. mg_global_unlock();
  14832. (void)pthread_mutex_destroy(&global_lock_mutex);
  14833. return 1;
  14834. }
  14835. mg_global_unlock();
  14836. return 1;
  14837. }
  14838. /* End of civetweb.c */