civetweb.c 417 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811
  1. /* Copyright (c) 2013-2017 the Civetweb developers
  2. * Copyright (c) 2004-2013 Sergey Lyubka
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. * THE SOFTWARE.
  21. */
  22. #if defined(_WIN32)
  23. #if !defined(_CRT_SECURE_NO_WARNINGS)
  24. #define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */
  25. #endif
  26. #ifndef _WIN32_WINNT /* defined for tdm-gcc so we can use getnameinfo */
  27. #define _WIN32_WINNT 0x0501
  28. #endif
  29. #else
  30. #if defined(__GNUC__) && !defined(_GNU_SOURCE)
  31. #define _GNU_SOURCE /* for setgroups() */
  32. #endif
  33. #if defined(__linux__) && !defined(_XOPEN_SOURCE)
  34. #define _XOPEN_SOURCE 600 /* For flockfile() on Linux */
  35. #endif
  36. #ifndef _LARGEFILE_SOURCE
  37. #define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
  38. #endif
  39. #ifndef _FILE_OFFSET_BITS
  40. #define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
  41. #endif
  42. #ifndef __STDC_FORMAT_MACROS
  43. #define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
  44. #endif
  45. #ifndef __STDC_LIMIT_MACROS
  46. #define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
  47. #endif
  48. #ifdef __sun
  49. #define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */
  50. #define __inline inline /* not recognized on older compiler versions */
  51. #endif
  52. #endif
  53. #if defined(USE_LUA)
  54. #define USE_TIMERS
  55. #endif
  56. #if defined(_MSC_VER)
  57. /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
  58. #pragma warning(disable : 4306)
  59. /* conditional expression is constant: introduced by FD_SET(..) */
  60. #pragma warning(disable : 4127)
  61. /* non-constant aggregate initializer: issued due to missing C99 support */
  62. #pragma warning(disable : 4204)
  63. /* padding added after data member */
  64. #pragma warning(disable : 4820)
  65. /* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
  66. #pragma warning(disable : 4668)
  67. /* no function prototype given: converting '()' to '(void)' */
  68. #pragma warning(disable : 4255)
  69. /* function has been selected for automatic inline expansion */
  70. #pragma warning(disable : 4711)
  71. #endif
  72. /* This code uses static_assert to check some conditions.
  73. * Unfortunately some compilers still do not support it, so we have a
  74. * replacement function here. */
  75. #if defined(_MSC_VER) && (_MSC_VER >= 1600)
  76. #define mg_static_assert static_assert
  77. #elif defined(__cplusplus) && (__cplusplus >= 201103L)
  78. #define mg_static_assert static_assert
  79. #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)
  80. #define mg_static_assert _Static_assert
  81. #else
  82. char static_assert_replacement[1];
  83. #define mg_static_assert(cond, txt) \
  84. extern char static_assert_replacement[(cond) ? 1 : -1]
  85. #endif
  86. mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
  87. "int data type size check");
  88. mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
  89. "pointer data type size check");
  90. mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
  91. /* DTL -- including winsock2.h works better if lean and mean */
  92. #ifndef WIN32_LEAN_AND_MEAN
  93. #define WIN32_LEAN_AND_MEAN
  94. #endif
  95. #if defined(__SYMBIAN32__)
  96. #define NO_SSL /* SSL is not supported */
  97. #define NO_CGI /* CGI is not supported */
  98. #define PATH_MAX FILENAME_MAX
  99. #endif /* __SYMBIAN32__ */
  100. #ifndef CIVETWEB_HEADER_INCLUDED
  101. /* Include the header file here, so the CivetWeb interface is defined for the
  102. * entire implementation, including the following forward definitions. */
  103. #include "civetweb.h"
  104. #endif
  105. #ifndef IGNORE_UNUSED_RESULT
  106. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  107. #endif
  108. #ifndef _WIN32_WCE /* Some ANSI #includes are not available on Windows CE */
  109. #include <sys/types.h>
  110. #include <sys/stat.h>
  111. #include <errno.h>
  112. #include <signal.h>
  113. #include <fcntl.h>
  114. #endif /* !_WIN32_WCE */
  115. #ifdef __clang__
  116. /* When using -Weverything, clang does not accept it's own headers
  117. * in a release build configuration. Disable what is too much in
  118. * -Weverything. */
  119. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  120. #endif
  121. #ifdef __MACH__ /* Apple OSX section */
  122. #ifdef __clang__
  123. /* Avoid warnings for Xopen 7.00 and higher */
  124. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  125. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  126. #endif
  127. #define CLOCK_MONOTONIC (1)
  128. #define CLOCK_REALTIME (2)
  129. #include <sys/errno.h>
  130. #include <sys/time.h>
  131. #include <mach/clock.h>
  132. #include <mach/mach.h>
  133. #include <mach/mach_time.h>
  134. #include <assert.h>
  135. /* clock_gettime is not implemented on OSX prior to 10.12 */
  136. static int
  137. _civet_clock_gettime(int clk_id, struct timespec *t)
  138. {
  139. memset(t, 0, sizeof(*t));
  140. if (clk_id == CLOCK_REALTIME) {
  141. struct timeval now;
  142. int rv = gettimeofday(&now, NULL);
  143. if (rv) {
  144. return rv;
  145. }
  146. t->tv_sec = now.tv_sec;
  147. t->tv_nsec = now.tv_usec * 1000;
  148. return 0;
  149. } else if (clk_id == CLOCK_MONOTONIC) {
  150. static uint64_t clock_start_time = 0;
  151. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  152. uint64_t now = mach_absolute_time();
  153. if (clock_start_time == 0) {
  154. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  155. #if defined(DEBUG)
  156. assert(mach_status == KERN_SUCCESS);
  157. #else
  158. /* appease "unused variable" warning for release builds */
  159. (void)mach_status;
  160. #endif
  161. clock_start_time = now;
  162. }
  163. now = (uint64_t)((double)(now - clock_start_time)
  164. * (double)timebase_ifo.numer
  165. / (double)timebase_ifo.denom);
  166. t->tv_sec = now / 1000000000;
  167. t->tv_nsec = now % 1000000000;
  168. return 0;
  169. }
  170. return -1; /* EINVAL - Clock ID is unknown */
  171. }
  172. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  173. #ifdef __CLOCK_AVAILABILITY
  174. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  175. * declared but it may be NULL at runtime. So we need to check before using
  176. * it. */
  177. static int
  178. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  179. {
  180. if (clock_gettime) {
  181. return clock_gettime(clk_id, t);
  182. }
  183. return _civet_clock_gettime(clk_id, t);
  184. }
  185. #define clock_gettime _civet_safe_clock_gettime
  186. #else
  187. #define clock_gettime _civet_clock_gettime
  188. #endif
  189. #endif
  190. #include <time.h>
  191. #include <stdlib.h>
  192. #include <stdarg.h>
  193. #include <assert.h>
  194. #include <string.h>
  195. #include <ctype.h>
  196. #include <limits.h>
  197. #include <stddef.h>
  198. #include <stdio.h>
  199. #include <stdint.h>
  200. #ifndef INT64_MAX
  201. #define INT64_MAX (9223372036854775807)
  202. #endif
  203. #ifndef MAX_WORKER_THREADS
  204. #define MAX_WORKER_THREADS (1024 * 64)
  205. #endif
  206. #ifndef SOCKET_TIMEOUT_QUANTUM /* in ms */
  207. #define SOCKET_TIMEOUT_QUANTUM (2000)
  208. #endif
  209. #define SHUTDOWN_RD (0)
  210. #define SHUTDOWN_WR (1)
  211. #define SHUTDOWN_BOTH (2)
  212. mg_static_assert(MAX_WORKER_THREADS >= 1,
  213. "worker threads must be a positive number");
  214. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  215. "size_t data type size check");
  216. #if defined(_WIN32) \
  217. && !defined(__SYMBIAN32__) /* WINDOWS / UNIX include block */
  218. #include <windows.h>
  219. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  220. #include <ws2tcpip.h>
  221. typedef const char *SOCK_OPT_TYPE;
  222. #if !defined(PATH_MAX)
  223. #define PATH_MAX (MAX_PATH)
  224. #endif
  225. #if !defined(PATH_MAX)
  226. #define PATH_MAX (4096)
  227. #endif
  228. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  229. #ifndef _IN_PORT_T
  230. #ifndef in_port_t
  231. #define in_port_t u_short
  232. #endif
  233. #endif
  234. #ifndef _WIN32_WCE
  235. #include <process.h>
  236. #include <direct.h>
  237. #include <io.h>
  238. #else /* _WIN32_WCE */
  239. #define NO_CGI /* WinCE has no pipes */
  240. #define NO_POPEN /* WinCE has no popen */
  241. typedef long off_t;
  242. #define errno ((int)(GetLastError()))
  243. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  244. #endif /* _WIN32_WCE */
  245. #define MAKEUQUAD(lo, hi) \
  246. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  247. #define RATE_DIFF (10000000) /* 100 nsecs */
  248. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  249. #define SYS2UNIX_TIME(lo, hi) \
  250. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  251. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  252. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  253. * Also use _strtoui64 on modern M$ compilers */
  254. #if defined(_MSC_VER)
  255. #if (_MSC_VER < 1300)
  256. #define STRX(x) #x
  257. #define STR(x) STRX(x)
  258. #define __func__ __FILE__ ":" STR(__LINE__)
  259. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  260. #define strtoll(x, y, z) (_atoi64(x))
  261. #else
  262. #define __func__ __FUNCTION__
  263. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  264. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  265. #endif
  266. #endif /* _MSC_VER */
  267. #define ERRNO ((int)(GetLastError()))
  268. #define NO_SOCKLEN_T
  269. #if defined(_WIN64) || defined(__MINGW64__)
  270. #define SSL_LIB "ssleay64.dll"
  271. #define CRYPTO_LIB "libeay64.dll"
  272. #else
  273. #define SSL_LIB "ssleay32.dll"
  274. #define CRYPTO_LIB "libeay32.dll"
  275. #endif
  276. #define O_NONBLOCK (0)
  277. #ifndef W_OK
  278. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  279. #endif
  280. #if !defined(EWOULDBLOCK)
  281. #define EWOULDBLOCK WSAEWOULDBLOCK
  282. #endif /* !EWOULDBLOCK */
  283. #define _POSIX_
  284. #define INT64_FMT "I64d"
  285. #define UINT64_FMT "I64u"
  286. #define WINCDECL __cdecl
  287. #define vsnprintf_impl _vsnprintf
  288. #define access _access
  289. #define mg_sleep(x) (Sleep(x))
  290. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  291. #ifndef popen
  292. #define popen(x, y) (_popen(x, y))
  293. #endif
  294. #ifndef pclose
  295. #define pclose(x) (_pclose(x))
  296. #endif
  297. #define close(x) (_close(x))
  298. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  299. #define RTLD_LAZY (0)
  300. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  301. #define fdopen(x, y) (_fdopen((x), (y)))
  302. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  303. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  304. #define flockfile(x) (EnterCriticalSection(&global_log_file_lock))
  305. #define funlockfile(x) (LeaveCriticalSection(&global_log_file_lock))
  306. #define sleep(x) (Sleep((x)*1000))
  307. #define rmdir(x) (_rmdir(x))
  308. #define timegm(x) (_mkgmtime(x))
  309. #if !defined(fileno)
  310. #define fileno(x) (_fileno(x))
  311. #endif /* !fileno MINGW #defines fileno */
  312. typedef HANDLE pthread_mutex_t;
  313. typedef DWORD pthread_key_t;
  314. typedef HANDLE pthread_t;
  315. typedef struct {
  316. CRITICAL_SECTION threadIdSec;
  317. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  318. } pthread_cond_t;
  319. #ifndef __clockid_t_defined
  320. typedef DWORD clockid_t;
  321. #endif
  322. #ifndef CLOCK_MONOTONIC
  323. #define CLOCK_MONOTONIC (1)
  324. #endif
  325. #ifndef CLOCK_REALTIME
  326. #define CLOCK_REALTIME (2)
  327. #endif
  328. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  329. #define _TIMESPEC_DEFINED
  330. #endif
  331. #ifndef _TIMESPEC_DEFINED
  332. struct timespec {
  333. time_t tv_sec; /* seconds */
  334. long tv_nsec; /* nanoseconds */
  335. };
  336. #endif
  337. #if !defined(WIN_PTHREADS_TIME_H)
  338. #define MUST_IMPLEMENT_CLOCK_GETTIME
  339. #endif
  340. #ifdef MUST_IMPLEMENT_CLOCK_GETTIME
  341. #define clock_gettime mg_clock_gettime
  342. static int
  343. clock_gettime(clockid_t clk_id, struct timespec *tp)
  344. {
  345. FILETIME ft;
  346. ULARGE_INTEGER li;
  347. BOOL ok = FALSE;
  348. double d;
  349. static double perfcnt_per_sec = 0.0;
  350. if (tp) {
  351. memset(tp, 0, sizeof(*tp));
  352. if (clk_id == CLOCK_REALTIME) {
  353. GetSystemTimeAsFileTime(&ft);
  354. li.LowPart = ft.dwLowDateTime;
  355. li.HighPart = ft.dwHighDateTime;
  356. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  357. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  358. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  359. ok = TRUE;
  360. } else if (clk_id == CLOCK_MONOTONIC) {
  361. if (perfcnt_per_sec == 0.0) {
  362. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  363. perfcnt_per_sec = 1.0 / li.QuadPart;
  364. }
  365. if (perfcnt_per_sec != 0.0) {
  366. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  367. d = li.QuadPart * perfcnt_per_sec;
  368. tp->tv_sec = (time_t)d;
  369. d -= tp->tv_sec;
  370. tp->tv_nsec = (long)(d * 1.0E9);
  371. ok = TRUE;
  372. }
  373. }
  374. }
  375. return ok ? 0 : -1;
  376. }
  377. #endif
  378. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  379. static int pthread_mutex_lock(pthread_mutex_t *);
  380. static int pthread_mutex_unlock(pthread_mutex_t *);
  381. static void path_to_unicode(const struct mg_connection *conn,
  382. const char *path,
  383. wchar_t *wbuf,
  384. size_t wbuf_len);
  385. /* All file operations need to be rewritten to solve #246. */
  386. #include "file_ops.inl"
  387. struct mg_file;
  388. static const char *
  389. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p);
  390. /* POSIX dirent interface */
  391. struct dirent {
  392. char d_name[PATH_MAX];
  393. };
  394. typedef struct DIR {
  395. HANDLE handle;
  396. WIN32_FIND_DATAW info;
  397. struct dirent result;
  398. } DIR;
  399. #if defined(_WIN32) && !defined(POLLIN)
  400. #ifndef HAVE_POLL
  401. struct pollfd {
  402. SOCKET fd;
  403. short events;
  404. short revents;
  405. };
  406. #define POLLIN (0x0300)
  407. #endif
  408. #endif
  409. /* Mark required libraries */
  410. #if defined(_MSC_VER)
  411. #pragma comment(lib, "Ws2_32.lib")
  412. #endif
  413. #else /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  414. WINDOWS / UNIX include block */
  415. #include <sys/wait.h>
  416. #include <sys/socket.h>
  417. #include <sys/poll.h>
  418. #include <netinet/in.h>
  419. #include <arpa/inet.h>
  420. #include <sys/time.h>
  421. #include <sys/utsname.h>
  422. #include <stdint.h>
  423. #include <inttypes.h>
  424. #include <netdb.h>
  425. #include <netinet/tcp.h>
  426. typedef const void *SOCK_OPT_TYPE;
  427. #if defined(ANDROID)
  428. typedef unsigned short int in_port_t;
  429. #endif
  430. #include <pwd.h>
  431. #include <unistd.h>
  432. #include <grp.h>
  433. #include <dirent.h>
  434. #define vsnprintf_impl vsnprintf
  435. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  436. #include <dlfcn.h>
  437. #endif
  438. #include <pthread.h>
  439. #if defined(__MACH__)
  440. #define SSL_LIB "libssl.dylib"
  441. #define CRYPTO_LIB "libcrypto.dylib"
  442. #else
  443. #if !defined(SSL_LIB)
  444. #define SSL_LIB "libssl.so"
  445. #endif
  446. #if !defined(CRYPTO_LIB)
  447. #define CRYPTO_LIB "libcrypto.so"
  448. #endif
  449. #endif
  450. #ifndef O_BINARY
  451. #define O_BINARY (0)
  452. #endif /* O_BINARY */
  453. #define closesocket(a) (close(a))
  454. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  455. #define mg_remove(conn, x) (remove(x))
  456. #define mg_sleep(x) (usleep((x)*1000))
  457. #define mg_opendir(conn, x) (opendir(x))
  458. #define mg_closedir(x) (closedir(x))
  459. #define mg_readdir(x) (readdir(x))
  460. #define ERRNO (errno)
  461. #define INVALID_SOCKET (-1)
  462. #define INT64_FMT PRId64
  463. #define UINT64_FMT PRIu64
  464. typedef int SOCKET;
  465. #define WINCDECL
  466. #if defined(__hpux)
  467. /* HPUX 11 does not have monotonic, fall back to realtime */
  468. #ifndef CLOCK_MONOTONIC
  469. #define CLOCK_MONOTONIC CLOCK_REALTIME
  470. #endif
  471. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  472. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  473. * the prototypes use int* rather than socklen_t* which matches the
  474. * actual library expectation. When called with the wrong size arg
  475. * accept() returns a zero client inet addr and check_acl() always
  476. * fails. Since socklen_t is widely used below, just force replace
  477. * their typedef with int. - DTL
  478. */
  479. #define socklen_t int
  480. #endif /* hpux */
  481. #endif /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  482. WINDOWS / UNIX include block */
  483. /* va_copy should always be a macro, C99 and C++11 - DTL */
  484. #ifndef va_copy
  485. #define va_copy(x, y) ((x) = (y))
  486. #endif
  487. #ifdef _WIN32
  488. /* Create substitutes for POSIX functions in Win32. */
  489. #if defined(__MINGW32__)
  490. /* Show no warning in case system functions are not used. */
  491. #pragma GCC diagnostic push
  492. #pragma GCC diagnostic ignored "-Wunused-function"
  493. #endif
  494. static CRITICAL_SECTION global_log_file_lock;
  495. static DWORD
  496. pthread_self(void)
  497. {
  498. return GetCurrentThreadId();
  499. }
  500. static int
  501. pthread_key_create(
  502. pthread_key_t *key,
  503. void (*_ignored)(void *) /* destructor not supported for Windows */
  504. )
  505. {
  506. (void)_ignored;
  507. if ((key != 0)) {
  508. *key = TlsAlloc();
  509. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  510. }
  511. return -2;
  512. }
  513. static int
  514. pthread_key_delete(pthread_key_t key)
  515. {
  516. return TlsFree(key) ? 0 : 1;
  517. }
  518. static int
  519. pthread_setspecific(pthread_key_t key, void *value)
  520. {
  521. return TlsSetValue(key, value) ? 0 : 1;
  522. }
  523. static void *
  524. pthread_getspecific(pthread_key_t key)
  525. {
  526. return TlsGetValue(key);
  527. }
  528. #if defined(__MINGW32__)
  529. /* Enable unused function warning again */
  530. #pragma GCC diagnostic pop
  531. #endif
  532. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  533. #else
  534. static pthread_mutexattr_t pthread_mutex_attr;
  535. #endif /* _WIN32 */
  536. #define PASSWORDS_FILE_NAME ".htpasswd"
  537. #define CGI_ENVIRONMENT_SIZE (4096)
  538. #define MAX_CGI_ENVIR_VARS (256)
  539. #define MG_BUF_LEN (8192)
  540. #ifndef MAX_REQUEST_SIZE
  541. #define MAX_REQUEST_SIZE (16384)
  542. #endif
  543. mg_static_assert(MAX_REQUEST_SIZE >= 256,
  544. "request size length must be a positive number");
  545. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  546. #if defined(_WIN32_WCE)
  547. /* Create substitutes for POSIX functions in Win32. */
  548. #if defined(__MINGW32__)
  549. /* Show no warning in case system functions are not used. */
  550. #pragma GCC diagnostic push
  551. #pragma GCC diagnostic ignored "-Wunused-function"
  552. #endif
  553. static time_t
  554. time(time_t *ptime)
  555. {
  556. time_t t;
  557. SYSTEMTIME st;
  558. FILETIME ft;
  559. GetSystemTime(&st);
  560. SystemTimeToFileTime(&st, &ft);
  561. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  562. if (ptime != NULL) {
  563. *ptime = t;
  564. }
  565. return t;
  566. }
  567. static struct tm *
  568. localtime_s(const time_t *ptime, struct tm *ptm)
  569. {
  570. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  571. FILETIME ft, lft;
  572. SYSTEMTIME st;
  573. TIME_ZONE_INFORMATION tzinfo;
  574. if (ptm == NULL) {
  575. return NULL;
  576. }
  577. *(int64_t *)&ft = t;
  578. FileTimeToLocalFileTime(&ft, &lft);
  579. FileTimeToSystemTime(&lft, &st);
  580. ptm->tm_year = st.wYear - 1900;
  581. ptm->tm_mon = st.wMonth - 1;
  582. ptm->tm_wday = st.wDayOfWeek;
  583. ptm->tm_mday = st.wDay;
  584. ptm->tm_hour = st.wHour;
  585. ptm->tm_min = st.wMinute;
  586. ptm->tm_sec = st.wSecond;
  587. ptm->tm_yday = 0; /* hope nobody uses this */
  588. ptm->tm_isdst =
  589. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  590. return ptm;
  591. }
  592. static struct tm *
  593. gmtime_s(const time_t *ptime, struct tm *ptm)
  594. {
  595. /* FIXME(lsm): fix this. */
  596. return localtime_s(ptime, ptm);
  597. }
  598. static int mg_atomic_inc(volatile int *addr);
  599. static struct tm tm_array[MAX_WORKER_THREADS];
  600. static int tm_index = 0;
  601. static struct tm *
  602. localtime(const time_t *ptime)
  603. {
  604. int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0]));
  605. return localtime_s(ptime, tm_array + i);
  606. }
  607. static struct tm *
  608. gmtime(const time_t *ptime)
  609. {
  610. int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  611. return gmtime_s(ptime, tm_array + i);
  612. }
  613. static size_t
  614. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  615. {
  616. /* TODO: (void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  617. * for WinCE"); */
  618. return 0;
  619. }
  620. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  621. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  622. #define remove(f) mg_remove(NULL, f)
  623. static int
  624. rename(const char *a, const char *b)
  625. {
  626. wchar_t wa[PATH_MAX];
  627. wchar_t wb[PATH_MAX];
  628. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  629. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  630. return MoveFileW(wa, wb) ? 0 : -1;
  631. }
  632. struct stat {
  633. int64_t st_size;
  634. time_t st_mtime;
  635. };
  636. static int
  637. stat(const char *name, struct stat *st)
  638. {
  639. wchar_t wbuf[PATH_MAX];
  640. WIN32_FILE_ATTRIBUTE_DATA attr;
  641. time_t creation_time, write_time;
  642. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  643. memset(&attr, 0, sizeof(attr));
  644. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  645. st->st_size =
  646. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  647. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  648. attr.ftLastWriteTime.dwHighDateTime);
  649. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  650. attr.ftCreationTime.dwHighDateTime);
  651. if (creation_time > write_time) {
  652. st->st_mtime = creation_time;
  653. } else {
  654. st->st_mtime = write_time;
  655. }
  656. return 0;
  657. }
  658. #define access(x, a) 1 /* not required anyway */
  659. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  660. /* Values from errno.h in Windows SDK (Visual Studio). */
  661. #define EEXIST 17
  662. #define EACCES 13
  663. #define ENOENT 2
  664. #if defined(__MINGW32__)
  665. /* Enable unused function warning again */
  666. #pragma GCC diagnostic pop
  667. #endif
  668. #endif /* defined(_WIN32_WCE) */
  669. static int
  670. mg_atomic_inc(volatile int *addr)
  671. {
  672. int ret;
  673. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  674. /* Depending on the SDK, this function uses either
  675. * (volatile unsigned int *) or (volatile LONG *),
  676. * so whatever you use, the other SDK is likely to raise a warning. */
  677. ret = InterlockedIncrement((volatile long *)addr);
  678. #elif defined(__GNUC__) \
  679. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  680. ret = __sync_add_and_fetch(addr, 1);
  681. #else
  682. ret = (++(*addr));
  683. #endif
  684. return ret;
  685. }
  686. static int
  687. mg_atomic_dec(volatile int *addr)
  688. {
  689. int ret;
  690. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  691. /* Depending on the SDK, this function uses either
  692. * (volatile unsigned int *) or (volatile LONG *),
  693. * so whatever you use, the other SDK is likely to raise a warning. */
  694. ret = InterlockedDecrement((volatile long *)addr);
  695. #elif defined(__GNUC__) \
  696. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  697. ret = __sync_sub_and_fetch(addr, 1);
  698. #else
  699. ret = (--(*addr));
  700. #endif
  701. return ret;
  702. }
  703. #if defined(MEMORY_DEBUGGING)
  704. static unsigned long mg_memory_debug_blockCount = 0;
  705. static unsigned long mg_memory_debug_totalMemUsed = 0;
  706. static void *
  707. mg_malloc_ex(size_t size, const char *file, unsigned line)
  708. {
  709. void *data = malloc(size + sizeof(size_t));
  710. void *memory = 0;
  711. char mallocStr[256];
  712. if (data) {
  713. *(size_t *)data = size;
  714. mg_memory_debug_totalMemUsed += size;
  715. mg_memory_debug_blockCount++;
  716. memory = (void *)(((char *)data) + sizeof(size_t));
  717. }
  718. sprintf(mallocStr,
  719. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  720. memory,
  721. (unsigned long)size,
  722. mg_memory_debug_totalMemUsed,
  723. mg_memory_debug_blockCount,
  724. file,
  725. line);
  726. #if defined(_WIN32)
  727. OutputDebugStringA(mallocStr);
  728. #else
  729. DEBUG_TRACE("%s", mallocStr);
  730. #endif
  731. return memory;
  732. }
  733. static void *
  734. mg_calloc_ex(size_t count, size_t size, const char *file, unsigned line)
  735. {
  736. void *data = mg_malloc_ex(size * count, file, line);
  737. if (data) {
  738. memset(data, 0, size * count);
  739. }
  740. return data;
  741. }
  742. static void
  743. mg_free_ex(void *memory, const char *file, unsigned line)
  744. {
  745. char mallocStr[256];
  746. void *data = (void *)(((char *)memory) - sizeof(size_t));
  747. size_t size;
  748. if (memory) {
  749. size = *(size_t *)data;
  750. mg_memory_debug_totalMemUsed -= size;
  751. mg_memory_debug_blockCount--;
  752. sprintf(mallocStr,
  753. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  754. memory,
  755. (unsigned long)size,
  756. mg_memory_debug_totalMemUsed,
  757. mg_memory_debug_blockCount,
  758. file,
  759. line);
  760. #if defined(_WIN32)
  761. OutputDebugStringA(mallocStr);
  762. #else
  763. DEBUG_TRACE("%s", mallocStr);
  764. #endif
  765. free(data);
  766. }
  767. }
  768. static void *
  769. mg_realloc_ex(void *memory, size_t newsize, const char *file, unsigned line)
  770. {
  771. char mallocStr[256];
  772. void *data;
  773. void *_realloc;
  774. size_t oldsize;
  775. if (newsize) {
  776. if (memory) {
  777. data = (void *)(((char *)memory) - sizeof(size_t));
  778. oldsize = *(size_t *)data;
  779. _realloc = realloc(data, newsize + sizeof(size_t));
  780. if (_realloc) {
  781. data = _realloc;
  782. mg_memory_debug_totalMemUsed -= oldsize;
  783. sprintf(mallocStr,
  784. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  785. memory,
  786. (unsigned long)oldsize,
  787. mg_memory_debug_totalMemUsed,
  788. mg_memory_debug_blockCount,
  789. file,
  790. line);
  791. #if defined(_WIN32)
  792. OutputDebugStringA(mallocStr);
  793. #else
  794. DEBUG_TRACE("%s", mallocStr);
  795. #endif
  796. mg_memory_debug_totalMemUsed += newsize;
  797. sprintf(mallocStr,
  798. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  799. memory,
  800. (unsigned long)newsize,
  801. mg_memory_debug_totalMemUsed,
  802. mg_memory_debug_blockCount,
  803. file,
  804. line);
  805. #if defined(_WIN32)
  806. OutputDebugStringA(mallocStr);
  807. #else
  808. DEBUG_TRACE("%s", mallocStr);
  809. #endif
  810. *(size_t *)data = newsize;
  811. data = (void *)(((char *)data) + sizeof(size_t));
  812. } else {
  813. #if defined(_WIN32)
  814. OutputDebugStringA("MEM: realloc failed\n");
  815. #else
  816. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  817. #endif
  818. return _realloc;
  819. }
  820. } else {
  821. data = mg_malloc_ex(newsize, file, line);
  822. }
  823. } else {
  824. data = 0;
  825. mg_free_ex(memory, file, line);
  826. }
  827. return data;
  828. }
  829. #define mg_malloc(a) mg_malloc_ex(a, __FILE__, __LINE__)
  830. #define mg_calloc(a, b) mg_calloc_ex(a, b, __FILE__, __LINE__)
  831. #define mg_realloc(a, b) mg_realloc_ex(a, b, __FILE__, __LINE__)
  832. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  833. #else
  834. static __inline void *
  835. mg_malloc(size_t a)
  836. {
  837. return malloc(a);
  838. }
  839. static __inline void *
  840. mg_calloc(size_t a, size_t b)
  841. {
  842. return calloc(a, b);
  843. }
  844. static __inline void *
  845. mg_realloc(void *a, size_t b)
  846. {
  847. return realloc(a, b);
  848. }
  849. static __inline void
  850. mg_free(void *a)
  851. {
  852. free(a);
  853. }
  854. #endif
  855. static void mg_vsnprintf(const struct mg_connection *conn,
  856. int *truncated,
  857. char *buf,
  858. size_t buflen,
  859. const char *fmt,
  860. va_list ap);
  861. static void mg_snprintf(const struct mg_connection *conn,
  862. int *truncated,
  863. char *buf,
  864. size_t buflen,
  865. PRINTF_FORMAT_STRING(const char *fmt),
  866. ...) PRINTF_ARGS(5, 6);
  867. /* This following lines are just meant as a reminder to use the mg-functions
  868. * for memory management */
  869. #ifdef malloc
  870. #undef malloc
  871. #endif
  872. #ifdef calloc
  873. #undef calloc
  874. #endif
  875. #ifdef realloc
  876. #undef realloc
  877. #endif
  878. #ifdef free
  879. #undef free
  880. #endif
  881. #ifdef snprintf
  882. #undef snprintf
  883. #endif
  884. #ifdef vsnprintf
  885. #undef vsnprintf
  886. #endif
  887. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  888. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  889. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  890. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  891. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  892. #ifdef _WIN32 /* vsnprintf must not be used in any system, * \ \ \ \
  893. * but this define only works well for Windows. */
  894. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  895. #endif
  896. static pthread_key_t sTlsKey; /* Thread local storage index */
  897. static int sTlsInit = 0;
  898. static int thread_idx_max = 0;
  899. struct mg_workerTLS {
  900. int is_master;
  901. unsigned long thread_idx;
  902. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  903. HANDLE pthread_cond_helper_mutex;
  904. struct mg_workerTLS *next_waiting_thread;
  905. #endif
  906. };
  907. #if defined(__GNUC__) || defined(__MINGW32__)
  908. /* Show no warning in case system functions are not used. */
  909. #pragma GCC diagnostic push
  910. #pragma GCC diagnostic ignored "-Wunused-function"
  911. #endif
  912. #if defined(__clang__)
  913. /* Show no warning in case system functions are not used. */
  914. #pragma clang diagnostic push
  915. #pragma clang diagnostic ignored "-Wunused-function"
  916. #endif
  917. /* Get a unique thread ID as unsigned long, independent from the data type
  918. * of thread IDs defined by the operating system API.
  919. * If two calls to mg_current_thread_id return the same value, they calls
  920. * are done from the same thread. If they return different values, they are
  921. * done from different threads. (Provided this function is used in the same
  922. * process context and threads are not repeatedly created and deleted, but
  923. * CivetWeb does not do that).
  924. * This function must match the signature required for SSL id callbacks:
  925. * CRYPTO_set_id_callback
  926. */
  927. static unsigned long
  928. mg_current_thread_id(void)
  929. {
  930. #ifdef _WIN32
  931. return GetCurrentThreadId();
  932. #else
  933. #ifdef __clang__
  934. #pragma clang diagnostic push
  935. #pragma clang diagnostic ignored "-Wunreachable-code"
  936. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  937. * or not, so one of the two conditions will be unreachable by construction.
  938. * Unfortunately the C standard does not define a way to check this at
  939. * compile time, since the #if preprocessor conditions can not use the sizeof
  940. * operator as an argument. */
  941. #endif
  942. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  943. /* This is the problematic case for CRYPTO_set_id_callback:
  944. * The OS pthread_t can not be cast to unsigned long. */
  945. struct mg_workerTLS *tls =
  946. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  947. if (tls == NULL) {
  948. /* SSL called from an unknown thread: Create some thread index.
  949. */
  950. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  951. tls->is_master = -2; /* -2 means "3rd party thread" */
  952. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  953. pthread_setspecific(sTlsKey, tls);
  954. }
  955. return tls->thread_idx;
  956. } else {
  957. /* pthread_t may be any data type, so a simple cast to unsigned long
  958. * can rise a warning/error, depending on the platform.
  959. * Here memcpy is used as an anything-to-anything cast. */
  960. unsigned long ret = 0;
  961. pthread_t t = pthread_self();
  962. memcpy(&ret, &t, sizeof(pthread_t));
  963. return ret;
  964. }
  965. #ifdef __clang__
  966. #pragma clang diagnostic pop
  967. #endif
  968. #endif
  969. }
  970. static uint64_t
  971. mg_get_current_time_ns()
  972. {
  973. struct timespec tsnow;
  974. clock_gettime(CLOCK_REALTIME, &tsnow);
  975. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  976. }
  977. #if defined(__GNUC__)
  978. /* Show no warning in case system functions are not used. */
  979. #pragma GCC diagnostic pop
  980. #endif
  981. #if defined(__clang__)
  982. /* Show no warning in case system functions are not used. */
  983. #pragma clang diagnostic pop
  984. #endif
  985. #if !defined(DEBUG_TRACE)
  986. #if defined(DEBUG)
  987. static void DEBUG_TRACE_FUNC(const char *func,
  988. unsigned line,
  989. PRINTF_FORMAT_STRING(const char *fmt),
  990. ...) PRINTF_ARGS(3, 4);
  991. static void
  992. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  993. {
  994. va_list args;
  995. uint64_t nsnow;
  996. static uint64_t nslast;
  997. struct timespec tsnow;
  998. /* Get some operating system independent thread id */
  999. unsigned long thread_id = mg_current_thread_id();
  1000. clock_gettime(CLOCK_REALTIME, &tsnow);
  1001. nsnow = ((uint64_t)tsnow.tv_sec) * ((uint64_t)1000000000)
  1002. + ((uint64_t)tsnow.tv_nsec);
  1003. if (!nslast) {
  1004. nslast = nsnow;
  1005. }
  1006. flockfile(stdout);
  1007. printf("*** %lu.%09lu %12" INT64_FMT " %lu %s:%u: ",
  1008. (unsigned long)tsnow.tv_sec,
  1009. (unsigned long)tsnow.tv_nsec,
  1010. nsnow - nslast,
  1011. thread_id,
  1012. func,
  1013. line);
  1014. va_start(args, fmt);
  1015. vprintf(fmt, args);
  1016. va_end(args);
  1017. putchar('\n');
  1018. fflush(stdout);
  1019. funlockfile(stdout);
  1020. nslast = nsnow;
  1021. }
  1022. #define DEBUG_TRACE(fmt, ...) \
  1023. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  1024. #else
  1025. #define DEBUG_TRACE(fmt, ...) \
  1026. do { \
  1027. } while (0)
  1028. #endif /* DEBUG */
  1029. #endif /* DEBUG_TRACE */
  1030. #define MD5_STATIC static
  1031. #include "md5.inl"
  1032. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1033. #ifdef NO_SOCKLEN_T
  1034. typedef int socklen_t;
  1035. #endif /* NO_SOCKLEN_T */
  1036. #define _DARWIN_UNLIMITED_SELECT
  1037. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1038. #if !defined(MSG_NOSIGNAL)
  1039. #define MSG_NOSIGNAL (0)
  1040. #endif
  1041. #if !defined(SOMAXCONN)
  1042. #define SOMAXCONN (100)
  1043. #endif
  1044. /* Size of the accepted socket queue */
  1045. #if !defined(MGSQLEN)
  1046. #define MGSQLEN (20)
  1047. #endif
  1048. #if defined(NO_SSL)
  1049. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1050. typedef struct SSL_CTX SSL_CTX;
  1051. #else
  1052. #if defined(NO_SSL_DL)
  1053. #include <openssl/ssl.h>
  1054. #include <openssl/err.h>
  1055. #include <openssl/crypto.h>
  1056. #include <openssl/x509.h>
  1057. #include <openssl/pem.h>
  1058. #include <openssl/engine.h>
  1059. #include <openssl/conf.h>
  1060. #include <openssl/dh.h>
  1061. #include <openssl/bn.h>
  1062. #include <openssl/opensslv.h>
  1063. #else
  1064. /* SSL loaded dynamically from DLL.
  1065. * I put the prototypes here to be independent from OpenSSL source
  1066. * installation. */
  1067. typedef struct ssl_st SSL;
  1068. typedef struct ssl_method_st SSL_METHOD;
  1069. typedef struct ssl_ctx_st SSL_CTX;
  1070. typedef struct x509_store_ctx_st X509_STORE_CTX;
  1071. typedef struct x509_name X509_NAME;
  1072. typedef struct asn1_integer ASN1_INTEGER;
  1073. typedef struct bignum BIGNUM;
  1074. typedef struct ossl_init_settings_st OPENSSL_INIT_SETTINGS;
  1075. typedef struct evp_md EVP_MD;
  1076. typedef struct x509 X509;
  1077. #define SSL_CTRL_OPTIONS (32)
  1078. #define SSL_CTRL_CLEAR_OPTIONS (77)
  1079. #define SSL_CTRL_SET_ECDH_AUTO (94)
  1080. #define OPENSSL_INIT_NO_LOAD_SSL_STRINGS 0x00100000L
  1081. #define OPENSSL_INIT_LOAD_SSL_STRINGS 0x00200000L
  1082. #define OPENSSL_INIT_LOAD_CRYPTO_STRINGS 0x00000002L
  1083. #define SSL_VERIFY_NONE (0)
  1084. #define SSL_VERIFY_PEER (1)
  1085. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  1086. #define SSL_VERIFY_CLIENT_ONCE (4)
  1087. #define SSL_OP_ALL ((long)(0x80000BFFUL))
  1088. #define SSL_OP_NO_SSLv2 (0x01000000L)
  1089. #define SSL_OP_NO_SSLv3 (0x02000000L)
  1090. #define SSL_OP_NO_TLSv1 (0x04000000L)
  1091. #define SSL_OP_NO_TLSv1_2 (0x08000000L)
  1092. #define SSL_OP_NO_TLSv1_1 (0x10000000L)
  1093. #define SSL_OP_SINGLE_DH_USE (0x00100000L)
  1094. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000L)
  1095. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000L)
  1096. #define SSL_ERROR_NONE (0)
  1097. #define SSL_ERROR_SSL (1)
  1098. #define SSL_ERROR_WANT_READ (2)
  1099. #define SSL_ERROR_WANT_WRITE (3)
  1100. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  1101. #define SSL_ERROR_SYSCALL (5) /* see errno */
  1102. #define SSL_ERROR_ZERO_RETURN (6)
  1103. #define SSL_ERROR_WANT_CONNECT (7)
  1104. #define SSL_ERROR_WANT_ACCEPT (8)
  1105. struct ssl_func {
  1106. const char *name; /* SSL function name */
  1107. void (*ptr)(void); /* Function pointer */
  1108. };
  1109. #ifdef OPENSSL_API_1_1
  1110. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1111. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1112. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1113. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1114. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1115. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1116. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1117. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  1118. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  1119. #define TLS_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  1120. #define OPENSSL_init_ssl \
  1121. (*(int (*)(uint64_t opts, \
  1122. const OPENSSL_INIT_SETTINGS *settings))ssl_sw[10].ptr)
  1123. #define SSL_CTX_use_PrivateKey_file \
  1124. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1125. #define SSL_CTX_use_certificate_file \
  1126. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1127. #define SSL_CTX_set_default_passwd_cb \
  1128. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1129. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1130. #define SSL_CTX_use_certificate_chain_file \
  1131. (*(int (*)(SSL_CTX *, const char *))ssl_sw[15].ptr)
  1132. #define TLS_client_method (*(SSL_METHOD * (*)(void))ssl_sw[16].ptr)
  1133. #define SSL_pending (*(int (*)(SSL *))ssl_sw[17].ptr)
  1134. #define SSL_CTX_set_verify \
  1135. (*(void (*)(SSL_CTX *, \
  1136. int, \
  1137. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[18].ptr)
  1138. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[19].ptr)
  1139. #define SSL_CTX_load_verify_locations \
  1140. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[20].ptr)
  1141. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[21].ptr)
  1142. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[22].ptr)
  1143. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[23].ptr)
  1144. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[24].ptr)
  1145. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[25].ptr)
  1146. #define SSL_CIPHER_get_name \
  1147. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[26].ptr)
  1148. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[27].ptr)
  1149. #define SSL_CTX_set_session_id_context \
  1150. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[28].ptr)
  1151. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[29].ptr)
  1152. #define SSL_CTX_set_cipher_list \
  1153. (*(int (*)(SSL_CTX *, const char *))ssl_sw[30].ptr)
  1154. #define SSL_CTX_set_options \
  1155. (*(unsigned long (*)(SSL_CTX *, unsigned long))ssl_sw[31].ptr)
  1156. #define SSL_CTX_clear_options(ctx, op) \
  1157. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1158. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1159. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1160. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1161. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1162. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[0].ptr)
  1163. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[1].ptr)
  1164. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[2].ptr)
  1165. #define CONF_modules_unload (*(void (*)(int))crypto_sw[3].ptr)
  1166. #define X509_free (*(void (*)(X509 *))crypto_sw[4].ptr)
  1167. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[5].ptr)
  1168. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[6].ptr)
  1169. #define X509_NAME_oneline \
  1170. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[7].ptr)
  1171. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[8].ptr)
  1172. #define EVP_get_digestbyname \
  1173. (*(const EVP_MD *(*)(const char *))crypto_sw[9].ptr)
  1174. #define EVP_Digest \
  1175. (*(int (*)( \
  1176. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1177. crypto_sw[10].ptr)
  1178. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[11].ptr)
  1179. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[12].ptr)
  1180. #define ASN1_INTEGER_to_BN \
  1181. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn))crypto_sw[13].ptr)
  1182. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[14].ptr)
  1183. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[15].ptr)
  1184. #define OPENSSL_free(a) CRYPTO_free(a)
  1185. /* set_ssl_option() function updates this array.
  1186. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1187. * of respective functions. The macros above (like SSL_connect()) are really
  1188. * just calling these functions indirectly via the pointer. */
  1189. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1190. {"SSL_accept", NULL},
  1191. {"SSL_connect", NULL},
  1192. {"SSL_read", NULL},
  1193. {"SSL_write", NULL},
  1194. {"SSL_get_error", NULL},
  1195. {"SSL_set_fd", NULL},
  1196. {"SSL_new", NULL},
  1197. {"SSL_CTX_new", NULL},
  1198. {"TLS_server_method", NULL},
  1199. {"OPENSSL_init_ssl", NULL},
  1200. {"SSL_CTX_use_PrivateKey_file", NULL},
  1201. {"SSL_CTX_use_certificate_file", NULL},
  1202. {"SSL_CTX_set_default_passwd_cb", NULL},
  1203. {"SSL_CTX_free", NULL},
  1204. {"SSL_CTX_use_certificate_chain_file", NULL},
  1205. {"TLS_client_method", NULL},
  1206. {"SSL_pending", NULL},
  1207. {"SSL_CTX_set_verify", NULL},
  1208. {"SSL_shutdown", NULL},
  1209. {"SSL_CTX_load_verify_locations", NULL},
  1210. {"SSL_CTX_set_default_verify_paths", NULL},
  1211. {"SSL_CTX_set_verify_depth", NULL},
  1212. {"SSL_get_peer_certificate", NULL},
  1213. {"SSL_get_version", NULL},
  1214. {"SSL_get_current_cipher", NULL},
  1215. {"SSL_CIPHER_get_name", NULL},
  1216. {"SSL_CTX_check_private_key", NULL},
  1217. {"SSL_CTX_set_session_id_context", NULL},
  1218. {"SSL_CTX_ctrl", NULL},
  1219. {"SSL_CTX_set_cipher_list", NULL},
  1220. {"SSL_CTX_set_options", NULL},
  1221. {NULL, NULL}};
  1222. /* Similar array as ssl_sw. These functions could be located in different
  1223. * lib. */
  1224. static struct ssl_func crypto_sw[] = {{"ERR_get_error", NULL},
  1225. {"ERR_error_string", NULL},
  1226. {"ERR_remove_state", NULL},
  1227. {"CONF_modules_unload", NULL},
  1228. {"X509_free", NULL},
  1229. {"X509_get_subject_name", NULL},
  1230. {"X509_get_issuer_name", NULL},
  1231. {"X509_NAME_oneline", NULL},
  1232. {"X509_get_serialNumber", NULL},
  1233. {"EVP_get_digestbyname", NULL},
  1234. {"EVP_Digest", NULL},
  1235. {"i2d_X509", NULL},
  1236. {"BN_bn2hex", NULL},
  1237. {"ASN1_INTEGER_to_BN", NULL},
  1238. {"BN_free", NULL},
  1239. {"CRYPTO_free", NULL},
  1240. {NULL, NULL}};
  1241. #else
  1242. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1243. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1244. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1245. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1246. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1247. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1248. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1249. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  1250. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  1251. #define SSLv23_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  1252. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  1253. #define SSL_CTX_use_PrivateKey_file \
  1254. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1255. #define SSL_CTX_use_certificate_file \
  1256. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1257. #define SSL_CTX_set_default_passwd_cb \
  1258. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1259. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1260. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  1261. #define SSL_CTX_use_certificate_chain_file \
  1262. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  1263. #define SSLv23_client_method (*(SSL_METHOD * (*)(void))ssl_sw[17].ptr)
  1264. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  1265. #define SSL_CTX_set_verify \
  1266. (*(void (*)(SSL_CTX *, \
  1267. int, \
  1268. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19].ptr)
  1269. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  1270. #define SSL_CTX_load_verify_locations \
  1271. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  1272. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  1273. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  1274. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[24].ptr)
  1275. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  1276. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[26].ptr)
  1277. #define SSL_CIPHER_get_name \
  1278. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  1279. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  1280. #define SSL_CTX_set_session_id_context \
  1281. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  1282. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  1283. #define SSL_CTX_set_cipher_list \
  1284. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  1285. #define SSL_CTX_set_options(ctx, op) \
  1286. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  1287. #define SSL_CTX_clear_options(ctx, op) \
  1288. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1289. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1290. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1291. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1292. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1293. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  1294. #define CRYPTO_set_locking_callback \
  1295. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  1296. #define CRYPTO_set_id_callback \
  1297. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  1298. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  1299. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  1300. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  1301. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  1302. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  1303. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  1304. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  1305. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  1306. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  1307. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[12].ptr)
  1308. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[13].ptr)
  1309. #define X509_NAME_oneline \
  1310. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  1311. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[15].ptr)
  1312. #define i2c_ASN1_INTEGER \
  1313. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  1314. #define EVP_get_digestbyname \
  1315. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1316. #define EVP_Digest \
  1317. (*(int (*)( \
  1318. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1319. crypto_sw[18].ptr)
  1320. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1321. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[20].ptr)
  1322. #define ASN1_INTEGER_to_BN \
  1323. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn))crypto_sw[21].ptr)
  1324. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[22].ptr)
  1325. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[23].ptr)
  1326. #define OPENSSL_free(a) CRYPTO_free(a)
  1327. /* set_ssl_option() function updates this array.
  1328. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1329. * of respective functions. The macros above (like SSL_connect()) are really
  1330. * just calling these functions indirectly via the pointer. */
  1331. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1332. {"SSL_accept", NULL},
  1333. {"SSL_connect", NULL},
  1334. {"SSL_read", NULL},
  1335. {"SSL_write", NULL},
  1336. {"SSL_get_error", NULL},
  1337. {"SSL_set_fd", NULL},
  1338. {"SSL_new", NULL},
  1339. {"SSL_CTX_new", NULL},
  1340. {"SSLv23_server_method", NULL},
  1341. {"SSL_library_init", NULL},
  1342. {"SSL_CTX_use_PrivateKey_file", NULL},
  1343. {"SSL_CTX_use_certificate_file", NULL},
  1344. {"SSL_CTX_set_default_passwd_cb", NULL},
  1345. {"SSL_CTX_free", NULL},
  1346. {"SSL_load_error_strings", NULL},
  1347. {"SSL_CTX_use_certificate_chain_file", NULL},
  1348. {"SSLv23_client_method", NULL},
  1349. {"SSL_pending", NULL},
  1350. {"SSL_CTX_set_verify", NULL},
  1351. {"SSL_shutdown", NULL},
  1352. {"SSL_CTX_load_verify_locations", NULL},
  1353. {"SSL_CTX_set_default_verify_paths", NULL},
  1354. {"SSL_CTX_set_verify_depth", NULL},
  1355. {"SSL_get_peer_certificate", NULL},
  1356. {"SSL_get_version", NULL},
  1357. {"SSL_get_current_cipher", NULL},
  1358. {"SSL_CIPHER_get_name", NULL},
  1359. {"SSL_CTX_check_private_key", NULL},
  1360. {"SSL_CTX_set_session_id_context", NULL},
  1361. {"SSL_CTX_ctrl", NULL},
  1362. {"SSL_CTX_set_cipher_list", NULL},
  1363. {NULL, NULL}};
  1364. /* Similar array as ssl_sw. These functions could be located in different
  1365. * lib. */
  1366. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  1367. {"CRYPTO_set_locking_callback", NULL},
  1368. {"CRYPTO_set_id_callback", NULL},
  1369. {"ERR_get_error", NULL},
  1370. {"ERR_error_string", NULL},
  1371. {"ERR_remove_state", NULL},
  1372. {"ERR_free_strings", NULL},
  1373. {"ENGINE_cleanup", NULL},
  1374. {"CONF_modules_unload", NULL},
  1375. {"CRYPTO_cleanup_all_ex_data", NULL},
  1376. {"EVP_cleanup", NULL},
  1377. {"X509_free", NULL},
  1378. {"X509_get_subject_name", NULL},
  1379. {"X509_get_issuer_name", NULL},
  1380. {"X509_NAME_oneline", NULL},
  1381. {"X509_get_serialNumber", NULL},
  1382. {"i2c_ASN1_INTEGER", NULL},
  1383. {"EVP_get_digestbyname", NULL},
  1384. {"EVP_Digest", NULL},
  1385. {"i2d_X509", NULL},
  1386. {"BN_bn2hex", NULL},
  1387. {"ASN1_INTEGER_to_BN", NULL},
  1388. {"BN_free", NULL},
  1389. {"CRYPTO_free", NULL},
  1390. {NULL, NULL}};
  1391. #endif /* OPENSSL_API_1_1 */
  1392. #endif /* NO_SSL_DL */
  1393. #endif /* NO_SSL */
  1394. #if !defined(NO_CACHING)
  1395. static const char *month_names[] = {"Jan",
  1396. "Feb",
  1397. "Mar",
  1398. "Apr",
  1399. "May",
  1400. "Jun",
  1401. "Jul",
  1402. "Aug",
  1403. "Sep",
  1404. "Oct",
  1405. "Nov",
  1406. "Dec"};
  1407. #endif /* !NO_CACHING */
  1408. /* Unified socket address. For IPv6 support, add IPv6 address structure in the
  1409. * union u. */
  1410. union usa {
  1411. struct sockaddr sa;
  1412. struct sockaddr_in sin;
  1413. #if defined(USE_IPV6)
  1414. struct sockaddr_in6 sin6;
  1415. #endif
  1416. };
  1417. /* Describes a string (chunk of memory). */
  1418. struct vec {
  1419. const char *ptr;
  1420. size_t len;
  1421. };
  1422. struct mg_file_stat {
  1423. /* File properties filled by mg_stat: */
  1424. uint64_t size;
  1425. time_t last_modified;
  1426. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1427. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1428. * case we need a "Content-Eencoding: gzip" header */
  1429. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1430. };
  1431. struct mg_file_in_memory {
  1432. char *p;
  1433. uint32_t pos;
  1434. char mode;
  1435. };
  1436. struct mg_file_access {
  1437. /* File properties filled by mg_fopen: */
  1438. FILE *fp;
  1439. /* TODO (low): Replace "membuf" implementation by a "file in memory"
  1440. * support library. Use some struct mg_file_in_memory *mf; instead of
  1441. * membuf char pointer. */
  1442. const char *membuf;
  1443. };
  1444. struct mg_file {
  1445. struct mg_file_stat stat;
  1446. struct mg_file_access access;
  1447. };
  1448. #define STRUCT_FILE_INITIALIZER \
  1449. { \
  1450. { \
  1451. (uint64_t)0, (time_t)0, 0, 0, 0 \
  1452. } \
  1453. , \
  1454. { \
  1455. (FILE *) NULL, (const char *)NULL \
  1456. } \
  1457. }
  1458. /* Describes listening socket, or socket which was accept()-ed by the master
  1459. * thread and queued for future handling by the worker thread. */
  1460. struct socket {
  1461. SOCKET sock; /* Listening socket */
  1462. union usa lsa; /* Local socket address */
  1463. union usa rsa; /* Remote socket address */
  1464. unsigned char is_ssl; /* Is port SSL-ed */
  1465. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1466. * port */
  1467. unsigned char in_use; /* Is valid */
  1468. };
  1469. /* NOTE(lsm): this enum shoulds be in sync with the config_options below. */
  1470. enum {
  1471. CGI_EXTENSIONS,
  1472. CGI_ENVIRONMENT,
  1473. PUT_DELETE_PASSWORDS_FILE,
  1474. CGI_INTERPRETER,
  1475. PROTECT_URI,
  1476. AUTHENTICATION_DOMAIN,
  1477. ENABLE_AUTH_DOMAIN_CHECK,
  1478. SSI_EXTENSIONS,
  1479. THROTTLE,
  1480. ACCESS_LOG_FILE,
  1481. ENABLE_DIRECTORY_LISTING,
  1482. ERROR_LOG_FILE,
  1483. GLOBAL_PASSWORDS_FILE,
  1484. INDEX_FILES,
  1485. ENABLE_KEEP_ALIVE,
  1486. ACCESS_CONTROL_LIST,
  1487. EXTRA_MIME_TYPES,
  1488. LISTENING_PORTS,
  1489. DOCUMENT_ROOT,
  1490. SSL_CERTIFICATE,
  1491. SSL_CERTIFICATE_CHAIN,
  1492. NUM_THREADS,
  1493. RUN_AS_USER,
  1494. REWRITE,
  1495. HIDE_FILES,
  1496. REQUEST_TIMEOUT,
  1497. KEEP_ALIVE_TIMEOUT,
  1498. LINGER_TIMEOUT,
  1499. SSL_DO_VERIFY_PEER,
  1500. SSL_CA_PATH,
  1501. SSL_CA_FILE,
  1502. SSL_VERIFY_DEPTH,
  1503. SSL_DEFAULT_VERIFY_PATHS,
  1504. SSL_CIPHER_LIST,
  1505. SSL_PROTOCOL_VERSION,
  1506. SSL_SHORT_TRUST,
  1507. #if defined(USE_WEBSOCKET)
  1508. WEBSOCKET_TIMEOUT,
  1509. #endif
  1510. DECODE_URL,
  1511. #if defined(USE_LUA)
  1512. LUA_PRELOAD_FILE,
  1513. LUA_SCRIPT_EXTENSIONS,
  1514. LUA_SERVER_PAGE_EXTENSIONS,
  1515. #endif
  1516. #if defined(USE_DUKTAPE)
  1517. DUKTAPE_SCRIPT_EXTENSIONS,
  1518. #endif
  1519. #if defined(USE_WEBSOCKET)
  1520. WEBSOCKET_ROOT,
  1521. #endif
  1522. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1523. LUA_WEBSOCKET_EXTENSIONS,
  1524. #endif
  1525. ACCESS_CONTROL_ALLOW_ORIGIN,
  1526. ERROR_PAGES,
  1527. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1528. * socket option typedef TCP_NODELAY. */
  1529. #if !defined(NO_CACHING)
  1530. STATIC_FILE_MAX_AGE,
  1531. #endif
  1532. #if defined(__linux__)
  1533. ALLOW_SENDFILE_CALL,
  1534. #endif
  1535. #if defined(_WIN32)
  1536. CASE_SENSITIVE_FILES,
  1537. #endif
  1538. #if defined(USE_LUA)
  1539. LUA_BACKGROUND_SCRIPT,
  1540. #endif
  1541. NUM_OPTIONS
  1542. };
  1543. /* Config option name, config types, default value */
  1544. static struct mg_option config_options[] = {
  1545. {"cgi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1546. {"cgi_environment", CONFIG_TYPE_STRING, NULL},
  1547. {"put_delete_auth_file", CONFIG_TYPE_FILE, NULL},
  1548. {"cgi_interpreter", CONFIG_TYPE_FILE, NULL},
  1549. {"protect_uri", CONFIG_TYPE_STRING, NULL},
  1550. {"authentication_domain", CONFIG_TYPE_STRING, "mydomain.com"},
  1551. {"enable_auth_domain_check", CONFIG_TYPE_BOOLEAN, "yes"},
  1552. {"ssi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1553. {"throttle", CONFIG_TYPE_STRING, NULL},
  1554. {"access_log_file", CONFIG_TYPE_FILE, NULL},
  1555. {"enable_directory_listing", CONFIG_TYPE_BOOLEAN, "yes"},
  1556. {"error_log_file", CONFIG_TYPE_FILE, NULL},
  1557. {"global_auth_file", CONFIG_TYPE_FILE, NULL},
  1558. {"index_files",
  1559. CONFIG_TYPE_STRING,
  1560. #ifdef USE_LUA
  1561. "index.xhtml,index.html,index.htm,index.lp,index.lsp,index.lua,index.cgi,"
  1562. "index.shtml,index.php"},
  1563. #else
  1564. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1565. #endif
  1566. {"enable_keep_alive", CONFIG_TYPE_BOOLEAN, "no"},
  1567. {"access_control_list", CONFIG_TYPE_STRING, NULL},
  1568. {"extra_mime_types", CONFIG_TYPE_STRING, NULL},
  1569. {"listening_ports", CONFIG_TYPE_STRING, "8080"},
  1570. {"document_root", CONFIG_TYPE_DIRECTORY, NULL},
  1571. {"ssl_certificate", CONFIG_TYPE_FILE, NULL},
  1572. {"ssl_certificate_chain", CONFIG_TYPE_FILE, NULL},
  1573. {"num_threads", CONFIG_TYPE_NUMBER, "50"},
  1574. {"run_as_user", CONFIG_TYPE_STRING, NULL},
  1575. {"url_rewrite_patterns", CONFIG_TYPE_STRING, NULL},
  1576. {"hide_files_patterns", CONFIG_TYPE_EXT_PATTERN, NULL},
  1577. {"request_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1578. {"keep_alive_timeout_ms", CONFIG_TYPE_NUMBER, "500"},
  1579. {"linger_timeout_ms", CONFIG_TYPE_NUMBER, NULL},
  1580. /* TODO(Feature): this is no longer a boolean, but yes/no/optional */
  1581. {"ssl_verify_peer", CONFIG_TYPE_BOOLEAN, "no"},
  1582. {"ssl_ca_path", CONFIG_TYPE_DIRECTORY, NULL},
  1583. {"ssl_ca_file", CONFIG_TYPE_FILE, NULL},
  1584. {"ssl_verify_depth", CONFIG_TYPE_NUMBER, "9"},
  1585. {"ssl_default_verify_paths", CONFIG_TYPE_BOOLEAN, "yes"},
  1586. {"ssl_cipher_list", CONFIG_TYPE_STRING, NULL},
  1587. {"ssl_protocol_version", CONFIG_TYPE_NUMBER, "0"},
  1588. {"ssl_short_trust", CONFIG_TYPE_BOOLEAN, "no"},
  1589. #if defined(USE_WEBSOCKET)
  1590. {"websocket_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1591. #endif
  1592. {"decode_url", CONFIG_TYPE_BOOLEAN, "yes"},
  1593. #if defined(USE_LUA)
  1594. {"lua_preload_file", CONFIG_TYPE_FILE, NULL},
  1595. {"lua_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1596. {"lua_server_page_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1597. #endif
  1598. #if defined(USE_DUKTAPE)
  1599. /* The support for duktape is still in alpha version state.
  1600. * The name of this config option might change. */
  1601. {"duktape_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1602. #endif
  1603. #if defined(USE_WEBSOCKET)
  1604. {"websocket_root", CONFIG_TYPE_DIRECTORY, NULL},
  1605. #endif
  1606. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1607. {"lua_websocket_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1608. #endif
  1609. {"access_control_allow_origin", CONFIG_TYPE_STRING, "*"},
  1610. {"error_pages", CONFIG_TYPE_DIRECTORY, NULL},
  1611. {"tcp_nodelay", CONFIG_TYPE_NUMBER, "0"},
  1612. #if !defined(NO_CACHING)
  1613. {"static_file_max_age", CONFIG_TYPE_NUMBER, "3600"},
  1614. #endif
  1615. #if defined(__linux__)
  1616. {"allow_sendfile_call", CONFIG_TYPE_BOOLEAN, "yes"},
  1617. #endif
  1618. #if defined(_WIN32)
  1619. {"case_sensitive", CONFIG_TYPE_BOOLEAN, "no"},
  1620. #endif
  1621. #if defined(USE_LUA)
  1622. {"lua_background_script", CONFIG_TYPE_FILE, NULL},
  1623. #endif
  1624. {NULL, CONFIG_TYPE_UNKNOWN, NULL}};
  1625. /* Check if the config_options and the corresponding enum have compatible
  1626. * sizes. */
  1627. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1628. == (NUM_OPTIONS + 1),
  1629. "config_options and enum not sync");
  1630. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1631. struct mg_handler_info {
  1632. /* Name/Pattern of the URI. */
  1633. char *uri;
  1634. size_t uri_len;
  1635. /* handler type */
  1636. int handler_type;
  1637. /* Handler for http/https or authorization requests. */
  1638. mg_request_handler handler;
  1639. /* Handler for ws/wss (websocket) requests. */
  1640. mg_websocket_connect_handler connect_handler;
  1641. mg_websocket_ready_handler ready_handler;
  1642. mg_websocket_data_handler data_handler;
  1643. mg_websocket_close_handler close_handler;
  1644. /* accepted subprotocols for ws/wss requests. */
  1645. struct mg_websocket_subprotocols *subprotocols;
  1646. /* Handler for authorization requests */
  1647. mg_authorization_handler auth_handler;
  1648. /* User supplied argument for the handler function. */
  1649. void *cbdata;
  1650. /* next handler in a linked list */
  1651. struct mg_handler_info *next;
  1652. };
  1653. struct mg_context {
  1654. volatile int stop_flag; /* Should we stop event loop */
  1655. SSL_CTX *ssl_ctx; /* SSL context */
  1656. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1657. struct mg_callbacks callbacks; /* User-defined callback function */
  1658. void *user_data; /* User-defined data */
  1659. int context_type; /* 1 = server context,
  1660. * 2 = ws/wss client context,
  1661. */
  1662. struct socket *listening_sockets;
  1663. struct pollfd *listening_socket_fds;
  1664. unsigned int num_listening_sockets;
  1665. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  1666. #ifdef ALTERNATIVE_QUEUE
  1667. struct socket *client_socks;
  1668. void **client_wait_events;
  1669. #else
  1670. struct socket queue[MGSQLEN]; /* Accepted sockets */
  1671. volatile int sq_head; /* Head of the socket queue */
  1672. volatile int sq_tail; /* Tail of the socket queue */
  1673. pthread_cond_t sq_full; /* Signaled when socket is produced */
  1674. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  1675. #endif
  1676. pthread_t masterthreadid; /* The master thread ID */
  1677. unsigned int
  1678. cfg_worker_threads; /* The number of configured worker threads. */
  1679. pthread_t *worker_threadids; /* The worker thread IDs */
  1680. struct mg_connection *worker_connections; /* The connection struct, pre-
  1681. * allocated for each worker */
  1682. time_t start_time; /* Server start time, used for authentication */
  1683. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1684. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  1685. unsigned long nonce_count; /* Used nonces, used for authentication */
  1686. char *systemName; /* What operating system is running */
  1687. /* linked list of uri handlers */
  1688. struct mg_handler_info *handlers;
  1689. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1690. /* linked list of shared lua websockets */
  1691. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1692. #endif
  1693. #if defined(USE_TIMERS)
  1694. struct ttimers *timers;
  1695. #endif
  1696. #if defined(USE_LUA)
  1697. void *lua_background_state;
  1698. #endif
  1699. };
  1700. struct mg_connection {
  1701. struct mg_request_info request_info;
  1702. struct mg_context *ctx;
  1703. SSL *ssl; /* SSL descriptor */
  1704. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  1705. struct socket client; /* Connected client */
  1706. time_t conn_birth_time; /* Time (wall clock) when connection was
  1707. * established */
  1708. struct timespec req_time; /* Time (since system start) when the request
  1709. * was received */
  1710. int64_t num_bytes_sent; /* Total bytes sent to client */
  1711. int64_t content_len; /* Content-Length header value */
  1712. int64_t consumed_content; /* How many bytes of content have been read */
  1713. int is_chunked; /* Transfer-Encoding is chunked: 0=no, 1=yes:
  1714. * data available, 2: all data read */
  1715. size_t chunk_remainder; /* Unread data from the last chunk */
  1716. char *buf; /* Buffer for received data */
  1717. char *path_info; /* PATH_INFO part of the URL */
  1718. int must_close; /* 1 if connection must be closed */
  1719. int in_error_handler; /* 1 if in handler for user defined error
  1720. * pages */
  1721. int handled_requests; /* Number of requests handled by this connection */
  1722. int buf_size; /* Buffer size */
  1723. int request_len; /* Size of the request + headers in a buffer */
  1724. int data_len; /* Total size of data in a buffer */
  1725. int status_code; /* HTTP reply status code, e.g. 200 */
  1726. int throttle; /* Throttling, bytes/sec. <= 0 means no
  1727. * throttle */
  1728. time_t last_throttle_time; /* Last time throttled data was sent */
  1729. int64_t last_throttle_bytes; /* Bytes sent this second */
  1730. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  1731. * atomic transmissions for websockets */
  1732. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1733. void *lua_websocket_state; /* Lua_State for a websocket connection */
  1734. #endif
  1735. int thread_index; /* Thread index within ctx */
  1736. };
  1737. /* Directory entry */
  1738. struct de {
  1739. struct mg_connection *conn;
  1740. char *file_name;
  1741. struct mg_file_stat file;
  1742. };
  1743. #if defined(USE_WEBSOCKET)
  1744. static int is_websocket_protocol(const struct mg_connection *conn);
  1745. #else
  1746. #define is_websocket_protocol(conn) (0)
  1747. #endif
  1748. #if !defined(NO_THREAD_NAME)
  1749. #if defined(_WIN32) && defined(_MSC_VER)
  1750. /* Set the thread name for debugging purposes in Visual Studio
  1751. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  1752. */
  1753. #pragma pack(push, 8)
  1754. typedef struct tagTHREADNAME_INFO {
  1755. DWORD dwType; /* Must be 0x1000. */
  1756. LPCSTR szName; /* Pointer to name (in user addr space). */
  1757. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  1758. DWORD dwFlags; /* Reserved for future use, must be zero. */
  1759. } THREADNAME_INFO;
  1760. #pragma pack(pop)
  1761. #elif defined(__linux__)
  1762. #include <sys/prctl.h>
  1763. #include <sys/sendfile.h>
  1764. #include <sys/eventfd.h>
  1765. #if defined(ALTERNATIVE_QUEUE)
  1766. static void *
  1767. event_create(void)
  1768. {
  1769. int ret = eventfd(0, EFD_CLOEXEC);
  1770. if (ret == -1) {
  1771. /* Linux uses -1 on error, Windows NULL. */
  1772. /* However, Linux does not return 0 on success either. */
  1773. return 0;
  1774. }
  1775. return (void *)ret;
  1776. }
  1777. static int
  1778. event_wait(void *eventhdl)
  1779. {
  1780. uint64_t u;
  1781. int s = (int)read((int)eventhdl, &u, sizeof(u));
  1782. if (s != sizeof(uint64_t)) {
  1783. /* error */
  1784. return 0;
  1785. }
  1786. (void)u; /* the value is not required */
  1787. return 1;
  1788. }
  1789. static int
  1790. event_signal(void *eventhdl)
  1791. {
  1792. uint64_t u = 1;
  1793. int s = (int)write((int)eventhdl, &u, sizeof(u));
  1794. if (s != sizeof(uint64_t)) {
  1795. /* error */
  1796. return 0;
  1797. }
  1798. return 1;
  1799. }
  1800. static void
  1801. event_destroy(void *eventhdl)
  1802. {
  1803. close((int)eventhdl);
  1804. }
  1805. #endif
  1806. #endif
  1807. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  1808. struct posix_event {
  1809. pthread_mutex_t mutex;
  1810. pthread_cond_t cond;
  1811. };
  1812. static void *
  1813. event_create(void)
  1814. {
  1815. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  1816. if (ret == 0) {
  1817. /* out of memory */
  1818. return 0;
  1819. }
  1820. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  1821. /* pthread mutex not available */
  1822. mg_free(ret);
  1823. return 0;
  1824. }
  1825. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  1826. /* pthread cond not available */
  1827. pthread_mutex_destroy(&(ret->mutex));
  1828. mg_free(ret);
  1829. return 0;
  1830. }
  1831. return (void *)ret;
  1832. }
  1833. static int
  1834. event_wait(void *eventhdl)
  1835. {
  1836. struct posix_event *ev = (struct posix_event *)eventhdl;
  1837. pthread_mutex_lock(&(ev->mutex));
  1838. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  1839. pthread_mutex_unlock(&(ev->mutex));
  1840. return 1;
  1841. }
  1842. static int
  1843. event_signal(void *eventhdl)
  1844. {
  1845. struct posix_event *ev = (struct posix_event *)eventhdl;
  1846. pthread_mutex_lock(&(ev->mutex));
  1847. pthread_cond_signal(&(ev->cond));
  1848. pthread_mutex_unlock(&(ev->mutex));
  1849. return 1;
  1850. }
  1851. static void
  1852. event_destroy(void *eventhdl)
  1853. {
  1854. struct posix_event *ev = (struct posix_event *)eventhdl;
  1855. pthread_cond_destroy(&(ev->cond));
  1856. pthread_mutex_destroy(&(ev->mutex));
  1857. mg_free(ev);
  1858. }
  1859. #endif
  1860. static void
  1861. mg_set_thread_name(const char *name)
  1862. {
  1863. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  1864. mg_snprintf(
  1865. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  1866. #if defined(_WIN32)
  1867. #if defined(_MSC_VER)
  1868. /* Windows and Visual Studio Compiler */
  1869. __try
  1870. {
  1871. THREADNAME_INFO info;
  1872. info.dwType = 0x1000;
  1873. info.szName = threadName;
  1874. info.dwThreadID = ~0U;
  1875. info.dwFlags = 0;
  1876. RaiseException(0x406D1388,
  1877. 0,
  1878. sizeof(info) / sizeof(ULONG_PTR),
  1879. (ULONG_PTR *)&info);
  1880. }
  1881. __except(EXCEPTION_EXECUTE_HANDLER)
  1882. {
  1883. }
  1884. #elif defined(__MINGW32__)
  1885. /* No option known to set thread name for MinGW */
  1886. #endif
  1887. #elif defined(__GLIBC__) \
  1888. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  1889. /* pthread_setname_np first appeared in glibc in version 2.12*/
  1890. (void)pthread_setname_np(pthread_self(), threadName);
  1891. #elif defined(__linux__)
  1892. /* on linux we can use the old prctl function */
  1893. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  1894. #endif
  1895. }
  1896. #else /* !defined(NO_THREAD_NAME) */
  1897. void
  1898. mg_set_thread_name(const char *threadName)
  1899. {
  1900. }
  1901. #endif
  1902. #if defined(MG_LEGACY_INTERFACE)
  1903. const char **
  1904. mg_get_valid_option_names(void)
  1905. {
  1906. /* This function is deprecated. Use mg_get_valid_options instead. */
  1907. static const char *
  1908. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  1909. int i;
  1910. for (i = 0; config_options[i].name != NULL; i++) {
  1911. data[i * 2] = config_options[i].name;
  1912. data[i * 2 + 1] = config_options[i].default_value;
  1913. }
  1914. return data;
  1915. }
  1916. #endif
  1917. const struct mg_option *
  1918. mg_get_valid_options(void)
  1919. {
  1920. return config_options;
  1921. }
  1922. /* Do not open file (used in is_file_in_memory) */
  1923. #define MG_FOPEN_MODE_NONE (0)
  1924. /* Open file for read only access */
  1925. #define MG_FOPEN_MODE_READ (1)
  1926. /* Open file for writing, create and overwrite */
  1927. #define MG_FOPEN_MODE_WRITE (2)
  1928. /* Open file for writing, create and append */
  1929. #define MG_FOPEN_MODE_APPEND (4)
  1930. /* If a file is in memory, set all "stat" members and the membuf pointer of
  1931. * output filep and return 1, otherwise return 0 and don't modify anything. */
  1932. static int
  1933. open_file_in_memory(const struct mg_connection *conn,
  1934. const char *path,
  1935. struct mg_file *filep,
  1936. int mode)
  1937. {
  1938. #if defined(MG_USE_OPEN_FILE)
  1939. size_t size = 0;
  1940. const char *buf = NULL;
  1941. if (!conn) {
  1942. return 0;
  1943. }
  1944. if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
  1945. return 0;
  1946. }
  1947. if (conn->ctx->callbacks.open_file) {
  1948. buf = conn->ctx->callbacks.open_file(conn, path, &size);
  1949. if (buf != NULL) {
  1950. if (filep == NULL) {
  1951. /* This is a file in memory, but we cannot store the properties
  1952. * now.
  1953. * Called from "is_file_in_memory" function. */
  1954. return 1;
  1955. }
  1956. /* NOTE: override filep->size only on success. Otherwise, it might
  1957. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  1958. filep->access.membuf = buf;
  1959. filep->access.fp = NULL;
  1960. /* Size was set by the callback */
  1961. filep->stat.size = size;
  1962. /* Assume the data may change during runtime by setting
  1963. * last_modified = now */
  1964. filep->stat.last_modified = time(NULL);
  1965. filep->stat.is_directory = 0;
  1966. filep->stat.is_gzipped = 0;
  1967. }
  1968. }
  1969. return (buf != NULL);
  1970. #else
  1971. (void)conn;
  1972. (void)path;
  1973. (void)filep;
  1974. (void)mode;
  1975. return 0;
  1976. #endif
  1977. }
  1978. static int
  1979. is_file_in_memory(const struct mg_connection *conn, const char *path)
  1980. {
  1981. return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
  1982. }
  1983. static int
  1984. is_file_opened(const struct mg_file_access *fileacc)
  1985. {
  1986. if (!fileacc) {
  1987. return 0;
  1988. }
  1989. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  1990. }
  1991. static int mg_stat(const struct mg_connection *conn,
  1992. const char *path,
  1993. struct mg_file_stat *filep);
  1994. /* mg_fopen will open a file either in memory or on the disk.
  1995. * The input parameter path is a string in UTF-8 encoding.
  1996. * The input parameter mode is MG_FOPEN_MODE_*
  1997. * On success, either fp or membuf will be set in the output
  1998. * struct file. All status members will also be set.
  1999. * The function returns 1 on success, 0 on error. */
  2000. static int
  2001. mg_fopen(const struct mg_connection *conn,
  2002. const char *path,
  2003. int mode,
  2004. struct mg_file *filep)
  2005. {
  2006. int found;
  2007. if (!filep) {
  2008. return 0;
  2009. }
  2010. filep->access.fp = NULL;
  2011. filep->access.membuf = NULL;
  2012. if (!is_file_in_memory(conn, path)) {
  2013. /* filep is initialized in mg_stat: all fields with memset to,
  2014. * some fields like size and modification date with values */
  2015. found = mg_stat(conn, path, &(filep->stat));
  2016. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2017. /* file does not exist and will not be created */
  2018. return 0;
  2019. }
  2020. #ifdef _WIN32
  2021. {
  2022. wchar_t wbuf[PATH_MAX];
  2023. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2024. switch (mode) {
  2025. case MG_FOPEN_MODE_READ:
  2026. filep->access.fp = _wfopen(wbuf, L"rb");
  2027. break;
  2028. case MG_FOPEN_MODE_WRITE:
  2029. filep->access.fp = _wfopen(wbuf, L"wb");
  2030. break;
  2031. case MG_FOPEN_MODE_APPEND:
  2032. filep->access.fp = _wfopen(wbuf, L"ab");
  2033. break;
  2034. }
  2035. }
  2036. #else
  2037. /* Linux et al already use unicode. No need to convert. */
  2038. switch (mode) {
  2039. case MG_FOPEN_MODE_READ:
  2040. filep->access.fp = fopen(path, "r");
  2041. break;
  2042. case MG_FOPEN_MODE_WRITE:
  2043. filep->access.fp = fopen(path, "w");
  2044. break;
  2045. case MG_FOPEN_MODE_APPEND:
  2046. filep->access.fp = fopen(path, "a");
  2047. break;
  2048. }
  2049. #endif
  2050. if (!found) {
  2051. /* File did not exist before fopen was called.
  2052. * Maybe it has been created now. Get stat info
  2053. * like creation time now. */
  2054. found = mg_stat(conn, path, &(filep->stat));
  2055. (void)found;
  2056. }
  2057. /* file is on disk */
  2058. return (filep->access.fp != NULL);
  2059. } else {
  2060. /* is_file_in_memory returned true */
  2061. if (open_file_in_memory(conn, path, filep, mode)) {
  2062. /* file is in memory */
  2063. return (filep->access.membuf != NULL);
  2064. }
  2065. }
  2066. /* Open failed */
  2067. return 0;
  2068. }
  2069. /* return 0 on success, just like fclose */
  2070. static int
  2071. mg_fclose(struct mg_file_access *fileacc)
  2072. {
  2073. int ret = -1;
  2074. if (fileacc != NULL) {
  2075. if (fileacc->fp != NULL) {
  2076. ret = fclose(fileacc->fp);
  2077. } else if (fileacc->membuf != NULL) {
  2078. ret = 0;
  2079. }
  2080. /* reset all members of fileacc */
  2081. memset(fileacc, 0, sizeof(*fileacc));
  2082. }
  2083. return ret;
  2084. }
  2085. static void
  2086. mg_strlcpy(register char *dst, register const char *src, size_t n)
  2087. {
  2088. for (; *src != '\0' && n > 1; n--) {
  2089. *dst++ = *src++;
  2090. }
  2091. *dst = '\0';
  2092. }
  2093. static int
  2094. lowercase(const char *s)
  2095. {
  2096. return tolower(*(const unsigned char *)s);
  2097. }
  2098. int
  2099. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2100. {
  2101. int diff = 0;
  2102. if (len > 0) {
  2103. do {
  2104. diff = lowercase(s1++) - lowercase(s2++);
  2105. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2106. }
  2107. return diff;
  2108. }
  2109. int
  2110. mg_strcasecmp(const char *s1, const char *s2)
  2111. {
  2112. int diff;
  2113. do {
  2114. diff = lowercase(s1++) - lowercase(s2++);
  2115. } while (diff == 0 && s1[-1] != '\0');
  2116. return diff;
  2117. }
  2118. static char *
  2119. mg_strndup(const char *ptr, size_t len)
  2120. {
  2121. char *p;
  2122. if ((p = (char *)mg_malloc(len + 1)) != NULL) {
  2123. mg_strlcpy(p, ptr, len + 1);
  2124. }
  2125. return p;
  2126. }
  2127. static char *
  2128. mg_strdup(const char *str)
  2129. {
  2130. return mg_strndup(str, strlen(str));
  2131. }
  2132. static const char *
  2133. mg_strcasestr(const char *big_str, const char *small_str)
  2134. {
  2135. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2136. if (big_len >= small_len) {
  2137. for (i = 0; i <= (big_len - small_len); i++) {
  2138. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2139. return big_str + i;
  2140. }
  2141. }
  2142. }
  2143. return NULL;
  2144. }
  2145. /* Return null terminated string of given maximum length.
  2146. * Report errors if length is exceeded. */
  2147. static void
  2148. mg_vsnprintf(const struct mg_connection *conn,
  2149. int *truncated,
  2150. char *buf,
  2151. size_t buflen,
  2152. const char *fmt,
  2153. va_list ap)
  2154. {
  2155. int n, ok;
  2156. if (buflen == 0) {
  2157. return;
  2158. }
  2159. #ifdef __clang__
  2160. #pragma clang diagnostic push
  2161. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2162. /* Using fmt as a non-literal is intended here, since it is mostly called
  2163. * indirectly by mg_snprintf */
  2164. #endif
  2165. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2166. ok = (n >= 0) && ((size_t)n < buflen);
  2167. #ifdef __clang__
  2168. #pragma clang diagnostic pop
  2169. #endif
  2170. if (ok) {
  2171. if (truncated) {
  2172. *truncated = 0;
  2173. }
  2174. } else {
  2175. if (truncated) {
  2176. *truncated = 1;
  2177. }
  2178. mg_cry(conn,
  2179. "truncating vsnprintf buffer: [%.*s]",
  2180. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2181. buf);
  2182. n = (int)buflen - 1;
  2183. }
  2184. buf[n] = '\0';
  2185. }
  2186. static void
  2187. mg_snprintf(const struct mg_connection *conn,
  2188. int *truncated,
  2189. char *buf,
  2190. size_t buflen,
  2191. const char *fmt,
  2192. ...)
  2193. {
  2194. va_list ap;
  2195. va_start(ap, fmt);
  2196. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2197. va_end(ap);
  2198. }
  2199. static int
  2200. get_option_index(const char *name)
  2201. {
  2202. int i;
  2203. for (i = 0; config_options[i].name != NULL; i++) {
  2204. if (strcmp(config_options[i].name, name) == 0) {
  2205. return i;
  2206. }
  2207. }
  2208. return -1;
  2209. }
  2210. const char *
  2211. mg_get_option(const struct mg_context *ctx, const char *name)
  2212. {
  2213. int i;
  2214. if ((i = get_option_index(name)) == -1) {
  2215. return NULL;
  2216. } else if (!ctx || ctx->config[i] == NULL) {
  2217. return "";
  2218. } else {
  2219. return ctx->config[i];
  2220. }
  2221. }
  2222. struct mg_context *
  2223. mg_get_context(const struct mg_connection *conn)
  2224. {
  2225. return (conn == NULL) ? (struct mg_context *)NULL : (conn->ctx);
  2226. }
  2227. void *
  2228. mg_get_user_data(const struct mg_context *ctx)
  2229. {
  2230. return (ctx == NULL) ? NULL : ctx->user_data;
  2231. }
  2232. void
  2233. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  2234. {
  2235. if (conn != NULL) {
  2236. conn->request_info.conn_data = data;
  2237. }
  2238. }
  2239. void *
  2240. mg_get_user_connection_data(const struct mg_connection *conn)
  2241. {
  2242. if (conn != NULL) {
  2243. return conn->request_info.conn_data;
  2244. }
  2245. return NULL;
  2246. }
  2247. #if defined(MG_LEGACY_INTERFACE)
  2248. /* Deprecated: Use mg_get_server_ports instead. */
  2249. size_t
  2250. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  2251. {
  2252. size_t i;
  2253. if (!ctx) {
  2254. return 0;
  2255. }
  2256. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  2257. ssl[i] = ctx->listening_sockets[i].is_ssl;
  2258. ports[i] =
  2259. #if defined(USE_IPV6)
  2260. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2261. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2262. :
  2263. #endif
  2264. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2265. }
  2266. return i;
  2267. }
  2268. #endif
  2269. int
  2270. mg_get_server_ports(const struct mg_context *ctx,
  2271. int size,
  2272. struct mg_server_ports *ports)
  2273. {
  2274. int i, cnt = 0;
  2275. if (size <= 0) {
  2276. return -1;
  2277. }
  2278. memset(ports, 0, sizeof(*ports) * (size_t)size);
  2279. if (!ctx) {
  2280. return -1;
  2281. }
  2282. if (!ctx->listening_sockets) {
  2283. return -1;
  2284. }
  2285. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  2286. ports[cnt].port =
  2287. #if defined(USE_IPV6)
  2288. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2289. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2290. :
  2291. #endif
  2292. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2293. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  2294. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  2295. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  2296. /* IPv4 */
  2297. ports[cnt].protocol = 1;
  2298. cnt++;
  2299. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  2300. /* IPv6 */
  2301. ports[cnt].protocol = 3;
  2302. cnt++;
  2303. }
  2304. }
  2305. return cnt;
  2306. }
  2307. static void
  2308. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  2309. {
  2310. buf[0] = '\0';
  2311. if (!usa) {
  2312. return;
  2313. }
  2314. if (usa->sa.sa_family == AF_INET) {
  2315. getnameinfo(&usa->sa,
  2316. sizeof(usa->sin),
  2317. buf,
  2318. (unsigned)len,
  2319. NULL,
  2320. 0,
  2321. NI_NUMERICHOST);
  2322. }
  2323. #if defined(USE_IPV6)
  2324. else if (usa->sa.sa_family == AF_INET6) {
  2325. getnameinfo(&usa->sa,
  2326. sizeof(usa->sin6),
  2327. buf,
  2328. (unsigned)len,
  2329. NULL,
  2330. 0,
  2331. NI_NUMERICHOST);
  2332. }
  2333. #endif
  2334. }
  2335. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  2336. * included in all responses other than 100, 101, 5xx. */
  2337. static void
  2338. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  2339. {
  2340. struct tm *tm;
  2341. tm = ((t != NULL) ? gmtime(t) : NULL);
  2342. if (tm != NULL) {
  2343. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  2344. } else {
  2345. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  2346. buf[buf_len - 1] = '\0';
  2347. }
  2348. }
  2349. /* difftime for struct timespec. Return value is in seconds. */
  2350. static double
  2351. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  2352. {
  2353. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  2354. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  2355. }
  2356. /* Print error message to the opened error log stream. */
  2357. void
  2358. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  2359. {
  2360. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  2361. va_list ap;
  2362. struct mg_file fi;
  2363. time_t timestamp;
  2364. va_start(ap, fmt);
  2365. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  2366. va_end(ap);
  2367. buf[sizeof(buf) - 1] = 0;
  2368. if (!conn) {
  2369. puts(buf);
  2370. return;
  2371. }
  2372. /* Do not lock when getting the callback value, here and below.
  2373. * I suppose this is fine, since function cannot disappear in the
  2374. * same way string option can. */
  2375. if ((conn->ctx->callbacks.log_message == NULL)
  2376. || (conn->ctx->callbacks.log_message(conn, buf) == 0)) {
  2377. if (conn->ctx->config[ERROR_LOG_FILE] != NULL) {
  2378. if (mg_fopen(conn,
  2379. conn->ctx->config[ERROR_LOG_FILE],
  2380. MG_FOPEN_MODE_APPEND,
  2381. &fi) == 0) {
  2382. fi.access.fp = NULL;
  2383. }
  2384. } else {
  2385. fi.access.fp = NULL;
  2386. }
  2387. if (fi.access.fp != NULL) {
  2388. flockfile(fi.access.fp);
  2389. timestamp = time(NULL);
  2390. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  2391. fprintf(fi.access.fp,
  2392. "[%010lu] [error] [client %s] ",
  2393. (unsigned long)timestamp,
  2394. src_addr);
  2395. if (conn->request_info.request_method != NULL) {
  2396. fprintf(fi.access.fp,
  2397. "%s %s: ",
  2398. conn->request_info.request_method,
  2399. conn->request_info.request_uri);
  2400. }
  2401. fprintf(fi.access.fp, "%s", buf);
  2402. fputc('\n', fi.access.fp);
  2403. fflush(fi.access.fp);
  2404. funlockfile(fi.access.fp);
  2405. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  2406. * mg_cry here anyway ;-) */
  2407. }
  2408. }
  2409. }
  2410. /* Return fake connection structure. Used for logging, if connection
  2411. * is not applicable at the moment of logging. */
  2412. static struct mg_connection *
  2413. fc(struct mg_context *ctx)
  2414. {
  2415. static struct mg_connection fake_connection;
  2416. fake_connection.ctx = ctx;
  2417. return &fake_connection;
  2418. }
  2419. const char *
  2420. mg_version(void)
  2421. {
  2422. return CIVETWEB_VERSION;
  2423. }
  2424. const struct mg_request_info *
  2425. mg_get_request_info(const struct mg_connection *conn)
  2426. {
  2427. if (!conn) {
  2428. return NULL;
  2429. }
  2430. return &conn->request_info;
  2431. }
  2432. int
  2433. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  2434. {
  2435. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  2436. return -1;
  2437. } else {
  2438. int truncated = 0;
  2439. const struct mg_request_info *ri = &conn->request_info;
  2440. #ifdef __clang__
  2441. #pragma clang diagnostic push
  2442. #pragma clang diagnostic ignored "-Wunreachable-code"
  2443. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  2444. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  2445. * unreachable, but splitting into four different #ifdef clauses here is more
  2446. * complicated.
  2447. */
  2448. #endif
  2449. const char *proto =
  2450. (is_websocket_protocol(conn) ? (ri->is_ssl ? "wss" : "ws")
  2451. : (ri->is_ssl ? "https" : "http"));
  2452. #ifdef __clang__
  2453. #pragma clang diagnostic pop
  2454. #endif
  2455. if (ri->local_uri == NULL) {
  2456. return -1;
  2457. }
  2458. if ((ri->request_uri != NULL)
  2459. && strcmp(ri->local_uri, ri->request_uri)) {
  2460. mg_snprintf(conn,
  2461. &truncated,
  2462. buf,
  2463. buflen,
  2464. "%s://%s",
  2465. proto,
  2466. ri->request_uri);
  2467. if (truncated) {
  2468. return -1;
  2469. }
  2470. return 0;
  2471. } else {
  2472. #if defined(USE_IPV6)
  2473. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  2474. int port = is_ipv6 ? htons(conn->client.lsa.sin6.sin6_port)
  2475. : htons(conn->client.lsa.sin.sin_port);
  2476. #else
  2477. int port = htons(conn->client.lsa.sin.sin_port);
  2478. #endif
  2479. int def_port = ri->is_ssl ? 443 : 80;
  2480. int auth_domain_check_enabled =
  2481. conn->ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  2482. && (!strcmp(conn->ctx->config[ENABLE_AUTH_DOMAIN_CHECK],
  2483. "yes"));
  2484. const char *server_domain =
  2485. conn->ctx->config[AUTHENTICATION_DOMAIN];
  2486. char portstr[16];
  2487. char server_ip[48];
  2488. if (port != def_port) {
  2489. sprintf(portstr, ":%u", (unsigned)port);
  2490. } else {
  2491. portstr[0] = 0;
  2492. }
  2493. if (!auth_domain_check_enabled || !server_domain) {
  2494. sockaddr_to_string(server_ip,
  2495. sizeof(server_ip),
  2496. &conn->client.lsa);
  2497. server_domain = server_ip;
  2498. }
  2499. mg_snprintf(conn,
  2500. &truncated,
  2501. buf,
  2502. buflen,
  2503. "%s://%s%s%s",
  2504. proto,
  2505. server_domain,
  2506. portstr,
  2507. ri->local_uri);
  2508. if (truncated) {
  2509. return -1;
  2510. }
  2511. return 0;
  2512. }
  2513. }
  2514. }
  2515. /* Skip the characters until one of the delimiters characters found.
  2516. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  2517. * Advance pointer to buffer to the next word. Return found 0-terminated word.
  2518. * Delimiters can be quoted with quotechar. */
  2519. static char *
  2520. skip_quoted(char **buf,
  2521. const char *delimiters,
  2522. const char *whitespace,
  2523. char quotechar)
  2524. {
  2525. char *p, *begin_word, *end_word, *end_whitespace;
  2526. begin_word = *buf;
  2527. end_word = begin_word + strcspn(begin_word, delimiters);
  2528. /* Check for quotechar */
  2529. if (end_word > begin_word) {
  2530. p = end_word - 1;
  2531. while (*p == quotechar) {
  2532. /* While the delimiter is quoted, look for the next delimiter. */
  2533. /* This happens, e.g., in calls from parse_auth_header,
  2534. * if the user name contains a " character. */
  2535. /* If there is anything beyond end_word, copy it. */
  2536. if (*end_word != '\0') {
  2537. size_t end_off = strcspn(end_word + 1, delimiters);
  2538. memmove(p, end_word, end_off + 1);
  2539. p += end_off; /* p must correspond to end_word - 1 */
  2540. end_word += end_off + 1;
  2541. } else {
  2542. *p = '\0';
  2543. break;
  2544. }
  2545. }
  2546. for (p++; p < end_word; p++) {
  2547. *p = '\0';
  2548. }
  2549. }
  2550. if (*end_word == '\0') {
  2551. *buf = end_word;
  2552. } else {
  2553. #if defined(__GNUC__) || defined(__MINGW32__)
  2554. /* Disable spurious conversion warning for GCC */
  2555. #pragma GCC diagnostic push
  2556. #pragma GCC diagnostic ignored "-Wsign-conversion"
  2557. #endif
  2558. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  2559. #if defined(__GNUC__) || defined(__MINGW32__)
  2560. #pragma GCC diagnostic pop
  2561. #endif
  2562. for (p = end_word; p < end_whitespace; p++) {
  2563. *p = '\0';
  2564. }
  2565. *buf = end_whitespace;
  2566. }
  2567. return begin_word;
  2568. }
  2569. /* Simplified version of skip_quoted without quote char
  2570. * and whitespace == delimiters */
  2571. static char *
  2572. skip(char **buf, const char *delimiters)
  2573. {
  2574. return skip_quoted(buf, delimiters, delimiters, 0);
  2575. }
  2576. /* Return HTTP header value, or NULL if not found. */
  2577. static const char *
  2578. get_header(const struct mg_request_info *ri, const char *name)
  2579. {
  2580. int i;
  2581. if (ri) {
  2582. for (i = 0; i < ri->num_headers; i++) {
  2583. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  2584. return ri->http_headers[i].value;
  2585. }
  2586. }
  2587. }
  2588. return NULL;
  2589. }
  2590. const char *
  2591. mg_get_header(const struct mg_connection *conn, const char *name)
  2592. {
  2593. if (!conn) {
  2594. return NULL;
  2595. }
  2596. return get_header(&conn->request_info, name);
  2597. }
  2598. /* A helper function for traversing a comma separated list of values.
  2599. * It returns a list pointer shifted to the next value, or NULL if the end
  2600. * of the list found.
  2601. * Value is stored in val vector. If value has form "x=y", then eq_val
  2602. * vector is initialized to point to the "y" part, and val vector length
  2603. * is adjusted to point only to "x". */
  2604. static const char *
  2605. next_option(const char *list, struct vec *val, struct vec *eq_val)
  2606. {
  2607. int end;
  2608. reparse:
  2609. if (val == NULL || list == NULL || *list == '\0') {
  2610. /* End of the list */
  2611. list = NULL;
  2612. } else {
  2613. /* Skip over leading LWS */
  2614. while (*list == ' ' || *list == '\t')
  2615. list++;
  2616. val->ptr = list;
  2617. if ((list = strchr(val->ptr, ',')) != NULL) {
  2618. /* Comma found. Store length and shift the list ptr */
  2619. val->len = ((size_t)(list - val->ptr));
  2620. list++;
  2621. } else {
  2622. /* This value is the last one */
  2623. list = val->ptr + strlen(val->ptr);
  2624. val->len = ((size_t)(list - val->ptr));
  2625. }
  2626. /* Adjust length for trailing LWS */
  2627. end = (int)val->len - 1;
  2628. while (end >= 0 && (val->ptr[end] == ' ' || val->ptr[end] == '\t'))
  2629. end--;
  2630. val->len = (size_t)(end + 1);
  2631. if (val->len == 0) {
  2632. /* Ignore any empty entries. */
  2633. goto reparse;
  2634. }
  2635. if (eq_val != NULL) {
  2636. /* Value has form "x=y", adjust pointers and lengths
  2637. * so that val points to "x", and eq_val points to "y". */
  2638. eq_val->len = 0;
  2639. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  2640. if (eq_val->ptr != NULL) {
  2641. eq_val->ptr++; /* Skip over '=' character */
  2642. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  2643. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  2644. }
  2645. }
  2646. }
  2647. return list;
  2648. }
  2649. /* A helper function for checking if a comma separated list of values contains
  2650. * the given option (case insensitvely).
  2651. * 'header' can be NULL, in which case false is returned. */
  2652. static int
  2653. header_has_option(const char *header, const char *option)
  2654. {
  2655. struct vec opt_vec;
  2656. struct vec eq_vec;
  2657. assert(option != NULL);
  2658. assert(option[0] != '\0');
  2659. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  2660. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  2661. return 1;
  2662. }
  2663. return 0;
  2664. }
  2665. /* Perform case-insensitive match of string against pattern */
  2666. static int
  2667. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  2668. {
  2669. const char *or_str;
  2670. size_t i;
  2671. int j, len, res;
  2672. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  2673. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  2674. return (res > 0) ? res : match_prefix(or_str + 1,
  2675. (size_t)((pattern + pattern_len)
  2676. - (or_str + 1)),
  2677. str);
  2678. }
  2679. for (i = 0, j = 0; i < pattern_len; i++, j++) {
  2680. if (pattern[i] == '?' && str[j] != '\0') {
  2681. continue;
  2682. } else if (pattern[i] == '$') {
  2683. return (str[j] == '\0') ? j : -1;
  2684. } else if (pattern[i] == '*') {
  2685. i++;
  2686. if (pattern[i] == '*') {
  2687. i++;
  2688. len = (int)strlen(str + j);
  2689. } else {
  2690. len = (int)strcspn(str + j, "/");
  2691. }
  2692. if (i == pattern_len) {
  2693. return j + len;
  2694. }
  2695. do {
  2696. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  2697. } while (res == -1 && len-- > 0);
  2698. return (res == -1) ? -1 : j + res + len;
  2699. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  2700. return -1;
  2701. }
  2702. }
  2703. return j;
  2704. }
  2705. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  2706. * This function must tolerate situations when connection info is not
  2707. * set up, for example if request parsing failed. */
  2708. static int
  2709. should_keep_alive(const struct mg_connection *conn)
  2710. {
  2711. if (conn != NULL) {
  2712. const char *http_version = conn->request_info.http_version;
  2713. const char *header = mg_get_header(conn, "Connection");
  2714. if (conn->must_close || conn->status_code == 401
  2715. || mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0
  2716. || (header != NULL && !header_has_option(header, "keep-alive"))
  2717. || (header == NULL && http_version
  2718. && 0 != strcmp(http_version, "1.1"))) {
  2719. return 0;
  2720. }
  2721. return 1;
  2722. }
  2723. return 0;
  2724. }
  2725. static int
  2726. should_decode_url(const struct mg_connection *conn)
  2727. {
  2728. if (!conn || !conn->ctx) {
  2729. return 0;
  2730. }
  2731. return (mg_strcasecmp(conn->ctx->config[DECODE_URL], "yes") == 0);
  2732. }
  2733. static const char *
  2734. suggest_connection_header(const struct mg_connection *conn)
  2735. {
  2736. return should_keep_alive(conn) ? "keep-alive" : "close";
  2737. }
  2738. static int
  2739. send_no_cache_header(struct mg_connection *conn)
  2740. {
  2741. /* Send all current and obsolete cache opt-out directives. */
  2742. return mg_printf(conn,
  2743. "Cache-Control: no-cache, no-store, "
  2744. "must-revalidate, private, max-age=0\r\n"
  2745. "Pragma: no-cache\r\n"
  2746. "Expires: 0\r\n");
  2747. }
  2748. static int
  2749. send_static_cache_header(struct mg_connection *conn)
  2750. {
  2751. #if !defined(NO_CACHING)
  2752. /* Read the server config to check how long a file may be cached.
  2753. * The configuration is in seconds. */
  2754. int max_age = atoi(conn->ctx->config[STATIC_FILE_MAX_AGE]);
  2755. if (max_age <= 0) {
  2756. /* 0 means "do not cache". All values <0 are reserved
  2757. * and may be used differently in the future. */
  2758. /* If a file should not be cached, do not only send
  2759. * max-age=0, but also pragmas and Expires headers. */
  2760. return send_no_cache_header(conn);
  2761. }
  2762. /* Use "Cache-Control: max-age" instead of "Expires" header.
  2763. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  2764. /* See also https://www.mnot.net/cache_docs/ */
  2765. /* According to RFC 2616, Section 14.21, caching times should not exceed
  2766. * one year. A year with 365 days corresponds to 31536000 seconds, a leap
  2767. * year to 31622400 seconds. For the moment, we just send whatever has
  2768. * been configured, still the behavior for >1 year should be considered
  2769. * as undefined. */
  2770. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  2771. #else /* NO_CACHING */
  2772. return send_no_cache_header(conn);
  2773. #endif /* !NO_CACHING */
  2774. }
  2775. static int
  2776. send_additional_header(struct mg_connection *conn)
  2777. {
  2778. int i = 0;
  2779. (void)conn;
  2780. #if 0
  2781. /* TODO (Feature): Configure additional response header */
  2782. i += mg_printf(conn, "Strict-Transport-Security: max-age=%u\r\n", 3600);
  2783. i += mg_printf(conn, "X-Some-Test-Header: %u\r\n", 42);
  2784. #endif
  2785. return i;
  2786. }
  2787. static void handle_file_based_request(struct mg_connection *conn,
  2788. const char *path,
  2789. struct mg_file *filep);
  2790. const char *
  2791. mg_get_response_code_text(struct mg_connection *conn, int response_code)
  2792. {
  2793. /* See IANA HTTP status code assignment:
  2794. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  2795. */
  2796. switch (response_code) {
  2797. /* RFC2616 Section 10.1 - Informational 1xx */
  2798. case 100:
  2799. return "Continue"; /* RFC2616 Section 10.1.1 */
  2800. case 101:
  2801. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  2802. case 102:
  2803. return "Processing"; /* RFC2518 Section 10.1 */
  2804. /* RFC2616 Section 10.2 - Successful 2xx */
  2805. case 200:
  2806. return "OK"; /* RFC2616 Section 10.2.1 */
  2807. case 201:
  2808. return "Created"; /* RFC2616 Section 10.2.2 */
  2809. case 202:
  2810. return "Accepted"; /* RFC2616 Section 10.2.3 */
  2811. case 203:
  2812. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  2813. case 204:
  2814. return "No Content"; /* RFC2616 Section 10.2.5 */
  2815. case 205:
  2816. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  2817. case 206:
  2818. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  2819. case 207:
  2820. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1 */
  2821. case 208:
  2822. return "Already Reported"; /* RFC5842 Section 7.1 */
  2823. case 226:
  2824. return "IM used"; /* RFC3229 Section 10.4.1 */
  2825. /* RFC2616 Section 10.3 - Redirection 3xx */
  2826. case 300:
  2827. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  2828. case 301:
  2829. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  2830. case 302:
  2831. return "Found"; /* RFC2616 Section 10.3.3 */
  2832. case 303:
  2833. return "See Other"; /* RFC2616 Section 10.3.4 */
  2834. case 304:
  2835. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  2836. case 305:
  2837. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  2838. case 307:
  2839. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  2840. case 308:
  2841. return "Permanent Redirect"; /* RFC7238 Section 3 */
  2842. /* RFC2616 Section 10.4 - Client Error 4xx */
  2843. case 400:
  2844. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  2845. case 401:
  2846. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  2847. case 402:
  2848. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  2849. case 403:
  2850. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  2851. case 404:
  2852. return "Not Found"; /* RFC2616 Section 10.4.5 */
  2853. case 405:
  2854. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  2855. case 406:
  2856. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  2857. case 407:
  2858. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  2859. case 408:
  2860. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  2861. case 409:
  2862. return "Conflict"; /* RFC2616 Section 10.4.10 */
  2863. case 410:
  2864. return "Gone"; /* RFC2616 Section 10.4.11 */
  2865. case 411:
  2866. return "Length Required"; /* RFC2616 Section 10.4.12 */
  2867. case 412:
  2868. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  2869. case 413:
  2870. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  2871. case 414:
  2872. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  2873. case 415:
  2874. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  2875. case 416:
  2876. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17 */
  2877. case 417:
  2878. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  2879. case 421:
  2880. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  2881. case 422:
  2882. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  2883. * Section 11.2 */
  2884. case 423:
  2885. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  2886. case 424:
  2887. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  2888. * Section 11.4 */
  2889. case 426:
  2890. return "Upgrade Required"; /* RFC 2817 Section 4 */
  2891. case 428:
  2892. return "Precondition Required"; /* RFC 6585, Section 3 */
  2893. case 429:
  2894. return "Too Many Requests"; /* RFC 6585, Section 4 */
  2895. case 431:
  2896. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  2897. case 451:
  2898. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  2899. * Section 3 */
  2900. /* RFC2616 Section 10.5 - Server Error 5xx */
  2901. case 500:
  2902. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  2903. case 501:
  2904. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  2905. case 502:
  2906. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  2907. case 503:
  2908. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  2909. case 504:
  2910. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  2911. case 505:
  2912. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  2913. case 506:
  2914. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  2915. case 507:
  2916. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  2917. * Section 11.5 */
  2918. case 508:
  2919. return "Loop Detected"; /* RFC5842 Section 7.1 */
  2920. case 510:
  2921. return "Not Extended"; /* RFC 2774, Section 7 */
  2922. case 511:
  2923. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  2924. /* Other status codes, not shown in the IANA HTTP status code assignment.
  2925. * E.g., "de facto" standards due to common use, ... */
  2926. case 418:
  2927. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  2928. case 419:
  2929. return "Authentication Timeout"; /* common use */
  2930. case 420:
  2931. return "Enhance Your Calm"; /* common use */
  2932. case 440:
  2933. return "Login Timeout"; /* common use */
  2934. case 509:
  2935. return "Bandwidth Limit Exceeded"; /* common use */
  2936. default:
  2937. /* This error code is unknown. This should not happen. */
  2938. if (conn) {
  2939. mg_cry(conn, "Unknown HTTP response code: %u", response_code);
  2940. }
  2941. /* Return at least a category according to RFC 2616 Section 10. */
  2942. if (response_code >= 100 && response_code < 200) {
  2943. /* Unknown informational status code */
  2944. return "Information";
  2945. }
  2946. if (response_code >= 200 && response_code < 300) {
  2947. /* Unknown success code */
  2948. return "Success";
  2949. }
  2950. if (response_code >= 300 && response_code < 400) {
  2951. /* Unknown redirection code */
  2952. return "Redirection";
  2953. }
  2954. if (response_code >= 400 && response_code < 500) {
  2955. /* Unknown request error code */
  2956. return "Client Error";
  2957. }
  2958. if (response_code >= 500 && response_code < 600) {
  2959. /* Unknown server error code */
  2960. return "Server Error";
  2961. }
  2962. /* Response code not even within reasonable range */
  2963. return "";
  2964. }
  2965. }
  2966. void
  2967. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  2968. {
  2969. char buf[MG_BUF_LEN];
  2970. va_list ap;
  2971. int len, i, page_handler_found, scope, truncated, has_body;
  2972. char date[64];
  2973. time_t curtime = time(NULL);
  2974. const char *error_handler = NULL;
  2975. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  2976. const char *error_page_file_ext, *tstr;
  2977. const char *status_text = mg_get_response_code_text(conn, status);
  2978. if (conn == NULL) {
  2979. return;
  2980. }
  2981. conn->status_code = status;
  2982. if (conn->in_error_handler || conn->ctx->callbacks.http_error == NULL
  2983. || conn->ctx->callbacks.http_error(conn, status)) {
  2984. if (!conn->in_error_handler) {
  2985. /* Send user defined error pages, if defined */
  2986. error_handler = conn->ctx->config[ERROR_PAGES];
  2987. error_page_file_ext = conn->ctx->config[INDEX_FILES];
  2988. page_handler_found = 0;
  2989. if (error_handler != NULL) {
  2990. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  2991. switch (scope) {
  2992. case 1: /* Handler for specific error, e.g. 404 error */
  2993. mg_snprintf(conn,
  2994. &truncated,
  2995. buf,
  2996. sizeof(buf) - 32,
  2997. "%serror%03u.",
  2998. error_handler,
  2999. status);
  3000. break;
  3001. case 2: /* Handler for error group, e.g., 5xx error handler
  3002. * for all server errors (500-599) */
  3003. mg_snprintf(conn,
  3004. &truncated,
  3005. buf,
  3006. sizeof(buf) - 32,
  3007. "%serror%01uxx.",
  3008. error_handler,
  3009. status / 100);
  3010. break;
  3011. default: /* Handler for all errors */
  3012. mg_snprintf(conn,
  3013. &truncated,
  3014. buf,
  3015. sizeof(buf) - 32,
  3016. "%serror.",
  3017. error_handler);
  3018. break;
  3019. }
  3020. /* String truncation in buf may only occur if error_handler
  3021. * is too long. This string is from the config, not from a
  3022. * client. */
  3023. (void)truncated;
  3024. len = (int)strlen(buf);
  3025. tstr = strchr(error_page_file_ext, '.');
  3026. while (tstr) {
  3027. for (i = 1; i < 32 && tstr[i] != 0 && tstr[i] != ',';
  3028. i++)
  3029. buf[len + i - 1] = tstr[i];
  3030. buf[len + i - 1] = 0;
  3031. if (mg_stat(conn, buf, &error_page_file.stat)) {
  3032. page_handler_found = 1;
  3033. break;
  3034. }
  3035. tstr = strchr(tstr + i, '.');
  3036. }
  3037. }
  3038. }
  3039. if (page_handler_found) {
  3040. conn->in_error_handler = 1;
  3041. handle_file_based_request(conn, buf, &error_page_file);
  3042. conn->in_error_handler = 0;
  3043. return;
  3044. }
  3045. }
  3046. /* No custom error page. Send default error page. */
  3047. gmt_time_string(date, sizeof(date), &curtime);
  3048. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3049. has_body = (status > 199 && status != 204 && status != 304);
  3050. conn->must_close = 1;
  3051. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  3052. send_no_cache_header(conn);
  3053. send_additional_header(conn);
  3054. if (has_body) {
  3055. mg_printf(conn,
  3056. "%s",
  3057. "Content-Type: text/plain; charset=utf-8\r\n");
  3058. }
  3059. mg_printf(conn,
  3060. "Date: %s\r\n"
  3061. "Connection: close\r\n\r\n",
  3062. date);
  3063. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3064. if (has_body) {
  3065. mg_printf(conn, "Error %d: %s\n", status, status_text);
  3066. if (fmt != NULL) {
  3067. va_start(ap, fmt);
  3068. mg_vsnprintf(conn, NULL, buf, sizeof(buf), fmt, ap);
  3069. va_end(ap);
  3070. mg_write(conn, buf, strlen(buf));
  3071. DEBUG_TRACE("Error %i - [%s]", status, buf);
  3072. }
  3073. } else {
  3074. /* No body allowed. Close the connection. */
  3075. DEBUG_TRACE("Error %i", status);
  3076. }
  3077. }
  3078. }
  3079. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  3080. /* Create substitutes for POSIX functions in Win32. */
  3081. #if defined(__MINGW32__)
  3082. /* Show no warning in case system functions are not used. */
  3083. #pragma GCC diagnostic push
  3084. #pragma GCC diagnostic ignored "-Wunused-function"
  3085. #endif
  3086. static int
  3087. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  3088. {
  3089. (void)unused;
  3090. *mutex = CreateMutex(NULL, FALSE, NULL);
  3091. return (*mutex == NULL) ? -1 : 0;
  3092. }
  3093. static int
  3094. pthread_mutex_destroy(pthread_mutex_t *mutex)
  3095. {
  3096. return (CloseHandle(*mutex) == 0) ? -1 : 0;
  3097. }
  3098. static int
  3099. pthread_mutex_lock(pthread_mutex_t *mutex)
  3100. {
  3101. return (WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0) ? 0 : -1;
  3102. }
  3103. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  3104. static int
  3105. pthread_mutex_trylock(pthread_mutex_t *mutex)
  3106. {
  3107. switch (WaitForSingleObject(*mutex, 0)) {
  3108. case WAIT_OBJECT_0:
  3109. return 0;
  3110. case WAIT_TIMEOUT:
  3111. return -2; /* EBUSY */
  3112. }
  3113. return -1;
  3114. }
  3115. #endif
  3116. static int
  3117. pthread_mutex_unlock(pthread_mutex_t *mutex)
  3118. {
  3119. return (ReleaseMutex(*mutex) == 0) ? -1 : 0;
  3120. }
  3121. static int
  3122. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  3123. {
  3124. (void)unused;
  3125. InitializeCriticalSection(&cv->threadIdSec);
  3126. cv->waiting_thread = NULL;
  3127. return 0;
  3128. }
  3129. static int
  3130. pthread_cond_timedwait(pthread_cond_t *cv,
  3131. pthread_mutex_t *mutex,
  3132. const struct timespec *abstime)
  3133. {
  3134. struct mg_workerTLS **ptls,
  3135. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3136. int ok;
  3137. int64_t nsnow, nswaitabs, nswaitrel;
  3138. DWORD mswaitrel;
  3139. EnterCriticalSection(&cv->threadIdSec);
  3140. /* Add this thread to cv's waiting list */
  3141. ptls = &cv->waiting_thread;
  3142. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  3143. ;
  3144. tls->next_waiting_thread = NULL;
  3145. *ptls = tls;
  3146. LeaveCriticalSection(&cv->threadIdSec);
  3147. if (abstime) {
  3148. nsnow = mg_get_current_time_ns();
  3149. nswaitabs =
  3150. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  3151. nswaitrel = nswaitabs - nsnow;
  3152. if (nswaitrel < 0) {
  3153. nswaitrel = 0;
  3154. }
  3155. mswaitrel = (DWORD)(nswaitrel / 1000000);
  3156. } else {
  3157. mswaitrel = INFINITE;
  3158. }
  3159. pthread_mutex_unlock(mutex);
  3160. ok = (WAIT_OBJECT_0
  3161. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  3162. if (!ok) {
  3163. ok = 1;
  3164. EnterCriticalSection(&cv->threadIdSec);
  3165. ptls = &cv->waiting_thread;
  3166. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  3167. if (*ptls == tls) {
  3168. *ptls = tls->next_waiting_thread;
  3169. ok = 0;
  3170. break;
  3171. }
  3172. }
  3173. LeaveCriticalSection(&cv->threadIdSec);
  3174. if (ok) {
  3175. WaitForSingleObject(tls->pthread_cond_helper_mutex, INFINITE);
  3176. }
  3177. }
  3178. /* This thread has been removed from cv's waiting list */
  3179. pthread_mutex_lock(mutex);
  3180. return ok ? 0 : -1;
  3181. }
  3182. static int
  3183. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  3184. {
  3185. return pthread_cond_timedwait(cv, mutex, NULL);
  3186. }
  3187. static int
  3188. pthread_cond_signal(pthread_cond_t *cv)
  3189. {
  3190. HANDLE wkup = NULL;
  3191. BOOL ok = FALSE;
  3192. EnterCriticalSection(&cv->threadIdSec);
  3193. if (cv->waiting_thread) {
  3194. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  3195. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  3196. ok = SetEvent(wkup);
  3197. assert(ok);
  3198. }
  3199. LeaveCriticalSection(&cv->threadIdSec);
  3200. return ok ? 0 : 1;
  3201. }
  3202. static int
  3203. pthread_cond_broadcast(pthread_cond_t *cv)
  3204. {
  3205. EnterCriticalSection(&cv->threadIdSec);
  3206. while (cv->waiting_thread) {
  3207. pthread_cond_signal(cv);
  3208. }
  3209. LeaveCriticalSection(&cv->threadIdSec);
  3210. return 0;
  3211. }
  3212. static int
  3213. pthread_cond_destroy(pthread_cond_t *cv)
  3214. {
  3215. EnterCriticalSection(&cv->threadIdSec);
  3216. assert(cv->waiting_thread == NULL);
  3217. LeaveCriticalSection(&cv->threadIdSec);
  3218. DeleteCriticalSection(&cv->threadIdSec);
  3219. return 0;
  3220. }
  3221. #ifdef ALTERNATIVE_QUEUE
  3222. static void *
  3223. event_create(void)
  3224. {
  3225. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  3226. }
  3227. static int
  3228. event_wait(void *eventhdl)
  3229. {
  3230. int res = WaitForSingleObject((HANDLE)eventhdl, INFINITE);
  3231. return (res == WAIT_OBJECT_0);
  3232. }
  3233. static int
  3234. event_signal(void *eventhdl)
  3235. {
  3236. return (int)SetEvent((HANDLE)eventhdl);
  3237. }
  3238. static void
  3239. event_destroy(void *eventhdl)
  3240. {
  3241. CloseHandle((HANDLE)eventhdl);
  3242. }
  3243. #endif
  3244. #if defined(__MINGW32__)
  3245. /* Enable unused function warning again */
  3246. #pragma GCC diagnostic pop
  3247. #endif
  3248. /* For Windows, change all slashes to backslashes in path names. */
  3249. static void
  3250. change_slashes_to_backslashes(char *path)
  3251. {
  3252. int i;
  3253. for (i = 0; path[i] != '\0'; i++) {
  3254. if (path[i] == '/') {
  3255. path[i] = '\\';
  3256. }
  3257. /* remove double backslash (check i > 0 to preserve UNC paths,
  3258. * like \\server\file.txt) */
  3259. if ((path[i] == '\\') && (i > 0)) {
  3260. while (path[i + 1] == '\\' || path[i + 1] == '/') {
  3261. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  3262. }
  3263. }
  3264. }
  3265. }
  3266. static int
  3267. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  3268. {
  3269. int diff;
  3270. do {
  3271. diff = tolower(*s1) - tolower(*s2);
  3272. s1++;
  3273. s2++;
  3274. } while (diff == 0 && s1[-1] != '\0');
  3275. return diff;
  3276. }
  3277. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  3278. * wbuf and wbuf_len is a target buffer and its length. */
  3279. static void
  3280. path_to_unicode(const struct mg_connection *conn,
  3281. const char *path,
  3282. wchar_t *wbuf,
  3283. size_t wbuf_len)
  3284. {
  3285. char buf[PATH_MAX], buf2[PATH_MAX];
  3286. wchar_t wbuf2[MAX_PATH + 1];
  3287. DWORD long_len, err;
  3288. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  3289. mg_strlcpy(buf, path, sizeof(buf));
  3290. change_slashes_to_backslashes(buf);
  3291. /* Convert to Unicode and back. If doubly-converted string does not
  3292. * match the original, something is fishy, reject. */
  3293. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  3294. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  3295. WideCharToMultiByte(
  3296. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  3297. if (strcmp(buf, buf2) != 0) {
  3298. wbuf[0] = L'\0';
  3299. }
  3300. /* Windows file systems are not case sensitive, but you can still use
  3301. * uppercase and lowercase letters (on all modern file systems).
  3302. * The server can check if the URI uses the same upper/lowercase
  3303. * letters an the file system, effectively making Windows servers
  3304. * case sensitive (like Linux servers are). It is still not possible
  3305. * to use two files with the same name in different cases on Windows
  3306. * (like /a and /A) - this would be possible in Linux.
  3307. * As a default, Windows is not case sensitive, but the case sensitive
  3308. * file name check can be activated by an additional configuration. */
  3309. if (conn) {
  3310. if (conn->ctx->config[CASE_SENSITIVE_FILES]
  3311. && !mg_strcasecmp(conn->ctx->config[CASE_SENSITIVE_FILES], "yes")) {
  3312. /* Use case sensitive compare function */
  3313. fcompare = wcscmp;
  3314. }
  3315. }
  3316. (void)conn; /* conn is currently unused */
  3317. #if !defined(_WIN32_WCE)
  3318. /* Only accept a full file path, not a Windows short (8.3) path. */
  3319. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  3320. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  3321. if (long_len == 0) {
  3322. err = GetLastError();
  3323. if (err == ERROR_FILE_NOT_FOUND) {
  3324. /* File does not exist. This is not always a problem here. */
  3325. return;
  3326. }
  3327. }
  3328. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  3329. /* Short name is used. */
  3330. wbuf[0] = L'\0';
  3331. }
  3332. #else
  3333. (void)long_len;
  3334. (void)wbuf2;
  3335. (void)err;
  3336. if (strchr(path, '~')) {
  3337. wbuf[0] = L'\0';
  3338. }
  3339. #endif
  3340. }
  3341. /* Windows happily opens files with some garbage at the end of file name.
  3342. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  3343. * "a.cgi", despite one would expect an error back.
  3344. * This function returns non-0 if path ends with some garbage. */
  3345. static int
  3346. path_cannot_disclose_cgi(const char *path)
  3347. {
  3348. static const char *allowed_last_characters = "_-";
  3349. int last = path[strlen(path) - 1];
  3350. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  3351. }
  3352. static int
  3353. mg_stat(const struct mg_connection *conn,
  3354. const char *path,
  3355. struct mg_file_stat *filep)
  3356. {
  3357. wchar_t wbuf[PATH_MAX];
  3358. WIN32_FILE_ATTRIBUTE_DATA info;
  3359. time_t creation_time;
  3360. if (!filep) {
  3361. return 0;
  3362. }
  3363. memset(filep, 0, sizeof(*filep));
  3364. if (conn && is_file_in_memory(conn, path)) {
  3365. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  3366. * memset */
  3367. /* Quick fix (for 1.9.x): */
  3368. /* mg_stat must fill all fields, also for files in memory */
  3369. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  3370. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  3371. filep->size = tmp_file.stat.size;
  3372. filep->location = 2;
  3373. /* TODO: for 1.10: restructure how files in memory are handled */
  3374. /* The "file in memory" feature is a candidate for deletion.
  3375. * Please join the discussion at
  3376. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  3377. */
  3378. filep->last_modified = time(NULL); /* TODO */
  3379. /* last_modified = now ... assumes the file may change during runtime,
  3380. * so every mg_fopen call may return different data */
  3381. /* last_modified = conn->ctx.start_time;
  3382. * May be used it the data does not change during runtime. This allows
  3383. * browser caching. Since we do not know, we have to assume the file
  3384. * in memory may change. */
  3385. return 1;
  3386. }
  3387. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3388. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  3389. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  3390. filep->last_modified =
  3391. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  3392. info.ftLastWriteTime.dwHighDateTime);
  3393. /* On Windows, the file creation time can be higher than the
  3394. * modification time, e.g. when a file is copied.
  3395. * Since the Last-Modified timestamp is used for caching
  3396. * it should be based on the most recent timestamp. */
  3397. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  3398. info.ftCreationTime.dwHighDateTime);
  3399. if (creation_time > filep->last_modified) {
  3400. filep->last_modified = creation_time;
  3401. }
  3402. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  3403. /* If file name is fishy, reset the file structure and return
  3404. * error.
  3405. * Note it is important to reset, not just return the error, cause
  3406. * functions like is_file_opened() check the struct. */
  3407. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  3408. memset(filep, 0, sizeof(*filep));
  3409. return 0;
  3410. }
  3411. return 1;
  3412. }
  3413. return 0;
  3414. }
  3415. static int
  3416. mg_remove(const struct mg_connection *conn, const char *path)
  3417. {
  3418. wchar_t wbuf[PATH_MAX];
  3419. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3420. return DeleteFileW(wbuf) ? 0 : -1;
  3421. }
  3422. static int
  3423. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  3424. {
  3425. wchar_t wbuf[PATH_MAX];
  3426. (void)mode;
  3427. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3428. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  3429. }
  3430. /* Create substitutes for POSIX functions in Win32. */
  3431. #if defined(__MINGW32__)
  3432. /* Show no warning in case system functions are not used. */
  3433. #pragma GCC diagnostic push
  3434. #pragma GCC diagnostic ignored "-Wunused-function"
  3435. #endif
  3436. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  3437. static DIR *
  3438. mg_opendir(const struct mg_connection *conn, const char *name)
  3439. {
  3440. DIR *dir = NULL;
  3441. wchar_t wpath[PATH_MAX];
  3442. DWORD attrs;
  3443. if (name == NULL) {
  3444. SetLastError(ERROR_BAD_ARGUMENTS);
  3445. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  3446. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  3447. } else {
  3448. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  3449. attrs = GetFileAttributesW(wpath);
  3450. if (attrs != 0xFFFFFFFF && ((attrs & FILE_ATTRIBUTE_DIRECTORY)
  3451. == FILE_ATTRIBUTE_DIRECTORY)) {
  3452. (void)wcscat(wpath, L"\\*");
  3453. dir->handle = FindFirstFileW(wpath, &dir->info);
  3454. dir->result.d_name[0] = '\0';
  3455. } else {
  3456. mg_free(dir);
  3457. dir = NULL;
  3458. }
  3459. }
  3460. return dir;
  3461. }
  3462. static int
  3463. mg_closedir(DIR *dir)
  3464. {
  3465. int result = 0;
  3466. if (dir != NULL) {
  3467. if (dir->handle != INVALID_HANDLE_VALUE)
  3468. result = FindClose(dir->handle) ? 0 : -1;
  3469. mg_free(dir);
  3470. } else {
  3471. result = -1;
  3472. SetLastError(ERROR_BAD_ARGUMENTS);
  3473. }
  3474. return result;
  3475. }
  3476. static struct dirent *
  3477. mg_readdir(DIR *dir)
  3478. {
  3479. struct dirent *result = 0;
  3480. if (dir) {
  3481. if (dir->handle != INVALID_HANDLE_VALUE) {
  3482. result = &dir->result;
  3483. (void)WideCharToMultiByte(CP_UTF8,
  3484. 0,
  3485. dir->info.cFileName,
  3486. -1,
  3487. result->d_name,
  3488. sizeof(result->d_name),
  3489. NULL,
  3490. NULL);
  3491. if (!FindNextFileW(dir->handle, &dir->info)) {
  3492. (void)FindClose(dir->handle);
  3493. dir->handle = INVALID_HANDLE_VALUE;
  3494. }
  3495. } else {
  3496. SetLastError(ERROR_FILE_NOT_FOUND);
  3497. }
  3498. } else {
  3499. SetLastError(ERROR_BAD_ARGUMENTS);
  3500. }
  3501. return result;
  3502. }
  3503. #ifndef HAVE_POLL
  3504. static int
  3505. poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  3506. {
  3507. struct timeval tv;
  3508. fd_set set;
  3509. unsigned int i;
  3510. int result;
  3511. SOCKET maxfd = 0;
  3512. memset(&tv, 0, sizeof(tv));
  3513. tv.tv_sec = milliseconds / 1000;
  3514. tv.tv_usec = (milliseconds % 1000) * 1000;
  3515. FD_ZERO(&set);
  3516. for (i = 0; i < n; i++) {
  3517. FD_SET((SOCKET)pfd[i].fd, &set);
  3518. pfd[i].revents = 0;
  3519. if (pfd[i].fd > maxfd) {
  3520. maxfd = pfd[i].fd;
  3521. }
  3522. }
  3523. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  3524. for (i = 0; i < n; i++) {
  3525. if (FD_ISSET(pfd[i].fd, &set)) {
  3526. pfd[i].revents = POLLIN;
  3527. }
  3528. }
  3529. }
  3530. /* We should subtract the time used in select from remaining
  3531. * "milliseconds", in particular if called from mg_poll with a
  3532. * timeout quantum.
  3533. * Unfortunately, the remaining time is not stored in "tv" in all
  3534. * implementations, so the result in "tv" must be considered undefined.
  3535. * See http://man7.org/linux/man-pages/man2/select.2.html */
  3536. return result;
  3537. }
  3538. #endif /* HAVE_POLL */
  3539. #if defined(__MINGW32__)
  3540. /* Enable unused function warning again */
  3541. #pragma GCC diagnostic pop
  3542. #endif
  3543. static void
  3544. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  3545. {
  3546. (void)conn; /* Unused. */
  3547. #if defined(_WIN32_WCE)
  3548. (void)sock;
  3549. #else
  3550. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  3551. #endif
  3552. }
  3553. int
  3554. mg_start_thread(mg_thread_func_t f, void *p)
  3555. {
  3556. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3557. /* Compile-time option to control stack size, e.g. -DUSE_STACK_SIZE=16384
  3558. */
  3559. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  3560. == ((uintptr_t)(-1L)))
  3561. ? -1
  3562. : 0);
  3563. #else
  3564. return (
  3565. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  3566. ? -1
  3567. : 0);
  3568. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3569. }
  3570. /* Start a thread storing the thread context. */
  3571. static int
  3572. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  3573. void *p,
  3574. pthread_t *threadidptr)
  3575. {
  3576. uintptr_t uip;
  3577. HANDLE threadhandle;
  3578. int result = -1;
  3579. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  3580. threadhandle = (HANDLE)uip;
  3581. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  3582. *threadidptr = threadhandle;
  3583. result = 0;
  3584. }
  3585. return result;
  3586. }
  3587. /* Wait for a thread to finish. */
  3588. static int
  3589. mg_join_thread(pthread_t threadid)
  3590. {
  3591. int result;
  3592. DWORD dwevent;
  3593. result = -1;
  3594. dwevent = WaitForSingleObject(threadid, INFINITE);
  3595. if (dwevent == WAIT_FAILED) {
  3596. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  3597. } else {
  3598. if (dwevent == WAIT_OBJECT_0) {
  3599. CloseHandle(threadid);
  3600. result = 0;
  3601. }
  3602. }
  3603. return result;
  3604. }
  3605. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  3606. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  3607. /* Create substitutes for POSIX functions in Win32. */
  3608. #if defined(__MINGW32__)
  3609. /* Show no warning in case system functions are not used. */
  3610. #pragma GCC diagnostic push
  3611. #pragma GCC diagnostic ignored "-Wunused-function"
  3612. #endif
  3613. static HANDLE
  3614. dlopen(const char *dll_name, int flags)
  3615. {
  3616. wchar_t wbuf[PATH_MAX];
  3617. (void)flags;
  3618. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  3619. return LoadLibraryW(wbuf);
  3620. }
  3621. static int
  3622. dlclose(void *handle)
  3623. {
  3624. int result;
  3625. if (FreeLibrary((HMODULE)handle) != 0) {
  3626. result = 0;
  3627. } else {
  3628. result = -1;
  3629. }
  3630. return result;
  3631. }
  3632. #if defined(__MINGW32__)
  3633. /* Enable unused function warning again */
  3634. #pragma GCC diagnostic pop
  3635. #endif
  3636. #endif
  3637. #if !defined(NO_CGI)
  3638. #define SIGKILL (0)
  3639. static int
  3640. kill(pid_t pid, int sig_num)
  3641. {
  3642. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  3643. (void)CloseHandle((HANDLE)pid);
  3644. return 0;
  3645. }
  3646. static void
  3647. trim_trailing_whitespaces(char *s)
  3648. {
  3649. char *e = s + strlen(s) - 1;
  3650. while (e > s && isspace(*(unsigned char *)e)) {
  3651. *e-- = '\0';
  3652. }
  3653. }
  3654. static pid_t
  3655. spawn_process(struct mg_connection *conn,
  3656. const char *prog,
  3657. char *envblk,
  3658. char *envp[],
  3659. int fdin[2],
  3660. int fdout[2],
  3661. int fderr[2],
  3662. const char *dir)
  3663. {
  3664. HANDLE me;
  3665. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  3666. cmdline[PATH_MAX], buf[PATH_MAX];
  3667. int truncated;
  3668. struct mg_file file = STRUCT_FILE_INITIALIZER;
  3669. STARTUPINFOA si;
  3670. PROCESS_INFORMATION pi = {0};
  3671. (void)envp;
  3672. memset(&si, 0, sizeof(si));
  3673. si.cb = sizeof(si);
  3674. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  3675. si.wShowWindow = SW_HIDE;
  3676. me = GetCurrentProcess();
  3677. DuplicateHandle(me,
  3678. (HANDLE)_get_osfhandle(fdin[0]),
  3679. me,
  3680. &si.hStdInput,
  3681. 0,
  3682. TRUE,
  3683. DUPLICATE_SAME_ACCESS);
  3684. DuplicateHandle(me,
  3685. (HANDLE)_get_osfhandle(fdout[1]),
  3686. me,
  3687. &si.hStdOutput,
  3688. 0,
  3689. TRUE,
  3690. DUPLICATE_SAME_ACCESS);
  3691. DuplicateHandle(me,
  3692. (HANDLE)_get_osfhandle(fderr[1]),
  3693. me,
  3694. &si.hStdError,
  3695. 0,
  3696. TRUE,
  3697. DUPLICATE_SAME_ACCESS);
  3698. /* Mark handles that should not be inherited. See
  3699. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  3700. */
  3701. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  3702. HANDLE_FLAG_INHERIT,
  3703. 0);
  3704. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  3705. HANDLE_FLAG_INHERIT,
  3706. 0);
  3707. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  3708. HANDLE_FLAG_INHERIT,
  3709. 0);
  3710. /* If CGI file is a script, try to read the interpreter line */
  3711. interp = conn->ctx->config[CGI_INTERPRETER];
  3712. if (interp == NULL) {
  3713. buf[0] = buf[1] = '\0';
  3714. /* Read the first line of the script into the buffer */
  3715. mg_snprintf(
  3716. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  3717. if (truncated) {
  3718. pi.hProcess = (pid_t)-1;
  3719. goto spawn_cleanup;
  3720. }
  3721. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  3722. p = (char *)file.access.membuf;
  3723. mg_fgets(buf, sizeof(buf), &file, &p);
  3724. (void)mg_fclose(&file.access); /* ignore error on read only file */
  3725. buf[sizeof(buf) - 1] = '\0';
  3726. }
  3727. if (buf[0] == '#' && buf[1] == '!') {
  3728. trim_trailing_whitespaces(buf + 2);
  3729. } else {
  3730. buf[2] = '\0';
  3731. }
  3732. interp = buf + 2;
  3733. }
  3734. if (interp[0] != '\0') {
  3735. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  3736. interp = full_interp;
  3737. }
  3738. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  3739. if (interp[0] != '\0') {
  3740. mg_snprintf(conn,
  3741. &truncated,
  3742. cmdline,
  3743. sizeof(cmdline),
  3744. "\"%s\" \"%s\\%s\"",
  3745. interp,
  3746. full_dir,
  3747. prog);
  3748. } else {
  3749. mg_snprintf(conn,
  3750. &truncated,
  3751. cmdline,
  3752. sizeof(cmdline),
  3753. "\"%s\\%s\"",
  3754. full_dir,
  3755. prog);
  3756. }
  3757. if (truncated) {
  3758. pi.hProcess = (pid_t)-1;
  3759. goto spawn_cleanup;
  3760. }
  3761. DEBUG_TRACE("Running [%s]", cmdline);
  3762. if (CreateProcessA(NULL,
  3763. cmdline,
  3764. NULL,
  3765. NULL,
  3766. TRUE,
  3767. CREATE_NEW_PROCESS_GROUP,
  3768. envblk,
  3769. NULL,
  3770. &si,
  3771. &pi) == 0) {
  3772. mg_cry(
  3773. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  3774. pi.hProcess = (pid_t)-1;
  3775. /* goto spawn_cleanup; */
  3776. }
  3777. spawn_cleanup:
  3778. (void)CloseHandle(si.hStdOutput);
  3779. (void)CloseHandle(si.hStdError);
  3780. (void)CloseHandle(si.hStdInput);
  3781. if (pi.hThread != NULL) {
  3782. (void)CloseHandle(pi.hThread);
  3783. }
  3784. return (pid_t)pi.hProcess;
  3785. }
  3786. #endif /* !NO_CGI */
  3787. static int
  3788. set_blocking_mode(SOCKET sock, int blocking)
  3789. {
  3790. unsigned long non_blocking = !blocking;
  3791. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  3792. }
  3793. #else
  3794. static int
  3795. mg_stat(const struct mg_connection *conn,
  3796. const char *path,
  3797. struct mg_file_stat *filep)
  3798. {
  3799. struct stat st;
  3800. if (!filep) {
  3801. return 0;
  3802. }
  3803. memset(filep, 0, sizeof(*filep));
  3804. if (conn && is_file_in_memory(conn, path)) {
  3805. /* Quick fix (for 1.9.x): */
  3806. /* mg_stat must fill all fields, also for files in memory */
  3807. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  3808. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  3809. filep->size = tmp_file.stat.size;
  3810. filep->last_modified = time(NULL);
  3811. filep->location = 2;
  3812. /* TODO: for 1.10: restructure how files in memory are handled */
  3813. return 1;
  3814. }
  3815. if (0 == stat(path, &st)) {
  3816. filep->size = (uint64_t)(st.st_size);
  3817. filep->last_modified = st.st_mtime;
  3818. filep->is_directory = S_ISDIR(st.st_mode);
  3819. return 1;
  3820. }
  3821. return 0;
  3822. }
  3823. static void
  3824. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  3825. {
  3826. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  3827. if (conn) {
  3828. mg_cry(conn,
  3829. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  3830. __func__,
  3831. strerror(ERRNO));
  3832. }
  3833. }
  3834. }
  3835. int
  3836. mg_start_thread(mg_thread_func_t func, void *param)
  3837. {
  3838. pthread_t thread_id;
  3839. pthread_attr_t attr;
  3840. int result;
  3841. (void)pthread_attr_init(&attr);
  3842. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  3843. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3844. /* Compile-time option to control stack size,
  3845. * e.g. -DUSE_STACK_SIZE=16384 */
  3846. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3847. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3848. result = pthread_create(&thread_id, &attr, func, param);
  3849. pthread_attr_destroy(&attr);
  3850. return result;
  3851. }
  3852. /* Start a thread storing the thread context. */
  3853. static int
  3854. mg_start_thread_with_id(mg_thread_func_t func,
  3855. void *param,
  3856. pthread_t *threadidptr)
  3857. {
  3858. pthread_t thread_id;
  3859. pthread_attr_t attr;
  3860. int result;
  3861. (void)pthread_attr_init(&attr);
  3862. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3863. /* Compile-time option to control stack size,
  3864. * e.g. -DUSE_STACK_SIZE=16384 */
  3865. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3866. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  3867. result = pthread_create(&thread_id, &attr, func, param);
  3868. pthread_attr_destroy(&attr);
  3869. if ((result == 0) && (threadidptr != NULL)) {
  3870. *threadidptr = thread_id;
  3871. }
  3872. return result;
  3873. }
  3874. /* Wait for a thread to finish. */
  3875. static int
  3876. mg_join_thread(pthread_t threadid)
  3877. {
  3878. int result;
  3879. result = pthread_join(threadid, NULL);
  3880. return result;
  3881. }
  3882. #ifndef NO_CGI
  3883. static pid_t
  3884. spawn_process(struct mg_connection *conn,
  3885. const char *prog,
  3886. char *envblk,
  3887. char *envp[],
  3888. int fdin[2],
  3889. int fdout[2],
  3890. int fderr[2],
  3891. const char *dir)
  3892. {
  3893. pid_t pid;
  3894. const char *interp;
  3895. (void)envblk;
  3896. if (conn == NULL) {
  3897. return 0;
  3898. }
  3899. if ((pid = fork()) == -1) {
  3900. /* Parent */
  3901. mg_send_http_error(conn,
  3902. 500,
  3903. "Error: Creating CGI process\nfork(): %s",
  3904. strerror(ERRNO));
  3905. } else if (pid == 0) {
  3906. /* Child */
  3907. if (chdir(dir) != 0) {
  3908. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  3909. } else if (dup2(fdin[0], 0) == -1) {
  3910. mg_cry(conn,
  3911. "%s: dup2(%d, 0): %s",
  3912. __func__,
  3913. fdin[0],
  3914. strerror(ERRNO));
  3915. } else if (dup2(fdout[1], 1) == -1) {
  3916. mg_cry(conn,
  3917. "%s: dup2(%d, 1): %s",
  3918. __func__,
  3919. fdout[1],
  3920. strerror(ERRNO));
  3921. } else if (dup2(fderr[1], 2) == -1) {
  3922. mg_cry(conn,
  3923. "%s: dup2(%d, 2): %s",
  3924. __func__,
  3925. fderr[1],
  3926. strerror(ERRNO));
  3927. } else {
  3928. /* Keep stderr and stdout in two different pipes.
  3929. * Stdout will be sent back to the client,
  3930. * stderr should go into a server error log. */
  3931. (void)close(fdin[0]);
  3932. (void)close(fdout[1]);
  3933. (void)close(fderr[1]);
  3934. /* Close write end fdin and read end fdout and fderr */
  3935. (void)close(fdin[1]);
  3936. (void)close(fdout[0]);
  3937. (void)close(fderr[0]);
  3938. /* After exec, all signal handlers are restored to their default
  3939. * values, with one exception of SIGCHLD. According to
  3940. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler will
  3941. * leave unchanged after exec if it was set to be ignored. Restore
  3942. * it to default action. */
  3943. signal(SIGCHLD, SIG_DFL);
  3944. interp = conn->ctx->config[CGI_INTERPRETER];
  3945. if (interp == NULL) {
  3946. (void)execle(prog, prog, NULL, envp);
  3947. mg_cry(conn,
  3948. "%s: execle(%s): %s",
  3949. __func__,
  3950. prog,
  3951. strerror(ERRNO));
  3952. } else {
  3953. (void)execle(interp, interp, prog, NULL, envp);
  3954. mg_cry(conn,
  3955. "%s: execle(%s %s): %s",
  3956. __func__,
  3957. interp,
  3958. prog,
  3959. strerror(ERRNO));
  3960. }
  3961. }
  3962. exit(EXIT_FAILURE);
  3963. }
  3964. return pid;
  3965. }
  3966. #endif /* !NO_CGI */
  3967. static int
  3968. set_blocking_mode(SOCKET sock, int blocking)
  3969. {
  3970. int flags;
  3971. flags = fcntl(sock, F_GETFL, 0);
  3972. if (blocking) {
  3973. (void)fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  3974. } else {
  3975. (void)fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK)));
  3976. }
  3977. return 0;
  3978. }
  3979. #endif /* _WIN32 */
  3980. /* End of initial operating system specific define block. */
  3981. /* Get a random number (independent of C rand function) */
  3982. static uint64_t
  3983. get_random(void)
  3984. {
  3985. static uint64_t lfsr = 0; /* Linear feedback shift register */
  3986. static uint64_t lcg = 0; /* Linear congruential generator */
  3987. uint64_t now = mg_get_current_time_ns();
  3988. if (lfsr == 0) {
  3989. /* lfsr will be only 0 if has not been initialized,
  3990. * so this code is called only once. */
  3991. lfsr = mg_get_current_time_ns();
  3992. lcg = mg_get_current_time_ns();
  3993. } else {
  3994. /* Get the next step of both random number generators. */
  3995. lfsr = (lfsr >> 1)
  3996. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  3997. << 63);
  3998. lcg = lcg * 6364136223846793005 + 1442695040888963407;
  3999. }
  4000. /* Combining two pseudo-random number generators and a high resolution part
  4001. * of the current server time will make it hard (impossible?) to guess the
  4002. * next number. */
  4003. return (lfsr ^ lcg ^ now);
  4004. }
  4005. static int
  4006. mg_poll(struct pollfd *pfd,
  4007. unsigned int n,
  4008. int milliseconds,
  4009. volatile int *stop_server)
  4010. {
  4011. int ms_now, result;
  4012. /* Call poll, but only for a maximum time of a few seconds.
  4013. * This will allow to stop the server after some seconds, instead
  4014. * of having to wait for a long socket timeout. */
  4015. ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  4016. do {
  4017. if (*stop_server) {
  4018. /* Shut down signal */
  4019. return -2;
  4020. }
  4021. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  4022. ms_now = milliseconds;
  4023. }
  4024. result = poll(pfd, n, ms_now);
  4025. if (result != 0) {
  4026. /* Poll returned either success (1) or error (-1).
  4027. * Forward both to the caller. */
  4028. return result;
  4029. }
  4030. /* Poll returned timeout (0). */
  4031. if (milliseconds > 0) {
  4032. milliseconds -= ms_now;
  4033. }
  4034. } while (milliseconds != 0);
  4035. return result;
  4036. }
  4037. /* Write data to the IO channel - opened file descriptor, socket or SSL
  4038. * descriptor. Return number of bytes written. */
  4039. static int
  4040. push(struct mg_context *ctx,
  4041. FILE *fp,
  4042. SOCKET sock,
  4043. SSL *ssl,
  4044. const char *buf,
  4045. int len,
  4046. double timeout)
  4047. {
  4048. uint64_t start = 0, now = 0, timeout_ns = 0;
  4049. int n, err;
  4050. #ifdef _WIN32
  4051. typedef int len_t;
  4052. #else
  4053. typedef size_t len_t;
  4054. #endif
  4055. if (timeout > 0) {
  4056. start = mg_get_current_time_ns();
  4057. timeout_ns = (uint64_t)(timeout * 1.0E9);
  4058. }
  4059. if (ctx == NULL) {
  4060. return -1;
  4061. }
  4062. #ifdef NO_SSL
  4063. if (ssl) {
  4064. return -1;
  4065. }
  4066. #endif
  4067. do {
  4068. #ifndef NO_SSL
  4069. if (ssl != NULL) {
  4070. n = SSL_write(ssl, buf, len);
  4071. if (n <= 0) {
  4072. err = SSL_get_error(ssl, n);
  4073. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  4074. err = ERRNO;
  4075. } else if ((err == SSL_ERROR_WANT_READ)
  4076. || (err == SSL_ERROR_WANT_WRITE)) {
  4077. n = 0;
  4078. } else {
  4079. DEBUG_TRACE("SSL_write() failed, error %d", err);
  4080. return -1;
  4081. }
  4082. } else {
  4083. err = 0;
  4084. }
  4085. } else
  4086. #endif
  4087. if (fp != NULL) {
  4088. n = (int)fwrite(buf, 1, (size_t)len, fp);
  4089. if (ferror(fp)) {
  4090. n = -1;
  4091. err = ERRNO;
  4092. } else {
  4093. err = 0;
  4094. }
  4095. } else {
  4096. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  4097. err = (n < 0) ? ERRNO : 0;
  4098. #ifdef _WIN32
  4099. if (err == WSAEWOULDBLOCK) {
  4100. err = 0;
  4101. n = 0;
  4102. }
  4103. #else
  4104. if (err == EWOULDBLOCK) {
  4105. err = 0;
  4106. n = 0;
  4107. }
  4108. #endif
  4109. if (n < 0) {
  4110. /* shutdown of the socket at client side */
  4111. return -1;
  4112. }
  4113. }
  4114. if (ctx->stop_flag) {
  4115. return -1;
  4116. }
  4117. if ((n > 0) || (n == 0 && len == 0)) {
  4118. /* some data has been read, or no data was requested */
  4119. return n;
  4120. }
  4121. if (n < 0) {
  4122. /* socket error - check errno */
  4123. DEBUG_TRACE("send() failed, error %d", err);
  4124. /* TODO (mid): error handling depending on the error code.
  4125. * These codes are different between Windows and Linux.
  4126. * Currently there is no problem with failing send calls,
  4127. * if there is a reproducible situation, it should be
  4128. * investigated in detail.
  4129. */
  4130. return -1;
  4131. }
  4132. /* Only in case n=0 (timeout), repeat calling the write function */
  4133. if (timeout >= 0) {
  4134. now = mg_get_current_time_ns();
  4135. }
  4136. } while ((timeout <= 0) || ((now - start) <= timeout_ns));
  4137. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  4138. used */
  4139. return -1;
  4140. }
  4141. static int64_t
  4142. push_all(struct mg_context *ctx,
  4143. FILE *fp,
  4144. SOCKET sock,
  4145. SSL *ssl,
  4146. const char *buf,
  4147. int64_t len)
  4148. {
  4149. double timeout = -1.0;
  4150. int64_t n, nwritten = 0;
  4151. if (ctx == NULL) {
  4152. return -1;
  4153. }
  4154. if (ctx->config[REQUEST_TIMEOUT]) {
  4155. timeout = atoi(ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  4156. }
  4157. while (len > 0 && ctx->stop_flag == 0) {
  4158. n = push(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  4159. if (n < 0) {
  4160. if (nwritten == 0) {
  4161. nwritten = n; /* Propagate the error */
  4162. }
  4163. break;
  4164. } else if (n == 0) {
  4165. break; /* No more data to write */
  4166. } else {
  4167. nwritten += n;
  4168. len -= n;
  4169. }
  4170. }
  4171. return nwritten;
  4172. }
  4173. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  4174. * Return value:
  4175. * >=0 .. number of bytes successfully read
  4176. * -1 .. timeout
  4177. * -2 .. error
  4178. */
  4179. static int
  4180. pull_inner(FILE *fp,
  4181. struct mg_connection *conn,
  4182. char *buf,
  4183. int len,
  4184. double timeout)
  4185. {
  4186. int nread, err = 0;
  4187. #ifdef _WIN32
  4188. typedef int len_t;
  4189. #else
  4190. typedef size_t len_t;
  4191. #endif
  4192. #ifndef NO_SSL
  4193. int ssl_pending;
  4194. #endif
  4195. /* We need an additional wait loop around this, because in some cases
  4196. * with TLSwe may get data from the socket but not from SSL_read.
  4197. * In this case we need to repeat at least once.
  4198. */
  4199. if (fp != NULL) {
  4200. #if !defined(_WIN32_WCE)
  4201. /* Use read() instead of fread(), because if we're reading from the
  4202. * CGI pipe, fread() may block until IO buffer is filled up. We
  4203. * cannot afford to block and must pass all read bytes immediately
  4204. * to the client. */
  4205. nread = (int)read(fileno(fp), buf, (size_t)len);
  4206. #else
  4207. /* WinCE does not support CGI pipes */
  4208. nread = (int)fread(buf, 1, (size_t)len, fp);
  4209. #endif
  4210. err = (nread < 0) ? ERRNO : 0;
  4211. #ifndef NO_SSL
  4212. } else if ((conn->ssl != NULL)
  4213. && ((ssl_pending = SSL_pending(conn->ssl)) > 0)) {
  4214. /* We already know there is no more data buffered in conn->buf
  4215. * but there is more available in the SSL layer. So don't poll
  4216. * conn->client.sock yet. */
  4217. if (ssl_pending > len) {
  4218. ssl_pending = len;
  4219. }
  4220. nread = SSL_read(conn->ssl, buf, ssl_pending);
  4221. if (nread <= 0) {
  4222. err = SSL_get_error(conn->ssl, nread);
  4223. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  4224. err = ERRNO;
  4225. } else if ((err == SSL_ERROR_WANT_READ)
  4226. || (err == SSL_ERROR_WANT_WRITE)) {
  4227. nread = 0;
  4228. } else {
  4229. DEBUG_TRACE("SSL_read() failed, error %d", err);
  4230. return -1;
  4231. }
  4232. } else {
  4233. err = 0;
  4234. }
  4235. } else if (conn->ssl != NULL) {
  4236. struct pollfd pfd[1];
  4237. int pollres;
  4238. pfd[0].fd = conn->client.sock;
  4239. pfd[0].events = POLLIN;
  4240. pollres =
  4241. mg_poll(pfd, 1, (int)(timeout * 1000.0), &(conn->ctx->stop_flag));
  4242. if (conn->ctx->stop_flag) {
  4243. return -2;
  4244. }
  4245. if (pollres > 0) {
  4246. nread = SSL_read(conn->ssl, buf, len);
  4247. if (nread <= 0) {
  4248. err = SSL_get_error(conn->ssl, nread);
  4249. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  4250. err = ERRNO;
  4251. } else if ((err == SSL_ERROR_WANT_READ)
  4252. || (err == SSL_ERROR_WANT_WRITE)) {
  4253. nread = 0;
  4254. } else {
  4255. DEBUG_TRACE("SSL_read() failed, error %d", err);
  4256. return -2;
  4257. }
  4258. } else {
  4259. err = 0;
  4260. }
  4261. } else if (pollres < 0) {
  4262. /* Error */
  4263. return -2;
  4264. } else {
  4265. /* pollres = 0 means timeout */
  4266. nread = 0;
  4267. }
  4268. #endif
  4269. } else {
  4270. struct pollfd pfd[1];
  4271. int pollres;
  4272. pfd[0].fd = conn->client.sock;
  4273. pfd[0].events = POLLIN;
  4274. pollres =
  4275. mg_poll(pfd, 1, (int)(timeout * 1000.0), &(conn->ctx->stop_flag));
  4276. if (conn->ctx->stop_flag) {
  4277. return -2;
  4278. }
  4279. if (pollres > 0) {
  4280. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  4281. err = (nread < 0) ? ERRNO : 0;
  4282. if (nread <= 0) {
  4283. /* shutdown of the socket at client side */
  4284. return -2;
  4285. }
  4286. } else if (pollres < 0) {
  4287. /* error callint poll */
  4288. return -2;
  4289. } else {
  4290. /* pollres = 0 means timeout */
  4291. nread = 0;
  4292. }
  4293. }
  4294. if (conn->ctx->stop_flag) {
  4295. return -2;
  4296. }
  4297. if ((nread > 0) || (nread == 0 && len == 0)) {
  4298. /* some data has been read, or no data was requested */
  4299. return nread;
  4300. }
  4301. if (nread < 0) {
  4302. /* socket error - check errno */
  4303. #ifdef _WIN32
  4304. if (err == WSAEWOULDBLOCK) {
  4305. /* TODO (low): check if this is still required */
  4306. /* standard case if called from close_socket_gracefully */
  4307. return -2;
  4308. } else if (err == WSAETIMEDOUT) {
  4309. /* TODO (low): check if this is still required */
  4310. /* timeout is handled by the while loop */
  4311. return 0;
  4312. } else if (err == WSAECONNABORTED) {
  4313. /* See https://www.chilkatsoft.com/p/p_299.asp */
  4314. return -2;
  4315. } else {
  4316. DEBUG_TRACE("recv() failed, error %d", err);
  4317. return -2;
  4318. }
  4319. #else
  4320. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  4321. * if the timeout is reached and if the socket was set to non-
  4322. * blocking in close_socket_gracefully, so we can not distinguish
  4323. * here. We have to wait for the timeout in both cases for now.
  4324. */
  4325. if (err == EAGAIN || err == EWOULDBLOCK || err == EINTR) {
  4326. /* TODO (low): check if this is still required */
  4327. /* EAGAIN/EWOULDBLOCK:
  4328. * standard case if called from close_socket_gracefully
  4329. * => should return -1 */
  4330. /* or timeout occured
  4331. * => the code must stay in the while loop */
  4332. /* EINTR can be generated on a socket with a timeout set even
  4333. * when SA_RESTART is effective for all relevant signals
  4334. * (see signal(7)).
  4335. * => stay in the while loop */
  4336. } else {
  4337. DEBUG_TRACE("recv() failed, error %d", err);
  4338. return -2;
  4339. }
  4340. #endif
  4341. }
  4342. /* Timeout occured, but no data available. */
  4343. return -1;
  4344. }
  4345. static int
  4346. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  4347. {
  4348. int n, nread = 0;
  4349. double timeout = -1.0;
  4350. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  4351. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  4352. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  4353. }
  4354. if (timeout >= 0.0) {
  4355. start_time = mg_get_current_time_ns();
  4356. timeout_ns = (uint64_t)(timeout * 1.0E9);
  4357. }
  4358. while (len > 0 && conn->ctx->stop_flag == 0) {
  4359. n = pull_inner(fp, conn, buf + nread, len, timeout);
  4360. if (n == -2) {
  4361. if (nread == 0) {
  4362. nread = -1; /* Propagate the error */
  4363. }
  4364. break;
  4365. } else if (n == -1) {
  4366. /* timeout */
  4367. if (timeout >= 0.0) {
  4368. now = mg_get_current_time_ns();
  4369. if ((now - start_time) <= timeout_ns) {
  4370. continue;
  4371. }
  4372. }
  4373. break;
  4374. } else if (n == 0) {
  4375. break; /* No more data to read */
  4376. } else {
  4377. conn->consumed_content += n;
  4378. nread += n;
  4379. len -= n;
  4380. }
  4381. }
  4382. return nread;
  4383. }
  4384. static void
  4385. discard_unread_request_data(struct mg_connection *conn)
  4386. {
  4387. char buf[MG_BUF_LEN];
  4388. size_t to_read;
  4389. int nread;
  4390. if (conn == NULL) {
  4391. return;
  4392. }
  4393. to_read = sizeof(buf);
  4394. if (conn->is_chunked) {
  4395. /* Chunked encoding: 1=chunk not read completely, 2=chunk read
  4396. * completely */
  4397. while (conn->is_chunked == 1) {
  4398. nread = mg_read(conn, buf, to_read);
  4399. if (nread <= 0) {
  4400. break;
  4401. }
  4402. }
  4403. } else {
  4404. /* Not chunked: content length is known */
  4405. while (conn->consumed_content < conn->content_len) {
  4406. if (to_read
  4407. > (size_t)(conn->content_len - conn->consumed_content)) {
  4408. to_read = (size_t)(conn->content_len - conn->consumed_content);
  4409. }
  4410. nread = mg_read(conn, buf, to_read);
  4411. if (nread <= 0) {
  4412. break;
  4413. }
  4414. }
  4415. }
  4416. }
  4417. static int
  4418. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  4419. {
  4420. int64_t n, buffered_len, nread;
  4421. int64_t len64 =
  4422. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  4423. * int, we may not read more
  4424. * bytes */
  4425. const char *body;
  4426. if (conn == NULL) {
  4427. return 0;
  4428. }
  4429. /* If Content-Length is not set for a PUT or POST request, read until
  4430. * socket is closed */
  4431. if (conn->consumed_content == 0 && conn->content_len == -1) {
  4432. conn->content_len = INT64_MAX;
  4433. conn->must_close = 1;
  4434. }
  4435. nread = 0;
  4436. if (conn->consumed_content < conn->content_len) {
  4437. /* Adjust number of bytes to read. */
  4438. int64_t left_to_read = conn->content_len - conn->consumed_content;
  4439. if (left_to_read < len64) {
  4440. /* Do not read more than the total content length of the request.
  4441. */
  4442. len64 = left_to_read;
  4443. }
  4444. /* Return buffered data */
  4445. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  4446. - conn->consumed_content;
  4447. if (buffered_len > 0) {
  4448. if (len64 < buffered_len) {
  4449. buffered_len = len64;
  4450. }
  4451. body = conn->buf + conn->request_len + conn->consumed_content;
  4452. memcpy(buf, body, (size_t)buffered_len);
  4453. len64 -= buffered_len;
  4454. conn->consumed_content += buffered_len;
  4455. nread += buffered_len;
  4456. buf = (char *)buf + buffered_len;
  4457. }
  4458. /* We have returned all buffered data. Read new data from the remote
  4459. * socket.
  4460. */
  4461. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  4462. nread += n;
  4463. } else {
  4464. nread = ((nread > 0) ? nread : n);
  4465. }
  4466. }
  4467. return (int)nread;
  4468. }
  4469. static char
  4470. mg_getc(struct mg_connection *conn)
  4471. {
  4472. char c;
  4473. if (conn == NULL) {
  4474. return 0;
  4475. }
  4476. conn->content_len++;
  4477. if (mg_read_inner(conn, &c, 1) <= 0) {
  4478. return (char)0;
  4479. }
  4480. return c;
  4481. }
  4482. int
  4483. mg_read(struct mg_connection *conn, void *buf, size_t len)
  4484. {
  4485. if (len > INT_MAX) {
  4486. len = INT_MAX;
  4487. }
  4488. if (conn == NULL) {
  4489. return 0;
  4490. }
  4491. if (conn->is_chunked) {
  4492. size_t all_read = 0;
  4493. while (len > 0) {
  4494. if (conn->is_chunked == 2) {
  4495. /* No more data left to read */
  4496. return 0;
  4497. }
  4498. if (conn->chunk_remainder) {
  4499. /* copy from the remainder of the last received chunk */
  4500. long read_ret;
  4501. size_t read_now =
  4502. ((conn->chunk_remainder > len) ? (len)
  4503. : (conn->chunk_remainder));
  4504. conn->content_len += (int)read_now;
  4505. read_ret =
  4506. mg_read_inner(conn, (char *)buf + all_read, read_now);
  4507. if (read_ret < 1) {
  4508. /* read error */
  4509. return -1;
  4510. }
  4511. all_read += (size_t)read_ret;
  4512. conn->chunk_remainder -= (size_t)read_ret;
  4513. len -= (size_t)read_ret;
  4514. if (conn->chunk_remainder == 0) {
  4515. /* Add data bytes in the current chunk have been read,
  4516. * so we are expecting \r\n now. */
  4517. char x1 = mg_getc(conn);
  4518. char x2 = mg_getc(conn);
  4519. if ((x1 != '\r') || (x2 != '\n')) {
  4520. /* Protocol violation */
  4521. return -1;
  4522. }
  4523. }
  4524. } else {
  4525. /* fetch a new chunk */
  4526. int i = 0;
  4527. char lenbuf[64];
  4528. char *end = 0;
  4529. unsigned long chunkSize = 0;
  4530. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  4531. lenbuf[i] = mg_getc(conn);
  4532. if (i > 0 && lenbuf[i] == '\r' && lenbuf[i - 1] != '\r') {
  4533. continue;
  4534. }
  4535. if (i > 1 && lenbuf[i] == '\n' && lenbuf[i - 1] == '\r') {
  4536. lenbuf[i + 1] = 0;
  4537. chunkSize = strtoul(lenbuf, &end, 16);
  4538. if (chunkSize == 0) {
  4539. /* regular end of content */
  4540. conn->is_chunked = 2;
  4541. }
  4542. break;
  4543. }
  4544. if (!isxdigit(lenbuf[i])) {
  4545. /* illegal character for chunk length */
  4546. return -1;
  4547. }
  4548. }
  4549. if ((end == NULL) || (*end != '\r')) {
  4550. /* chunksize not set correctly */
  4551. return -1;
  4552. }
  4553. if (chunkSize == 0) {
  4554. break;
  4555. }
  4556. conn->chunk_remainder = chunkSize;
  4557. }
  4558. }
  4559. return (int)all_read;
  4560. }
  4561. return mg_read_inner(conn, buf, len);
  4562. }
  4563. int
  4564. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  4565. {
  4566. time_t now;
  4567. int64_t n, total, allowed;
  4568. if (conn == NULL) {
  4569. return 0;
  4570. }
  4571. if (conn->throttle > 0) {
  4572. if ((now = time(NULL)) != conn->last_throttle_time) {
  4573. conn->last_throttle_time = now;
  4574. conn->last_throttle_bytes = 0;
  4575. }
  4576. allowed = conn->throttle - conn->last_throttle_bytes;
  4577. if (allowed > (int64_t)len) {
  4578. allowed = (int64_t)len;
  4579. }
  4580. if ((total = push_all(conn->ctx,
  4581. NULL,
  4582. conn->client.sock,
  4583. conn->ssl,
  4584. (const char *)buf,
  4585. (int64_t)allowed)) == allowed) {
  4586. buf = (const char *)buf + total;
  4587. conn->last_throttle_bytes += total;
  4588. while (total < (int64_t)len && conn->ctx->stop_flag == 0) {
  4589. allowed = (conn->throttle > ((int64_t)len - total))
  4590. ? (int64_t)len - total
  4591. : conn->throttle;
  4592. if ((n = push_all(conn->ctx,
  4593. NULL,
  4594. conn->client.sock,
  4595. conn->ssl,
  4596. (const char *)buf,
  4597. (int64_t)allowed)) != allowed) {
  4598. break;
  4599. }
  4600. sleep(1);
  4601. conn->last_throttle_bytes = allowed;
  4602. conn->last_throttle_time = time(NULL);
  4603. buf = (const char *)buf + n;
  4604. total += n;
  4605. }
  4606. }
  4607. } else {
  4608. total = push_all(conn->ctx,
  4609. NULL,
  4610. conn->client.sock,
  4611. conn->ssl,
  4612. (const char *)buf,
  4613. (int64_t)len);
  4614. }
  4615. return (int)total;
  4616. }
  4617. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  4618. int
  4619. mg_send_chunk(struct mg_connection *conn,
  4620. const char *chunk,
  4621. unsigned int chunk_len)
  4622. {
  4623. char lenbuf[16];
  4624. size_t lenbuf_len;
  4625. int ret;
  4626. int t;
  4627. /* First store the length information in a text buffer. */
  4628. sprintf(lenbuf, "%x\r\n", chunk_len);
  4629. lenbuf_len = strlen(lenbuf);
  4630. /* Then send length information, chunk and terminating \r\n. */
  4631. ret = mg_write(conn, lenbuf, lenbuf_len);
  4632. if (ret != (int)lenbuf_len) {
  4633. return -1;
  4634. }
  4635. t = ret;
  4636. ret = mg_write(conn, chunk, chunk_len);
  4637. if (ret != (int)chunk_len) {
  4638. return -1;
  4639. }
  4640. t += ret;
  4641. ret = mg_write(conn, "\r\n", 2);
  4642. if (ret != 2) {
  4643. return -1;
  4644. }
  4645. t += ret;
  4646. return t;
  4647. }
  4648. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  4649. static int
  4650. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  4651. {
  4652. va_list ap_copy;
  4653. size_t size = MG_BUF_LEN / 4;
  4654. int len = -1;
  4655. *buf = NULL;
  4656. while (len < 0) {
  4657. if (*buf) {
  4658. mg_free(*buf);
  4659. }
  4660. size *= 4;
  4661. *buf = (char *)mg_malloc(size);
  4662. if (!*buf) {
  4663. break;
  4664. }
  4665. va_copy(ap_copy, ap);
  4666. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  4667. va_end(ap_copy);
  4668. (*buf)[size - 1] = 0;
  4669. }
  4670. return len;
  4671. }
  4672. /* Print message to buffer. If buffer is large enough to hold the message,
  4673. * return buffer. If buffer is to small, allocate large enough buffer on heap,
  4674. * and return allocated buffer. */
  4675. static int
  4676. alloc_vprintf(char **out_buf,
  4677. char *prealloc_buf,
  4678. size_t prealloc_size,
  4679. const char *fmt,
  4680. va_list ap)
  4681. {
  4682. va_list ap_copy;
  4683. int len;
  4684. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  4685. * buffer is too small. Also, older versions of msvcrt.dll do not have
  4686. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  4687. * Therefore, we make two passes: on first pass, get required message
  4688. * length.
  4689. * On second pass, actually print the message. */
  4690. va_copy(ap_copy, ap);
  4691. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  4692. va_end(ap_copy);
  4693. if (len < 0) {
  4694. /* C runtime is not standard compliant, vsnprintf() returned -1.
  4695. * Switch to alternative code path that uses incremental allocations.
  4696. */
  4697. va_copy(ap_copy, ap);
  4698. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  4699. va_end(ap_copy);
  4700. } else if ((size_t)(len) >= prealloc_size) {
  4701. /* The pre-allocated buffer not large enough. */
  4702. /* Allocate a new buffer. */
  4703. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  4704. if (!*out_buf) {
  4705. /* Allocation failed. Return -1 as "out of memory" error. */
  4706. return -1;
  4707. }
  4708. /* Buffer allocation successful. Store the string there. */
  4709. va_copy(ap_copy, ap);
  4710. IGNORE_UNUSED_RESULT(
  4711. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  4712. va_end(ap_copy);
  4713. } else {
  4714. /* The pre-allocated buffer is large enough.
  4715. * Use it to store the string and return the address. */
  4716. va_copy(ap_copy, ap);
  4717. IGNORE_UNUSED_RESULT(
  4718. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  4719. va_end(ap_copy);
  4720. *out_buf = prealloc_buf;
  4721. }
  4722. return len;
  4723. }
  4724. static int
  4725. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  4726. {
  4727. char mem[MG_BUF_LEN];
  4728. char *buf = NULL;
  4729. int len;
  4730. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  4731. len = mg_write(conn, buf, (size_t)len);
  4732. }
  4733. if (buf != mem && buf != NULL) {
  4734. mg_free(buf);
  4735. }
  4736. return len;
  4737. }
  4738. int
  4739. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  4740. {
  4741. va_list ap;
  4742. int result;
  4743. va_start(ap, fmt);
  4744. result = mg_vprintf(conn, fmt, ap);
  4745. va_end(ap);
  4746. return result;
  4747. }
  4748. int
  4749. mg_url_decode(const char *src,
  4750. int src_len,
  4751. char *dst,
  4752. int dst_len,
  4753. int is_form_url_encoded)
  4754. {
  4755. int i, j, a, b;
  4756. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  4757. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  4758. if (i < src_len - 2 && src[i] == '%'
  4759. && isxdigit(*(const unsigned char *)(src + i + 1))
  4760. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  4761. a = tolower(*(const unsigned char *)(src + i + 1));
  4762. b = tolower(*(const unsigned char *)(src + i + 2));
  4763. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  4764. i += 2;
  4765. } else if (is_form_url_encoded && src[i] == '+') {
  4766. dst[j] = ' ';
  4767. } else {
  4768. dst[j] = src[i];
  4769. }
  4770. }
  4771. dst[j] = '\0'; /* Null-terminate the destination */
  4772. return (i >= src_len) ? j : -1;
  4773. }
  4774. int
  4775. mg_get_var(const char *data,
  4776. size_t data_len,
  4777. const char *name,
  4778. char *dst,
  4779. size_t dst_len)
  4780. {
  4781. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  4782. }
  4783. int
  4784. mg_get_var2(const char *data,
  4785. size_t data_len,
  4786. const char *name,
  4787. char *dst,
  4788. size_t dst_len,
  4789. size_t occurrence)
  4790. {
  4791. const char *p, *e, *s;
  4792. size_t name_len;
  4793. int len;
  4794. if (dst == NULL || dst_len == 0) {
  4795. len = -2;
  4796. } else if (data == NULL || name == NULL || data_len == 0) {
  4797. len = -1;
  4798. dst[0] = '\0';
  4799. } else {
  4800. name_len = strlen(name);
  4801. e = data + data_len;
  4802. len = -1;
  4803. dst[0] = '\0';
  4804. /* data is "var1=val1&var2=val2...". Find variable first */
  4805. for (p = data; p + name_len < e; p++) {
  4806. if ((p == data || p[-1] == '&') && p[name_len] == '='
  4807. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  4808. /* Point p to variable value */
  4809. p += name_len + 1;
  4810. /* Point s to the end of the value */
  4811. s = (const char *)memchr(p, '&', (size_t)(e - p));
  4812. if (s == NULL) {
  4813. s = e;
  4814. }
  4815. /* assert(s >= p); */
  4816. if (s < p) {
  4817. return -3;
  4818. }
  4819. /* Decode variable into destination buffer */
  4820. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  4821. /* Redirect error code from -1 to -2 (destination buffer too
  4822. * small). */
  4823. if (len == -1) {
  4824. len = -2;
  4825. }
  4826. break;
  4827. }
  4828. }
  4829. }
  4830. return len;
  4831. }
  4832. /* HCP24: some changes to compare hole var_name */
  4833. int
  4834. mg_get_cookie(const char *cookie_header,
  4835. const char *var_name,
  4836. char *dst,
  4837. size_t dst_size)
  4838. {
  4839. const char *s, *p, *end;
  4840. int name_len, len = -1;
  4841. if (dst == NULL || dst_size == 0) {
  4842. return -2;
  4843. }
  4844. dst[0] = '\0';
  4845. if (var_name == NULL || (s = cookie_header) == NULL) {
  4846. return -1;
  4847. }
  4848. name_len = (int)strlen(var_name);
  4849. end = s + strlen(s);
  4850. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  4851. if (s[name_len] == '=') {
  4852. /* HCP24: now check is it a substring or a full cookie name */
  4853. if ((s == cookie_header) || (s[-1] == ' ')) {
  4854. s += name_len + 1;
  4855. if ((p = strchr(s, ' ')) == NULL) {
  4856. p = end;
  4857. }
  4858. if (p[-1] == ';') {
  4859. p--;
  4860. }
  4861. if (*s == '"' && p[-1] == '"' && p > s + 1) {
  4862. s++;
  4863. p--;
  4864. }
  4865. if ((size_t)(p - s) < dst_size) {
  4866. len = (int)(p - s);
  4867. mg_strlcpy(dst, s, (size_t)len + 1);
  4868. } else {
  4869. len = -3;
  4870. }
  4871. break;
  4872. }
  4873. }
  4874. }
  4875. return len;
  4876. }
  4877. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  4878. static void
  4879. base64_encode(const unsigned char *src, int src_len, char *dst)
  4880. {
  4881. static const char *b64 =
  4882. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  4883. int i, j, a, b, c;
  4884. for (i = j = 0; i < src_len; i += 3) {
  4885. a = src[i];
  4886. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  4887. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  4888. dst[j++] = b64[a >> 2];
  4889. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  4890. if (i + 1 < src_len) {
  4891. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  4892. }
  4893. if (i + 2 < src_len) {
  4894. dst[j++] = b64[c & 63];
  4895. }
  4896. }
  4897. while (j % 4 != 0) {
  4898. dst[j++] = '=';
  4899. }
  4900. dst[j++] = '\0';
  4901. }
  4902. #endif
  4903. #if defined(USE_LUA)
  4904. static unsigned char
  4905. b64reverse(char letter)
  4906. {
  4907. if (letter >= 'A' && letter <= 'Z') {
  4908. return letter - 'A';
  4909. }
  4910. if (letter >= 'a' && letter <= 'z') {
  4911. return letter - 'a' + 26;
  4912. }
  4913. if (letter >= '0' && letter <= '9') {
  4914. return letter - '0' + 52;
  4915. }
  4916. if (letter == '+') {
  4917. return 62;
  4918. }
  4919. if (letter == '/') {
  4920. return 63;
  4921. }
  4922. if (letter == '=') {
  4923. return 255; /* normal end */
  4924. }
  4925. return 254; /* error */
  4926. }
  4927. static int
  4928. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  4929. {
  4930. int i;
  4931. unsigned char a, b, c, d;
  4932. *dst_len = 0;
  4933. for (i = 0; i < src_len; i += 4) {
  4934. a = b64reverse(src[i]);
  4935. if (a >= 254) {
  4936. return i;
  4937. }
  4938. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  4939. if (b >= 254) {
  4940. return i + 1;
  4941. }
  4942. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  4943. if (c == 254) {
  4944. return i + 2;
  4945. }
  4946. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  4947. if (d == 254) {
  4948. return i + 3;
  4949. }
  4950. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  4951. if (c != 255) {
  4952. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  4953. if (d != 255) {
  4954. dst[(*dst_len)++] = (c << 6) + d;
  4955. }
  4956. }
  4957. }
  4958. return -1;
  4959. }
  4960. #endif
  4961. static int
  4962. is_put_or_delete_method(const struct mg_connection *conn)
  4963. {
  4964. if (conn) {
  4965. const char *s = conn->request_info.request_method;
  4966. return s != NULL && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  4967. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  4968. }
  4969. return 0;
  4970. }
  4971. #if !defined(NO_FILES)
  4972. static int
  4973. extention_matches_script(
  4974. struct mg_connection *conn, /* in: request (must be valid) */
  4975. const char *filename /* in: filename (must be valid) */
  4976. )
  4977. {
  4978. #if !defined(NO_CGI)
  4979. if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  4980. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4981. filename) > 0) {
  4982. return 1;
  4983. }
  4984. #endif
  4985. #if defined(USE_LUA)
  4986. if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  4987. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  4988. filename) > 0) {
  4989. return 1;
  4990. }
  4991. #endif
  4992. #if defined(USE_DUKTAPE)
  4993. if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  4994. strlen(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  4995. filename) > 0) {
  4996. return 1;
  4997. }
  4998. #endif
  4999. /* filename and conn could be unused, if all preocessor conditions
  5000. * are false (no script language supported). */
  5001. (void)filename;
  5002. (void)conn;
  5003. return 0;
  5004. }
  5005. /* For given directory path, substitute it to valid index file.
  5006. * Return 1 if index file has been found, 0 if not found.
  5007. * If the file is found, it's stats is returned in stp. */
  5008. static int
  5009. substitute_index_file(struct mg_connection *conn,
  5010. char *path,
  5011. size_t path_len,
  5012. struct mg_file_stat *filestat)
  5013. {
  5014. const char *list = conn->ctx->config[INDEX_FILES];
  5015. struct vec filename_vec;
  5016. size_t n = strlen(path);
  5017. int found = 0;
  5018. /* The 'path' given to us points to the directory. Remove all trailing
  5019. * directory separator characters from the end of the path, and
  5020. * then append single directory separator character. */
  5021. while (n > 0 && path[n - 1] == '/') {
  5022. n--;
  5023. }
  5024. path[n] = '/';
  5025. /* Traverse index files list. For each entry, append it to the given
  5026. * path and see if the file exists. If it exists, break the loop */
  5027. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  5028. /* Ignore too long entries that may overflow path buffer */
  5029. if (filename_vec.len > path_len - (n + 2)) {
  5030. continue;
  5031. }
  5032. /* Prepare full path to the index file */
  5033. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  5034. /* Does it exist? */
  5035. if (mg_stat(conn, path, filestat)) {
  5036. /* Yes it does, break the loop */
  5037. found = 1;
  5038. break;
  5039. }
  5040. }
  5041. /* If no index file exists, restore directory path */
  5042. if (!found) {
  5043. path[n] = '\0';
  5044. }
  5045. return found;
  5046. }
  5047. #endif
  5048. static void
  5049. interpret_uri(struct mg_connection *conn, /* in: request (must be valid) */
  5050. char *filename, /* out: filename */
  5051. size_t filename_buf_len, /* in: size of filename buffer */
  5052. struct mg_file_stat *filestat, /* out: file status structure */
  5053. int *is_found, /* out: file found (directly) */
  5054. int *is_script_resource, /* out: handled by a script? */
  5055. int *is_websocket_request, /* out: websocket connetion? */
  5056. int *is_put_or_delete_request /* out: put/delete a file? */
  5057. )
  5058. {
  5059. #if !defined(NO_FILES)
  5060. const char *uri = conn->request_info.local_uri;
  5061. const char *root = conn->ctx->config[DOCUMENT_ROOT];
  5062. const char *rewrite;
  5063. struct vec a, b;
  5064. int match_len;
  5065. char gz_path[PATH_MAX];
  5066. char const *accept_encoding;
  5067. int truncated;
  5068. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  5069. char *tmp_str;
  5070. size_t tmp_str_len, sep_pos;
  5071. #endif
  5072. #else
  5073. (void)filename_buf_len; /* unused if NO_FILES is defined */
  5074. #endif
  5075. /* Step 1: Set all initially unknown outputs to zero */
  5076. memset(filestat, 0, sizeof(*filestat));
  5077. *filename = 0;
  5078. *is_found = 0;
  5079. *is_script_resource = 0;
  5080. /* Step 2: Check if the request attempts to modify the file system */
  5081. *is_put_or_delete_request = is_put_or_delete_method(conn);
  5082. /* Step 3: Check if it is a websocket request, and modify the document
  5083. * root if required */
  5084. #if defined(USE_WEBSOCKET)
  5085. *is_websocket_request = is_websocket_protocol(conn);
  5086. #if !defined(NO_FILES)
  5087. if (*is_websocket_request && conn->ctx->config[WEBSOCKET_ROOT]) {
  5088. root = conn->ctx->config[WEBSOCKET_ROOT];
  5089. }
  5090. #endif /* !NO_FILES */
  5091. #else /* USE_WEBSOCKET */
  5092. *is_websocket_request = 0;
  5093. #endif /* USE_WEBSOCKET */
  5094. #if !defined(NO_FILES)
  5095. /* Step 4: If there is no root directory, don't look for files. */
  5096. /* Note that root == NULL is a regular use case here. This occurs,
  5097. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  5098. * config is not required. */
  5099. if (root == NULL) {
  5100. /* all file related outputs have already been set to 0, just return
  5101. */
  5102. return;
  5103. }
  5104. /* Step 5: Determine the local file path from the root path and the
  5105. * request uri. */
  5106. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  5107. * part of the path one byte on the right. */
  5108. mg_snprintf(
  5109. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  5110. if (truncated) {
  5111. goto interpret_cleanup;
  5112. }
  5113. /* Step 6: URI rewriting */
  5114. rewrite = conn->ctx->config[REWRITE];
  5115. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  5116. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  5117. mg_snprintf(conn,
  5118. &truncated,
  5119. filename,
  5120. filename_buf_len - 1,
  5121. "%.*s%s",
  5122. (int)b.len,
  5123. b.ptr,
  5124. uri + match_len);
  5125. break;
  5126. }
  5127. }
  5128. if (truncated) {
  5129. goto interpret_cleanup;
  5130. }
  5131. /* Step 7: Check if the file exists at the server */
  5132. /* Local file path and name, corresponding to requested URI
  5133. * is now stored in "filename" variable. */
  5134. if (mg_stat(conn, filename, filestat)) {
  5135. /* 7.1: File exists. */
  5136. *is_found = 1;
  5137. /* 7.2: Check if it is a script type. */
  5138. if (extention_matches_script(conn, filename)) {
  5139. /* The request addresses a CGI resource, Lua script or
  5140. * server-side javascript.
  5141. * The URI corresponds to the script itself (like
  5142. * /path/script.cgi), and there is no additional resource
  5143. * path (like /path/script.cgi/something).
  5144. * Requests that modify (replace or delete) a resource, like
  5145. * PUT and DELETE requests, should replace/delete the script
  5146. * file.
  5147. * Requests that read or write from/to a resource, like GET and
  5148. * POST requests, should call the script and return the
  5149. * generated response. */
  5150. *is_script_resource = (!*is_put_or_delete_request);
  5151. }
  5152. /* 7.3: If the request target is a directory, there could be
  5153. * a substitute file (index.html, index.cgi, ...). */
  5154. if (filestat->is_directory) {
  5155. /* Use a local copy here, since substitute_index_file will
  5156. * change the content of the file status */
  5157. struct mg_file_stat tmp_filestat;
  5158. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  5159. if (substitute_index_file(
  5160. conn, filename, filename_buf_len, &tmp_filestat)) {
  5161. /* Substitute file found. Copy stat to the output, then
  5162. * check if the file is a script file */
  5163. *filestat = tmp_filestat;
  5164. if (extention_matches_script(conn, filename)) {
  5165. /* Substitute file is a script file */
  5166. *is_script_resource = 1;
  5167. } else {
  5168. /* Substitute file is a regular file */
  5169. *is_script_resource = 0;
  5170. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  5171. }
  5172. }
  5173. /* If there is no substitute file, the server could return
  5174. * a directory listing in a later step */
  5175. }
  5176. return;
  5177. }
  5178. /* Step 8: Check for zipped files: */
  5179. /* If we can't find the actual file, look for the file
  5180. * with the same name but a .gz extension. If we find it,
  5181. * use that and set the gzipped flag in the file struct
  5182. * to indicate that the response need to have the content-
  5183. * encoding: gzip header.
  5184. * We can only do this if the browser declares support. */
  5185. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  5186. if (strstr(accept_encoding, "gzip") != NULL) {
  5187. mg_snprintf(
  5188. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  5189. if (truncated) {
  5190. goto interpret_cleanup;
  5191. }
  5192. if (mg_stat(conn, gz_path, filestat)) {
  5193. if (filestat) {
  5194. filestat->is_gzipped = 1;
  5195. *is_found = 1;
  5196. }
  5197. /* Currently gz files can not be scripts. */
  5198. return;
  5199. }
  5200. }
  5201. }
  5202. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  5203. /* Step 9: Script resources may handle sub-resources */
  5204. /* Support PATH_INFO for CGI scripts. */
  5205. tmp_str_len = strlen(filename);
  5206. tmp_str = mg_malloc(tmp_str_len + PATH_MAX + 1);
  5207. if (!tmp_str) {
  5208. /* Out of memory */
  5209. goto interpret_cleanup;
  5210. }
  5211. memcpy(tmp_str, filename, tmp_str_len + 1);
  5212. sep_pos = tmp_str_len;
  5213. while (sep_pos > 0) {
  5214. sep_pos--;
  5215. if (tmp_str[sep_pos] == '/') {
  5216. int is_script = 0, does_exist = 0;
  5217. tmp_str[sep_pos] = 0;
  5218. if (tmp_str[0]) {
  5219. is_script = extention_matches_script(conn, tmp_str);
  5220. does_exist = mg_stat(conn, tmp_str, filestat);
  5221. }
  5222. if (does_exist && is_script) {
  5223. filename[sep_pos] = 0;
  5224. memmove(filename + sep_pos + 2,
  5225. filename + sep_pos + 1,
  5226. strlen(filename + sep_pos + 1) + 1);
  5227. conn->path_info = filename + sep_pos + 1;
  5228. filename[sep_pos + 1] = '/';
  5229. *is_script_resource = 1;
  5230. *is_found = 1;
  5231. break;
  5232. }
  5233. if (substitute_index_file(
  5234. conn, tmp_str, tmp_str_len + PATH_MAX, filestat)) {
  5235. /* some intermediate directory has an index file */
  5236. if (extention_matches_script(conn, tmp_str)) {
  5237. /* this index file is a script */
  5238. char *tmp_str2 = mg_strdup(filename + sep_pos + 1);
  5239. mg_snprintf(conn,
  5240. &truncated,
  5241. filename,
  5242. filename_buf_len,
  5243. "%s//%s",
  5244. tmp_str,
  5245. tmp_str2);
  5246. mg_free(tmp_str2);
  5247. if (truncated) {
  5248. mg_free(tmp_str);
  5249. tmp_str = NULL;
  5250. goto interpret_cleanup;
  5251. }
  5252. sep_pos = strlen(tmp_str);
  5253. filename[sep_pos] = 0;
  5254. conn->path_info = filename + sep_pos + 1;
  5255. *is_script_resource = 1;
  5256. *is_found = 1;
  5257. break;
  5258. } else {
  5259. /* non-script files will not have sub-resources */
  5260. filename[sep_pos] = 0;
  5261. conn->path_info = 0;
  5262. *is_script_resource = 0;
  5263. *is_found = 0;
  5264. break;
  5265. }
  5266. }
  5267. tmp_str[sep_pos] = '/';
  5268. }
  5269. }
  5270. mg_free(tmp_str);
  5271. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  5272. #endif /* !defined(NO_FILES) */
  5273. return;
  5274. #if !defined(NO_FILES)
  5275. /* Reset all outputs */
  5276. interpret_cleanup:
  5277. memset(filestat, 0, sizeof(*filestat));
  5278. *filename = 0;
  5279. *is_found = 0;
  5280. *is_script_resource = 0;
  5281. *is_websocket_request = 0;
  5282. *is_put_or_delete_request = 0;
  5283. #endif /* !defined(NO_FILES) */
  5284. }
  5285. /* Check whether full request is buffered. Return:
  5286. * -1 if request is malformed
  5287. * 0 if request is not yet fully buffered
  5288. * >0 actual request length, including last \r\n\r\n */
  5289. static int
  5290. get_request_len(const char *buf, int buflen)
  5291. {
  5292. const char *s, *e;
  5293. int len = 0;
  5294. for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
  5295. /* Control characters are not allowed but >=128 is. */
  5296. if (!isprint(*(const unsigned char *)s) && *s != '\r' && *s != '\n'
  5297. && *(const unsigned char *)s < 128) {
  5298. len = -1;
  5299. break; /* [i_a] abort scan as soon as one malformed character is
  5300. * found; */
  5301. /* don't let subsequent \r\n\r\n win us over anyhow */
  5302. } else if (s[0] == '\n' && s[1] == '\n') {
  5303. len = (int)(s - buf) + 2;
  5304. } else if (s[0] == '\n' && &s[1] < e && s[1] == '\r' && s[2] == '\n') {
  5305. len = (int)(s - buf) + 3;
  5306. }
  5307. return len;
  5308. }
  5309. #if !defined(NO_CACHING)
  5310. /* Convert month to the month number. Return -1 on error, or month number */
  5311. static int
  5312. get_month_index(const char *s)
  5313. {
  5314. size_t i;
  5315. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  5316. if (!strcmp(s, month_names[i])) {
  5317. return (int)i;
  5318. }
  5319. }
  5320. return -1;
  5321. }
  5322. /* Parse UTC date-time string, and return the corresponding time_t value. */
  5323. static time_t
  5324. parse_date_string(const char *datetime)
  5325. {
  5326. char month_str[32] = {0};
  5327. int second, minute, hour, day, month, year;
  5328. time_t result = (time_t)0;
  5329. struct tm tm;
  5330. if ((sscanf(datetime,
  5331. "%d/%3s/%d %d:%d:%d",
  5332. &day,
  5333. month_str,
  5334. &year,
  5335. &hour,
  5336. &minute,
  5337. &second) == 6) || (sscanf(datetime,
  5338. "%d %3s %d %d:%d:%d",
  5339. &day,
  5340. month_str,
  5341. &year,
  5342. &hour,
  5343. &minute,
  5344. &second) == 6)
  5345. || (sscanf(datetime,
  5346. "%*3s, %d %3s %d %d:%d:%d",
  5347. &day,
  5348. month_str,
  5349. &year,
  5350. &hour,
  5351. &minute,
  5352. &second) == 6) || (sscanf(datetime,
  5353. "%d-%3s-%d %d:%d:%d",
  5354. &day,
  5355. month_str,
  5356. &year,
  5357. &hour,
  5358. &minute,
  5359. &second) == 6)) {
  5360. month = get_month_index(month_str);
  5361. if ((month >= 0) && (year >= 1970)) {
  5362. memset(&tm, 0, sizeof(tm));
  5363. tm.tm_year = year - 1900;
  5364. tm.tm_mon = month;
  5365. tm.tm_mday = day;
  5366. tm.tm_hour = hour;
  5367. tm.tm_min = minute;
  5368. tm.tm_sec = second;
  5369. result = timegm(&tm);
  5370. }
  5371. }
  5372. return result;
  5373. }
  5374. #endif /* !NO_CACHING */
  5375. /* Protect against directory disclosure attack by removing '..',
  5376. * excessive '/' and '\' characters */
  5377. static void
  5378. remove_double_dots_and_double_slashes(char *s)
  5379. {
  5380. char *p = s;
  5381. while ((s[0] == '.') && (s[1] == '.')) {
  5382. s++;
  5383. }
  5384. while (*s != '\0') {
  5385. *p++ = *s++;
  5386. if (s[-1] == '/' || s[-1] == '\\') {
  5387. /* Skip all following slashes, backslashes and double-dots */
  5388. while (s[0] != '\0') {
  5389. if (s[0] == '/' || s[0] == '\\') {
  5390. s++;
  5391. } else if (s[0] == '.' && s[1] == '.') {
  5392. s += 2;
  5393. } else {
  5394. break;
  5395. }
  5396. }
  5397. }
  5398. }
  5399. *p = '\0';
  5400. }
  5401. static const struct {
  5402. const char *extension;
  5403. size_t ext_len;
  5404. const char *mime_type;
  5405. } builtin_mime_types[] = {
  5406. /* IANA registered MIME types (http://www.iana.org/assignments/media-types)
  5407. * application types */
  5408. {".doc", 4, "application/msword"},
  5409. {".eps", 4, "application/postscript"},
  5410. {".exe", 4, "application/octet-stream"},
  5411. {".js", 3, "application/javascript"},
  5412. {".json", 5, "application/json"},
  5413. {".pdf", 4, "application/pdf"},
  5414. {".ps", 3, "application/postscript"},
  5415. {".rtf", 4, "application/rtf"},
  5416. {".xhtml", 6, "application/xhtml+xml"},
  5417. {".xsl", 4, "application/xml"},
  5418. {".xslt", 5, "application/xml"},
  5419. /* fonts */
  5420. {".ttf", 4, "application/font-sfnt"},
  5421. {".cff", 4, "application/font-sfnt"},
  5422. {".otf", 4, "application/font-sfnt"},
  5423. {".aat", 4, "application/font-sfnt"},
  5424. {".sil", 4, "application/font-sfnt"},
  5425. {".pfr", 4, "application/font-tdpfr"},
  5426. {".woff", 5, "application/font-woff"},
  5427. /* audio */
  5428. {".mp3", 4, "audio/mpeg"},
  5429. {".oga", 4, "audio/ogg"},
  5430. {".ogg", 4, "audio/ogg"},
  5431. /* image */
  5432. {".gif", 4, "image/gif"},
  5433. {".ief", 4, "image/ief"},
  5434. {".jpeg", 5, "image/jpeg"},
  5435. {".jpg", 4, "image/jpeg"},
  5436. {".jpm", 4, "image/jpm"},
  5437. {".jpx", 4, "image/jpx"},
  5438. {".png", 4, "image/png"},
  5439. {".svg", 4, "image/svg+xml"},
  5440. {".tif", 4, "image/tiff"},
  5441. {".tiff", 5, "image/tiff"},
  5442. /* model */
  5443. {".wrl", 4, "model/vrml"},
  5444. /* text */
  5445. {".css", 4, "text/css"},
  5446. {".csv", 4, "text/csv"},
  5447. {".htm", 4, "text/html"},
  5448. {".html", 5, "text/html"},
  5449. {".sgm", 4, "text/sgml"},
  5450. {".shtm", 5, "text/html"},
  5451. {".shtml", 6, "text/html"},
  5452. {".txt", 4, "text/plain"},
  5453. {".xml", 4, "text/xml"},
  5454. /* video */
  5455. {".mov", 4, "video/quicktime"},
  5456. {".mp4", 4, "video/mp4"},
  5457. {".mpeg", 5, "video/mpeg"},
  5458. {".mpg", 4, "video/mpeg"},
  5459. {".ogv", 4, "video/ogg"},
  5460. {".qt", 3, "video/quicktime"},
  5461. /* not registered types
  5462. * (http://reference.sitepoint.com/html/mime-types-full,
  5463. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  5464. {".arj", 4, "application/x-arj-compressed"},
  5465. {".gz", 3, "application/x-gunzip"},
  5466. {".rar", 4, "application/x-arj-compressed"},
  5467. {".swf", 4, "application/x-shockwave-flash"},
  5468. {".tar", 4, "application/x-tar"},
  5469. {".tgz", 4, "application/x-tar-gz"},
  5470. {".torrent", 8, "application/x-bittorrent"},
  5471. {".ppt", 4, "application/x-mspowerpoint"},
  5472. {".xls", 4, "application/x-msexcel"},
  5473. {".zip", 4, "application/x-zip-compressed"},
  5474. {".aac",
  5475. 4,
  5476. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  5477. {".aif", 4, "audio/x-aif"},
  5478. {".m3u", 4, "audio/x-mpegurl"},
  5479. {".mid", 4, "audio/x-midi"},
  5480. {".ra", 3, "audio/x-pn-realaudio"},
  5481. {".ram", 4, "audio/x-pn-realaudio"},
  5482. {".wav", 4, "audio/x-wav"},
  5483. {".bmp", 4, "image/bmp"},
  5484. {".ico", 4, "image/x-icon"},
  5485. {".pct", 4, "image/x-pct"},
  5486. {".pict", 5, "image/pict"},
  5487. {".rgb", 4, "image/x-rgb"},
  5488. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  5489. {".asf", 4, "video/x-ms-asf"},
  5490. {".avi", 4, "video/x-msvideo"},
  5491. {".m4v", 4, "video/x-m4v"},
  5492. {NULL, 0, NULL}};
  5493. const char *
  5494. mg_get_builtin_mime_type(const char *path)
  5495. {
  5496. const char *ext;
  5497. size_t i, path_len;
  5498. path_len = strlen(path);
  5499. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  5500. ext = path + (path_len - builtin_mime_types[i].ext_len);
  5501. if (path_len > builtin_mime_types[i].ext_len
  5502. && mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {
  5503. return builtin_mime_types[i].mime_type;
  5504. }
  5505. }
  5506. return "text/plain";
  5507. }
  5508. /* Look at the "path" extension and figure what mime type it has.
  5509. * Store mime type in the vector. */
  5510. static void
  5511. get_mime_type(struct mg_context *ctx, const char *path, struct vec *vec)
  5512. {
  5513. struct vec ext_vec, mime_vec;
  5514. const char *list, *ext;
  5515. size_t path_len;
  5516. path_len = strlen(path);
  5517. if (ctx == NULL || vec == NULL) {
  5518. return;
  5519. }
  5520. /* Scan user-defined mime types first, in case user wants to
  5521. * override default mime types. */
  5522. list = ctx->config[EXTRA_MIME_TYPES];
  5523. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  5524. /* ext now points to the path suffix */
  5525. ext = path + path_len - ext_vec.len;
  5526. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  5527. *vec = mime_vec;
  5528. return;
  5529. }
  5530. }
  5531. vec->ptr = mg_get_builtin_mime_type(path);
  5532. vec->len = strlen(vec->ptr);
  5533. }
  5534. /* Stringify binary data. Output buffer must be twice as big as input,
  5535. * because each byte takes 2 bytes in string representation */
  5536. static void
  5537. bin2str(char *to, const unsigned char *p, size_t len)
  5538. {
  5539. static const char *hex = "0123456789abcdef";
  5540. for (; len--; p++) {
  5541. *to++ = hex[p[0] >> 4];
  5542. *to++ = hex[p[0] & 0x0f];
  5543. }
  5544. *to = '\0';
  5545. }
  5546. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes. */
  5547. char *
  5548. mg_md5(char buf[33], ...)
  5549. {
  5550. md5_byte_t hash[16];
  5551. const char *p;
  5552. va_list ap;
  5553. md5_state_t ctx;
  5554. md5_init(&ctx);
  5555. va_start(ap, buf);
  5556. while ((p = va_arg(ap, const char *)) != NULL) {
  5557. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  5558. }
  5559. va_end(ap);
  5560. md5_finish(&ctx, hash);
  5561. bin2str(buf, hash, sizeof(hash));
  5562. return buf;
  5563. }
  5564. /* Check the user's password, return 1 if OK */
  5565. static int
  5566. check_password(const char *method,
  5567. const char *ha1,
  5568. const char *uri,
  5569. const char *nonce,
  5570. const char *nc,
  5571. const char *cnonce,
  5572. const char *qop,
  5573. const char *response)
  5574. {
  5575. char ha2[32 + 1], expected_response[32 + 1];
  5576. /* Some of the parameters may be NULL */
  5577. if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL
  5578. || qop == NULL
  5579. || response == NULL) {
  5580. return 0;
  5581. }
  5582. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  5583. if (strlen(response) != 32) {
  5584. return 0;
  5585. }
  5586. mg_md5(ha2, method, ":", uri, NULL);
  5587. mg_md5(expected_response,
  5588. ha1,
  5589. ":",
  5590. nonce,
  5591. ":",
  5592. nc,
  5593. ":",
  5594. cnonce,
  5595. ":",
  5596. qop,
  5597. ":",
  5598. ha2,
  5599. NULL);
  5600. return mg_strcasecmp(response, expected_response) == 0;
  5601. }
  5602. /* Use the global passwords file, if specified by auth_gpass option,
  5603. * or search for .htpasswd in the requested directory. */
  5604. static void
  5605. open_auth_file(struct mg_connection *conn,
  5606. const char *path,
  5607. struct mg_file *filep)
  5608. {
  5609. if (conn != NULL && conn->ctx != NULL) {
  5610. char name[PATH_MAX];
  5611. const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
  5612. int truncated;
  5613. if (gpass != NULL) {
  5614. /* Use global passwords file */
  5615. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  5616. #ifdef DEBUG
  5617. /* Use mg_cry here, since gpass has been configured. */
  5618. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  5619. #endif
  5620. }
  5621. /* Important: using local struct mg_file to test path for
  5622. * is_directory flag. If filep is used, mg_stat() makes it
  5623. * appear as if auth file was opened.
  5624. * TODO(mid): Check if this is still required after rewriting
  5625. * mg_stat */
  5626. } else if (mg_stat(conn, path, &filep->stat)
  5627. && filep->stat.is_directory) {
  5628. mg_snprintf(conn,
  5629. &truncated,
  5630. name,
  5631. sizeof(name),
  5632. "%s/%s",
  5633. path,
  5634. PASSWORDS_FILE_NAME);
  5635. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  5636. #ifdef DEBUG
  5637. /* Don't use mg_cry here, but only a trace, since this is
  5638. * a typical case. It will occur for every directory
  5639. * without a password file. */
  5640. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  5641. #endif
  5642. }
  5643. } else {
  5644. /* Try to find .htpasswd in requested directory. */
  5645. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  5646. if (e[0] == '/') {
  5647. break;
  5648. }
  5649. }
  5650. mg_snprintf(conn,
  5651. &truncated,
  5652. name,
  5653. sizeof(name),
  5654. "%.*s/%s",
  5655. (int)(e - p),
  5656. p,
  5657. PASSWORDS_FILE_NAME);
  5658. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  5659. #ifdef DEBUG
  5660. /* Don't use mg_cry here, but only a trace, since this is
  5661. * a typical case. It will occur for every directory
  5662. * without a password file. */
  5663. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  5664. #endif
  5665. }
  5666. }
  5667. }
  5668. }
  5669. /* Parsed Authorization header */
  5670. struct ah {
  5671. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  5672. };
  5673. /* Return 1 on success. Always initializes the ah structure. */
  5674. static int
  5675. parse_auth_header(struct mg_connection *conn,
  5676. char *buf,
  5677. size_t buf_size,
  5678. struct ah *ah)
  5679. {
  5680. char *name, *value, *s;
  5681. const char *auth_header;
  5682. uint64_t nonce;
  5683. if (!ah || !conn) {
  5684. return 0;
  5685. }
  5686. (void)memset(ah, 0, sizeof(*ah));
  5687. if ((auth_header = mg_get_header(conn, "Authorization")) == NULL
  5688. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  5689. return 0;
  5690. }
  5691. /* Make modifiable copy of the auth header */
  5692. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  5693. s = buf;
  5694. /* Parse authorization header */
  5695. for (;;) {
  5696. /* Gobble initial spaces */
  5697. while (isspace(*(unsigned char *)s)) {
  5698. s++;
  5699. }
  5700. name = skip_quoted(&s, "=", " ", 0);
  5701. /* Value is either quote-delimited, or ends at first comma or space. */
  5702. if (s[0] == '\"') {
  5703. s++;
  5704. value = skip_quoted(&s, "\"", " ", '\\');
  5705. if (s[0] == ',') {
  5706. s++;
  5707. }
  5708. } else {
  5709. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  5710. * spaces */
  5711. }
  5712. if (*name == '\0') {
  5713. break;
  5714. }
  5715. if (!strcmp(name, "username")) {
  5716. ah->user = value;
  5717. } else if (!strcmp(name, "cnonce")) {
  5718. ah->cnonce = value;
  5719. } else if (!strcmp(name, "response")) {
  5720. ah->response = value;
  5721. } else if (!strcmp(name, "uri")) {
  5722. ah->uri = value;
  5723. } else if (!strcmp(name, "qop")) {
  5724. ah->qop = value;
  5725. } else if (!strcmp(name, "nc")) {
  5726. ah->nc = value;
  5727. } else if (!strcmp(name, "nonce")) {
  5728. ah->nonce = value;
  5729. }
  5730. }
  5731. #ifndef NO_NONCE_CHECK
  5732. /* Read the nonce from the response. */
  5733. if (ah->nonce == NULL) {
  5734. return 0;
  5735. }
  5736. s = NULL;
  5737. nonce = strtoull(ah->nonce, &s, 10);
  5738. if ((s == NULL) || (*s != 0)) {
  5739. return 0;
  5740. }
  5741. /* Convert the nonce from the client to a number. */
  5742. nonce ^= conn->ctx->auth_nonce_mask;
  5743. /* The converted number corresponds to the time the nounce has been
  5744. * created. This should not be earlier than the server start. */
  5745. /* Server side nonce check is valuable in all situations but one:
  5746. * if the server restarts frequently, but the client should not see
  5747. * that, so the server should accept nonces from previous starts. */
  5748. /* However, the reasonable default is to not accept a nonce from a
  5749. * previous start, so if anyone changed the access rights between
  5750. * two restarts, a new login is required. */
  5751. if (nonce < (uint64_t)conn->ctx->start_time) {
  5752. /* nonce is from a previous start of the server and no longer valid
  5753. * (replay attack?) */
  5754. return 0;
  5755. }
  5756. /* Check if the nonce is too high, so it has not (yet) been used by the
  5757. * server. */
  5758. if (nonce >= ((uint64_t)conn->ctx->start_time + conn->ctx->nonce_count)) {
  5759. return 0;
  5760. }
  5761. #else
  5762. (void)nonce;
  5763. #endif
  5764. /* CGI needs it as REMOTE_USER */
  5765. if (ah->user != NULL) {
  5766. conn->request_info.remote_user = mg_strdup(ah->user);
  5767. } else {
  5768. return 0;
  5769. }
  5770. return 1;
  5771. }
  5772. static const char *
  5773. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  5774. {
  5775. const char *eof;
  5776. size_t len;
  5777. const char *memend;
  5778. if (!filep) {
  5779. return NULL;
  5780. }
  5781. if (filep->access.membuf != NULL && *p != NULL) {
  5782. memend = (const char *)&filep->access.membuf[filep->stat.size];
  5783. /* Search for \n from p till the end of stream */
  5784. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  5785. if (eof != NULL) {
  5786. eof += 1; /* Include \n */
  5787. } else {
  5788. eof = memend; /* Copy remaining data */
  5789. }
  5790. len =
  5791. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  5792. memcpy(buf, *p, len);
  5793. buf[len] = '\0';
  5794. *p += len;
  5795. return len ? eof : NULL;
  5796. } else if (filep->access.fp != NULL) {
  5797. return fgets(buf, (int)size, filep->access.fp);
  5798. } else {
  5799. return NULL;
  5800. }
  5801. }
  5802. /* Define the initial recursion depth for procesesing htpasswd files that
  5803. * include other htpasswd
  5804. * (or even the same) files. It is not difficult to provide a file or files
  5805. * s.t. they force civetweb
  5806. * to infinitely recurse and then crash.
  5807. */
  5808. #define INITIAL_DEPTH 9
  5809. #if INITIAL_DEPTH <= 0
  5810. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  5811. #endif
  5812. struct read_auth_file_struct {
  5813. struct mg_connection *conn;
  5814. struct ah ah;
  5815. char *domain;
  5816. char buf[256 + 256 + 40];
  5817. char *f_user;
  5818. char *f_domain;
  5819. char *f_ha1;
  5820. };
  5821. static int
  5822. read_auth_file(struct mg_file *filep,
  5823. struct read_auth_file_struct *workdata,
  5824. int depth)
  5825. {
  5826. char *p;
  5827. int is_authorized = 0;
  5828. struct mg_file fp;
  5829. size_t l;
  5830. if (!filep || !workdata || 0 == depth) {
  5831. return 0;
  5832. }
  5833. /* Loop over passwords file */
  5834. p = (char *)filep->access.membuf;
  5835. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  5836. l = strlen(workdata->buf);
  5837. while (l > 0) {
  5838. if (isspace(workdata->buf[l - 1])
  5839. || iscntrl(workdata->buf[l - 1])) {
  5840. l--;
  5841. workdata->buf[l] = 0;
  5842. } else
  5843. break;
  5844. }
  5845. if (l < 1) {
  5846. continue;
  5847. }
  5848. workdata->f_user = workdata->buf;
  5849. if (workdata->f_user[0] == ':') {
  5850. /* user names may not contain a ':' and may not be empty,
  5851. * so lines starting with ':' may be used for a special purpose */
  5852. if (workdata->f_user[1] == '#') {
  5853. /* :# is a comment */
  5854. continue;
  5855. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  5856. if (mg_fopen(workdata->conn,
  5857. workdata->f_user + 9,
  5858. MG_FOPEN_MODE_READ,
  5859. &fp)) {
  5860. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  5861. (void)mg_fclose(
  5862. &fp.access); /* ignore error on read only file */
  5863. /* No need to continue processing files once we have a
  5864. * match, since nothing will reset it back
  5865. * to 0.
  5866. */
  5867. if (is_authorized) {
  5868. return is_authorized;
  5869. }
  5870. } else {
  5871. mg_cry(workdata->conn,
  5872. "%s: cannot open authorization file: %s",
  5873. __func__,
  5874. workdata->buf);
  5875. }
  5876. continue;
  5877. }
  5878. /* everything is invalid for the moment (might change in the
  5879. * future) */
  5880. mg_cry(workdata->conn,
  5881. "%s: syntax error in authorization file: %s",
  5882. __func__,
  5883. workdata->buf);
  5884. continue;
  5885. }
  5886. workdata->f_domain = strchr(workdata->f_user, ':');
  5887. if (workdata->f_domain == NULL) {
  5888. mg_cry(workdata->conn,
  5889. "%s: syntax error in authorization file: %s",
  5890. __func__,
  5891. workdata->buf);
  5892. continue;
  5893. }
  5894. *(workdata->f_domain) = 0;
  5895. (workdata->f_domain)++;
  5896. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  5897. if (workdata->f_ha1 == NULL) {
  5898. mg_cry(workdata->conn,
  5899. "%s: syntax error in authorization file: %s",
  5900. __func__,
  5901. workdata->buf);
  5902. continue;
  5903. }
  5904. *(workdata->f_ha1) = 0;
  5905. (workdata->f_ha1)++;
  5906. if (!strcmp(workdata->ah.user, workdata->f_user)
  5907. && !strcmp(workdata->domain, workdata->f_domain)) {
  5908. return check_password(workdata->conn->request_info.request_method,
  5909. workdata->f_ha1,
  5910. workdata->ah.uri,
  5911. workdata->ah.nonce,
  5912. workdata->ah.nc,
  5913. workdata->ah.cnonce,
  5914. workdata->ah.qop,
  5915. workdata->ah.response);
  5916. }
  5917. }
  5918. return is_authorized;
  5919. }
  5920. /* Authorize against the opened passwords file. Return 1 if authorized. */
  5921. static int
  5922. authorize(struct mg_connection *conn, struct mg_file *filep)
  5923. {
  5924. struct read_auth_file_struct workdata;
  5925. char buf[MG_BUF_LEN];
  5926. if (!conn || !conn->ctx) {
  5927. return 0;
  5928. }
  5929. memset(&workdata, 0, sizeof(workdata));
  5930. workdata.conn = conn;
  5931. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  5932. return 0;
  5933. }
  5934. workdata.domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  5935. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  5936. }
  5937. /* Return 1 if request is authorised, 0 otherwise. */
  5938. static int
  5939. check_authorization(struct mg_connection *conn, const char *path)
  5940. {
  5941. char fname[PATH_MAX];
  5942. struct vec uri_vec, filename_vec;
  5943. const char *list;
  5944. struct mg_file file = STRUCT_FILE_INITIALIZER;
  5945. int authorized = 1, truncated;
  5946. if (!conn || !conn->ctx) {
  5947. return 0;
  5948. }
  5949. list = conn->ctx->config[PROTECT_URI];
  5950. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  5951. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  5952. mg_snprintf(conn,
  5953. &truncated,
  5954. fname,
  5955. sizeof(fname),
  5956. "%.*s",
  5957. (int)filename_vec.len,
  5958. filename_vec.ptr);
  5959. if (truncated
  5960. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  5961. mg_cry(conn,
  5962. "%s: cannot open %s: %s",
  5963. __func__,
  5964. fname,
  5965. strerror(errno));
  5966. }
  5967. break;
  5968. }
  5969. }
  5970. if (!is_file_opened(&file.access)) {
  5971. open_auth_file(conn, path, &file);
  5972. }
  5973. if (is_file_opened(&file.access)) {
  5974. authorized = authorize(conn, &file);
  5975. (void)mg_fclose(&file.access); /* ignore error on read only file */
  5976. }
  5977. return authorized;
  5978. }
  5979. static void
  5980. send_authorization_request(struct mg_connection *conn)
  5981. {
  5982. char date[64];
  5983. time_t curtime = time(NULL);
  5984. if (conn && conn->ctx) {
  5985. uint64_t nonce = (uint64_t)(conn->ctx->start_time);
  5986. (void)pthread_mutex_lock(&conn->ctx->nonce_mutex);
  5987. nonce += conn->ctx->nonce_count;
  5988. ++conn->ctx->nonce_count;
  5989. (void)pthread_mutex_unlock(&conn->ctx->nonce_mutex);
  5990. nonce ^= conn->ctx->auth_nonce_mask;
  5991. conn->status_code = 401;
  5992. conn->must_close = 1;
  5993. gmt_time_string(date, sizeof(date), &curtime);
  5994. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  5995. send_no_cache_header(conn);
  5996. send_additional_header(conn);
  5997. mg_printf(conn,
  5998. "Date: %s\r\n"
  5999. "Connection: %s\r\n"
  6000. "Content-Length: 0\r\n"
  6001. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  6002. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  6003. date,
  6004. suggest_connection_header(conn),
  6005. conn->ctx->config[AUTHENTICATION_DOMAIN],
  6006. nonce);
  6007. }
  6008. }
  6009. #if !defined(NO_FILES)
  6010. static int
  6011. is_authorized_for_put(struct mg_connection *conn)
  6012. {
  6013. if (conn) {
  6014. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6015. const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
  6016. int ret = 0;
  6017. if (passfile != NULL
  6018. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  6019. ret = authorize(conn, &file);
  6020. (void)mg_fclose(&file.access); /* ignore error on read only file */
  6021. }
  6022. return ret;
  6023. }
  6024. return 0;
  6025. }
  6026. #endif
  6027. int
  6028. mg_modify_passwords_file(const char *fname,
  6029. const char *domain,
  6030. const char *user,
  6031. const char *pass)
  6032. {
  6033. int found, i;
  6034. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  6035. FILE *fp, *fp2;
  6036. found = 0;
  6037. fp = fp2 = NULL;
  6038. /* Regard empty password as no password - remove user record. */
  6039. if (pass != NULL && pass[0] == '\0') {
  6040. pass = NULL;
  6041. }
  6042. /* Other arguments must not be empty */
  6043. if (fname == NULL || domain == NULL || user == NULL) {
  6044. return 0;
  6045. }
  6046. /* Using the given file format, user name and domain must not contain ':'
  6047. */
  6048. if (strchr(user, ':') != NULL) {
  6049. return 0;
  6050. }
  6051. if (strchr(domain, ':') != NULL) {
  6052. return 0;
  6053. }
  6054. /* Do not allow control characters like newline in user name and domain.
  6055. * Do not allow excessively long names either. */
  6056. for (i = 0; i < 255 && user[i] != 0; i++) {
  6057. if (iscntrl(user[i])) {
  6058. return 0;
  6059. }
  6060. }
  6061. if (user[i]) {
  6062. return 0;
  6063. }
  6064. for (i = 0; i < 255 && domain[i] != 0; i++) {
  6065. if (iscntrl(domain[i])) {
  6066. return 0;
  6067. }
  6068. }
  6069. if (domain[i]) {
  6070. return 0;
  6071. }
  6072. /* The maximum length of the path to the password file is limited */
  6073. if ((strlen(fname) + 4) >= PATH_MAX) {
  6074. return 0;
  6075. }
  6076. /* Create a temporary file name. Length has been checked before. */
  6077. strcpy(tmp, fname);
  6078. strcat(tmp, ".tmp");
  6079. /* Create the file if does not exist */
  6080. /* Use of fopen here is OK, since fname is only ASCII */
  6081. if ((fp = fopen(fname, "a+")) != NULL) {
  6082. (void)fclose(fp);
  6083. }
  6084. /* Open the given file and temporary file */
  6085. if ((fp = fopen(fname, "r")) == NULL) {
  6086. return 0;
  6087. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  6088. fclose(fp);
  6089. return 0;
  6090. }
  6091. /* Copy the stuff to temporary file */
  6092. while (fgets(line, sizeof(line), fp) != NULL) {
  6093. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  6094. continue;
  6095. }
  6096. u[255] = 0;
  6097. d[255] = 0;
  6098. if (!strcmp(u, user) && !strcmp(d, domain)) {
  6099. found++;
  6100. if (pass != NULL) {
  6101. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  6102. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  6103. }
  6104. } else {
  6105. fprintf(fp2, "%s", line);
  6106. }
  6107. }
  6108. /* If new user, just add it */
  6109. if (!found && pass != NULL) {
  6110. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  6111. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  6112. }
  6113. /* Close files */
  6114. fclose(fp);
  6115. fclose(fp2);
  6116. /* Put the temp file in place of real file */
  6117. IGNORE_UNUSED_RESULT(remove(fname));
  6118. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  6119. return 1;
  6120. }
  6121. static int
  6122. is_valid_port(unsigned long port)
  6123. {
  6124. return (port <= 0xffff);
  6125. }
  6126. static int
  6127. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  6128. {
  6129. struct addrinfo hints, *res, *ressave;
  6130. int func_ret = 0;
  6131. int gai_ret;
  6132. memset(&hints, 0, sizeof(struct addrinfo));
  6133. hints.ai_family = af;
  6134. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  6135. if (gai_ret != 0) {
  6136. /* gai_strerror could be used to convert gai_ret to a string */
  6137. /* POSIX return values: see
  6138. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  6139. */
  6140. /* Windows return values: see
  6141. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  6142. */
  6143. return 0;
  6144. }
  6145. ressave = res;
  6146. while (res) {
  6147. if (dstlen >= res->ai_addrlen) {
  6148. memcpy(dst, res->ai_addr, res->ai_addrlen);
  6149. func_ret = 1;
  6150. }
  6151. res = res->ai_next;
  6152. }
  6153. freeaddrinfo(ressave);
  6154. return func_ret;
  6155. }
  6156. static int
  6157. connect_socket(struct mg_context *ctx /* may be NULL */,
  6158. const char *host,
  6159. int port,
  6160. int use_ssl,
  6161. char *ebuf,
  6162. size_t ebuf_len,
  6163. SOCKET *sock /* output: socket, must not be NULL */,
  6164. union usa *sa /* output: socket address, must not be NULL */
  6165. )
  6166. {
  6167. int ip_ver = 0;
  6168. *sock = INVALID_SOCKET;
  6169. memset(sa, 0, sizeof(*sa));
  6170. if (ebuf_len > 0) {
  6171. *ebuf = 0;
  6172. }
  6173. if (host == NULL) {
  6174. mg_snprintf(NULL,
  6175. NULL, /* No truncation check for ebuf */
  6176. ebuf,
  6177. ebuf_len,
  6178. "%s",
  6179. "NULL host");
  6180. return 0;
  6181. }
  6182. if (port <= 0 || !is_valid_port((unsigned)port)) {
  6183. mg_snprintf(NULL,
  6184. NULL, /* No truncation check for ebuf */
  6185. ebuf,
  6186. ebuf_len,
  6187. "%s",
  6188. "invalid port");
  6189. return 0;
  6190. }
  6191. #if !defined(NO_SSL)
  6192. #if !defined(NO_SSL_DL)
  6193. #ifdef OPENSSL_API_1_1
  6194. if (use_ssl && (TLS_client_method == NULL)) {
  6195. mg_snprintf(NULL,
  6196. NULL, /* No truncation check for ebuf */
  6197. ebuf,
  6198. ebuf_len,
  6199. "%s",
  6200. "SSL is not initialized");
  6201. return 0;
  6202. }
  6203. #else
  6204. if (use_ssl && (SSLv23_client_method == NULL)) {
  6205. mg_snprintf(NULL,
  6206. NULL, /* No truncation check for ebuf */
  6207. ebuf,
  6208. ebuf_len,
  6209. "%s",
  6210. "SSL is not initialized");
  6211. return 0;
  6212. }
  6213. #endif /* OPENSSL_API_1_1 */
  6214. #else
  6215. (void)use_ssl;
  6216. #endif /* NO_SSL_DL */
  6217. #else
  6218. (void)use_ssl;
  6219. #endif /* !defined(NO_SSL) */
  6220. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  6221. sa->sin.sin_port = htons((uint16_t)port);
  6222. ip_ver = 4;
  6223. #ifdef USE_IPV6
  6224. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  6225. sa->sin6.sin6_port = htons((uint16_t)port);
  6226. ip_ver = 6;
  6227. } else if (host[0] == '[') {
  6228. /* While getaddrinfo on Windows will work with [::1],
  6229. * getaddrinfo on Linux only works with ::1 (without []). */
  6230. size_t l = strlen(host + 1);
  6231. char *h = (l > 1) ? mg_strdup(host + 1) : NULL;
  6232. if (h) {
  6233. h[l - 1] = 0;
  6234. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  6235. sa->sin6.sin6_port = htons((uint16_t)port);
  6236. ip_ver = 6;
  6237. }
  6238. mg_free(h);
  6239. }
  6240. #endif
  6241. }
  6242. if (ip_ver == 0) {
  6243. mg_snprintf(NULL,
  6244. NULL, /* No truncation check for ebuf */
  6245. ebuf,
  6246. ebuf_len,
  6247. "%s",
  6248. "host not found");
  6249. return 0;
  6250. }
  6251. if (ip_ver == 4) {
  6252. *sock = socket(PF_INET, SOCK_STREAM, 0);
  6253. }
  6254. #ifdef USE_IPV6
  6255. else if (ip_ver == 6) {
  6256. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  6257. }
  6258. #endif
  6259. if (*sock == INVALID_SOCKET) {
  6260. mg_snprintf(NULL,
  6261. NULL, /* No truncation check for ebuf */
  6262. ebuf,
  6263. ebuf_len,
  6264. "socket(): %s",
  6265. strerror(ERRNO));
  6266. return 0;
  6267. }
  6268. set_close_on_exec(*sock, fc(ctx));
  6269. if ((ip_ver == 4)
  6270. && (connect(*sock, (struct sockaddr *)&sa->sin, sizeof(sa->sin))
  6271. == 0)) {
  6272. /* connected with IPv4 */
  6273. set_blocking_mode(*sock, 0);
  6274. return 1;
  6275. }
  6276. #ifdef USE_IPV6
  6277. if ((ip_ver == 6)
  6278. && (connect(*sock, (struct sockaddr *)&sa->sin6, sizeof(sa->sin6))
  6279. == 0)) {
  6280. /* connected with IPv6 */
  6281. set_blocking_mode(*sock, 0);
  6282. return 1;
  6283. }
  6284. #endif
  6285. /* Not connected */
  6286. mg_snprintf(NULL,
  6287. NULL, /* No truncation check for ebuf */
  6288. ebuf,
  6289. ebuf_len,
  6290. "connect(%s:%d): %s",
  6291. host,
  6292. port,
  6293. strerror(ERRNO));
  6294. closesocket(*sock);
  6295. *sock = INVALID_SOCKET;
  6296. return 0;
  6297. }
  6298. int
  6299. mg_url_encode(const char *src, char *dst, size_t dst_len)
  6300. {
  6301. static const char *dont_escape = "._-$,;~()";
  6302. static const char *hex = "0123456789abcdef";
  6303. char *pos = dst;
  6304. const char *end = dst + dst_len - 1;
  6305. for (; *src != '\0' && pos < end; src++, pos++) {
  6306. if (isalnum(*(const unsigned char *)src)
  6307. || strchr(dont_escape, *(const unsigned char *)src) != NULL) {
  6308. *pos = *src;
  6309. } else if (pos + 2 < end) {
  6310. pos[0] = '%';
  6311. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  6312. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  6313. pos += 2;
  6314. } else {
  6315. break;
  6316. }
  6317. }
  6318. *pos = '\0';
  6319. return (*src == '\0') ? (int)(pos - dst) : -1;
  6320. }
  6321. static void
  6322. print_dir_entry(struct de *de)
  6323. {
  6324. char size[64], mod[64], href[PATH_MAX * 3 /* worst case */];
  6325. struct tm *tm;
  6326. if (de->file.is_directory) {
  6327. mg_snprintf(de->conn,
  6328. NULL, /* Buffer is big enough */
  6329. size,
  6330. sizeof(size),
  6331. "%s",
  6332. "[DIRECTORY]");
  6333. } else {
  6334. /* We use (signed) cast below because MSVC 6 compiler cannot
  6335. * convert unsigned __int64 to double. Sigh. */
  6336. if (de->file.size < 1024) {
  6337. mg_snprintf(de->conn,
  6338. NULL, /* Buffer is big enough */
  6339. size,
  6340. sizeof(size),
  6341. "%d",
  6342. (int)de->file.size);
  6343. } else if (de->file.size < 0x100000) {
  6344. mg_snprintf(de->conn,
  6345. NULL, /* Buffer is big enough */
  6346. size,
  6347. sizeof(size),
  6348. "%.1fk",
  6349. (double)de->file.size / 1024.0);
  6350. } else if (de->file.size < 0x40000000) {
  6351. mg_snprintf(de->conn,
  6352. NULL, /* Buffer is big enough */
  6353. size,
  6354. sizeof(size),
  6355. "%.1fM",
  6356. (double)de->file.size / 1048576);
  6357. } else {
  6358. mg_snprintf(de->conn,
  6359. NULL, /* Buffer is big enough */
  6360. size,
  6361. sizeof(size),
  6362. "%.1fG",
  6363. (double)de->file.size / 1073741824);
  6364. }
  6365. }
  6366. /* Note: mg_snprintf will not cause a buffer overflow above.
  6367. * So, string truncation checks are not required here. */
  6368. tm = localtime(&de->file.last_modified);
  6369. if (tm != NULL) {
  6370. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  6371. } else {
  6372. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  6373. mod[sizeof(mod) - 1] = '\0';
  6374. }
  6375. mg_url_encode(de->file_name, href, sizeof(href));
  6376. de->conn->num_bytes_sent +=
  6377. mg_printf(de->conn,
  6378. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  6379. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  6380. de->conn->request_info.local_uri,
  6381. href,
  6382. de->file.is_directory ? "/" : "",
  6383. de->file_name,
  6384. de->file.is_directory ? "/" : "",
  6385. mod,
  6386. size);
  6387. }
  6388. /* This function is called from send_directory() and used for
  6389. * sorting directory entries by size, or name, or modification time.
  6390. * On windows, __cdecl specification is needed in case if project is built
  6391. * with __stdcall convention. qsort always requires __cdels callback. */
  6392. static int WINCDECL
  6393. compare_dir_entries(const void *p1, const void *p2)
  6394. {
  6395. if (p1 && p2) {
  6396. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  6397. const char *query_string = a->conn->request_info.query_string;
  6398. int cmp_result = 0;
  6399. if (query_string == NULL) {
  6400. query_string = "na";
  6401. }
  6402. if (a->file.is_directory && !b->file.is_directory) {
  6403. return -1; /* Always put directories on top */
  6404. } else if (!a->file.is_directory && b->file.is_directory) {
  6405. return 1; /* Always put directories on top */
  6406. } else if (*query_string == 'n') {
  6407. cmp_result = strcmp(a->file_name, b->file_name);
  6408. } else if (*query_string == 's') {
  6409. cmp_result = (a->file.size == b->file.size)
  6410. ? 0
  6411. : ((a->file.size > b->file.size) ? 1 : -1);
  6412. } else if (*query_string == 'd') {
  6413. cmp_result =
  6414. (a->file.last_modified == b->file.last_modified)
  6415. ? 0
  6416. : ((a->file.last_modified > b->file.last_modified) ? 1
  6417. : -1);
  6418. }
  6419. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  6420. }
  6421. return 0;
  6422. }
  6423. static int
  6424. must_hide_file(struct mg_connection *conn, const char *path)
  6425. {
  6426. if (conn && conn->ctx) {
  6427. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  6428. const char *pattern = conn->ctx->config[HIDE_FILES];
  6429. return match_prefix(pw_pattern, strlen(pw_pattern), path) > 0
  6430. || (pattern != NULL
  6431. && match_prefix(pattern, strlen(pattern), path) > 0);
  6432. }
  6433. return 0;
  6434. }
  6435. static int
  6436. scan_directory(struct mg_connection *conn,
  6437. const char *dir,
  6438. void *data,
  6439. void (*cb)(struct de *, void *))
  6440. {
  6441. char path[PATH_MAX];
  6442. struct dirent *dp;
  6443. DIR *dirp;
  6444. struct de de;
  6445. int truncated;
  6446. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  6447. return 0;
  6448. } else {
  6449. de.conn = conn;
  6450. while ((dp = mg_readdir(dirp)) != NULL) {
  6451. /* Do not show current dir and hidden files */
  6452. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  6453. || must_hide_file(conn, dp->d_name)) {
  6454. continue;
  6455. }
  6456. mg_snprintf(
  6457. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  6458. /* If we don't memset stat structure to zero, mtime will have
  6459. * garbage and strftime() will segfault later on in
  6460. * print_dir_entry(). memset is required only if mg_stat()
  6461. * fails. For more details, see
  6462. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  6463. memset(&de.file, 0, sizeof(de.file));
  6464. if (truncated) {
  6465. /* If the path is not complete, skip processing. */
  6466. continue;
  6467. }
  6468. if (!mg_stat(conn, path, &de.file)) {
  6469. mg_cry(conn,
  6470. "%s: mg_stat(%s) failed: %s",
  6471. __func__,
  6472. path,
  6473. strerror(ERRNO));
  6474. }
  6475. de.file_name = dp->d_name;
  6476. cb(&de, data);
  6477. }
  6478. (void)mg_closedir(dirp);
  6479. }
  6480. return 1;
  6481. }
  6482. #if !defined(NO_FILES)
  6483. static int
  6484. remove_directory(struct mg_connection *conn, const char *dir)
  6485. {
  6486. char path[PATH_MAX];
  6487. struct dirent *dp;
  6488. DIR *dirp;
  6489. struct de de;
  6490. int truncated;
  6491. int ok = 1;
  6492. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  6493. return 0;
  6494. } else {
  6495. de.conn = conn;
  6496. while ((dp = mg_readdir(dirp)) != NULL) {
  6497. /* Do not show current dir (but show hidden files as they will
  6498. * also be removed) */
  6499. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  6500. continue;
  6501. }
  6502. mg_snprintf(
  6503. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  6504. /* If we don't memset stat structure to zero, mtime will have
  6505. * garbage and strftime() will segfault later on in
  6506. * print_dir_entry(). memset is required only if mg_stat()
  6507. * fails. For more details, see
  6508. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  6509. memset(&de.file, 0, sizeof(de.file));
  6510. if (truncated) {
  6511. /* Do not delete anything shorter */
  6512. ok = 0;
  6513. continue;
  6514. }
  6515. if (!mg_stat(conn, path, &de.file)) {
  6516. mg_cry(conn,
  6517. "%s: mg_stat(%s) failed: %s",
  6518. __func__,
  6519. path,
  6520. strerror(ERRNO));
  6521. ok = 0;
  6522. }
  6523. if (de.file.is_directory) {
  6524. if (remove_directory(conn, path) == 0) {
  6525. ok = 0;
  6526. }
  6527. } else {
  6528. /* This will fail file is the file is in memory */
  6529. if (mg_remove(conn, path) == 0) {
  6530. ok = 0;
  6531. }
  6532. }
  6533. }
  6534. (void)mg_closedir(dirp);
  6535. IGNORE_UNUSED_RESULT(rmdir(dir));
  6536. }
  6537. return ok;
  6538. }
  6539. #endif
  6540. struct dir_scan_data {
  6541. struct de *entries;
  6542. unsigned int num_entries;
  6543. unsigned int arr_size;
  6544. };
  6545. /* Behaves like realloc(), but frees original pointer on failure */
  6546. static void *
  6547. realloc2(void *ptr, size_t size)
  6548. {
  6549. void *new_ptr = mg_realloc(ptr, size);
  6550. if (new_ptr == NULL) {
  6551. mg_free(ptr);
  6552. }
  6553. return new_ptr;
  6554. }
  6555. static void
  6556. dir_scan_callback(struct de *de, void *data)
  6557. {
  6558. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  6559. if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {
  6560. dsd->arr_size *= 2;
  6561. dsd->entries =
  6562. (struct de *)realloc2(dsd->entries,
  6563. dsd->arr_size * sizeof(dsd->entries[0]));
  6564. }
  6565. if (dsd->entries == NULL) {
  6566. /* TODO(lsm, low): propagate an error to the caller */
  6567. dsd->num_entries = 0;
  6568. } else {
  6569. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  6570. dsd->entries[dsd->num_entries].file = de->file;
  6571. dsd->entries[dsd->num_entries].conn = de->conn;
  6572. dsd->num_entries++;
  6573. }
  6574. }
  6575. static void
  6576. handle_directory_request(struct mg_connection *conn, const char *dir)
  6577. {
  6578. unsigned int i;
  6579. int sort_direction;
  6580. struct dir_scan_data data = {NULL, 0, 128};
  6581. char date[64];
  6582. time_t curtime = time(NULL);
  6583. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  6584. mg_send_http_error(conn,
  6585. 500,
  6586. "Error: Cannot open directory\nopendir(%s): %s",
  6587. dir,
  6588. strerror(ERRNO));
  6589. return;
  6590. }
  6591. gmt_time_string(date, sizeof(date), &curtime);
  6592. if (!conn) {
  6593. return;
  6594. }
  6595. sort_direction = ((conn->request_info.query_string != NULL)
  6596. && (conn->request_info.query_string[1] == 'd'))
  6597. ? 'a'
  6598. : 'd';
  6599. conn->must_close = 1;
  6600. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  6601. send_static_cache_header(conn);
  6602. send_additional_header(conn);
  6603. mg_printf(conn,
  6604. "Date: %s\r\n"
  6605. "Connection: close\r\n"
  6606. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  6607. date);
  6608. conn->num_bytes_sent +=
  6609. mg_printf(conn,
  6610. "<html><head><title>Index of %s</title>"
  6611. "<style>th {text-align: left;}</style></head>"
  6612. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  6613. "<tr><th><a href=\"?n%c\">Name</a></th>"
  6614. "<th><a href=\"?d%c\">Modified</a></th>"
  6615. "<th><a href=\"?s%c\">Size</a></th></tr>"
  6616. "<tr><td colspan=\"3\"><hr></td></tr>",
  6617. conn->request_info.local_uri,
  6618. conn->request_info.local_uri,
  6619. sort_direction,
  6620. sort_direction,
  6621. sort_direction);
  6622. /* Print first entry - link to a parent directory */
  6623. conn->num_bytes_sent +=
  6624. mg_printf(conn,
  6625. "<tr><td><a href=\"%s%s\">%s</a></td>"
  6626. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  6627. conn->request_info.local_uri,
  6628. "..",
  6629. "Parent directory",
  6630. "-",
  6631. "-");
  6632. /* Sort and print directory entries */
  6633. if (data.entries != NULL) {
  6634. qsort(data.entries,
  6635. (size_t)data.num_entries,
  6636. sizeof(data.entries[0]),
  6637. compare_dir_entries);
  6638. for (i = 0; i < data.num_entries; i++) {
  6639. print_dir_entry(&data.entries[i]);
  6640. mg_free(data.entries[i].file_name);
  6641. }
  6642. mg_free(data.entries);
  6643. }
  6644. conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");
  6645. conn->status_code = 200;
  6646. }
  6647. /* Send len bytes from the opened file to the client. */
  6648. static void
  6649. send_file_data(struct mg_connection *conn,
  6650. struct mg_file *filep,
  6651. int64_t offset,
  6652. int64_t len)
  6653. {
  6654. char buf[MG_BUF_LEN];
  6655. int to_read, num_read, num_written;
  6656. int64_t size;
  6657. if (!filep || !conn) {
  6658. return;
  6659. }
  6660. /* Sanity check the offset */
  6661. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  6662. : (int64_t)(filep->stat.size);
  6663. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  6664. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  6665. /* file stored in memory */
  6666. if (len > size - offset) {
  6667. len = size - offset;
  6668. }
  6669. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  6670. } else if (len > 0 && filep->access.fp != NULL) {
  6671. /* file stored on disk */
  6672. #if defined(__linux__)
  6673. /* sendfile is only available for Linux */
  6674. if ((conn->ssl == 0) && (conn->throttle == 0)
  6675. && (!mg_strcasecmp(conn->ctx->config[ALLOW_SENDFILE_CALL],
  6676. "yes"))) {
  6677. off_t sf_offs = (off_t)offset;
  6678. ssize_t sf_sent;
  6679. int sf_file = fileno(filep->access.fp);
  6680. int loop_cnt = 0;
  6681. do {
  6682. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  6683. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  6684. size_t sf_tosend =
  6685. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  6686. sf_sent =
  6687. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  6688. if (sf_sent > 0) {
  6689. conn->num_bytes_sent += sf_sent;
  6690. len -= sf_sent;
  6691. offset += sf_sent;
  6692. } else if (loop_cnt == 0) {
  6693. /* This file can not be sent using sendfile.
  6694. * This might be the case for pseudo-files in the
  6695. * /sys/ and /proc/ file system.
  6696. * Use the regular user mode copy code instead. */
  6697. break;
  6698. } else if (sf_sent == 0) {
  6699. /* No error, but 0 bytes sent. May be EOF? */
  6700. return;
  6701. }
  6702. loop_cnt++;
  6703. } while ((len > 0) && (sf_sent >= 0));
  6704. if (sf_sent > 0) {
  6705. return; /* OK */
  6706. }
  6707. /* sf_sent<0 means error, thus fall back to the classic way */
  6708. /* This is always the case, if sf_file is not a "normal" file,
  6709. * e.g., for sending data from the output of a CGI process. */
  6710. offset = (int64_t)sf_offs;
  6711. }
  6712. #endif
  6713. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  6714. mg_cry(conn, "%s: fseeko() failed: %s", __func__, strerror(ERRNO));
  6715. mg_send_http_error(
  6716. conn,
  6717. 500,
  6718. "%s",
  6719. "Error: Unable to access file at requested position.");
  6720. } else {
  6721. while (len > 0) {
  6722. /* Calculate how much to read from the file in the buffer */
  6723. to_read = sizeof(buf);
  6724. if ((int64_t)to_read > len) {
  6725. to_read = (int)len;
  6726. }
  6727. /* Read from file, exit the loop on error */
  6728. if ((num_read =
  6729. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  6730. <= 0) {
  6731. break;
  6732. }
  6733. /* Send read bytes to the client, exit the loop on error */
  6734. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  6735. != num_read) {
  6736. break;
  6737. }
  6738. /* Both read and were successful, adjust counters */
  6739. conn->num_bytes_sent += num_written;
  6740. len -= num_written;
  6741. }
  6742. }
  6743. }
  6744. }
  6745. static int
  6746. parse_range_header(const char *header, int64_t *a, int64_t *b)
  6747. {
  6748. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  6749. }
  6750. static void
  6751. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  6752. {
  6753. if (filestat != NULL && buf != NULL) {
  6754. mg_snprintf(NULL,
  6755. NULL, /* All calls to construct_etag use 64 byte buffer */
  6756. buf,
  6757. buf_len,
  6758. "\"%lx.%" INT64_FMT "\"",
  6759. (unsigned long)filestat->last_modified,
  6760. filestat->size);
  6761. }
  6762. }
  6763. static void
  6764. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  6765. {
  6766. if (filep != NULL && filep->fp != NULL) {
  6767. #ifdef _WIN32
  6768. (void)conn; /* Unused. */
  6769. #else
  6770. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  6771. mg_cry(conn,
  6772. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  6773. __func__,
  6774. strerror(ERRNO));
  6775. }
  6776. #endif
  6777. }
  6778. }
  6779. static void
  6780. handle_static_file_request(struct mg_connection *conn,
  6781. const char *path,
  6782. struct mg_file *filep,
  6783. const char *mime_type,
  6784. const char *additional_headers)
  6785. {
  6786. char date[64], lm[64], etag[64];
  6787. char range[128]; /* large enough, so there will be no overflow */
  6788. const char *msg = "OK", *hdr;
  6789. time_t curtime = time(NULL);
  6790. int64_t cl, r1, r2;
  6791. struct vec mime_vec;
  6792. int n, truncated;
  6793. char gz_path[PATH_MAX];
  6794. const char *encoding = "";
  6795. const char *cors1, *cors2, *cors3;
  6796. if (conn == NULL || conn->ctx == NULL || filep == NULL) {
  6797. return;
  6798. }
  6799. if (mime_type == NULL) {
  6800. get_mime_type(conn->ctx, path, &mime_vec);
  6801. } else {
  6802. mime_vec.ptr = mime_type;
  6803. mime_vec.len = strlen(mime_type);
  6804. }
  6805. if (filep->stat.size > INT64_MAX) {
  6806. mg_send_http_error(conn,
  6807. 500,
  6808. "Error: File size is too large to send\n%" INT64_FMT,
  6809. filep->stat.size);
  6810. }
  6811. cl = (int64_t)filep->stat.size;
  6812. conn->status_code = 200;
  6813. range[0] = '\0';
  6814. /* if this file is in fact a pre-gzipped file, rewrite its filename
  6815. * it's important to rewrite the filename after resolving
  6816. * the mime type from it, to preserve the actual file's type */
  6817. if (filep->stat.is_gzipped) {
  6818. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  6819. if (truncated) {
  6820. mg_send_http_error(conn,
  6821. 500,
  6822. "Error: Path of zipped file too long (%s)",
  6823. path);
  6824. return;
  6825. }
  6826. path = gz_path;
  6827. encoding = "Content-Encoding: gzip\r\n";
  6828. }
  6829. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  6830. mg_send_http_error(conn,
  6831. 500,
  6832. "Error: Cannot open file\nfopen(%s): %s",
  6833. path,
  6834. strerror(ERRNO));
  6835. return;
  6836. }
  6837. fclose_on_exec(&filep->access, conn);
  6838. /* If Range: header specified, act accordingly */
  6839. r1 = r2 = 0;
  6840. hdr = mg_get_header(conn, "Range");
  6841. if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 && r1 >= 0
  6842. && r2 >= 0) {
  6843. /* actually, range requests don't play well with a pre-gzipped
  6844. * file (since the range is specified in the uncompressed space) */
  6845. if (filep->stat.is_gzipped) {
  6846. mg_send_http_error(
  6847. conn,
  6848. 416, /* 416 = Range Not Satisfiable */
  6849. "%s",
  6850. "Error: Range requests in gzipped files are not supported");
  6851. (void)mg_fclose(
  6852. &filep->access); /* ignore error on read only file */
  6853. return;
  6854. }
  6855. conn->status_code = 206;
  6856. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  6857. mg_snprintf(conn,
  6858. NULL, /* range buffer is big enough */
  6859. range,
  6860. sizeof(range),
  6861. "Content-Range: bytes "
  6862. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  6863. r1,
  6864. r1 + cl - 1,
  6865. filep->stat.size);
  6866. msg = "Partial Content";
  6867. }
  6868. hdr = mg_get_header(conn, "Origin");
  6869. if (hdr) {
  6870. /* Cross-origin resource sharing (CORS), see
  6871. * http://www.html5rocks.com/en/tutorials/cors/,
  6872. * http://www.html5rocks.com/static/images/cors_server_flowchart.png -
  6873. * preflight is not supported for files. */
  6874. cors1 = "Access-Control-Allow-Origin: ";
  6875. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  6876. cors3 = "\r\n";
  6877. } else {
  6878. cors1 = cors2 = cors3 = "";
  6879. }
  6880. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
  6881. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  6882. gmt_time_string(date, sizeof(date), &curtime);
  6883. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  6884. construct_etag(etag, sizeof(etag), &filep->stat);
  6885. (void)mg_printf(conn,
  6886. "HTTP/1.1 %d %s\r\n"
  6887. "%s%s%s"
  6888. "Date: %s\r\n",
  6889. conn->status_code,
  6890. msg,
  6891. cors1,
  6892. cors2,
  6893. cors3,
  6894. date);
  6895. send_static_cache_header(conn);
  6896. send_additional_header(conn);
  6897. (void)mg_printf(conn,
  6898. "Last-Modified: %s\r\n"
  6899. "Etag: %s\r\n"
  6900. "Content-Type: %.*s\r\n"
  6901. "Content-Length: %" INT64_FMT "\r\n"
  6902. "Connection: %s\r\n"
  6903. "Accept-Ranges: bytes\r\n"
  6904. "%s%s",
  6905. lm,
  6906. etag,
  6907. (int)mime_vec.len,
  6908. mime_vec.ptr,
  6909. cl,
  6910. suggest_connection_header(conn),
  6911. range,
  6912. encoding);
  6913. /* The previous code must not add any header starting with X- to make
  6914. * sure no one of the additional_headers is included twice */
  6915. if (additional_headers != NULL) {
  6916. (void)mg_printf(conn,
  6917. "%.*s\r\n\r\n",
  6918. (int)strlen(additional_headers),
  6919. additional_headers);
  6920. } else {
  6921. (void)mg_printf(conn, "\r\n");
  6922. }
  6923. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  6924. send_file_data(conn, filep, r1, cl);
  6925. }
  6926. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  6927. }
  6928. #if !defined(NO_CACHING)
  6929. static void
  6930. handle_not_modified_static_file_request(struct mg_connection *conn,
  6931. struct mg_file *filep)
  6932. {
  6933. char date[64], lm[64], etag[64];
  6934. time_t curtime = time(NULL);
  6935. if (conn == NULL || filep == NULL) {
  6936. return;
  6937. }
  6938. conn->status_code = 304;
  6939. gmt_time_string(date, sizeof(date), &curtime);
  6940. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  6941. construct_etag(etag, sizeof(etag), &filep->stat);
  6942. (void)mg_printf(conn,
  6943. "HTTP/1.1 %d %s\r\n"
  6944. "Date: %s\r\n",
  6945. conn->status_code,
  6946. mg_get_response_code_text(conn, conn->status_code),
  6947. date);
  6948. send_static_cache_header(conn);
  6949. send_additional_header(conn);
  6950. (void)mg_printf(conn,
  6951. "Last-Modified: %s\r\n"
  6952. "Etag: %s\r\n"
  6953. "Connection: %s\r\n"
  6954. "\r\n",
  6955. lm,
  6956. etag,
  6957. suggest_connection_header(conn));
  6958. }
  6959. #endif
  6960. void
  6961. mg_send_file(struct mg_connection *conn, const char *path)
  6962. {
  6963. mg_send_mime_file(conn, path, NULL);
  6964. }
  6965. void
  6966. mg_send_mime_file(struct mg_connection *conn,
  6967. const char *path,
  6968. const char *mime_type)
  6969. {
  6970. mg_send_mime_file2(conn, path, mime_type, NULL);
  6971. }
  6972. void
  6973. mg_send_mime_file2(struct mg_connection *conn,
  6974. const char *path,
  6975. const char *mime_type,
  6976. const char *additional_headers)
  6977. {
  6978. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6979. if (mg_stat(conn, path, &file.stat)) {
  6980. if (file.stat.is_directory) {
  6981. if (!conn) {
  6982. return;
  6983. }
  6984. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  6985. "yes")) {
  6986. handle_directory_request(conn, path);
  6987. } else {
  6988. mg_send_http_error(conn,
  6989. 403,
  6990. "%s",
  6991. "Error: Directory listing denied");
  6992. }
  6993. } else {
  6994. handle_static_file_request(
  6995. conn, path, &file, mime_type, additional_headers);
  6996. }
  6997. } else {
  6998. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  6999. }
  7000. }
  7001. /* For a given PUT path, create all intermediate subdirectories.
  7002. * Return 0 if the path itself is a directory.
  7003. * Return 1 if the path leads to a file.
  7004. * Return -1 for if the path is too long.
  7005. * Return -2 if path can not be created.
  7006. */
  7007. static int
  7008. put_dir(struct mg_connection *conn, const char *path)
  7009. {
  7010. char buf[PATH_MAX];
  7011. const char *s, *p;
  7012. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7013. size_t len;
  7014. int res = 1;
  7015. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  7016. len = (size_t)(p - path);
  7017. if (len >= sizeof(buf)) {
  7018. /* path too long */
  7019. res = -1;
  7020. break;
  7021. }
  7022. memcpy(buf, path, len);
  7023. buf[len] = '\0';
  7024. /* Try to create intermediate directory */
  7025. DEBUG_TRACE("mkdir(%s)", buf);
  7026. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  7027. /* path does not exixt and can not be created */
  7028. res = -2;
  7029. break;
  7030. }
  7031. /* Is path itself a directory? */
  7032. if (p[1] == '\0') {
  7033. res = 0;
  7034. }
  7035. }
  7036. return res;
  7037. }
  7038. static void
  7039. remove_bad_file(const struct mg_connection *conn, const char *path)
  7040. {
  7041. int r = mg_remove(conn, path);
  7042. if (r != 0) {
  7043. mg_cry(conn, "%s: Cannot remove invalid file %s", __func__, path);
  7044. }
  7045. }
  7046. long long
  7047. mg_store_body(struct mg_connection *conn, const char *path)
  7048. {
  7049. char buf[MG_BUF_LEN];
  7050. long long len = 0;
  7051. int ret, n;
  7052. struct mg_file fi;
  7053. if (conn->consumed_content != 0) {
  7054. mg_cry(conn, "%s: Contents already consumed", __func__);
  7055. return -11;
  7056. }
  7057. ret = put_dir(conn, path);
  7058. if (ret < 0) {
  7059. /* -1 for path too long,
  7060. * -2 for path can not be created. */
  7061. return ret;
  7062. }
  7063. if (ret != 1) {
  7064. /* Return 0 means, path itself is a directory. */
  7065. return 0;
  7066. }
  7067. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  7068. return -12;
  7069. }
  7070. ret = mg_read(conn, buf, sizeof(buf));
  7071. while (ret > 0) {
  7072. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  7073. if (n != ret) {
  7074. (void)mg_fclose(
  7075. &fi.access); /* File is bad and will be removed anyway. */
  7076. remove_bad_file(conn, path);
  7077. return -13;
  7078. }
  7079. len += ret;
  7080. ret = mg_read(conn, buf, sizeof(buf));
  7081. }
  7082. /* File is open for writing. If fclose fails, there was probably an
  7083. * error flushing the buffer to disk, so the file on disk might be
  7084. * broken. Delete it and return an error to the caller. */
  7085. if (mg_fclose(&fi.access) != 0) {
  7086. remove_bad_file(conn, path);
  7087. return -14;
  7088. }
  7089. return len;
  7090. }
  7091. /* Parse HTTP headers from the given buffer, advance buf pointer
  7092. * to the point where parsing stopped.
  7093. * All parameters must be valid pointers (not NULL).
  7094. * Return <0 on error. */
  7095. static int
  7096. parse_http_headers(char **buf, struct mg_request_info *ri)
  7097. {
  7098. int i;
  7099. ri->num_headers = 0;
  7100. for (i = 0; i < (int)ARRAY_SIZE(ri->http_headers); i++) {
  7101. char *dp = *buf;
  7102. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  7103. dp++;
  7104. }
  7105. if (dp == *buf) {
  7106. /* End of headers reached. */
  7107. break;
  7108. }
  7109. if (*dp != ':') {
  7110. /* This is not a valid field. */
  7111. return -1;
  7112. }
  7113. /* End of header key (*dp == ':') */
  7114. /* Truncate here and set the key name */
  7115. *dp = 0;
  7116. ri->http_headers[i].name = *buf;
  7117. do {
  7118. dp++;
  7119. } while (*dp == ' ');
  7120. /* The rest of the line is the value */
  7121. ri->http_headers[i].value = dp;
  7122. *buf = dp + strcspn(dp, "\r\n");
  7123. if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) {
  7124. *buf = NULL;
  7125. }
  7126. ri->num_headers = i + 1;
  7127. if (*buf) {
  7128. (*buf)[0] = 0;
  7129. (*buf)[1] = 0;
  7130. *buf += 2;
  7131. } else {
  7132. *buf = dp;
  7133. break;
  7134. }
  7135. if ((*buf)[0] == '\r') {
  7136. /* This is the end of the header */
  7137. break;
  7138. }
  7139. }
  7140. return ri->num_headers;
  7141. }
  7142. static int
  7143. is_valid_http_method(const char *method)
  7144. {
  7145. /* Check if the method is known to the server. The list of all known
  7146. * HTTP methods can be found here at
  7147. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  7148. */
  7149. return !strcmp(method, "GET") /* HTTP (RFC 2616) */
  7150. || !strcmp(method, "POST") /* HTTP (RFC 2616) */
  7151. || !strcmp(method, "HEAD") /* HTTP (RFC 2616) */
  7152. || !strcmp(method, "PUT") /* HTTP (RFC 2616) */
  7153. || !strcmp(method, "DELETE") /* HTTP (RFC 2616) */
  7154. || !strcmp(method, "OPTIONS") /* HTTP (RFC 2616) */
  7155. /* TRACE method (RFC 2616) is not supported for security reasons */
  7156. || !strcmp(method, "CONNECT") /* HTTP (RFC 2616) */
  7157. || !strcmp(method, "PROPFIND") /* WEBDAV (RFC 2518) */
  7158. || !strcmp(method, "MKCOL") /* WEBDAV (RFC 2518) */
  7159. /* Unsupported WEBDAV Methods: */
  7160. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  7161. /* + 11 methods from RFC 3253 */
  7162. /* ORDERPATCH (RFC 3648) */
  7163. /* ACL (RFC 3744) */
  7164. /* SEARCH (RFC 5323) */
  7165. /* + MicroSoft extensions
  7166. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  7167. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  7168. || !strcmp(method, "PATCH") /* PATCH method (RFC 5789) */
  7169. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  7170. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  7171. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  7172. * to be useful for REST in case a "GET request with body" is
  7173. * required. */
  7174. || !strcmp(method, "REPORT") /* REPORT method (RFC 3253) */
  7175. ;
  7176. }
  7177. /* Parse HTTP request, fill in mg_request_info structure.
  7178. * This function modifies the buffer by NUL-terminating
  7179. * HTTP request components, header names and header values.
  7180. * Parameters:
  7181. * buf (in/out): pointer to the HTTP header to parse and split
  7182. * len (in): length of HTTP header buffer
  7183. * re (out): parsed header as mg_request_info
  7184. * buf and ri must be valid pointers (not NULL), len>0.
  7185. * Returns <0 on error. */
  7186. static int
  7187. parse_http_message(char *buf, int len, struct mg_request_info *ri)
  7188. {
  7189. int is_request, request_length;
  7190. char *start_line;
  7191. request_length = get_request_len(buf, len);
  7192. if (request_length > 0) {
  7193. /* Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_addr,
  7194. * remote_port */
  7195. ri->remote_user = ri->request_method = ri->request_uri =
  7196. ri->http_version = NULL;
  7197. ri->num_headers = 0;
  7198. buf[request_length - 1] = '\0';
  7199. /* RFC says that all initial whitespaces should be ingored */
  7200. while (*buf != '\0' && isspace(*(unsigned char *)buf)) {
  7201. buf++;
  7202. }
  7203. start_line = skip(&buf, "\r\n");
  7204. ri->request_method = skip(&start_line, " ");
  7205. ri->request_uri = skip(&start_line, " ");
  7206. ri->http_version = start_line;
  7207. /* HTTP message could be either HTTP request:
  7208. * "GET / HTTP/1.0 ..."
  7209. * or a HTTP response:
  7210. * "HTTP/1.0 200 OK ..."
  7211. * otherwise it is invalid.
  7212. */
  7213. is_request = is_valid_http_method(ri->request_method);
  7214. if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0)
  7215. || (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
  7216. /* Not a valid request or response: invalid */
  7217. return -1;
  7218. }
  7219. if (is_request) {
  7220. ri->http_version += 5;
  7221. }
  7222. if (parse_http_headers(&buf, ri) < 0) {
  7223. /* Error while parsing headers */
  7224. return -1;
  7225. }
  7226. }
  7227. return request_length;
  7228. }
  7229. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  7230. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  7231. * buffer (which marks the end of HTTP request). Buffer buf may already
  7232. * have some data. The length of the data is stored in nread.
  7233. * Upon every read operation, increase nread by the number of bytes read. */
  7234. static int
  7235. read_request(FILE *fp,
  7236. struct mg_connection *conn,
  7237. char *buf,
  7238. int bufsiz,
  7239. int *nread)
  7240. {
  7241. int request_len, n = 0;
  7242. struct timespec last_action_time;
  7243. double request_timeout;
  7244. if (!conn) {
  7245. return 0;
  7246. }
  7247. memset(&last_action_time, 0, sizeof(last_action_time));
  7248. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  7249. /* value of request_timeout is in seconds, config in milliseconds */
  7250. request_timeout = atof(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  7251. } else {
  7252. request_timeout = -1.0;
  7253. }
  7254. if (conn->handled_requests > 0) {
  7255. if (conn->ctx->config[KEEP_ALIVE_TIMEOUT]) {
  7256. request_timeout =
  7257. atof(conn->ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  7258. }
  7259. }
  7260. request_len = get_request_len(buf, *nread);
  7261. /* first time reading from this connection */
  7262. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  7263. while (request_len == 0) {
  7264. /* Full request not yet received */
  7265. if (conn->ctx->stop_flag != 0) {
  7266. /* Server is to be stopped. */
  7267. return -1;
  7268. }
  7269. if (*nread >= bufsiz) {
  7270. /* Request too long */
  7271. return -2;
  7272. }
  7273. n = pull_inner(
  7274. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  7275. if (n == -2) {
  7276. /* Receive error */
  7277. return -1;
  7278. }
  7279. if (n > 0) {
  7280. *nread += n;
  7281. request_len = get_request_len(buf, *nread);
  7282. } else {
  7283. request_len = 0;
  7284. }
  7285. if ((request_len == 0) && (request_timeout >= 0)) {
  7286. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  7287. > request_timeout) {
  7288. /* Timeout */
  7289. return -1;
  7290. }
  7291. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  7292. }
  7293. }
  7294. return request_len;
  7295. }
  7296. #if !defined(NO_CACHING)
  7297. /* Return True if we should reply 304 Not Modified. */
  7298. static int
  7299. is_not_modified(const struct mg_connection *conn,
  7300. const struct mg_file_stat *filestat)
  7301. {
  7302. char etag[64];
  7303. const char *ims = mg_get_header(conn, "If-Modified-Since");
  7304. const char *inm = mg_get_header(conn, "If-None-Match");
  7305. construct_etag(etag, sizeof(etag), filestat);
  7306. return (inm != NULL && !mg_strcasecmp(etag, inm))
  7307. || ((ims != NULL)
  7308. && (filestat->last_modified <= parse_date_string(ims)));
  7309. }
  7310. #endif /* !NO_CACHING */
  7311. #if !defined(NO_CGI) || !defined(NO_FILES)
  7312. static int
  7313. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  7314. {
  7315. const char *expect, *body;
  7316. char buf[MG_BUF_LEN];
  7317. int to_read, nread, success = 0;
  7318. int64_t buffered_len;
  7319. double timeout = -1.0;
  7320. if (!conn) {
  7321. return 0;
  7322. }
  7323. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  7324. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  7325. }
  7326. expect = mg_get_header(conn, "Expect");
  7327. /* assert(fp != NULL); */
  7328. if (!fp) {
  7329. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  7330. return 0;
  7331. }
  7332. if (conn->content_len == -1 && !conn->is_chunked) {
  7333. /* Content length is not specified by the client. */
  7334. mg_send_http_error(conn,
  7335. 411,
  7336. "%s",
  7337. "Error: Client did not specify content length");
  7338. } else if ((expect != NULL)
  7339. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  7340. /* Client sent an "Expect: xyz" header and xyz is not 100-continue. */
  7341. mg_send_http_error(conn,
  7342. 417,
  7343. "Error: Can not fulfill expectation %s",
  7344. expect);
  7345. } else {
  7346. if (expect != NULL) {
  7347. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  7348. conn->status_code = 100;
  7349. } else {
  7350. conn->status_code = 200;
  7351. }
  7352. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  7353. - conn->consumed_content;
  7354. /* assert(buffered_len >= 0); */
  7355. /* assert(conn->consumed_content == 0); */
  7356. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  7357. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  7358. return 0;
  7359. }
  7360. if (buffered_len > 0) {
  7361. if ((int64_t)buffered_len > conn->content_len) {
  7362. buffered_len = (int)conn->content_len;
  7363. }
  7364. body = conn->buf + conn->request_len + conn->consumed_content;
  7365. push_all(conn->ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  7366. conn->consumed_content += buffered_len;
  7367. }
  7368. nread = 0;
  7369. while (conn->consumed_content < conn->content_len) {
  7370. to_read = sizeof(buf);
  7371. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  7372. to_read = (int)(conn->content_len - conn->consumed_content);
  7373. }
  7374. nread = pull_inner(NULL, conn, buf, to_read, timeout);
  7375. if (nread == -2) {
  7376. /* error */
  7377. break;
  7378. }
  7379. if (nread > 0) {
  7380. if (push_all(conn->ctx, fp, sock, ssl, buf, nread) != nread) {
  7381. break;
  7382. }
  7383. }
  7384. conn->consumed_content += nread;
  7385. }
  7386. if (conn->consumed_content == conn->content_len) {
  7387. success = (nread >= 0);
  7388. }
  7389. /* Each error code path in this function must send an error */
  7390. if (!success) {
  7391. /* NOTE: Maybe some data has already been sent. */
  7392. /* TODO (low): If some data has been sent, a correct error
  7393. * reply can no longer be sent, so just close the connection */
  7394. mg_send_http_error(conn, 500, "%s", "");
  7395. }
  7396. }
  7397. return success;
  7398. }
  7399. #endif
  7400. #if !defined(NO_CGI)
  7401. /* This structure helps to create an environment for the spawned CGI program.
  7402. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  7403. * last element must be NULL.
  7404. * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  7405. * strings must reside in a contiguous buffer. The end of the buffer is
  7406. * marked by two '\0' characters.
  7407. * We satisfy both worlds: we create an envp array (which is vars), all
  7408. * entries are actually pointers inside buf. */
  7409. struct cgi_environment {
  7410. struct mg_connection *conn;
  7411. /* Data block */
  7412. char *buf; /* Environment buffer */
  7413. size_t buflen; /* Space available in buf */
  7414. size_t bufused; /* Space taken in buf */
  7415. /* Index block */
  7416. char **var; /* char **envp */
  7417. size_t varlen; /* Number of variables available in var */
  7418. size_t varused; /* Number of variables stored in var */
  7419. };
  7420. static void addenv(struct cgi_environment *env,
  7421. PRINTF_FORMAT_STRING(const char *fmt),
  7422. ...) PRINTF_ARGS(2, 3);
  7423. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  7424. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  7425. static void
  7426. addenv(struct cgi_environment *env, const char *fmt, ...)
  7427. {
  7428. size_t n, space;
  7429. int truncated = 0;
  7430. char *added;
  7431. va_list ap;
  7432. /* Calculate how much space is left in the buffer */
  7433. space = (env->buflen - env->bufused);
  7434. /* Calculate an estimate for the required space */
  7435. n = strlen(fmt) + 2 + 128;
  7436. do {
  7437. if (space <= n) {
  7438. /* Allocate new buffer */
  7439. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  7440. added = (char *)mg_realloc(env->buf, n);
  7441. if (!added) {
  7442. /* Out of memory */
  7443. mg_cry(env->conn,
  7444. "%s: Cannot allocate memory for CGI variable [%s]",
  7445. __func__,
  7446. fmt);
  7447. return;
  7448. }
  7449. env->buf = added;
  7450. env->buflen = n;
  7451. space = (env->buflen - env->bufused);
  7452. }
  7453. /* Make a pointer to the free space int the buffer */
  7454. added = env->buf + env->bufused;
  7455. /* Copy VARIABLE=VALUE\0 string into the free space */
  7456. va_start(ap, fmt);
  7457. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  7458. va_end(ap);
  7459. /* Do not add truncated strings to the environment */
  7460. if (truncated) {
  7461. /* Reallocate the buffer */
  7462. space = 0;
  7463. n = 1;
  7464. }
  7465. } while (truncated);
  7466. /* Calculate number of bytes added to the environment */
  7467. n = strlen(added) + 1;
  7468. env->bufused += n;
  7469. /* Now update the variable index */
  7470. space = (env->varlen - env->varused);
  7471. if (space < 2) {
  7472. mg_cry(env->conn,
  7473. "%s: Cannot register CGI variable [%s]",
  7474. __func__,
  7475. fmt);
  7476. return;
  7477. }
  7478. /* Append a pointer to the added string into the envp array */
  7479. env->var[env->varused] = added;
  7480. env->varused++;
  7481. }
  7482. static void
  7483. prepare_cgi_environment(struct mg_connection *conn,
  7484. const char *prog,
  7485. struct cgi_environment *env)
  7486. {
  7487. const char *s;
  7488. struct vec var_vec;
  7489. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  7490. int i, truncated, uri_len;
  7491. if (conn == NULL || prog == NULL || env == NULL) {
  7492. return;
  7493. }
  7494. env->conn = conn;
  7495. env->buflen = CGI_ENVIRONMENT_SIZE;
  7496. env->bufused = 0;
  7497. env->buf = (char *)mg_malloc(env->buflen);
  7498. env->varlen = MAX_CGI_ENVIR_VARS;
  7499. env->varused = 0;
  7500. env->var = (char **)mg_malloc(env->buflen * sizeof(char *));
  7501. addenv(env, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  7502. addenv(env, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  7503. addenv(env, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  7504. addenv(env, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  7505. /* Prepare the environment block */
  7506. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  7507. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  7508. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  7509. #if defined(USE_IPV6)
  7510. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  7511. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  7512. } else
  7513. #endif
  7514. {
  7515. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  7516. }
  7517. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  7518. addenv(env, "REMOTE_ADDR=%s", src_addr);
  7519. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  7520. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  7521. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  7522. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  7523. /* SCRIPT_NAME */
  7524. uri_len = (int)strlen(conn->request_info.local_uri);
  7525. if (conn->path_info == NULL) {
  7526. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  7527. /* URI: /path_to_script/script.cgi */
  7528. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  7529. } else {
  7530. /* URI: /path_to_script/ ... using index.cgi */
  7531. const char *index_file = strrchr(prog, '/');
  7532. if (index_file) {
  7533. addenv(env,
  7534. "SCRIPT_NAME=%s%s",
  7535. conn->request_info.local_uri,
  7536. index_file + 1);
  7537. }
  7538. }
  7539. } else {
  7540. /* URI: /path_to_script/script.cgi/path_info */
  7541. addenv(env,
  7542. "SCRIPT_NAME=%.*s",
  7543. uri_len - (int)strlen(conn->path_info),
  7544. conn->request_info.local_uri);
  7545. }
  7546. addenv(env, "SCRIPT_FILENAME=%s", prog);
  7547. if (conn->path_info == NULL) {
  7548. addenv(env, "PATH_TRANSLATED=%s", conn->ctx->config[DOCUMENT_ROOT]);
  7549. } else {
  7550. addenv(env,
  7551. "PATH_TRANSLATED=%s%s",
  7552. conn->ctx->config[DOCUMENT_ROOT],
  7553. conn->path_info);
  7554. }
  7555. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  7556. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  7557. addenv(env, "CONTENT_TYPE=%s", s);
  7558. }
  7559. if (conn->request_info.query_string != NULL) {
  7560. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  7561. }
  7562. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  7563. addenv(env, "CONTENT_LENGTH=%s", s);
  7564. }
  7565. if ((s = getenv("PATH")) != NULL) {
  7566. addenv(env, "PATH=%s", s);
  7567. }
  7568. if (conn->path_info != NULL) {
  7569. addenv(env, "PATH_INFO=%s", conn->path_info);
  7570. }
  7571. if (conn->status_code > 0) {
  7572. /* CGI error handler should show the status code */
  7573. addenv(env, "STATUS=%d", conn->status_code);
  7574. }
  7575. #if defined(_WIN32)
  7576. if ((s = getenv("COMSPEC")) != NULL) {
  7577. addenv(env, "COMSPEC=%s", s);
  7578. }
  7579. if ((s = getenv("SYSTEMROOT")) != NULL) {
  7580. addenv(env, "SYSTEMROOT=%s", s);
  7581. }
  7582. if ((s = getenv("SystemDrive")) != NULL) {
  7583. addenv(env, "SystemDrive=%s", s);
  7584. }
  7585. if ((s = getenv("ProgramFiles")) != NULL) {
  7586. addenv(env, "ProgramFiles=%s", s);
  7587. }
  7588. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  7589. addenv(env, "ProgramFiles(x86)=%s", s);
  7590. }
  7591. #else
  7592. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  7593. addenv(env, "LD_LIBRARY_PATH=%s", s);
  7594. }
  7595. #endif /* _WIN32 */
  7596. if ((s = getenv("PERLLIB")) != NULL) {
  7597. addenv(env, "PERLLIB=%s", s);
  7598. }
  7599. if (conn->request_info.remote_user != NULL) {
  7600. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  7601. addenv(env, "%s", "AUTH_TYPE=Digest");
  7602. }
  7603. /* Add all headers as HTTP_* variables */
  7604. for (i = 0; i < conn->request_info.num_headers; i++) {
  7605. (void)mg_snprintf(conn,
  7606. &truncated,
  7607. http_var_name,
  7608. sizeof(http_var_name),
  7609. "HTTP_%s",
  7610. conn->request_info.http_headers[i].name);
  7611. if (truncated) {
  7612. mg_cry(conn,
  7613. "%s: HTTP header variable too long [%s]",
  7614. __func__,
  7615. conn->request_info.http_headers[i].name);
  7616. continue;
  7617. }
  7618. /* Convert variable name into uppercase, and change - to _ */
  7619. for (p = http_var_name; *p != '\0'; p++) {
  7620. if (*p == '-') {
  7621. *p = '_';
  7622. }
  7623. *p = (char)toupper(*(unsigned char *)p);
  7624. }
  7625. addenv(env,
  7626. "%s=%s",
  7627. http_var_name,
  7628. conn->request_info.http_headers[i].value);
  7629. }
  7630. /* Add user-specified variables */
  7631. s = conn->ctx->config[CGI_ENVIRONMENT];
  7632. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  7633. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  7634. }
  7635. env->var[env->varused] = NULL;
  7636. env->buf[env->bufused] = '\0';
  7637. }
  7638. static void
  7639. handle_cgi_request(struct mg_connection *conn, const char *prog)
  7640. {
  7641. char *buf;
  7642. size_t buflen;
  7643. int headers_len, data_len, i, truncated;
  7644. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  7645. const char *status, *status_text, *connection_state;
  7646. char *pbuf, dir[PATH_MAX], *p;
  7647. struct mg_request_info ri;
  7648. struct cgi_environment blk;
  7649. FILE *in = NULL, *out = NULL, *err = NULL;
  7650. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  7651. pid_t pid = (pid_t)-1;
  7652. if (conn == NULL) {
  7653. return;
  7654. }
  7655. buf = NULL;
  7656. buflen = 16384;
  7657. prepare_cgi_environment(conn, prog, &blk);
  7658. /* CGI must be executed in its own directory. 'dir' must point to the
  7659. * directory containing executable program, 'p' must point to the
  7660. * executable program name relative to 'dir'. */
  7661. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  7662. if (truncated) {
  7663. mg_cry(conn, "Error: CGI program \"%s\": Path too long", prog);
  7664. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  7665. goto done;
  7666. }
  7667. if ((p = strrchr(dir, '/')) != NULL) {
  7668. *p++ = '\0';
  7669. } else {
  7670. dir[0] = '.', dir[1] = '\0';
  7671. p = (char *)prog;
  7672. }
  7673. if (pipe(fdin) != 0 || pipe(fdout) != 0 || pipe(fderr) != 0) {
  7674. status = strerror(ERRNO);
  7675. mg_cry(conn,
  7676. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  7677. prog,
  7678. status);
  7679. mg_send_http_error(conn,
  7680. 500,
  7681. "Error: Cannot create CGI pipe: %s",
  7682. status);
  7683. goto done;
  7684. }
  7685. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  7686. if (pid == (pid_t)-1) {
  7687. status = strerror(ERRNO);
  7688. mg_cry(conn,
  7689. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  7690. prog,
  7691. status);
  7692. mg_send_http_error(conn,
  7693. 500,
  7694. "Error: Cannot spawn CGI process [%s]: %s",
  7695. prog,
  7696. status);
  7697. goto done;
  7698. }
  7699. /* Make sure child closes all pipe descriptors. It must dup them to 0,1 */
  7700. set_close_on_exec((SOCKET)fdin[0], conn); /* stdin read */
  7701. set_close_on_exec((SOCKET)fdout[1], conn); /* stdout write */
  7702. set_close_on_exec((SOCKET)fderr[1], conn); /* stderr write */
  7703. set_close_on_exec((SOCKET)fdin[1], conn); /* stdin write */
  7704. set_close_on_exec((SOCKET)fdout[0], conn); /* stdout read */
  7705. set_close_on_exec((SOCKET)fderr[0], conn); /* stderr read */
  7706. /* Parent closes only one side of the pipes.
  7707. * If we don't mark them as closed, close() attempt before
  7708. * return from this function throws an exception on Windows.
  7709. * Windows does not like when closed descriptor is closed again. */
  7710. (void)close(fdin[0]);
  7711. (void)close(fdout[1]);
  7712. (void)close(fderr[1]);
  7713. fdin[0] = fdout[1] = fderr[1] = -1;
  7714. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  7715. status = strerror(ERRNO);
  7716. mg_cry(conn,
  7717. "Error: CGI program \"%s\": Can not open stdin: %s",
  7718. prog,
  7719. status);
  7720. mg_send_http_error(conn,
  7721. 500,
  7722. "Error: CGI can not open fdin\nfopen: %s",
  7723. status);
  7724. goto done;
  7725. }
  7726. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  7727. status = strerror(ERRNO);
  7728. mg_cry(conn,
  7729. "Error: CGI program \"%s\": Can not open stdout: %s",
  7730. prog,
  7731. status);
  7732. mg_send_http_error(conn,
  7733. 500,
  7734. "Error: CGI can not open fdout\nfopen: %s",
  7735. status);
  7736. goto done;
  7737. }
  7738. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  7739. status = strerror(ERRNO);
  7740. mg_cry(conn,
  7741. "Error: CGI program \"%s\": Can not open stderr: %s",
  7742. prog,
  7743. status);
  7744. mg_send_http_error(conn,
  7745. 500,
  7746. "Error: CGI can not open fdout\nfopen: %s",
  7747. status);
  7748. goto done;
  7749. }
  7750. setbuf(in, NULL);
  7751. setbuf(out, NULL);
  7752. setbuf(err, NULL);
  7753. fout.access.fp = out;
  7754. if ((conn->request_info.content_length > 0) || conn->is_chunked) {
  7755. /* This is a POST/PUT request, or another request with body data. */
  7756. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  7757. /* Error sending the body data */
  7758. mg_cry(conn,
  7759. "Error: CGI program \"%s\": Forward body data failed",
  7760. prog);
  7761. goto done;
  7762. }
  7763. }
  7764. /* Close so child gets an EOF. */
  7765. fclose(in);
  7766. in = NULL;
  7767. fdin[1] = -1;
  7768. /* Now read CGI reply into a buffer. We need to set correct
  7769. * status code, thus we need to see all HTTP headers first.
  7770. * Do not send anything back to client, until we buffer in all
  7771. * HTTP headers. */
  7772. data_len = 0;
  7773. buf = (char *)mg_malloc(buflen);
  7774. if (buf == NULL) {
  7775. mg_send_http_error(conn,
  7776. 500,
  7777. "Error: Not enough memory for CGI buffer (%u bytes)",
  7778. (unsigned int)buflen);
  7779. mg_cry(conn,
  7780. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  7781. "bytes)",
  7782. prog,
  7783. (unsigned int)buflen);
  7784. goto done;
  7785. }
  7786. headers_len = read_request(out, conn, buf, (int)buflen, &data_len);
  7787. if (headers_len <= 0) {
  7788. /* Could not parse the CGI response. Check if some error message on
  7789. * stderr. */
  7790. i = pull_all(err, conn, buf, (int)buflen);
  7791. if (i > 0) {
  7792. mg_cry(conn,
  7793. "Error: CGI program \"%s\" sent error "
  7794. "message: [%.*s]",
  7795. prog,
  7796. i,
  7797. buf);
  7798. mg_send_http_error(conn,
  7799. 500,
  7800. "Error: CGI program \"%s\" sent error "
  7801. "message: [%.*s]",
  7802. prog,
  7803. i,
  7804. buf);
  7805. } else {
  7806. mg_cry(conn,
  7807. "Error: CGI program sent malformed or too big "
  7808. "(>%u bytes) HTTP headers: [%.*s]",
  7809. (unsigned)buflen,
  7810. data_len,
  7811. buf);
  7812. mg_send_http_error(conn,
  7813. 500,
  7814. "Error: CGI program sent malformed or too big "
  7815. "(>%u bytes) HTTP headers: [%.*s]",
  7816. (unsigned)buflen,
  7817. data_len,
  7818. buf);
  7819. }
  7820. goto done;
  7821. }
  7822. pbuf = buf;
  7823. buf[headers_len - 1] = '\0';
  7824. parse_http_headers(&pbuf, &ri);
  7825. /* Make up and send the status line */
  7826. status_text = "OK";
  7827. if ((status = get_header(&ri, "Status")) != NULL) {
  7828. conn->status_code = atoi(status);
  7829. status_text = status;
  7830. while (isdigit(*(const unsigned char *)status_text)
  7831. || *status_text == ' ') {
  7832. status_text++;
  7833. }
  7834. } else if (get_header(&ri, "Location") != NULL) {
  7835. conn->status_code = 302;
  7836. } else {
  7837. conn->status_code = 200;
  7838. }
  7839. connection_state = get_header(&ri, "Connection");
  7840. if (!header_has_option(connection_state, "keep-alive")) {
  7841. conn->must_close = 1;
  7842. }
  7843. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  7844. /* Send headers */
  7845. for (i = 0; i < ri.num_headers; i++) {
  7846. mg_printf(conn,
  7847. "%s: %s\r\n",
  7848. ri.http_headers[i].name,
  7849. ri.http_headers[i].value);
  7850. }
  7851. mg_write(conn, "\r\n", 2);
  7852. /* Send chunk of data that may have been read after the headers */
  7853. conn->num_bytes_sent +=
  7854. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  7855. /* Read the rest of CGI output and send to the client */
  7856. send_file_data(conn, &fout, 0, INT64_MAX);
  7857. done:
  7858. mg_free(blk.var);
  7859. mg_free(blk.buf);
  7860. if (pid != (pid_t)-1) {
  7861. kill(pid, SIGKILL);
  7862. #if !defined(_WIN32)
  7863. {
  7864. int st;
  7865. while (waitpid(pid, &st, 0) != -1)
  7866. ; /* clean zombies */
  7867. }
  7868. #endif
  7869. }
  7870. if (fdin[0] != -1) {
  7871. close(fdin[0]);
  7872. }
  7873. if (fdout[1] != -1) {
  7874. close(fdout[1]);
  7875. }
  7876. if (in != NULL) {
  7877. fclose(in);
  7878. } else if (fdin[1] != -1) {
  7879. close(fdin[1]);
  7880. }
  7881. if (out != NULL) {
  7882. fclose(out);
  7883. } else if (fdout[0] != -1) {
  7884. close(fdout[0]);
  7885. }
  7886. if (err != NULL) {
  7887. fclose(err);
  7888. } else if (fderr[0] != -1) {
  7889. close(fderr[0]);
  7890. }
  7891. if (buf != NULL) {
  7892. mg_free(buf);
  7893. }
  7894. }
  7895. #endif /* !NO_CGI */
  7896. #if !defined(NO_FILES)
  7897. static void
  7898. mkcol(struct mg_connection *conn, const char *path)
  7899. {
  7900. int rc, body_len;
  7901. struct de de;
  7902. char date[64];
  7903. time_t curtime = time(NULL);
  7904. if (conn == NULL) {
  7905. return;
  7906. }
  7907. /* TODO (mid): Check the mg_send_http_error situations in this function */
  7908. memset(&de.file, 0, sizeof(de.file));
  7909. if (!mg_stat(conn, path, &de.file)) {
  7910. mg_cry(conn,
  7911. "%s: mg_stat(%s) failed: %s",
  7912. __func__,
  7913. path,
  7914. strerror(ERRNO));
  7915. }
  7916. if (de.file.last_modified) {
  7917. /* TODO (mid): This check does not seem to make any sense ! */
  7918. /* TODO (mid): Add a webdav unit test first, before changing
  7919. * anything here. */
  7920. mg_send_http_error(
  7921. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7922. return;
  7923. }
  7924. body_len = conn->data_len - conn->request_len;
  7925. if (body_len > 0) {
  7926. mg_send_http_error(
  7927. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7928. return;
  7929. }
  7930. rc = mg_mkdir(conn, path, 0755);
  7931. if (rc == 0) {
  7932. conn->status_code = 201;
  7933. gmt_time_string(date, sizeof(date), &curtime);
  7934. mg_printf(conn,
  7935. "HTTP/1.1 %d Created\r\n"
  7936. "Date: %s\r\n",
  7937. conn->status_code,
  7938. date);
  7939. send_static_cache_header(conn);
  7940. send_additional_header(conn);
  7941. mg_printf(conn,
  7942. "Content-Length: 0\r\n"
  7943. "Connection: %s\r\n\r\n",
  7944. suggest_connection_header(conn));
  7945. } else if (rc == -1) {
  7946. if (errno == EEXIST) {
  7947. mg_send_http_error(
  7948. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7949. } else if (errno == EACCES) {
  7950. mg_send_http_error(
  7951. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7952. } else if (errno == ENOENT) {
  7953. mg_send_http_error(
  7954. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7955. } else {
  7956. mg_send_http_error(
  7957. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  7958. }
  7959. }
  7960. }
  7961. static void
  7962. put_file(struct mg_connection *conn, const char *path)
  7963. {
  7964. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7965. const char *range;
  7966. int64_t r1, r2;
  7967. int rc;
  7968. char date[64];
  7969. time_t curtime = time(NULL);
  7970. if (conn == NULL) {
  7971. return;
  7972. }
  7973. if (mg_stat(conn, path, &file.stat)) {
  7974. /* File already exists */
  7975. conn->status_code = 200;
  7976. if (file.stat.is_directory) {
  7977. /* This is an already existing directory,
  7978. * so there is nothing to do for the server. */
  7979. rc = 0;
  7980. } else {
  7981. /* File exists and is not a directory. */
  7982. /* Can it be replaced? */
  7983. if (file.access.membuf != NULL) {
  7984. /* This is an "in-memory" file, that can not be replaced */
  7985. mg_send_http_error(
  7986. conn,
  7987. 405,
  7988. "Error: Put not possible\nReplacing %s is not supported",
  7989. path);
  7990. return;
  7991. }
  7992. /* Check if the server may write this file */
  7993. if (access(path, W_OK) == 0) {
  7994. /* Access granted */
  7995. conn->status_code = 200;
  7996. rc = 1;
  7997. } else {
  7998. mg_send_http_error(
  7999. conn,
  8000. 403,
  8001. "Error: Put not possible\nReplacing %s is not allowed",
  8002. path);
  8003. return;
  8004. }
  8005. }
  8006. } else {
  8007. /* File should be created */
  8008. conn->status_code = 201;
  8009. rc = put_dir(conn, path);
  8010. }
  8011. if (rc == 0) {
  8012. /* put_dir returns 0 if path is a directory */
  8013. gmt_time_string(date, sizeof(date), &curtime);
  8014. mg_printf(conn,
  8015. "HTTP/1.1 %d %s\r\n",
  8016. conn->status_code,
  8017. mg_get_response_code_text(NULL, conn->status_code));
  8018. send_no_cache_header(conn);
  8019. send_additional_header(conn);
  8020. mg_printf(conn,
  8021. "Date: %s\r\n"
  8022. "Content-Length: 0\r\n"
  8023. "Connection: %s\r\n\r\n",
  8024. date,
  8025. suggest_connection_header(conn));
  8026. /* Request to create a directory has been fulfilled successfully.
  8027. * No need to put a file. */
  8028. return;
  8029. }
  8030. if (rc == -1) {
  8031. /* put_dir returns -1 if the path is too long */
  8032. mg_send_http_error(conn,
  8033. 414,
  8034. "Error: Path too long\nput_dir(%s): %s",
  8035. path,
  8036. strerror(ERRNO));
  8037. return;
  8038. }
  8039. if (rc == -2) {
  8040. /* put_dir returns -2 if the directory can not be created */
  8041. mg_send_http_error(conn,
  8042. 500,
  8043. "Error: Can not create directory\nput_dir(%s): %s",
  8044. path,
  8045. strerror(ERRNO));
  8046. return;
  8047. }
  8048. /* A file should be created or overwritten. */
  8049. /* Currently CivetWeb does not nead read+write access. */
  8050. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  8051. || file.access.fp == NULL) {
  8052. (void)mg_fclose(&file.access);
  8053. mg_send_http_error(conn,
  8054. 500,
  8055. "Error: Can not create file\nfopen(%s): %s",
  8056. path,
  8057. strerror(ERRNO));
  8058. return;
  8059. }
  8060. fclose_on_exec(&file.access, conn);
  8061. range = mg_get_header(conn, "Content-Range");
  8062. r1 = r2 = 0;
  8063. if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
  8064. conn->status_code = 206; /* Partial content */
  8065. fseeko(file.access.fp, r1, SEEK_SET);
  8066. }
  8067. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  8068. /* forward_body_data failed.
  8069. * The error code has already been sent to the client,
  8070. * and conn->status_code is already set. */
  8071. (void)mg_fclose(&file.access);
  8072. return;
  8073. }
  8074. if (mg_fclose(&file.access) != 0) {
  8075. /* fclose failed. This might have different reasons, but a likely
  8076. * one is "no space on disk", http 507. */
  8077. conn->status_code = 507;
  8078. }
  8079. gmt_time_string(date, sizeof(date), &curtime);
  8080. mg_printf(conn,
  8081. "HTTP/1.1 %d %s\r\n",
  8082. conn->status_code,
  8083. mg_get_response_code_text(NULL, conn->status_code));
  8084. send_no_cache_header(conn);
  8085. send_additional_header(conn);
  8086. mg_printf(conn,
  8087. "Date: %s\r\n"
  8088. "Content-Length: 0\r\n"
  8089. "Connection: %s\r\n\r\n",
  8090. date,
  8091. suggest_connection_header(conn));
  8092. }
  8093. static void
  8094. delete_file(struct mg_connection *conn, const char *path)
  8095. {
  8096. struct de de;
  8097. memset(&de.file, 0, sizeof(de.file));
  8098. if (!mg_stat(conn, path, &de.file)) {
  8099. /* mg_stat returns 0 if the file does not exist */
  8100. mg_send_http_error(conn,
  8101. 404,
  8102. "Error: Cannot delete file\nFile %s not found",
  8103. path);
  8104. return;
  8105. }
  8106. #if 0 /* Ignore if a file in memory is inside a folder */
  8107. if (de.access.membuf != NULL) {
  8108. /* the file is cached in memory */
  8109. mg_send_http_error(
  8110. conn,
  8111. 405,
  8112. "Error: Delete not possible\nDeleting %s is not supported",
  8113. path);
  8114. return;
  8115. }
  8116. #endif
  8117. if (de.file.is_directory) {
  8118. if (remove_directory(conn, path)) {
  8119. /* Delete is successful: Return 204 without content. */
  8120. mg_send_http_error(conn, 204, "%s", "");
  8121. } else {
  8122. /* Delete is not successful: Return 500 (Server error). */
  8123. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  8124. }
  8125. return;
  8126. }
  8127. /* This is an existing file (not a directory).
  8128. * Check if write permission is granted. */
  8129. if (access(path, W_OK) != 0) {
  8130. /* File is read only */
  8131. mg_send_http_error(
  8132. conn,
  8133. 403,
  8134. "Error: Delete not possible\nDeleting %s is not allowed",
  8135. path);
  8136. return;
  8137. }
  8138. /* Try to delete it. */
  8139. if (mg_remove(conn, path) == 0) {
  8140. /* Delete was successful: Return 204 without content. */
  8141. mg_send_http_error(conn, 204, "%s", "");
  8142. } else {
  8143. /* Delete not successful (file locked). */
  8144. mg_send_http_error(conn,
  8145. 423,
  8146. "Error: Cannot delete file\nremove(%s): %s",
  8147. path,
  8148. strerror(ERRNO));
  8149. }
  8150. }
  8151. #endif /* !NO_FILES */
  8152. static void
  8153. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  8154. static void
  8155. do_ssi_include(struct mg_connection *conn,
  8156. const char *ssi,
  8157. char *tag,
  8158. int include_level)
  8159. {
  8160. char file_name[MG_BUF_LEN], path[512], *p;
  8161. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8162. size_t len;
  8163. int truncated = 0;
  8164. if (conn == NULL) {
  8165. return;
  8166. }
  8167. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  8168. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  8169. * always < MG_BUF_LEN. */
  8170. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  8171. /* File name is relative to the webserver root */
  8172. file_name[511] = 0;
  8173. (void)mg_snprintf(conn,
  8174. &truncated,
  8175. path,
  8176. sizeof(path),
  8177. "%s/%s",
  8178. conn->ctx->config[DOCUMENT_ROOT],
  8179. file_name);
  8180. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  8181. /* File name is relative to the webserver working directory
  8182. * or it is absolute system path */
  8183. file_name[511] = 0;
  8184. (void)
  8185. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  8186. } else if (sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1
  8187. || sscanf(tag, " \"%511[^\"]\"", file_name) == 1) {
  8188. /* File name is relative to the currect document */
  8189. file_name[511] = 0;
  8190. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  8191. if (!truncated) {
  8192. if ((p = strrchr(path, '/')) != NULL) {
  8193. p[1] = '\0';
  8194. }
  8195. len = strlen(path);
  8196. (void)mg_snprintf(conn,
  8197. &truncated,
  8198. path + len,
  8199. sizeof(path) - len,
  8200. "%s",
  8201. file_name);
  8202. }
  8203. } else {
  8204. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  8205. return;
  8206. }
  8207. if (truncated) {
  8208. mg_cry(conn, "SSI #include path length overflow: [%s]", tag);
  8209. return;
  8210. }
  8211. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  8212. mg_cry(conn,
  8213. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  8214. tag,
  8215. path,
  8216. strerror(ERRNO));
  8217. } else {
  8218. fclose_on_exec(&file.access, conn);
  8219. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  8220. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  8221. path) > 0) {
  8222. send_ssi_file(conn, path, &file, include_level + 1);
  8223. } else {
  8224. send_file_data(conn, &file, 0, INT64_MAX);
  8225. }
  8226. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  8227. }
  8228. }
  8229. #if !defined(NO_POPEN)
  8230. static void
  8231. do_ssi_exec(struct mg_connection *conn, char *tag)
  8232. {
  8233. char cmd[1024] = "";
  8234. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8235. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  8236. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  8237. } else {
  8238. cmd[1023] = 0;
  8239. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  8240. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  8241. } else {
  8242. send_file_data(conn, &file, 0, INT64_MAX);
  8243. pclose(file.access.fp);
  8244. }
  8245. }
  8246. }
  8247. #endif /* !NO_POPEN */
  8248. static int
  8249. mg_fgetc(struct mg_file *filep, int offset)
  8250. {
  8251. if (filep == NULL) {
  8252. return EOF;
  8253. }
  8254. if (filep->access.membuf != NULL && offset >= 0
  8255. && ((unsigned int)(offset)) < filep->stat.size) {
  8256. return ((const unsigned char *)filep->access.membuf)[offset];
  8257. } else if (filep->access.fp != NULL) {
  8258. return fgetc(filep->access.fp);
  8259. } else {
  8260. return EOF;
  8261. }
  8262. }
  8263. static void
  8264. send_ssi_file(struct mg_connection *conn,
  8265. const char *path,
  8266. struct mg_file *filep,
  8267. int include_level)
  8268. {
  8269. char buf[MG_BUF_LEN];
  8270. int ch, offset, len, in_ssi_tag;
  8271. if (include_level > 10) {
  8272. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  8273. return;
  8274. }
  8275. in_ssi_tag = len = offset = 0;
  8276. while ((ch = mg_fgetc(filep, offset)) != EOF) {
  8277. if (in_ssi_tag && ch == '>') {
  8278. in_ssi_tag = 0;
  8279. buf[len++] = (char)ch;
  8280. buf[len] = '\0';
  8281. /* assert(len <= (int) sizeof(buf)); */
  8282. if (len > (int)sizeof(buf)) {
  8283. break;
  8284. }
  8285. if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
  8286. /* Not an SSI tag, pass it */
  8287. (void)mg_write(conn, buf, (size_t)len);
  8288. } else {
  8289. if (!memcmp(buf + 5, "include", 7)) {
  8290. do_ssi_include(conn, path, buf + 12, include_level);
  8291. #if !defined(NO_POPEN)
  8292. } else if (!memcmp(buf + 5, "exec", 4)) {
  8293. do_ssi_exec(conn, buf + 9);
  8294. #endif /* !NO_POPEN */
  8295. } else {
  8296. mg_cry(conn,
  8297. "%s: unknown SSI "
  8298. "command: \"%s\"",
  8299. path,
  8300. buf);
  8301. }
  8302. }
  8303. len = 0;
  8304. } else if (in_ssi_tag) {
  8305. if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
  8306. /* Not an SSI tag */
  8307. in_ssi_tag = 0;
  8308. } else if (len == (int)sizeof(buf) - 2) {
  8309. mg_cry(conn, "%s: SSI tag is too large", path);
  8310. len = 0;
  8311. }
  8312. buf[len++] = (char)(ch & 0xff);
  8313. } else if (ch == '<') {
  8314. in_ssi_tag = 1;
  8315. if (len > 0) {
  8316. mg_write(conn, buf, (size_t)len);
  8317. }
  8318. len = 0;
  8319. buf[len++] = (char)(ch & 0xff);
  8320. } else {
  8321. buf[len++] = (char)(ch & 0xff);
  8322. if (len == (int)sizeof(buf)) {
  8323. mg_write(conn, buf, (size_t)len);
  8324. len = 0;
  8325. }
  8326. }
  8327. }
  8328. /* Send the rest of buffered data */
  8329. if (len > 0) {
  8330. mg_write(conn, buf, (size_t)len);
  8331. }
  8332. }
  8333. static void
  8334. handle_ssi_file_request(struct mg_connection *conn,
  8335. const char *path,
  8336. struct mg_file *filep)
  8337. {
  8338. char date[64];
  8339. time_t curtime = time(NULL);
  8340. const char *cors1, *cors2, *cors3;
  8341. if (conn == NULL || path == NULL || filep == NULL) {
  8342. return;
  8343. }
  8344. if (mg_get_header(conn, "Origin")) {
  8345. /* Cross-origin resource sharing (CORS). */
  8346. cors1 = "Access-Control-Allow-Origin: ";
  8347. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  8348. cors3 = "\r\n";
  8349. } else {
  8350. cors1 = cors2 = cors3 = "";
  8351. }
  8352. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8353. /* File exists (precondition for calling this function),
  8354. * but can not be opened by the server. */
  8355. mg_send_http_error(conn,
  8356. 500,
  8357. "Error: Cannot read file\nfopen(%s): %s",
  8358. path,
  8359. strerror(ERRNO));
  8360. } else {
  8361. conn->must_close = 1;
  8362. gmt_time_string(date, sizeof(date), &curtime);
  8363. fclose_on_exec(&filep->access, conn);
  8364. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  8365. send_no_cache_header(conn);
  8366. send_additional_header(conn);
  8367. mg_printf(conn,
  8368. "%s%s%s"
  8369. "Date: %s\r\n"
  8370. "Content-Type: text/html\r\n"
  8371. "Connection: %s\r\n\r\n",
  8372. cors1,
  8373. cors2,
  8374. cors3,
  8375. date,
  8376. suggest_connection_header(conn));
  8377. send_ssi_file(conn, path, filep, 0);
  8378. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  8379. }
  8380. }
  8381. #if !defined(NO_FILES)
  8382. static void
  8383. send_options(struct mg_connection *conn)
  8384. {
  8385. char date[64];
  8386. time_t curtime = time(NULL);
  8387. if (!conn) {
  8388. return;
  8389. }
  8390. conn->status_code = 200;
  8391. conn->must_close = 1;
  8392. gmt_time_string(date, sizeof(date), &curtime);
  8393. /* We do not set a "Cache-Control" header here, but leave the default.
  8394. * Since browsers do not send an OPTIONS request, we can not test the
  8395. * effect anyway. */
  8396. mg_printf(conn,
  8397. "HTTP/1.1 200 OK\r\n"
  8398. "Date: %s\r\n"
  8399. "Connection: %s\r\n"
  8400. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  8401. "PROPFIND, MKCOL\r\n"
  8402. "DAV: 1\r\n",
  8403. date,
  8404. suggest_connection_header(conn));
  8405. send_additional_header(conn);
  8406. mg_printf(conn, "\r\n");
  8407. }
  8408. /* Writes PROPFIND properties for a collection element */
  8409. static void
  8410. print_props(struct mg_connection *conn,
  8411. const char *uri,
  8412. struct mg_file_stat *filep)
  8413. {
  8414. char mtime[64];
  8415. if (conn == NULL || uri == NULL || filep == NULL) {
  8416. return;
  8417. }
  8418. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  8419. conn->num_bytes_sent +=
  8420. mg_printf(conn,
  8421. "<d:response>"
  8422. "<d:href>%s</d:href>"
  8423. "<d:propstat>"
  8424. "<d:prop>"
  8425. "<d:resourcetype>%s</d:resourcetype>"
  8426. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  8427. "<d:getlastmodified>%s</d:getlastmodified>"
  8428. "</d:prop>"
  8429. "<d:status>HTTP/1.1 200 OK</d:status>"
  8430. "</d:propstat>"
  8431. "</d:response>\n",
  8432. uri,
  8433. filep->is_directory ? "<d:collection/>" : "",
  8434. filep->size,
  8435. mtime);
  8436. }
  8437. static void
  8438. print_dav_dir_entry(struct de *de, void *data)
  8439. {
  8440. char href[PATH_MAX];
  8441. char href_encoded[PATH_MAX * 3 /* worst case */];
  8442. int truncated;
  8443. struct mg_connection *conn = (struct mg_connection *)data;
  8444. if (!de || !conn) {
  8445. return;
  8446. }
  8447. mg_snprintf(conn,
  8448. &truncated,
  8449. href,
  8450. sizeof(href),
  8451. "%s%s",
  8452. conn->request_info.local_uri,
  8453. de->file_name);
  8454. if (!truncated) {
  8455. mg_url_encode(href, href_encoded, PATH_MAX * 3);
  8456. print_props(conn, href_encoded, &de->file);
  8457. }
  8458. }
  8459. static void
  8460. handle_propfind(struct mg_connection *conn,
  8461. const char *path,
  8462. struct mg_file_stat *filep)
  8463. {
  8464. const char *depth = mg_get_header(conn, "Depth");
  8465. char date[64];
  8466. time_t curtime = time(NULL);
  8467. gmt_time_string(date, sizeof(date), &curtime);
  8468. if (!conn || !path || !filep || !conn->ctx) {
  8469. return;
  8470. }
  8471. conn->must_close = 1;
  8472. conn->status_code = 207;
  8473. mg_printf(conn,
  8474. "HTTP/1.1 207 Multi-Status\r\n"
  8475. "Date: %s\r\n",
  8476. date);
  8477. send_static_cache_header(conn);
  8478. send_additional_header(conn);
  8479. mg_printf(conn,
  8480. "Connection: %s\r\n"
  8481. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  8482. suggest_connection_header(conn));
  8483. conn->num_bytes_sent +=
  8484. mg_printf(conn,
  8485. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  8486. "<d:multistatus xmlns:d='DAV:'>\n");
  8487. /* Print properties for the requested resource itself */
  8488. print_props(conn, conn->request_info.local_uri, filep);
  8489. /* If it is a directory, print directory entries too if Depth is not 0 */
  8490. if (filep && filep->is_directory
  8491. && !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")
  8492. && (depth == NULL || strcmp(depth, "0") != 0)) {
  8493. scan_directory(conn, path, conn, &print_dav_dir_entry);
  8494. }
  8495. conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");
  8496. }
  8497. #endif
  8498. void
  8499. mg_lock_connection(struct mg_connection *conn)
  8500. {
  8501. if (conn) {
  8502. (void)pthread_mutex_lock(&conn->mutex);
  8503. }
  8504. }
  8505. void
  8506. mg_unlock_connection(struct mg_connection *conn)
  8507. {
  8508. if (conn) {
  8509. (void)pthread_mutex_unlock(&conn->mutex);
  8510. }
  8511. }
  8512. void
  8513. mg_lock_context(struct mg_context *ctx)
  8514. {
  8515. if (ctx) {
  8516. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  8517. }
  8518. }
  8519. void
  8520. mg_unlock_context(struct mg_context *ctx)
  8521. {
  8522. if (ctx) {
  8523. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  8524. }
  8525. }
  8526. #if defined(USE_TIMERS)
  8527. #define TIMER_API static
  8528. #include "timer.inl"
  8529. #endif /* USE_TIMERS */
  8530. #ifdef USE_LUA
  8531. #include "mod_lua.inl"
  8532. #endif /* USE_LUA */
  8533. #ifdef USE_DUKTAPE
  8534. #include "mod_duktape.inl"
  8535. #endif /* USE_DUKTAPE */
  8536. #if defined(USE_WEBSOCKET)
  8537. #if !defined(NO_SSL_DL)
  8538. #define SHA_API static
  8539. #include "sha1.inl"
  8540. #endif
  8541. static int
  8542. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  8543. {
  8544. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  8545. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  8546. SHA_CTX sha_ctx;
  8547. int truncated;
  8548. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  8549. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  8550. if (truncated) {
  8551. conn->must_close = 1;
  8552. return 0;
  8553. }
  8554. SHA1_Init(&sha_ctx);
  8555. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  8556. SHA1_Final((unsigned char *)sha, &sha_ctx);
  8557. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  8558. mg_printf(conn,
  8559. "HTTP/1.1 101 Switching Protocols\r\n"
  8560. "Upgrade: websocket\r\n"
  8561. "Connection: Upgrade\r\n"
  8562. "Sec-WebSocket-Accept: %s\r\n",
  8563. b64_sha);
  8564. if (conn->request_info.acceptedWebSocketSubprotocol) {
  8565. mg_printf(conn,
  8566. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  8567. conn->request_info.acceptedWebSocketSubprotocol);
  8568. } else {
  8569. mg_printf(conn, "%s", "\r\n");
  8570. }
  8571. return 1;
  8572. }
  8573. static void
  8574. read_websocket(struct mg_connection *conn,
  8575. mg_websocket_data_handler ws_data_handler,
  8576. void *callback_data)
  8577. {
  8578. /* Pointer to the beginning of the portion of the incoming websocket
  8579. * message queue.
  8580. * The original websocket upgrade request is never removed, so the queue
  8581. * begins after it. */
  8582. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  8583. int n, error, exit_by_callback;
  8584. /* body_len is the length of the entire queue in bytes
  8585. * len is the length of the current message
  8586. * data_len is the length of the current message's data payload
  8587. * header_len is the length of the current message's header */
  8588. size_t i, len, mask_len = 0, data_len = 0, header_len, body_len;
  8589. /* "The masking key is a 32-bit value chosen at random by the client."
  8590. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  8591. */
  8592. unsigned char mask[4];
  8593. /* data points to the place where the message is stored when passed to
  8594. * the
  8595. * websocket_data callback. This is either mem on the stack, or a
  8596. * dynamically allocated buffer if it is too large. */
  8597. unsigned char mem[4096];
  8598. unsigned char *data = mem;
  8599. unsigned char mop; /* mask flag and opcode */
  8600. double timeout = -1.0;
  8601. if (conn->ctx->config[WEBSOCKET_TIMEOUT]) {
  8602. timeout = atoi(conn->ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  8603. }
  8604. if ((timeout <= 0.0) && (conn->ctx->config[REQUEST_TIMEOUT])) {
  8605. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  8606. }
  8607. mg_set_thread_name("wsock");
  8608. /* Loop continuously, reading messages from the socket, invoking the
  8609. * callback, and waiting repeatedly until an error occurs. */
  8610. while (!conn->ctx->stop_flag) {
  8611. header_len = 0;
  8612. assert(conn->data_len >= conn->request_len);
  8613. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  8614. len = buf[1] & 127;
  8615. mask_len = (buf[1] & 128) ? 4 : 0;
  8616. if ((len < 126) && (body_len >= mask_len)) {
  8617. /* inline 7-bit length field */
  8618. data_len = len;
  8619. header_len = 2 + mask_len;
  8620. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  8621. /* 16-bit length field */
  8622. header_len = 4 + mask_len;
  8623. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  8624. } else if (body_len >= (10 + mask_len)) {
  8625. /* 64-bit length field */
  8626. uint32_t l1, l2;
  8627. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  8628. memcpy(&l2, &buf[6], 4);
  8629. header_len = 10 + mask_len;
  8630. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  8631. }
  8632. }
  8633. if (header_len > 0 && body_len >= header_len) {
  8634. /* Allocate space to hold websocket payload */
  8635. data = mem;
  8636. if (data_len > sizeof(mem)) {
  8637. data = (unsigned char *)mg_malloc(data_len);
  8638. if (data == NULL) {
  8639. /* Allocation failed, exit the loop and then close the
  8640. * connection */
  8641. mg_cry(conn, "websocket out of memory; closing connection");
  8642. break;
  8643. }
  8644. }
  8645. /* Copy the mask before we shift the queue and destroy it */
  8646. if (mask_len > 0) {
  8647. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  8648. } else {
  8649. memset(mask, 0, sizeof(mask));
  8650. }
  8651. /* Read frame payload from the first message in the queue into
  8652. * data and advance the queue by moving the memory in place. */
  8653. assert(body_len >= header_len);
  8654. if (data_len + header_len > body_len) {
  8655. mop = buf[0]; /* current mask and opcode */
  8656. /* Overflow case */
  8657. len = body_len - header_len;
  8658. memcpy(data, buf + header_len, len);
  8659. error = 0;
  8660. while (len < data_len) {
  8661. n = pull_inner(NULL,
  8662. conn,
  8663. (char *)(data + len),
  8664. (int)(data_len - len),
  8665. timeout);
  8666. if (n <= -2) {
  8667. error = 1;
  8668. break;
  8669. } else if (n > 0) {
  8670. len += (size_t)n;
  8671. } else {
  8672. /* Timeout: should retry */
  8673. /* TODO: retry condition */
  8674. }
  8675. }
  8676. if (error) {
  8677. mg_cry(conn, "Websocket pull failed; closing connection");
  8678. break;
  8679. }
  8680. conn->data_len = conn->request_len;
  8681. } else {
  8682. mop = buf[0]; /* current mask and opcode, overwritten by
  8683. * memmove() */
  8684. /* Length of the message being read at the front of the
  8685. * queue */
  8686. len = data_len + header_len;
  8687. /* Copy the data payload into the data pointer for the
  8688. * callback */
  8689. memcpy(data, buf + header_len, data_len);
  8690. /* Move the queue forward len bytes */
  8691. memmove(buf, buf + len, body_len - len);
  8692. /* Mark the queue as advanced */
  8693. conn->data_len -= (int)len;
  8694. }
  8695. /* Apply mask if necessary */
  8696. if (mask_len > 0) {
  8697. for (i = 0; i < data_len; ++i) {
  8698. data[i] ^= mask[i & 3];
  8699. }
  8700. }
  8701. /* Exit the loop if callback signals to exit (server side),
  8702. * or "connection close" opcode received (client side). */
  8703. exit_by_callback = 0;
  8704. if ((ws_data_handler != NULL)
  8705. && !ws_data_handler(
  8706. conn, mop, (char *)data, data_len, callback_data)) {
  8707. exit_by_callback = 1;
  8708. }
  8709. if (data != mem) {
  8710. mg_free(data);
  8711. }
  8712. if (exit_by_callback
  8713. || ((mop & 0xf) == WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  8714. /* Opcode == 8, connection close */
  8715. break;
  8716. }
  8717. /* Not breaking the loop, process next websocket frame. */
  8718. } else {
  8719. /* Read from the socket into the next available location in the
  8720. * message queue. */
  8721. n = pull_inner(NULL,
  8722. conn,
  8723. conn->buf + conn->data_len,
  8724. conn->buf_size - conn->data_len,
  8725. timeout);
  8726. if (n <= -2) {
  8727. /* Error, no bytes read */
  8728. break;
  8729. }
  8730. if (n > 0) {
  8731. conn->data_len += n;
  8732. } else {
  8733. /* Timeout: should retry */
  8734. /* TODO: get timeout def */
  8735. }
  8736. }
  8737. }
  8738. mg_set_thread_name("worker");
  8739. }
  8740. static int
  8741. mg_websocket_write_exec(struct mg_connection *conn,
  8742. int opcode,
  8743. const char *data,
  8744. size_t dataLen,
  8745. uint32_t masking_key)
  8746. {
  8747. unsigned char header[14];
  8748. size_t headerLen = 1;
  8749. int retval = -1;
  8750. #if defined(__GNUC__) || defined(__MINGW32__)
  8751. /* Disable spurious conversion warning for GCC */
  8752. #pragma GCC diagnostic push
  8753. #pragma GCC diagnostic ignored "-Wconversion"
  8754. #endif
  8755. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  8756. #if defined(__GNUC__) || defined(__MINGW32__)
  8757. #pragma GCC diagnostic pop
  8758. #endif
  8759. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  8760. if (dataLen < 126) {
  8761. /* inline 7-bit length field */
  8762. header[1] = (unsigned char)dataLen;
  8763. headerLen = 2;
  8764. } else if (dataLen <= 0xFFFF) {
  8765. /* 16-bit length field */
  8766. uint16_t len = htons((uint16_t)dataLen);
  8767. header[1] = 126;
  8768. memcpy(header + 2, &len, 2);
  8769. headerLen = 4;
  8770. } else {
  8771. /* 64-bit length field */
  8772. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  8773. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  8774. header[1] = 127;
  8775. memcpy(header + 2, &len1, 4);
  8776. memcpy(header + 6, &len2, 4);
  8777. headerLen = 10;
  8778. }
  8779. if (masking_key) {
  8780. /* add mask */
  8781. header[1] |= 0x80;
  8782. memcpy(header + headerLen, &masking_key, 4);
  8783. headerLen += 4;
  8784. }
  8785. /* Note that POSIX/Winsock's send() is threadsafe
  8786. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  8787. * but mongoose's mg_printf/mg_write is not (because of the loop in
  8788. * push(), although that is only a problem if the packet is large or
  8789. * outgoing buffer is full). */
  8790. /* TODO: Check if this lock should be moved to user land.
  8791. * Currently the server sets this lock for websockets, but
  8792. * not for any other connection. It must be set for every
  8793. * conn read/written by more than one thread, no matter if
  8794. * it is a websocket or regular connection. */
  8795. (void)mg_lock_connection(conn);
  8796. retval = mg_write(conn, header, headerLen);
  8797. if (dataLen > 0) {
  8798. retval = mg_write(conn, data, dataLen);
  8799. }
  8800. /* TODO: Remove this unlock as well, when lock is moved. */
  8801. mg_unlock_connection(conn);
  8802. return retval;
  8803. }
  8804. int
  8805. mg_websocket_write(struct mg_connection *conn,
  8806. int opcode,
  8807. const char *data,
  8808. size_t dataLen)
  8809. {
  8810. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  8811. }
  8812. static void
  8813. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  8814. {
  8815. size_t i = 0;
  8816. i = 0;
  8817. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  8818. /* Convert in 32 bit words, if data is 4 byte aligned */
  8819. while (i < (in_len - 3)) {
  8820. *(uint32_t *)(void *)(out + i) =
  8821. *(uint32_t *)(void *)(in + i) ^ masking_key;
  8822. i += 4;
  8823. }
  8824. }
  8825. if (i != in_len) {
  8826. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  8827. while (i < in_len) {
  8828. *(uint8_t *)(void *)(out + i) =
  8829. *(uint8_t *)(void *)(in + i)
  8830. ^ *(((uint8_t *)&masking_key) + (i % 4));
  8831. i++;
  8832. }
  8833. }
  8834. }
  8835. int
  8836. mg_websocket_client_write(struct mg_connection *conn,
  8837. int opcode,
  8838. const char *data,
  8839. size_t dataLen)
  8840. {
  8841. int retval = -1;
  8842. char *masked_data = (char *)mg_malloc(((dataLen + 7) / 4) * 4);
  8843. uint32_t masking_key = (uint32_t)get_random();
  8844. if (masked_data == NULL) {
  8845. /* Return -1 in an error case */
  8846. mg_cry(conn,
  8847. "Cannot allocate buffer for masked websocket response: "
  8848. "Out of memory");
  8849. return -1;
  8850. }
  8851. mask_data(data, dataLen, masking_key, masked_data);
  8852. retval = mg_websocket_write_exec(
  8853. conn, opcode, masked_data, dataLen, masking_key);
  8854. mg_free(masked_data);
  8855. return retval;
  8856. }
  8857. static void
  8858. handle_websocket_request(struct mg_connection *conn,
  8859. const char *path,
  8860. int is_callback_resource,
  8861. struct mg_websocket_subprotocols *subprotocols,
  8862. mg_websocket_connect_handler ws_connect_handler,
  8863. mg_websocket_ready_handler ws_ready_handler,
  8864. mg_websocket_data_handler ws_data_handler,
  8865. mg_websocket_close_handler ws_close_handler,
  8866. void *cbData)
  8867. {
  8868. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  8869. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  8870. int lua_websock = 0;
  8871. #if !defined(USE_LUA)
  8872. (void)path;
  8873. #endif
  8874. /* Step 1: Check websocket protocol version. */
  8875. /* Step 1.1: Check Sec-WebSocket-Key. */
  8876. if (!websock_key) {
  8877. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  8878. * requires a Sec-WebSocket-Key header.
  8879. */
  8880. /* It could be the hixie draft version
  8881. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  8882. */
  8883. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  8884. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  8885. char key3[8];
  8886. if ((key1 != NULL) && (key2 != NULL)) {
  8887. /* This version uses 8 byte body data in a GET request */
  8888. conn->content_len = 8;
  8889. if (8 == mg_read(conn, key3, 8)) {
  8890. /* This is the hixie version */
  8891. mg_send_http_error(conn,
  8892. 426,
  8893. "%s",
  8894. "Protocol upgrade to RFC 6455 required");
  8895. return;
  8896. }
  8897. }
  8898. /* This is an unknown version */
  8899. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  8900. return;
  8901. }
  8902. /* Step 1.2: Check websocket protocol version. */
  8903. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  8904. if (version == NULL || strcmp(version, "13") != 0) {
  8905. /* Reject wrong versions */
  8906. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  8907. return;
  8908. }
  8909. /* Step 1.3: Could check for "Host", but we do not really nead this
  8910. * value for anything, so just ignore it. */
  8911. /* Step 2: If a callback is responsible, call it. */
  8912. if (is_callback_resource) {
  8913. /* Step 2.1 check and select subprotocol */
  8914. const char *protocol = mg_get_header(conn, "Sec-WebSocket-Protocol");
  8915. if (protocol && subprotocols) {
  8916. int idx;
  8917. unsigned long len;
  8918. const char *sep, *curSubProtocol,
  8919. *acceptedWebSocketSubprotocol = NULL;
  8920. /* look for matching subprotocol */
  8921. do {
  8922. sep = strchr(protocol, ',');
  8923. curSubProtocol = protocol;
  8924. len = sep ? (unsigned long)(sep - protocol)
  8925. : (unsigned long)strlen(protocol);
  8926. while (sep && isspace(*++sep)) {
  8927. ; /* ignore leading whitespaces */
  8928. }
  8929. protocol = sep;
  8930. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  8931. if ((strlen(subprotocols->subprotocols[idx]) == len)
  8932. && (strncmp(curSubProtocol,
  8933. subprotocols->subprotocols[idx],
  8934. len) == 0)) {
  8935. acceptedWebSocketSubprotocol =
  8936. subprotocols->subprotocols[idx];
  8937. break;
  8938. }
  8939. }
  8940. } while (sep && !acceptedWebSocketSubprotocol);
  8941. conn->request_info.acceptedWebSocketSubprotocol =
  8942. acceptedWebSocketSubprotocol;
  8943. } else if (protocol) {
  8944. /* keep legacy behavior */
  8945. /* The protocol is a comma seperated list of names. */
  8946. /* The server must only return one value from this list. */
  8947. /* First check if it is a list or just a single value. */
  8948. const char *sep = strrchr(protocol, ',');
  8949. if (sep == NULL) {
  8950. /* Just a single protocol -> accept it. */
  8951. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  8952. } else {
  8953. /* Multiple protocols -> accept the last one. */
  8954. /* This is just a quick fix if the client offers multiple
  8955. * protocols. The handler should have a list of accepted
  8956. * protocols on his own
  8957. * and use it to select one protocol among those the client has
  8958. * offered.
  8959. */
  8960. while (isspace(*++sep)) {
  8961. ; /* ignore leading whitespaces */
  8962. }
  8963. conn->request_info.acceptedWebSocketSubprotocol = sep;
  8964. }
  8965. }
  8966. if (ws_connect_handler != NULL
  8967. && ws_connect_handler(conn, cbData) != 0) {
  8968. /* C callback has returned non-zero, do not proceed with
  8969. * handshake.
  8970. */
  8971. /* Note that C callbacks are no longer called when Lua is
  8972. * responsible, so C can no longer filter callbacks for Lua. */
  8973. return;
  8974. }
  8975. }
  8976. #if defined(USE_LUA)
  8977. /* Step 3: No callback. Check if Lua is responsible. */
  8978. else {
  8979. /* Step 3.1: Check if Lua is responsible. */
  8980. if (conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  8981. lua_websock =
  8982. match_prefix(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  8983. strlen(
  8984. conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  8985. path);
  8986. }
  8987. if (lua_websock) {
  8988. /* Step 3.2: Lua is responsible: call it. */
  8989. conn->lua_websocket_state = lua_websocket_new(path, conn);
  8990. if (!conn->lua_websocket_state) {
  8991. /* Lua rejected the new client */
  8992. return;
  8993. }
  8994. }
  8995. }
  8996. #endif
  8997. /* Step 4: Check if there is a responsible websocket handler. */
  8998. if (!is_callback_resource && !lua_websock) {
  8999. /* There is no callback, and Lua is not responsible either. */
  9000. /* Reply with a 404 Not Found. We are still at a standard
  9001. * HTTP request here, before the websocket handshake, so
  9002. * we can still send standard HTTP error replies. */
  9003. mg_send_http_error(conn, 404, "%s", "Not found");
  9004. return;
  9005. }
  9006. /* Step 5: The websocket connection has been accepted */
  9007. if (!send_websocket_handshake(conn, websock_key)) {
  9008. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  9009. return;
  9010. }
  9011. /* Step 6: Call the ready handler */
  9012. if (is_callback_resource) {
  9013. if (ws_ready_handler != NULL) {
  9014. ws_ready_handler(conn, cbData);
  9015. }
  9016. #if defined(USE_LUA)
  9017. } else if (lua_websock) {
  9018. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  9019. /* the ready handler returned false */
  9020. return;
  9021. }
  9022. #endif
  9023. }
  9024. /* Step 7: Enter the read loop */
  9025. if (is_callback_resource) {
  9026. read_websocket(conn, ws_data_handler, cbData);
  9027. #if defined(USE_LUA)
  9028. } else if (lua_websock) {
  9029. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  9030. #endif
  9031. }
  9032. /* Step 8: Call the close handler */
  9033. if (ws_close_handler) {
  9034. ws_close_handler(conn, cbData);
  9035. }
  9036. }
  9037. static int
  9038. is_websocket_protocol(const struct mg_connection *conn)
  9039. {
  9040. const char *upgrade, *connection;
  9041. /* A websocket protocoll has the following HTTP headers:
  9042. *
  9043. * Connection: Upgrade
  9044. * Upgrade: Websocket
  9045. */
  9046. upgrade = mg_get_header(conn, "Upgrade");
  9047. if (upgrade == NULL) {
  9048. return 0; /* fail early, don't waste time checking other header
  9049. * fields
  9050. */
  9051. }
  9052. if (!mg_strcasestr(upgrade, "websocket")) {
  9053. return 0;
  9054. }
  9055. connection = mg_get_header(conn, "Connection");
  9056. if (connection == NULL) {
  9057. return 0;
  9058. }
  9059. if (!mg_strcasestr(connection, "upgrade")) {
  9060. return 0;
  9061. }
  9062. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  9063. * "Sec-WebSocket-Version" are also required.
  9064. * Don't check them here, since even an unsupported websocket protocol
  9065. * request still IS a websocket request (in contrast to a standard HTTP
  9066. * request). It will fail later in handle_websocket_request.
  9067. */
  9068. return 1;
  9069. }
  9070. #endif /* !USE_WEBSOCKET */
  9071. static int
  9072. isbyte(int n)
  9073. {
  9074. return n >= 0 && n <= 255;
  9075. }
  9076. static int
  9077. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  9078. {
  9079. int n, a, b, c, d, slash = 32, len = 0;
  9080. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5
  9081. || sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) && isbyte(a)
  9082. && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0
  9083. && slash < 33) {
  9084. len = n;
  9085. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  9086. | (uint32_t)d;
  9087. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  9088. }
  9089. return len;
  9090. }
  9091. static int
  9092. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  9093. {
  9094. int throttle = 0;
  9095. struct vec vec, val;
  9096. uint32_t net, mask;
  9097. char mult;
  9098. double v;
  9099. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  9100. mult = ',';
  9101. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  9102. || (v < 0) || ((lowercase(&mult) != 'k')
  9103. && (lowercase(&mult) != 'm') && (mult != ','))) {
  9104. continue;
  9105. }
  9106. v *= (lowercase(&mult) == 'k')
  9107. ? 1024
  9108. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  9109. if (vec.len == 1 && vec.ptr[0] == '*') {
  9110. throttle = (int)v;
  9111. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  9112. if ((remote_ip & mask) == net) {
  9113. throttle = (int)v;
  9114. }
  9115. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  9116. throttle = (int)v;
  9117. }
  9118. }
  9119. return throttle;
  9120. }
  9121. static uint32_t
  9122. get_remote_ip(const struct mg_connection *conn)
  9123. {
  9124. if (!conn) {
  9125. return 0;
  9126. }
  9127. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  9128. }
  9129. /* The mg_upload function is superseeded by mg_handle_form_request. */
  9130. #include "handle_form.inl"
  9131. #if defined(MG_LEGACY_INTERFACE)
  9132. /* Implement the deprecated mg_upload function by calling the new
  9133. * mg_handle_form_request function. While mg_upload could only handle
  9134. * HTML forms sent as POST request in multipart/form-data format
  9135. * containing only file input elements, mg_handle_form_request can
  9136. * handle all form input elements and all standard request methods. */
  9137. struct mg_upload_user_data {
  9138. struct mg_connection *conn;
  9139. const char *destination_dir;
  9140. int num_uploaded_files;
  9141. };
  9142. /* Helper function for deprecated mg_upload. */
  9143. static int
  9144. mg_upload_field_found(const char *key,
  9145. const char *filename,
  9146. char *path,
  9147. size_t pathlen,
  9148. void *user_data)
  9149. {
  9150. int truncated = 0;
  9151. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  9152. (void)key;
  9153. if (!filename) {
  9154. mg_cry(fud->conn, "%s: No filename set", __func__);
  9155. return FORM_FIELD_STORAGE_ABORT;
  9156. }
  9157. mg_snprintf(fud->conn,
  9158. &truncated,
  9159. path,
  9160. pathlen - 1,
  9161. "%s/%s",
  9162. fud->destination_dir,
  9163. filename);
  9164. if (!truncated) {
  9165. mg_cry(fud->conn, "%s: File path too long", __func__);
  9166. return FORM_FIELD_STORAGE_ABORT;
  9167. }
  9168. return FORM_FIELD_STORAGE_STORE;
  9169. }
  9170. /* Helper function for deprecated mg_upload. */
  9171. static int
  9172. mg_upload_field_get(const char *key,
  9173. const char *value,
  9174. size_t value_size,
  9175. void *user_data)
  9176. {
  9177. /* Function should never be called */
  9178. (void)key;
  9179. (void)value;
  9180. (void)value_size;
  9181. (void)user_data;
  9182. return 0;
  9183. }
  9184. /* Helper function for deprecated mg_upload. */
  9185. static int
  9186. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  9187. {
  9188. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  9189. (void)file_size;
  9190. fud->num_uploaded_files++;
  9191. fud->conn->ctx->callbacks.upload(fud->conn, path);
  9192. return 0;
  9193. }
  9194. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  9195. int
  9196. mg_upload(struct mg_connection *conn, const char *destination_dir)
  9197. {
  9198. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  9199. struct mg_form_data_handler fdh = {mg_upload_field_found,
  9200. mg_upload_field_get,
  9201. mg_upload_field_stored,
  9202. 0};
  9203. int ret;
  9204. fdh.user_data = (void *)&fud;
  9205. ret = mg_handle_form_request(conn, &fdh);
  9206. if (ret < 0) {
  9207. mg_cry(conn, "%s: Error while parsing the request", __func__);
  9208. }
  9209. return fud.num_uploaded_files;
  9210. }
  9211. #endif
  9212. static int
  9213. get_first_ssl_listener_index(const struct mg_context *ctx)
  9214. {
  9215. unsigned int i;
  9216. int idx = -1;
  9217. if (ctx) {
  9218. for (i = 0; idx == -1 && i < ctx->num_listening_sockets; i++) {
  9219. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  9220. }
  9221. }
  9222. return idx;
  9223. }
  9224. static void
  9225. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  9226. {
  9227. char host[1025];
  9228. const char *host_header;
  9229. size_t hostlen;
  9230. host_header = mg_get_header(conn, "Host");
  9231. hostlen = sizeof(host);
  9232. if (host_header != NULL) {
  9233. char *pos;
  9234. mg_strlcpy(host, host_header, hostlen);
  9235. host[hostlen - 1] = '\0';
  9236. pos = strchr(host, ':');
  9237. if (pos != NULL) {
  9238. *pos = '\0';
  9239. }
  9240. } else {
  9241. /* Cannot get host from the Host: header.
  9242. * Fallback to our IP address. */
  9243. if (conn) {
  9244. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  9245. }
  9246. }
  9247. /* Send host, port, uri and (if it exists) ?query_string */
  9248. if (conn) {
  9249. mg_printf(conn,
  9250. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  9251. host,
  9252. #if defined(USE_IPV6)
  9253. (conn->ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  9254. == AF_INET6)
  9255. ? (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  9256. .lsa.sin6.sin6_port)
  9257. :
  9258. #endif
  9259. (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  9260. .lsa.sin.sin_port),
  9261. conn->request_info.local_uri,
  9262. (conn->request_info.query_string == NULL) ? "" : "?",
  9263. (conn->request_info.query_string == NULL)
  9264. ? ""
  9265. : conn->request_info.query_string);
  9266. }
  9267. }
  9268. static void
  9269. mg_set_handler_type(struct mg_context *ctx,
  9270. const char *uri,
  9271. int handler_type,
  9272. int is_delete_request,
  9273. mg_request_handler handler,
  9274. struct mg_websocket_subprotocols *subprotocols,
  9275. mg_websocket_connect_handler connect_handler,
  9276. mg_websocket_ready_handler ready_handler,
  9277. mg_websocket_data_handler data_handler,
  9278. mg_websocket_close_handler close_handler,
  9279. mg_authorization_handler auth_handler,
  9280. void *cbdata)
  9281. {
  9282. struct mg_handler_info *tmp_rh, **lastref;
  9283. size_t urilen = strlen(uri);
  9284. if (handler_type == WEBSOCKET_HANDLER) {
  9285. /* assert(handler == NULL); */
  9286. /* assert(is_delete_request || connect_handler!=NULL ||
  9287. * ready_handler!=NULL || data_handler!=NULL ||
  9288. * close_handler!=NULL);
  9289. */
  9290. /* assert(auth_handler == NULL); */
  9291. if (handler != NULL) {
  9292. return;
  9293. }
  9294. if (!is_delete_request && connect_handler == NULL
  9295. && ready_handler == NULL
  9296. && data_handler == NULL
  9297. && close_handler == NULL) {
  9298. return;
  9299. }
  9300. if (auth_handler != NULL) {
  9301. return;
  9302. }
  9303. } else if (handler_type == REQUEST_HANDLER) {
  9304. /* assert(connect_handler==NULL && ready_handler==NULL &&
  9305. * data_handler==NULL && close_handler==NULL); */
  9306. /* assert(is_delete_request || (handler!=NULL));
  9307. */
  9308. /* assert(auth_handler == NULL); */
  9309. if (connect_handler != NULL || ready_handler != NULL
  9310. || data_handler != NULL
  9311. || close_handler != NULL) {
  9312. return;
  9313. }
  9314. if (!is_delete_request && (handler == NULL)) {
  9315. return;
  9316. }
  9317. if (auth_handler != NULL) {
  9318. return;
  9319. }
  9320. } else { /* AUTH_HANDLER */
  9321. /* assert(handler == NULL); */
  9322. /* assert(connect_handler==NULL && ready_handler==NULL &&
  9323. * data_handler==NULL && close_handler==NULL); */
  9324. /* assert(auth_handler != NULL); */
  9325. if (handler != NULL) {
  9326. return;
  9327. }
  9328. if (connect_handler != NULL || ready_handler != NULL
  9329. || data_handler != NULL
  9330. || close_handler != NULL) {
  9331. return;
  9332. }
  9333. if (!is_delete_request && (auth_handler == NULL)) {
  9334. return;
  9335. }
  9336. }
  9337. if (!ctx) {
  9338. return;
  9339. }
  9340. mg_lock_context(ctx);
  9341. /* first try to find an existing handler */
  9342. lastref = &(ctx->handlers);
  9343. for (tmp_rh = ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  9344. if (tmp_rh->handler_type == handler_type) {
  9345. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  9346. if (!is_delete_request) {
  9347. /* update existing handler */
  9348. if (handler_type == REQUEST_HANDLER) {
  9349. tmp_rh->handler = handler;
  9350. } else if (handler_type == WEBSOCKET_HANDLER) {
  9351. tmp_rh->subprotocols = subprotocols;
  9352. tmp_rh->connect_handler = connect_handler;
  9353. tmp_rh->ready_handler = ready_handler;
  9354. tmp_rh->data_handler = data_handler;
  9355. tmp_rh->close_handler = close_handler;
  9356. } else { /* AUTH_HANDLER */
  9357. tmp_rh->auth_handler = auth_handler;
  9358. }
  9359. tmp_rh->cbdata = cbdata;
  9360. } else {
  9361. /* remove existing handler */
  9362. *lastref = tmp_rh->next;
  9363. mg_free(tmp_rh->uri);
  9364. mg_free(tmp_rh);
  9365. }
  9366. mg_unlock_context(ctx);
  9367. return;
  9368. }
  9369. }
  9370. lastref = &(tmp_rh->next);
  9371. }
  9372. if (is_delete_request) {
  9373. /* no handler to set, this was a remove request to a non-existing
  9374. * handler */
  9375. mg_unlock_context(ctx);
  9376. return;
  9377. }
  9378. tmp_rh =
  9379. (struct mg_handler_info *)mg_calloc(sizeof(struct mg_handler_info), 1);
  9380. if (tmp_rh == NULL) {
  9381. mg_unlock_context(ctx);
  9382. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  9383. return;
  9384. }
  9385. tmp_rh->uri = mg_strdup(uri);
  9386. if (!tmp_rh->uri) {
  9387. mg_unlock_context(ctx);
  9388. mg_free(tmp_rh);
  9389. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  9390. return;
  9391. }
  9392. tmp_rh->uri_len = urilen;
  9393. if (handler_type == REQUEST_HANDLER) {
  9394. tmp_rh->handler = handler;
  9395. } else if (handler_type == WEBSOCKET_HANDLER) {
  9396. tmp_rh->subprotocols = subprotocols;
  9397. tmp_rh->connect_handler = connect_handler;
  9398. tmp_rh->ready_handler = ready_handler;
  9399. tmp_rh->data_handler = data_handler;
  9400. tmp_rh->close_handler = close_handler;
  9401. } else { /* AUTH_HANDLER */
  9402. tmp_rh->auth_handler = auth_handler;
  9403. }
  9404. tmp_rh->cbdata = cbdata;
  9405. tmp_rh->handler_type = handler_type;
  9406. tmp_rh->next = NULL;
  9407. *lastref = tmp_rh;
  9408. mg_unlock_context(ctx);
  9409. }
  9410. void
  9411. mg_set_request_handler(struct mg_context *ctx,
  9412. const char *uri,
  9413. mg_request_handler handler,
  9414. void *cbdata)
  9415. {
  9416. mg_set_handler_type(ctx,
  9417. uri,
  9418. REQUEST_HANDLER,
  9419. handler == NULL,
  9420. handler,
  9421. NULL,
  9422. NULL,
  9423. NULL,
  9424. NULL,
  9425. NULL,
  9426. NULL,
  9427. cbdata);
  9428. }
  9429. void
  9430. mg_set_websocket_handler(struct mg_context *ctx,
  9431. const char *uri,
  9432. mg_websocket_connect_handler connect_handler,
  9433. mg_websocket_ready_handler ready_handler,
  9434. mg_websocket_data_handler data_handler,
  9435. mg_websocket_close_handler close_handler,
  9436. void *cbdata)
  9437. {
  9438. mg_set_websocket_handler_with_subprotocols(ctx,
  9439. uri,
  9440. NULL,
  9441. connect_handler,
  9442. ready_handler,
  9443. data_handler,
  9444. close_handler,
  9445. cbdata);
  9446. }
  9447. void
  9448. mg_set_websocket_handler_with_subprotocols(
  9449. struct mg_context *ctx,
  9450. const char *uri,
  9451. struct mg_websocket_subprotocols *subprotocols,
  9452. mg_websocket_connect_handler connect_handler,
  9453. mg_websocket_ready_handler ready_handler,
  9454. mg_websocket_data_handler data_handler,
  9455. mg_websocket_close_handler close_handler,
  9456. void *cbdata)
  9457. {
  9458. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  9459. && (data_handler == NULL)
  9460. && (close_handler == NULL);
  9461. mg_set_handler_type(ctx,
  9462. uri,
  9463. WEBSOCKET_HANDLER,
  9464. is_delete_request,
  9465. NULL,
  9466. subprotocols,
  9467. connect_handler,
  9468. ready_handler,
  9469. data_handler,
  9470. close_handler,
  9471. NULL,
  9472. cbdata);
  9473. }
  9474. void
  9475. mg_set_auth_handler(struct mg_context *ctx,
  9476. const char *uri,
  9477. mg_request_handler handler,
  9478. void *cbdata)
  9479. {
  9480. mg_set_handler_type(ctx,
  9481. uri,
  9482. AUTH_HANDLER,
  9483. handler == NULL,
  9484. NULL,
  9485. NULL,
  9486. NULL,
  9487. NULL,
  9488. NULL,
  9489. NULL,
  9490. handler,
  9491. cbdata);
  9492. }
  9493. static int
  9494. get_request_handler(struct mg_connection *conn,
  9495. int handler_type,
  9496. mg_request_handler *handler,
  9497. struct mg_websocket_subprotocols **subprotocols,
  9498. mg_websocket_connect_handler *connect_handler,
  9499. mg_websocket_ready_handler *ready_handler,
  9500. mg_websocket_data_handler *data_handler,
  9501. mg_websocket_close_handler *close_handler,
  9502. mg_authorization_handler *auth_handler,
  9503. void **cbdata)
  9504. {
  9505. const struct mg_request_info *request_info = mg_get_request_info(conn);
  9506. if (request_info) {
  9507. const char *uri = request_info->local_uri;
  9508. size_t urilen = strlen(uri);
  9509. struct mg_handler_info *tmp_rh;
  9510. if (!conn || !conn->ctx) {
  9511. return 0;
  9512. }
  9513. mg_lock_context(conn->ctx);
  9514. /* first try for an exact match */
  9515. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  9516. tmp_rh = tmp_rh->next) {
  9517. if (tmp_rh->handler_type == handler_type) {
  9518. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  9519. if (handler_type == WEBSOCKET_HANDLER) {
  9520. *subprotocols = tmp_rh->subprotocols;
  9521. *connect_handler = tmp_rh->connect_handler;
  9522. *ready_handler = tmp_rh->ready_handler;
  9523. *data_handler = tmp_rh->data_handler;
  9524. *close_handler = tmp_rh->close_handler;
  9525. } else if (handler_type == REQUEST_HANDLER) {
  9526. *handler = tmp_rh->handler;
  9527. } else { /* AUTH_HANDLER */
  9528. *auth_handler = tmp_rh->auth_handler;
  9529. }
  9530. *cbdata = tmp_rh->cbdata;
  9531. mg_unlock_context(conn->ctx);
  9532. return 1;
  9533. }
  9534. }
  9535. }
  9536. /* next try for a partial match, we will accept uri/something */
  9537. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  9538. tmp_rh = tmp_rh->next) {
  9539. if (tmp_rh->handler_type == handler_type) {
  9540. if (tmp_rh->uri_len < urilen && uri[tmp_rh->uri_len] == '/'
  9541. && memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0) {
  9542. if (handler_type == WEBSOCKET_HANDLER) {
  9543. *subprotocols = tmp_rh->subprotocols;
  9544. *connect_handler = tmp_rh->connect_handler;
  9545. *ready_handler = tmp_rh->ready_handler;
  9546. *data_handler = tmp_rh->data_handler;
  9547. *close_handler = tmp_rh->close_handler;
  9548. } else if (handler_type == REQUEST_HANDLER) {
  9549. *handler = tmp_rh->handler;
  9550. } else { /* AUTH_HANDLER */
  9551. *auth_handler = tmp_rh->auth_handler;
  9552. }
  9553. *cbdata = tmp_rh->cbdata;
  9554. mg_unlock_context(conn->ctx);
  9555. return 1;
  9556. }
  9557. }
  9558. }
  9559. /* finally try for pattern match */
  9560. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  9561. tmp_rh = tmp_rh->next) {
  9562. if (tmp_rh->handler_type == handler_type) {
  9563. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  9564. if (handler_type == WEBSOCKET_HANDLER) {
  9565. *subprotocols = tmp_rh->subprotocols;
  9566. *connect_handler = tmp_rh->connect_handler;
  9567. *ready_handler = tmp_rh->ready_handler;
  9568. *data_handler = tmp_rh->data_handler;
  9569. *close_handler = tmp_rh->close_handler;
  9570. } else if (handler_type == REQUEST_HANDLER) {
  9571. *handler = tmp_rh->handler;
  9572. } else { /* AUTH_HANDLER */
  9573. *auth_handler = tmp_rh->auth_handler;
  9574. }
  9575. *cbdata = tmp_rh->cbdata;
  9576. mg_unlock_context(conn->ctx);
  9577. return 1;
  9578. }
  9579. }
  9580. }
  9581. mg_unlock_context(conn->ctx);
  9582. }
  9583. return 0; /* none found */
  9584. }
  9585. /* Check if the script file is in a path, allowed for script files.
  9586. * This can be used if uploading files is possible not only for the server
  9587. * admin, and the upload mechanism does not check the file extension.
  9588. */
  9589. static int
  9590. is_in_script_path(const struct mg_connection *conn, const char *path)
  9591. {
  9592. /* TODO (Feature): Add config value for allowed script path.
  9593. * Default: All allowed. */
  9594. (void)conn;
  9595. (void)path;
  9596. return 1;
  9597. }
  9598. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  9599. static int
  9600. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  9601. void *cbdata)
  9602. {
  9603. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9604. if (pcallbacks->websocket_connect) {
  9605. return pcallbacks->websocket_connect(conn);
  9606. }
  9607. /* No handler set - assume "OK" */
  9608. return 0;
  9609. }
  9610. static void
  9611. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  9612. {
  9613. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9614. if (pcallbacks->websocket_ready) {
  9615. pcallbacks->websocket_ready(conn);
  9616. }
  9617. }
  9618. static int
  9619. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  9620. int bits,
  9621. char *data,
  9622. size_t len,
  9623. void *cbdata)
  9624. {
  9625. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9626. if (pcallbacks->websocket_data) {
  9627. return pcallbacks->websocket_data(conn, bits, data, len);
  9628. }
  9629. /* No handler set - assume "OK" */
  9630. return 1;
  9631. }
  9632. #endif
  9633. /* This is the heart of the Civetweb's logic.
  9634. * This function is called when the request is read, parsed and validated,
  9635. * and Civetweb must decide what action to take: serve a file, or
  9636. * a directory, or call embedded function, etcetera. */
  9637. static void
  9638. handle_request(struct mg_connection *conn)
  9639. {
  9640. struct mg_request_info *ri = &conn->request_info;
  9641. char path[PATH_MAX];
  9642. int uri_len, ssl_index;
  9643. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  9644. is_put_or_delete_request = 0, is_callback_resource = 0;
  9645. int i;
  9646. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9647. mg_request_handler callback_handler = NULL;
  9648. struct mg_websocket_subprotocols *subprotocols;
  9649. mg_websocket_connect_handler ws_connect_handler = NULL;
  9650. mg_websocket_ready_handler ws_ready_handler = NULL;
  9651. mg_websocket_data_handler ws_data_handler = NULL;
  9652. mg_websocket_close_handler ws_close_handler = NULL;
  9653. void *callback_data = NULL;
  9654. mg_authorization_handler auth_handler = NULL;
  9655. void *auth_callback_data = NULL;
  9656. #if !defined(NO_FILES)
  9657. time_t curtime = time(NULL);
  9658. char date[64];
  9659. #endif
  9660. path[0] = 0;
  9661. /* 1. get the request url */
  9662. /* 1.1. split into url and query string */
  9663. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  9664. != NULL) {
  9665. *((char *)conn->request_info.query_string++) = '\0';
  9666. }
  9667. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  9668. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  9669. ssl_index = get_first_ssl_listener_index(conn->ctx);
  9670. if (ssl_index >= 0) {
  9671. redirect_to_https_port(conn, ssl_index);
  9672. } else {
  9673. /* A http to https forward port has been specified,
  9674. * but no https port to forward to. */
  9675. mg_send_http_error(conn,
  9676. 503,
  9677. "%s",
  9678. "Error: SSL forward not configured properly");
  9679. mg_cry(conn, "Can not redirect to SSL, no SSL port available");
  9680. }
  9681. return;
  9682. }
  9683. uri_len = (int)strlen(ri->local_uri);
  9684. /* 1.3. decode url (if config says so) */
  9685. if (should_decode_url(conn)) {
  9686. mg_url_decode(
  9687. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  9688. }
  9689. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  9690. * not possible */
  9691. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  9692. /* step 1. completed, the url is known now */
  9693. uri_len = (int)strlen(ri->local_uri);
  9694. DEBUG_TRACE("URL: %s", ri->local_uri);
  9695. /* 3. if this ip has limited speed, set it for this connection */
  9696. conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
  9697. get_remote_ip(conn),
  9698. ri->local_uri);
  9699. /* 4. call a "handle everything" callback, if registered */
  9700. if (conn->ctx->callbacks.begin_request != NULL) {
  9701. /* Note that since V1.7 the "begin_request" function is called
  9702. * before an authorization check. If an authorization check is
  9703. * required, use a request_handler instead. */
  9704. i = conn->ctx->callbacks.begin_request(conn);
  9705. if (i > 0) {
  9706. /* callback already processed the request. Store the
  9707. return value as a status code for the access log. */
  9708. conn->status_code = i;
  9709. discard_unread_request_data(conn);
  9710. return;
  9711. } else if (i == 0) {
  9712. /* civetweb should process the request */
  9713. } else {
  9714. /* unspecified - may change with the next version */
  9715. return;
  9716. }
  9717. }
  9718. /* request not yet handled by a handler or redirect, so the request
  9719. * is processed here */
  9720. /* 5. interpret the url to find out how the request must be handled
  9721. */
  9722. /* 5.1. first test, if the request targets the regular http(s)://
  9723. * protocol namespace or the websocket ws(s):// protocol namespace.
  9724. */
  9725. is_websocket_request = is_websocket_protocol(conn);
  9726. /* 5.2. check if the request will be handled by a callback */
  9727. if (get_request_handler(conn,
  9728. is_websocket_request ? WEBSOCKET_HANDLER
  9729. : REQUEST_HANDLER,
  9730. &callback_handler,
  9731. &subprotocols,
  9732. &ws_connect_handler,
  9733. &ws_ready_handler,
  9734. &ws_data_handler,
  9735. &ws_close_handler,
  9736. NULL,
  9737. &callback_data)) {
  9738. /* 5.2.1. A callback will handle this request. All requests
  9739. * handled
  9740. * by a callback have to be considered as requests to a script
  9741. * resource. */
  9742. is_callback_resource = 1;
  9743. is_script_resource = 1;
  9744. is_put_or_delete_request = is_put_or_delete_method(conn);
  9745. } else {
  9746. no_callback_resource:
  9747. /* 5.2.2. No callback is responsible for this request. The URI
  9748. * addresses a file based resource (static content or Lua/cgi
  9749. * scripts in the file system). */
  9750. is_callback_resource = 0;
  9751. interpret_uri(conn,
  9752. path,
  9753. sizeof(path),
  9754. &file.stat,
  9755. &is_found,
  9756. &is_script_resource,
  9757. &is_websocket_request,
  9758. &is_put_or_delete_request);
  9759. }
  9760. /* 6. authorization check */
  9761. /* 6.1. a custom authorization handler is installed */
  9762. if (get_request_handler(conn,
  9763. AUTH_HANDLER,
  9764. NULL,
  9765. NULL,
  9766. NULL,
  9767. NULL,
  9768. NULL,
  9769. NULL,
  9770. &auth_handler,
  9771. &auth_callback_data)) {
  9772. if (!auth_handler(conn, auth_callback_data)) {
  9773. return;
  9774. }
  9775. } else if (is_put_or_delete_request && !is_script_resource
  9776. && !is_callback_resource) {
  9777. /* 6.2. this request is a PUT/DELETE to a real file */
  9778. /* 6.2.1. thus, the server must have real files */
  9779. #if defined(NO_FILES)
  9780. if (1) {
  9781. #else
  9782. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  9783. #endif
  9784. /* This server does not have any real files, thus the
  9785. * PUT/DELETE methods are not valid. */
  9786. mg_send_http_error(conn,
  9787. 405,
  9788. "%s method not allowed",
  9789. conn->request_info.request_method);
  9790. return;
  9791. }
  9792. #if !defined(NO_FILES)
  9793. /* 6.2.2. Check if put authorization for static files is
  9794. * available.
  9795. */
  9796. if (!is_authorized_for_put(conn)) {
  9797. send_authorization_request(conn);
  9798. return;
  9799. }
  9800. #endif
  9801. } else {
  9802. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  9803. * or it is a PUT or DELETE request to a resource that does not
  9804. * correspond to a file. Check authorization. */
  9805. if (!check_authorization(conn, path)) {
  9806. send_authorization_request(conn);
  9807. return;
  9808. }
  9809. }
  9810. /* request is authorized or does not need authorization */
  9811. /* 7. check if there are request handlers for this uri */
  9812. if (is_callback_resource) {
  9813. if (!is_websocket_request) {
  9814. i = callback_handler(conn, callback_data);
  9815. if (i > 0) {
  9816. /* Do nothing, callback has served the request. Store
  9817. * then return value as status code for the log and discard
  9818. * all data from the client not used by the callback. */
  9819. conn->status_code = i;
  9820. discard_unread_request_data(conn);
  9821. } else {
  9822. /* The handler did NOT handle the request. */
  9823. /* Some proper reactions would be:
  9824. * a) close the connections without sending anything
  9825. * b) send a 404 not found
  9826. * c) try if there is a file matching the URI
  9827. * It would be possible to do a, b or c in the callback
  9828. * implementation, and return 1 - we cannot do anything
  9829. * here, that is not possible in the callback.
  9830. *
  9831. * TODO: What would be the best reaction here?
  9832. * (Note: The reaction may change, if there is a better idea.)
  9833. */
  9834. /* For the moment, use option c: We look for a proper file,
  9835. * but since a file request is not always a script resource,
  9836. * the authorization check might be different. */
  9837. interpret_uri(conn,
  9838. path,
  9839. sizeof(path),
  9840. &file.stat,
  9841. &is_found,
  9842. &is_script_resource,
  9843. &is_websocket_request,
  9844. &is_put_or_delete_request);
  9845. callback_handler = NULL;
  9846. /* Here we are at a dead end:
  9847. * According to URI matching, a callback should be
  9848. * responsible for handling the request,
  9849. * we called it, but the callback declared itself
  9850. * not responsible.
  9851. * We use a goto here, to get out of this dead end,
  9852. * and continue with the default handling.
  9853. * A goto here is simpler and better to understand
  9854. * than some curious loop. */
  9855. goto no_callback_resource;
  9856. }
  9857. } else {
  9858. #if defined(USE_WEBSOCKET)
  9859. handle_websocket_request(conn,
  9860. path,
  9861. is_callback_resource,
  9862. subprotocols,
  9863. ws_connect_handler,
  9864. ws_ready_handler,
  9865. ws_data_handler,
  9866. ws_close_handler,
  9867. callback_data);
  9868. #endif
  9869. }
  9870. return;
  9871. }
  9872. /* 8. handle websocket requests */
  9873. #if defined(USE_WEBSOCKET)
  9874. if (is_websocket_request) {
  9875. if (is_script_resource) {
  9876. if (is_in_script_path(conn, path)) {
  9877. /* Websocket Lua script */
  9878. handle_websocket_request(conn,
  9879. path,
  9880. 0 /* Lua Script */,
  9881. NULL,
  9882. NULL,
  9883. NULL,
  9884. NULL,
  9885. NULL,
  9886. &conn->ctx->callbacks);
  9887. } else {
  9888. /* Script was in an illegal path */
  9889. mg_send_http_error(conn, 403, "%s", "Forbidden");
  9890. }
  9891. } else {
  9892. #if defined(MG_LEGACY_INTERFACE)
  9893. handle_websocket_request(
  9894. conn,
  9895. path,
  9896. !is_script_resource /* could be deprecated global callback */,
  9897. NULL,
  9898. deprecated_websocket_connect_wrapper,
  9899. deprecated_websocket_ready_wrapper,
  9900. deprecated_websocket_data_wrapper,
  9901. NULL,
  9902. &conn->ctx->callbacks);
  9903. #else
  9904. mg_send_http_error(conn, 404, "%s", "Not found");
  9905. #endif
  9906. }
  9907. return;
  9908. } else
  9909. #endif
  9910. #if defined(NO_FILES)
  9911. /* 9a. In case the server uses only callbacks, this uri is
  9912. * unknown.
  9913. * Then, all request handling ends here. */
  9914. mg_send_http_error(conn, 404, "%s", "Not Found");
  9915. #else
  9916. /* 9b. This request is either for a static file or resource handled
  9917. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  9918. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  9919. mg_send_http_error(conn, 404, "%s", "Not Found");
  9920. return;
  9921. }
  9922. /* 10. Request is handled by a script */
  9923. if (is_script_resource) {
  9924. handle_file_based_request(conn, path, &file);
  9925. return;
  9926. }
  9927. /* 11. Handle put/delete/mkcol requests */
  9928. if (is_put_or_delete_request) {
  9929. /* 11.1. PUT method */
  9930. if (!strcmp(ri->request_method, "PUT")) {
  9931. put_file(conn, path);
  9932. return;
  9933. }
  9934. /* 11.2. DELETE method */
  9935. if (!strcmp(ri->request_method, "DELETE")) {
  9936. delete_file(conn, path);
  9937. return;
  9938. }
  9939. /* 11.3. MKCOL method */
  9940. if (!strcmp(ri->request_method, "MKCOL")) {
  9941. mkcol(conn, path);
  9942. return;
  9943. }
  9944. /* 11.4. PATCH method
  9945. * This method is not supported for static resources,
  9946. * only for scripts (Lua, CGI) and callbacks. */
  9947. mg_send_http_error(conn,
  9948. 405,
  9949. "%s method not allowed",
  9950. conn->request_info.request_method);
  9951. return;
  9952. }
  9953. /* 11. File does not exist, or it was configured that it should be
  9954. * hidden */
  9955. if (!is_found || (must_hide_file(conn, path))) {
  9956. mg_send_http_error(conn, 404, "%s", "Not found");
  9957. return;
  9958. }
  9959. /* 12. Directory uris should end with a slash */
  9960. if (file.stat.is_directory && (uri_len > 0)
  9961. && (ri->local_uri[uri_len - 1] != '/')) {
  9962. gmt_time_string(date, sizeof(date), &curtime);
  9963. mg_printf(conn,
  9964. "HTTP/1.1 301 Moved Permanently\r\n"
  9965. "Location: %s/\r\n"
  9966. "Date: %s\r\n"
  9967. /* "Cache-Control: private\r\n" (= default) */
  9968. "Content-Length: 0\r\n"
  9969. "Connection: %s\r\n",
  9970. ri->request_uri,
  9971. date,
  9972. suggest_connection_header(conn));
  9973. send_additional_header(conn);
  9974. mg_printf(conn, "\r\n");
  9975. return;
  9976. }
  9977. /* 13. Handle other methods than GET/HEAD */
  9978. /* 13.1. Handle PROPFIND */
  9979. if (!strcmp(ri->request_method, "PROPFIND")) {
  9980. handle_propfind(conn, path, &file.stat);
  9981. return;
  9982. }
  9983. /* 13.2. Handle OPTIONS for files */
  9984. if (!strcmp(ri->request_method, "OPTIONS")) {
  9985. /* This standard handler is only used for real files.
  9986. * Scripts should support the OPTIONS method themselves, to allow a
  9987. * maximum flexibility.
  9988. * Lua and CGI scripts may fully support CORS this way (including
  9989. * preflights). */
  9990. send_options(conn);
  9991. return;
  9992. }
  9993. /* 13.3. everything but GET and HEAD (e.g. POST) */
  9994. if (0 != strcmp(ri->request_method, "GET")
  9995. && 0 != strcmp(ri->request_method, "HEAD")) {
  9996. mg_send_http_error(conn,
  9997. 405,
  9998. "%s method not allowed",
  9999. conn->request_info.request_method);
  10000. return;
  10001. }
  10002. /* 14. directories */
  10003. if (file.stat.is_directory) {
  10004. /* Substitute files have already been handled above. */
  10005. /* Here we can either generate and send a directory listing,
  10006. * or send an "access denied" error. */
  10007. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  10008. "yes")) {
  10009. handle_directory_request(conn, path);
  10010. } else {
  10011. mg_send_http_error(conn,
  10012. 403,
  10013. "%s",
  10014. "Error: Directory listing denied");
  10015. }
  10016. return;
  10017. }
  10018. handle_file_based_request(conn, path, &file);
  10019. #endif /* !defined(NO_FILES) */
  10020. #if 0
  10021. /* Perform redirect and auth checks before calling begin_request()
  10022. * handler.
  10023. * Otherwise, begin_request() would need to perform auth checks and
  10024. * redirects. */
  10025. #endif
  10026. }
  10027. static void
  10028. handle_file_based_request(struct mg_connection *conn,
  10029. const char *path,
  10030. struct mg_file *file)
  10031. {
  10032. if (!conn || !conn->ctx) {
  10033. return;
  10034. }
  10035. if (0) {
  10036. #ifdef USE_LUA
  10037. } else if (match_prefix(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  10038. strlen(
  10039. conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  10040. path) > 0) {
  10041. if (is_in_script_path(conn, path)) {
  10042. /* Lua server page: an SSI like page containing mostly plain html
  10043. * code
  10044. * plus some tags with server generated contents. */
  10045. handle_lsp_request(conn, path, file, NULL);
  10046. } else {
  10047. /* Script was in an illegal path */
  10048. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10049. }
  10050. } else if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  10051. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  10052. path) > 0) {
  10053. if (is_in_script_path(conn, path)) {
  10054. /* Lua in-server module script: a CGI like script used to generate
  10055. * the
  10056. * entire reply. */
  10057. mg_exec_lua_script(conn, path, NULL);
  10058. } else {
  10059. /* Script was in an illegal path */
  10060. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10061. }
  10062. #endif
  10063. #if defined(USE_DUKTAPE)
  10064. } else if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  10065. strlen(
  10066. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  10067. path) > 0) {
  10068. if (is_in_script_path(conn, path)) {
  10069. /* Call duktape to generate the page */
  10070. mg_exec_duktape_script(conn, path);
  10071. } else {
  10072. /* Script was in an illegal path */
  10073. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10074. }
  10075. #endif
  10076. #if !defined(NO_CGI)
  10077. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  10078. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  10079. path) > 0) {
  10080. if (is_in_script_path(conn, path)) {
  10081. /* CGI scripts may support all HTTP methods */
  10082. handle_cgi_request(conn, path);
  10083. } else {
  10084. /* Script was in an illegal path */
  10085. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10086. }
  10087. #endif /* !NO_CGI */
  10088. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  10089. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  10090. path) > 0) {
  10091. if (is_in_script_path(conn, path)) {
  10092. handle_ssi_file_request(conn, path, file);
  10093. } else {
  10094. /* Script was in an illegal path */
  10095. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10096. }
  10097. #if !defined(NO_CACHING)
  10098. } else if ((!conn->in_error_handler)
  10099. && is_not_modified(conn, &file->stat)) {
  10100. /* Send 304 "Not Modified" - this must not send any body data */
  10101. handle_not_modified_static_file_request(conn, file);
  10102. #endif /* !NO_CACHING */
  10103. } else {
  10104. handle_static_file_request(conn, path, file, NULL, NULL);
  10105. }
  10106. }
  10107. static void
  10108. close_all_listening_sockets(struct mg_context *ctx)
  10109. {
  10110. unsigned int i;
  10111. if (!ctx) {
  10112. return;
  10113. }
  10114. for (i = 0; i < ctx->num_listening_sockets; i++) {
  10115. closesocket(ctx->listening_sockets[i].sock);
  10116. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  10117. }
  10118. mg_free(ctx->listening_sockets);
  10119. ctx->listening_sockets = NULL;
  10120. mg_free(ctx->listening_socket_fds);
  10121. ctx->listening_socket_fds = NULL;
  10122. }
  10123. /* Valid listening port specification is: [ip_address:]port[s]
  10124. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  10125. * Examples for IPv6: [::]:80, [::1]:80,
  10126. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  10127. * see https://tools.ietf.org/html/rfc3513#section-2.2
  10128. * In order to bind to both, IPv4 and IPv6, you can either add
  10129. * both ports using 8080,[::]:8080, or the short form +8080.
  10130. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  10131. * one only accepting IPv4 the other only IPv6. +8080 creates
  10132. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  10133. * environment, they might work differently, or might not work
  10134. * at all - it must be tested what options work best in the
  10135. * relevant network environment.
  10136. */
  10137. static int
  10138. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  10139. {
  10140. unsigned int a, b, c, d, port;
  10141. int ch, len;
  10142. #if defined(USE_IPV6)
  10143. char buf[100] = {0};
  10144. #endif
  10145. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  10146. * Also, all-zeroes in the socket address means binding to all addresses
  10147. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  10148. memset(so, 0, sizeof(*so));
  10149. so->lsa.sin.sin_family = AF_INET;
  10150. *ip_version = 0;
  10151. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  10152. == 5) {
  10153. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  10154. so->lsa.sin.sin_addr.s_addr =
  10155. htonl((a << 24) | (b << 16) | (c << 8) | d);
  10156. so->lsa.sin.sin_port = htons((uint16_t)port);
  10157. *ip_version = 4;
  10158. #if defined(USE_IPV6)
  10159. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  10160. && mg_inet_pton(
  10161. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  10162. /* IPv6 address, examples: see above */
  10163. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  10164. */
  10165. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  10166. *ip_version = 6;
  10167. #endif
  10168. } else if ((vec->ptr[0] == '+')
  10169. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  10170. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  10171. /* Add 1 to len for the + character we skipped before */
  10172. len++;
  10173. #if defined(USE_IPV6)
  10174. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  10175. so->lsa.sin6.sin6_family = AF_INET6;
  10176. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  10177. *ip_version = 4 + 6;
  10178. #else
  10179. /* Bind to IPv4 only, since IPv6 is not built in. */
  10180. so->lsa.sin.sin_port = htons((uint16_t)port);
  10181. *ip_version = 4;
  10182. #endif
  10183. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  10184. /* If only port is specified, bind to IPv4, INADDR_ANY */
  10185. so->lsa.sin.sin_port = htons((uint16_t)port);
  10186. *ip_version = 4;
  10187. } else {
  10188. /* Parsing failure. Make port invalid. */
  10189. port = 0;
  10190. len = 0;
  10191. }
  10192. /* sscanf and the option splitting code ensure the following condition
  10193. */
  10194. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  10195. *ip_version = 0;
  10196. return 0;
  10197. }
  10198. ch = vec->ptr[len]; /* Next character after the port number */
  10199. so->is_ssl = (ch == 's');
  10200. so->ssl_redir = (ch == 'r');
  10201. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  10202. if (is_valid_port(port)
  10203. && (ch == '\0' || ch == 's' || ch == 'r' || ch == ',')) {
  10204. return 1;
  10205. }
  10206. /* Reset ip_version to 0 of there is an error */
  10207. *ip_version = 0;
  10208. return 0;
  10209. }
  10210. static int
  10211. set_ports_option(struct mg_context *ctx)
  10212. {
  10213. const char *list;
  10214. int on = 1;
  10215. #if defined(USE_IPV6)
  10216. int off = 0;
  10217. #endif
  10218. struct vec vec;
  10219. struct socket so, *ptr;
  10220. struct pollfd *pfd;
  10221. union usa usa;
  10222. socklen_t len;
  10223. int ip_version;
  10224. int portsTotal = 0;
  10225. int portsOk = 0;
  10226. if (!ctx) {
  10227. return 0;
  10228. }
  10229. memset(&so, 0, sizeof(so));
  10230. memset(&usa, 0, sizeof(usa));
  10231. len = sizeof(usa);
  10232. list = ctx->config[LISTENING_PORTS];
  10233. while ((list = next_option(list, &vec, NULL)) != NULL) {
  10234. portsTotal++;
  10235. if (!parse_port_string(&vec, &so, &ip_version)) {
  10236. mg_cry(fc(ctx),
  10237. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  10238. (int)vec.len,
  10239. vec.ptr,
  10240. portsTotal,
  10241. "[IP_ADDRESS:]PORT[s|r]");
  10242. continue;
  10243. }
  10244. #if !defined(NO_SSL)
  10245. if (so.is_ssl && ctx->ssl_ctx == NULL) {
  10246. mg_cry(fc(ctx),
  10247. "Cannot add SSL socket (entry %i). Is -ssl_certificate "
  10248. "option set?",
  10249. portsTotal);
  10250. continue;
  10251. }
  10252. #endif
  10253. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  10254. == INVALID_SOCKET) {
  10255. mg_cry(fc(ctx), "cannot create socket (entry %i)", portsTotal);
  10256. continue;
  10257. }
  10258. #ifdef _WIN32
  10259. /* Windows SO_REUSEADDR lets many procs binds to a
  10260. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  10261. * if someone already has the socket -- DTL */
  10262. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  10263. * Windows might need a few seconds before
  10264. * the same port can be used again in the
  10265. * same process, so a short Sleep may be
  10266. * required between mg_stop and mg_start.
  10267. */
  10268. if (setsockopt(so.sock,
  10269. SOL_SOCKET,
  10270. SO_EXCLUSIVEADDRUSE,
  10271. (SOCK_OPT_TYPE)&on,
  10272. sizeof(on)) != 0) {
  10273. /* Set reuse option, but don't abort on errors. */
  10274. mg_cry(fc(ctx),
  10275. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  10276. portsTotal);
  10277. }
  10278. #else
  10279. if (setsockopt(so.sock,
  10280. SOL_SOCKET,
  10281. SO_REUSEADDR,
  10282. (SOCK_OPT_TYPE)&on,
  10283. sizeof(on)) != 0) {
  10284. /* Set reuse option, but don't abort on errors. */
  10285. mg_cry(fc(ctx),
  10286. "cannot set socket option SO_REUSEADDR (entry %i)",
  10287. portsTotal);
  10288. }
  10289. #endif
  10290. if (ip_version > 4) {
  10291. #if defined(USE_IPV6)
  10292. if (ip_version == 6) {
  10293. if (so.lsa.sa.sa_family == AF_INET6
  10294. && setsockopt(so.sock,
  10295. IPPROTO_IPV6,
  10296. IPV6_V6ONLY,
  10297. (void *)&off,
  10298. sizeof(off)) != 0) {
  10299. /* Set IPv6 only option, but don't abort on errors. */
  10300. mg_cry(fc(ctx),
  10301. "cannot set socket option IPV6_V6ONLY (entry %i)",
  10302. portsTotal);
  10303. }
  10304. }
  10305. #else
  10306. mg_cry(fc(ctx), "IPv6 not available");
  10307. closesocket(so.sock);
  10308. so.sock = INVALID_SOCKET;
  10309. continue;
  10310. #endif
  10311. }
  10312. if (so.lsa.sa.sa_family == AF_INET) {
  10313. len = sizeof(so.lsa.sin);
  10314. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  10315. mg_cry(fc(ctx),
  10316. "cannot bind to %.*s: %d (%s)",
  10317. (int)vec.len,
  10318. vec.ptr,
  10319. (int)ERRNO,
  10320. strerror(errno));
  10321. closesocket(so.sock);
  10322. so.sock = INVALID_SOCKET;
  10323. continue;
  10324. }
  10325. }
  10326. #if defined(USE_IPV6)
  10327. else if (so.lsa.sa.sa_family == AF_INET6) {
  10328. len = sizeof(so.lsa.sin6);
  10329. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  10330. mg_cry(fc(ctx),
  10331. "cannot bind to IPv6 %.*s: %d (%s)",
  10332. (int)vec.len,
  10333. vec.ptr,
  10334. (int)ERRNO,
  10335. strerror(errno));
  10336. closesocket(so.sock);
  10337. so.sock = INVALID_SOCKET;
  10338. continue;
  10339. }
  10340. }
  10341. #endif
  10342. else {
  10343. mg_cry(fc(ctx),
  10344. "cannot bind: address family not supported (entry %i)",
  10345. portsTotal);
  10346. continue;
  10347. }
  10348. if (listen(so.sock, SOMAXCONN) != 0) {
  10349. mg_cry(fc(ctx),
  10350. "cannot listen to %.*s: %d (%s)",
  10351. (int)vec.len,
  10352. vec.ptr,
  10353. (int)ERRNO,
  10354. strerror(errno));
  10355. closesocket(so.sock);
  10356. so.sock = INVALID_SOCKET;
  10357. continue;
  10358. }
  10359. if (getsockname(so.sock, &(usa.sa), &len) != 0
  10360. || usa.sa.sa_family != so.lsa.sa.sa_family) {
  10361. int err = (int)ERRNO;
  10362. mg_cry(fc(ctx),
  10363. "call to getsockname failed %.*s: %d (%s)",
  10364. (int)vec.len,
  10365. vec.ptr,
  10366. err,
  10367. strerror(errno));
  10368. closesocket(so.sock);
  10369. so.sock = INVALID_SOCKET;
  10370. continue;
  10371. }
  10372. /* Update lsa port in case of random free ports */
  10373. #if defined(USE_IPV6)
  10374. if (so.lsa.sa.sa_family == AF_INET6) {
  10375. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  10376. } else
  10377. #endif
  10378. {
  10379. so.lsa.sin.sin_port = usa.sin.sin_port;
  10380. }
  10381. if ((ptr = (struct socket *)
  10382. mg_realloc(ctx->listening_sockets,
  10383. (ctx->num_listening_sockets + 1)
  10384. * sizeof(ctx->listening_sockets[0]))) == NULL) {
  10385. mg_cry(fc(ctx), "%s", "Out of memory");
  10386. closesocket(so.sock);
  10387. so.sock = INVALID_SOCKET;
  10388. continue;
  10389. }
  10390. if ((pfd = (struct pollfd *)mg_realloc(
  10391. ctx->listening_socket_fds,
  10392. (ctx->num_listening_sockets + 1)
  10393. * sizeof(ctx->listening_socket_fds[0]))) == NULL) {
  10394. mg_cry(fc(ctx), "%s", "Out of memory");
  10395. closesocket(so.sock);
  10396. so.sock = INVALID_SOCKET;
  10397. mg_free(ptr);
  10398. continue;
  10399. }
  10400. set_close_on_exec(so.sock, fc(ctx));
  10401. ctx->listening_sockets = ptr;
  10402. ctx->listening_sockets[ctx->num_listening_sockets] = so;
  10403. ctx->listening_socket_fds = pfd;
  10404. ctx->num_listening_sockets++;
  10405. portsOk++;
  10406. }
  10407. if (portsOk != portsTotal) {
  10408. close_all_listening_sockets(ctx);
  10409. portsOk = 0;
  10410. }
  10411. return portsOk;
  10412. }
  10413. static const char *
  10414. header_val(const struct mg_connection *conn, const char *header)
  10415. {
  10416. const char *header_value;
  10417. if ((header_value = mg_get_header(conn, header)) == NULL) {
  10418. return "-";
  10419. } else {
  10420. return header_value;
  10421. }
  10422. }
  10423. static void
  10424. log_access(const struct mg_connection *conn)
  10425. {
  10426. const struct mg_request_info *ri;
  10427. struct mg_file fi;
  10428. char date[64], src_addr[IP_ADDR_STR_LEN];
  10429. struct tm *tm;
  10430. const char *referer;
  10431. const char *user_agent;
  10432. char buf[4096];
  10433. if (!conn || !conn->ctx) {
  10434. return;
  10435. }
  10436. if (conn->ctx->config[ACCESS_LOG_FILE] != NULL) {
  10437. if (mg_fopen(conn,
  10438. conn->ctx->config[ACCESS_LOG_FILE],
  10439. MG_FOPEN_MODE_APPEND,
  10440. &fi) == 0) {
  10441. fi.access.fp = NULL;
  10442. }
  10443. } else {
  10444. fi.access.fp = NULL;
  10445. }
  10446. /* Log is written to a file and/or a callback. If both are not set,
  10447. * executing the rest of the function is pointless. */
  10448. if ((fi.access.fp == NULL) && (conn->ctx->callbacks.log_access == NULL)) {
  10449. return;
  10450. }
  10451. tm = localtime(&conn->conn_birth_time);
  10452. if (tm != NULL) {
  10453. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  10454. } else {
  10455. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  10456. date[sizeof(date) - 1] = '\0';
  10457. }
  10458. ri = &conn->request_info;
  10459. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  10460. referer = header_val(conn, "Referer");
  10461. user_agent = header_val(conn, "User-Agent");
  10462. mg_snprintf(conn,
  10463. NULL, /* Ignore truncation in access log */
  10464. buf,
  10465. sizeof(buf),
  10466. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  10467. src_addr,
  10468. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  10469. date,
  10470. ri->request_method ? ri->request_method : "-",
  10471. ri->request_uri ? ri->request_uri : "-",
  10472. ri->query_string ? "?" : "",
  10473. ri->query_string ? ri->query_string : "",
  10474. ri->http_version,
  10475. conn->status_code,
  10476. conn->num_bytes_sent,
  10477. referer,
  10478. user_agent);
  10479. if (conn->ctx->callbacks.log_access) {
  10480. conn->ctx->callbacks.log_access(conn, buf);
  10481. }
  10482. if (fi.access.fp) {
  10483. int ok = 1;
  10484. flockfile(fi.access.fp);
  10485. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  10486. ok = 0;
  10487. }
  10488. if (fflush(fi.access.fp) != 0) {
  10489. ok = 0;
  10490. }
  10491. funlockfile(fi.access.fp);
  10492. if (mg_fclose(&fi.access) != 0) {
  10493. ok = 0;
  10494. }
  10495. if (!ok) {
  10496. mg_cry(conn,
  10497. "Error writing log file %s",
  10498. conn->ctx->config[ACCESS_LOG_FILE]);
  10499. }
  10500. }
  10501. }
  10502. /* Verify given socket address against the ACL.
  10503. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  10504. */
  10505. static int
  10506. check_acl(struct mg_context *ctx, uint32_t remote_ip)
  10507. {
  10508. int allowed, flag;
  10509. uint32_t net, mask;
  10510. struct vec vec;
  10511. if (ctx) {
  10512. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  10513. /* If any ACL is set, deny by default */
  10514. allowed = (list == NULL) ? '+' : '-';
  10515. while ((list = next_option(list, &vec, NULL)) != NULL) {
  10516. flag = vec.ptr[0];
  10517. if ((flag != '+' && flag != '-')
  10518. || parse_net(&vec.ptr[1], &net, &mask) == 0) {
  10519. mg_cry(fc(ctx),
  10520. "%s: subnet must be [+|-]x.x.x.x[/x]",
  10521. __func__);
  10522. return -1;
  10523. }
  10524. if (net == (remote_ip & mask)) {
  10525. allowed = flag;
  10526. }
  10527. }
  10528. return allowed == '+';
  10529. }
  10530. return -1;
  10531. }
  10532. #if !defined(_WIN32)
  10533. static int
  10534. set_uid_option(struct mg_context *ctx)
  10535. {
  10536. struct passwd *pw;
  10537. if (ctx) {
  10538. const char *uid = ctx->config[RUN_AS_USER];
  10539. int success = 0;
  10540. if (uid == NULL) {
  10541. success = 1;
  10542. } else {
  10543. if ((pw = getpwnam(uid)) == NULL) {
  10544. mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  10545. } else if (setgid(pw->pw_gid) == -1) {
  10546. mg_cry(fc(ctx),
  10547. "%s: setgid(%s): %s",
  10548. __func__,
  10549. uid,
  10550. strerror(errno));
  10551. } else if (setgroups(0, NULL)) {
  10552. mg_cry(fc(ctx),
  10553. "%s: setgroups(): %s",
  10554. __func__,
  10555. strerror(errno));
  10556. } else if (setuid(pw->pw_uid) == -1) {
  10557. mg_cry(fc(ctx),
  10558. "%s: setuid(%s): %s",
  10559. __func__,
  10560. uid,
  10561. strerror(errno));
  10562. } else {
  10563. success = 1;
  10564. }
  10565. }
  10566. return success;
  10567. }
  10568. return 0;
  10569. }
  10570. #endif /* !_WIN32 */
  10571. static void
  10572. tls_dtor(void *key)
  10573. {
  10574. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  10575. /* key == pthread_getspecific(sTlsKey); */
  10576. if (tls) {
  10577. if (tls->is_master == 2) {
  10578. tls->is_master = -3; /* Mark memory as dead */
  10579. mg_free(tls);
  10580. }
  10581. }
  10582. pthread_setspecific(sTlsKey, NULL);
  10583. }
  10584. #if !defined(NO_SSL)
  10585. static int
  10586. ssl_use_pem_file(struct mg_context *ctx, const char *pem, const char *chain);
  10587. static const char *ssl_error(void);
  10588. static int
  10589. refresh_trust(struct mg_connection *conn)
  10590. {
  10591. static int reload_lock = 0;
  10592. static long int data_check = 0;
  10593. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  10594. struct stat cert_buf;
  10595. long int t;
  10596. const char *pem;
  10597. const char *chain;
  10598. int should_verify_peer;
  10599. if ((pem = conn->ctx->config[SSL_CERTIFICATE]) == NULL) {
  10600. /* If peem is NULL and conn->ctx->callbacks.init_ssl is not,
  10601. * refresh_trust still can not work. */
  10602. return 0;
  10603. }
  10604. chain = conn->ctx->config[SSL_CERTIFICATE_CHAIN];
  10605. if (chain == NULL) {
  10606. chain = pem;
  10607. }
  10608. if ((chain != NULL) && (*chain == 0)) {
  10609. chain = NULL;
  10610. }
  10611. t = data_check;
  10612. if (stat(pem, &cert_buf) != -1) {
  10613. t = (long int)cert_buf.st_mtime;
  10614. }
  10615. if (data_check != t) {
  10616. data_check = t;
  10617. should_verify_peer = 0;
  10618. if (conn->ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  10619. if (mg_strcasecmp(conn->ctx->config[SSL_DO_VERIFY_PEER], "yes")
  10620. == 0) {
  10621. should_verify_peer = 1;
  10622. } else if (mg_strcasecmp(conn->ctx->config[SSL_DO_VERIFY_PEER],
  10623. "optional") == 0) {
  10624. should_verify_peer = 1;
  10625. }
  10626. }
  10627. if (should_verify_peer) {
  10628. char *ca_path = conn->ctx->config[SSL_CA_PATH];
  10629. char *ca_file = conn->ctx->config[SSL_CA_FILE];
  10630. if (SSL_CTX_load_verify_locations(conn->ctx->ssl_ctx,
  10631. ca_file,
  10632. ca_path) != 1) {
  10633. mg_cry(fc(conn->ctx),
  10634. "SSL_CTX_load_verify_locations error: %s "
  10635. "ssl_verify_peer requires setting "
  10636. "either ssl_ca_path or ssl_ca_file. Is any of them "
  10637. "present in "
  10638. "the .conf file?",
  10639. ssl_error());
  10640. return 0;
  10641. }
  10642. }
  10643. if (1 == mg_atomic_inc(p_reload_lock)) {
  10644. if (ssl_use_pem_file(conn->ctx, pem, chain) == 0) {
  10645. return 0;
  10646. }
  10647. *p_reload_lock = 0;
  10648. }
  10649. }
  10650. /* lock while cert is reloading */
  10651. while (*p_reload_lock) {
  10652. sleep(1);
  10653. }
  10654. return 1;
  10655. }
  10656. #ifdef OPENSSL_API_1_1
  10657. #else
  10658. static pthread_mutex_t *ssl_mutexes;
  10659. #endif /* OPENSSL_API_1_1 */
  10660. static int
  10661. sslize(struct mg_connection *conn,
  10662. SSL_CTX *s,
  10663. int (*func)(SSL *),
  10664. volatile int *stop_server)
  10665. {
  10666. int ret, err;
  10667. int short_trust;
  10668. unsigned i;
  10669. if (!conn) {
  10670. return 0;
  10671. }
  10672. short_trust =
  10673. (conn->ctx->config[SSL_SHORT_TRUST] != NULL)
  10674. && (mg_strcasecmp(conn->ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  10675. if (short_trust) {
  10676. int trust_ret = refresh_trust(conn);
  10677. if (!trust_ret) {
  10678. return trust_ret;
  10679. }
  10680. }
  10681. conn->ssl = SSL_new(s);
  10682. if (conn->ssl == NULL) {
  10683. return 0;
  10684. }
  10685. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  10686. if (ret != 1) {
  10687. err = SSL_get_error(conn->ssl, ret);
  10688. (void)err; /* TODO: set some error message */
  10689. SSL_free(conn->ssl);
  10690. conn->ssl = NULL;
  10691. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  10692. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  10693. #ifndef OPENSSL_API_1_1
  10694. ERR_remove_state(0);
  10695. #endif
  10696. return 0;
  10697. }
  10698. /* SSL functions may fail and require to be called again:
  10699. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  10700. * Here "func" could be SSL_connect or SSL_accept. */
  10701. for (i = 16; i <= 1024; i *= 2) {
  10702. ret = func(conn->ssl);
  10703. if (ret != 1) {
  10704. err = SSL_get_error(conn->ssl, ret);
  10705. if ((err == SSL_ERROR_WANT_CONNECT)
  10706. || (err == SSL_ERROR_WANT_ACCEPT)
  10707. || (err == SSL_ERROR_WANT_READ)
  10708. || (err == SSL_ERROR_WANT_WRITE)) {
  10709. /* Need to retry the function call "later".
  10710. * See https://linux.die.net/man/3/ssl_get_error
  10711. * This is typical for non-blocking sockets. */
  10712. if (*stop_server) {
  10713. /* Don't wait if the server is going to be stopped. */
  10714. break;
  10715. }
  10716. mg_sleep(i);
  10717. } else if (err == SSL_ERROR_SYSCALL) {
  10718. /* This is an IO error. Look at errno. */
  10719. err = errno;
  10720. /* TODO: set some error message */
  10721. (void)err;
  10722. break;
  10723. } else {
  10724. /* This is an SSL specific error */
  10725. /* TODO: set some error message */
  10726. break;
  10727. }
  10728. } else {
  10729. /* success */
  10730. break;
  10731. }
  10732. }
  10733. if (ret != 1) {
  10734. SSL_free(conn->ssl);
  10735. conn->ssl = NULL;
  10736. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  10737. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  10738. #ifndef OPENSSL_API_1_1
  10739. ERR_remove_state(0);
  10740. #endif
  10741. return 0;
  10742. }
  10743. return 1;
  10744. }
  10745. /* Return OpenSSL error message (from CRYPTO lib) */
  10746. static const char *
  10747. ssl_error(void)
  10748. {
  10749. unsigned long err;
  10750. err = ERR_get_error();
  10751. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  10752. }
  10753. static int
  10754. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  10755. {
  10756. int i;
  10757. const char hexdigit[] = "0123456789abcdef";
  10758. if (memlen <= 0 || buflen <= 0) {
  10759. return 0;
  10760. }
  10761. if (buflen < (3 * memlen)) {
  10762. return 0;
  10763. }
  10764. for (i = 0; i < memlen; i++) {
  10765. if (i > 0) {
  10766. buf[3 * i - 1] = ' ';
  10767. }
  10768. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  10769. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  10770. }
  10771. buf[3 * memlen - 1] = 0;
  10772. return 1;
  10773. }
  10774. static void
  10775. ssl_get_client_cert_info(struct mg_connection *conn)
  10776. {
  10777. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  10778. if (cert) {
  10779. char str_subject[1024];
  10780. char str_issuer[1024];
  10781. char str_finger[1024];
  10782. unsigned char buf[256];
  10783. char *str_serial = NULL;
  10784. unsigned int ulen;
  10785. int ilen;
  10786. unsigned char *tmp_buf;
  10787. unsigned char *tmp_p;
  10788. /* Handle to algorithm used for fingerprint */
  10789. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  10790. /* Get Subject and issuer */
  10791. X509_NAME *subj = X509_get_subject_name(cert);
  10792. X509_NAME *iss = X509_get_issuer_name(cert);
  10793. /* Get serial number */
  10794. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  10795. /* Translate serial number to a hex string */
  10796. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  10797. str_serial = BN_bn2hex(serial_bn);
  10798. BN_free(serial_bn);
  10799. /* Translate subject and issuer to a string */
  10800. (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
  10801. (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
  10802. /* Calculate SHA1 fingerprint and store as a hex string */
  10803. ulen = 0;
  10804. /* ASN1_digest is deprecated. Do the calculation manually,
  10805. * using EVP_Digest. */
  10806. ilen = i2d_X509((void *)cert, NULL);
  10807. tmp_buf =
  10808. (ilen > 0) ? (unsigned char *)mg_malloc((unsigned)ilen + 1) : NULL;
  10809. if (tmp_buf) {
  10810. tmp_p = tmp_buf;
  10811. (void)i2d_X509((void *)cert, &tmp_p);
  10812. if (!EVP_Digest(
  10813. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  10814. ulen = 0;
  10815. }
  10816. mg_free(tmp_buf);
  10817. }
  10818. if (!hexdump2string(
  10819. buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
  10820. *str_finger = 0;
  10821. }
  10822. conn->request_info.client_cert =
  10823. (struct client_cert *)mg_malloc(sizeof(struct client_cert));
  10824. if (conn->request_info.client_cert) {
  10825. conn->request_info.client_cert->subject = mg_strdup(str_subject);
  10826. conn->request_info.client_cert->issuer = mg_strdup(str_issuer);
  10827. conn->request_info.client_cert->serial = mg_strdup(str_serial);
  10828. conn->request_info.client_cert->finger = mg_strdup(str_finger);
  10829. } else {
  10830. /* TODO: write some OOM message */
  10831. }
  10832. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  10833. * see https://linux.die.net/man/3/bn_bn2hex */
  10834. OPENSSL_free(str_serial);
  10835. /* Free certificate memory */
  10836. X509_free(cert);
  10837. }
  10838. }
  10839. #ifdef OPENSSL_API_1_1
  10840. #else
  10841. static void
  10842. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  10843. {
  10844. (void)line;
  10845. (void)file;
  10846. if (mode & 1) {
  10847. /* 1 is CRYPTO_LOCK */
  10848. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  10849. } else {
  10850. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  10851. }
  10852. }
  10853. #endif /* OPENSSL_API_1_1 */
  10854. #if !defined(NO_SSL_DL)
  10855. static void *
  10856. load_dll(char *ebuf, size_t ebuf_len, const char *dll_name, struct ssl_func *sw)
  10857. {
  10858. union {
  10859. void *p;
  10860. void (*fp)(void);
  10861. } u;
  10862. void *dll_handle;
  10863. struct ssl_func *fp;
  10864. int ok;
  10865. int truncated = 0;
  10866. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  10867. mg_snprintf(NULL,
  10868. NULL, /* No truncation check for ebuf */
  10869. ebuf,
  10870. ebuf_len,
  10871. "%s: cannot load %s",
  10872. __func__,
  10873. dll_name);
  10874. return NULL;
  10875. }
  10876. ok = 1;
  10877. for (fp = sw; fp->name != NULL; fp++) {
  10878. #ifdef _WIN32
  10879. /* GetProcAddress() returns pointer to function */
  10880. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  10881. #else
  10882. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  10883. * pointers to function pointers. We need to use a union to make a
  10884. * cast. */
  10885. u.p = dlsym(dll_handle, fp->name);
  10886. #endif /* _WIN32 */
  10887. if (u.fp == NULL) {
  10888. if (ok) {
  10889. mg_snprintf(NULL,
  10890. &truncated,
  10891. ebuf,
  10892. ebuf_len,
  10893. "%s: %s: cannot find %s",
  10894. __func__,
  10895. dll_name,
  10896. fp->name);
  10897. ok = 0;
  10898. } else {
  10899. size_t cur_len = strlen(ebuf);
  10900. if (!truncated) {
  10901. mg_snprintf(NULL,
  10902. &truncated,
  10903. ebuf + cur_len,
  10904. ebuf_len - cur_len - 3,
  10905. ", %s",
  10906. fp->name);
  10907. if (truncated) {
  10908. /* If truncated, add "..." */
  10909. strcat(ebuf, "...");
  10910. }
  10911. }
  10912. }
  10913. /* Debug:
  10914. * printf("Missing function: %s\n", fp->name); */
  10915. } else {
  10916. fp->ptr = u.fp;
  10917. }
  10918. }
  10919. if (!ok) {
  10920. (void)dlclose(dll_handle);
  10921. return NULL;
  10922. }
  10923. return dll_handle;
  10924. }
  10925. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  10926. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  10927. #endif /* NO_SSL_DL */
  10928. #if defined(SSL_ALREADY_INITIALIZED)
  10929. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  10930. #else
  10931. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  10932. #endif
  10933. static int
  10934. initialize_ssl(char *ebuf, size_t ebuf_len)
  10935. {
  10936. #ifdef OPENSSL_API_1_1
  10937. if (ebuf_len > 0) {
  10938. ebuf[0] = 0;
  10939. }
  10940. #if !defined(NO_SSL_DL)
  10941. if (!cryptolib_dll_handle) {
  10942. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  10943. if (!cryptolib_dll_handle) {
  10944. return 0;
  10945. }
  10946. }
  10947. #endif /* NO_SSL_DL */
  10948. if (mg_atomic_inc(&cryptolib_users) > 1) {
  10949. return 1;
  10950. }
  10951. #else /* not OPENSSL_API_1_1 */
  10952. int i;
  10953. size_t size;
  10954. if (ebuf_len > 0) {
  10955. ebuf[0] = 0;
  10956. }
  10957. #if !defined(NO_SSL_DL)
  10958. if (!cryptolib_dll_handle) {
  10959. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  10960. if (!cryptolib_dll_handle) {
  10961. return 0;
  10962. }
  10963. }
  10964. #endif /* NO_SSL_DL */
  10965. if (mg_atomic_inc(&cryptolib_users) > 1) {
  10966. return 1;
  10967. }
  10968. /* Initialize locking callbacks, needed for thread safety.
  10969. * http://www.openssl.org/support/faq.html#PROG1
  10970. */
  10971. i = CRYPTO_num_locks();
  10972. if (i < 0) {
  10973. i = 0;
  10974. }
  10975. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  10976. if (size == 0) {
  10977. ssl_mutexes = NULL;
  10978. } else if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  10979. mg_snprintf(NULL,
  10980. NULL, /* No truncation check for ebuf */
  10981. ebuf,
  10982. ebuf_len,
  10983. "%s: cannot allocate mutexes: %s",
  10984. __func__,
  10985. ssl_error());
  10986. return 0;
  10987. }
  10988. for (i = 0; i < CRYPTO_num_locks(); i++) {
  10989. pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr);
  10990. }
  10991. CRYPTO_set_locking_callback(&ssl_locking_callback);
  10992. CRYPTO_set_id_callback(&mg_current_thread_id);
  10993. #endif /* OPENSSL_API_1_1 */
  10994. return 1;
  10995. }
  10996. static int
  10997. ssl_use_pem_file(struct mg_context *ctx, const char *pem, const char *chain)
  10998. {
  10999. if (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0) {
  11000. mg_cry(fc(ctx),
  11001. "%s: cannot open certificate file %s: %s",
  11002. __func__,
  11003. pem,
  11004. ssl_error());
  11005. return 0;
  11006. }
  11007. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  11008. if (SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0) {
  11009. mg_cry(fc(ctx),
  11010. "%s: cannot open private key file %s: %s",
  11011. __func__,
  11012. pem,
  11013. ssl_error());
  11014. return 0;
  11015. }
  11016. if (SSL_CTX_check_private_key(ctx->ssl_ctx) == 0) {
  11017. mg_cry(fc(ctx),
  11018. "%s: certificate and private key do not match: %s",
  11019. __func__,
  11020. pem);
  11021. return 0;
  11022. }
  11023. /* In contrast to OpenSSL, wolfSSL does not support certificate
  11024. * chain files that contain private keys and certificates in
  11025. * SSL_CTX_use_certificate_chain_file.
  11026. * The CivetWeb-Server used pem-Files that contained both information.
  11027. * In order to make wolfSSL work, it is split in two files.
  11028. * One file that contains key and certificate used by the server and
  11029. * an optional chain file for the ssl stack.
  11030. */
  11031. if (chain) {
  11032. if (SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, chain) == 0) {
  11033. mg_cry(fc(ctx),
  11034. "%s: cannot use certificate chain file %s: %s",
  11035. __func__,
  11036. pem,
  11037. ssl_error());
  11038. return 0;
  11039. }
  11040. }
  11041. return 1;
  11042. }
  11043. #ifdef OPENSSL_API_1_1
  11044. static unsigned long
  11045. ssl_get_protocol(int version_id)
  11046. {
  11047. long unsigned ret = SSL_OP_ALL;
  11048. if (version_id > 0)
  11049. ret |= SSL_OP_NO_SSLv2;
  11050. if (version_id > 1)
  11051. ret |= SSL_OP_NO_SSLv3;
  11052. if (version_id > 2)
  11053. ret |= SSL_OP_NO_TLSv1;
  11054. if (version_id > 3)
  11055. ret |= SSL_OP_NO_TLSv1_1;
  11056. return ret;
  11057. }
  11058. #else
  11059. static long
  11060. ssl_get_protocol(int version_id)
  11061. {
  11062. long ret = SSL_OP_ALL;
  11063. if (version_id > 0)
  11064. ret |= SSL_OP_NO_SSLv2;
  11065. if (version_id > 1)
  11066. ret |= SSL_OP_NO_SSLv3;
  11067. if (version_id > 2)
  11068. ret |= SSL_OP_NO_TLSv1;
  11069. if (version_id > 3)
  11070. ret |= SSL_OP_NO_TLSv1_1;
  11071. return ret;
  11072. }
  11073. #endif /* OPENSSL_API_1_1 */
  11074. /* Dynamically load SSL library. Set up ctx->ssl_ctx pointer. */
  11075. static int
  11076. set_ssl_option(struct mg_context *ctx)
  11077. {
  11078. const char *pem;
  11079. const char *chain;
  11080. int callback_ret;
  11081. int should_verify_peer;
  11082. int peer_certificate_optional;
  11083. const char *ca_path;
  11084. const char *ca_file;
  11085. int use_default_verify_paths;
  11086. int verify_depth;
  11087. time_t now_rt = time(NULL);
  11088. struct timespec now_mt;
  11089. md5_byte_t ssl_context_id[16];
  11090. md5_state_t md5state;
  11091. int protocol_ver;
  11092. char ebuf[128];
  11093. /* If PEM file is not specified and the init_ssl callback
  11094. * is not specified, skip SSL initialization. */
  11095. if (!ctx) {
  11096. return 0;
  11097. }
  11098. if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL
  11099. && ctx->callbacks.init_ssl == NULL) {
  11100. return 1;
  11101. }
  11102. chain = ctx->config[SSL_CERTIFICATE_CHAIN];
  11103. if (chain == NULL) {
  11104. chain = pem;
  11105. }
  11106. if ((chain != NULL) && (*chain == 0)) {
  11107. chain = NULL;
  11108. }
  11109. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  11110. mg_cry(fc(ctx), "%s", ebuf);
  11111. return 0;
  11112. }
  11113. #if !defined(NO_SSL_DL)
  11114. if (!ssllib_dll_handle) {
  11115. ssllib_dll_handle = load_dll(ebuf, sizeof(ebuf), SSL_LIB, ssl_sw);
  11116. if (!ssllib_dll_handle) {
  11117. mg_cry(fc(ctx), "%s", ebuf);
  11118. return 0;
  11119. }
  11120. }
  11121. #endif /* NO_SSL_DL */
  11122. #ifdef OPENSSL_API_1_1
  11123. /* Initialize SSL library */
  11124. OPENSSL_init_ssl(0, NULL);
  11125. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  11126. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  11127. NULL);
  11128. if ((ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  11129. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  11130. return 0;
  11131. }
  11132. #else
  11133. /* Initialize SSL library */
  11134. SSL_library_init();
  11135. SSL_load_error_strings();
  11136. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  11137. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  11138. return 0;
  11139. }
  11140. #endif /* OPENSSL_API_1_1 */
  11141. SSL_CTX_clear_options(ctx->ssl_ctx,
  11142. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  11143. | SSL_OP_NO_TLSv1_1);
  11144. protocol_ver = atoi(ctx->config[SSL_PROTOCOL_VERSION]);
  11145. SSL_CTX_set_options(ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  11146. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  11147. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  11148. #if !defined(NO_SSL_DL)
  11149. SSL_CTX_set_ecdh_auto(ctx->ssl_ctx, 1);
  11150. #endif /* NO_SSL_DL */
  11151. /* If a callback has been specified, call it. */
  11152. callback_ret =
  11153. (ctx->callbacks.init_ssl == NULL)
  11154. ? 0
  11155. : (ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data));
  11156. /* If callback returns 0, civetweb sets up the SSL certificate.
  11157. * If it returns 1, civetweb assumes the calback already did this.
  11158. * If it returns -1, initializing ssl fails. */
  11159. if (callback_ret < 0) {
  11160. mg_cry(fc(ctx), "SSL callback returned error: %i", callback_ret);
  11161. return 0;
  11162. }
  11163. if (callback_ret > 0) {
  11164. if (pem != NULL) {
  11165. (void)SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
  11166. }
  11167. return 1;
  11168. }
  11169. /* Use some UID as session context ID. */
  11170. md5_init(&md5state);
  11171. md5_append(&md5state, (const md5_byte_t *)&now_rt, sizeof(now_rt));
  11172. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  11173. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  11174. md5_append(&md5state,
  11175. (const md5_byte_t *)ctx->config[LISTENING_PORTS],
  11176. strlen(ctx->config[LISTENING_PORTS]));
  11177. md5_append(&md5state, (const md5_byte_t *)ctx, sizeof(*ctx));
  11178. md5_finish(&md5state, ssl_context_id);
  11179. SSL_CTX_set_session_id_context(ctx->ssl_ctx,
  11180. (const unsigned char *)&ssl_context_id,
  11181. sizeof(ssl_context_id));
  11182. if (pem != NULL) {
  11183. if (!ssl_use_pem_file(ctx, pem, chain)) {
  11184. return 0;
  11185. }
  11186. }
  11187. /* Should we support client certificates? */
  11188. /* Default is "no". */
  11189. should_verify_peer = 0;
  11190. peer_certificate_optional = 0;
  11191. if (ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  11192. if (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  11193. /* Yes, they are mandatory */
  11194. should_verify_peer = 1;
  11195. peer_certificate_optional = 0;
  11196. } else if (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "optional")
  11197. == 0) {
  11198. /* Yes, they are optional */
  11199. should_verify_peer = 1;
  11200. peer_certificate_optional = 1;
  11201. }
  11202. }
  11203. use_default_verify_paths =
  11204. (ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  11205. && (mg_strcasecmp(ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes") == 0);
  11206. if (should_verify_peer) {
  11207. ca_path = ctx->config[SSL_CA_PATH];
  11208. ca_file = ctx->config[SSL_CA_FILE];
  11209. if (SSL_CTX_load_verify_locations(ctx->ssl_ctx, ca_file, ca_path)
  11210. != 1) {
  11211. mg_cry(fc(ctx),
  11212. "SSL_CTX_load_verify_locations error: %s "
  11213. "ssl_verify_peer requires setting "
  11214. "either ssl_ca_path or ssl_ca_file. Is any of them "
  11215. "present in "
  11216. "the .conf file?",
  11217. ssl_error());
  11218. return 0;
  11219. }
  11220. if (peer_certificate_optional) {
  11221. SSL_CTX_set_verify(ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  11222. } else {
  11223. SSL_CTX_set_verify(ctx->ssl_ctx,
  11224. SSL_VERIFY_PEER
  11225. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  11226. NULL);
  11227. }
  11228. if (use_default_verify_paths
  11229. && SSL_CTX_set_default_verify_paths(ctx->ssl_ctx) != 1) {
  11230. mg_cry(fc(ctx),
  11231. "SSL_CTX_set_default_verify_paths error: %s",
  11232. ssl_error());
  11233. return 0;
  11234. }
  11235. if (ctx->config[SSL_VERIFY_DEPTH]) {
  11236. verify_depth = atoi(ctx->config[SSL_VERIFY_DEPTH]);
  11237. SSL_CTX_set_verify_depth(ctx->ssl_ctx, verify_depth);
  11238. }
  11239. }
  11240. if (ctx->config[SSL_CIPHER_LIST] != NULL) {
  11241. if (SSL_CTX_set_cipher_list(ctx->ssl_ctx, ctx->config[SSL_CIPHER_LIST])
  11242. != 1) {
  11243. mg_cry(fc(ctx), "SSL_CTX_set_cipher_list error: %s", ssl_error());
  11244. }
  11245. }
  11246. return 1;
  11247. }
  11248. static void
  11249. uninitialize_ssl(void)
  11250. {
  11251. #ifdef OPENSSL_API_1_1
  11252. if (mg_atomic_dec(&cryptolib_users) == 0) {
  11253. /* Shutdown according to
  11254. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  11255. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  11256. */
  11257. CONF_modules_unload(1);
  11258. #else
  11259. int i;
  11260. if (mg_atomic_dec(&cryptolib_users) == 0) {
  11261. /* Shutdown according to
  11262. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  11263. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  11264. */
  11265. CRYPTO_set_locking_callback(NULL);
  11266. CRYPTO_set_id_callback(NULL);
  11267. ENGINE_cleanup();
  11268. CONF_modules_unload(1);
  11269. ERR_free_strings();
  11270. EVP_cleanup();
  11271. CRYPTO_cleanup_all_ex_data();
  11272. ERR_remove_state(0);
  11273. for (i = 0; i < CRYPTO_num_locks(); i++) {
  11274. pthread_mutex_destroy(&ssl_mutexes[i]);
  11275. }
  11276. mg_free(ssl_mutexes);
  11277. ssl_mutexes = NULL;
  11278. #endif /* OPENSSL_API_1_1 */
  11279. }
  11280. }
  11281. #endif /* !NO_SSL */
  11282. static int
  11283. set_gpass_option(struct mg_context *ctx)
  11284. {
  11285. if (ctx) {
  11286. struct mg_file file = STRUCT_FILE_INITIALIZER;
  11287. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  11288. if (path != NULL && !mg_stat(fc(ctx), path, &file.stat)) {
  11289. mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  11290. return 0;
  11291. }
  11292. return 1;
  11293. }
  11294. return 0;
  11295. }
  11296. static int
  11297. set_acl_option(struct mg_context *ctx)
  11298. {
  11299. return check_acl(ctx, (uint32_t)0x7f000001UL) != -1;
  11300. }
  11301. static void
  11302. reset_per_request_attributes(struct mg_connection *conn)
  11303. {
  11304. if (!conn) {
  11305. return;
  11306. }
  11307. conn->path_info = NULL;
  11308. conn->num_bytes_sent = conn->consumed_content = 0;
  11309. conn->status_code = -1;
  11310. conn->is_chunked = 0;
  11311. conn->must_close = conn->request_len = conn->throttle = 0;
  11312. conn->request_info.content_length = -1;
  11313. conn->request_info.remote_user = NULL;
  11314. conn->request_info.request_method = NULL;
  11315. conn->request_info.request_uri = NULL;
  11316. conn->request_info.local_uri = NULL;
  11317. #if defined(MG_LEGACY_INTERFACE)
  11318. conn->request_info.uri = NULL; /* TODO: cleanup uri,
  11319. * local_uri and request_uri */
  11320. #endif
  11321. conn->request_info.http_version = NULL;
  11322. conn->request_info.num_headers = 0;
  11323. conn->data_len = 0;
  11324. conn->chunk_remainder = 0;
  11325. }
  11326. #if 0
  11327. /* Note: set_sock_timeout is not required for non-blocking sockets.
  11328. * Leave this function here (commented out) for reference until
  11329. * CivetWeb 1.9 is tested, and the tests confirme this function is
  11330. * no longer required.
  11331. */
  11332. static int
  11333. set_sock_timeout(SOCKET sock, int milliseconds)
  11334. {
  11335. int r0 = 0, r1, r2;
  11336. #ifdef _WIN32
  11337. /* Windows specific */
  11338. DWORD tv = (DWORD)milliseconds;
  11339. #else
  11340. /* Linux, ... (not Windows) */
  11341. struct timeval tv;
  11342. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  11343. * max. time waiting for the acknowledged of TCP data before the connection
  11344. * will be forcefully closed and ETIMEDOUT is returned to the application.
  11345. * If this option is not set, the default timeout of 20-30 minutes is used.
  11346. */
  11347. /* #define TCP_USER_TIMEOUT (18) */
  11348. #if defined(TCP_USER_TIMEOUT)
  11349. unsigned int uto = (unsigned int)milliseconds;
  11350. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  11351. #endif
  11352. memset(&tv, 0, sizeof(tv));
  11353. tv.tv_sec = milliseconds / 1000;
  11354. tv.tv_usec = (milliseconds * 1000) % 1000000;
  11355. #endif /* _WIN32 */
  11356. r1 = setsockopt(
  11357. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  11358. r2 = setsockopt(
  11359. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  11360. return r0 || r1 || r2;
  11361. }
  11362. #endif
  11363. static int
  11364. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  11365. {
  11366. if (setsockopt(sock,
  11367. IPPROTO_TCP,
  11368. TCP_NODELAY,
  11369. (SOCK_OPT_TYPE)&nodelay_on,
  11370. sizeof(nodelay_on)) != 0) {
  11371. /* Error */
  11372. return 1;
  11373. }
  11374. /* OK */
  11375. return 0;
  11376. }
  11377. static void
  11378. close_socket_gracefully(struct mg_connection *conn)
  11379. {
  11380. #if defined(_WIN32)
  11381. char buf[MG_BUF_LEN];
  11382. int n;
  11383. #endif
  11384. struct linger linger;
  11385. int error_code = 0;
  11386. int linger_timeout = -2;
  11387. socklen_t opt_len = sizeof(error_code);
  11388. if (!conn) {
  11389. return;
  11390. }
  11391. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  11392. * "Note that enabling a nonzero timeout on a nonblocking socket
  11393. * is not recommended.", so set it to blocking now */
  11394. set_blocking_mode(conn->client.sock, 1);
  11395. /* Send FIN to the client */
  11396. shutdown(conn->client.sock, SHUTDOWN_WR);
  11397. #if defined(_WIN32)
  11398. /* Read and discard pending incoming data. If we do not do that and
  11399. * close
  11400. * the socket, the data in the send buffer may be discarded. This
  11401. * behaviour is seen on Windows, when client keeps sending data
  11402. * when server decides to close the connection; then when client
  11403. * does recv() it gets no data back. */
  11404. do {
  11405. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  11406. } while (n > 0);
  11407. #endif
  11408. if (conn->ctx->config[LINGER_TIMEOUT]) {
  11409. linger_timeout = atoi(conn->ctx->config[LINGER_TIMEOUT]);
  11410. }
  11411. /* Set linger option according to configuration */
  11412. if (linger_timeout >= 0) {
  11413. /* Set linger option to avoid socket hanging out after close. This
  11414. * prevent ephemeral port exhaust problem under high QPS. */
  11415. linger.l_onoff = 1;
  11416. #if defined(_MSC_VER)
  11417. #pragma warning(push)
  11418. #pragma warning(disable : 4244)
  11419. #endif
  11420. linger.l_linger = (linger_timeout + 999) / 1000;
  11421. #if defined(_MSC_VER)
  11422. #pragma warning(pop)
  11423. #endif
  11424. } else {
  11425. linger.l_onoff = 0;
  11426. linger.l_linger = 0;
  11427. }
  11428. if (linger_timeout < -1) {
  11429. /* Default: don't configure any linger */
  11430. } else if (getsockopt(conn->client.sock,
  11431. SOL_SOCKET,
  11432. SO_ERROR,
  11433. (char *)&error_code,
  11434. &opt_len) != 0) {
  11435. /* Cannot determine if socket is already closed. This should
  11436. * not occur and never did in a test. Log an error message
  11437. * and continue. */
  11438. mg_cry(conn,
  11439. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  11440. __func__,
  11441. strerror(ERRNO));
  11442. } else if (error_code == ECONNRESET) {
  11443. /* Socket already closed by client/peer, close socket without linger */
  11444. } else {
  11445. /* Set linger timeout */
  11446. if (setsockopt(conn->client.sock,
  11447. SOL_SOCKET,
  11448. SO_LINGER,
  11449. (char *)&linger,
  11450. sizeof(linger)) != 0) {
  11451. mg_cry(conn,
  11452. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  11453. __func__,
  11454. linger.l_onoff,
  11455. linger.l_linger,
  11456. strerror(ERRNO));
  11457. }
  11458. }
  11459. /* Now we know that our FIN is ACK-ed, safe to close */
  11460. closesocket(conn->client.sock);
  11461. conn->client.sock = INVALID_SOCKET;
  11462. }
  11463. static void
  11464. close_connection(struct mg_connection *conn)
  11465. {
  11466. if (!conn || !conn->ctx) {
  11467. return;
  11468. }
  11469. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  11470. if (conn->lua_websocket_state) {
  11471. lua_websocket_close(conn, conn->lua_websocket_state);
  11472. conn->lua_websocket_state = NULL;
  11473. }
  11474. #endif
  11475. /* call the connection_close callback if assigned */
  11476. if ((conn->ctx->callbacks.connection_close != NULL)
  11477. && (conn->ctx->context_type == 1)) {
  11478. conn->ctx->callbacks.connection_close(conn);
  11479. }
  11480. mg_lock_connection(conn);
  11481. conn->must_close = 1;
  11482. #ifndef NO_SSL
  11483. if (conn->ssl != NULL) {
  11484. /* Run SSL_shutdown twice to ensure completly close SSL connection
  11485. */
  11486. SSL_shutdown(conn->ssl);
  11487. SSL_free(conn->ssl);
  11488. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  11489. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  11490. #ifndef OPENSSL_API_1_1
  11491. ERR_remove_state(0);
  11492. #endif
  11493. conn->ssl = NULL;
  11494. }
  11495. #endif
  11496. if (conn->client.sock != INVALID_SOCKET) {
  11497. close_socket_gracefully(conn);
  11498. conn->client.sock = INVALID_SOCKET;
  11499. }
  11500. mg_unlock_connection(conn);
  11501. }
  11502. void
  11503. mg_close_connection(struct mg_connection *conn)
  11504. {
  11505. struct mg_context *client_ctx = NULL;
  11506. if (conn == NULL) {
  11507. return;
  11508. }
  11509. #if defined(USE_WEBSOCKET)
  11510. if (conn->ctx->context_type == 2) {
  11511. unsigned int i;
  11512. /* ws/wss client */
  11513. client_ctx = conn->ctx;
  11514. /* client context: loops must end */
  11515. conn->ctx->stop_flag = 1;
  11516. /* We need to get the client thread out of the select/recv call here. */
  11517. /* Since we use a sleep quantum of some seconds to check for recv
  11518. * timeouts, we will just wait a few seconds in mg_join_thread. */
  11519. /* join worker thread */
  11520. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  11521. if (client_ctx->worker_threadids[i] != 0) {
  11522. mg_join_thread(client_ctx->worker_threadids[i]);
  11523. }
  11524. }
  11525. }
  11526. #else
  11527. (void)client_ctx;
  11528. #endif
  11529. close_connection(conn);
  11530. #ifndef NO_SSL
  11531. if (conn->client_ssl_ctx != NULL) {
  11532. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  11533. }
  11534. #endif
  11535. if (client_ctx != NULL) {
  11536. /* free context */
  11537. mg_free(client_ctx->worker_threadids);
  11538. mg_free(client_ctx);
  11539. (void)pthread_mutex_destroy(&conn->mutex);
  11540. mg_free(conn);
  11541. } else if (conn->ctx->context_type == 0) { // Client
  11542. mg_free(conn);
  11543. }
  11544. }
  11545. static struct mg_connection *
  11546. mg_connect_client_impl(const struct mg_client_options *client_options,
  11547. int use_ssl,
  11548. char *ebuf,
  11549. size_t ebuf_len)
  11550. {
  11551. static struct mg_context fake_ctx;
  11552. struct mg_connection *conn = NULL;
  11553. SOCKET sock;
  11554. union usa sa;
  11555. if (!connect_socket(&fake_ctx,
  11556. client_options->host,
  11557. client_options->port,
  11558. use_ssl,
  11559. ebuf,
  11560. ebuf_len,
  11561. &sock,
  11562. &sa)) {
  11563. return NULL;
  11564. }
  11565. if ((conn = (struct mg_connection *)
  11566. mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) {
  11567. mg_snprintf(NULL,
  11568. NULL, /* No truncation check for ebuf */
  11569. ebuf,
  11570. ebuf_len,
  11571. "calloc(): %s",
  11572. strerror(ERRNO));
  11573. closesocket(sock);
  11574. return NULL;
  11575. }
  11576. #ifndef NO_SSL
  11577. #ifdef OPENSSL_API_1_1
  11578. if (use_ssl
  11579. && (conn->client_ssl_ctx = SSL_CTX_new(TLS_client_method())) == NULL) {
  11580. mg_snprintf(NULL,
  11581. NULL, /* No truncation check for ebuf */
  11582. ebuf,
  11583. ebuf_len,
  11584. "SSL_CTX_new error");
  11585. closesocket(sock);
  11586. mg_free(conn);
  11587. return NULL;
  11588. }
  11589. #else
  11590. if (use_ssl
  11591. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  11592. == NULL) {
  11593. mg_snprintf(NULL,
  11594. NULL, /* No truncation check for ebuf */
  11595. ebuf,
  11596. ebuf_len,
  11597. "SSL_CTX_new error");
  11598. closesocket(sock);
  11599. mg_free(conn);
  11600. return NULL;
  11601. }
  11602. #endif /* OPENSSL_API_1_1 */
  11603. #endif /* NO_SSL */
  11604. #ifdef USE_IPV6
  11605. socklen_t len = (sa.sa.sa_family == AF_INET)
  11606. ? sizeof(conn->client.rsa.sin)
  11607. : sizeof(conn->client.rsa.sin6);
  11608. struct sockaddr *psa = (sa.sa.sa_family == AF_INET)
  11609. ? (struct sockaddr *)&(conn->client.rsa.sin)
  11610. : (struct sockaddr *)&(conn->client.rsa.sin6);
  11611. #else
  11612. socklen_t len = sizeof(conn->client.rsa.sin);
  11613. struct sockaddr *psa = (struct sockaddr *)&(conn->client.rsa.sin);
  11614. #endif
  11615. conn->buf_size = MAX_REQUEST_SIZE;
  11616. conn->buf = (char *)(conn + 1);
  11617. conn->ctx = &fake_ctx;
  11618. conn->client.sock = sock;
  11619. conn->client.lsa = sa;
  11620. if (getsockname(sock, psa, &len) != 0) {
  11621. mg_cry(conn, "%s: getsockname() failed: %s", __func__, strerror(ERRNO));
  11622. }
  11623. conn->client.is_ssl = use_ssl ? 1 : 0;
  11624. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  11625. #ifndef NO_SSL
  11626. if (use_ssl) {
  11627. fake_ctx.ssl_ctx = conn->client_ssl_ctx;
  11628. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  11629. * SSL_CTX_set_verify call is needed to switch off server
  11630. * certificate checking, which is off by default in OpenSSL and
  11631. * on in yaSSL. */
  11632. /* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  11633. * SSL_VERIFY_PEER, verify_ssl_server); */
  11634. if (client_options->client_cert) {
  11635. if (!ssl_use_pem_file(&fake_ctx,
  11636. client_options->client_cert,
  11637. NULL)) {
  11638. mg_snprintf(NULL,
  11639. NULL, /* No truncation check for ebuf */
  11640. ebuf,
  11641. ebuf_len,
  11642. "Can not use SSL client certificate");
  11643. SSL_CTX_free(conn->client_ssl_ctx);
  11644. closesocket(sock);
  11645. mg_free(conn);
  11646. return NULL;
  11647. }
  11648. }
  11649. if (client_options->server_cert) {
  11650. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  11651. client_options->server_cert,
  11652. NULL);
  11653. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  11654. } else {
  11655. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  11656. }
  11657. if (!sslize(conn,
  11658. conn->client_ssl_ctx,
  11659. SSL_connect,
  11660. &(conn->ctx->stop_flag))) {
  11661. mg_snprintf(NULL,
  11662. NULL, /* No truncation check for ebuf */
  11663. ebuf,
  11664. ebuf_len,
  11665. "SSL connection error");
  11666. SSL_CTX_free(conn->client_ssl_ctx);
  11667. closesocket(sock);
  11668. mg_free(conn);
  11669. return NULL;
  11670. }
  11671. }
  11672. #endif
  11673. set_blocking_mode(sock, 0);
  11674. return conn;
  11675. }
  11676. CIVETWEB_API struct mg_connection *
  11677. mg_connect_client_secure(const struct mg_client_options *client_options,
  11678. char *error_buffer,
  11679. size_t error_buffer_size)
  11680. {
  11681. return mg_connect_client_impl(client_options,
  11682. 1,
  11683. error_buffer,
  11684. error_buffer_size);
  11685. }
  11686. struct mg_connection *
  11687. mg_connect_client(const char *host,
  11688. int port,
  11689. int use_ssl,
  11690. char *error_buffer,
  11691. size_t error_buffer_size)
  11692. {
  11693. struct mg_client_options opts;
  11694. memset(&opts, 0, sizeof(opts));
  11695. opts.host = host;
  11696. opts.port = port;
  11697. return mg_connect_client_impl(&opts,
  11698. use_ssl,
  11699. error_buffer,
  11700. error_buffer_size);
  11701. }
  11702. static const struct {
  11703. const char *proto;
  11704. size_t proto_len;
  11705. unsigned default_port;
  11706. } abs_uri_protocols[] = {{"http://", 7, 80},
  11707. {"https://", 8, 443},
  11708. {"ws://", 5, 80},
  11709. {"wss://", 6, 443},
  11710. {NULL, 0, 0}};
  11711. /* Check if the uri is valid.
  11712. * return 0 for invalid uri,
  11713. * return 1 for *,
  11714. * return 2 for relative uri,
  11715. * return 3 for absolute uri without port,
  11716. * return 4 for absolute uri with port */
  11717. static int
  11718. get_uri_type(const char *uri)
  11719. {
  11720. int i;
  11721. const char *hostend, *portbegin;
  11722. char *portend;
  11723. unsigned long port;
  11724. /* According to the HTTP standard
  11725. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  11726. * URI can be an asterisk (*) or should start with slash (relative uri),
  11727. * or it should start with the protocol (absolute uri). */
  11728. if (uri[0] == '*' && uri[1] == '\0') {
  11729. /* asterisk */
  11730. return 1;
  11731. }
  11732. /* Valid URIs according to RFC 3986
  11733. * (https://www.ietf.org/rfc/rfc3986.txt)
  11734. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  11735. * and unreserved characters A-Z a-z 0-9 and -._~
  11736. * and % encoded symbols.
  11737. */
  11738. for (i = 0; uri[i] != 0; i++) {
  11739. if (uri[i] < 33) {
  11740. /* control characters and spaces are invalid */
  11741. return 0;
  11742. }
  11743. if (uri[i] > 126) {
  11744. /* non-ascii characters must be % encoded */
  11745. return 0;
  11746. } else {
  11747. switch (uri[i]) {
  11748. case '"': /* 34 */
  11749. case '<': /* 60 */
  11750. case '>': /* 62 */
  11751. case '\\': /* 92 */
  11752. case '^': /* 94 */
  11753. case '`': /* 96 */
  11754. case '{': /* 123 */
  11755. case '|': /* 124 */
  11756. case '}': /* 125 */
  11757. return 0;
  11758. default:
  11759. /* character is ok */
  11760. break;
  11761. }
  11762. }
  11763. }
  11764. /* A relative uri starts with a / character */
  11765. if (uri[0] == '/') {
  11766. /* relative uri */
  11767. return 2;
  11768. }
  11769. /* It could be an absolute uri: */
  11770. /* This function only checks if the uri is valid, not if it is
  11771. * addressing the current server. So civetweb can also be used
  11772. * as a proxy server. */
  11773. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  11774. if (mg_strncasecmp(uri,
  11775. abs_uri_protocols[i].proto,
  11776. abs_uri_protocols[i].proto_len) == 0) {
  11777. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  11778. if (!hostend) {
  11779. return 0;
  11780. }
  11781. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  11782. if (!portbegin) {
  11783. return 3;
  11784. }
  11785. port = strtoul(portbegin + 1, &portend, 10);
  11786. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  11787. return 0;
  11788. }
  11789. return 4;
  11790. }
  11791. }
  11792. return 0;
  11793. }
  11794. /* Return NULL or the relative uri at the current server */
  11795. static const char *
  11796. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  11797. {
  11798. const char *server_domain;
  11799. size_t server_domain_len;
  11800. size_t request_domain_len = 0;
  11801. unsigned long port = 0;
  11802. int i, auth_domain_check_enabled;
  11803. const char *hostbegin = NULL;
  11804. const char *hostend = NULL;
  11805. const char *portbegin;
  11806. char *portend;
  11807. auth_domain_check_enabled =
  11808. !strcmp(conn->ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  11809. if (!auth_domain_check_enabled) {
  11810. return 0;
  11811. }
  11812. server_domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  11813. if (!server_domain) {
  11814. return 0;
  11815. }
  11816. server_domain_len = strlen(server_domain);
  11817. if (!server_domain_len) {
  11818. return 0;
  11819. }
  11820. /* DNS is case insensitive, so use case insensitive string compare here
  11821. */
  11822. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  11823. if (mg_strncasecmp(uri,
  11824. abs_uri_protocols[i].proto,
  11825. abs_uri_protocols[i].proto_len) == 0) {
  11826. hostbegin = uri + abs_uri_protocols[i].proto_len;
  11827. hostend = strchr(hostbegin, '/');
  11828. if (!hostend) {
  11829. return 0;
  11830. }
  11831. portbegin = strchr(hostbegin, ':');
  11832. if ((!portbegin) || (portbegin > hostend)) {
  11833. port = abs_uri_protocols[i].default_port;
  11834. request_domain_len = (size_t)(hostend - hostbegin);
  11835. } else {
  11836. port = strtoul(portbegin + 1, &portend, 10);
  11837. if ((portend != hostend) || (port <= 0)
  11838. || !is_valid_port(port)) {
  11839. return 0;
  11840. }
  11841. request_domain_len = (size_t)(portbegin - hostbegin);
  11842. }
  11843. /* protocol found, port set */
  11844. break;
  11845. }
  11846. }
  11847. if (!port) {
  11848. /* port remains 0 if the protocol is not found */
  11849. return 0;
  11850. }
  11851. /* Check if the request is directed to a different server. */
  11852. /* First check if the port is the same (IPv4 and IPv6). */
  11853. #if defined(USE_IPV6)
  11854. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  11855. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  11856. /* Request is directed to a different port */
  11857. return 0;
  11858. }
  11859. } else
  11860. #endif
  11861. {
  11862. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  11863. /* Request is directed to a different port */
  11864. return 0;
  11865. }
  11866. }
  11867. /* Finally check if the server corresponds to the authentication
  11868. * domain of the server (the server domain).
  11869. * Allow full matches (like http://mydomain.com/path/file.ext), and
  11870. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  11871. * but do not allow substrings (like http://notmydomain.com/path/file.ext
  11872. * or http://mydomain.com.fake/path/file.ext).
  11873. */
  11874. if (auth_domain_check_enabled) {
  11875. if ((request_domain_len == server_domain_len)
  11876. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  11877. /* Request is directed to this server - full name match. */
  11878. } else {
  11879. if (request_domain_len < (server_domain_len + 2)) {
  11880. /* Request is directed to another server: The server name is
  11881. * longer
  11882. * than
  11883. * the request name. Drop this case here to avoid overflows in
  11884. * the
  11885. * following checks. */
  11886. return 0;
  11887. }
  11888. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  11889. /* Request is directed to another server: It could be a
  11890. * substring
  11891. * like notmyserver.com */
  11892. return 0;
  11893. }
  11894. if (0 != memcmp(server_domain,
  11895. hostbegin + request_domain_len - server_domain_len,
  11896. server_domain_len)) {
  11897. /* Request is directed to another server:
  11898. * The server name is different. */
  11899. return 0;
  11900. }
  11901. }
  11902. }
  11903. return hostend;
  11904. }
  11905. static int
  11906. getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  11907. {
  11908. const char *cl;
  11909. if (ebuf_len > 0) {
  11910. ebuf[0] = '\0';
  11911. }
  11912. *err = 0;
  11913. reset_per_request_attributes(conn);
  11914. if (!conn) {
  11915. mg_snprintf(conn,
  11916. NULL, /* No truncation check for ebuf */
  11917. ebuf,
  11918. ebuf_len,
  11919. "%s",
  11920. "Internal error");
  11921. *err = 500;
  11922. return 0;
  11923. }
  11924. /* Set the time the request was received. This value should be used for
  11925. * timeouts. */
  11926. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  11927. conn->request_len =
  11928. read_request(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  11929. /* assert(conn->request_len < 0 || conn->data_len >= conn->request_len);
  11930. */
  11931. if (conn->request_len >= 0 && conn->data_len < conn->request_len) {
  11932. mg_snprintf(conn,
  11933. NULL, /* No truncation check for ebuf */
  11934. ebuf,
  11935. ebuf_len,
  11936. "%s",
  11937. "Invalid request size");
  11938. *err = 500;
  11939. return 0;
  11940. }
  11941. if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
  11942. mg_snprintf(conn,
  11943. NULL, /* No truncation check for ebuf */
  11944. ebuf,
  11945. ebuf_len,
  11946. "%s",
  11947. "Request Too Large");
  11948. *err = 413;
  11949. return 0;
  11950. } else if (conn->request_len <= 0) {
  11951. if (conn->data_len > 0) {
  11952. mg_snprintf(conn,
  11953. NULL, /* No truncation check for ebuf */
  11954. ebuf,
  11955. ebuf_len,
  11956. "%s",
  11957. "Client sent malformed request");
  11958. *err = 400;
  11959. } else {
  11960. /* Server did not recv anything -> just close the connection */
  11961. conn->must_close = 1;
  11962. mg_snprintf(conn,
  11963. NULL, /* No truncation check for ebuf */
  11964. ebuf,
  11965. ebuf_len,
  11966. "%s",
  11967. "Client did not send a request");
  11968. *err = 0;
  11969. }
  11970. return 0;
  11971. } else if (parse_http_message(conn->buf,
  11972. conn->buf_size,
  11973. &conn->request_info) <= 0) {
  11974. mg_snprintf(conn,
  11975. NULL, /* No truncation check for ebuf */
  11976. ebuf,
  11977. ebuf_len,
  11978. "%s",
  11979. "Bad Request");
  11980. *err = 400;
  11981. return 0;
  11982. } else {
  11983. /* Message is a valid request or response */
  11984. if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) {
  11985. /* Request/response has content length set */
  11986. char *endptr = NULL;
  11987. conn->content_len = strtoll(cl, &endptr, 10);
  11988. if (endptr == cl) {
  11989. mg_snprintf(conn,
  11990. NULL, /* No truncation check for ebuf */
  11991. ebuf,
  11992. ebuf_len,
  11993. "%s",
  11994. "Bad Request");
  11995. *err = 411;
  11996. return 0;
  11997. }
  11998. /* Publish the content length back to the request info. */
  11999. conn->request_info.content_length = conn->content_len;
  12000. } else if ((cl = get_header(&conn->request_info, "Transfer-Encoding"))
  12001. != NULL
  12002. && !mg_strcasecmp(cl, "chunked")) {
  12003. conn->is_chunked = 1;
  12004. } else if (!mg_strcasecmp(conn->request_info.request_method, "POST")
  12005. || !mg_strcasecmp(conn->request_info.request_method,
  12006. "PUT")) {
  12007. /* POST or PUT request without content length set */
  12008. conn->content_len = -1;
  12009. } else if (!mg_strncasecmp(conn->request_info.request_method,
  12010. "HTTP/",
  12011. 5)) {
  12012. /* Response without content length set */
  12013. conn->content_len = -1;
  12014. } else {
  12015. /* Other request */
  12016. conn->content_len = 0;
  12017. }
  12018. }
  12019. return 1;
  12020. }
  12021. int
  12022. mg_get_response(struct mg_connection *conn,
  12023. char *ebuf,
  12024. size_t ebuf_len,
  12025. int timeout)
  12026. {
  12027. if (conn) {
  12028. /* Implementation of API function for HTTP clients */
  12029. int err, ret;
  12030. struct mg_context *octx = conn->ctx;
  12031. struct mg_context rctx = *(conn->ctx);
  12032. char txt[32]; /* will not overflow */
  12033. if (timeout >= 0) {
  12034. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  12035. rctx.config[REQUEST_TIMEOUT] = txt;
  12036. /* Not required for non-blocking sockets.
  12037. set_sock_timeout(conn->client.sock, timeout);
  12038. */
  12039. } else {
  12040. rctx.config[REQUEST_TIMEOUT] = NULL;
  12041. }
  12042. conn->ctx = &rctx;
  12043. ret = getreq(conn, ebuf, ebuf_len, &err);
  12044. conn->ctx = octx;
  12045. #if defined(MG_LEGACY_INTERFACE)
  12046. /* TODO: 1) uri is deprecated;
  12047. * 2) here, ri.uri is the http response code */
  12048. conn->request_info.uri = conn->request_info.request_uri;
  12049. #endif
  12050. conn->request_info.local_uri = conn->request_info.request_uri;
  12051. /* TODO (mid): Define proper return values - maybe return length?
  12052. * For the first test use <0 for error and >0 for OK */
  12053. return (ret == 0) ? -1 : +1;
  12054. }
  12055. return -1;
  12056. }
  12057. struct mg_connection *
  12058. mg_download(const char *host,
  12059. int port,
  12060. int use_ssl,
  12061. char *ebuf,
  12062. size_t ebuf_len,
  12063. const char *fmt,
  12064. ...)
  12065. {
  12066. struct mg_connection *conn;
  12067. va_list ap;
  12068. int i;
  12069. int reqerr;
  12070. va_start(ap, fmt);
  12071. ebuf[0] = '\0';
  12072. /* open a connection */
  12073. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  12074. if (conn != NULL) {
  12075. i = mg_vprintf(conn, fmt, ap);
  12076. if (i <= 0) {
  12077. mg_snprintf(conn,
  12078. NULL, /* No truncation check for ebuf */
  12079. ebuf,
  12080. ebuf_len,
  12081. "%s",
  12082. "Error sending request");
  12083. } else {
  12084. getreq(conn, ebuf, ebuf_len, &reqerr);
  12085. #if defined(MG_LEGACY_INTERFACE)
  12086. /* TODO: 1) uri is deprecated;
  12087. * 2) here, ri.uri is the http response code */
  12088. conn->request_info.uri = conn->request_info.request_uri;
  12089. #endif
  12090. conn->request_info.local_uri = conn->request_info.request_uri;
  12091. }
  12092. }
  12093. /* if an error occured, close the connection */
  12094. if (ebuf[0] != '\0' && conn != NULL) {
  12095. mg_close_connection(conn);
  12096. conn = NULL;
  12097. }
  12098. va_end(ap);
  12099. return conn;
  12100. }
  12101. struct websocket_client_thread_data {
  12102. struct mg_connection *conn;
  12103. mg_websocket_data_handler data_handler;
  12104. mg_websocket_close_handler close_handler;
  12105. void *callback_data;
  12106. };
  12107. #if defined(USE_WEBSOCKET)
  12108. #ifdef _WIN32
  12109. static unsigned __stdcall websocket_client_thread(void *data)
  12110. #else
  12111. static void *
  12112. websocket_client_thread(void *data)
  12113. #endif
  12114. {
  12115. struct websocket_client_thread_data *cdata =
  12116. (struct websocket_client_thread_data *)data;
  12117. mg_set_thread_name("ws-clnt");
  12118. if (cdata->conn->ctx) {
  12119. if (cdata->conn->ctx->callbacks.init_thread) {
  12120. /* 3 indicates a websocket client thread */
  12121. /* TODO: check if conn->ctx can be set */
  12122. cdata->conn->ctx->callbacks.init_thread(cdata->conn->ctx, 3);
  12123. }
  12124. }
  12125. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  12126. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  12127. if (cdata->close_handler != NULL) {
  12128. cdata->close_handler(cdata->conn, cdata->callback_data);
  12129. }
  12130. /* The websocket_client context has only this thread. If it runs out,
  12131. set the stop_flag to 2 (= "stopped"). */
  12132. cdata->conn->ctx->stop_flag = 2;
  12133. mg_free((void *)cdata);
  12134. #ifdef _WIN32
  12135. return 0;
  12136. #else
  12137. return NULL;
  12138. #endif
  12139. }
  12140. #endif
  12141. struct mg_connection *
  12142. mg_connect_websocket_client(const char *host,
  12143. int port,
  12144. int use_ssl,
  12145. char *error_buffer,
  12146. size_t error_buffer_size,
  12147. const char *path,
  12148. const char *origin,
  12149. mg_websocket_data_handler data_func,
  12150. mg_websocket_close_handler close_func,
  12151. void *user_data)
  12152. {
  12153. struct mg_connection *conn = NULL;
  12154. #if defined(USE_WEBSOCKET)
  12155. struct mg_context *newctx = NULL;
  12156. struct websocket_client_thread_data *thread_data;
  12157. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  12158. static const char *handshake_req;
  12159. if (origin != NULL) {
  12160. handshake_req = "GET %s HTTP/1.1\r\n"
  12161. "Host: %s\r\n"
  12162. "Upgrade: websocket\r\n"
  12163. "Connection: Upgrade\r\n"
  12164. "Sec-WebSocket-Key: %s\r\n"
  12165. "Sec-WebSocket-Version: 13\r\n"
  12166. "Origin: %s\r\n"
  12167. "\r\n";
  12168. } else {
  12169. handshake_req = "GET %s HTTP/1.1\r\n"
  12170. "Host: %s\r\n"
  12171. "Upgrade: websocket\r\n"
  12172. "Connection: Upgrade\r\n"
  12173. "Sec-WebSocket-Key: %s\r\n"
  12174. "Sec-WebSocket-Version: 13\r\n"
  12175. "\r\n";
  12176. }
  12177. /* Establish the client connection and request upgrade */
  12178. conn = mg_download(host,
  12179. port,
  12180. use_ssl,
  12181. error_buffer,
  12182. error_buffer_size,
  12183. handshake_req,
  12184. path,
  12185. host,
  12186. magic,
  12187. origin);
  12188. /* Connection object will be null if something goes wrong */
  12189. if (conn == NULL || (strcmp(conn->request_info.request_uri, "101") != 0)) {
  12190. if (!*error_buffer) {
  12191. /* if there is a connection, but it did not return 101,
  12192. * error_buffer is not yet set */
  12193. mg_snprintf(conn,
  12194. NULL, /* No truncation check for ebuf */
  12195. error_buffer,
  12196. error_buffer_size,
  12197. "Unexpected server reply");
  12198. }
  12199. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  12200. if (conn != NULL) {
  12201. mg_free(conn);
  12202. conn = NULL;
  12203. }
  12204. return conn;
  12205. }
  12206. /* For client connections, mg_context is fake. Since we need to set a
  12207. * callback function, we need to create a copy and modify it. */
  12208. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  12209. memcpy(newctx, conn->ctx, sizeof(struct mg_context));
  12210. newctx->user_data = user_data;
  12211. newctx->context_type = 2; /* ws/wss client context type */
  12212. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  12213. newctx->worker_threadids =
  12214. (pthread_t *)mg_calloc(newctx->cfg_worker_threads, sizeof(pthread_t));
  12215. conn->ctx = newctx;
  12216. thread_data = (struct websocket_client_thread_data *)
  12217. mg_calloc(sizeof(struct websocket_client_thread_data), 1);
  12218. thread_data->conn = conn;
  12219. thread_data->data_handler = data_func;
  12220. thread_data->close_handler = close_func;
  12221. thread_data->callback_data = user_data;
  12222. /* Start a thread to read the websocket client connection
  12223. * This thread will automatically stop when mg_disconnect is
  12224. * called on the client connection */
  12225. if (mg_start_thread_with_id(websocket_client_thread,
  12226. (void *)thread_data,
  12227. newctx->worker_threadids) != 0) {
  12228. mg_free((void *)thread_data);
  12229. mg_free((void *)newctx->worker_threadids);
  12230. mg_free((void *)newctx);
  12231. mg_free((void *)conn);
  12232. conn = NULL;
  12233. DEBUG_TRACE("%s",
  12234. "Websocket client connect thread could not be started\r\n");
  12235. }
  12236. #else
  12237. /* Appease "unused parameter" warnings */
  12238. (void)host;
  12239. (void)port;
  12240. (void)use_ssl;
  12241. (void)error_buffer;
  12242. (void)error_buffer_size;
  12243. (void)path;
  12244. (void)origin;
  12245. (void)user_data;
  12246. (void)data_func;
  12247. (void)close_func;
  12248. #endif
  12249. return conn;
  12250. }
  12251. static void
  12252. process_new_connection(struct mg_connection *conn)
  12253. {
  12254. if (conn && conn->ctx) {
  12255. struct mg_request_info *ri = &conn->request_info;
  12256. int keep_alive_enabled, keep_alive, discard_len;
  12257. char ebuf[100];
  12258. const char *hostend;
  12259. int reqerr, uri_type;
  12260. keep_alive_enabled =
  12261. !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  12262. /* Important: on new connection, reset the receiving buffer. Credit
  12263. * goes to crule42. */
  12264. conn->data_len = 0;
  12265. conn->handled_requests = 0;
  12266. do {
  12267. DEBUG_TRACE("calling getreq (%i times for this connection)",
  12268. conn->handled_requests + 1);
  12269. if (!getreq(conn, ebuf, sizeof(ebuf), &reqerr)) {
  12270. /* The request sent by the client could not be understood by
  12271. * the server, or it was incomplete or a timeout. Send an
  12272. * error message and close the connection. */
  12273. if (reqerr > 0) {
  12274. /*assert(ebuf[0] != '\0');*/
  12275. mg_send_http_error(conn, reqerr, "%s", ebuf);
  12276. }
  12277. } else if (strcmp(ri->http_version, "1.0")
  12278. && strcmp(ri->http_version, "1.1")) {
  12279. mg_snprintf(conn,
  12280. NULL, /* No truncation check for ebuf */
  12281. ebuf,
  12282. sizeof(ebuf),
  12283. "Bad HTTP version: [%s]",
  12284. ri->http_version);
  12285. mg_send_http_error(conn, 505, "%s", ebuf);
  12286. }
  12287. if (ebuf[0] == '\0') {
  12288. uri_type = get_uri_type(conn->request_info.request_uri);
  12289. switch (uri_type) {
  12290. case 1:
  12291. /* Asterisk */
  12292. conn->request_info.local_uri = NULL;
  12293. break;
  12294. case 2:
  12295. /* relative uri */
  12296. conn->request_info.local_uri =
  12297. conn->request_info.request_uri;
  12298. break;
  12299. case 3:
  12300. case 4:
  12301. /* absolute uri (with/without port) */
  12302. hostend = get_rel_url_at_current_server(
  12303. conn->request_info.request_uri, conn);
  12304. if (hostend) {
  12305. conn->request_info.local_uri = hostend;
  12306. } else {
  12307. conn->request_info.local_uri = NULL;
  12308. }
  12309. break;
  12310. default:
  12311. mg_snprintf(conn,
  12312. NULL, /* No truncation check for ebuf */
  12313. ebuf,
  12314. sizeof(ebuf),
  12315. "Invalid URI");
  12316. mg_send_http_error(conn, 400, "%s", ebuf);
  12317. conn->request_info.local_uri = NULL;
  12318. break;
  12319. }
  12320. #if defined(MG_LEGACY_INTERFACE)
  12321. /* TODO: cleanup uri, local_uri and request_uri */
  12322. conn->request_info.uri = conn->request_info.local_uri;
  12323. #endif
  12324. }
  12325. DEBUG_TRACE("http: %s, error: %s",
  12326. (ri->http_version ? ri->http_version : "none"),
  12327. (ebuf[0] ? ebuf : "none"));
  12328. if (ebuf[0] == '\0') {
  12329. if (conn->request_info.local_uri) {
  12330. /* handle request to local server */
  12331. handle_request(conn);
  12332. DEBUG_TRACE("%s", "handle_request done");
  12333. if (conn->ctx->callbacks.end_request != NULL) {
  12334. conn->ctx->callbacks.end_request(conn,
  12335. conn->status_code);
  12336. DEBUG_TRACE("%s", "end_request callback done");
  12337. }
  12338. log_access(conn);
  12339. } else {
  12340. /* TODO: handle non-local request (PROXY) */
  12341. conn->must_close = 1;
  12342. }
  12343. } else {
  12344. conn->must_close = 1;
  12345. }
  12346. if (ri->remote_user != NULL) {
  12347. mg_free((void *)ri->remote_user);
  12348. /* Important! When having connections with and without auth
  12349. * would cause double free and then crash */
  12350. ri->remote_user = NULL;
  12351. }
  12352. /* NOTE(lsm): order is important here. should_keep_alive() call
  12353. * is
  12354. * using parsed request, which will be invalid after memmove's
  12355. * below.
  12356. * Therefore, memorize should_keep_alive() result now for later
  12357. * use
  12358. * in loop exit condition. */
  12359. keep_alive = (conn->ctx->stop_flag == 0) && keep_alive_enabled
  12360. && (conn->content_len >= 0) && should_keep_alive(conn);
  12361. /* Discard all buffered data for this request */
  12362. discard_len = ((conn->content_len >= 0) && (conn->request_len > 0)
  12363. && ((conn->request_len + conn->content_len)
  12364. < (int64_t)conn->data_len))
  12365. ? (int)(conn->request_len + conn->content_len)
  12366. : conn->data_len;
  12367. /*assert(discard_len >= 0);*/
  12368. if (discard_len < 0) {
  12369. DEBUG_TRACE("internal error: discard_len = %li",
  12370. (long int)discard_len);
  12371. break;
  12372. }
  12373. conn->data_len -= discard_len;
  12374. if (conn->data_len > 0) {
  12375. DEBUG_TRACE("discard_len = %lu", (long unsigned)discard_len);
  12376. memmove(conn->buf,
  12377. conn->buf + discard_len,
  12378. (size_t)conn->data_len);
  12379. }
  12380. /* assert(conn->data_len >= 0); */
  12381. /* assert(conn->data_len <= conn->buf_size); */
  12382. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  12383. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  12384. (long int)conn->data_len,
  12385. (long int)conn->buf_size);
  12386. break;
  12387. }
  12388. conn->handled_requests++;
  12389. } while (keep_alive);
  12390. }
  12391. }
  12392. #if defined(ALTERNATIVE_QUEUE)
  12393. static void
  12394. produce_socket(struct mg_context *ctx, const struct socket *sp)
  12395. {
  12396. unsigned int i;
  12397. for (;;) {
  12398. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  12399. /* find a free worker slot and signal it */
  12400. if (ctx->client_socks[i].in_use == 0) {
  12401. ctx->client_socks[i] = *sp;
  12402. ctx->client_socks[i].in_use = 1;
  12403. event_signal(ctx->client_wait_events[i]);
  12404. return;
  12405. }
  12406. }
  12407. /* queue is full */
  12408. mg_sleep(1);
  12409. }
  12410. }
  12411. static int
  12412. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  12413. {
  12414. DEBUG_TRACE("%s", "going idle");
  12415. ctx->client_socks[thread_index].in_use = 0;
  12416. event_wait(ctx->client_wait_events[thread_index]);
  12417. *sp = ctx->client_socks[thread_index];
  12418. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  12419. return !ctx->stop_flag;
  12420. }
  12421. #else /* ALTERNATIVE_QUEUE */
  12422. /* Worker threads take accepted socket from the queue */
  12423. static int
  12424. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  12425. {
  12426. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  12427. (void)thread_index;
  12428. (void)pthread_mutex_lock(&ctx->thread_mutex);
  12429. DEBUG_TRACE("%s", "going idle");
  12430. /* If the queue is empty, wait. We're idle at this point. */
  12431. while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
  12432. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  12433. }
  12434. /* If we're stopping, sq_head may be equal to sq_tail. */
  12435. if (ctx->sq_head > ctx->sq_tail) {
  12436. /* Copy socket from the queue and increment tail */
  12437. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  12438. ctx->sq_tail++;
  12439. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  12440. /* Wrap pointers if needed */
  12441. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  12442. ctx->sq_tail -= QUEUE_SIZE(ctx);
  12443. ctx->sq_head -= QUEUE_SIZE(ctx);
  12444. }
  12445. }
  12446. (void)pthread_cond_signal(&ctx->sq_empty);
  12447. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  12448. return !ctx->stop_flag;
  12449. #undef QUEUE_SIZE
  12450. }
  12451. /* Master thread adds accepted socket to a queue */
  12452. static void
  12453. produce_socket(struct mg_context *ctx, const struct socket *sp)
  12454. {
  12455. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  12456. if (!ctx) {
  12457. return;
  12458. }
  12459. (void)pthread_mutex_lock(&ctx->thread_mutex);
  12460. /* If the queue is full, wait */
  12461. while (ctx->stop_flag == 0
  12462. && ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx)) {
  12463. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  12464. }
  12465. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  12466. /* Copy socket to the queue and increment head */
  12467. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  12468. ctx->sq_head++;
  12469. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  12470. }
  12471. (void)pthread_cond_signal(&ctx->sq_full);
  12472. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  12473. #undef QUEUE_SIZE
  12474. }
  12475. #endif /* ALTERNATIVE_QUEUE */
  12476. struct worker_thread_args {
  12477. struct mg_context *ctx;
  12478. int index;
  12479. };
  12480. static void *
  12481. worker_thread_run(struct worker_thread_args *thread_args)
  12482. {
  12483. struct mg_context *ctx = thread_args->ctx;
  12484. struct mg_connection *conn;
  12485. struct mg_workerTLS tls;
  12486. #if defined(MG_LEGACY_INTERFACE)
  12487. uint32_t addr;
  12488. #endif
  12489. mg_set_thread_name("worker");
  12490. tls.is_master = 0;
  12491. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  12492. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12493. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  12494. #endif
  12495. /* Initialize thread local storage before calling any callback */
  12496. pthread_setspecific(sTlsKey, &tls);
  12497. if (ctx->callbacks.init_thread) {
  12498. /* call init_thread for a worker thread (type 1) */
  12499. ctx->callbacks.init_thread(ctx, 1);
  12500. }
  12501. /* Connection structure has been pre-allocated */
  12502. if (((int)thread_args->index < 0)
  12503. || ((unsigned)thread_args->index
  12504. >= (unsigned)ctx->cfg_worker_threads)) {
  12505. mg_cry(fc(ctx),
  12506. "Internal error: Invalid worker index %i",
  12507. (int)thread_args->index);
  12508. return NULL;
  12509. }
  12510. conn = ctx->worker_connections + thread_args->index;
  12511. /* Request buffers are not pre-allocated. They are private to the
  12512. * request and do not contain any state information that might be
  12513. * of interest to anyone observing a server status. */
  12514. conn->buf = (char *)mg_malloc(MAX_REQUEST_SIZE);
  12515. if (conn->buf == NULL) {
  12516. mg_cry(fc(ctx),
  12517. "Out of memory: Cannot allocate buffer for worker %i",
  12518. (int)thread_args->index);
  12519. return NULL;
  12520. }
  12521. conn->buf_size = MAX_REQUEST_SIZE;
  12522. conn->ctx = ctx;
  12523. conn->thread_index = thread_args->index;
  12524. conn->request_info.user_data = ctx->user_data;
  12525. /* Allocate a mutex for this connection to allow communication both
  12526. * within the request handler and from elsewhere in the application
  12527. */
  12528. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  12529. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  12530. * signal sq_empty condvar to wake up the master waiting in
  12531. * produce_socket() */
  12532. while (consume_socket(ctx, &conn->client, conn->thread_index)) {
  12533. conn->conn_birth_time = time(NULL);
  12534. /* Fill in IP, port info early so even if SSL setup below fails,
  12535. * error handler would have the corresponding info.
  12536. * Thanks to Johannes Winkelmann for the patch.
  12537. */
  12538. #if defined(USE_IPV6)
  12539. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  12540. conn->request_info.remote_port =
  12541. ntohs(conn->client.rsa.sin6.sin6_port);
  12542. } else
  12543. #endif
  12544. {
  12545. conn->request_info.remote_port =
  12546. ntohs(conn->client.rsa.sin.sin_port);
  12547. }
  12548. sockaddr_to_string(conn->request_info.remote_addr,
  12549. sizeof(conn->request_info.remote_addr),
  12550. &conn->client.rsa);
  12551. DEBUG_TRACE("Start processing connection from %s",
  12552. conn->request_info.remote_addr);
  12553. #if defined(MG_LEGACY_INTERFACE)
  12554. /* This legacy interface only works for the IPv4 case */
  12555. addr = ntohl(conn->client.rsa.sin.sin_addr.s_addr);
  12556. memcpy(&conn->request_info.remote_ip, &addr, 4);
  12557. #endif
  12558. conn->request_info.is_ssl = conn->client.is_ssl;
  12559. if (conn->client.is_ssl) {
  12560. #ifndef NO_SSL
  12561. /* HTTPS connection */
  12562. if (sslize(conn,
  12563. conn->ctx->ssl_ctx,
  12564. SSL_accept,
  12565. &(conn->ctx->stop_flag))) {
  12566. /* Get SSL client certificate information (if set) */
  12567. ssl_get_client_cert_info(conn);
  12568. /* process HTTPS connection */
  12569. process_new_connection(conn);
  12570. /* Free client certificate info */
  12571. if (conn->request_info.client_cert) {
  12572. mg_free((void *)(conn->request_info.client_cert->subject));
  12573. mg_free((void *)(conn->request_info.client_cert->issuer));
  12574. mg_free((void *)(conn->request_info.client_cert->serial));
  12575. mg_free((void *)(conn->request_info.client_cert->finger));
  12576. conn->request_info.client_cert->subject = 0;
  12577. conn->request_info.client_cert->issuer = 0;
  12578. conn->request_info.client_cert->serial = 0;
  12579. conn->request_info.client_cert->finger = 0;
  12580. mg_free(conn->request_info.client_cert);
  12581. conn->request_info.client_cert = 0;
  12582. }
  12583. }
  12584. #endif
  12585. } else {
  12586. /* process HTTP connection */
  12587. process_new_connection(conn);
  12588. }
  12589. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  12590. conn->request_info.remote_addr,
  12591. difftime(time(NULL), conn->conn_birth_time));
  12592. close_connection(conn);
  12593. DEBUG_TRACE("%s", "Connection closed");
  12594. }
  12595. pthread_setspecific(sTlsKey, NULL);
  12596. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12597. CloseHandle(tls.pthread_cond_helper_mutex);
  12598. #endif
  12599. pthread_mutex_destroy(&conn->mutex);
  12600. /* Free the request buffer. */
  12601. conn->buf_size = 0;
  12602. mg_free(conn->buf);
  12603. conn->buf = NULL;
  12604. DEBUG_TRACE("%s", "exiting");
  12605. return NULL;
  12606. }
  12607. /* Threads have different return types on Windows and Unix. */
  12608. #ifdef _WIN32
  12609. static unsigned __stdcall worker_thread(void *thread_func_param)
  12610. {
  12611. struct worker_thread_args *pwta =
  12612. (struct worker_thread_args *)thread_func_param;
  12613. worker_thread_run(pwta);
  12614. mg_free(thread_func_param);
  12615. return 0;
  12616. }
  12617. #else
  12618. static void *
  12619. worker_thread(void *thread_func_param)
  12620. {
  12621. struct worker_thread_args *pwta =
  12622. (struct worker_thread_args *)thread_func_param;
  12623. worker_thread_run(pwta);
  12624. mg_free(thread_func_param);
  12625. return NULL;
  12626. }
  12627. #endif /* _WIN32 */
  12628. static void
  12629. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  12630. {
  12631. struct socket so;
  12632. char src_addr[IP_ADDR_STR_LEN];
  12633. socklen_t len = sizeof(so.rsa);
  12634. int on = 1;
  12635. if (!listener) {
  12636. return;
  12637. }
  12638. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  12639. == INVALID_SOCKET) {
  12640. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  12641. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  12642. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  12643. closesocket(so.sock);
  12644. so.sock = INVALID_SOCKET;
  12645. } else {
  12646. /* Put so socket structure into the queue */
  12647. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  12648. set_close_on_exec(so.sock, fc(ctx));
  12649. so.is_ssl = listener->is_ssl;
  12650. so.ssl_redir = listener->ssl_redir;
  12651. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  12652. mg_cry(fc(ctx),
  12653. "%s: getsockname() failed: %s",
  12654. __func__,
  12655. strerror(ERRNO));
  12656. }
  12657. /* Set TCP keep-alive. This is needed because if HTTP-level
  12658. * keep-alive
  12659. * is enabled, and client resets the connection, server won't get
  12660. * TCP FIN or RST and will keep the connection open forever. With
  12661. * TCP keep-alive, next keep-alive handshake will figure out that
  12662. * the client is down and will close the server end.
  12663. * Thanks to Igor Klopov who suggested the patch. */
  12664. if (setsockopt(so.sock,
  12665. SOL_SOCKET,
  12666. SO_KEEPALIVE,
  12667. (SOCK_OPT_TYPE)&on,
  12668. sizeof(on)) != 0) {
  12669. mg_cry(fc(ctx),
  12670. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  12671. __func__,
  12672. strerror(ERRNO));
  12673. }
  12674. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  12675. * to effectively fill up the underlying IP packet payload and
  12676. * reduce the overhead of sending lots of small buffers. However
  12677. * this hurts the server's throughput (ie. operations per second)
  12678. * when HTTP 1.1 persistent connections are used and the responses
  12679. * are relatively small (eg. less than 1400 bytes).
  12680. */
  12681. if ((ctx != NULL) && (ctx->config[CONFIG_TCP_NODELAY] != NULL)
  12682. && (!strcmp(ctx->config[CONFIG_TCP_NODELAY], "1"))) {
  12683. if (set_tcp_nodelay(so.sock, 1) != 0) {
  12684. mg_cry(fc(ctx),
  12685. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  12686. __func__,
  12687. strerror(ERRNO));
  12688. }
  12689. }
  12690. /* We are using non-blocking sockets. Thus, the
  12691. * set_sock_timeout(so.sock, timeout);
  12692. * call is no longer required. */
  12693. set_blocking_mode(so.sock, 0);
  12694. produce_socket(ctx, &so);
  12695. }
  12696. }
  12697. static void
  12698. master_thread_run(void *thread_func_param)
  12699. {
  12700. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  12701. struct mg_workerTLS tls;
  12702. struct pollfd *pfd;
  12703. unsigned int i;
  12704. unsigned int workerthreadcount;
  12705. if (!ctx) {
  12706. return;
  12707. }
  12708. mg_set_thread_name("master");
  12709. /* Increase priority of the master thread */
  12710. #if defined(_WIN32)
  12711. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  12712. #elif defined(USE_MASTER_THREAD_PRIORITY)
  12713. int min_prio = sched_get_priority_min(SCHED_RR);
  12714. int max_prio = sched_get_priority_max(SCHED_RR);
  12715. if ((min_prio >= 0) && (max_prio >= 0)
  12716. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  12717. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  12718. struct sched_param sched_param = {0};
  12719. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  12720. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  12721. }
  12722. #endif
  12723. /* Initialize thread local storage */
  12724. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12725. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  12726. #endif
  12727. tls.is_master = 1;
  12728. pthread_setspecific(sTlsKey, &tls);
  12729. if (ctx->callbacks.init_thread) {
  12730. /* Callback for the master thread (type 0) */
  12731. ctx->callbacks.init_thread(ctx, 0);
  12732. }
  12733. /* Server starts *now* */
  12734. ctx->start_time = time(NULL);
  12735. /* Start the server */
  12736. pfd = ctx->listening_socket_fds;
  12737. while (ctx->stop_flag == 0) {
  12738. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12739. pfd[i].fd = ctx->listening_sockets[i].sock;
  12740. pfd[i].events = POLLIN;
  12741. }
  12742. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  12743. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12744. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  12745. * successful poll, and POLLIN is defined as
  12746. * (POLLRDNORM | POLLRDBAND)
  12747. * Therefore, we're checking pfd[i].revents & POLLIN, not
  12748. * pfd[i].revents == POLLIN. */
  12749. if (ctx->stop_flag == 0 && (pfd[i].revents & POLLIN)) {
  12750. accept_new_connection(&ctx->listening_sockets[i], ctx);
  12751. }
  12752. }
  12753. }
  12754. }
  12755. /* Here stop_flag is 1 - Initiate shutdown. */
  12756. DEBUG_TRACE("%s", "stopping workers");
  12757. /* Stop signal received: somebody called mg_stop. Quit. */
  12758. close_all_listening_sockets(ctx);
  12759. /* Wakeup workers that are waiting for connections to handle. */
  12760. (void)pthread_mutex_lock(&ctx->thread_mutex);
  12761. #if defined(ALTERNATIVE_QUEUE)
  12762. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  12763. event_signal(ctx->client_wait_events[i]);
  12764. /* Since we know all sockets, we can shutdown the connections. */
  12765. if (ctx->client_socks[i].in_use) {
  12766. shutdown(ctx->client_socks[i].sock, SHUTDOWN_BOTH);
  12767. }
  12768. }
  12769. #else
  12770. pthread_cond_broadcast(&ctx->sq_full);
  12771. #endif
  12772. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  12773. /* Join all worker threads to avoid leaking threads. */
  12774. workerthreadcount = ctx->cfg_worker_threads;
  12775. for (i = 0; i < workerthreadcount; i++) {
  12776. if (ctx->worker_threadids[i] != 0) {
  12777. mg_join_thread(ctx->worker_threadids[i]);
  12778. }
  12779. }
  12780. #if defined(USE_LUA)
  12781. /* Free Lua state of lua background task */
  12782. if (ctx->lua_background_state) {
  12783. lua_close((lua_State *)ctx->lua_background_state);
  12784. ctx->lua_background_state = 0;
  12785. }
  12786. #endif
  12787. #if !defined(NO_SSL)
  12788. if (ctx->ssl_ctx != NULL) {
  12789. uninitialize_ssl();
  12790. }
  12791. #endif
  12792. DEBUG_TRACE("%s", "exiting");
  12793. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12794. CloseHandle(tls.pthread_cond_helper_mutex);
  12795. #endif
  12796. pthread_setspecific(sTlsKey, NULL);
  12797. /* Signal mg_stop() that we're done.
  12798. * WARNING: This must be the very last thing this
  12799. * thread does, as ctx becomes invalid after this line. */
  12800. ctx->stop_flag = 2;
  12801. }
  12802. /* Threads have different return types on Windows and Unix. */
  12803. #ifdef _WIN32
  12804. static unsigned __stdcall master_thread(void *thread_func_param)
  12805. {
  12806. master_thread_run(thread_func_param);
  12807. return 0;
  12808. }
  12809. #else
  12810. static void *
  12811. master_thread(void *thread_func_param)
  12812. {
  12813. master_thread_run(thread_func_param);
  12814. return NULL;
  12815. }
  12816. #endif /* _WIN32 */
  12817. static void
  12818. free_context(struct mg_context *ctx)
  12819. {
  12820. int i;
  12821. struct mg_handler_info *tmp_rh;
  12822. if (ctx == NULL) {
  12823. return;
  12824. }
  12825. if (ctx->callbacks.exit_context) {
  12826. ctx->callbacks.exit_context(ctx);
  12827. }
  12828. /* All threads exited, no sync is needed. Destroy thread mutex and
  12829. * condvars
  12830. */
  12831. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  12832. #if defined(ALTERNATIVE_QUEUE)
  12833. mg_free(ctx->client_socks);
  12834. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  12835. event_destroy(ctx->client_wait_events[i]);
  12836. }
  12837. mg_free(ctx->client_wait_events);
  12838. #else
  12839. (void)pthread_cond_destroy(&ctx->sq_empty);
  12840. (void)pthread_cond_destroy(&ctx->sq_full);
  12841. #endif
  12842. /* Destroy other context global data structures mutex */
  12843. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  12844. #if defined(USE_TIMERS)
  12845. timers_exit(ctx);
  12846. #endif
  12847. /* Deallocate config parameters */
  12848. for (i = 0; i < NUM_OPTIONS; i++) {
  12849. if (ctx->config[i] != NULL) {
  12850. #if defined(_MSC_VER)
  12851. #pragma warning(suppress : 6001)
  12852. #endif
  12853. mg_free(ctx->config[i]);
  12854. }
  12855. }
  12856. /* Deallocate request handlers */
  12857. while (ctx->handlers) {
  12858. tmp_rh = ctx->handlers;
  12859. ctx->handlers = tmp_rh->next;
  12860. mg_free(tmp_rh->uri);
  12861. mg_free(tmp_rh);
  12862. }
  12863. #ifndef NO_SSL
  12864. /* Deallocate SSL context */
  12865. if (ctx->ssl_ctx != NULL) {
  12866. SSL_CTX_free(ctx->ssl_ctx);
  12867. }
  12868. #endif /* !NO_SSL */
  12869. /* Deallocate worker thread ID array */
  12870. if (ctx->worker_threadids != NULL) {
  12871. mg_free(ctx->worker_threadids);
  12872. }
  12873. /* Deallocate worker thread ID array */
  12874. if (ctx->worker_connections != NULL) {
  12875. mg_free(ctx->worker_connections);
  12876. }
  12877. /* Deallocate the tls variable */
  12878. if (mg_atomic_dec(&sTlsInit) == 0) {
  12879. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12880. DeleteCriticalSection(&global_log_file_lock);
  12881. #endif /* _WIN32 && !__SYMBIAN32__ */
  12882. #if !defined(_WIN32)
  12883. pthread_mutexattr_destroy(&pthread_mutex_attr);
  12884. #endif
  12885. pthread_key_delete(sTlsKey);
  12886. #if defined(USE_LUA)
  12887. lua_exit_optional_libraries();
  12888. #endif
  12889. }
  12890. /* deallocate system name string */
  12891. mg_free(ctx->systemName);
  12892. /* Deallocate context itself */
  12893. mg_free(ctx);
  12894. }
  12895. void
  12896. mg_stop(struct mg_context *ctx)
  12897. {
  12898. pthread_t mt;
  12899. if (!ctx) {
  12900. return;
  12901. }
  12902. /* We don't use a lock here. Calling mg_stop with the same ctx from
  12903. * two threads is not allowed. */
  12904. mt = ctx->masterthreadid;
  12905. if (mt == 0) {
  12906. return;
  12907. }
  12908. ctx->masterthreadid = 0;
  12909. /* Set stop flag, so all threads know they have to exit. */
  12910. ctx->stop_flag = 1;
  12911. /* Wait until everything has stopped. */
  12912. while (ctx->stop_flag != 2) {
  12913. (void)mg_sleep(10);
  12914. }
  12915. mg_join_thread(mt);
  12916. free_context(ctx);
  12917. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12918. (void)WSACleanup();
  12919. #endif /* _WIN32 && !__SYMBIAN32__ */
  12920. }
  12921. static void
  12922. get_system_name(char **sysName)
  12923. {
  12924. #if defined(_WIN32)
  12925. #if !defined(__SYMBIAN32__)
  12926. #if defined(_WIN32_WCE)
  12927. *sysName = mg_strdup("WinCE");
  12928. #else
  12929. char name[128];
  12930. DWORD dwVersion = 0;
  12931. DWORD dwMajorVersion = 0;
  12932. DWORD dwMinorVersion = 0;
  12933. DWORD dwBuild = 0;
  12934. BOOL wowRet, isWoW = FALSE;
  12935. #ifdef _MSC_VER
  12936. #pragma warning(push)
  12937. /* GetVersion was declared deprecated */
  12938. #pragma warning(disable : 4996)
  12939. #endif
  12940. dwVersion = GetVersion();
  12941. #ifdef _MSC_VER
  12942. #pragma warning(pop)
  12943. #endif
  12944. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  12945. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  12946. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  12947. (void)dwBuild;
  12948. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  12949. sprintf(name,
  12950. "Windows %u.%u%s",
  12951. (unsigned)dwMajorVersion,
  12952. (unsigned)dwMinorVersion,
  12953. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  12954. *sysName = mg_strdup(name);
  12955. #endif
  12956. #else
  12957. *sysName = mg_strdup("Symbian");
  12958. #endif
  12959. #else
  12960. struct utsname name;
  12961. memset(&name, 0, sizeof(name));
  12962. uname(&name);
  12963. *sysName = mg_strdup(name.sysname);
  12964. #endif
  12965. }
  12966. struct mg_context *
  12967. mg_start(const struct mg_callbacks *callbacks,
  12968. void *user_data,
  12969. const char **options)
  12970. {
  12971. struct mg_context *ctx;
  12972. const char *name, *value, *default_value;
  12973. int idx, ok, workerthreadcount;
  12974. unsigned int i;
  12975. void (*exit_callback)(const struct mg_context *ctx) = 0;
  12976. struct mg_workerTLS tls;
  12977. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12978. WSADATA data;
  12979. WSAStartup(MAKEWORD(2, 2), &data);
  12980. #endif /* _WIN32 && !__SYMBIAN32__ */
  12981. /* Allocate context and initialize reasonable general case defaults. */
  12982. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  12983. return NULL;
  12984. }
  12985. /* Random number generator will initialize at the first call */
  12986. ctx->auth_nonce_mask =
  12987. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  12988. if (mg_atomic_inc(&sTlsInit) == 1) {
  12989. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12990. InitializeCriticalSection(&global_log_file_lock);
  12991. #endif /* _WIN32 && !__SYMBIAN32__ */
  12992. #if !defined(_WIN32)
  12993. pthread_mutexattr_init(&pthread_mutex_attr);
  12994. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  12995. #endif
  12996. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  12997. /* Fatal error - abort start. However, this situation should
  12998. * never occur in practice. */
  12999. mg_atomic_dec(&sTlsInit);
  13000. mg_cry(fc(ctx), "Cannot initialize thread local storage");
  13001. mg_free(ctx);
  13002. return NULL;
  13003. }
  13004. #if defined(USE_LUA)
  13005. lua_init_optional_libraries();
  13006. #endif
  13007. } else {
  13008. /* TODO (low): instead of sleeping, check if sTlsKey is already
  13009. * initialized. */
  13010. mg_sleep(1);
  13011. }
  13012. tls.is_master = -1;
  13013. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  13014. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13015. tls.pthread_cond_helper_mutex = NULL;
  13016. #endif
  13017. pthread_setspecific(sTlsKey, &tls);
  13018. /* Dummy use this function - in some #ifdef combinations it's used,
  13019. * while it's not used in others, but GCC seems to stupid to understand
  13020. * #pragma GCC diagnostic ignored "-Wunused-function"
  13021. * in cases the function is unused, and it also complains on
  13022. * __attribute((unused))__ in cases it is used.
  13023. * So dummy use it, to have our peace. */
  13024. (void)mg_current_thread_id();
  13025. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr);
  13026. #if !defined(ALTERNATIVE_QUEUE)
  13027. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  13028. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  13029. #endif
  13030. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr);
  13031. if (!ok) {
  13032. /* Fatal error - abort start. However, this situation should never
  13033. * occur in practice. */
  13034. mg_cry(fc(ctx), "Cannot initialize thread synchronization objects");
  13035. mg_free(ctx);
  13036. pthread_setspecific(sTlsKey, NULL);
  13037. return NULL;
  13038. }
  13039. if (callbacks) {
  13040. ctx->callbacks = *callbacks;
  13041. exit_callback = callbacks->exit_context;
  13042. ctx->callbacks.exit_context = 0;
  13043. }
  13044. ctx->user_data = user_data;
  13045. ctx->handlers = NULL;
  13046. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  13047. ctx->shared_lua_websockets = 0;
  13048. #endif
  13049. while (options && (name = *options++) != NULL) {
  13050. if ((idx = get_option_index(name)) == -1) {
  13051. mg_cry(fc(ctx), "Invalid option: %s", name);
  13052. free_context(ctx);
  13053. pthread_setspecific(sTlsKey, NULL);
  13054. return NULL;
  13055. } else if ((value = *options++) == NULL) {
  13056. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  13057. free_context(ctx);
  13058. pthread_setspecific(sTlsKey, NULL);
  13059. return NULL;
  13060. }
  13061. if (ctx->config[idx] != NULL) {
  13062. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  13063. mg_free(ctx->config[idx]);
  13064. }
  13065. ctx->config[idx] = mg_strdup(value);
  13066. DEBUG_TRACE("[%s] -> [%s]", name, value);
  13067. }
  13068. /* Set default value if needed */
  13069. for (i = 0; config_options[i].name != NULL; i++) {
  13070. default_value = config_options[i].default_value;
  13071. if (ctx->config[i] == NULL && default_value != NULL) {
  13072. ctx->config[i] = mg_strdup(default_value);
  13073. }
  13074. }
  13075. workerthreadcount = atoi(ctx->config[NUM_THREADS]);
  13076. if (workerthreadcount > MAX_WORKER_THREADS) {
  13077. mg_cry(fc(ctx), "Too many worker threads");
  13078. free_context(ctx);
  13079. pthread_setspecific(sTlsKey, NULL);
  13080. return NULL;
  13081. }
  13082. if (workerthreadcount <= 0) {
  13083. mg_cry(fc(ctx), "Invalid number of worker threads");
  13084. free_context(ctx);
  13085. pthread_setspecific(sTlsKey, NULL);
  13086. return NULL;
  13087. }
  13088. #if defined(NO_FILES)
  13089. if (ctx->config[DOCUMENT_ROOT] != NULL) {
  13090. mg_cry(fc(ctx), "%s", "Document root must not be set");
  13091. free_context(ctx);
  13092. pthread_setspecific(sTlsKey, NULL);
  13093. return NULL;
  13094. }
  13095. #endif
  13096. get_system_name(&ctx->systemName);
  13097. #if defined(USE_LUA)
  13098. /* If a Lua background script has been configured, start it. */
  13099. if (ctx->config[LUA_BACKGROUND_SCRIPT] != NULL) {
  13100. char ebuf[256];
  13101. void *state = (void *)mg_prepare_lua_context_script(
  13102. ctx->config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  13103. if (!state) {
  13104. mg_cry(fc(ctx), "lua_background_script error: %s", ebuf);
  13105. free_context(ctx);
  13106. pthread_setspecific(sTlsKey, NULL);
  13107. return NULL;
  13108. }
  13109. ctx->lua_background_state = state;
  13110. } else {
  13111. ctx->lua_background_state = 0;
  13112. }
  13113. #endif
  13114. /* NOTE(lsm): order is important here. SSL certificates must
  13115. * be initialized before listening ports. UID must be set last. */
  13116. if (!set_gpass_option(ctx) ||
  13117. #if !defined(NO_SSL)
  13118. !set_ssl_option(ctx) ||
  13119. #endif
  13120. !set_ports_option(ctx) ||
  13121. #if !defined(_WIN32)
  13122. !set_uid_option(ctx) ||
  13123. #endif
  13124. !set_acl_option(ctx)) {
  13125. free_context(ctx);
  13126. pthread_setspecific(sTlsKey, NULL);
  13127. return NULL;
  13128. }
  13129. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  13130. /* Ignore SIGPIPE signal, so if browser cancels the request, it
  13131. * won't kill the whole process. */
  13132. (void)signal(SIGPIPE, SIG_IGN);
  13133. #endif /* !_WIN32 && !__SYMBIAN32__ */
  13134. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  13135. ctx->worker_threadids =
  13136. (pthread_t *)mg_calloc(ctx->cfg_worker_threads, sizeof(pthread_t));
  13137. if (ctx->worker_threadids == NULL) {
  13138. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  13139. free_context(ctx);
  13140. pthread_setspecific(sTlsKey, NULL);
  13141. return NULL;
  13142. }
  13143. ctx->worker_connections =
  13144. (struct mg_connection *)mg_calloc(ctx->cfg_worker_threads,
  13145. sizeof(struct mg_connection));
  13146. if (ctx->worker_connections == NULL) {
  13147. mg_cry(fc(ctx), "Not enough memory for worker thread connection array");
  13148. free_context(ctx);
  13149. pthread_setspecific(sTlsKey, NULL);
  13150. return NULL;
  13151. }
  13152. #if defined(ALTERNATIVE_QUEUE)
  13153. ctx->client_wait_events =
  13154. mg_calloc(sizeof(ctx->client_wait_events[0]), ctx->cfg_worker_threads);
  13155. if (ctx->client_wait_events == NULL) {
  13156. mg_cry(fc(ctx), "Not enough memory for worker event array");
  13157. mg_free(ctx->worker_threadids);
  13158. free_context(ctx);
  13159. pthread_setspecific(sTlsKey, NULL);
  13160. return NULL;
  13161. }
  13162. ctx->client_socks =
  13163. mg_calloc(sizeof(ctx->client_socks[0]), ctx->cfg_worker_threads);
  13164. if (ctx->client_wait_events == NULL) {
  13165. mg_cry(fc(ctx), "Not enough memory for worker socket array");
  13166. mg_free(ctx->client_socks);
  13167. mg_free(ctx->worker_threadids);
  13168. free_context(ctx);
  13169. pthread_setspecific(sTlsKey, NULL);
  13170. return NULL;
  13171. }
  13172. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  13173. ctx->client_wait_events[i] = event_create();
  13174. if (ctx->client_wait_events[i] == 0) {
  13175. mg_cry(fc(ctx), "Error creating worker event %i", i);
  13176. while (i > 0) {
  13177. i--;
  13178. event_destroy(ctx->client_wait_events[i]);
  13179. }
  13180. mg_free(ctx->client_socks);
  13181. mg_free(ctx->worker_threadids);
  13182. free_context(ctx);
  13183. pthread_setspecific(sTlsKey, NULL);
  13184. return NULL;
  13185. }
  13186. }
  13187. #endif
  13188. #if defined(USE_TIMERS)
  13189. if (timers_init(ctx) != 0) {
  13190. mg_cry(fc(ctx), "Error creating timers");
  13191. free_context(ctx);
  13192. pthread_setspecific(sTlsKey, NULL);
  13193. return NULL;
  13194. }
  13195. #endif
  13196. /* Context has been created - init user libraries */
  13197. if (ctx->callbacks.init_context) {
  13198. ctx->callbacks.init_context(ctx);
  13199. }
  13200. ctx->callbacks.exit_context = exit_callback;
  13201. ctx->context_type = 1; /* server context */
  13202. /* Start master (listening) thread */
  13203. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  13204. /* Start worker threads */
  13205. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  13206. struct worker_thread_args *wta = (struct worker_thread_args *)mg_malloc(
  13207. sizeof(struct worker_thread_args));
  13208. if (wta) {
  13209. wta->ctx = ctx;
  13210. wta->index = (int)i;
  13211. }
  13212. if ((wta == NULL)
  13213. || (mg_start_thread_with_id(worker_thread,
  13214. wta,
  13215. &ctx->worker_threadids[i]) != 0)) {
  13216. /* thread was not created */
  13217. if (wta != NULL) {
  13218. mg_free(wta);
  13219. }
  13220. if (i > 0) {
  13221. mg_cry(fc(ctx),
  13222. "Cannot start worker thread %i: error %ld",
  13223. i + 1,
  13224. (long)ERRNO);
  13225. } else {
  13226. mg_cry(fc(ctx),
  13227. "Cannot create threads: error %ld",
  13228. (long)ERRNO);
  13229. free_context(ctx);
  13230. pthread_setspecific(sTlsKey, NULL);
  13231. return NULL;
  13232. }
  13233. break;
  13234. }
  13235. }
  13236. pthread_setspecific(sTlsKey, NULL);
  13237. return ctx;
  13238. }
  13239. /* Feature check API function */
  13240. unsigned
  13241. mg_check_feature(unsigned feature)
  13242. {
  13243. static const unsigned feature_set = 0
  13244. /* Set bits for available features according to API documentation.
  13245. * This bit mask is created at compile time, according to the active
  13246. * preprocessor defines. It is a single const value at runtime. */
  13247. #if !defined(NO_FILES)
  13248. | 0x0001u
  13249. #endif
  13250. #if !defined(NO_SSL)
  13251. | 0x0002u
  13252. #endif
  13253. #if !defined(NO_CGI)
  13254. | 0x0004u
  13255. #endif
  13256. #if defined(USE_IPV6)
  13257. | 0x0008u
  13258. #endif
  13259. #if defined(USE_WEBSOCKET)
  13260. | 0x0010u
  13261. #endif
  13262. #if defined(USE_LUA)
  13263. | 0x0020u
  13264. #endif
  13265. #if defined(USE_DUKTAPE)
  13266. | 0x0040u
  13267. #endif
  13268. #if !defined(NO_CACHING)
  13269. | 0x0080u
  13270. #endif
  13271. /* Set some extra bits not defined in the API documentation.
  13272. * These bits may change without further notice. */
  13273. #if defined(MG_LEGACY_INTERFACE)
  13274. | 0x8000u
  13275. #endif
  13276. #if defined(MEMORY_DEBUGGING)
  13277. | 0x0100u
  13278. #endif
  13279. #if defined(USE_TIMERS)
  13280. | 0x0200u
  13281. #endif
  13282. #if !defined(NO_NONCE_CHECK)
  13283. | 0x0400u
  13284. #endif
  13285. #if !defined(NO_POPEN)
  13286. | 0x0800u
  13287. #endif
  13288. ;
  13289. return (feature & feature_set);
  13290. }
  13291. /* Get system information. It can be printed or stored by the caller.
  13292. * Return the size of available information. */
  13293. static int
  13294. mg_get_system_info_impl(char *buffer, int buflen)
  13295. {
  13296. char block[256];
  13297. int system_info_length = 0;
  13298. #if defined(_WIN32)
  13299. const char *eol = "\r\n";
  13300. #else
  13301. const char *eol = "\n";
  13302. #endif
  13303. if (buffer == NULL) {
  13304. /* Avoid some warning (although, if some dillweed supplies
  13305. * buffer==NULL combined with buflen>0, he deserves a crash).
  13306. */
  13307. buflen = 0;
  13308. }
  13309. /* Server version */
  13310. {
  13311. const char *version = mg_version();
  13312. mg_snprintf(NULL,
  13313. NULL,
  13314. block,
  13315. sizeof(block),
  13316. "Server Version: %s%s",
  13317. version,
  13318. eol);
  13319. system_info_length += (int)strlen(block);
  13320. if (system_info_length < buflen) {
  13321. strcat(buffer, block);
  13322. }
  13323. }
  13324. /* System info */
  13325. {
  13326. #if defined(_WIN32)
  13327. #if !defined(__SYMBIAN32__)
  13328. DWORD dwVersion = 0;
  13329. DWORD dwMajorVersion = 0;
  13330. DWORD dwMinorVersion = 0;
  13331. SYSTEM_INFO si;
  13332. GetSystemInfo(&si);
  13333. #ifdef _MSC_VER
  13334. #pragma warning(push)
  13335. /* GetVersion was declared deprecated */
  13336. #pragma warning(disable : 4996)
  13337. #endif
  13338. dwVersion = GetVersion();
  13339. #ifdef _MSC_VER
  13340. #pragma warning(pop)
  13341. #endif
  13342. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  13343. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  13344. mg_snprintf(NULL,
  13345. NULL,
  13346. block,
  13347. sizeof(block),
  13348. "Windows %u.%u%s",
  13349. (unsigned)dwMajorVersion,
  13350. (unsigned)dwMinorVersion,
  13351. eol);
  13352. system_info_length += (int)strlen(block);
  13353. if (system_info_length < buflen) {
  13354. strcat(buffer, block);
  13355. }
  13356. mg_snprintf(NULL,
  13357. NULL,
  13358. block,
  13359. sizeof(block),
  13360. "CPU: type %u, cores %u, mask %x%s",
  13361. (unsigned)si.wProcessorArchitecture,
  13362. (unsigned)si.dwNumberOfProcessors,
  13363. (unsigned)si.dwActiveProcessorMask,
  13364. eol);
  13365. system_info_length += (int)strlen(block);
  13366. if (system_info_length < buflen) {
  13367. strcat(buffer, block);
  13368. }
  13369. #else
  13370. mg_snprintf(NULL, NULL, block, sizeof(block), "%s - Symbian%s", eol);
  13371. system_info_length += (int)strlen(block);
  13372. if (system_info_length < buflen) {
  13373. strcat(buffer, block);
  13374. }
  13375. #endif
  13376. #else
  13377. struct utsname name;
  13378. memset(&name, 0, sizeof(name));
  13379. uname(&name);
  13380. mg_snprintf(NULL,
  13381. NULL,
  13382. block,
  13383. sizeof(block),
  13384. "%s %s (%s) - %s%s",
  13385. name.sysname,
  13386. name.version,
  13387. name.release,
  13388. name.machine,
  13389. eol);
  13390. system_info_length += (int)strlen(block);
  13391. if (system_info_length < buflen) {
  13392. strcat(buffer, block);
  13393. }
  13394. #endif
  13395. }
  13396. /* Features */
  13397. {
  13398. mg_snprintf(NULL,
  13399. NULL,
  13400. block,
  13401. sizeof(block),
  13402. "Features: %X%s%s%s%s%s%s%s%s%s%s",
  13403. mg_check_feature(0xFFFFFFFFu),
  13404. eol,
  13405. mg_check_feature(1) ? " Files" : "",
  13406. mg_check_feature(2) ? " HTTPS" : "",
  13407. mg_check_feature(4) ? " CGI" : "",
  13408. mg_check_feature(8) ? " IPv6" : "",
  13409. mg_check_feature(16) ? " WebSockets" : "",
  13410. mg_check_feature(32) ? " Lua" : "",
  13411. mg_check_feature(64) ? " JavaScript" : "",
  13412. mg_check_feature(128) ? " Cache" : "",
  13413. eol);
  13414. system_info_length += (int)strlen(block);
  13415. if (system_info_length < buflen) {
  13416. strcat(buffer, block);
  13417. }
  13418. #ifdef USE_LUA
  13419. mg_snprintf(NULL,
  13420. NULL,
  13421. block,
  13422. sizeof(block),
  13423. "Lua Version: %u (%s)%s",
  13424. (unsigned)LUA_VERSION_NUM,
  13425. LUA_RELEASE,
  13426. eol);
  13427. system_info_length += (int)strlen(block);
  13428. if (system_info_length < buflen) {
  13429. strcat(buffer, block);
  13430. }
  13431. #endif
  13432. #if defined(USE_DUKTAPE)
  13433. mg_snprintf(NULL,
  13434. NULL,
  13435. block,
  13436. sizeof(block),
  13437. "JavaScript: Duktape %u.%u.%u%s",
  13438. (unsigned)DUK_VERSION / 10000,
  13439. ((unsigned)DUK_VERSION / 100) % 100,
  13440. (unsigned)DUK_VERSION % 100,
  13441. eol);
  13442. system_info_length += (int)strlen(block);
  13443. if (system_info_length < buflen) {
  13444. strcat(buffer, block);
  13445. }
  13446. #endif
  13447. }
  13448. /* Build date */
  13449. {
  13450. mg_snprintf(
  13451. NULL, NULL, block, sizeof(block), "Build: %s%s", __DATE__, eol);
  13452. system_info_length += (int)strlen(block);
  13453. if (system_info_length < buflen) {
  13454. strcat(buffer, block);
  13455. }
  13456. }
  13457. /* Compiler information */
  13458. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  13459. {
  13460. #if defined(_MSC_VER)
  13461. mg_snprintf(NULL,
  13462. NULL,
  13463. block,
  13464. sizeof(block),
  13465. "MSC: %u (%u)%s",
  13466. (unsigned)_MSC_VER,
  13467. (unsigned)_MSC_FULL_VER,
  13468. eol);
  13469. system_info_length += (int)strlen(block);
  13470. if (system_info_length < buflen) {
  13471. strcat(buffer, block);
  13472. }
  13473. #elif defined(__MINGW64__)
  13474. mg_snprintf(NULL,
  13475. NULL,
  13476. block,
  13477. sizeof(block),
  13478. "MinGW64: %u.%u%s",
  13479. (unsigned)__MINGW64_VERSION_MAJOR,
  13480. (unsigned)__MINGW64_VERSION_MINOR,
  13481. eol);
  13482. system_info_length += (int)strlen(block);
  13483. if (system_info_length < buflen) {
  13484. strcat(buffer, block);
  13485. }
  13486. mg_snprintf(NULL,
  13487. NULL,
  13488. block,
  13489. sizeof(block),
  13490. "MinGW32: %u.%u%s",
  13491. (unsigned)__MINGW32_MAJOR_VERSION,
  13492. (unsigned)__MINGW32_MINOR_VERSION,
  13493. eol);
  13494. system_info_length += (int)strlen(block);
  13495. if (system_info_length < buflen) {
  13496. strcat(buffer, block);
  13497. }
  13498. #elif defined(__MINGW32__)
  13499. mg_snprintf(NULL,
  13500. NULL,
  13501. block,
  13502. sizeof(block),
  13503. "MinGW32: %u.%u%s",
  13504. (unsigned)__MINGW32_MAJOR_VERSION,
  13505. (unsigned)__MINGW32_MINOR_VERSION,
  13506. eol);
  13507. system_info_length += (int)strlen(block);
  13508. if (system_info_length < buflen) {
  13509. strcat(buffer, block);
  13510. }
  13511. #elif defined(__clang__)
  13512. mg_snprintf(NULL,
  13513. NULL,
  13514. block,
  13515. sizeof(block),
  13516. "clang: %u.%u.%u (%s)%s",
  13517. __clang_major__,
  13518. __clang_minor__,
  13519. __clang_patchlevel__,
  13520. __clang_version__,
  13521. eol);
  13522. system_info_length += (int)strlen(block);
  13523. if (system_info_length < buflen) {
  13524. strcat(buffer, block);
  13525. }
  13526. #elif defined(__GNUC__)
  13527. mg_snprintf(NULL,
  13528. NULL,
  13529. block,
  13530. sizeof(block),
  13531. "gcc: %u.%u.%u%s",
  13532. (unsigned)__GNUC__,
  13533. (unsigned)__GNUC_MINOR__,
  13534. (unsigned)__GNUC_PATCHLEVEL__,
  13535. eol);
  13536. system_info_length += (int)strlen(block);
  13537. if (system_info_length < buflen) {
  13538. strcat(buffer, block);
  13539. }
  13540. #elif defined(__INTEL_COMPILER)
  13541. mg_snprintf(NULL,
  13542. NULL,
  13543. block,
  13544. sizeof(block),
  13545. "Intel C/C++: %u%s",
  13546. (unsigned)__INTEL_COMPILER,
  13547. eol);
  13548. system_info_length += (int)strlen(block);
  13549. if (system_info_length < buflen) {
  13550. strcat(buffer, block);
  13551. }
  13552. #elif defined(__BORLANDC__)
  13553. mg_snprintf(NULL,
  13554. NULL,
  13555. block,
  13556. sizeof(block),
  13557. "Borland C: 0x%x%s",
  13558. (unsigned)__BORLANDC__,
  13559. eol);
  13560. system_info_length += (int)strlen(block);
  13561. if (system_info_length < buflen) {
  13562. strcat(buffer, block);
  13563. }
  13564. #elif defined(__SUNPRO_C)
  13565. mg_snprintf(NULL,
  13566. NULL,
  13567. block,
  13568. sizeof(block),
  13569. "Solaris: 0x%x%s",
  13570. (unsigned)__SUNPRO_C,
  13571. eol);
  13572. system_info_length += (int)strlen(block);
  13573. if (system_info_length < buflen) {
  13574. strcat(buffer, block);
  13575. }
  13576. #else
  13577. mg_snprintf(NULL, NULL, block, sizeof(block), "Other compiler%s", eol);
  13578. system_info_length += (int)strlen(block);
  13579. if (system_info_length < buflen) {
  13580. strcat(buffer, block);
  13581. }
  13582. #endif
  13583. }
  13584. /* Determine 32/64 bit data mode.
  13585. * see https://en.wikipedia.org/wiki/64-bit_computing */
  13586. {
  13587. mg_snprintf(NULL,
  13588. NULL,
  13589. block,
  13590. sizeof(block),
  13591. "Data model: int:%u/%u/%u/%u, float:%u/%u/%u, char:%u/%u, "
  13592. "ptr:%u, size:%u, time:%u%s",
  13593. (unsigned)sizeof(short),
  13594. (unsigned)sizeof(int),
  13595. (unsigned)sizeof(long),
  13596. (unsigned)sizeof(long long),
  13597. (unsigned)sizeof(float),
  13598. (unsigned)sizeof(double),
  13599. (unsigned)sizeof(long double),
  13600. (unsigned)sizeof(char),
  13601. (unsigned)sizeof(wchar_t),
  13602. (unsigned)sizeof(void *),
  13603. (unsigned)sizeof(size_t),
  13604. (unsigned)sizeof(time_t),
  13605. eol);
  13606. system_info_length += (int)strlen(block);
  13607. if (system_info_length < buflen) {
  13608. strcat(buffer, block);
  13609. }
  13610. }
  13611. return system_info_length;
  13612. }
  13613. /* Get system information. It can be printed or stored by the caller.
  13614. * Return the size of available information. */
  13615. int
  13616. mg_get_system_info(char *buffer, int buflen)
  13617. {
  13618. if ((buffer == NULL) || (buflen < 1)) {
  13619. return mg_get_system_info_impl(NULL, 0);
  13620. } else {
  13621. /* Reset buffer, so we can always use strcat. */
  13622. buffer[0] = 0;
  13623. return mg_get_system_info_impl(buffer, buflen);
  13624. }
  13625. }
  13626. /* mg_init_library counter */
  13627. static int mg_init_library_called = 0;
  13628. #if !defined(NO_SSL)
  13629. static int mg_ssl_initialized = 0;
  13630. #endif
  13631. /* Initialize this library. This function does not need to be thread safe. */
  13632. unsigned
  13633. mg_init_library(unsigned features)
  13634. {
  13635. #if !defined(NO_SSL)
  13636. char ebuf[128];
  13637. #endif
  13638. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  13639. unsigned features_inited = features_to_init;
  13640. #if !defined(NO_SSL)
  13641. if (features_to_init & 2) {
  13642. if (!mg_ssl_initialized) {
  13643. if (initialize_ssl(ebuf, sizeof(ebuf))) {
  13644. mg_ssl_initialized = 1;
  13645. } else {
  13646. (void)ebuf;
  13647. /* TODO: print error */
  13648. features_inited &= ~(2u);
  13649. }
  13650. } else {
  13651. /* ssl already initialized */
  13652. }
  13653. }
  13654. #endif
  13655. /* Start Windows. */
  13656. if (mg_init_library_called <= 0) {
  13657. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13658. WSADATA data;
  13659. WSAStartup(MAKEWORD(2, 2), &data);
  13660. #endif /* _WIN32 && !__SYMBIAN32__ */
  13661. mg_init_library_called = 1;
  13662. } else {
  13663. mg_init_library_called++;
  13664. }
  13665. return features_inited;
  13666. }
  13667. /* Un-initialize this library. */
  13668. unsigned
  13669. mg_exit_library(void)
  13670. {
  13671. if (mg_init_library_called <= 0) {
  13672. return 0;
  13673. }
  13674. mg_init_library_called--;
  13675. if (mg_init_library_called == 0) {
  13676. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13677. (void)WSACleanup();
  13678. #endif /* _WIN32 && !__SYMBIAN32__ */
  13679. #if !defined(NO_SSL)
  13680. if (mg_ssl_initialized) {
  13681. uninitialize_ssl();
  13682. mg_ssl_initialized = 0;
  13683. }
  13684. #endif
  13685. }
  13686. return 1;
  13687. }
  13688. /* End of civetweb.c */