civetweb.c 420 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935
  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(__GNUC__) || defined(__MINGW32__)
  704. /* Show no warning in case system functions are not used. */
  705. #pragma GCC diagnostic push
  706. #pragma GCC diagnostic ignored "-Wunused-function"
  707. #endif
  708. #if defined(__clang__)
  709. /* Show no warning in case system functions are not used. */
  710. #pragma clang diagnostic push
  711. #pragma clang diagnostic ignored "-Wunused-function"
  712. #endif
  713. static int
  714. mg_atomic_add(volatile int *addr, int value)
  715. {
  716. int ret;
  717. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  718. /* Depending on the SDK, this function uses either
  719. * (volatile unsigned int *) or (volatile LONG *),
  720. * so whatever you use, the other SDK is likely to raise a warning. */
  721. ret = InterlockedAdd((volatile long *)addr, (long)value);
  722. #elif defined(__GNUC__) \
  723. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  724. ret = __sync_add_and_fetch(addr, value);
  725. #else
  726. ret = (++(*addr));
  727. #endif
  728. return ret;
  729. }
  730. #if defined(__GNUC__)
  731. /* Show no warning in case system functions are not used. */
  732. #pragma GCC diagnostic pop
  733. #endif
  734. #if defined(__clang__)
  735. /* Show no warning in case system functions are not used. */
  736. #pragma clang diagnostic pop
  737. #endif
  738. #if defined(USE_SERVER_STATS)
  739. // static unsigned long mg_memory_debug_blockCount = 0;
  740. // static unsigned long mg_memory_debug_totalMemUsed = 0;
  741. volatile int mg_memory_debug_blockCount = 0;
  742. volatile int mg_memory_debug_totalMemUsed = 0;
  743. volatile int mg_memory_debug_maxMemUsed = 0;
  744. static void *
  745. mg_malloc_ex(size_t size,
  746. struct mg_context *ctx,
  747. const char *file,
  748. unsigned line)
  749. {
  750. void *data = malloc(size + sizeof(size_t));
  751. void *memory = 0;
  752. #if defined(MEMORY_DEBUGGING)
  753. char mallocStr[256];
  754. #endif
  755. (void)ctx;
  756. if (data) {
  757. int mmem = mg_atomic_add(&mg_memory_debug_totalMemUsed, size);
  758. if (mmem > mg_memory_debug_maxMemUsed) {
  759. /* could use atomic compare exchange, but this
  760. * seems overkill for statistics data */
  761. mg_memory_debug_maxMemUsed = mmem;
  762. }
  763. mg_atomic_inc(&mg_memory_debug_blockCount);
  764. *(size_t *)data = size;
  765. memory = (void *)(((char *)data) + sizeof(size_t));
  766. }
  767. #if defined(MEMORY_DEBUGGING)
  768. sprintf(mallocStr,
  769. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  770. memory,
  771. (unsigned long)size,
  772. mg_memory_debug_totalMemUsed,
  773. mg_memory_debug_blockCount,
  774. file,
  775. line);
  776. #if defined(_WIN32)
  777. OutputDebugStringA(mallocStr);
  778. #else
  779. DEBUG_TRACE("%s", mallocStr);
  780. #endif
  781. #endif
  782. return memory;
  783. }
  784. static void *
  785. mg_calloc_ex(size_t count,
  786. size_t size,
  787. struct mg_context *ctx,
  788. const char *file,
  789. unsigned line)
  790. {
  791. void *data = mg_malloc_ex(size * count, file, line);
  792. (void)ctx;
  793. if (data) {
  794. memset(data, 0, size * count);
  795. }
  796. return data;
  797. }
  798. static void
  799. mg_free_ex(void *memory,
  800. struct mg_context *ctx,
  801. const char *file,
  802. unsigned line)
  803. {
  804. #if defined(MEMORY_DEBUGGING)
  805. char mallocStr[256];
  806. #endif
  807. void *data = (void *)(((char *)memory) - sizeof(size_t));
  808. size_t size;
  809. (void)ctx;
  810. if (memory) {
  811. size = *(size_t *)data;
  812. mg_atomic_add(&mg_memory_debug_totalMemUsed, -size);
  813. mg_atomic_dec(&mg_memory_debug_blockCount);
  814. #if defined(MEMORY_DEBUGGING)
  815. sprintf(mallocStr,
  816. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  817. memory,
  818. (unsigned long)size,
  819. mg_memory_debug_totalMemUsed,
  820. mg_memory_debug_blockCount,
  821. file,
  822. line);
  823. #if defined(_WIN32)
  824. OutputDebugStringA(mallocStr);
  825. #else
  826. DEBUG_TRACE("%s", mallocStr);
  827. #endif
  828. #endif
  829. free(data);
  830. }
  831. }
  832. static void *
  833. mg_realloc_ex(void *memory,
  834. size_t newsize,
  835. struct mg_context *ctx,
  836. const char *file,
  837. unsigned line)
  838. {
  839. #if defined(MEMORY_DEBUGGING)
  840. char mallocStr[256];
  841. #endif
  842. void *data;
  843. void *_realloc;
  844. size_t oldsize;
  845. (void)ctx;
  846. if (newsize) {
  847. if (memory) {
  848. data = (void *)(((char *)memory) - sizeof(size_t));
  849. oldsize = *(size_t *)data;
  850. _realloc = realloc(data, newsize + sizeof(size_t));
  851. if (_realloc) {
  852. data = _realloc;
  853. mg_memory_debug_totalMemUsed -= oldsize;
  854. #if defined(MEMORY_DEBUGGING)
  855. sprintf(mallocStr,
  856. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  857. memory,
  858. (unsigned long)oldsize,
  859. mg_memory_debug_totalMemUsed,
  860. mg_memory_debug_blockCount,
  861. file,
  862. line);
  863. #if defined(_WIN32)
  864. OutputDebugStringA(mallocStr);
  865. #else
  866. DEBUG_TRACE("%s", mallocStr);
  867. #endif
  868. #endif
  869. mg_memory_debug_totalMemUsed += newsize;
  870. #if defined(MEMORY_DEBUGGING)
  871. sprintf(mallocStr,
  872. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  873. memory,
  874. (unsigned long)newsize,
  875. mg_memory_debug_totalMemUsed,
  876. mg_memory_debug_blockCount,
  877. file,
  878. line);
  879. #if defined(_WIN32)
  880. OutputDebugStringA(mallocStr);
  881. #else
  882. DEBUG_TRACE("%s", mallocStr);
  883. #endif
  884. #endif
  885. *(size_t *)data = newsize;
  886. data = (void *)(((char *)data) + sizeof(size_t));
  887. } else {
  888. #if defined(MEMORY_DEBUGGING)
  889. #if defined(_WIN32)
  890. OutputDebugStringA("MEM: realloc failed\n");
  891. #else
  892. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  893. #endif
  894. #endif
  895. return _realloc;
  896. }
  897. } else {
  898. data = mg_malloc_ex(newsize, file, line);
  899. }
  900. } else {
  901. data = 0;
  902. mg_free_ex(memory, file, line);
  903. }
  904. return data;
  905. }
  906. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  907. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  908. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  909. #define mg_free(a) mg_free_ex(a, NULL, __FILE__, __LINE__)
  910. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  911. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  912. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  913. #define mg_free_ctx(a, c) mg_free_ex(a, c, __FILE__, __LINE__)
  914. #else /* USE_SERVER_STATS */
  915. static __inline void *
  916. mg_malloc(size_t a)
  917. {
  918. return malloc(a);
  919. }
  920. static __inline void *
  921. mg_calloc(size_t a, size_t b)
  922. {
  923. return calloc(a, b);
  924. }
  925. static __inline void *
  926. mg_realloc(void *a, size_t b)
  927. {
  928. return realloc(a, b);
  929. }
  930. static __inline void
  931. mg_free(void *a)
  932. {
  933. free(a);
  934. }
  935. #define mg_malloc_ctx(a, c) mg_malloc(a)
  936. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  937. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  938. #define mg_free_ctx(a, c) mg_free(a)
  939. #endif /* USE_SERVER_STATS */
  940. static void mg_vsnprintf(const struct mg_connection *conn,
  941. int *truncated,
  942. char *buf,
  943. size_t buflen,
  944. const char *fmt,
  945. va_list ap);
  946. static void mg_snprintf(const struct mg_connection *conn,
  947. int *truncated,
  948. char *buf,
  949. size_t buflen,
  950. PRINTF_FORMAT_STRING(const char *fmt),
  951. ...) PRINTF_ARGS(5, 6);
  952. /* This following lines are just meant as a reminder to use the mg-functions
  953. * for memory management */
  954. #ifdef malloc
  955. #undef malloc
  956. #endif
  957. #ifdef calloc
  958. #undef calloc
  959. #endif
  960. #ifdef realloc
  961. #undef realloc
  962. #endif
  963. #ifdef free
  964. #undef free
  965. #endif
  966. #ifdef snprintf
  967. #undef snprintf
  968. #endif
  969. #ifdef vsnprintf
  970. #undef vsnprintf
  971. #endif
  972. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  973. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  974. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  975. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  976. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  977. #ifdef _WIN32 /* vsnprintf must not be used in any system, * \ \ \ \
  978. * but this define only works well for Windows. */
  979. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  980. #endif
  981. static pthread_key_t sTlsKey; /* Thread local storage index */
  982. static int sTlsInit = 0;
  983. static int thread_idx_max = 0;
  984. struct mg_workerTLS {
  985. int is_master;
  986. unsigned long thread_idx;
  987. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  988. HANDLE pthread_cond_helper_mutex;
  989. struct mg_workerTLS *next_waiting_thread;
  990. #endif
  991. };
  992. #if defined(__GNUC__) || defined(__MINGW32__)
  993. /* Show no warning in case system functions are not used. */
  994. #pragma GCC diagnostic push
  995. #pragma GCC diagnostic ignored "-Wunused-function"
  996. #endif
  997. #if defined(__clang__)
  998. /* Show no warning in case system functions are not used. */
  999. #pragma clang diagnostic push
  1000. #pragma clang diagnostic ignored "-Wunused-function"
  1001. #endif
  1002. /* Get a unique thread ID as unsigned long, independent from the data type
  1003. * of thread IDs defined by the operating system API.
  1004. * If two calls to mg_current_thread_id return the same value, they calls
  1005. * are done from the same thread. If they return different values, they are
  1006. * done from different threads. (Provided this function is used in the same
  1007. * process context and threads are not repeatedly created and deleted, but
  1008. * CivetWeb does not do that).
  1009. * This function must match the signature required for SSL id callbacks:
  1010. * CRYPTO_set_id_callback
  1011. */
  1012. static unsigned long
  1013. mg_current_thread_id(void)
  1014. {
  1015. #ifdef _WIN32
  1016. return GetCurrentThreadId();
  1017. #else
  1018. #ifdef __clang__
  1019. #pragma clang diagnostic push
  1020. #pragma clang diagnostic ignored "-Wunreachable-code"
  1021. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  1022. * or not, so one of the two conditions will be unreachable by construction.
  1023. * Unfortunately the C standard does not define a way to check this at
  1024. * compile time, since the #if preprocessor conditions can not use the sizeof
  1025. * operator as an argument. */
  1026. #endif
  1027. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  1028. /* This is the problematic case for CRYPTO_set_id_callback:
  1029. * The OS pthread_t can not be cast to unsigned long. */
  1030. struct mg_workerTLS *tls =
  1031. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  1032. if (tls == NULL) {
  1033. /* SSL called from an unknown thread: Create some thread index.
  1034. */
  1035. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  1036. tls->is_master = -2; /* -2 means "3rd party thread" */
  1037. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  1038. pthread_setspecific(sTlsKey, tls);
  1039. }
  1040. return tls->thread_idx;
  1041. } else {
  1042. /* pthread_t may be any data type, so a simple cast to unsigned long
  1043. * can rise a warning/error, depending on the platform.
  1044. * Here memcpy is used as an anything-to-anything cast. */
  1045. unsigned long ret = 0;
  1046. pthread_t t = pthread_self();
  1047. memcpy(&ret, &t, sizeof(pthread_t));
  1048. return ret;
  1049. }
  1050. #ifdef __clang__
  1051. #pragma clang diagnostic pop
  1052. #endif
  1053. #endif
  1054. }
  1055. static uint64_t
  1056. mg_get_current_time_ns()
  1057. {
  1058. struct timespec tsnow;
  1059. clock_gettime(CLOCK_REALTIME, &tsnow);
  1060. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  1061. }
  1062. #if defined(__GNUC__)
  1063. /* Show no warning in case system functions are not used. */
  1064. #pragma GCC diagnostic pop
  1065. #endif
  1066. #if defined(__clang__)
  1067. /* Show no warning in case system functions are not used. */
  1068. #pragma clang diagnostic pop
  1069. #endif
  1070. #if !defined(DEBUG_TRACE)
  1071. #if defined(DEBUG)
  1072. static void DEBUG_TRACE_FUNC(const char *func,
  1073. unsigned line,
  1074. PRINTF_FORMAT_STRING(const char *fmt),
  1075. ...) PRINTF_ARGS(3, 4);
  1076. static void
  1077. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  1078. {
  1079. va_list args;
  1080. uint64_t nsnow;
  1081. static uint64_t nslast;
  1082. struct timespec tsnow;
  1083. /* Get some operating system independent thread id */
  1084. unsigned long thread_id = mg_current_thread_id();
  1085. clock_gettime(CLOCK_REALTIME, &tsnow);
  1086. nsnow = ((uint64_t)tsnow.tv_sec) * ((uint64_t)1000000000)
  1087. + ((uint64_t)tsnow.tv_nsec);
  1088. if (!nslast) {
  1089. nslast = nsnow;
  1090. }
  1091. flockfile(stdout);
  1092. printf("*** %lu.%09lu %12" INT64_FMT " %lu %s:%u: ",
  1093. (unsigned long)tsnow.tv_sec,
  1094. (unsigned long)tsnow.tv_nsec,
  1095. nsnow - nslast,
  1096. thread_id,
  1097. func,
  1098. line);
  1099. va_start(args, fmt);
  1100. vprintf(fmt, args);
  1101. va_end(args);
  1102. putchar('\n');
  1103. fflush(stdout);
  1104. funlockfile(stdout);
  1105. nslast = nsnow;
  1106. }
  1107. #define DEBUG_TRACE(fmt, ...) \
  1108. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  1109. #else
  1110. #define DEBUG_TRACE(fmt, ...) \
  1111. do { \
  1112. } while (0)
  1113. #endif /* DEBUG */
  1114. #endif /* DEBUG_TRACE */
  1115. #define MD5_STATIC static
  1116. #include "md5.inl"
  1117. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1118. #ifdef NO_SOCKLEN_T
  1119. typedef int socklen_t;
  1120. #endif /* NO_SOCKLEN_T */
  1121. #define _DARWIN_UNLIMITED_SELECT
  1122. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1123. #if !defined(MSG_NOSIGNAL)
  1124. #define MSG_NOSIGNAL (0)
  1125. #endif
  1126. #if !defined(SOMAXCONN)
  1127. #define SOMAXCONN (100)
  1128. #endif
  1129. /* Size of the accepted socket queue */
  1130. #if !defined(MGSQLEN)
  1131. #define MGSQLEN (20)
  1132. #endif
  1133. #if defined(NO_SSL)
  1134. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1135. typedef struct SSL_CTX SSL_CTX;
  1136. #else
  1137. #if defined(NO_SSL_DL)
  1138. #include <openssl/ssl.h>
  1139. #include <openssl/err.h>
  1140. #include <openssl/crypto.h>
  1141. #include <openssl/x509.h>
  1142. #include <openssl/pem.h>
  1143. #include <openssl/engine.h>
  1144. #include <openssl/conf.h>
  1145. #include <openssl/dh.h>
  1146. #include <openssl/bn.h>
  1147. #include <openssl/opensslv.h>
  1148. #else
  1149. /* SSL loaded dynamically from DLL.
  1150. * I put the prototypes here to be independent from OpenSSL source
  1151. * installation. */
  1152. typedef struct ssl_st SSL;
  1153. typedef struct ssl_method_st SSL_METHOD;
  1154. typedef struct ssl_ctx_st SSL_CTX;
  1155. typedef struct x509_store_ctx_st X509_STORE_CTX;
  1156. typedef struct x509_name X509_NAME;
  1157. typedef struct asn1_integer ASN1_INTEGER;
  1158. typedef struct bignum BIGNUM;
  1159. typedef struct ossl_init_settings_st OPENSSL_INIT_SETTINGS;
  1160. typedef struct evp_md EVP_MD;
  1161. typedef struct x509 X509;
  1162. #define SSL_CTRL_OPTIONS (32)
  1163. #define SSL_CTRL_CLEAR_OPTIONS (77)
  1164. #define SSL_CTRL_SET_ECDH_AUTO (94)
  1165. #define OPENSSL_INIT_NO_LOAD_SSL_STRINGS 0x00100000L
  1166. #define OPENSSL_INIT_LOAD_SSL_STRINGS 0x00200000L
  1167. #define OPENSSL_INIT_LOAD_CRYPTO_STRINGS 0x00000002L
  1168. #define SSL_VERIFY_NONE (0)
  1169. #define SSL_VERIFY_PEER (1)
  1170. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  1171. #define SSL_VERIFY_CLIENT_ONCE (4)
  1172. #define SSL_OP_ALL ((long)(0x80000BFFUL))
  1173. #define SSL_OP_NO_SSLv2 (0x01000000L)
  1174. #define SSL_OP_NO_SSLv3 (0x02000000L)
  1175. #define SSL_OP_NO_TLSv1 (0x04000000L)
  1176. #define SSL_OP_NO_TLSv1_2 (0x08000000L)
  1177. #define SSL_OP_NO_TLSv1_1 (0x10000000L)
  1178. #define SSL_OP_SINGLE_DH_USE (0x00100000L)
  1179. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000L)
  1180. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000L)
  1181. #define SSL_ERROR_NONE (0)
  1182. #define SSL_ERROR_SSL (1)
  1183. #define SSL_ERROR_WANT_READ (2)
  1184. #define SSL_ERROR_WANT_WRITE (3)
  1185. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  1186. #define SSL_ERROR_SYSCALL (5) /* see errno */
  1187. #define SSL_ERROR_ZERO_RETURN (6)
  1188. #define SSL_ERROR_WANT_CONNECT (7)
  1189. #define SSL_ERROR_WANT_ACCEPT (8)
  1190. struct ssl_func {
  1191. const char *name; /* SSL function name */
  1192. void (*ptr)(void); /* Function pointer */
  1193. };
  1194. #ifdef OPENSSL_API_1_1
  1195. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1196. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1197. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1198. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1199. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1200. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1201. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1202. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  1203. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  1204. #define TLS_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  1205. #define OPENSSL_init_ssl \
  1206. (*(int (*)(uint64_t opts, \
  1207. const OPENSSL_INIT_SETTINGS *settings))ssl_sw[10].ptr)
  1208. #define SSL_CTX_use_PrivateKey_file \
  1209. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1210. #define SSL_CTX_use_certificate_file \
  1211. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1212. #define SSL_CTX_set_default_passwd_cb \
  1213. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1214. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1215. #define SSL_CTX_use_certificate_chain_file \
  1216. (*(int (*)(SSL_CTX *, const char *))ssl_sw[15].ptr)
  1217. #define TLS_client_method (*(SSL_METHOD * (*)(void))ssl_sw[16].ptr)
  1218. #define SSL_pending (*(int (*)(SSL *))ssl_sw[17].ptr)
  1219. #define SSL_CTX_set_verify \
  1220. (*(void (*)(SSL_CTX *, \
  1221. int, \
  1222. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[18].ptr)
  1223. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[19].ptr)
  1224. #define SSL_CTX_load_verify_locations \
  1225. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[20].ptr)
  1226. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[21].ptr)
  1227. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[22].ptr)
  1228. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[23].ptr)
  1229. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[24].ptr)
  1230. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[25].ptr)
  1231. #define SSL_CIPHER_get_name \
  1232. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[26].ptr)
  1233. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[27].ptr)
  1234. #define SSL_CTX_set_session_id_context \
  1235. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[28].ptr)
  1236. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[29].ptr)
  1237. #define SSL_CTX_set_cipher_list \
  1238. (*(int (*)(SSL_CTX *, const char *))ssl_sw[30].ptr)
  1239. #define SSL_CTX_set_options \
  1240. (*(unsigned long (*)(SSL_CTX *, unsigned long))ssl_sw[31].ptr)
  1241. #define SSL_CTX_clear_options(ctx, op) \
  1242. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1243. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1244. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1245. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1246. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1247. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[0].ptr)
  1248. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[1].ptr)
  1249. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[2].ptr)
  1250. #define CONF_modules_unload (*(void (*)(int))crypto_sw[3].ptr)
  1251. #define X509_free (*(void (*)(X509 *))crypto_sw[4].ptr)
  1252. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[5].ptr)
  1253. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[6].ptr)
  1254. #define X509_NAME_oneline \
  1255. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[7].ptr)
  1256. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[8].ptr)
  1257. #define EVP_get_digestbyname \
  1258. (*(const EVP_MD *(*)(const char *))crypto_sw[9].ptr)
  1259. #define EVP_Digest \
  1260. (*(int (*)( \
  1261. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1262. crypto_sw[10].ptr)
  1263. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[11].ptr)
  1264. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[12].ptr)
  1265. #define ASN1_INTEGER_to_BN \
  1266. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn))crypto_sw[13].ptr)
  1267. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[14].ptr)
  1268. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[15].ptr)
  1269. #define OPENSSL_free(a) CRYPTO_free(a)
  1270. /* set_ssl_option() function updates this array.
  1271. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1272. * of respective functions. The macros above (like SSL_connect()) are really
  1273. * just calling these functions indirectly via the pointer. */
  1274. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1275. {"SSL_accept", NULL},
  1276. {"SSL_connect", NULL},
  1277. {"SSL_read", NULL},
  1278. {"SSL_write", NULL},
  1279. {"SSL_get_error", NULL},
  1280. {"SSL_set_fd", NULL},
  1281. {"SSL_new", NULL},
  1282. {"SSL_CTX_new", NULL},
  1283. {"TLS_server_method", NULL},
  1284. {"OPENSSL_init_ssl", NULL},
  1285. {"SSL_CTX_use_PrivateKey_file", NULL},
  1286. {"SSL_CTX_use_certificate_file", NULL},
  1287. {"SSL_CTX_set_default_passwd_cb", NULL},
  1288. {"SSL_CTX_free", NULL},
  1289. {"SSL_CTX_use_certificate_chain_file", NULL},
  1290. {"TLS_client_method", NULL},
  1291. {"SSL_pending", NULL},
  1292. {"SSL_CTX_set_verify", NULL},
  1293. {"SSL_shutdown", NULL},
  1294. {"SSL_CTX_load_verify_locations", NULL},
  1295. {"SSL_CTX_set_default_verify_paths", NULL},
  1296. {"SSL_CTX_set_verify_depth", NULL},
  1297. {"SSL_get_peer_certificate", NULL},
  1298. {"SSL_get_version", NULL},
  1299. {"SSL_get_current_cipher", NULL},
  1300. {"SSL_CIPHER_get_name", NULL},
  1301. {"SSL_CTX_check_private_key", NULL},
  1302. {"SSL_CTX_set_session_id_context", NULL},
  1303. {"SSL_CTX_ctrl", NULL},
  1304. {"SSL_CTX_set_cipher_list", NULL},
  1305. {"SSL_CTX_set_options", NULL},
  1306. {NULL, NULL}};
  1307. /* Similar array as ssl_sw. These functions could be located in different
  1308. * lib. */
  1309. static struct ssl_func crypto_sw[] = {{"ERR_get_error", NULL},
  1310. {"ERR_error_string", NULL},
  1311. {"ERR_remove_state", NULL},
  1312. {"CONF_modules_unload", NULL},
  1313. {"X509_free", NULL},
  1314. {"X509_get_subject_name", NULL},
  1315. {"X509_get_issuer_name", NULL},
  1316. {"X509_NAME_oneline", NULL},
  1317. {"X509_get_serialNumber", NULL},
  1318. {"EVP_get_digestbyname", NULL},
  1319. {"EVP_Digest", NULL},
  1320. {"i2d_X509", NULL},
  1321. {"BN_bn2hex", NULL},
  1322. {"ASN1_INTEGER_to_BN", NULL},
  1323. {"BN_free", NULL},
  1324. {"CRYPTO_free", NULL},
  1325. {NULL, NULL}};
  1326. #else
  1327. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1328. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1329. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1330. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1331. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1332. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1333. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1334. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  1335. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  1336. #define SSLv23_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  1337. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  1338. #define SSL_CTX_use_PrivateKey_file \
  1339. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1340. #define SSL_CTX_use_certificate_file \
  1341. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1342. #define SSL_CTX_set_default_passwd_cb \
  1343. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1344. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1345. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  1346. #define SSL_CTX_use_certificate_chain_file \
  1347. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  1348. #define SSLv23_client_method (*(SSL_METHOD * (*)(void))ssl_sw[17].ptr)
  1349. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  1350. #define SSL_CTX_set_verify \
  1351. (*(void (*)(SSL_CTX *, \
  1352. int, \
  1353. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19].ptr)
  1354. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  1355. #define SSL_CTX_load_verify_locations \
  1356. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  1357. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  1358. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  1359. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[24].ptr)
  1360. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  1361. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[26].ptr)
  1362. #define SSL_CIPHER_get_name \
  1363. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  1364. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  1365. #define SSL_CTX_set_session_id_context \
  1366. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  1367. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  1368. #define SSL_CTX_set_cipher_list \
  1369. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  1370. #define SSL_CTX_set_options(ctx, op) \
  1371. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  1372. #define SSL_CTX_clear_options(ctx, op) \
  1373. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1374. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1375. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1376. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1377. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1378. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  1379. #define CRYPTO_set_locking_callback \
  1380. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  1381. #define CRYPTO_set_id_callback \
  1382. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  1383. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  1384. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  1385. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  1386. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  1387. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  1388. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  1389. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  1390. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  1391. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  1392. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[12].ptr)
  1393. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[13].ptr)
  1394. #define X509_NAME_oneline \
  1395. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  1396. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[15].ptr)
  1397. #define i2c_ASN1_INTEGER \
  1398. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  1399. #define EVP_get_digestbyname \
  1400. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1401. #define EVP_Digest \
  1402. (*(int (*)( \
  1403. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1404. crypto_sw[18].ptr)
  1405. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1406. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[20].ptr)
  1407. #define ASN1_INTEGER_to_BN \
  1408. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn))crypto_sw[21].ptr)
  1409. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[22].ptr)
  1410. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[23].ptr)
  1411. #define OPENSSL_free(a) CRYPTO_free(a)
  1412. /* set_ssl_option() function updates this array.
  1413. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1414. * of respective functions. The macros above (like SSL_connect()) are really
  1415. * just calling these functions indirectly via the pointer. */
  1416. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1417. {"SSL_accept", NULL},
  1418. {"SSL_connect", NULL},
  1419. {"SSL_read", NULL},
  1420. {"SSL_write", NULL},
  1421. {"SSL_get_error", NULL},
  1422. {"SSL_set_fd", NULL},
  1423. {"SSL_new", NULL},
  1424. {"SSL_CTX_new", NULL},
  1425. {"SSLv23_server_method", NULL},
  1426. {"SSL_library_init", NULL},
  1427. {"SSL_CTX_use_PrivateKey_file", NULL},
  1428. {"SSL_CTX_use_certificate_file", NULL},
  1429. {"SSL_CTX_set_default_passwd_cb", NULL},
  1430. {"SSL_CTX_free", NULL},
  1431. {"SSL_load_error_strings", NULL},
  1432. {"SSL_CTX_use_certificate_chain_file", NULL},
  1433. {"SSLv23_client_method", NULL},
  1434. {"SSL_pending", NULL},
  1435. {"SSL_CTX_set_verify", NULL},
  1436. {"SSL_shutdown", NULL},
  1437. {"SSL_CTX_load_verify_locations", NULL},
  1438. {"SSL_CTX_set_default_verify_paths", NULL},
  1439. {"SSL_CTX_set_verify_depth", NULL},
  1440. {"SSL_get_peer_certificate", NULL},
  1441. {"SSL_get_version", NULL},
  1442. {"SSL_get_current_cipher", NULL},
  1443. {"SSL_CIPHER_get_name", NULL},
  1444. {"SSL_CTX_check_private_key", NULL},
  1445. {"SSL_CTX_set_session_id_context", NULL},
  1446. {"SSL_CTX_ctrl", NULL},
  1447. {"SSL_CTX_set_cipher_list", NULL},
  1448. {NULL, NULL}};
  1449. /* Similar array as ssl_sw. These functions could be located in different
  1450. * lib. */
  1451. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  1452. {"CRYPTO_set_locking_callback", NULL},
  1453. {"CRYPTO_set_id_callback", NULL},
  1454. {"ERR_get_error", NULL},
  1455. {"ERR_error_string", NULL},
  1456. {"ERR_remove_state", NULL},
  1457. {"ERR_free_strings", NULL},
  1458. {"ENGINE_cleanup", NULL},
  1459. {"CONF_modules_unload", NULL},
  1460. {"CRYPTO_cleanup_all_ex_data", NULL},
  1461. {"EVP_cleanup", NULL},
  1462. {"X509_free", NULL},
  1463. {"X509_get_subject_name", NULL},
  1464. {"X509_get_issuer_name", NULL},
  1465. {"X509_NAME_oneline", NULL},
  1466. {"X509_get_serialNumber", NULL},
  1467. {"i2c_ASN1_INTEGER", NULL},
  1468. {"EVP_get_digestbyname", NULL},
  1469. {"EVP_Digest", NULL},
  1470. {"i2d_X509", NULL},
  1471. {"BN_bn2hex", NULL},
  1472. {"ASN1_INTEGER_to_BN", NULL},
  1473. {"BN_free", NULL},
  1474. {"CRYPTO_free", NULL},
  1475. {NULL, NULL}};
  1476. #endif /* OPENSSL_API_1_1 */
  1477. #endif /* NO_SSL_DL */
  1478. #endif /* NO_SSL */
  1479. #if !defined(NO_CACHING)
  1480. static const char *month_names[] = {"Jan",
  1481. "Feb",
  1482. "Mar",
  1483. "Apr",
  1484. "May",
  1485. "Jun",
  1486. "Jul",
  1487. "Aug",
  1488. "Sep",
  1489. "Oct",
  1490. "Nov",
  1491. "Dec"};
  1492. #endif /* !NO_CACHING */
  1493. /* Unified socket address. For IPv6 support, add IPv6 address structure in the
  1494. * union u. */
  1495. union usa {
  1496. struct sockaddr sa;
  1497. struct sockaddr_in sin;
  1498. #if defined(USE_IPV6)
  1499. struct sockaddr_in6 sin6;
  1500. #endif
  1501. };
  1502. /* Describes a string (chunk of memory). */
  1503. struct vec {
  1504. const char *ptr;
  1505. size_t len;
  1506. };
  1507. struct mg_file_stat {
  1508. /* File properties filled by mg_stat: */
  1509. uint64_t size;
  1510. time_t last_modified;
  1511. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1512. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1513. * case we need a "Content-Eencoding: gzip" header */
  1514. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1515. };
  1516. struct mg_file_in_memory {
  1517. char *p;
  1518. uint32_t pos;
  1519. char mode;
  1520. };
  1521. struct mg_file_access {
  1522. /* File properties filled by mg_fopen: */
  1523. FILE *fp;
  1524. /* TODO (low): Replace "membuf" implementation by a "file in memory"
  1525. * support library. Use some struct mg_file_in_memory *mf; instead of
  1526. * membuf char pointer. */
  1527. const char *membuf;
  1528. };
  1529. struct mg_file {
  1530. struct mg_file_stat stat;
  1531. struct mg_file_access access;
  1532. };
  1533. #define STRUCT_FILE_INITIALIZER \
  1534. { \
  1535. { \
  1536. (uint64_t)0, (time_t)0, 0, 0, 0 \
  1537. } \
  1538. , \
  1539. { \
  1540. (FILE *) NULL, (const char *)NULL \
  1541. } \
  1542. }
  1543. /* Describes listening socket, or socket which was accept()-ed by the master
  1544. * thread and queued for future handling by the worker thread. */
  1545. struct socket {
  1546. SOCKET sock; /* Listening socket */
  1547. union usa lsa; /* Local socket address */
  1548. union usa rsa; /* Remote socket address */
  1549. unsigned char is_ssl; /* Is port SSL-ed */
  1550. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1551. * port */
  1552. unsigned char in_use; /* Is valid */
  1553. };
  1554. /* NOTE(lsm): this enum shoulds be in sync with the config_options below. */
  1555. enum {
  1556. CGI_EXTENSIONS,
  1557. CGI_ENVIRONMENT,
  1558. PUT_DELETE_PASSWORDS_FILE,
  1559. CGI_INTERPRETER,
  1560. PROTECT_URI,
  1561. AUTHENTICATION_DOMAIN,
  1562. ENABLE_AUTH_DOMAIN_CHECK,
  1563. SSI_EXTENSIONS,
  1564. THROTTLE,
  1565. ACCESS_LOG_FILE,
  1566. ENABLE_DIRECTORY_LISTING,
  1567. ERROR_LOG_FILE,
  1568. GLOBAL_PASSWORDS_FILE,
  1569. INDEX_FILES,
  1570. ENABLE_KEEP_ALIVE,
  1571. ACCESS_CONTROL_LIST,
  1572. EXTRA_MIME_TYPES,
  1573. LISTENING_PORTS,
  1574. DOCUMENT_ROOT,
  1575. SSL_CERTIFICATE,
  1576. SSL_CERTIFICATE_CHAIN,
  1577. NUM_THREADS,
  1578. RUN_AS_USER,
  1579. REWRITE,
  1580. HIDE_FILES,
  1581. REQUEST_TIMEOUT,
  1582. KEEP_ALIVE_TIMEOUT,
  1583. LINGER_TIMEOUT,
  1584. SSL_DO_VERIFY_PEER,
  1585. SSL_CA_PATH,
  1586. SSL_CA_FILE,
  1587. SSL_VERIFY_DEPTH,
  1588. SSL_DEFAULT_VERIFY_PATHS,
  1589. SSL_CIPHER_LIST,
  1590. SSL_PROTOCOL_VERSION,
  1591. SSL_SHORT_TRUST,
  1592. #if defined(USE_WEBSOCKET)
  1593. WEBSOCKET_TIMEOUT,
  1594. #endif
  1595. DECODE_URL,
  1596. #if defined(USE_LUA)
  1597. LUA_PRELOAD_FILE,
  1598. LUA_SCRIPT_EXTENSIONS,
  1599. LUA_SERVER_PAGE_EXTENSIONS,
  1600. #endif
  1601. #if defined(USE_DUKTAPE)
  1602. DUKTAPE_SCRIPT_EXTENSIONS,
  1603. #endif
  1604. #if defined(USE_WEBSOCKET)
  1605. WEBSOCKET_ROOT,
  1606. #endif
  1607. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1608. LUA_WEBSOCKET_EXTENSIONS,
  1609. #endif
  1610. ACCESS_CONTROL_ALLOW_ORIGIN,
  1611. ERROR_PAGES,
  1612. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1613. * socket option typedef TCP_NODELAY. */
  1614. #if !defined(NO_CACHING)
  1615. STATIC_FILE_MAX_AGE,
  1616. #endif
  1617. #if defined(__linux__)
  1618. ALLOW_SENDFILE_CALL,
  1619. #endif
  1620. #if defined(_WIN32)
  1621. CASE_SENSITIVE_FILES,
  1622. #endif
  1623. #if defined(USE_LUA)
  1624. LUA_BACKGROUND_SCRIPT,
  1625. #endif
  1626. NUM_OPTIONS
  1627. };
  1628. /* Config option name, config types, default value */
  1629. static struct mg_option config_options[] = {
  1630. {"cgi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1631. {"cgi_environment", CONFIG_TYPE_STRING, NULL},
  1632. {"put_delete_auth_file", CONFIG_TYPE_FILE, NULL},
  1633. {"cgi_interpreter", CONFIG_TYPE_FILE, NULL},
  1634. {"protect_uri", CONFIG_TYPE_STRING, NULL},
  1635. {"authentication_domain", CONFIG_TYPE_STRING, "mydomain.com"},
  1636. {"enable_auth_domain_check", CONFIG_TYPE_BOOLEAN, "yes"},
  1637. {"ssi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1638. {"throttle", CONFIG_TYPE_STRING, NULL},
  1639. {"access_log_file", CONFIG_TYPE_FILE, NULL},
  1640. {"enable_directory_listing", CONFIG_TYPE_BOOLEAN, "yes"},
  1641. {"error_log_file", CONFIG_TYPE_FILE, NULL},
  1642. {"global_auth_file", CONFIG_TYPE_FILE, NULL},
  1643. {"index_files",
  1644. CONFIG_TYPE_STRING,
  1645. #ifdef USE_LUA
  1646. "index.xhtml,index.html,index.htm,index.lp,index.lsp,index.lua,index.cgi,"
  1647. "index.shtml,index.php"},
  1648. #else
  1649. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1650. #endif
  1651. {"enable_keep_alive", CONFIG_TYPE_BOOLEAN, "no"},
  1652. {"access_control_list", CONFIG_TYPE_STRING, NULL},
  1653. {"extra_mime_types", CONFIG_TYPE_STRING, NULL},
  1654. {"listening_ports", CONFIG_TYPE_STRING, "8080"},
  1655. {"document_root", CONFIG_TYPE_DIRECTORY, NULL},
  1656. {"ssl_certificate", CONFIG_TYPE_FILE, NULL},
  1657. {"ssl_certificate_chain", CONFIG_TYPE_FILE, NULL},
  1658. {"num_threads", CONFIG_TYPE_NUMBER, "50"},
  1659. {"run_as_user", CONFIG_TYPE_STRING, NULL},
  1660. {"url_rewrite_patterns", CONFIG_TYPE_STRING, NULL},
  1661. {"hide_files_patterns", CONFIG_TYPE_EXT_PATTERN, NULL},
  1662. {"request_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1663. {"keep_alive_timeout_ms", CONFIG_TYPE_NUMBER, "500"},
  1664. {"linger_timeout_ms", CONFIG_TYPE_NUMBER, NULL},
  1665. /* TODO(Feature): this is no longer a boolean, but yes/no/optional */
  1666. {"ssl_verify_peer", CONFIG_TYPE_BOOLEAN, "no"},
  1667. {"ssl_ca_path", CONFIG_TYPE_DIRECTORY, NULL},
  1668. {"ssl_ca_file", CONFIG_TYPE_FILE, NULL},
  1669. {"ssl_verify_depth", CONFIG_TYPE_NUMBER, "9"},
  1670. {"ssl_default_verify_paths", CONFIG_TYPE_BOOLEAN, "yes"},
  1671. {"ssl_cipher_list", CONFIG_TYPE_STRING, NULL},
  1672. {"ssl_protocol_version", CONFIG_TYPE_NUMBER, "0"},
  1673. {"ssl_short_trust", CONFIG_TYPE_BOOLEAN, "no"},
  1674. #if defined(USE_WEBSOCKET)
  1675. {"websocket_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1676. #endif
  1677. {"decode_url", CONFIG_TYPE_BOOLEAN, "yes"},
  1678. #if defined(USE_LUA)
  1679. {"lua_preload_file", CONFIG_TYPE_FILE, NULL},
  1680. {"lua_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1681. {"lua_server_page_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1682. #endif
  1683. #if defined(USE_DUKTAPE)
  1684. /* The support for duktape is still in alpha version state.
  1685. * The name of this config option might change. */
  1686. {"duktape_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1687. #endif
  1688. #if defined(USE_WEBSOCKET)
  1689. {"websocket_root", CONFIG_TYPE_DIRECTORY, NULL},
  1690. #endif
  1691. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1692. {"lua_websocket_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1693. #endif
  1694. {"access_control_allow_origin", CONFIG_TYPE_STRING, "*"},
  1695. {"error_pages", CONFIG_TYPE_DIRECTORY, NULL},
  1696. {"tcp_nodelay", CONFIG_TYPE_NUMBER, "0"},
  1697. #if !defined(NO_CACHING)
  1698. {"static_file_max_age", CONFIG_TYPE_NUMBER, "3600"},
  1699. #endif
  1700. #if defined(__linux__)
  1701. {"allow_sendfile_call", CONFIG_TYPE_BOOLEAN, "yes"},
  1702. #endif
  1703. #if defined(_WIN32)
  1704. {"case_sensitive", CONFIG_TYPE_BOOLEAN, "no"},
  1705. #endif
  1706. #if defined(USE_LUA)
  1707. {"lua_background_script", CONFIG_TYPE_FILE, NULL},
  1708. #endif
  1709. {NULL, CONFIG_TYPE_UNKNOWN, NULL}};
  1710. /* Check if the config_options and the corresponding enum have compatible
  1711. * sizes. */
  1712. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1713. == (NUM_OPTIONS + 1),
  1714. "config_options and enum not sync");
  1715. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1716. struct mg_handler_info {
  1717. /* Name/Pattern of the URI. */
  1718. char *uri;
  1719. size_t uri_len;
  1720. /* handler type */
  1721. int handler_type;
  1722. /* Handler for http/https or authorization requests. */
  1723. mg_request_handler handler;
  1724. /* Handler for ws/wss (websocket) requests. */
  1725. mg_websocket_connect_handler connect_handler;
  1726. mg_websocket_ready_handler ready_handler;
  1727. mg_websocket_data_handler data_handler;
  1728. mg_websocket_close_handler close_handler;
  1729. /* accepted subprotocols for ws/wss requests. */
  1730. struct mg_websocket_subprotocols *subprotocols;
  1731. /* Handler for authorization requests */
  1732. mg_authorization_handler auth_handler;
  1733. /* User supplied argument for the handler function. */
  1734. void *cbdata;
  1735. /* next handler in a linked list */
  1736. struct mg_handler_info *next;
  1737. };
  1738. struct mg_context {
  1739. volatile int stop_flag; /* Should we stop event loop */
  1740. SSL_CTX *ssl_ctx; /* SSL context */
  1741. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1742. struct mg_callbacks callbacks; /* User-defined callback function */
  1743. void *user_data; /* User-defined data */
  1744. int context_type; /* 1 = server context,
  1745. * 2 = ws/wss client context,
  1746. */
  1747. struct socket *listening_sockets;
  1748. struct pollfd *listening_socket_fds;
  1749. unsigned int num_listening_sockets;
  1750. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  1751. #ifdef ALTERNATIVE_QUEUE
  1752. struct socket *client_socks;
  1753. void **client_wait_events;
  1754. #else
  1755. struct socket queue[MGSQLEN]; /* Accepted sockets */
  1756. volatile int sq_head; /* Head of the socket queue */
  1757. volatile int sq_tail; /* Tail of the socket queue */
  1758. pthread_cond_t sq_full; /* Signaled when socket is produced */
  1759. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  1760. #endif
  1761. pthread_t masterthreadid; /* The master thread ID */
  1762. unsigned int
  1763. cfg_worker_threads; /* The number of configured worker threads. */
  1764. pthread_t *worker_threadids; /* The worker thread IDs */
  1765. struct mg_connection *worker_connections; /* The connection struct, pre-
  1766. * allocated for each worker */
  1767. time_t start_time; /* Server start time, used for authentication */
  1768. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1769. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  1770. unsigned long nonce_count; /* Used nonces, used for authentication */
  1771. char *systemName; /* What operating system is running */
  1772. /* linked list of uri handlers */
  1773. struct mg_handler_info *handlers;
  1774. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1775. /* linked list of shared lua websockets */
  1776. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1777. #endif
  1778. #if defined(USE_TIMERS)
  1779. struct ttimers *timers;
  1780. #endif
  1781. #if defined(USE_LUA)
  1782. void *lua_background_state;
  1783. #endif
  1784. #if defined(USE_SERVER_STATS)
  1785. int active_connections;
  1786. int total_connections;
  1787. int total_requests;
  1788. int max_connections;
  1789. #endif
  1790. };
  1791. struct mg_connection {
  1792. struct mg_request_info request_info;
  1793. struct mg_context *ctx;
  1794. SSL *ssl; /* SSL descriptor */
  1795. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  1796. struct socket client; /* Connected client */
  1797. time_t conn_birth_time; /* Time (wall clock) when connection was
  1798. * established */
  1799. struct timespec req_time; /* Time (since system start) when the request
  1800. * was received */
  1801. int64_t num_bytes_sent; /* Total bytes sent to client */
  1802. int64_t content_len; /* Content-Length header value */
  1803. int64_t consumed_content; /* How many bytes of content have been read */
  1804. int is_chunked; /* Transfer-Encoding is chunked: 0=no, 1=yes:
  1805. * data available, 2: all data read */
  1806. size_t chunk_remainder; /* Unread data from the last chunk */
  1807. char *buf; /* Buffer for received data */
  1808. char *path_info; /* PATH_INFO part of the URL */
  1809. int must_close; /* 1 if connection must be closed */
  1810. int in_error_handler; /* 1 if in handler for user defined error
  1811. * pages */
  1812. int handled_requests; /* Number of requests handled by this connection */
  1813. int buf_size; /* Buffer size */
  1814. int request_len; /* Size of the request + headers in a buffer */
  1815. int data_len; /* Total size of data in a buffer */
  1816. int status_code; /* HTTP reply status code, e.g. 200 */
  1817. int throttle; /* Throttling, bytes/sec. <= 0 means no
  1818. * throttle */
  1819. time_t last_throttle_time; /* Last time throttled data was sent */
  1820. int64_t last_throttle_bytes; /* Bytes sent this second */
  1821. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  1822. * atomic transmissions for websockets */
  1823. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1824. void *lua_websocket_state; /* Lua_State for a websocket connection */
  1825. #endif
  1826. int thread_index; /* Thread index within ctx */
  1827. };
  1828. /* Directory entry */
  1829. struct de {
  1830. struct mg_connection *conn;
  1831. char *file_name;
  1832. struct mg_file_stat file;
  1833. };
  1834. #if defined(USE_WEBSOCKET)
  1835. static int is_websocket_protocol(const struct mg_connection *conn);
  1836. #else
  1837. #define is_websocket_protocol(conn) (0)
  1838. #endif
  1839. #if !defined(NO_THREAD_NAME)
  1840. #if defined(_WIN32) && defined(_MSC_VER)
  1841. /* Set the thread name for debugging purposes in Visual Studio
  1842. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  1843. */
  1844. #pragma pack(push, 8)
  1845. typedef struct tagTHREADNAME_INFO {
  1846. DWORD dwType; /* Must be 0x1000. */
  1847. LPCSTR szName; /* Pointer to name (in user addr space). */
  1848. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  1849. DWORD dwFlags; /* Reserved for future use, must be zero. */
  1850. } THREADNAME_INFO;
  1851. #pragma pack(pop)
  1852. #elif defined(__linux__)
  1853. #include <sys/prctl.h>
  1854. #include <sys/sendfile.h>
  1855. #include <sys/eventfd.h>
  1856. #if defined(ALTERNATIVE_QUEUE)
  1857. static void *
  1858. event_create(void)
  1859. {
  1860. int ret = eventfd(0, EFD_CLOEXEC);
  1861. if (ret == -1) {
  1862. /* Linux uses -1 on error, Windows NULL. */
  1863. /* However, Linux does not return 0 on success either. */
  1864. return 0;
  1865. }
  1866. return (void *)ret;
  1867. }
  1868. static int
  1869. event_wait(void *eventhdl)
  1870. {
  1871. uint64_t u;
  1872. int s = (int)read((int)eventhdl, &u, sizeof(u));
  1873. if (s != sizeof(uint64_t)) {
  1874. /* error */
  1875. return 0;
  1876. }
  1877. (void)u; /* the value is not required */
  1878. return 1;
  1879. }
  1880. static int
  1881. event_signal(void *eventhdl)
  1882. {
  1883. uint64_t u = 1;
  1884. int s = (int)write((int)eventhdl, &u, sizeof(u));
  1885. if (s != sizeof(uint64_t)) {
  1886. /* error */
  1887. return 0;
  1888. }
  1889. return 1;
  1890. }
  1891. static void
  1892. event_destroy(void *eventhdl)
  1893. {
  1894. close((int)eventhdl);
  1895. }
  1896. #endif
  1897. #endif
  1898. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  1899. struct posix_event {
  1900. pthread_mutex_t mutex;
  1901. pthread_cond_t cond;
  1902. };
  1903. static void *
  1904. event_create(void)
  1905. {
  1906. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  1907. if (ret == 0) {
  1908. /* out of memory */
  1909. return 0;
  1910. }
  1911. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  1912. /* pthread mutex not available */
  1913. mg_free(ret);
  1914. return 0;
  1915. }
  1916. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  1917. /* pthread cond not available */
  1918. pthread_mutex_destroy(&(ret->mutex));
  1919. mg_free(ret);
  1920. return 0;
  1921. }
  1922. return (void *)ret;
  1923. }
  1924. static int
  1925. event_wait(void *eventhdl)
  1926. {
  1927. struct posix_event *ev = (struct posix_event *)eventhdl;
  1928. pthread_mutex_lock(&(ev->mutex));
  1929. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  1930. pthread_mutex_unlock(&(ev->mutex));
  1931. return 1;
  1932. }
  1933. static int
  1934. event_signal(void *eventhdl)
  1935. {
  1936. struct posix_event *ev = (struct posix_event *)eventhdl;
  1937. pthread_mutex_lock(&(ev->mutex));
  1938. pthread_cond_signal(&(ev->cond));
  1939. pthread_mutex_unlock(&(ev->mutex));
  1940. return 1;
  1941. }
  1942. static void
  1943. event_destroy(void *eventhdl)
  1944. {
  1945. struct posix_event *ev = (struct posix_event *)eventhdl;
  1946. pthread_cond_destroy(&(ev->cond));
  1947. pthread_mutex_destroy(&(ev->mutex));
  1948. mg_free(ev);
  1949. }
  1950. #endif
  1951. static void
  1952. mg_set_thread_name(const char *name)
  1953. {
  1954. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  1955. mg_snprintf(
  1956. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  1957. #if defined(_WIN32)
  1958. #if defined(_MSC_VER)
  1959. /* Windows and Visual Studio Compiler */
  1960. __try
  1961. {
  1962. THREADNAME_INFO info;
  1963. info.dwType = 0x1000;
  1964. info.szName = threadName;
  1965. info.dwThreadID = ~0U;
  1966. info.dwFlags = 0;
  1967. RaiseException(0x406D1388,
  1968. 0,
  1969. sizeof(info) / sizeof(ULONG_PTR),
  1970. (ULONG_PTR *)&info);
  1971. }
  1972. __except(EXCEPTION_EXECUTE_HANDLER)
  1973. {
  1974. }
  1975. #elif defined(__MINGW32__)
  1976. /* No option known to set thread name for MinGW */
  1977. #endif
  1978. #elif defined(__GLIBC__) \
  1979. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  1980. /* pthread_setname_np first appeared in glibc in version 2.12*/
  1981. (void)pthread_setname_np(pthread_self(), threadName);
  1982. #elif defined(__linux__)
  1983. /* on linux we can use the old prctl function */
  1984. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  1985. #endif
  1986. }
  1987. #else /* !defined(NO_THREAD_NAME) */
  1988. void
  1989. mg_set_thread_name(const char *threadName)
  1990. {
  1991. }
  1992. #endif
  1993. #if defined(MG_LEGACY_INTERFACE)
  1994. const char **
  1995. mg_get_valid_option_names(void)
  1996. {
  1997. /* This function is deprecated. Use mg_get_valid_options instead. */
  1998. static const char *
  1999. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  2000. int i;
  2001. for (i = 0; config_options[i].name != NULL; i++) {
  2002. data[i * 2] = config_options[i].name;
  2003. data[i * 2 + 1] = config_options[i].default_value;
  2004. }
  2005. return data;
  2006. }
  2007. #endif
  2008. const struct mg_option *
  2009. mg_get_valid_options(void)
  2010. {
  2011. return config_options;
  2012. }
  2013. /* Do not open file (used in is_file_in_memory) */
  2014. #define MG_FOPEN_MODE_NONE (0)
  2015. /* Open file for read only access */
  2016. #define MG_FOPEN_MODE_READ (1)
  2017. /* Open file for writing, create and overwrite */
  2018. #define MG_FOPEN_MODE_WRITE (2)
  2019. /* Open file for writing, create and append */
  2020. #define MG_FOPEN_MODE_APPEND (4)
  2021. /* If a file is in memory, set all "stat" members and the membuf pointer of
  2022. * output filep and return 1, otherwise return 0 and don't modify anything. */
  2023. static int
  2024. open_file_in_memory(const struct mg_connection *conn,
  2025. const char *path,
  2026. struct mg_file *filep,
  2027. int mode)
  2028. {
  2029. #if defined(MG_USE_OPEN_FILE)
  2030. size_t size = 0;
  2031. const char *buf = NULL;
  2032. if (!conn) {
  2033. return 0;
  2034. }
  2035. if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
  2036. return 0;
  2037. }
  2038. if (conn->ctx->callbacks.open_file) {
  2039. buf = conn->ctx->callbacks.open_file(conn, path, &size);
  2040. if (buf != NULL) {
  2041. if (filep == NULL) {
  2042. /* This is a file in memory, but we cannot store the properties
  2043. * now.
  2044. * Called from "is_file_in_memory" function. */
  2045. return 1;
  2046. }
  2047. /* NOTE: override filep->size only on success. Otherwise, it might
  2048. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  2049. filep->access.membuf = buf;
  2050. filep->access.fp = NULL;
  2051. /* Size was set by the callback */
  2052. filep->stat.size = size;
  2053. /* Assume the data may change during runtime by setting
  2054. * last_modified = now */
  2055. filep->stat.last_modified = time(NULL);
  2056. filep->stat.is_directory = 0;
  2057. filep->stat.is_gzipped = 0;
  2058. }
  2059. }
  2060. return (buf != NULL);
  2061. #else
  2062. (void)conn;
  2063. (void)path;
  2064. (void)filep;
  2065. (void)mode;
  2066. return 0;
  2067. #endif
  2068. }
  2069. static int
  2070. is_file_in_memory(const struct mg_connection *conn, const char *path)
  2071. {
  2072. return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
  2073. }
  2074. static int
  2075. is_file_opened(const struct mg_file_access *fileacc)
  2076. {
  2077. if (!fileacc) {
  2078. return 0;
  2079. }
  2080. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  2081. }
  2082. static int mg_stat(const struct mg_connection *conn,
  2083. const char *path,
  2084. struct mg_file_stat *filep);
  2085. /* mg_fopen will open a file either in memory or on the disk.
  2086. * The input parameter path is a string in UTF-8 encoding.
  2087. * The input parameter mode is MG_FOPEN_MODE_*
  2088. * On success, either fp or membuf will be set in the output
  2089. * struct file. All status members will also be set.
  2090. * The function returns 1 on success, 0 on error. */
  2091. static int
  2092. mg_fopen(const struct mg_connection *conn,
  2093. const char *path,
  2094. int mode,
  2095. struct mg_file *filep)
  2096. {
  2097. int found;
  2098. if (!filep) {
  2099. return 0;
  2100. }
  2101. filep->access.fp = NULL;
  2102. filep->access.membuf = NULL;
  2103. if (!is_file_in_memory(conn, path)) {
  2104. /* filep is initialized in mg_stat: all fields with memset to,
  2105. * some fields like size and modification date with values */
  2106. found = mg_stat(conn, path, &(filep->stat));
  2107. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2108. /* file does not exist and will not be created */
  2109. return 0;
  2110. }
  2111. #ifdef _WIN32
  2112. {
  2113. wchar_t wbuf[PATH_MAX];
  2114. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2115. switch (mode) {
  2116. case MG_FOPEN_MODE_READ:
  2117. filep->access.fp = _wfopen(wbuf, L"rb");
  2118. break;
  2119. case MG_FOPEN_MODE_WRITE:
  2120. filep->access.fp = _wfopen(wbuf, L"wb");
  2121. break;
  2122. case MG_FOPEN_MODE_APPEND:
  2123. filep->access.fp = _wfopen(wbuf, L"ab");
  2124. break;
  2125. }
  2126. }
  2127. #else
  2128. /* Linux et al already use unicode. No need to convert. */
  2129. switch (mode) {
  2130. case MG_FOPEN_MODE_READ:
  2131. filep->access.fp = fopen(path, "r");
  2132. break;
  2133. case MG_FOPEN_MODE_WRITE:
  2134. filep->access.fp = fopen(path, "w");
  2135. break;
  2136. case MG_FOPEN_MODE_APPEND:
  2137. filep->access.fp = fopen(path, "a");
  2138. break;
  2139. }
  2140. #endif
  2141. if (!found) {
  2142. /* File did not exist before fopen was called.
  2143. * Maybe it has been created now. Get stat info
  2144. * like creation time now. */
  2145. found = mg_stat(conn, path, &(filep->stat));
  2146. (void)found;
  2147. }
  2148. /* file is on disk */
  2149. return (filep->access.fp != NULL);
  2150. } else {
  2151. /* is_file_in_memory returned true */
  2152. if (open_file_in_memory(conn, path, filep, mode)) {
  2153. /* file is in memory */
  2154. return (filep->access.membuf != NULL);
  2155. }
  2156. }
  2157. /* Open failed */
  2158. return 0;
  2159. }
  2160. /* return 0 on success, just like fclose */
  2161. static int
  2162. mg_fclose(struct mg_file_access *fileacc)
  2163. {
  2164. int ret = -1;
  2165. if (fileacc != NULL) {
  2166. if (fileacc->fp != NULL) {
  2167. ret = fclose(fileacc->fp);
  2168. } else if (fileacc->membuf != NULL) {
  2169. ret = 0;
  2170. }
  2171. /* reset all members of fileacc */
  2172. memset(fileacc, 0, sizeof(*fileacc));
  2173. }
  2174. return ret;
  2175. }
  2176. static void
  2177. mg_strlcpy(register char *dst, register const char *src, size_t n)
  2178. {
  2179. for (; *src != '\0' && n > 1; n--) {
  2180. *dst++ = *src++;
  2181. }
  2182. *dst = '\0';
  2183. }
  2184. static int
  2185. lowercase(const char *s)
  2186. {
  2187. return tolower(*(const unsigned char *)s);
  2188. }
  2189. int
  2190. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2191. {
  2192. int diff = 0;
  2193. if (len > 0) {
  2194. do {
  2195. diff = lowercase(s1++) - lowercase(s2++);
  2196. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2197. }
  2198. return diff;
  2199. }
  2200. int
  2201. mg_strcasecmp(const char *s1, const char *s2)
  2202. {
  2203. int diff;
  2204. do {
  2205. diff = lowercase(s1++) - lowercase(s2++);
  2206. } while (diff == 0 && s1[-1] != '\0');
  2207. return diff;
  2208. }
  2209. static char *
  2210. mg_strndup(const char *ptr, size_t len)
  2211. {
  2212. char *p;
  2213. if ((p = (char *)mg_malloc(len + 1)) != NULL) {
  2214. mg_strlcpy(p, ptr, len + 1);
  2215. }
  2216. return p;
  2217. }
  2218. static char *
  2219. mg_strdup(const char *str)
  2220. {
  2221. return mg_strndup(str, strlen(str));
  2222. }
  2223. static const char *
  2224. mg_strcasestr(const char *big_str, const char *small_str)
  2225. {
  2226. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2227. if (big_len >= small_len) {
  2228. for (i = 0; i <= (big_len - small_len); i++) {
  2229. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2230. return big_str + i;
  2231. }
  2232. }
  2233. }
  2234. return NULL;
  2235. }
  2236. /* Return null terminated string of given maximum length.
  2237. * Report errors if length is exceeded. */
  2238. static void
  2239. mg_vsnprintf(const struct mg_connection *conn,
  2240. int *truncated,
  2241. char *buf,
  2242. size_t buflen,
  2243. const char *fmt,
  2244. va_list ap)
  2245. {
  2246. int n, ok;
  2247. if (buflen == 0) {
  2248. return;
  2249. }
  2250. #ifdef __clang__
  2251. #pragma clang diagnostic push
  2252. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2253. /* Using fmt as a non-literal is intended here, since it is mostly called
  2254. * indirectly by mg_snprintf */
  2255. #endif
  2256. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2257. ok = (n >= 0) && ((size_t)n < buflen);
  2258. #ifdef __clang__
  2259. #pragma clang diagnostic pop
  2260. #endif
  2261. if (ok) {
  2262. if (truncated) {
  2263. *truncated = 0;
  2264. }
  2265. } else {
  2266. if (truncated) {
  2267. *truncated = 1;
  2268. }
  2269. mg_cry(conn,
  2270. "truncating vsnprintf buffer: [%.*s]",
  2271. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2272. buf);
  2273. n = (int)buflen - 1;
  2274. }
  2275. buf[n] = '\0';
  2276. }
  2277. static void
  2278. mg_snprintf(const struct mg_connection *conn,
  2279. int *truncated,
  2280. char *buf,
  2281. size_t buflen,
  2282. const char *fmt,
  2283. ...)
  2284. {
  2285. va_list ap;
  2286. va_start(ap, fmt);
  2287. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2288. va_end(ap);
  2289. }
  2290. static int
  2291. get_option_index(const char *name)
  2292. {
  2293. int i;
  2294. for (i = 0; config_options[i].name != NULL; i++) {
  2295. if (strcmp(config_options[i].name, name) == 0) {
  2296. return i;
  2297. }
  2298. }
  2299. return -1;
  2300. }
  2301. const char *
  2302. mg_get_option(const struct mg_context *ctx, const char *name)
  2303. {
  2304. int i;
  2305. if ((i = get_option_index(name)) == -1) {
  2306. return NULL;
  2307. } else if (!ctx || ctx->config[i] == NULL) {
  2308. return "";
  2309. } else {
  2310. return ctx->config[i];
  2311. }
  2312. }
  2313. struct mg_context *
  2314. mg_get_context(const struct mg_connection *conn)
  2315. {
  2316. return (conn == NULL) ? (struct mg_context *)NULL : (conn->ctx);
  2317. }
  2318. void *
  2319. mg_get_user_data(const struct mg_context *ctx)
  2320. {
  2321. return (ctx == NULL) ? NULL : ctx->user_data;
  2322. }
  2323. void
  2324. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  2325. {
  2326. if (conn != NULL) {
  2327. conn->request_info.conn_data = data;
  2328. }
  2329. }
  2330. void *
  2331. mg_get_user_connection_data(const struct mg_connection *conn)
  2332. {
  2333. if (conn != NULL) {
  2334. return conn->request_info.conn_data;
  2335. }
  2336. return NULL;
  2337. }
  2338. #if defined(MG_LEGACY_INTERFACE)
  2339. /* Deprecated: Use mg_get_server_ports instead. */
  2340. size_t
  2341. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  2342. {
  2343. size_t i;
  2344. if (!ctx) {
  2345. return 0;
  2346. }
  2347. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  2348. ssl[i] = ctx->listening_sockets[i].is_ssl;
  2349. ports[i] =
  2350. #if defined(USE_IPV6)
  2351. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2352. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2353. :
  2354. #endif
  2355. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2356. }
  2357. return i;
  2358. }
  2359. #endif
  2360. int
  2361. mg_get_server_ports(const struct mg_context *ctx,
  2362. int size,
  2363. struct mg_server_ports *ports)
  2364. {
  2365. int i, cnt = 0;
  2366. if (size <= 0) {
  2367. return -1;
  2368. }
  2369. memset(ports, 0, sizeof(*ports) * (size_t)size);
  2370. if (!ctx) {
  2371. return -1;
  2372. }
  2373. if (!ctx->listening_sockets) {
  2374. return -1;
  2375. }
  2376. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  2377. ports[cnt].port =
  2378. #if defined(USE_IPV6)
  2379. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2380. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2381. :
  2382. #endif
  2383. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2384. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  2385. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  2386. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  2387. /* IPv4 */
  2388. ports[cnt].protocol = 1;
  2389. cnt++;
  2390. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  2391. /* IPv6 */
  2392. ports[cnt].protocol = 3;
  2393. cnt++;
  2394. }
  2395. }
  2396. return cnt;
  2397. }
  2398. static void
  2399. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  2400. {
  2401. buf[0] = '\0';
  2402. if (!usa) {
  2403. return;
  2404. }
  2405. if (usa->sa.sa_family == AF_INET) {
  2406. getnameinfo(&usa->sa,
  2407. sizeof(usa->sin),
  2408. buf,
  2409. (unsigned)len,
  2410. NULL,
  2411. 0,
  2412. NI_NUMERICHOST);
  2413. }
  2414. #if defined(USE_IPV6)
  2415. else if (usa->sa.sa_family == AF_INET6) {
  2416. getnameinfo(&usa->sa,
  2417. sizeof(usa->sin6),
  2418. buf,
  2419. (unsigned)len,
  2420. NULL,
  2421. 0,
  2422. NI_NUMERICHOST);
  2423. }
  2424. #endif
  2425. }
  2426. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  2427. * included in all responses other than 100, 101, 5xx. */
  2428. static void
  2429. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  2430. {
  2431. struct tm *tm;
  2432. tm = ((t != NULL) ? gmtime(t) : NULL);
  2433. if (tm != NULL) {
  2434. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  2435. } else {
  2436. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  2437. buf[buf_len - 1] = '\0';
  2438. }
  2439. }
  2440. /* difftime for struct timespec. Return value is in seconds. */
  2441. static double
  2442. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  2443. {
  2444. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  2445. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  2446. }
  2447. /* Print error message to the opened error log stream. */
  2448. void
  2449. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  2450. {
  2451. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  2452. va_list ap;
  2453. struct mg_file fi;
  2454. time_t timestamp;
  2455. va_start(ap, fmt);
  2456. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  2457. va_end(ap);
  2458. buf[sizeof(buf) - 1] = 0;
  2459. if (!conn) {
  2460. puts(buf);
  2461. return;
  2462. }
  2463. /* Do not lock when getting the callback value, here and below.
  2464. * I suppose this is fine, since function cannot disappear in the
  2465. * same way string option can. */
  2466. if ((conn->ctx->callbacks.log_message == NULL)
  2467. || (conn->ctx->callbacks.log_message(conn, buf) == 0)) {
  2468. if (conn->ctx->config[ERROR_LOG_FILE] != NULL) {
  2469. if (mg_fopen(conn,
  2470. conn->ctx->config[ERROR_LOG_FILE],
  2471. MG_FOPEN_MODE_APPEND,
  2472. &fi) == 0) {
  2473. fi.access.fp = NULL;
  2474. }
  2475. } else {
  2476. fi.access.fp = NULL;
  2477. }
  2478. if (fi.access.fp != NULL) {
  2479. flockfile(fi.access.fp);
  2480. timestamp = time(NULL);
  2481. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  2482. fprintf(fi.access.fp,
  2483. "[%010lu] [error] [client %s] ",
  2484. (unsigned long)timestamp,
  2485. src_addr);
  2486. if (conn->request_info.request_method != NULL) {
  2487. fprintf(fi.access.fp,
  2488. "%s %s: ",
  2489. conn->request_info.request_method,
  2490. conn->request_info.request_uri);
  2491. }
  2492. fprintf(fi.access.fp, "%s", buf);
  2493. fputc('\n', fi.access.fp);
  2494. fflush(fi.access.fp);
  2495. funlockfile(fi.access.fp);
  2496. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  2497. * mg_cry here anyway ;-) */
  2498. }
  2499. }
  2500. }
  2501. /* Return fake connection structure. Used for logging, if connection
  2502. * is not applicable at the moment of logging. */
  2503. static struct mg_connection *
  2504. fc(struct mg_context *ctx)
  2505. {
  2506. static struct mg_connection fake_connection;
  2507. fake_connection.ctx = ctx;
  2508. return &fake_connection;
  2509. }
  2510. const char *
  2511. mg_version(void)
  2512. {
  2513. return CIVETWEB_VERSION;
  2514. }
  2515. const struct mg_request_info *
  2516. mg_get_request_info(const struct mg_connection *conn)
  2517. {
  2518. if (!conn) {
  2519. return NULL;
  2520. }
  2521. return &conn->request_info;
  2522. }
  2523. int
  2524. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  2525. {
  2526. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  2527. return -1;
  2528. } else {
  2529. int truncated = 0;
  2530. const struct mg_request_info *ri = &conn->request_info;
  2531. #ifdef __clang__
  2532. #pragma clang diagnostic push
  2533. #pragma clang diagnostic ignored "-Wunreachable-code"
  2534. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  2535. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  2536. * unreachable, but splitting into four different #ifdef clauses here is more
  2537. * complicated.
  2538. */
  2539. #endif
  2540. const char *proto =
  2541. (is_websocket_protocol(conn) ? (ri->is_ssl ? "wss" : "ws")
  2542. : (ri->is_ssl ? "https" : "http"));
  2543. #ifdef __clang__
  2544. #pragma clang diagnostic pop
  2545. #endif
  2546. if (ri->local_uri == NULL) {
  2547. return -1;
  2548. }
  2549. if ((ri->request_uri != NULL)
  2550. && strcmp(ri->local_uri, ri->request_uri)) {
  2551. mg_snprintf(conn,
  2552. &truncated,
  2553. buf,
  2554. buflen,
  2555. "%s://%s",
  2556. proto,
  2557. ri->request_uri);
  2558. if (truncated) {
  2559. return -1;
  2560. }
  2561. return 0;
  2562. } else {
  2563. #if defined(USE_IPV6)
  2564. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  2565. int port = is_ipv6 ? htons(conn->client.lsa.sin6.sin6_port)
  2566. : htons(conn->client.lsa.sin.sin_port);
  2567. #else
  2568. int port = htons(conn->client.lsa.sin.sin_port);
  2569. #endif
  2570. int def_port = ri->is_ssl ? 443 : 80;
  2571. int auth_domain_check_enabled =
  2572. conn->ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  2573. && (!strcmp(conn->ctx->config[ENABLE_AUTH_DOMAIN_CHECK],
  2574. "yes"));
  2575. const char *server_domain =
  2576. conn->ctx->config[AUTHENTICATION_DOMAIN];
  2577. char portstr[16];
  2578. char server_ip[48];
  2579. if (port != def_port) {
  2580. sprintf(portstr, ":%u", (unsigned)port);
  2581. } else {
  2582. portstr[0] = 0;
  2583. }
  2584. if (!auth_domain_check_enabled || !server_domain) {
  2585. sockaddr_to_string(server_ip,
  2586. sizeof(server_ip),
  2587. &conn->client.lsa);
  2588. server_domain = server_ip;
  2589. }
  2590. mg_snprintf(conn,
  2591. &truncated,
  2592. buf,
  2593. buflen,
  2594. "%s://%s%s%s",
  2595. proto,
  2596. server_domain,
  2597. portstr,
  2598. ri->local_uri);
  2599. if (truncated) {
  2600. return -1;
  2601. }
  2602. return 0;
  2603. }
  2604. }
  2605. }
  2606. /* Skip the characters until one of the delimiters characters found.
  2607. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  2608. * Advance pointer to buffer to the next word. Return found 0-terminated word.
  2609. * Delimiters can be quoted with quotechar. */
  2610. static char *
  2611. skip_quoted(char **buf,
  2612. const char *delimiters,
  2613. const char *whitespace,
  2614. char quotechar)
  2615. {
  2616. char *p, *begin_word, *end_word, *end_whitespace;
  2617. begin_word = *buf;
  2618. end_word = begin_word + strcspn(begin_word, delimiters);
  2619. /* Check for quotechar */
  2620. if (end_word > begin_word) {
  2621. p = end_word - 1;
  2622. while (*p == quotechar) {
  2623. /* While the delimiter is quoted, look for the next delimiter. */
  2624. /* This happens, e.g., in calls from parse_auth_header,
  2625. * if the user name contains a " character. */
  2626. /* If there is anything beyond end_word, copy it. */
  2627. if (*end_word != '\0') {
  2628. size_t end_off = strcspn(end_word + 1, delimiters);
  2629. memmove(p, end_word, end_off + 1);
  2630. p += end_off; /* p must correspond to end_word - 1 */
  2631. end_word += end_off + 1;
  2632. } else {
  2633. *p = '\0';
  2634. break;
  2635. }
  2636. }
  2637. for (p++; p < end_word; p++) {
  2638. *p = '\0';
  2639. }
  2640. }
  2641. if (*end_word == '\0') {
  2642. *buf = end_word;
  2643. } else {
  2644. #if defined(__GNUC__) || defined(__MINGW32__)
  2645. /* Disable spurious conversion warning for GCC */
  2646. #pragma GCC diagnostic push
  2647. #pragma GCC diagnostic ignored "-Wsign-conversion"
  2648. #endif
  2649. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  2650. #if defined(__GNUC__) || defined(__MINGW32__)
  2651. #pragma GCC diagnostic pop
  2652. #endif
  2653. for (p = end_word; p < end_whitespace; p++) {
  2654. *p = '\0';
  2655. }
  2656. *buf = end_whitespace;
  2657. }
  2658. return begin_word;
  2659. }
  2660. /* Simplified version of skip_quoted without quote char
  2661. * and whitespace == delimiters */
  2662. static char *
  2663. skip(char **buf, const char *delimiters)
  2664. {
  2665. return skip_quoted(buf, delimiters, delimiters, 0);
  2666. }
  2667. /* Return HTTP header value, or NULL if not found. */
  2668. static const char *
  2669. get_header(const struct mg_request_info *ri, const char *name)
  2670. {
  2671. int i;
  2672. if (ri) {
  2673. for (i = 0; i < ri->num_headers; i++) {
  2674. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  2675. return ri->http_headers[i].value;
  2676. }
  2677. }
  2678. }
  2679. return NULL;
  2680. }
  2681. const char *
  2682. mg_get_header(const struct mg_connection *conn, const char *name)
  2683. {
  2684. if (!conn) {
  2685. return NULL;
  2686. }
  2687. return get_header(&conn->request_info, name);
  2688. }
  2689. /* A helper function for traversing a comma separated list of values.
  2690. * It returns a list pointer shifted to the next value, or NULL if the end
  2691. * of the list found.
  2692. * Value is stored in val vector. If value has form "x=y", then eq_val
  2693. * vector is initialized to point to the "y" part, and val vector length
  2694. * is adjusted to point only to "x". */
  2695. static const char *
  2696. next_option(const char *list, struct vec *val, struct vec *eq_val)
  2697. {
  2698. int end;
  2699. reparse:
  2700. if (val == NULL || list == NULL || *list == '\0') {
  2701. /* End of the list */
  2702. list = NULL;
  2703. } else {
  2704. /* Skip over leading LWS */
  2705. while (*list == ' ' || *list == '\t')
  2706. list++;
  2707. val->ptr = list;
  2708. if ((list = strchr(val->ptr, ',')) != NULL) {
  2709. /* Comma found. Store length and shift the list ptr */
  2710. val->len = ((size_t)(list - val->ptr));
  2711. list++;
  2712. } else {
  2713. /* This value is the last one */
  2714. list = val->ptr + strlen(val->ptr);
  2715. val->len = ((size_t)(list - val->ptr));
  2716. }
  2717. /* Adjust length for trailing LWS */
  2718. end = (int)val->len - 1;
  2719. while (end >= 0 && (val->ptr[end] == ' ' || val->ptr[end] == '\t'))
  2720. end--;
  2721. val->len = (size_t)(end + 1);
  2722. if (val->len == 0) {
  2723. /* Ignore any empty entries. */
  2724. goto reparse;
  2725. }
  2726. if (eq_val != NULL) {
  2727. /* Value has form "x=y", adjust pointers and lengths
  2728. * so that val points to "x", and eq_val points to "y". */
  2729. eq_val->len = 0;
  2730. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  2731. if (eq_val->ptr != NULL) {
  2732. eq_val->ptr++; /* Skip over '=' character */
  2733. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  2734. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  2735. }
  2736. }
  2737. }
  2738. return list;
  2739. }
  2740. /* A helper function for checking if a comma separated list of values contains
  2741. * the given option (case insensitvely).
  2742. * 'header' can be NULL, in which case false is returned. */
  2743. static int
  2744. header_has_option(const char *header, const char *option)
  2745. {
  2746. struct vec opt_vec;
  2747. struct vec eq_vec;
  2748. assert(option != NULL);
  2749. assert(option[0] != '\0');
  2750. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  2751. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  2752. return 1;
  2753. }
  2754. return 0;
  2755. }
  2756. /* Perform case-insensitive match of string against pattern */
  2757. static int
  2758. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  2759. {
  2760. const char *or_str;
  2761. size_t i;
  2762. int j, len, res;
  2763. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  2764. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  2765. return (res > 0) ? res : match_prefix(or_str + 1,
  2766. (size_t)((pattern + pattern_len)
  2767. - (or_str + 1)),
  2768. str);
  2769. }
  2770. for (i = 0, j = 0; i < pattern_len; i++, j++) {
  2771. if (pattern[i] == '?' && str[j] != '\0') {
  2772. continue;
  2773. } else if (pattern[i] == '$') {
  2774. return (str[j] == '\0') ? j : -1;
  2775. } else if (pattern[i] == '*') {
  2776. i++;
  2777. if (pattern[i] == '*') {
  2778. i++;
  2779. len = (int)strlen(str + j);
  2780. } else {
  2781. len = (int)strcspn(str + j, "/");
  2782. }
  2783. if (i == pattern_len) {
  2784. return j + len;
  2785. }
  2786. do {
  2787. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  2788. } while (res == -1 && len-- > 0);
  2789. return (res == -1) ? -1 : j + res + len;
  2790. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  2791. return -1;
  2792. }
  2793. }
  2794. return j;
  2795. }
  2796. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  2797. * This function must tolerate situations when connection info is not
  2798. * set up, for example if request parsing failed. */
  2799. static int
  2800. should_keep_alive(const struct mg_connection *conn)
  2801. {
  2802. if (conn != NULL) {
  2803. const char *http_version = conn->request_info.http_version;
  2804. const char *header = mg_get_header(conn, "Connection");
  2805. if (conn->must_close || conn->status_code == 401
  2806. || mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0
  2807. || (header != NULL && !header_has_option(header, "keep-alive"))
  2808. || (header == NULL && http_version
  2809. && 0 != strcmp(http_version, "1.1"))) {
  2810. return 0;
  2811. }
  2812. return 1;
  2813. }
  2814. return 0;
  2815. }
  2816. static int
  2817. should_decode_url(const struct mg_connection *conn)
  2818. {
  2819. if (!conn || !conn->ctx) {
  2820. return 0;
  2821. }
  2822. return (mg_strcasecmp(conn->ctx->config[DECODE_URL], "yes") == 0);
  2823. }
  2824. static const char *
  2825. suggest_connection_header(const struct mg_connection *conn)
  2826. {
  2827. return should_keep_alive(conn) ? "keep-alive" : "close";
  2828. }
  2829. static int
  2830. send_no_cache_header(struct mg_connection *conn)
  2831. {
  2832. /* Send all current and obsolete cache opt-out directives. */
  2833. return mg_printf(conn,
  2834. "Cache-Control: no-cache, no-store, "
  2835. "must-revalidate, private, max-age=0\r\n"
  2836. "Pragma: no-cache\r\n"
  2837. "Expires: 0\r\n");
  2838. }
  2839. static int
  2840. send_static_cache_header(struct mg_connection *conn)
  2841. {
  2842. #if !defined(NO_CACHING)
  2843. /* Read the server config to check how long a file may be cached.
  2844. * The configuration is in seconds. */
  2845. int max_age = atoi(conn->ctx->config[STATIC_FILE_MAX_AGE]);
  2846. if (max_age <= 0) {
  2847. /* 0 means "do not cache". All values <0 are reserved
  2848. * and may be used differently in the future. */
  2849. /* If a file should not be cached, do not only send
  2850. * max-age=0, but also pragmas and Expires headers. */
  2851. return send_no_cache_header(conn);
  2852. }
  2853. /* Use "Cache-Control: max-age" instead of "Expires" header.
  2854. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  2855. /* See also https://www.mnot.net/cache_docs/ */
  2856. /* According to RFC 2616, Section 14.21, caching times should not exceed
  2857. * one year. A year with 365 days corresponds to 31536000 seconds, a leap
  2858. * year to 31622400 seconds. For the moment, we just send whatever has
  2859. * been configured, still the behavior for >1 year should be considered
  2860. * as undefined. */
  2861. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  2862. #else /* NO_CACHING */
  2863. return send_no_cache_header(conn);
  2864. #endif /* !NO_CACHING */
  2865. }
  2866. static int
  2867. send_additional_header(struct mg_connection *conn)
  2868. {
  2869. int i = 0;
  2870. (void)conn;
  2871. #if 0
  2872. /* TODO (Feature): Configure additional response header */
  2873. i += mg_printf(conn, "Strict-Transport-Security: max-age=%u\r\n", 3600);
  2874. i += mg_printf(conn, "X-Some-Test-Header: %u\r\n", 42);
  2875. #endif
  2876. return i;
  2877. }
  2878. static void handle_file_based_request(struct mg_connection *conn,
  2879. const char *path,
  2880. struct mg_file *filep);
  2881. const char *
  2882. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  2883. {
  2884. /* See IANA HTTP status code assignment:
  2885. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  2886. */
  2887. switch (response_code) {
  2888. /* RFC2616 Section 10.1 - Informational 1xx */
  2889. case 100:
  2890. return "Continue"; /* RFC2616 Section 10.1.1 */
  2891. case 101:
  2892. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  2893. case 102:
  2894. return "Processing"; /* RFC2518 Section 10.1 */
  2895. /* RFC2616 Section 10.2 - Successful 2xx */
  2896. case 200:
  2897. return "OK"; /* RFC2616 Section 10.2.1 */
  2898. case 201:
  2899. return "Created"; /* RFC2616 Section 10.2.2 */
  2900. case 202:
  2901. return "Accepted"; /* RFC2616 Section 10.2.3 */
  2902. case 203:
  2903. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  2904. case 204:
  2905. return "No Content"; /* RFC2616 Section 10.2.5 */
  2906. case 205:
  2907. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  2908. case 206:
  2909. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  2910. case 207:
  2911. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1 */
  2912. case 208:
  2913. return "Already Reported"; /* RFC5842 Section 7.1 */
  2914. case 226:
  2915. return "IM used"; /* RFC3229 Section 10.4.1 */
  2916. /* RFC2616 Section 10.3 - Redirection 3xx */
  2917. case 300:
  2918. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  2919. case 301:
  2920. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  2921. case 302:
  2922. return "Found"; /* RFC2616 Section 10.3.3 */
  2923. case 303:
  2924. return "See Other"; /* RFC2616 Section 10.3.4 */
  2925. case 304:
  2926. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  2927. case 305:
  2928. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  2929. case 307:
  2930. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  2931. case 308:
  2932. return "Permanent Redirect"; /* RFC7238 Section 3 */
  2933. /* RFC2616 Section 10.4 - Client Error 4xx */
  2934. case 400:
  2935. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  2936. case 401:
  2937. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  2938. case 402:
  2939. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  2940. case 403:
  2941. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  2942. case 404:
  2943. return "Not Found"; /* RFC2616 Section 10.4.5 */
  2944. case 405:
  2945. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  2946. case 406:
  2947. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  2948. case 407:
  2949. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  2950. case 408:
  2951. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  2952. case 409:
  2953. return "Conflict"; /* RFC2616 Section 10.4.10 */
  2954. case 410:
  2955. return "Gone"; /* RFC2616 Section 10.4.11 */
  2956. case 411:
  2957. return "Length Required"; /* RFC2616 Section 10.4.12 */
  2958. case 412:
  2959. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  2960. case 413:
  2961. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  2962. case 414:
  2963. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  2964. case 415:
  2965. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  2966. case 416:
  2967. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17 */
  2968. case 417:
  2969. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  2970. case 421:
  2971. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  2972. case 422:
  2973. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  2974. * Section 11.2 */
  2975. case 423:
  2976. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  2977. case 424:
  2978. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  2979. * Section 11.4 */
  2980. case 426:
  2981. return "Upgrade Required"; /* RFC 2817 Section 4 */
  2982. case 428:
  2983. return "Precondition Required"; /* RFC 6585, Section 3 */
  2984. case 429:
  2985. return "Too Many Requests"; /* RFC 6585, Section 4 */
  2986. case 431:
  2987. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  2988. case 451:
  2989. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  2990. * Section 3 */
  2991. /* RFC2616 Section 10.5 - Server Error 5xx */
  2992. case 500:
  2993. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  2994. case 501:
  2995. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  2996. case 502:
  2997. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  2998. case 503:
  2999. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3000. case 504:
  3001. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3002. case 505:
  3003. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3004. case 506:
  3005. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3006. case 507:
  3007. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3008. * Section 11.5 */
  3009. case 508:
  3010. return "Loop Detected"; /* RFC5842 Section 7.1 */
  3011. case 510:
  3012. return "Not Extended"; /* RFC 2774, Section 7 */
  3013. case 511:
  3014. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  3015. /* Other status codes, not shown in the IANA HTTP status code assignment.
  3016. * E.g., "de facto" standards due to common use, ... */
  3017. case 418:
  3018. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  3019. case 419:
  3020. return "Authentication Timeout"; /* common use */
  3021. case 420:
  3022. return "Enhance Your Calm"; /* common use */
  3023. case 440:
  3024. return "Login Timeout"; /* common use */
  3025. case 509:
  3026. return "Bandwidth Limit Exceeded"; /* common use */
  3027. default:
  3028. /* This error code is unknown. This should not happen. */
  3029. if (conn) {
  3030. mg_cry(conn, "Unknown HTTP response code: %u", response_code);
  3031. }
  3032. /* Return at least a category according to RFC 2616 Section 10. */
  3033. if (response_code >= 100 && response_code < 200) {
  3034. /* Unknown informational status code */
  3035. return "Information";
  3036. }
  3037. if (response_code >= 200 && response_code < 300) {
  3038. /* Unknown success code */
  3039. return "Success";
  3040. }
  3041. if (response_code >= 300 && response_code < 400) {
  3042. /* Unknown redirection code */
  3043. return "Redirection";
  3044. }
  3045. if (response_code >= 400 && response_code < 500) {
  3046. /* Unknown request error code */
  3047. return "Client Error";
  3048. }
  3049. if (response_code >= 500 && response_code < 600) {
  3050. /* Unknown server error code */
  3051. return "Server Error";
  3052. }
  3053. /* Response code not even within reasonable range */
  3054. return "";
  3055. }
  3056. }
  3057. void
  3058. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  3059. {
  3060. char buf[MG_BUF_LEN];
  3061. va_list ap;
  3062. int len, i, page_handler_found, scope, truncated, has_body;
  3063. char date[64];
  3064. time_t curtime = time(NULL);
  3065. const char *error_handler = NULL;
  3066. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  3067. const char *error_page_file_ext, *tstr;
  3068. const char *status_text = mg_get_response_code_text(conn, status);
  3069. if (conn == NULL) {
  3070. return;
  3071. }
  3072. conn->status_code = status;
  3073. if (conn->in_error_handler || conn->ctx->callbacks.http_error == NULL
  3074. || conn->ctx->callbacks.http_error(conn, status)) {
  3075. if (!conn->in_error_handler) {
  3076. /* Send user defined error pages, if defined */
  3077. error_handler = conn->ctx->config[ERROR_PAGES];
  3078. error_page_file_ext = conn->ctx->config[INDEX_FILES];
  3079. page_handler_found = 0;
  3080. if (error_handler != NULL) {
  3081. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  3082. switch (scope) {
  3083. case 1: /* Handler for specific error, e.g. 404 error */
  3084. mg_snprintf(conn,
  3085. &truncated,
  3086. buf,
  3087. sizeof(buf) - 32,
  3088. "%serror%03u.",
  3089. error_handler,
  3090. status);
  3091. break;
  3092. case 2: /* Handler for error group, e.g., 5xx error handler
  3093. * for all server errors (500-599) */
  3094. mg_snprintf(conn,
  3095. &truncated,
  3096. buf,
  3097. sizeof(buf) - 32,
  3098. "%serror%01uxx.",
  3099. error_handler,
  3100. status / 100);
  3101. break;
  3102. default: /* Handler for all errors */
  3103. mg_snprintf(conn,
  3104. &truncated,
  3105. buf,
  3106. sizeof(buf) - 32,
  3107. "%serror.",
  3108. error_handler);
  3109. break;
  3110. }
  3111. /* String truncation in buf may only occur if error_handler
  3112. * is too long. This string is from the config, not from a
  3113. * client. */
  3114. (void)truncated;
  3115. len = (int)strlen(buf);
  3116. tstr = strchr(error_page_file_ext, '.');
  3117. while (tstr) {
  3118. for (i = 1; i < 32 && tstr[i] != 0 && tstr[i] != ',';
  3119. i++)
  3120. buf[len + i - 1] = tstr[i];
  3121. buf[len + i - 1] = 0;
  3122. if (mg_stat(conn, buf, &error_page_file.stat)) {
  3123. page_handler_found = 1;
  3124. break;
  3125. }
  3126. tstr = strchr(tstr + i, '.');
  3127. }
  3128. }
  3129. }
  3130. if (page_handler_found) {
  3131. conn->in_error_handler = 1;
  3132. handle_file_based_request(conn, buf, &error_page_file);
  3133. conn->in_error_handler = 0;
  3134. return;
  3135. }
  3136. }
  3137. /* No custom error page. Send default error page. */
  3138. gmt_time_string(date, sizeof(date), &curtime);
  3139. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3140. has_body = (status > 199 && status != 204 && status != 304);
  3141. conn->must_close = 1;
  3142. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  3143. send_no_cache_header(conn);
  3144. send_additional_header(conn);
  3145. if (has_body) {
  3146. mg_printf(conn,
  3147. "%s",
  3148. "Content-Type: text/plain; charset=utf-8\r\n");
  3149. }
  3150. mg_printf(conn,
  3151. "Date: %s\r\n"
  3152. "Connection: close\r\n\r\n",
  3153. date);
  3154. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3155. if (has_body) {
  3156. mg_printf(conn, "Error %d: %s\n", status, status_text);
  3157. if (fmt != NULL) {
  3158. va_start(ap, fmt);
  3159. mg_vsnprintf(conn, NULL, buf, sizeof(buf), fmt, ap);
  3160. va_end(ap);
  3161. mg_write(conn, buf, strlen(buf));
  3162. DEBUG_TRACE("Error %i - [%s]", status, buf);
  3163. }
  3164. } else {
  3165. /* No body allowed. Close the connection. */
  3166. DEBUG_TRACE("Error %i", status);
  3167. }
  3168. }
  3169. }
  3170. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  3171. /* Create substitutes for POSIX functions in Win32. */
  3172. #if defined(__MINGW32__)
  3173. /* Show no warning in case system functions are not used. */
  3174. #pragma GCC diagnostic push
  3175. #pragma GCC diagnostic ignored "-Wunused-function"
  3176. #endif
  3177. static int
  3178. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  3179. {
  3180. (void)unused;
  3181. *mutex = CreateMutex(NULL, FALSE, NULL);
  3182. return (*mutex == NULL) ? -1 : 0;
  3183. }
  3184. static int
  3185. pthread_mutex_destroy(pthread_mutex_t *mutex)
  3186. {
  3187. return (CloseHandle(*mutex) == 0) ? -1 : 0;
  3188. }
  3189. static int
  3190. pthread_mutex_lock(pthread_mutex_t *mutex)
  3191. {
  3192. return (WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0) ? 0 : -1;
  3193. }
  3194. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  3195. static int
  3196. pthread_mutex_trylock(pthread_mutex_t *mutex)
  3197. {
  3198. switch (WaitForSingleObject(*mutex, 0)) {
  3199. case WAIT_OBJECT_0:
  3200. return 0;
  3201. case WAIT_TIMEOUT:
  3202. return -2; /* EBUSY */
  3203. }
  3204. return -1;
  3205. }
  3206. #endif
  3207. static int
  3208. pthread_mutex_unlock(pthread_mutex_t *mutex)
  3209. {
  3210. return (ReleaseMutex(*mutex) == 0) ? -1 : 0;
  3211. }
  3212. static int
  3213. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  3214. {
  3215. (void)unused;
  3216. InitializeCriticalSection(&cv->threadIdSec);
  3217. cv->waiting_thread = NULL;
  3218. return 0;
  3219. }
  3220. static int
  3221. pthread_cond_timedwait(pthread_cond_t *cv,
  3222. pthread_mutex_t *mutex,
  3223. const struct timespec *abstime)
  3224. {
  3225. struct mg_workerTLS **ptls,
  3226. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3227. int ok;
  3228. int64_t nsnow, nswaitabs, nswaitrel;
  3229. DWORD mswaitrel;
  3230. EnterCriticalSection(&cv->threadIdSec);
  3231. /* Add this thread to cv's waiting list */
  3232. ptls = &cv->waiting_thread;
  3233. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  3234. ;
  3235. tls->next_waiting_thread = NULL;
  3236. *ptls = tls;
  3237. LeaveCriticalSection(&cv->threadIdSec);
  3238. if (abstime) {
  3239. nsnow = mg_get_current_time_ns();
  3240. nswaitabs =
  3241. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  3242. nswaitrel = nswaitabs - nsnow;
  3243. if (nswaitrel < 0) {
  3244. nswaitrel = 0;
  3245. }
  3246. mswaitrel = (DWORD)(nswaitrel / 1000000);
  3247. } else {
  3248. mswaitrel = INFINITE;
  3249. }
  3250. pthread_mutex_unlock(mutex);
  3251. ok = (WAIT_OBJECT_0
  3252. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  3253. if (!ok) {
  3254. ok = 1;
  3255. EnterCriticalSection(&cv->threadIdSec);
  3256. ptls = &cv->waiting_thread;
  3257. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  3258. if (*ptls == tls) {
  3259. *ptls = tls->next_waiting_thread;
  3260. ok = 0;
  3261. break;
  3262. }
  3263. }
  3264. LeaveCriticalSection(&cv->threadIdSec);
  3265. if (ok) {
  3266. WaitForSingleObject(tls->pthread_cond_helper_mutex, INFINITE);
  3267. }
  3268. }
  3269. /* This thread has been removed from cv's waiting list */
  3270. pthread_mutex_lock(mutex);
  3271. return ok ? 0 : -1;
  3272. }
  3273. static int
  3274. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  3275. {
  3276. return pthread_cond_timedwait(cv, mutex, NULL);
  3277. }
  3278. static int
  3279. pthread_cond_signal(pthread_cond_t *cv)
  3280. {
  3281. HANDLE wkup = NULL;
  3282. BOOL ok = FALSE;
  3283. EnterCriticalSection(&cv->threadIdSec);
  3284. if (cv->waiting_thread) {
  3285. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  3286. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  3287. ok = SetEvent(wkup);
  3288. assert(ok);
  3289. }
  3290. LeaveCriticalSection(&cv->threadIdSec);
  3291. return ok ? 0 : 1;
  3292. }
  3293. static int
  3294. pthread_cond_broadcast(pthread_cond_t *cv)
  3295. {
  3296. EnterCriticalSection(&cv->threadIdSec);
  3297. while (cv->waiting_thread) {
  3298. pthread_cond_signal(cv);
  3299. }
  3300. LeaveCriticalSection(&cv->threadIdSec);
  3301. return 0;
  3302. }
  3303. static int
  3304. pthread_cond_destroy(pthread_cond_t *cv)
  3305. {
  3306. EnterCriticalSection(&cv->threadIdSec);
  3307. assert(cv->waiting_thread == NULL);
  3308. LeaveCriticalSection(&cv->threadIdSec);
  3309. DeleteCriticalSection(&cv->threadIdSec);
  3310. return 0;
  3311. }
  3312. #ifdef ALTERNATIVE_QUEUE
  3313. static void *
  3314. event_create(void)
  3315. {
  3316. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  3317. }
  3318. static int
  3319. event_wait(void *eventhdl)
  3320. {
  3321. int res = WaitForSingleObject((HANDLE)eventhdl, INFINITE);
  3322. return (res == WAIT_OBJECT_0);
  3323. }
  3324. static int
  3325. event_signal(void *eventhdl)
  3326. {
  3327. return (int)SetEvent((HANDLE)eventhdl);
  3328. }
  3329. static void
  3330. event_destroy(void *eventhdl)
  3331. {
  3332. CloseHandle((HANDLE)eventhdl);
  3333. }
  3334. #endif
  3335. #if defined(__MINGW32__)
  3336. /* Enable unused function warning again */
  3337. #pragma GCC diagnostic pop
  3338. #endif
  3339. /* For Windows, change all slashes to backslashes in path names. */
  3340. static void
  3341. change_slashes_to_backslashes(char *path)
  3342. {
  3343. int i;
  3344. for (i = 0; path[i] != '\0'; i++) {
  3345. if (path[i] == '/') {
  3346. path[i] = '\\';
  3347. }
  3348. /* remove double backslash (check i > 0 to preserve UNC paths,
  3349. * like \\server\file.txt) */
  3350. if ((path[i] == '\\') && (i > 0)) {
  3351. while (path[i + 1] == '\\' || path[i + 1] == '/') {
  3352. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  3353. }
  3354. }
  3355. }
  3356. }
  3357. static int
  3358. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  3359. {
  3360. int diff;
  3361. do {
  3362. diff = tolower(*s1) - tolower(*s2);
  3363. s1++;
  3364. s2++;
  3365. } while (diff == 0 && s1[-1] != '\0');
  3366. return diff;
  3367. }
  3368. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  3369. * wbuf and wbuf_len is a target buffer and its length. */
  3370. static void
  3371. path_to_unicode(const struct mg_connection *conn,
  3372. const char *path,
  3373. wchar_t *wbuf,
  3374. size_t wbuf_len)
  3375. {
  3376. char buf[PATH_MAX], buf2[PATH_MAX];
  3377. wchar_t wbuf2[MAX_PATH + 1];
  3378. DWORD long_len, err;
  3379. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  3380. mg_strlcpy(buf, path, sizeof(buf));
  3381. change_slashes_to_backslashes(buf);
  3382. /* Convert to Unicode and back. If doubly-converted string does not
  3383. * match the original, something is fishy, reject. */
  3384. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  3385. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  3386. WideCharToMultiByte(
  3387. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  3388. if (strcmp(buf, buf2) != 0) {
  3389. wbuf[0] = L'\0';
  3390. }
  3391. /* Windows file systems are not case sensitive, but you can still use
  3392. * uppercase and lowercase letters (on all modern file systems).
  3393. * The server can check if the URI uses the same upper/lowercase
  3394. * letters an the file system, effectively making Windows servers
  3395. * case sensitive (like Linux servers are). It is still not possible
  3396. * to use two files with the same name in different cases on Windows
  3397. * (like /a and /A) - this would be possible in Linux.
  3398. * As a default, Windows is not case sensitive, but the case sensitive
  3399. * file name check can be activated by an additional configuration. */
  3400. if (conn) {
  3401. if (conn->ctx->config[CASE_SENSITIVE_FILES]
  3402. && !mg_strcasecmp(conn->ctx->config[CASE_SENSITIVE_FILES], "yes")) {
  3403. /* Use case sensitive compare function */
  3404. fcompare = wcscmp;
  3405. }
  3406. }
  3407. (void)conn; /* conn is currently unused */
  3408. #if !defined(_WIN32_WCE)
  3409. /* Only accept a full file path, not a Windows short (8.3) path. */
  3410. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  3411. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  3412. if (long_len == 0) {
  3413. err = GetLastError();
  3414. if (err == ERROR_FILE_NOT_FOUND) {
  3415. /* File does not exist. This is not always a problem here. */
  3416. return;
  3417. }
  3418. }
  3419. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  3420. /* Short name is used. */
  3421. wbuf[0] = L'\0';
  3422. }
  3423. #else
  3424. (void)long_len;
  3425. (void)wbuf2;
  3426. (void)err;
  3427. if (strchr(path, '~')) {
  3428. wbuf[0] = L'\0';
  3429. }
  3430. #endif
  3431. }
  3432. /* Windows happily opens files with some garbage at the end of file name.
  3433. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  3434. * "a.cgi", despite one would expect an error back.
  3435. * This function returns non-0 if path ends with some garbage. */
  3436. static int
  3437. path_cannot_disclose_cgi(const char *path)
  3438. {
  3439. static const char *allowed_last_characters = "_-";
  3440. int last = path[strlen(path) - 1];
  3441. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  3442. }
  3443. static int
  3444. mg_stat(const struct mg_connection *conn,
  3445. const char *path,
  3446. struct mg_file_stat *filep)
  3447. {
  3448. wchar_t wbuf[PATH_MAX];
  3449. WIN32_FILE_ATTRIBUTE_DATA info;
  3450. time_t creation_time;
  3451. if (!filep) {
  3452. return 0;
  3453. }
  3454. memset(filep, 0, sizeof(*filep));
  3455. if (conn && is_file_in_memory(conn, path)) {
  3456. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  3457. * memset */
  3458. /* Quick fix (for 1.9.x): */
  3459. /* mg_stat must fill all fields, also for files in memory */
  3460. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  3461. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  3462. filep->size = tmp_file.stat.size;
  3463. filep->location = 2;
  3464. /* TODO: for 1.10: restructure how files in memory are handled */
  3465. /* The "file in memory" feature is a candidate for deletion.
  3466. * Please join the discussion at
  3467. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  3468. */
  3469. filep->last_modified = time(NULL); /* TODO */
  3470. /* last_modified = now ... assumes the file may change during runtime,
  3471. * so every mg_fopen call may return different data */
  3472. /* last_modified = conn->ctx.start_time;
  3473. * May be used it the data does not change during runtime. This allows
  3474. * browser caching. Since we do not know, we have to assume the file
  3475. * in memory may change. */
  3476. return 1;
  3477. }
  3478. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3479. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  3480. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  3481. filep->last_modified =
  3482. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  3483. info.ftLastWriteTime.dwHighDateTime);
  3484. /* On Windows, the file creation time can be higher than the
  3485. * modification time, e.g. when a file is copied.
  3486. * Since the Last-Modified timestamp is used for caching
  3487. * it should be based on the most recent timestamp. */
  3488. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  3489. info.ftCreationTime.dwHighDateTime);
  3490. if (creation_time > filep->last_modified) {
  3491. filep->last_modified = creation_time;
  3492. }
  3493. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  3494. /* If file name is fishy, reset the file structure and return
  3495. * error.
  3496. * Note it is important to reset, not just return the error, cause
  3497. * functions like is_file_opened() check the struct. */
  3498. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  3499. memset(filep, 0, sizeof(*filep));
  3500. return 0;
  3501. }
  3502. return 1;
  3503. }
  3504. return 0;
  3505. }
  3506. static int
  3507. mg_remove(const struct mg_connection *conn, const char *path)
  3508. {
  3509. wchar_t wbuf[PATH_MAX];
  3510. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3511. return DeleteFileW(wbuf) ? 0 : -1;
  3512. }
  3513. static int
  3514. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  3515. {
  3516. wchar_t wbuf[PATH_MAX];
  3517. (void)mode;
  3518. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3519. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  3520. }
  3521. /* Create substitutes for POSIX functions in Win32. */
  3522. #if defined(__MINGW32__)
  3523. /* Show no warning in case system functions are not used. */
  3524. #pragma GCC diagnostic push
  3525. #pragma GCC diagnostic ignored "-Wunused-function"
  3526. #endif
  3527. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  3528. static DIR *
  3529. mg_opendir(const struct mg_connection *conn, const char *name)
  3530. {
  3531. DIR *dir = NULL;
  3532. wchar_t wpath[PATH_MAX];
  3533. DWORD attrs;
  3534. if (name == NULL) {
  3535. SetLastError(ERROR_BAD_ARGUMENTS);
  3536. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  3537. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  3538. } else {
  3539. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  3540. attrs = GetFileAttributesW(wpath);
  3541. if (attrs != 0xFFFFFFFF && ((attrs & FILE_ATTRIBUTE_DIRECTORY)
  3542. == FILE_ATTRIBUTE_DIRECTORY)) {
  3543. (void)wcscat(wpath, L"\\*");
  3544. dir->handle = FindFirstFileW(wpath, &dir->info);
  3545. dir->result.d_name[0] = '\0';
  3546. } else {
  3547. mg_free(dir);
  3548. dir = NULL;
  3549. }
  3550. }
  3551. return dir;
  3552. }
  3553. static int
  3554. mg_closedir(DIR *dir)
  3555. {
  3556. int result = 0;
  3557. if (dir != NULL) {
  3558. if (dir->handle != INVALID_HANDLE_VALUE)
  3559. result = FindClose(dir->handle) ? 0 : -1;
  3560. mg_free(dir);
  3561. } else {
  3562. result = -1;
  3563. SetLastError(ERROR_BAD_ARGUMENTS);
  3564. }
  3565. return result;
  3566. }
  3567. static struct dirent *
  3568. mg_readdir(DIR *dir)
  3569. {
  3570. struct dirent *result = 0;
  3571. if (dir) {
  3572. if (dir->handle != INVALID_HANDLE_VALUE) {
  3573. result = &dir->result;
  3574. (void)WideCharToMultiByte(CP_UTF8,
  3575. 0,
  3576. dir->info.cFileName,
  3577. -1,
  3578. result->d_name,
  3579. sizeof(result->d_name),
  3580. NULL,
  3581. NULL);
  3582. if (!FindNextFileW(dir->handle, &dir->info)) {
  3583. (void)FindClose(dir->handle);
  3584. dir->handle = INVALID_HANDLE_VALUE;
  3585. }
  3586. } else {
  3587. SetLastError(ERROR_FILE_NOT_FOUND);
  3588. }
  3589. } else {
  3590. SetLastError(ERROR_BAD_ARGUMENTS);
  3591. }
  3592. return result;
  3593. }
  3594. #ifndef HAVE_POLL
  3595. static int
  3596. poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  3597. {
  3598. struct timeval tv;
  3599. fd_set set;
  3600. unsigned int i;
  3601. int result;
  3602. SOCKET maxfd = 0;
  3603. memset(&tv, 0, sizeof(tv));
  3604. tv.tv_sec = milliseconds / 1000;
  3605. tv.tv_usec = (milliseconds % 1000) * 1000;
  3606. FD_ZERO(&set);
  3607. for (i = 0; i < n; i++) {
  3608. FD_SET((SOCKET)pfd[i].fd, &set);
  3609. pfd[i].revents = 0;
  3610. if (pfd[i].fd > maxfd) {
  3611. maxfd = pfd[i].fd;
  3612. }
  3613. }
  3614. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  3615. for (i = 0; i < n; i++) {
  3616. if (FD_ISSET(pfd[i].fd, &set)) {
  3617. pfd[i].revents = POLLIN;
  3618. }
  3619. }
  3620. }
  3621. /* We should subtract the time used in select from remaining
  3622. * "milliseconds", in particular if called from mg_poll with a
  3623. * timeout quantum.
  3624. * Unfortunately, the remaining time is not stored in "tv" in all
  3625. * implementations, so the result in "tv" must be considered undefined.
  3626. * See http://man7.org/linux/man-pages/man2/select.2.html */
  3627. return result;
  3628. }
  3629. #endif /* HAVE_POLL */
  3630. #if defined(__MINGW32__)
  3631. /* Enable unused function warning again */
  3632. #pragma GCC diagnostic pop
  3633. #endif
  3634. static void
  3635. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  3636. {
  3637. (void)conn; /* Unused. */
  3638. #if defined(_WIN32_WCE)
  3639. (void)sock;
  3640. #else
  3641. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  3642. #endif
  3643. }
  3644. int
  3645. mg_start_thread(mg_thread_func_t f, void *p)
  3646. {
  3647. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3648. /* Compile-time option to control stack size, e.g. -DUSE_STACK_SIZE=16384
  3649. */
  3650. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  3651. == ((uintptr_t)(-1L)))
  3652. ? -1
  3653. : 0);
  3654. #else
  3655. return (
  3656. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  3657. ? -1
  3658. : 0);
  3659. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3660. }
  3661. /* Start a thread storing the thread context. */
  3662. static int
  3663. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  3664. void *p,
  3665. pthread_t *threadidptr)
  3666. {
  3667. uintptr_t uip;
  3668. HANDLE threadhandle;
  3669. int result = -1;
  3670. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  3671. threadhandle = (HANDLE)uip;
  3672. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  3673. *threadidptr = threadhandle;
  3674. result = 0;
  3675. }
  3676. return result;
  3677. }
  3678. /* Wait for a thread to finish. */
  3679. static int
  3680. mg_join_thread(pthread_t threadid)
  3681. {
  3682. int result;
  3683. DWORD dwevent;
  3684. result = -1;
  3685. dwevent = WaitForSingleObject(threadid, INFINITE);
  3686. if (dwevent == WAIT_FAILED) {
  3687. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  3688. } else {
  3689. if (dwevent == WAIT_OBJECT_0) {
  3690. CloseHandle(threadid);
  3691. result = 0;
  3692. }
  3693. }
  3694. return result;
  3695. }
  3696. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  3697. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  3698. /* Create substitutes for POSIX functions in Win32. */
  3699. #if defined(__MINGW32__)
  3700. /* Show no warning in case system functions are not used. */
  3701. #pragma GCC diagnostic push
  3702. #pragma GCC diagnostic ignored "-Wunused-function"
  3703. #endif
  3704. static HANDLE
  3705. dlopen(const char *dll_name, int flags)
  3706. {
  3707. wchar_t wbuf[PATH_MAX];
  3708. (void)flags;
  3709. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  3710. return LoadLibraryW(wbuf);
  3711. }
  3712. static int
  3713. dlclose(void *handle)
  3714. {
  3715. int result;
  3716. if (FreeLibrary((HMODULE)handle) != 0) {
  3717. result = 0;
  3718. } else {
  3719. result = -1;
  3720. }
  3721. return result;
  3722. }
  3723. #if defined(__MINGW32__)
  3724. /* Enable unused function warning again */
  3725. #pragma GCC diagnostic pop
  3726. #endif
  3727. #endif
  3728. #if !defined(NO_CGI)
  3729. #define SIGKILL (0)
  3730. static int
  3731. kill(pid_t pid, int sig_num)
  3732. {
  3733. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  3734. (void)CloseHandle((HANDLE)pid);
  3735. return 0;
  3736. }
  3737. static void
  3738. trim_trailing_whitespaces(char *s)
  3739. {
  3740. char *e = s + strlen(s) - 1;
  3741. while (e > s && isspace(*(unsigned char *)e)) {
  3742. *e-- = '\0';
  3743. }
  3744. }
  3745. static pid_t
  3746. spawn_process(struct mg_connection *conn,
  3747. const char *prog,
  3748. char *envblk,
  3749. char *envp[],
  3750. int fdin[2],
  3751. int fdout[2],
  3752. int fderr[2],
  3753. const char *dir)
  3754. {
  3755. HANDLE me;
  3756. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  3757. cmdline[PATH_MAX], buf[PATH_MAX];
  3758. int truncated;
  3759. struct mg_file file = STRUCT_FILE_INITIALIZER;
  3760. STARTUPINFOA si;
  3761. PROCESS_INFORMATION pi = {0};
  3762. (void)envp;
  3763. memset(&si, 0, sizeof(si));
  3764. si.cb = sizeof(si);
  3765. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  3766. si.wShowWindow = SW_HIDE;
  3767. me = GetCurrentProcess();
  3768. DuplicateHandle(me,
  3769. (HANDLE)_get_osfhandle(fdin[0]),
  3770. me,
  3771. &si.hStdInput,
  3772. 0,
  3773. TRUE,
  3774. DUPLICATE_SAME_ACCESS);
  3775. DuplicateHandle(me,
  3776. (HANDLE)_get_osfhandle(fdout[1]),
  3777. me,
  3778. &si.hStdOutput,
  3779. 0,
  3780. TRUE,
  3781. DUPLICATE_SAME_ACCESS);
  3782. DuplicateHandle(me,
  3783. (HANDLE)_get_osfhandle(fderr[1]),
  3784. me,
  3785. &si.hStdError,
  3786. 0,
  3787. TRUE,
  3788. DUPLICATE_SAME_ACCESS);
  3789. /* Mark handles that should not be inherited. See
  3790. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  3791. */
  3792. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  3793. HANDLE_FLAG_INHERIT,
  3794. 0);
  3795. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  3796. HANDLE_FLAG_INHERIT,
  3797. 0);
  3798. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  3799. HANDLE_FLAG_INHERIT,
  3800. 0);
  3801. /* If CGI file is a script, try to read the interpreter line */
  3802. interp = conn->ctx->config[CGI_INTERPRETER];
  3803. if (interp == NULL) {
  3804. buf[0] = buf[1] = '\0';
  3805. /* Read the first line of the script into the buffer */
  3806. mg_snprintf(
  3807. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  3808. if (truncated) {
  3809. pi.hProcess = (pid_t)-1;
  3810. goto spawn_cleanup;
  3811. }
  3812. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  3813. p = (char *)file.access.membuf;
  3814. mg_fgets(buf, sizeof(buf), &file, &p);
  3815. (void)mg_fclose(&file.access); /* ignore error on read only file */
  3816. buf[sizeof(buf) - 1] = '\0';
  3817. }
  3818. if (buf[0] == '#' && buf[1] == '!') {
  3819. trim_trailing_whitespaces(buf + 2);
  3820. } else {
  3821. buf[2] = '\0';
  3822. }
  3823. interp = buf + 2;
  3824. }
  3825. if (interp[0] != '\0') {
  3826. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  3827. interp = full_interp;
  3828. }
  3829. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  3830. if (interp[0] != '\0') {
  3831. mg_snprintf(conn,
  3832. &truncated,
  3833. cmdline,
  3834. sizeof(cmdline),
  3835. "\"%s\" \"%s\\%s\"",
  3836. interp,
  3837. full_dir,
  3838. prog);
  3839. } else {
  3840. mg_snprintf(conn,
  3841. &truncated,
  3842. cmdline,
  3843. sizeof(cmdline),
  3844. "\"%s\\%s\"",
  3845. full_dir,
  3846. prog);
  3847. }
  3848. if (truncated) {
  3849. pi.hProcess = (pid_t)-1;
  3850. goto spawn_cleanup;
  3851. }
  3852. DEBUG_TRACE("Running [%s]", cmdline);
  3853. if (CreateProcessA(NULL,
  3854. cmdline,
  3855. NULL,
  3856. NULL,
  3857. TRUE,
  3858. CREATE_NEW_PROCESS_GROUP,
  3859. envblk,
  3860. NULL,
  3861. &si,
  3862. &pi) == 0) {
  3863. mg_cry(
  3864. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  3865. pi.hProcess = (pid_t)-1;
  3866. /* goto spawn_cleanup; */
  3867. }
  3868. spawn_cleanup:
  3869. (void)CloseHandle(si.hStdOutput);
  3870. (void)CloseHandle(si.hStdError);
  3871. (void)CloseHandle(si.hStdInput);
  3872. if (pi.hThread != NULL) {
  3873. (void)CloseHandle(pi.hThread);
  3874. }
  3875. return (pid_t)pi.hProcess;
  3876. }
  3877. #endif /* !NO_CGI */
  3878. static int
  3879. set_blocking_mode(SOCKET sock, int blocking)
  3880. {
  3881. unsigned long non_blocking = !blocking;
  3882. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  3883. }
  3884. #else
  3885. static int
  3886. mg_stat(const struct mg_connection *conn,
  3887. const char *path,
  3888. struct mg_file_stat *filep)
  3889. {
  3890. struct stat st;
  3891. if (!filep) {
  3892. return 0;
  3893. }
  3894. memset(filep, 0, sizeof(*filep));
  3895. if (conn && is_file_in_memory(conn, path)) {
  3896. /* Quick fix (for 1.9.x): */
  3897. /* mg_stat must fill all fields, also for files in memory */
  3898. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  3899. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  3900. filep->size = tmp_file.stat.size;
  3901. filep->last_modified = time(NULL);
  3902. filep->location = 2;
  3903. /* TODO: for 1.10: restructure how files in memory are handled */
  3904. return 1;
  3905. }
  3906. if (0 == stat(path, &st)) {
  3907. filep->size = (uint64_t)(st.st_size);
  3908. filep->last_modified = st.st_mtime;
  3909. filep->is_directory = S_ISDIR(st.st_mode);
  3910. return 1;
  3911. }
  3912. return 0;
  3913. }
  3914. static void
  3915. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  3916. {
  3917. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  3918. if (conn) {
  3919. mg_cry(conn,
  3920. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  3921. __func__,
  3922. strerror(ERRNO));
  3923. }
  3924. }
  3925. }
  3926. int
  3927. mg_start_thread(mg_thread_func_t func, void *param)
  3928. {
  3929. pthread_t thread_id;
  3930. pthread_attr_t attr;
  3931. int result;
  3932. (void)pthread_attr_init(&attr);
  3933. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  3934. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3935. /* Compile-time option to control stack size,
  3936. * e.g. -DUSE_STACK_SIZE=16384 */
  3937. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3938. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3939. result = pthread_create(&thread_id, &attr, func, param);
  3940. pthread_attr_destroy(&attr);
  3941. return result;
  3942. }
  3943. /* Start a thread storing the thread context. */
  3944. static int
  3945. mg_start_thread_with_id(mg_thread_func_t func,
  3946. void *param,
  3947. pthread_t *threadidptr)
  3948. {
  3949. pthread_t thread_id;
  3950. pthread_attr_t attr;
  3951. int result;
  3952. (void)pthread_attr_init(&attr);
  3953. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3954. /* Compile-time option to control stack size,
  3955. * e.g. -DUSE_STACK_SIZE=16384 */
  3956. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3957. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  3958. result = pthread_create(&thread_id, &attr, func, param);
  3959. pthread_attr_destroy(&attr);
  3960. if ((result == 0) && (threadidptr != NULL)) {
  3961. *threadidptr = thread_id;
  3962. }
  3963. return result;
  3964. }
  3965. /* Wait for a thread to finish. */
  3966. static int
  3967. mg_join_thread(pthread_t threadid)
  3968. {
  3969. int result;
  3970. result = pthread_join(threadid, NULL);
  3971. return result;
  3972. }
  3973. #ifndef NO_CGI
  3974. static pid_t
  3975. spawn_process(struct mg_connection *conn,
  3976. const char *prog,
  3977. char *envblk,
  3978. char *envp[],
  3979. int fdin[2],
  3980. int fdout[2],
  3981. int fderr[2],
  3982. const char *dir)
  3983. {
  3984. pid_t pid;
  3985. const char *interp;
  3986. (void)envblk;
  3987. if (conn == NULL) {
  3988. return 0;
  3989. }
  3990. if ((pid = fork()) == -1) {
  3991. /* Parent */
  3992. mg_send_http_error(conn,
  3993. 500,
  3994. "Error: Creating CGI process\nfork(): %s",
  3995. strerror(ERRNO));
  3996. } else if (pid == 0) {
  3997. /* Child */
  3998. if (chdir(dir) != 0) {
  3999. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  4000. } else if (dup2(fdin[0], 0) == -1) {
  4001. mg_cry(conn,
  4002. "%s: dup2(%d, 0): %s",
  4003. __func__,
  4004. fdin[0],
  4005. strerror(ERRNO));
  4006. } else if (dup2(fdout[1], 1) == -1) {
  4007. mg_cry(conn,
  4008. "%s: dup2(%d, 1): %s",
  4009. __func__,
  4010. fdout[1],
  4011. strerror(ERRNO));
  4012. } else if (dup2(fderr[1], 2) == -1) {
  4013. mg_cry(conn,
  4014. "%s: dup2(%d, 2): %s",
  4015. __func__,
  4016. fderr[1],
  4017. strerror(ERRNO));
  4018. } else {
  4019. /* Keep stderr and stdout in two different pipes.
  4020. * Stdout will be sent back to the client,
  4021. * stderr should go into a server error log. */
  4022. (void)close(fdin[0]);
  4023. (void)close(fdout[1]);
  4024. (void)close(fderr[1]);
  4025. /* Close write end fdin and read end fdout and fderr */
  4026. (void)close(fdin[1]);
  4027. (void)close(fdout[0]);
  4028. (void)close(fderr[0]);
  4029. /* After exec, all signal handlers are restored to their default
  4030. * values, with one exception of SIGCHLD. According to
  4031. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler will
  4032. * leave unchanged after exec if it was set to be ignored. Restore
  4033. * it to default action. */
  4034. signal(SIGCHLD, SIG_DFL);
  4035. interp = conn->ctx->config[CGI_INTERPRETER];
  4036. if (interp == NULL) {
  4037. (void)execle(prog, prog, NULL, envp);
  4038. mg_cry(conn,
  4039. "%s: execle(%s): %s",
  4040. __func__,
  4041. prog,
  4042. strerror(ERRNO));
  4043. } else {
  4044. (void)execle(interp, interp, prog, NULL, envp);
  4045. mg_cry(conn,
  4046. "%s: execle(%s %s): %s",
  4047. __func__,
  4048. interp,
  4049. prog,
  4050. strerror(ERRNO));
  4051. }
  4052. }
  4053. exit(EXIT_FAILURE);
  4054. }
  4055. return pid;
  4056. }
  4057. #endif /* !NO_CGI */
  4058. static int
  4059. set_blocking_mode(SOCKET sock, int blocking)
  4060. {
  4061. int flags;
  4062. flags = fcntl(sock, F_GETFL, 0);
  4063. if (blocking) {
  4064. (void)fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  4065. } else {
  4066. (void)fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK)));
  4067. }
  4068. return 0;
  4069. }
  4070. #endif /* _WIN32 */
  4071. /* End of initial operating system specific define block. */
  4072. /* Get a random number (independent of C rand function) */
  4073. static uint64_t
  4074. get_random(void)
  4075. {
  4076. static uint64_t lfsr = 0; /* Linear feedback shift register */
  4077. static uint64_t lcg = 0; /* Linear congruential generator */
  4078. uint64_t now = mg_get_current_time_ns();
  4079. if (lfsr == 0) {
  4080. /* lfsr will be only 0 if has not been initialized,
  4081. * so this code is called only once. */
  4082. lfsr = mg_get_current_time_ns();
  4083. lcg = mg_get_current_time_ns();
  4084. } else {
  4085. /* Get the next step of both random number generators. */
  4086. lfsr = (lfsr >> 1)
  4087. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  4088. << 63);
  4089. lcg = lcg * 6364136223846793005 + 1442695040888963407;
  4090. }
  4091. /* Combining two pseudo-random number generators and a high resolution part
  4092. * of the current server time will make it hard (impossible?) to guess the
  4093. * next number. */
  4094. return (lfsr ^ lcg ^ now);
  4095. }
  4096. static int
  4097. mg_poll(struct pollfd *pfd,
  4098. unsigned int n,
  4099. int milliseconds,
  4100. volatile int *stop_server)
  4101. {
  4102. int ms_now, result;
  4103. /* Call poll, but only for a maximum time of a few seconds.
  4104. * This will allow to stop the server after some seconds, instead
  4105. * of having to wait for a long socket timeout. */
  4106. ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  4107. do {
  4108. if (*stop_server) {
  4109. /* Shut down signal */
  4110. return -2;
  4111. }
  4112. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  4113. ms_now = milliseconds;
  4114. }
  4115. result = poll(pfd, n, ms_now);
  4116. if (result != 0) {
  4117. /* Poll returned either success (1) or error (-1).
  4118. * Forward both to the caller. */
  4119. return result;
  4120. }
  4121. /* Poll returned timeout (0). */
  4122. if (milliseconds > 0) {
  4123. milliseconds -= ms_now;
  4124. }
  4125. } while (milliseconds != 0);
  4126. return result;
  4127. }
  4128. /* Write data to the IO channel - opened file descriptor, socket or SSL
  4129. * descriptor. Return number of bytes written. */
  4130. static int
  4131. push(struct mg_context *ctx,
  4132. FILE *fp,
  4133. SOCKET sock,
  4134. SSL *ssl,
  4135. const char *buf,
  4136. int len,
  4137. double timeout)
  4138. {
  4139. uint64_t start = 0, now = 0, timeout_ns = 0;
  4140. int n, err;
  4141. #ifdef _WIN32
  4142. typedef int len_t;
  4143. #else
  4144. typedef size_t len_t;
  4145. #endif
  4146. if (timeout > 0) {
  4147. start = mg_get_current_time_ns();
  4148. timeout_ns = (uint64_t)(timeout * 1.0E9);
  4149. }
  4150. if (ctx == NULL) {
  4151. return -1;
  4152. }
  4153. #ifdef NO_SSL
  4154. if (ssl) {
  4155. return -1;
  4156. }
  4157. #endif
  4158. do {
  4159. #ifndef NO_SSL
  4160. if (ssl != NULL) {
  4161. n = SSL_write(ssl, buf, len);
  4162. if (n <= 0) {
  4163. err = SSL_get_error(ssl, n);
  4164. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  4165. err = ERRNO;
  4166. } else if ((err == SSL_ERROR_WANT_READ)
  4167. || (err == SSL_ERROR_WANT_WRITE)) {
  4168. n = 0;
  4169. } else {
  4170. DEBUG_TRACE("SSL_write() failed, error %d", err);
  4171. return -1;
  4172. }
  4173. } else {
  4174. err = 0;
  4175. }
  4176. } else
  4177. #endif
  4178. if (fp != NULL) {
  4179. n = (int)fwrite(buf, 1, (size_t)len, fp);
  4180. if (ferror(fp)) {
  4181. n = -1;
  4182. err = ERRNO;
  4183. } else {
  4184. err = 0;
  4185. }
  4186. } else {
  4187. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  4188. err = (n < 0) ? ERRNO : 0;
  4189. #ifdef _WIN32
  4190. if (err == WSAEWOULDBLOCK) {
  4191. err = 0;
  4192. n = 0;
  4193. }
  4194. #else
  4195. if (err == EWOULDBLOCK) {
  4196. err = 0;
  4197. n = 0;
  4198. }
  4199. #endif
  4200. if (n < 0) {
  4201. /* shutdown of the socket at client side */
  4202. return -1;
  4203. }
  4204. }
  4205. if (ctx->stop_flag) {
  4206. return -1;
  4207. }
  4208. if ((n > 0) || (n == 0 && len == 0)) {
  4209. /* some data has been read, or no data was requested */
  4210. return n;
  4211. }
  4212. if (n < 0) {
  4213. /* socket error - check errno */
  4214. DEBUG_TRACE("send() failed, error %d", err);
  4215. /* TODO (mid): error handling depending on the error code.
  4216. * These codes are different between Windows and Linux.
  4217. * Currently there is no problem with failing send calls,
  4218. * if there is a reproducible situation, it should be
  4219. * investigated in detail.
  4220. */
  4221. return -1;
  4222. }
  4223. /* Only in case n=0 (timeout), repeat calling the write function */
  4224. if (timeout >= 0) {
  4225. now = mg_get_current_time_ns();
  4226. }
  4227. } while ((timeout <= 0) || ((now - start) <= timeout_ns));
  4228. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  4229. used */
  4230. return -1;
  4231. }
  4232. static int64_t
  4233. push_all(struct mg_context *ctx,
  4234. FILE *fp,
  4235. SOCKET sock,
  4236. SSL *ssl,
  4237. const char *buf,
  4238. int64_t len)
  4239. {
  4240. double timeout = -1.0;
  4241. int64_t n, nwritten = 0;
  4242. if (ctx == NULL) {
  4243. return -1;
  4244. }
  4245. if (ctx->config[REQUEST_TIMEOUT]) {
  4246. timeout = atoi(ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  4247. }
  4248. while (len > 0 && ctx->stop_flag == 0) {
  4249. n = push(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  4250. if (n < 0) {
  4251. if (nwritten == 0) {
  4252. nwritten = n; /* Propagate the error */
  4253. }
  4254. break;
  4255. } else if (n == 0) {
  4256. break; /* No more data to write */
  4257. } else {
  4258. nwritten += n;
  4259. len -= n;
  4260. }
  4261. }
  4262. return nwritten;
  4263. }
  4264. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  4265. * Return value:
  4266. * >=0 .. number of bytes successfully read
  4267. * -1 .. timeout
  4268. * -2 .. error
  4269. */
  4270. static int
  4271. pull_inner(FILE *fp,
  4272. struct mg_connection *conn,
  4273. char *buf,
  4274. int len,
  4275. double timeout)
  4276. {
  4277. int nread, err = 0;
  4278. #ifdef _WIN32
  4279. typedef int len_t;
  4280. #else
  4281. typedef size_t len_t;
  4282. #endif
  4283. #ifndef NO_SSL
  4284. int ssl_pending;
  4285. #endif
  4286. /* We need an additional wait loop around this, because in some cases
  4287. * with TLSwe may get data from the socket but not from SSL_read.
  4288. * In this case we need to repeat at least once.
  4289. */
  4290. if (fp != NULL) {
  4291. #if !defined(_WIN32_WCE)
  4292. /* Use read() instead of fread(), because if we're reading from the
  4293. * CGI pipe, fread() may block until IO buffer is filled up. We
  4294. * cannot afford to block and must pass all read bytes immediately
  4295. * to the client. */
  4296. nread = (int)read(fileno(fp), buf, (size_t)len);
  4297. #else
  4298. /* WinCE does not support CGI pipes */
  4299. nread = (int)fread(buf, 1, (size_t)len, fp);
  4300. #endif
  4301. err = (nread < 0) ? ERRNO : 0;
  4302. #ifndef NO_SSL
  4303. } else if ((conn->ssl != NULL)
  4304. && ((ssl_pending = SSL_pending(conn->ssl)) > 0)) {
  4305. /* We already know there is no more data buffered in conn->buf
  4306. * but there is more available in the SSL layer. So don't poll
  4307. * conn->client.sock yet. */
  4308. if (ssl_pending > len) {
  4309. ssl_pending = len;
  4310. }
  4311. nread = SSL_read(conn->ssl, buf, ssl_pending);
  4312. if (nread <= 0) {
  4313. err = SSL_get_error(conn->ssl, nread);
  4314. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  4315. err = ERRNO;
  4316. } else if ((err == SSL_ERROR_WANT_READ)
  4317. || (err == SSL_ERROR_WANT_WRITE)) {
  4318. nread = 0;
  4319. } else {
  4320. DEBUG_TRACE("SSL_read() failed, error %d", err);
  4321. return -1;
  4322. }
  4323. } else {
  4324. err = 0;
  4325. }
  4326. } else if (conn->ssl != NULL) {
  4327. struct pollfd pfd[1];
  4328. int pollres;
  4329. pfd[0].fd = conn->client.sock;
  4330. pfd[0].events = POLLIN;
  4331. pollres =
  4332. mg_poll(pfd, 1, (int)(timeout * 1000.0), &(conn->ctx->stop_flag));
  4333. if (conn->ctx->stop_flag) {
  4334. return -2;
  4335. }
  4336. if (pollres > 0) {
  4337. nread = SSL_read(conn->ssl, buf, len);
  4338. if (nread <= 0) {
  4339. err = SSL_get_error(conn->ssl, nread);
  4340. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  4341. err = ERRNO;
  4342. } else if ((err == SSL_ERROR_WANT_READ)
  4343. || (err == SSL_ERROR_WANT_WRITE)) {
  4344. nread = 0;
  4345. } else {
  4346. DEBUG_TRACE("SSL_read() failed, error %d", err);
  4347. return -2;
  4348. }
  4349. } else {
  4350. err = 0;
  4351. }
  4352. } else if (pollres < 0) {
  4353. /* Error */
  4354. return -2;
  4355. } else {
  4356. /* pollres = 0 means timeout */
  4357. nread = 0;
  4358. }
  4359. #endif
  4360. } else {
  4361. struct pollfd pfd[1];
  4362. int pollres;
  4363. pfd[0].fd = conn->client.sock;
  4364. pfd[0].events = POLLIN;
  4365. pollres =
  4366. mg_poll(pfd, 1, (int)(timeout * 1000.0), &(conn->ctx->stop_flag));
  4367. if (conn->ctx->stop_flag) {
  4368. return -2;
  4369. }
  4370. if (pollres > 0) {
  4371. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  4372. err = (nread < 0) ? ERRNO : 0;
  4373. if (nread <= 0) {
  4374. /* shutdown of the socket at client side */
  4375. return -2;
  4376. }
  4377. } else if (pollres < 0) {
  4378. /* error callint poll */
  4379. return -2;
  4380. } else {
  4381. /* pollres = 0 means timeout */
  4382. nread = 0;
  4383. }
  4384. }
  4385. if (conn->ctx->stop_flag) {
  4386. return -2;
  4387. }
  4388. if ((nread > 0) || (nread == 0 && len == 0)) {
  4389. /* some data has been read, or no data was requested */
  4390. return nread;
  4391. }
  4392. if (nread < 0) {
  4393. /* socket error - check errno */
  4394. #ifdef _WIN32
  4395. if (err == WSAEWOULDBLOCK) {
  4396. /* TODO (low): check if this is still required */
  4397. /* standard case if called from close_socket_gracefully */
  4398. return -2;
  4399. } else if (err == WSAETIMEDOUT) {
  4400. /* TODO (low): check if this is still required */
  4401. /* timeout is handled by the while loop */
  4402. return 0;
  4403. } else if (err == WSAECONNABORTED) {
  4404. /* See https://www.chilkatsoft.com/p/p_299.asp */
  4405. return -2;
  4406. } else {
  4407. DEBUG_TRACE("recv() failed, error %d", err);
  4408. return -2;
  4409. }
  4410. #else
  4411. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  4412. * if the timeout is reached and if the socket was set to non-
  4413. * blocking in close_socket_gracefully, so we can not distinguish
  4414. * here. We have to wait for the timeout in both cases for now.
  4415. */
  4416. if (err == EAGAIN || err == EWOULDBLOCK || err == EINTR) {
  4417. /* TODO (low): check if this is still required */
  4418. /* EAGAIN/EWOULDBLOCK:
  4419. * standard case if called from close_socket_gracefully
  4420. * => should return -1 */
  4421. /* or timeout occured
  4422. * => the code must stay in the while loop */
  4423. /* EINTR can be generated on a socket with a timeout set even
  4424. * when SA_RESTART is effective for all relevant signals
  4425. * (see signal(7)).
  4426. * => stay in the while loop */
  4427. } else {
  4428. DEBUG_TRACE("recv() failed, error %d", err);
  4429. return -2;
  4430. }
  4431. #endif
  4432. }
  4433. /* Timeout occured, but no data available. */
  4434. return -1;
  4435. }
  4436. static int
  4437. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  4438. {
  4439. int n, nread = 0;
  4440. double timeout = -1.0;
  4441. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  4442. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  4443. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  4444. }
  4445. if (timeout >= 0.0) {
  4446. start_time = mg_get_current_time_ns();
  4447. timeout_ns = (uint64_t)(timeout * 1.0E9);
  4448. }
  4449. while (len > 0 && conn->ctx->stop_flag == 0) {
  4450. n = pull_inner(fp, conn, buf + nread, len, timeout);
  4451. if (n == -2) {
  4452. if (nread == 0) {
  4453. nread = -1; /* Propagate the error */
  4454. }
  4455. break;
  4456. } else if (n == -1) {
  4457. /* timeout */
  4458. if (timeout >= 0.0) {
  4459. now = mg_get_current_time_ns();
  4460. if ((now - start_time) <= timeout_ns) {
  4461. continue;
  4462. }
  4463. }
  4464. break;
  4465. } else if (n == 0) {
  4466. break; /* No more data to read */
  4467. } else {
  4468. conn->consumed_content += n;
  4469. nread += n;
  4470. len -= n;
  4471. }
  4472. }
  4473. return nread;
  4474. }
  4475. static void
  4476. discard_unread_request_data(struct mg_connection *conn)
  4477. {
  4478. char buf[MG_BUF_LEN];
  4479. size_t to_read;
  4480. int nread;
  4481. if (conn == NULL) {
  4482. return;
  4483. }
  4484. to_read = sizeof(buf);
  4485. if (conn->is_chunked) {
  4486. /* Chunked encoding: 1=chunk not read completely, 2=chunk read
  4487. * completely */
  4488. while (conn->is_chunked == 1) {
  4489. nread = mg_read(conn, buf, to_read);
  4490. if (nread <= 0) {
  4491. break;
  4492. }
  4493. }
  4494. } else {
  4495. /* Not chunked: content length is known */
  4496. while (conn->consumed_content < conn->content_len) {
  4497. if (to_read
  4498. > (size_t)(conn->content_len - conn->consumed_content)) {
  4499. to_read = (size_t)(conn->content_len - conn->consumed_content);
  4500. }
  4501. nread = mg_read(conn, buf, to_read);
  4502. if (nread <= 0) {
  4503. break;
  4504. }
  4505. }
  4506. }
  4507. }
  4508. static int
  4509. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  4510. {
  4511. int64_t n, buffered_len, nread;
  4512. int64_t len64 =
  4513. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  4514. * int, we may not read more
  4515. * bytes */
  4516. const char *body;
  4517. if (conn == NULL) {
  4518. return 0;
  4519. }
  4520. /* If Content-Length is not set for a PUT or POST request, read until
  4521. * socket is closed */
  4522. if (conn->consumed_content == 0 && conn->content_len == -1) {
  4523. conn->content_len = INT64_MAX;
  4524. conn->must_close = 1;
  4525. }
  4526. nread = 0;
  4527. if (conn->consumed_content < conn->content_len) {
  4528. /* Adjust number of bytes to read. */
  4529. int64_t left_to_read = conn->content_len - conn->consumed_content;
  4530. if (left_to_read < len64) {
  4531. /* Do not read more than the total content length of the request.
  4532. */
  4533. len64 = left_to_read;
  4534. }
  4535. /* Return buffered data */
  4536. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  4537. - conn->consumed_content;
  4538. if (buffered_len > 0) {
  4539. if (len64 < buffered_len) {
  4540. buffered_len = len64;
  4541. }
  4542. body = conn->buf + conn->request_len + conn->consumed_content;
  4543. memcpy(buf, body, (size_t)buffered_len);
  4544. len64 -= buffered_len;
  4545. conn->consumed_content += buffered_len;
  4546. nread += buffered_len;
  4547. buf = (char *)buf + buffered_len;
  4548. }
  4549. /* We have returned all buffered data. Read new data from the remote
  4550. * socket.
  4551. */
  4552. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  4553. nread += n;
  4554. } else {
  4555. nread = ((nread > 0) ? nread : n);
  4556. }
  4557. }
  4558. return (int)nread;
  4559. }
  4560. static char
  4561. mg_getc(struct mg_connection *conn)
  4562. {
  4563. char c;
  4564. if (conn == NULL) {
  4565. return 0;
  4566. }
  4567. conn->content_len++;
  4568. if (mg_read_inner(conn, &c, 1) <= 0) {
  4569. return (char)0;
  4570. }
  4571. return c;
  4572. }
  4573. int
  4574. mg_read(struct mg_connection *conn, void *buf, size_t len)
  4575. {
  4576. if (len > INT_MAX) {
  4577. len = INT_MAX;
  4578. }
  4579. if (conn == NULL) {
  4580. return 0;
  4581. }
  4582. if (conn->is_chunked) {
  4583. size_t all_read = 0;
  4584. while (len > 0) {
  4585. if (conn->is_chunked == 2) {
  4586. /* No more data left to read */
  4587. return 0;
  4588. }
  4589. if (conn->chunk_remainder) {
  4590. /* copy from the remainder of the last received chunk */
  4591. long read_ret;
  4592. size_t read_now =
  4593. ((conn->chunk_remainder > len) ? (len)
  4594. : (conn->chunk_remainder));
  4595. conn->content_len += (int)read_now;
  4596. read_ret =
  4597. mg_read_inner(conn, (char *)buf + all_read, read_now);
  4598. if (read_ret < 1) {
  4599. /* read error */
  4600. return -1;
  4601. }
  4602. all_read += (size_t)read_ret;
  4603. conn->chunk_remainder -= (size_t)read_ret;
  4604. len -= (size_t)read_ret;
  4605. if (conn->chunk_remainder == 0) {
  4606. /* Add data bytes in the current chunk have been read,
  4607. * so we are expecting \r\n now. */
  4608. char x1 = mg_getc(conn);
  4609. char x2 = mg_getc(conn);
  4610. if ((x1 != '\r') || (x2 != '\n')) {
  4611. /* Protocol violation */
  4612. return -1;
  4613. }
  4614. }
  4615. } else {
  4616. /* fetch a new chunk */
  4617. int i = 0;
  4618. char lenbuf[64];
  4619. char *end = 0;
  4620. unsigned long chunkSize = 0;
  4621. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  4622. lenbuf[i] = mg_getc(conn);
  4623. if (i > 0 && lenbuf[i] == '\r' && lenbuf[i - 1] != '\r') {
  4624. continue;
  4625. }
  4626. if (i > 1 && lenbuf[i] == '\n' && lenbuf[i - 1] == '\r') {
  4627. lenbuf[i + 1] = 0;
  4628. chunkSize = strtoul(lenbuf, &end, 16);
  4629. if (chunkSize == 0) {
  4630. /* regular end of content */
  4631. conn->is_chunked = 2;
  4632. }
  4633. break;
  4634. }
  4635. if (!isxdigit(lenbuf[i])) {
  4636. /* illegal character for chunk length */
  4637. return -1;
  4638. }
  4639. }
  4640. if ((end == NULL) || (*end != '\r')) {
  4641. /* chunksize not set correctly */
  4642. return -1;
  4643. }
  4644. if (chunkSize == 0) {
  4645. break;
  4646. }
  4647. conn->chunk_remainder = chunkSize;
  4648. }
  4649. }
  4650. return (int)all_read;
  4651. }
  4652. return mg_read_inner(conn, buf, len);
  4653. }
  4654. int
  4655. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  4656. {
  4657. time_t now;
  4658. int64_t n, total, allowed;
  4659. if (conn == NULL) {
  4660. return 0;
  4661. }
  4662. if (conn->throttle > 0) {
  4663. if ((now = time(NULL)) != conn->last_throttle_time) {
  4664. conn->last_throttle_time = now;
  4665. conn->last_throttle_bytes = 0;
  4666. }
  4667. allowed = conn->throttle - conn->last_throttle_bytes;
  4668. if (allowed > (int64_t)len) {
  4669. allowed = (int64_t)len;
  4670. }
  4671. if ((total = push_all(conn->ctx,
  4672. NULL,
  4673. conn->client.sock,
  4674. conn->ssl,
  4675. (const char *)buf,
  4676. (int64_t)allowed)) == allowed) {
  4677. buf = (const char *)buf + total;
  4678. conn->last_throttle_bytes += total;
  4679. while (total < (int64_t)len && conn->ctx->stop_flag == 0) {
  4680. allowed = (conn->throttle > ((int64_t)len - total))
  4681. ? (int64_t)len - total
  4682. : conn->throttle;
  4683. if ((n = push_all(conn->ctx,
  4684. NULL,
  4685. conn->client.sock,
  4686. conn->ssl,
  4687. (const char *)buf,
  4688. (int64_t)allowed)) != allowed) {
  4689. break;
  4690. }
  4691. sleep(1);
  4692. conn->last_throttle_bytes = allowed;
  4693. conn->last_throttle_time = time(NULL);
  4694. buf = (const char *)buf + n;
  4695. total += n;
  4696. }
  4697. }
  4698. } else {
  4699. total = push_all(conn->ctx,
  4700. NULL,
  4701. conn->client.sock,
  4702. conn->ssl,
  4703. (const char *)buf,
  4704. (int64_t)len);
  4705. }
  4706. return (int)total;
  4707. }
  4708. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  4709. int
  4710. mg_send_chunk(struct mg_connection *conn,
  4711. const char *chunk,
  4712. unsigned int chunk_len)
  4713. {
  4714. char lenbuf[16];
  4715. size_t lenbuf_len;
  4716. int ret;
  4717. int t;
  4718. /* First store the length information in a text buffer. */
  4719. sprintf(lenbuf, "%x\r\n", chunk_len);
  4720. lenbuf_len = strlen(lenbuf);
  4721. /* Then send length information, chunk and terminating \r\n. */
  4722. ret = mg_write(conn, lenbuf, lenbuf_len);
  4723. if (ret != (int)lenbuf_len) {
  4724. return -1;
  4725. }
  4726. t = ret;
  4727. ret = mg_write(conn, chunk, chunk_len);
  4728. if (ret != (int)chunk_len) {
  4729. return -1;
  4730. }
  4731. t += ret;
  4732. ret = mg_write(conn, "\r\n", 2);
  4733. if (ret != 2) {
  4734. return -1;
  4735. }
  4736. t += ret;
  4737. return t;
  4738. }
  4739. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  4740. static int
  4741. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  4742. {
  4743. va_list ap_copy;
  4744. size_t size = MG_BUF_LEN / 4;
  4745. int len = -1;
  4746. *buf = NULL;
  4747. while (len < 0) {
  4748. if (*buf) {
  4749. mg_free(*buf);
  4750. }
  4751. size *= 4;
  4752. *buf = (char *)mg_malloc(size);
  4753. if (!*buf) {
  4754. break;
  4755. }
  4756. va_copy(ap_copy, ap);
  4757. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  4758. va_end(ap_copy);
  4759. (*buf)[size - 1] = 0;
  4760. }
  4761. return len;
  4762. }
  4763. /* Print message to buffer. If buffer is large enough to hold the message,
  4764. * return buffer. If buffer is to small, allocate large enough buffer on heap,
  4765. * and return allocated buffer. */
  4766. static int
  4767. alloc_vprintf(char **out_buf,
  4768. char *prealloc_buf,
  4769. size_t prealloc_size,
  4770. const char *fmt,
  4771. va_list ap)
  4772. {
  4773. va_list ap_copy;
  4774. int len;
  4775. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  4776. * buffer is too small. Also, older versions of msvcrt.dll do not have
  4777. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  4778. * Therefore, we make two passes: on first pass, get required message
  4779. * length.
  4780. * On second pass, actually print the message. */
  4781. va_copy(ap_copy, ap);
  4782. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  4783. va_end(ap_copy);
  4784. if (len < 0) {
  4785. /* C runtime is not standard compliant, vsnprintf() returned -1.
  4786. * Switch to alternative code path that uses incremental allocations.
  4787. */
  4788. va_copy(ap_copy, ap);
  4789. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  4790. va_end(ap_copy);
  4791. } else if ((size_t)(len) >= prealloc_size) {
  4792. /* The pre-allocated buffer not large enough. */
  4793. /* Allocate a new buffer. */
  4794. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  4795. if (!*out_buf) {
  4796. /* Allocation failed. Return -1 as "out of memory" error. */
  4797. return -1;
  4798. }
  4799. /* Buffer allocation successful. Store the string there. */
  4800. va_copy(ap_copy, ap);
  4801. IGNORE_UNUSED_RESULT(
  4802. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  4803. va_end(ap_copy);
  4804. } else {
  4805. /* The pre-allocated buffer is large enough.
  4806. * Use it to store the string and return the address. */
  4807. va_copy(ap_copy, ap);
  4808. IGNORE_UNUSED_RESULT(
  4809. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  4810. va_end(ap_copy);
  4811. *out_buf = prealloc_buf;
  4812. }
  4813. return len;
  4814. }
  4815. static int
  4816. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  4817. {
  4818. char mem[MG_BUF_LEN];
  4819. char *buf = NULL;
  4820. int len;
  4821. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  4822. len = mg_write(conn, buf, (size_t)len);
  4823. }
  4824. if (buf != mem && buf != NULL) {
  4825. mg_free(buf);
  4826. }
  4827. return len;
  4828. }
  4829. int
  4830. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  4831. {
  4832. va_list ap;
  4833. int result;
  4834. va_start(ap, fmt);
  4835. result = mg_vprintf(conn, fmt, ap);
  4836. va_end(ap);
  4837. return result;
  4838. }
  4839. int
  4840. mg_url_decode(const char *src,
  4841. int src_len,
  4842. char *dst,
  4843. int dst_len,
  4844. int is_form_url_encoded)
  4845. {
  4846. int i, j, a, b;
  4847. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  4848. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  4849. if (i < src_len - 2 && src[i] == '%'
  4850. && isxdigit(*(const unsigned char *)(src + i + 1))
  4851. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  4852. a = tolower(*(const unsigned char *)(src + i + 1));
  4853. b = tolower(*(const unsigned char *)(src + i + 2));
  4854. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  4855. i += 2;
  4856. } else if (is_form_url_encoded && src[i] == '+') {
  4857. dst[j] = ' ';
  4858. } else {
  4859. dst[j] = src[i];
  4860. }
  4861. }
  4862. dst[j] = '\0'; /* Null-terminate the destination */
  4863. return (i >= src_len) ? j : -1;
  4864. }
  4865. int
  4866. mg_get_var(const char *data,
  4867. size_t data_len,
  4868. const char *name,
  4869. char *dst,
  4870. size_t dst_len)
  4871. {
  4872. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  4873. }
  4874. int
  4875. mg_get_var2(const char *data,
  4876. size_t data_len,
  4877. const char *name,
  4878. char *dst,
  4879. size_t dst_len,
  4880. size_t occurrence)
  4881. {
  4882. const char *p, *e, *s;
  4883. size_t name_len;
  4884. int len;
  4885. if (dst == NULL || dst_len == 0) {
  4886. len = -2;
  4887. } else if (data == NULL || name == NULL || data_len == 0) {
  4888. len = -1;
  4889. dst[0] = '\0';
  4890. } else {
  4891. name_len = strlen(name);
  4892. e = data + data_len;
  4893. len = -1;
  4894. dst[0] = '\0';
  4895. /* data is "var1=val1&var2=val2...". Find variable first */
  4896. for (p = data; p + name_len < e; p++) {
  4897. if ((p == data || p[-1] == '&') && p[name_len] == '='
  4898. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  4899. /* Point p to variable value */
  4900. p += name_len + 1;
  4901. /* Point s to the end of the value */
  4902. s = (const char *)memchr(p, '&', (size_t)(e - p));
  4903. if (s == NULL) {
  4904. s = e;
  4905. }
  4906. /* assert(s >= p); */
  4907. if (s < p) {
  4908. return -3;
  4909. }
  4910. /* Decode variable into destination buffer */
  4911. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  4912. /* Redirect error code from -1 to -2 (destination buffer too
  4913. * small). */
  4914. if (len == -1) {
  4915. len = -2;
  4916. }
  4917. break;
  4918. }
  4919. }
  4920. }
  4921. return len;
  4922. }
  4923. /* HCP24: some changes to compare hole var_name */
  4924. int
  4925. mg_get_cookie(const char *cookie_header,
  4926. const char *var_name,
  4927. char *dst,
  4928. size_t dst_size)
  4929. {
  4930. const char *s, *p, *end;
  4931. int name_len, len = -1;
  4932. if (dst == NULL || dst_size == 0) {
  4933. return -2;
  4934. }
  4935. dst[0] = '\0';
  4936. if (var_name == NULL || (s = cookie_header) == NULL) {
  4937. return -1;
  4938. }
  4939. name_len = (int)strlen(var_name);
  4940. end = s + strlen(s);
  4941. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  4942. if (s[name_len] == '=') {
  4943. /* HCP24: now check is it a substring or a full cookie name */
  4944. if ((s == cookie_header) || (s[-1] == ' ')) {
  4945. s += name_len + 1;
  4946. if ((p = strchr(s, ' ')) == NULL) {
  4947. p = end;
  4948. }
  4949. if (p[-1] == ';') {
  4950. p--;
  4951. }
  4952. if (*s == '"' && p[-1] == '"' && p > s + 1) {
  4953. s++;
  4954. p--;
  4955. }
  4956. if ((size_t)(p - s) < dst_size) {
  4957. len = (int)(p - s);
  4958. mg_strlcpy(dst, s, (size_t)len + 1);
  4959. } else {
  4960. len = -3;
  4961. }
  4962. break;
  4963. }
  4964. }
  4965. }
  4966. return len;
  4967. }
  4968. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  4969. static void
  4970. base64_encode(const unsigned char *src, int src_len, char *dst)
  4971. {
  4972. static const char *b64 =
  4973. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  4974. int i, j, a, b, c;
  4975. for (i = j = 0; i < src_len; i += 3) {
  4976. a = src[i];
  4977. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  4978. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  4979. dst[j++] = b64[a >> 2];
  4980. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  4981. if (i + 1 < src_len) {
  4982. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  4983. }
  4984. if (i + 2 < src_len) {
  4985. dst[j++] = b64[c & 63];
  4986. }
  4987. }
  4988. while (j % 4 != 0) {
  4989. dst[j++] = '=';
  4990. }
  4991. dst[j++] = '\0';
  4992. }
  4993. #endif
  4994. #if defined(USE_LUA)
  4995. static unsigned char
  4996. b64reverse(char letter)
  4997. {
  4998. if (letter >= 'A' && letter <= 'Z') {
  4999. return letter - 'A';
  5000. }
  5001. if (letter >= 'a' && letter <= 'z') {
  5002. return letter - 'a' + 26;
  5003. }
  5004. if (letter >= '0' && letter <= '9') {
  5005. return letter - '0' + 52;
  5006. }
  5007. if (letter == '+') {
  5008. return 62;
  5009. }
  5010. if (letter == '/') {
  5011. return 63;
  5012. }
  5013. if (letter == '=') {
  5014. return 255; /* normal end */
  5015. }
  5016. return 254; /* error */
  5017. }
  5018. static int
  5019. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  5020. {
  5021. int i;
  5022. unsigned char a, b, c, d;
  5023. *dst_len = 0;
  5024. for (i = 0; i < src_len; i += 4) {
  5025. a = b64reverse(src[i]);
  5026. if (a >= 254) {
  5027. return i;
  5028. }
  5029. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  5030. if (b >= 254) {
  5031. return i + 1;
  5032. }
  5033. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  5034. if (c == 254) {
  5035. return i + 2;
  5036. }
  5037. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  5038. if (d == 254) {
  5039. return i + 3;
  5040. }
  5041. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  5042. if (c != 255) {
  5043. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  5044. if (d != 255) {
  5045. dst[(*dst_len)++] = (c << 6) + d;
  5046. }
  5047. }
  5048. }
  5049. return -1;
  5050. }
  5051. #endif
  5052. static int
  5053. is_put_or_delete_method(const struct mg_connection *conn)
  5054. {
  5055. if (conn) {
  5056. const char *s = conn->request_info.request_method;
  5057. return s != NULL && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  5058. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  5059. }
  5060. return 0;
  5061. }
  5062. #if !defined(NO_FILES)
  5063. static int
  5064. extention_matches_script(
  5065. struct mg_connection *conn, /* in: request (must be valid) */
  5066. const char *filename /* in: filename (must be valid) */
  5067. )
  5068. {
  5069. #if !defined(NO_CGI)
  5070. if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  5071. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  5072. filename) > 0) {
  5073. return 1;
  5074. }
  5075. #endif
  5076. #if defined(USE_LUA)
  5077. if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  5078. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  5079. filename) > 0) {
  5080. return 1;
  5081. }
  5082. #endif
  5083. #if defined(USE_DUKTAPE)
  5084. if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  5085. strlen(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  5086. filename) > 0) {
  5087. return 1;
  5088. }
  5089. #endif
  5090. /* filename and conn could be unused, if all preocessor conditions
  5091. * are false (no script language supported). */
  5092. (void)filename;
  5093. (void)conn;
  5094. return 0;
  5095. }
  5096. /* For given directory path, substitute it to valid index file.
  5097. * Return 1 if index file has been found, 0 if not found.
  5098. * If the file is found, it's stats is returned in stp. */
  5099. static int
  5100. substitute_index_file(struct mg_connection *conn,
  5101. char *path,
  5102. size_t path_len,
  5103. struct mg_file_stat *filestat)
  5104. {
  5105. const char *list = conn->ctx->config[INDEX_FILES];
  5106. struct vec filename_vec;
  5107. size_t n = strlen(path);
  5108. int found = 0;
  5109. /* The 'path' given to us points to the directory. Remove all trailing
  5110. * directory separator characters from the end of the path, and
  5111. * then append single directory separator character. */
  5112. while (n > 0 && path[n - 1] == '/') {
  5113. n--;
  5114. }
  5115. path[n] = '/';
  5116. /* Traverse index files list. For each entry, append it to the given
  5117. * path and see if the file exists. If it exists, break the loop */
  5118. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  5119. /* Ignore too long entries that may overflow path buffer */
  5120. if (filename_vec.len > path_len - (n + 2)) {
  5121. continue;
  5122. }
  5123. /* Prepare full path to the index file */
  5124. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  5125. /* Does it exist? */
  5126. if (mg_stat(conn, path, filestat)) {
  5127. /* Yes it does, break the loop */
  5128. found = 1;
  5129. break;
  5130. }
  5131. }
  5132. /* If no index file exists, restore directory path */
  5133. if (!found) {
  5134. path[n] = '\0';
  5135. }
  5136. return found;
  5137. }
  5138. #endif
  5139. static void
  5140. interpret_uri(struct mg_connection *conn, /* in: request (must be valid) */
  5141. char *filename, /* out: filename */
  5142. size_t filename_buf_len, /* in: size of filename buffer */
  5143. struct mg_file_stat *filestat, /* out: file status structure */
  5144. int *is_found, /* out: file found (directly) */
  5145. int *is_script_resource, /* out: handled by a script? */
  5146. int *is_websocket_request, /* out: websocket connetion? */
  5147. int *is_put_or_delete_request /* out: put/delete a file? */
  5148. )
  5149. {
  5150. #if !defined(NO_FILES)
  5151. const char *uri = conn->request_info.local_uri;
  5152. const char *root = conn->ctx->config[DOCUMENT_ROOT];
  5153. const char *rewrite;
  5154. struct vec a, b;
  5155. int match_len;
  5156. char gz_path[PATH_MAX];
  5157. char const *accept_encoding;
  5158. int truncated;
  5159. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  5160. char *tmp_str;
  5161. size_t tmp_str_len, sep_pos;
  5162. #endif
  5163. #else
  5164. (void)filename_buf_len; /* unused if NO_FILES is defined */
  5165. #endif
  5166. /* Step 1: Set all initially unknown outputs to zero */
  5167. memset(filestat, 0, sizeof(*filestat));
  5168. *filename = 0;
  5169. *is_found = 0;
  5170. *is_script_resource = 0;
  5171. /* Step 2: Check if the request attempts to modify the file system */
  5172. *is_put_or_delete_request = is_put_or_delete_method(conn);
  5173. /* Step 3: Check if it is a websocket request, and modify the document
  5174. * root if required */
  5175. #if defined(USE_WEBSOCKET)
  5176. *is_websocket_request = is_websocket_protocol(conn);
  5177. #if !defined(NO_FILES)
  5178. if (*is_websocket_request && conn->ctx->config[WEBSOCKET_ROOT]) {
  5179. root = conn->ctx->config[WEBSOCKET_ROOT];
  5180. }
  5181. #endif /* !NO_FILES */
  5182. #else /* USE_WEBSOCKET */
  5183. *is_websocket_request = 0;
  5184. #endif /* USE_WEBSOCKET */
  5185. #if !defined(NO_FILES)
  5186. /* Step 4: If there is no root directory, don't look for files. */
  5187. /* Note that root == NULL is a regular use case here. This occurs,
  5188. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  5189. * config is not required. */
  5190. if (root == NULL) {
  5191. /* all file related outputs have already been set to 0, just return
  5192. */
  5193. return;
  5194. }
  5195. /* Step 5: Determine the local file path from the root path and the
  5196. * request uri. */
  5197. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  5198. * part of the path one byte on the right. */
  5199. mg_snprintf(
  5200. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  5201. if (truncated) {
  5202. goto interpret_cleanup;
  5203. }
  5204. /* Step 6: URI rewriting */
  5205. rewrite = conn->ctx->config[REWRITE];
  5206. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  5207. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  5208. mg_snprintf(conn,
  5209. &truncated,
  5210. filename,
  5211. filename_buf_len - 1,
  5212. "%.*s%s",
  5213. (int)b.len,
  5214. b.ptr,
  5215. uri + match_len);
  5216. break;
  5217. }
  5218. }
  5219. if (truncated) {
  5220. goto interpret_cleanup;
  5221. }
  5222. /* Step 7: Check if the file exists at the server */
  5223. /* Local file path and name, corresponding to requested URI
  5224. * is now stored in "filename" variable. */
  5225. if (mg_stat(conn, filename, filestat)) {
  5226. /* 7.1: File exists. */
  5227. *is_found = 1;
  5228. /* 7.2: Check if it is a script type. */
  5229. if (extention_matches_script(conn, filename)) {
  5230. /* The request addresses a CGI resource, Lua script or
  5231. * server-side javascript.
  5232. * The URI corresponds to the script itself (like
  5233. * /path/script.cgi), and there is no additional resource
  5234. * path (like /path/script.cgi/something).
  5235. * Requests that modify (replace or delete) a resource, like
  5236. * PUT and DELETE requests, should replace/delete the script
  5237. * file.
  5238. * Requests that read or write from/to a resource, like GET and
  5239. * POST requests, should call the script and return the
  5240. * generated response. */
  5241. *is_script_resource = (!*is_put_or_delete_request);
  5242. }
  5243. /* 7.3: If the request target is a directory, there could be
  5244. * a substitute file (index.html, index.cgi, ...). */
  5245. if (filestat->is_directory) {
  5246. /* Use a local copy here, since substitute_index_file will
  5247. * change the content of the file status */
  5248. struct mg_file_stat tmp_filestat;
  5249. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  5250. if (substitute_index_file(
  5251. conn, filename, filename_buf_len, &tmp_filestat)) {
  5252. /* Substitute file found. Copy stat to the output, then
  5253. * check if the file is a script file */
  5254. *filestat = tmp_filestat;
  5255. if (extention_matches_script(conn, filename)) {
  5256. /* Substitute file is a script file */
  5257. *is_script_resource = 1;
  5258. } else {
  5259. /* Substitute file is a regular file */
  5260. *is_script_resource = 0;
  5261. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  5262. }
  5263. }
  5264. /* If there is no substitute file, the server could return
  5265. * a directory listing in a later step */
  5266. }
  5267. return;
  5268. }
  5269. /* Step 8: Check for zipped files: */
  5270. /* If we can't find the actual file, look for the file
  5271. * with the same name but a .gz extension. If we find it,
  5272. * use that and set the gzipped flag in the file struct
  5273. * to indicate that the response need to have the content-
  5274. * encoding: gzip header.
  5275. * We can only do this if the browser declares support. */
  5276. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  5277. if (strstr(accept_encoding, "gzip") != NULL) {
  5278. mg_snprintf(
  5279. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  5280. if (truncated) {
  5281. goto interpret_cleanup;
  5282. }
  5283. if (mg_stat(conn, gz_path, filestat)) {
  5284. if (filestat) {
  5285. filestat->is_gzipped = 1;
  5286. *is_found = 1;
  5287. }
  5288. /* Currently gz files can not be scripts. */
  5289. return;
  5290. }
  5291. }
  5292. }
  5293. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  5294. /* Step 9: Script resources may handle sub-resources */
  5295. /* Support PATH_INFO for CGI scripts. */
  5296. tmp_str_len = strlen(filename);
  5297. tmp_str = mg_malloc(tmp_str_len + PATH_MAX + 1);
  5298. if (!tmp_str) {
  5299. /* Out of memory */
  5300. goto interpret_cleanup;
  5301. }
  5302. memcpy(tmp_str, filename, tmp_str_len + 1);
  5303. sep_pos = tmp_str_len;
  5304. while (sep_pos > 0) {
  5305. sep_pos--;
  5306. if (tmp_str[sep_pos] == '/') {
  5307. int is_script = 0, does_exist = 0;
  5308. tmp_str[sep_pos] = 0;
  5309. if (tmp_str[0]) {
  5310. is_script = extention_matches_script(conn, tmp_str);
  5311. does_exist = mg_stat(conn, tmp_str, filestat);
  5312. }
  5313. if (does_exist && is_script) {
  5314. filename[sep_pos] = 0;
  5315. memmove(filename + sep_pos + 2,
  5316. filename + sep_pos + 1,
  5317. strlen(filename + sep_pos + 1) + 1);
  5318. conn->path_info = filename + sep_pos + 1;
  5319. filename[sep_pos + 1] = '/';
  5320. *is_script_resource = 1;
  5321. *is_found = 1;
  5322. break;
  5323. }
  5324. if (substitute_index_file(
  5325. conn, tmp_str, tmp_str_len + PATH_MAX, filestat)) {
  5326. /* some intermediate directory has an index file */
  5327. if (extention_matches_script(conn, tmp_str)) {
  5328. /* this index file is a script */
  5329. char *tmp_str2 = mg_strdup(filename + sep_pos + 1);
  5330. mg_snprintf(conn,
  5331. &truncated,
  5332. filename,
  5333. filename_buf_len,
  5334. "%s//%s",
  5335. tmp_str,
  5336. tmp_str2);
  5337. mg_free(tmp_str2);
  5338. if (truncated) {
  5339. mg_free(tmp_str);
  5340. tmp_str = NULL;
  5341. goto interpret_cleanup;
  5342. }
  5343. sep_pos = strlen(tmp_str);
  5344. filename[sep_pos] = 0;
  5345. conn->path_info = filename + sep_pos + 1;
  5346. *is_script_resource = 1;
  5347. *is_found = 1;
  5348. break;
  5349. } else {
  5350. /* non-script files will not have sub-resources */
  5351. filename[sep_pos] = 0;
  5352. conn->path_info = 0;
  5353. *is_script_resource = 0;
  5354. *is_found = 0;
  5355. break;
  5356. }
  5357. }
  5358. tmp_str[sep_pos] = '/';
  5359. }
  5360. }
  5361. mg_free(tmp_str);
  5362. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  5363. #endif /* !defined(NO_FILES) */
  5364. return;
  5365. #if !defined(NO_FILES)
  5366. /* Reset all outputs */
  5367. interpret_cleanup:
  5368. memset(filestat, 0, sizeof(*filestat));
  5369. *filename = 0;
  5370. *is_found = 0;
  5371. *is_script_resource = 0;
  5372. *is_websocket_request = 0;
  5373. *is_put_or_delete_request = 0;
  5374. #endif /* !defined(NO_FILES) */
  5375. }
  5376. /* Check whether full request is buffered. Return:
  5377. * -1 if request is malformed
  5378. * 0 if request is not yet fully buffered
  5379. * >0 actual request length, including last \r\n\r\n */
  5380. static int
  5381. get_request_len(const char *buf, int buflen)
  5382. {
  5383. const char *s, *e;
  5384. int len = 0;
  5385. for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
  5386. /* Control characters are not allowed but >=128 is. */
  5387. if (!isprint(*(const unsigned char *)s) && *s != '\r' && *s != '\n'
  5388. && *(const unsigned char *)s < 128) {
  5389. len = -1;
  5390. break; /* [i_a] abort scan as soon as one malformed character is
  5391. * found; */
  5392. /* don't let subsequent \r\n\r\n win us over anyhow */
  5393. } else if (s[0] == '\n' && s[1] == '\n') {
  5394. len = (int)(s - buf) + 2;
  5395. } else if (s[0] == '\n' && &s[1] < e && s[1] == '\r' && s[2] == '\n') {
  5396. len = (int)(s - buf) + 3;
  5397. }
  5398. return len;
  5399. }
  5400. #if !defined(NO_CACHING)
  5401. /* Convert month to the month number. Return -1 on error, or month number */
  5402. static int
  5403. get_month_index(const char *s)
  5404. {
  5405. size_t i;
  5406. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  5407. if (!strcmp(s, month_names[i])) {
  5408. return (int)i;
  5409. }
  5410. }
  5411. return -1;
  5412. }
  5413. /* Parse UTC date-time string, and return the corresponding time_t value. */
  5414. static time_t
  5415. parse_date_string(const char *datetime)
  5416. {
  5417. char month_str[32] = {0};
  5418. int second, minute, hour, day, month, year;
  5419. time_t result = (time_t)0;
  5420. struct tm tm;
  5421. if ((sscanf(datetime,
  5422. "%d/%3s/%d %d:%d:%d",
  5423. &day,
  5424. month_str,
  5425. &year,
  5426. &hour,
  5427. &minute,
  5428. &second) == 6) || (sscanf(datetime,
  5429. "%d %3s %d %d:%d:%d",
  5430. &day,
  5431. month_str,
  5432. &year,
  5433. &hour,
  5434. &minute,
  5435. &second) == 6)
  5436. || (sscanf(datetime,
  5437. "%*3s, %d %3s %d %d:%d:%d",
  5438. &day,
  5439. month_str,
  5440. &year,
  5441. &hour,
  5442. &minute,
  5443. &second) == 6) || (sscanf(datetime,
  5444. "%d-%3s-%d %d:%d:%d",
  5445. &day,
  5446. month_str,
  5447. &year,
  5448. &hour,
  5449. &minute,
  5450. &second) == 6)) {
  5451. month = get_month_index(month_str);
  5452. if ((month >= 0) && (year >= 1970)) {
  5453. memset(&tm, 0, sizeof(tm));
  5454. tm.tm_year = year - 1900;
  5455. tm.tm_mon = month;
  5456. tm.tm_mday = day;
  5457. tm.tm_hour = hour;
  5458. tm.tm_min = minute;
  5459. tm.tm_sec = second;
  5460. result = timegm(&tm);
  5461. }
  5462. }
  5463. return result;
  5464. }
  5465. #endif /* !NO_CACHING */
  5466. /* Protect against directory disclosure attack by removing '..',
  5467. * excessive '/' and '\' characters */
  5468. static void
  5469. remove_double_dots_and_double_slashes(char *s)
  5470. {
  5471. char *p = s;
  5472. while ((s[0] == '.') && (s[1] == '.')) {
  5473. s++;
  5474. }
  5475. while (*s != '\0') {
  5476. *p++ = *s++;
  5477. if (s[-1] == '/' || s[-1] == '\\') {
  5478. /* Skip all following slashes, backslashes and double-dots */
  5479. while (s[0] != '\0') {
  5480. if (s[0] == '/' || s[0] == '\\') {
  5481. s++;
  5482. } else if (s[0] == '.' && s[1] == '.') {
  5483. s += 2;
  5484. } else {
  5485. break;
  5486. }
  5487. }
  5488. }
  5489. }
  5490. *p = '\0';
  5491. }
  5492. static const struct {
  5493. const char *extension;
  5494. size_t ext_len;
  5495. const char *mime_type;
  5496. } builtin_mime_types[] = {
  5497. /* IANA registered MIME types (http://www.iana.org/assignments/media-types)
  5498. * application types */
  5499. {".doc", 4, "application/msword"},
  5500. {".eps", 4, "application/postscript"},
  5501. {".exe", 4, "application/octet-stream"},
  5502. {".js", 3, "application/javascript"},
  5503. {".json", 5, "application/json"},
  5504. {".pdf", 4, "application/pdf"},
  5505. {".ps", 3, "application/postscript"},
  5506. {".rtf", 4, "application/rtf"},
  5507. {".xhtml", 6, "application/xhtml+xml"},
  5508. {".xsl", 4, "application/xml"},
  5509. {".xslt", 5, "application/xml"},
  5510. /* fonts */
  5511. {".ttf", 4, "application/font-sfnt"},
  5512. {".cff", 4, "application/font-sfnt"},
  5513. {".otf", 4, "application/font-sfnt"},
  5514. {".aat", 4, "application/font-sfnt"},
  5515. {".sil", 4, "application/font-sfnt"},
  5516. {".pfr", 4, "application/font-tdpfr"},
  5517. {".woff", 5, "application/font-woff"},
  5518. /* audio */
  5519. {".mp3", 4, "audio/mpeg"},
  5520. {".oga", 4, "audio/ogg"},
  5521. {".ogg", 4, "audio/ogg"},
  5522. /* image */
  5523. {".gif", 4, "image/gif"},
  5524. {".ief", 4, "image/ief"},
  5525. {".jpeg", 5, "image/jpeg"},
  5526. {".jpg", 4, "image/jpeg"},
  5527. {".jpm", 4, "image/jpm"},
  5528. {".jpx", 4, "image/jpx"},
  5529. {".png", 4, "image/png"},
  5530. {".svg", 4, "image/svg+xml"},
  5531. {".tif", 4, "image/tiff"},
  5532. {".tiff", 5, "image/tiff"},
  5533. /* model */
  5534. {".wrl", 4, "model/vrml"},
  5535. /* text */
  5536. {".css", 4, "text/css"},
  5537. {".csv", 4, "text/csv"},
  5538. {".htm", 4, "text/html"},
  5539. {".html", 5, "text/html"},
  5540. {".sgm", 4, "text/sgml"},
  5541. {".shtm", 5, "text/html"},
  5542. {".shtml", 6, "text/html"},
  5543. {".txt", 4, "text/plain"},
  5544. {".xml", 4, "text/xml"},
  5545. /* video */
  5546. {".mov", 4, "video/quicktime"},
  5547. {".mp4", 4, "video/mp4"},
  5548. {".mpeg", 5, "video/mpeg"},
  5549. {".mpg", 4, "video/mpeg"},
  5550. {".ogv", 4, "video/ogg"},
  5551. {".qt", 3, "video/quicktime"},
  5552. /* not registered types
  5553. * (http://reference.sitepoint.com/html/mime-types-full,
  5554. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  5555. {".arj", 4, "application/x-arj-compressed"},
  5556. {".gz", 3, "application/x-gunzip"},
  5557. {".rar", 4, "application/x-arj-compressed"},
  5558. {".swf", 4, "application/x-shockwave-flash"},
  5559. {".tar", 4, "application/x-tar"},
  5560. {".tgz", 4, "application/x-tar-gz"},
  5561. {".torrent", 8, "application/x-bittorrent"},
  5562. {".ppt", 4, "application/x-mspowerpoint"},
  5563. {".xls", 4, "application/x-msexcel"},
  5564. {".zip", 4, "application/x-zip-compressed"},
  5565. {".aac",
  5566. 4,
  5567. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  5568. {".aif", 4, "audio/x-aif"},
  5569. {".m3u", 4, "audio/x-mpegurl"},
  5570. {".mid", 4, "audio/x-midi"},
  5571. {".ra", 3, "audio/x-pn-realaudio"},
  5572. {".ram", 4, "audio/x-pn-realaudio"},
  5573. {".wav", 4, "audio/x-wav"},
  5574. {".bmp", 4, "image/bmp"},
  5575. {".ico", 4, "image/x-icon"},
  5576. {".pct", 4, "image/x-pct"},
  5577. {".pict", 5, "image/pict"},
  5578. {".rgb", 4, "image/x-rgb"},
  5579. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  5580. {".asf", 4, "video/x-ms-asf"},
  5581. {".avi", 4, "video/x-msvideo"},
  5582. {".m4v", 4, "video/x-m4v"},
  5583. {NULL, 0, NULL}};
  5584. const char *
  5585. mg_get_builtin_mime_type(const char *path)
  5586. {
  5587. const char *ext;
  5588. size_t i, path_len;
  5589. path_len = strlen(path);
  5590. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  5591. ext = path + (path_len - builtin_mime_types[i].ext_len);
  5592. if (path_len > builtin_mime_types[i].ext_len
  5593. && mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {
  5594. return builtin_mime_types[i].mime_type;
  5595. }
  5596. }
  5597. return "text/plain";
  5598. }
  5599. /* Look at the "path" extension and figure what mime type it has.
  5600. * Store mime type in the vector. */
  5601. static void
  5602. get_mime_type(struct mg_context *ctx, const char *path, struct vec *vec)
  5603. {
  5604. struct vec ext_vec, mime_vec;
  5605. const char *list, *ext;
  5606. size_t path_len;
  5607. path_len = strlen(path);
  5608. if (ctx == NULL || vec == NULL) {
  5609. return;
  5610. }
  5611. /* Scan user-defined mime types first, in case user wants to
  5612. * override default mime types. */
  5613. list = ctx->config[EXTRA_MIME_TYPES];
  5614. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  5615. /* ext now points to the path suffix */
  5616. ext = path + path_len - ext_vec.len;
  5617. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  5618. *vec = mime_vec;
  5619. return;
  5620. }
  5621. }
  5622. vec->ptr = mg_get_builtin_mime_type(path);
  5623. vec->len = strlen(vec->ptr);
  5624. }
  5625. /* Stringify binary data. Output buffer must be twice as big as input,
  5626. * because each byte takes 2 bytes in string representation */
  5627. static void
  5628. bin2str(char *to, const unsigned char *p, size_t len)
  5629. {
  5630. static const char *hex = "0123456789abcdef";
  5631. for (; len--; p++) {
  5632. *to++ = hex[p[0] >> 4];
  5633. *to++ = hex[p[0] & 0x0f];
  5634. }
  5635. *to = '\0';
  5636. }
  5637. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes. */
  5638. char *
  5639. mg_md5(char buf[33], ...)
  5640. {
  5641. md5_byte_t hash[16];
  5642. const char *p;
  5643. va_list ap;
  5644. md5_state_t ctx;
  5645. md5_init(&ctx);
  5646. va_start(ap, buf);
  5647. while ((p = va_arg(ap, const char *)) != NULL) {
  5648. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  5649. }
  5650. va_end(ap);
  5651. md5_finish(&ctx, hash);
  5652. bin2str(buf, hash, sizeof(hash));
  5653. return buf;
  5654. }
  5655. /* Check the user's password, return 1 if OK */
  5656. static int
  5657. check_password(const char *method,
  5658. const char *ha1,
  5659. const char *uri,
  5660. const char *nonce,
  5661. const char *nc,
  5662. const char *cnonce,
  5663. const char *qop,
  5664. const char *response)
  5665. {
  5666. char ha2[32 + 1], expected_response[32 + 1];
  5667. /* Some of the parameters may be NULL */
  5668. if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL
  5669. || qop == NULL
  5670. || response == NULL) {
  5671. return 0;
  5672. }
  5673. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  5674. if (strlen(response) != 32) {
  5675. return 0;
  5676. }
  5677. mg_md5(ha2, method, ":", uri, NULL);
  5678. mg_md5(expected_response,
  5679. ha1,
  5680. ":",
  5681. nonce,
  5682. ":",
  5683. nc,
  5684. ":",
  5685. cnonce,
  5686. ":",
  5687. qop,
  5688. ":",
  5689. ha2,
  5690. NULL);
  5691. return mg_strcasecmp(response, expected_response) == 0;
  5692. }
  5693. /* Use the global passwords file, if specified by auth_gpass option,
  5694. * or search for .htpasswd in the requested directory. */
  5695. static void
  5696. open_auth_file(struct mg_connection *conn,
  5697. const char *path,
  5698. struct mg_file *filep)
  5699. {
  5700. if (conn != NULL && conn->ctx != NULL) {
  5701. char name[PATH_MAX];
  5702. const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
  5703. int truncated;
  5704. if (gpass != NULL) {
  5705. /* Use global passwords file */
  5706. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  5707. #ifdef DEBUG
  5708. /* Use mg_cry here, since gpass has been configured. */
  5709. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  5710. #endif
  5711. }
  5712. /* Important: using local struct mg_file to test path for
  5713. * is_directory flag. If filep is used, mg_stat() makes it
  5714. * appear as if auth file was opened.
  5715. * TODO(mid): Check if this is still required after rewriting
  5716. * mg_stat */
  5717. } else if (mg_stat(conn, path, &filep->stat)
  5718. && filep->stat.is_directory) {
  5719. mg_snprintf(conn,
  5720. &truncated,
  5721. name,
  5722. sizeof(name),
  5723. "%s/%s",
  5724. path,
  5725. PASSWORDS_FILE_NAME);
  5726. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  5727. #ifdef DEBUG
  5728. /* Don't use mg_cry here, but only a trace, since this is
  5729. * a typical case. It will occur for every directory
  5730. * without a password file. */
  5731. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  5732. #endif
  5733. }
  5734. } else {
  5735. /* Try to find .htpasswd in requested directory. */
  5736. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  5737. if (e[0] == '/') {
  5738. break;
  5739. }
  5740. }
  5741. mg_snprintf(conn,
  5742. &truncated,
  5743. name,
  5744. sizeof(name),
  5745. "%.*s/%s",
  5746. (int)(e - p),
  5747. p,
  5748. PASSWORDS_FILE_NAME);
  5749. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  5750. #ifdef DEBUG
  5751. /* Don't use mg_cry here, but only a trace, since this is
  5752. * a typical case. It will occur for every directory
  5753. * without a password file. */
  5754. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  5755. #endif
  5756. }
  5757. }
  5758. }
  5759. }
  5760. /* Parsed Authorization header */
  5761. struct ah {
  5762. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  5763. };
  5764. /* Return 1 on success. Always initializes the ah structure. */
  5765. static int
  5766. parse_auth_header(struct mg_connection *conn,
  5767. char *buf,
  5768. size_t buf_size,
  5769. struct ah *ah)
  5770. {
  5771. char *name, *value, *s;
  5772. const char *auth_header;
  5773. uint64_t nonce;
  5774. if (!ah || !conn) {
  5775. return 0;
  5776. }
  5777. (void)memset(ah, 0, sizeof(*ah));
  5778. if ((auth_header = mg_get_header(conn, "Authorization")) == NULL
  5779. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  5780. return 0;
  5781. }
  5782. /* Make modifiable copy of the auth header */
  5783. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  5784. s = buf;
  5785. /* Parse authorization header */
  5786. for (;;) {
  5787. /* Gobble initial spaces */
  5788. while (isspace(*(unsigned char *)s)) {
  5789. s++;
  5790. }
  5791. name = skip_quoted(&s, "=", " ", 0);
  5792. /* Value is either quote-delimited, or ends at first comma or space. */
  5793. if (s[0] == '\"') {
  5794. s++;
  5795. value = skip_quoted(&s, "\"", " ", '\\');
  5796. if (s[0] == ',') {
  5797. s++;
  5798. }
  5799. } else {
  5800. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  5801. * spaces */
  5802. }
  5803. if (*name == '\0') {
  5804. break;
  5805. }
  5806. if (!strcmp(name, "username")) {
  5807. ah->user = value;
  5808. } else if (!strcmp(name, "cnonce")) {
  5809. ah->cnonce = value;
  5810. } else if (!strcmp(name, "response")) {
  5811. ah->response = value;
  5812. } else if (!strcmp(name, "uri")) {
  5813. ah->uri = value;
  5814. } else if (!strcmp(name, "qop")) {
  5815. ah->qop = value;
  5816. } else if (!strcmp(name, "nc")) {
  5817. ah->nc = value;
  5818. } else if (!strcmp(name, "nonce")) {
  5819. ah->nonce = value;
  5820. }
  5821. }
  5822. #ifndef NO_NONCE_CHECK
  5823. /* Read the nonce from the response. */
  5824. if (ah->nonce == NULL) {
  5825. return 0;
  5826. }
  5827. s = NULL;
  5828. nonce = strtoull(ah->nonce, &s, 10);
  5829. if ((s == NULL) || (*s != 0)) {
  5830. return 0;
  5831. }
  5832. /* Convert the nonce from the client to a number. */
  5833. nonce ^= conn->ctx->auth_nonce_mask;
  5834. /* The converted number corresponds to the time the nounce has been
  5835. * created. This should not be earlier than the server start. */
  5836. /* Server side nonce check is valuable in all situations but one:
  5837. * if the server restarts frequently, but the client should not see
  5838. * that, so the server should accept nonces from previous starts. */
  5839. /* However, the reasonable default is to not accept a nonce from a
  5840. * previous start, so if anyone changed the access rights between
  5841. * two restarts, a new login is required. */
  5842. if (nonce < (uint64_t)conn->ctx->start_time) {
  5843. /* nonce is from a previous start of the server and no longer valid
  5844. * (replay attack?) */
  5845. return 0;
  5846. }
  5847. /* Check if the nonce is too high, so it has not (yet) been used by the
  5848. * server. */
  5849. if (nonce >= ((uint64_t)conn->ctx->start_time + conn->ctx->nonce_count)) {
  5850. return 0;
  5851. }
  5852. #else
  5853. (void)nonce;
  5854. #endif
  5855. /* CGI needs it as REMOTE_USER */
  5856. if (ah->user != NULL) {
  5857. conn->request_info.remote_user = mg_strdup(ah->user);
  5858. } else {
  5859. return 0;
  5860. }
  5861. return 1;
  5862. }
  5863. static const char *
  5864. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  5865. {
  5866. const char *eof;
  5867. size_t len;
  5868. const char *memend;
  5869. if (!filep) {
  5870. return NULL;
  5871. }
  5872. if (filep->access.membuf != NULL && *p != NULL) {
  5873. memend = (const char *)&filep->access.membuf[filep->stat.size];
  5874. /* Search for \n from p till the end of stream */
  5875. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  5876. if (eof != NULL) {
  5877. eof += 1; /* Include \n */
  5878. } else {
  5879. eof = memend; /* Copy remaining data */
  5880. }
  5881. len =
  5882. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  5883. memcpy(buf, *p, len);
  5884. buf[len] = '\0';
  5885. *p += len;
  5886. return len ? eof : NULL;
  5887. } else if (filep->access.fp != NULL) {
  5888. return fgets(buf, (int)size, filep->access.fp);
  5889. } else {
  5890. return NULL;
  5891. }
  5892. }
  5893. /* Define the initial recursion depth for procesesing htpasswd files that
  5894. * include other htpasswd
  5895. * (or even the same) files. It is not difficult to provide a file or files
  5896. * s.t. they force civetweb
  5897. * to infinitely recurse and then crash.
  5898. */
  5899. #define INITIAL_DEPTH 9
  5900. #if INITIAL_DEPTH <= 0
  5901. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  5902. #endif
  5903. struct read_auth_file_struct {
  5904. struct mg_connection *conn;
  5905. struct ah ah;
  5906. char *domain;
  5907. char buf[256 + 256 + 40];
  5908. char *f_user;
  5909. char *f_domain;
  5910. char *f_ha1;
  5911. };
  5912. static int
  5913. read_auth_file(struct mg_file *filep,
  5914. struct read_auth_file_struct *workdata,
  5915. int depth)
  5916. {
  5917. char *p;
  5918. int is_authorized = 0;
  5919. struct mg_file fp;
  5920. size_t l;
  5921. if (!filep || !workdata || 0 == depth) {
  5922. return 0;
  5923. }
  5924. /* Loop over passwords file */
  5925. p = (char *)filep->access.membuf;
  5926. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  5927. l = strlen(workdata->buf);
  5928. while (l > 0) {
  5929. if (isspace(workdata->buf[l - 1])
  5930. || iscntrl(workdata->buf[l - 1])) {
  5931. l--;
  5932. workdata->buf[l] = 0;
  5933. } else
  5934. break;
  5935. }
  5936. if (l < 1) {
  5937. continue;
  5938. }
  5939. workdata->f_user = workdata->buf;
  5940. if (workdata->f_user[0] == ':') {
  5941. /* user names may not contain a ':' and may not be empty,
  5942. * so lines starting with ':' may be used for a special purpose */
  5943. if (workdata->f_user[1] == '#') {
  5944. /* :# is a comment */
  5945. continue;
  5946. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  5947. if (mg_fopen(workdata->conn,
  5948. workdata->f_user + 9,
  5949. MG_FOPEN_MODE_READ,
  5950. &fp)) {
  5951. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  5952. (void)mg_fclose(
  5953. &fp.access); /* ignore error on read only file */
  5954. /* No need to continue processing files once we have a
  5955. * match, since nothing will reset it back
  5956. * to 0.
  5957. */
  5958. if (is_authorized) {
  5959. return is_authorized;
  5960. }
  5961. } else {
  5962. mg_cry(workdata->conn,
  5963. "%s: cannot open authorization file: %s",
  5964. __func__,
  5965. workdata->buf);
  5966. }
  5967. continue;
  5968. }
  5969. /* everything is invalid for the moment (might change in the
  5970. * future) */
  5971. mg_cry(workdata->conn,
  5972. "%s: syntax error in authorization file: %s",
  5973. __func__,
  5974. workdata->buf);
  5975. continue;
  5976. }
  5977. workdata->f_domain = strchr(workdata->f_user, ':');
  5978. if (workdata->f_domain == NULL) {
  5979. mg_cry(workdata->conn,
  5980. "%s: syntax error in authorization file: %s",
  5981. __func__,
  5982. workdata->buf);
  5983. continue;
  5984. }
  5985. *(workdata->f_domain) = 0;
  5986. (workdata->f_domain)++;
  5987. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  5988. if (workdata->f_ha1 == NULL) {
  5989. mg_cry(workdata->conn,
  5990. "%s: syntax error in authorization file: %s",
  5991. __func__,
  5992. workdata->buf);
  5993. continue;
  5994. }
  5995. *(workdata->f_ha1) = 0;
  5996. (workdata->f_ha1)++;
  5997. if (!strcmp(workdata->ah.user, workdata->f_user)
  5998. && !strcmp(workdata->domain, workdata->f_domain)) {
  5999. return check_password(workdata->conn->request_info.request_method,
  6000. workdata->f_ha1,
  6001. workdata->ah.uri,
  6002. workdata->ah.nonce,
  6003. workdata->ah.nc,
  6004. workdata->ah.cnonce,
  6005. workdata->ah.qop,
  6006. workdata->ah.response);
  6007. }
  6008. }
  6009. return is_authorized;
  6010. }
  6011. /* Authorize against the opened passwords file. Return 1 if authorized. */
  6012. static int
  6013. authorize(struct mg_connection *conn, struct mg_file *filep)
  6014. {
  6015. struct read_auth_file_struct workdata;
  6016. char buf[MG_BUF_LEN];
  6017. if (!conn || !conn->ctx) {
  6018. return 0;
  6019. }
  6020. memset(&workdata, 0, sizeof(workdata));
  6021. workdata.conn = conn;
  6022. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  6023. return 0;
  6024. }
  6025. workdata.domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  6026. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  6027. }
  6028. /* Return 1 if request is authorised, 0 otherwise. */
  6029. static int
  6030. check_authorization(struct mg_connection *conn, const char *path)
  6031. {
  6032. char fname[PATH_MAX];
  6033. struct vec uri_vec, filename_vec;
  6034. const char *list;
  6035. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6036. int authorized = 1, truncated;
  6037. if (!conn || !conn->ctx) {
  6038. return 0;
  6039. }
  6040. list = conn->ctx->config[PROTECT_URI];
  6041. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  6042. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  6043. mg_snprintf(conn,
  6044. &truncated,
  6045. fname,
  6046. sizeof(fname),
  6047. "%.*s",
  6048. (int)filename_vec.len,
  6049. filename_vec.ptr);
  6050. if (truncated
  6051. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  6052. mg_cry(conn,
  6053. "%s: cannot open %s: %s",
  6054. __func__,
  6055. fname,
  6056. strerror(errno));
  6057. }
  6058. break;
  6059. }
  6060. }
  6061. if (!is_file_opened(&file.access)) {
  6062. open_auth_file(conn, path, &file);
  6063. }
  6064. if (is_file_opened(&file.access)) {
  6065. authorized = authorize(conn, &file);
  6066. (void)mg_fclose(&file.access); /* ignore error on read only file */
  6067. }
  6068. return authorized;
  6069. }
  6070. static void
  6071. send_authorization_request(struct mg_connection *conn)
  6072. {
  6073. char date[64];
  6074. time_t curtime = time(NULL);
  6075. if (conn && conn->ctx) {
  6076. uint64_t nonce = (uint64_t)(conn->ctx->start_time);
  6077. (void)pthread_mutex_lock(&conn->ctx->nonce_mutex);
  6078. nonce += conn->ctx->nonce_count;
  6079. ++conn->ctx->nonce_count;
  6080. (void)pthread_mutex_unlock(&conn->ctx->nonce_mutex);
  6081. nonce ^= conn->ctx->auth_nonce_mask;
  6082. conn->status_code = 401;
  6083. conn->must_close = 1;
  6084. gmt_time_string(date, sizeof(date), &curtime);
  6085. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  6086. send_no_cache_header(conn);
  6087. send_additional_header(conn);
  6088. mg_printf(conn,
  6089. "Date: %s\r\n"
  6090. "Connection: %s\r\n"
  6091. "Content-Length: 0\r\n"
  6092. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  6093. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  6094. date,
  6095. suggest_connection_header(conn),
  6096. conn->ctx->config[AUTHENTICATION_DOMAIN],
  6097. nonce);
  6098. }
  6099. }
  6100. #if !defined(NO_FILES)
  6101. static int
  6102. is_authorized_for_put(struct mg_connection *conn)
  6103. {
  6104. if (conn) {
  6105. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6106. const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
  6107. int ret = 0;
  6108. if (passfile != NULL
  6109. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  6110. ret = authorize(conn, &file);
  6111. (void)mg_fclose(&file.access); /* ignore error on read only file */
  6112. }
  6113. return ret;
  6114. }
  6115. return 0;
  6116. }
  6117. #endif
  6118. int
  6119. mg_modify_passwords_file(const char *fname,
  6120. const char *domain,
  6121. const char *user,
  6122. const char *pass)
  6123. {
  6124. int found, i;
  6125. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  6126. FILE *fp, *fp2;
  6127. found = 0;
  6128. fp = fp2 = NULL;
  6129. /* Regard empty password as no password - remove user record. */
  6130. if (pass != NULL && pass[0] == '\0') {
  6131. pass = NULL;
  6132. }
  6133. /* Other arguments must not be empty */
  6134. if (fname == NULL || domain == NULL || user == NULL) {
  6135. return 0;
  6136. }
  6137. /* Using the given file format, user name and domain must not contain ':'
  6138. */
  6139. if (strchr(user, ':') != NULL) {
  6140. return 0;
  6141. }
  6142. if (strchr(domain, ':') != NULL) {
  6143. return 0;
  6144. }
  6145. /* Do not allow control characters like newline in user name and domain.
  6146. * Do not allow excessively long names either. */
  6147. for (i = 0; i < 255 && user[i] != 0; i++) {
  6148. if (iscntrl(user[i])) {
  6149. return 0;
  6150. }
  6151. }
  6152. if (user[i]) {
  6153. return 0;
  6154. }
  6155. for (i = 0; i < 255 && domain[i] != 0; i++) {
  6156. if (iscntrl(domain[i])) {
  6157. return 0;
  6158. }
  6159. }
  6160. if (domain[i]) {
  6161. return 0;
  6162. }
  6163. /* The maximum length of the path to the password file is limited */
  6164. if ((strlen(fname) + 4) >= PATH_MAX) {
  6165. return 0;
  6166. }
  6167. /* Create a temporary file name. Length has been checked before. */
  6168. strcpy(tmp, fname);
  6169. strcat(tmp, ".tmp");
  6170. /* Create the file if does not exist */
  6171. /* Use of fopen here is OK, since fname is only ASCII */
  6172. if ((fp = fopen(fname, "a+")) != NULL) {
  6173. (void)fclose(fp);
  6174. }
  6175. /* Open the given file and temporary file */
  6176. if ((fp = fopen(fname, "r")) == NULL) {
  6177. return 0;
  6178. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  6179. fclose(fp);
  6180. return 0;
  6181. }
  6182. /* Copy the stuff to temporary file */
  6183. while (fgets(line, sizeof(line), fp) != NULL) {
  6184. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  6185. continue;
  6186. }
  6187. u[255] = 0;
  6188. d[255] = 0;
  6189. if (!strcmp(u, user) && !strcmp(d, domain)) {
  6190. found++;
  6191. if (pass != NULL) {
  6192. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  6193. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  6194. }
  6195. } else {
  6196. fprintf(fp2, "%s", line);
  6197. }
  6198. }
  6199. /* If new user, just add it */
  6200. if (!found && pass != NULL) {
  6201. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  6202. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  6203. }
  6204. /* Close files */
  6205. fclose(fp);
  6206. fclose(fp2);
  6207. /* Put the temp file in place of real file */
  6208. IGNORE_UNUSED_RESULT(remove(fname));
  6209. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  6210. return 1;
  6211. }
  6212. static int
  6213. is_valid_port(unsigned long port)
  6214. {
  6215. return (port <= 0xffff);
  6216. }
  6217. static int
  6218. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  6219. {
  6220. struct addrinfo hints, *res, *ressave;
  6221. int func_ret = 0;
  6222. int gai_ret;
  6223. memset(&hints, 0, sizeof(struct addrinfo));
  6224. hints.ai_family = af;
  6225. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  6226. if (gai_ret != 0) {
  6227. /* gai_strerror could be used to convert gai_ret to a string */
  6228. /* POSIX return values: see
  6229. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  6230. */
  6231. /* Windows return values: see
  6232. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  6233. */
  6234. return 0;
  6235. }
  6236. ressave = res;
  6237. while (res) {
  6238. if (dstlen >= res->ai_addrlen) {
  6239. memcpy(dst, res->ai_addr, res->ai_addrlen);
  6240. func_ret = 1;
  6241. }
  6242. res = res->ai_next;
  6243. }
  6244. freeaddrinfo(ressave);
  6245. return func_ret;
  6246. }
  6247. static int
  6248. connect_socket(struct mg_context *ctx /* may be NULL */,
  6249. const char *host,
  6250. int port,
  6251. int use_ssl,
  6252. char *ebuf,
  6253. size_t ebuf_len,
  6254. SOCKET *sock /* output: socket, must not be NULL */,
  6255. union usa *sa /* output: socket address, must not be NULL */
  6256. )
  6257. {
  6258. int ip_ver = 0;
  6259. *sock = INVALID_SOCKET;
  6260. memset(sa, 0, sizeof(*sa));
  6261. if (ebuf_len > 0) {
  6262. *ebuf = 0;
  6263. }
  6264. if (host == NULL) {
  6265. mg_snprintf(NULL,
  6266. NULL, /* No truncation check for ebuf */
  6267. ebuf,
  6268. ebuf_len,
  6269. "%s",
  6270. "NULL host");
  6271. return 0;
  6272. }
  6273. if (port <= 0 || !is_valid_port((unsigned)port)) {
  6274. mg_snprintf(NULL,
  6275. NULL, /* No truncation check for ebuf */
  6276. ebuf,
  6277. ebuf_len,
  6278. "%s",
  6279. "invalid port");
  6280. return 0;
  6281. }
  6282. #if !defined(NO_SSL)
  6283. #if !defined(NO_SSL_DL)
  6284. #ifdef OPENSSL_API_1_1
  6285. if (use_ssl && (TLS_client_method == NULL)) {
  6286. mg_snprintf(NULL,
  6287. NULL, /* No truncation check for ebuf */
  6288. ebuf,
  6289. ebuf_len,
  6290. "%s",
  6291. "SSL is not initialized");
  6292. return 0;
  6293. }
  6294. #else
  6295. if (use_ssl && (SSLv23_client_method == NULL)) {
  6296. mg_snprintf(NULL,
  6297. NULL, /* No truncation check for ebuf */
  6298. ebuf,
  6299. ebuf_len,
  6300. "%s",
  6301. "SSL is not initialized");
  6302. return 0;
  6303. }
  6304. #endif /* OPENSSL_API_1_1 */
  6305. #else
  6306. (void)use_ssl;
  6307. #endif /* NO_SSL_DL */
  6308. #else
  6309. (void)use_ssl;
  6310. #endif /* !defined(NO_SSL) */
  6311. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  6312. sa->sin.sin_port = htons((uint16_t)port);
  6313. ip_ver = 4;
  6314. #ifdef USE_IPV6
  6315. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  6316. sa->sin6.sin6_port = htons((uint16_t)port);
  6317. ip_ver = 6;
  6318. } else if (host[0] == '[') {
  6319. /* While getaddrinfo on Windows will work with [::1],
  6320. * getaddrinfo on Linux only works with ::1 (without []). */
  6321. size_t l = strlen(host + 1);
  6322. char *h = (l > 1) ? mg_strdup(host + 1) : NULL;
  6323. if (h) {
  6324. h[l - 1] = 0;
  6325. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  6326. sa->sin6.sin6_port = htons((uint16_t)port);
  6327. ip_ver = 6;
  6328. }
  6329. mg_free(h);
  6330. }
  6331. #endif
  6332. }
  6333. if (ip_ver == 0) {
  6334. mg_snprintf(NULL,
  6335. NULL, /* No truncation check for ebuf */
  6336. ebuf,
  6337. ebuf_len,
  6338. "%s",
  6339. "host not found");
  6340. return 0;
  6341. }
  6342. if (ip_ver == 4) {
  6343. *sock = socket(PF_INET, SOCK_STREAM, 0);
  6344. }
  6345. #ifdef USE_IPV6
  6346. else if (ip_ver == 6) {
  6347. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  6348. }
  6349. #endif
  6350. if (*sock == INVALID_SOCKET) {
  6351. mg_snprintf(NULL,
  6352. NULL, /* No truncation check for ebuf */
  6353. ebuf,
  6354. ebuf_len,
  6355. "socket(): %s",
  6356. strerror(ERRNO));
  6357. return 0;
  6358. }
  6359. set_close_on_exec(*sock, fc(ctx));
  6360. if ((ip_ver == 4)
  6361. && (connect(*sock, (struct sockaddr *)&sa->sin, sizeof(sa->sin))
  6362. == 0)) {
  6363. /* connected with IPv4 */
  6364. set_blocking_mode(*sock, 0);
  6365. return 1;
  6366. }
  6367. #ifdef USE_IPV6
  6368. if ((ip_ver == 6)
  6369. && (connect(*sock, (struct sockaddr *)&sa->sin6, sizeof(sa->sin6))
  6370. == 0)) {
  6371. /* connected with IPv6 */
  6372. set_blocking_mode(*sock, 0);
  6373. return 1;
  6374. }
  6375. #endif
  6376. /* Not connected */
  6377. mg_snprintf(NULL,
  6378. NULL, /* No truncation check for ebuf */
  6379. ebuf,
  6380. ebuf_len,
  6381. "connect(%s:%d): %s",
  6382. host,
  6383. port,
  6384. strerror(ERRNO));
  6385. closesocket(*sock);
  6386. *sock = INVALID_SOCKET;
  6387. return 0;
  6388. }
  6389. int
  6390. mg_url_encode(const char *src, char *dst, size_t dst_len)
  6391. {
  6392. static const char *dont_escape = "._-$,;~()";
  6393. static const char *hex = "0123456789abcdef";
  6394. char *pos = dst;
  6395. const char *end = dst + dst_len - 1;
  6396. for (; *src != '\0' && pos < end; src++, pos++) {
  6397. if (isalnum(*(const unsigned char *)src)
  6398. || strchr(dont_escape, *(const unsigned char *)src) != NULL) {
  6399. *pos = *src;
  6400. } else if (pos + 2 < end) {
  6401. pos[0] = '%';
  6402. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  6403. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  6404. pos += 2;
  6405. } else {
  6406. break;
  6407. }
  6408. }
  6409. *pos = '\0';
  6410. return (*src == '\0') ? (int)(pos - dst) : -1;
  6411. }
  6412. static void
  6413. print_dir_entry(struct de *de)
  6414. {
  6415. char size[64], mod[64], href[PATH_MAX * 3 /* worst case */];
  6416. struct tm *tm;
  6417. if (de->file.is_directory) {
  6418. mg_snprintf(de->conn,
  6419. NULL, /* Buffer is big enough */
  6420. size,
  6421. sizeof(size),
  6422. "%s",
  6423. "[DIRECTORY]");
  6424. } else {
  6425. /* We use (signed) cast below because MSVC 6 compiler cannot
  6426. * convert unsigned __int64 to double. Sigh. */
  6427. if (de->file.size < 1024) {
  6428. mg_snprintf(de->conn,
  6429. NULL, /* Buffer is big enough */
  6430. size,
  6431. sizeof(size),
  6432. "%d",
  6433. (int)de->file.size);
  6434. } else if (de->file.size < 0x100000) {
  6435. mg_snprintf(de->conn,
  6436. NULL, /* Buffer is big enough */
  6437. size,
  6438. sizeof(size),
  6439. "%.1fk",
  6440. (double)de->file.size / 1024.0);
  6441. } else if (de->file.size < 0x40000000) {
  6442. mg_snprintf(de->conn,
  6443. NULL, /* Buffer is big enough */
  6444. size,
  6445. sizeof(size),
  6446. "%.1fM",
  6447. (double)de->file.size / 1048576);
  6448. } else {
  6449. mg_snprintf(de->conn,
  6450. NULL, /* Buffer is big enough */
  6451. size,
  6452. sizeof(size),
  6453. "%.1fG",
  6454. (double)de->file.size / 1073741824);
  6455. }
  6456. }
  6457. /* Note: mg_snprintf will not cause a buffer overflow above.
  6458. * So, string truncation checks are not required here. */
  6459. tm = localtime(&de->file.last_modified);
  6460. if (tm != NULL) {
  6461. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  6462. } else {
  6463. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  6464. mod[sizeof(mod) - 1] = '\0';
  6465. }
  6466. mg_url_encode(de->file_name, href, sizeof(href));
  6467. de->conn->num_bytes_sent +=
  6468. mg_printf(de->conn,
  6469. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  6470. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  6471. de->conn->request_info.local_uri,
  6472. href,
  6473. de->file.is_directory ? "/" : "",
  6474. de->file_name,
  6475. de->file.is_directory ? "/" : "",
  6476. mod,
  6477. size);
  6478. }
  6479. /* This function is called from send_directory() and used for
  6480. * sorting directory entries by size, or name, or modification time.
  6481. * On windows, __cdecl specification is needed in case if project is built
  6482. * with __stdcall convention. qsort always requires __cdels callback. */
  6483. static int WINCDECL
  6484. compare_dir_entries(const void *p1, const void *p2)
  6485. {
  6486. if (p1 && p2) {
  6487. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  6488. const char *query_string = a->conn->request_info.query_string;
  6489. int cmp_result = 0;
  6490. if (query_string == NULL) {
  6491. query_string = "na";
  6492. }
  6493. if (a->file.is_directory && !b->file.is_directory) {
  6494. return -1; /* Always put directories on top */
  6495. } else if (!a->file.is_directory && b->file.is_directory) {
  6496. return 1; /* Always put directories on top */
  6497. } else if (*query_string == 'n') {
  6498. cmp_result = strcmp(a->file_name, b->file_name);
  6499. } else if (*query_string == 's') {
  6500. cmp_result = (a->file.size == b->file.size)
  6501. ? 0
  6502. : ((a->file.size > b->file.size) ? 1 : -1);
  6503. } else if (*query_string == 'd') {
  6504. cmp_result =
  6505. (a->file.last_modified == b->file.last_modified)
  6506. ? 0
  6507. : ((a->file.last_modified > b->file.last_modified) ? 1
  6508. : -1);
  6509. }
  6510. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  6511. }
  6512. return 0;
  6513. }
  6514. static int
  6515. must_hide_file(struct mg_connection *conn, const char *path)
  6516. {
  6517. if (conn && conn->ctx) {
  6518. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  6519. const char *pattern = conn->ctx->config[HIDE_FILES];
  6520. return match_prefix(pw_pattern, strlen(pw_pattern), path) > 0
  6521. || (pattern != NULL
  6522. && match_prefix(pattern, strlen(pattern), path) > 0);
  6523. }
  6524. return 0;
  6525. }
  6526. static int
  6527. scan_directory(struct mg_connection *conn,
  6528. const char *dir,
  6529. void *data,
  6530. void (*cb)(struct de *, void *))
  6531. {
  6532. char path[PATH_MAX];
  6533. struct dirent *dp;
  6534. DIR *dirp;
  6535. struct de de;
  6536. int truncated;
  6537. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  6538. return 0;
  6539. } else {
  6540. de.conn = conn;
  6541. while ((dp = mg_readdir(dirp)) != NULL) {
  6542. /* Do not show current dir and hidden files */
  6543. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  6544. || must_hide_file(conn, dp->d_name)) {
  6545. continue;
  6546. }
  6547. mg_snprintf(
  6548. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  6549. /* If we don't memset stat structure to zero, mtime will have
  6550. * garbage and strftime() will segfault later on in
  6551. * print_dir_entry(). memset is required only if mg_stat()
  6552. * fails. For more details, see
  6553. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  6554. memset(&de.file, 0, sizeof(de.file));
  6555. if (truncated) {
  6556. /* If the path is not complete, skip processing. */
  6557. continue;
  6558. }
  6559. if (!mg_stat(conn, path, &de.file)) {
  6560. mg_cry(conn,
  6561. "%s: mg_stat(%s) failed: %s",
  6562. __func__,
  6563. path,
  6564. strerror(ERRNO));
  6565. }
  6566. de.file_name = dp->d_name;
  6567. cb(&de, data);
  6568. }
  6569. (void)mg_closedir(dirp);
  6570. }
  6571. return 1;
  6572. }
  6573. #if !defined(NO_FILES)
  6574. static int
  6575. remove_directory(struct mg_connection *conn, const char *dir)
  6576. {
  6577. char path[PATH_MAX];
  6578. struct dirent *dp;
  6579. DIR *dirp;
  6580. struct de de;
  6581. int truncated;
  6582. int ok = 1;
  6583. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  6584. return 0;
  6585. } else {
  6586. de.conn = conn;
  6587. while ((dp = mg_readdir(dirp)) != NULL) {
  6588. /* Do not show current dir (but show hidden files as they will
  6589. * also be removed) */
  6590. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  6591. continue;
  6592. }
  6593. mg_snprintf(
  6594. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  6595. /* If we don't memset stat structure to zero, mtime will have
  6596. * garbage and strftime() will segfault later on in
  6597. * print_dir_entry(). memset is required only if mg_stat()
  6598. * fails. For more details, see
  6599. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  6600. memset(&de.file, 0, sizeof(de.file));
  6601. if (truncated) {
  6602. /* Do not delete anything shorter */
  6603. ok = 0;
  6604. continue;
  6605. }
  6606. if (!mg_stat(conn, path, &de.file)) {
  6607. mg_cry(conn,
  6608. "%s: mg_stat(%s) failed: %s",
  6609. __func__,
  6610. path,
  6611. strerror(ERRNO));
  6612. ok = 0;
  6613. }
  6614. if (de.file.is_directory) {
  6615. if (remove_directory(conn, path) == 0) {
  6616. ok = 0;
  6617. }
  6618. } else {
  6619. /* This will fail file is the file is in memory */
  6620. if (mg_remove(conn, path) == 0) {
  6621. ok = 0;
  6622. }
  6623. }
  6624. }
  6625. (void)mg_closedir(dirp);
  6626. IGNORE_UNUSED_RESULT(rmdir(dir));
  6627. }
  6628. return ok;
  6629. }
  6630. #endif
  6631. struct dir_scan_data {
  6632. struct de *entries;
  6633. unsigned int num_entries;
  6634. unsigned int arr_size;
  6635. };
  6636. /* Behaves like realloc(), but frees original pointer on failure */
  6637. static void *
  6638. realloc2(void *ptr, size_t size)
  6639. {
  6640. void *new_ptr = mg_realloc(ptr, size);
  6641. if (new_ptr == NULL) {
  6642. mg_free(ptr);
  6643. }
  6644. return new_ptr;
  6645. }
  6646. static void
  6647. dir_scan_callback(struct de *de, void *data)
  6648. {
  6649. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  6650. if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {
  6651. dsd->arr_size *= 2;
  6652. dsd->entries =
  6653. (struct de *)realloc2(dsd->entries,
  6654. dsd->arr_size * sizeof(dsd->entries[0]));
  6655. }
  6656. if (dsd->entries == NULL) {
  6657. /* TODO(lsm, low): propagate an error to the caller */
  6658. dsd->num_entries = 0;
  6659. } else {
  6660. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  6661. dsd->entries[dsd->num_entries].file = de->file;
  6662. dsd->entries[dsd->num_entries].conn = de->conn;
  6663. dsd->num_entries++;
  6664. }
  6665. }
  6666. static void
  6667. handle_directory_request(struct mg_connection *conn, const char *dir)
  6668. {
  6669. unsigned int i;
  6670. int sort_direction;
  6671. struct dir_scan_data data = {NULL, 0, 128};
  6672. char date[64];
  6673. time_t curtime = time(NULL);
  6674. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  6675. mg_send_http_error(conn,
  6676. 500,
  6677. "Error: Cannot open directory\nopendir(%s): %s",
  6678. dir,
  6679. strerror(ERRNO));
  6680. return;
  6681. }
  6682. gmt_time_string(date, sizeof(date), &curtime);
  6683. if (!conn) {
  6684. return;
  6685. }
  6686. sort_direction = ((conn->request_info.query_string != NULL)
  6687. && (conn->request_info.query_string[1] == 'd'))
  6688. ? 'a'
  6689. : 'd';
  6690. conn->must_close = 1;
  6691. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  6692. send_static_cache_header(conn);
  6693. send_additional_header(conn);
  6694. mg_printf(conn,
  6695. "Date: %s\r\n"
  6696. "Connection: close\r\n"
  6697. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  6698. date);
  6699. conn->num_bytes_sent +=
  6700. mg_printf(conn,
  6701. "<html><head><title>Index of %s</title>"
  6702. "<style>th {text-align: left;}</style></head>"
  6703. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  6704. "<tr><th><a href=\"?n%c\">Name</a></th>"
  6705. "<th><a href=\"?d%c\">Modified</a></th>"
  6706. "<th><a href=\"?s%c\">Size</a></th></tr>"
  6707. "<tr><td colspan=\"3\"><hr></td></tr>",
  6708. conn->request_info.local_uri,
  6709. conn->request_info.local_uri,
  6710. sort_direction,
  6711. sort_direction,
  6712. sort_direction);
  6713. /* Print first entry - link to a parent directory */
  6714. conn->num_bytes_sent +=
  6715. mg_printf(conn,
  6716. "<tr><td><a href=\"%s%s\">%s</a></td>"
  6717. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  6718. conn->request_info.local_uri,
  6719. "..",
  6720. "Parent directory",
  6721. "-",
  6722. "-");
  6723. /* Sort and print directory entries */
  6724. if (data.entries != NULL) {
  6725. qsort(data.entries,
  6726. (size_t)data.num_entries,
  6727. sizeof(data.entries[0]),
  6728. compare_dir_entries);
  6729. for (i = 0; i < data.num_entries; i++) {
  6730. print_dir_entry(&data.entries[i]);
  6731. mg_free(data.entries[i].file_name);
  6732. }
  6733. mg_free(data.entries);
  6734. }
  6735. conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");
  6736. conn->status_code = 200;
  6737. }
  6738. /* Send len bytes from the opened file to the client. */
  6739. static void
  6740. send_file_data(struct mg_connection *conn,
  6741. struct mg_file *filep,
  6742. int64_t offset,
  6743. int64_t len)
  6744. {
  6745. char buf[MG_BUF_LEN];
  6746. int to_read, num_read, num_written;
  6747. int64_t size;
  6748. if (!filep || !conn) {
  6749. return;
  6750. }
  6751. /* Sanity check the offset */
  6752. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  6753. : (int64_t)(filep->stat.size);
  6754. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  6755. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  6756. /* file stored in memory */
  6757. if (len > size - offset) {
  6758. len = size - offset;
  6759. }
  6760. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  6761. } else if (len > 0 && filep->access.fp != NULL) {
  6762. /* file stored on disk */
  6763. #if defined(__linux__)
  6764. /* sendfile is only available for Linux */
  6765. if ((conn->ssl == 0) && (conn->throttle == 0)
  6766. && (!mg_strcasecmp(conn->ctx->config[ALLOW_SENDFILE_CALL],
  6767. "yes"))) {
  6768. off_t sf_offs = (off_t)offset;
  6769. ssize_t sf_sent;
  6770. int sf_file = fileno(filep->access.fp);
  6771. int loop_cnt = 0;
  6772. do {
  6773. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  6774. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  6775. size_t sf_tosend =
  6776. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  6777. sf_sent =
  6778. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  6779. if (sf_sent > 0) {
  6780. conn->num_bytes_sent += sf_sent;
  6781. len -= sf_sent;
  6782. offset += sf_sent;
  6783. } else if (loop_cnt == 0) {
  6784. /* This file can not be sent using sendfile.
  6785. * This might be the case for pseudo-files in the
  6786. * /sys/ and /proc/ file system.
  6787. * Use the regular user mode copy code instead. */
  6788. break;
  6789. } else if (sf_sent == 0) {
  6790. /* No error, but 0 bytes sent. May be EOF? */
  6791. return;
  6792. }
  6793. loop_cnt++;
  6794. } while ((len > 0) && (sf_sent >= 0));
  6795. if (sf_sent > 0) {
  6796. return; /* OK */
  6797. }
  6798. /* sf_sent<0 means error, thus fall back to the classic way */
  6799. /* This is always the case, if sf_file is not a "normal" file,
  6800. * e.g., for sending data from the output of a CGI process. */
  6801. offset = (int64_t)sf_offs;
  6802. }
  6803. #endif
  6804. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  6805. mg_cry(conn, "%s: fseeko() failed: %s", __func__, strerror(ERRNO));
  6806. mg_send_http_error(
  6807. conn,
  6808. 500,
  6809. "%s",
  6810. "Error: Unable to access file at requested position.");
  6811. } else {
  6812. while (len > 0) {
  6813. /* Calculate how much to read from the file in the buffer */
  6814. to_read = sizeof(buf);
  6815. if ((int64_t)to_read > len) {
  6816. to_read = (int)len;
  6817. }
  6818. /* Read from file, exit the loop on error */
  6819. if ((num_read =
  6820. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  6821. <= 0) {
  6822. break;
  6823. }
  6824. /* Send read bytes to the client, exit the loop on error */
  6825. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  6826. != num_read) {
  6827. break;
  6828. }
  6829. /* Both read and were successful, adjust counters */
  6830. conn->num_bytes_sent += num_written;
  6831. len -= num_written;
  6832. }
  6833. }
  6834. }
  6835. }
  6836. static int
  6837. parse_range_header(const char *header, int64_t *a, int64_t *b)
  6838. {
  6839. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  6840. }
  6841. static void
  6842. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  6843. {
  6844. if (filestat != NULL && buf != NULL) {
  6845. mg_snprintf(NULL,
  6846. NULL, /* All calls to construct_etag use 64 byte buffer */
  6847. buf,
  6848. buf_len,
  6849. "\"%lx.%" INT64_FMT "\"",
  6850. (unsigned long)filestat->last_modified,
  6851. filestat->size);
  6852. }
  6853. }
  6854. static void
  6855. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  6856. {
  6857. if (filep != NULL && filep->fp != NULL) {
  6858. #ifdef _WIN32
  6859. (void)conn; /* Unused. */
  6860. #else
  6861. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  6862. mg_cry(conn,
  6863. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  6864. __func__,
  6865. strerror(ERRNO));
  6866. }
  6867. #endif
  6868. }
  6869. }
  6870. static void
  6871. handle_static_file_request(struct mg_connection *conn,
  6872. const char *path,
  6873. struct mg_file *filep,
  6874. const char *mime_type,
  6875. const char *additional_headers)
  6876. {
  6877. char date[64], lm[64], etag[64];
  6878. char range[128]; /* large enough, so there will be no overflow */
  6879. const char *msg = "OK", *hdr;
  6880. time_t curtime = time(NULL);
  6881. int64_t cl, r1, r2;
  6882. struct vec mime_vec;
  6883. int n, truncated;
  6884. char gz_path[PATH_MAX];
  6885. const char *encoding = "";
  6886. const char *cors1, *cors2, *cors3;
  6887. if (conn == NULL || conn->ctx == NULL || filep == NULL) {
  6888. return;
  6889. }
  6890. if (mime_type == NULL) {
  6891. get_mime_type(conn->ctx, path, &mime_vec);
  6892. } else {
  6893. mime_vec.ptr = mime_type;
  6894. mime_vec.len = strlen(mime_type);
  6895. }
  6896. if (filep->stat.size > INT64_MAX) {
  6897. mg_send_http_error(conn,
  6898. 500,
  6899. "Error: File size is too large to send\n%" INT64_FMT,
  6900. filep->stat.size);
  6901. }
  6902. cl = (int64_t)filep->stat.size;
  6903. conn->status_code = 200;
  6904. range[0] = '\0';
  6905. /* if this file is in fact a pre-gzipped file, rewrite its filename
  6906. * it's important to rewrite the filename after resolving
  6907. * the mime type from it, to preserve the actual file's type */
  6908. if (filep->stat.is_gzipped) {
  6909. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  6910. if (truncated) {
  6911. mg_send_http_error(conn,
  6912. 500,
  6913. "Error: Path of zipped file too long (%s)",
  6914. path);
  6915. return;
  6916. }
  6917. path = gz_path;
  6918. encoding = "Content-Encoding: gzip\r\n";
  6919. }
  6920. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  6921. mg_send_http_error(conn,
  6922. 500,
  6923. "Error: Cannot open file\nfopen(%s): %s",
  6924. path,
  6925. strerror(ERRNO));
  6926. return;
  6927. }
  6928. fclose_on_exec(&filep->access, conn);
  6929. /* If Range: header specified, act accordingly */
  6930. r1 = r2 = 0;
  6931. hdr = mg_get_header(conn, "Range");
  6932. if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 && r1 >= 0
  6933. && r2 >= 0) {
  6934. /* actually, range requests don't play well with a pre-gzipped
  6935. * file (since the range is specified in the uncompressed space) */
  6936. if (filep->stat.is_gzipped) {
  6937. mg_send_http_error(
  6938. conn,
  6939. 416, /* 416 = Range Not Satisfiable */
  6940. "%s",
  6941. "Error: Range requests in gzipped files are not supported");
  6942. (void)mg_fclose(
  6943. &filep->access); /* ignore error on read only file */
  6944. return;
  6945. }
  6946. conn->status_code = 206;
  6947. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  6948. mg_snprintf(conn,
  6949. NULL, /* range buffer is big enough */
  6950. range,
  6951. sizeof(range),
  6952. "Content-Range: bytes "
  6953. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  6954. r1,
  6955. r1 + cl - 1,
  6956. filep->stat.size);
  6957. msg = "Partial Content";
  6958. }
  6959. hdr = mg_get_header(conn, "Origin");
  6960. if (hdr) {
  6961. /* Cross-origin resource sharing (CORS), see
  6962. * http://www.html5rocks.com/en/tutorials/cors/,
  6963. * http://www.html5rocks.com/static/images/cors_server_flowchart.png -
  6964. * preflight is not supported for files. */
  6965. cors1 = "Access-Control-Allow-Origin: ";
  6966. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  6967. cors3 = "\r\n";
  6968. } else {
  6969. cors1 = cors2 = cors3 = "";
  6970. }
  6971. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
  6972. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  6973. gmt_time_string(date, sizeof(date), &curtime);
  6974. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  6975. construct_etag(etag, sizeof(etag), &filep->stat);
  6976. (void)mg_printf(conn,
  6977. "HTTP/1.1 %d %s\r\n"
  6978. "%s%s%s"
  6979. "Date: %s\r\n",
  6980. conn->status_code,
  6981. msg,
  6982. cors1,
  6983. cors2,
  6984. cors3,
  6985. date);
  6986. send_static_cache_header(conn);
  6987. send_additional_header(conn);
  6988. (void)mg_printf(conn,
  6989. "Last-Modified: %s\r\n"
  6990. "Etag: %s\r\n"
  6991. "Content-Type: %.*s\r\n"
  6992. "Content-Length: %" INT64_FMT "\r\n"
  6993. "Connection: %s\r\n"
  6994. "Accept-Ranges: bytes\r\n"
  6995. "%s%s",
  6996. lm,
  6997. etag,
  6998. (int)mime_vec.len,
  6999. mime_vec.ptr,
  7000. cl,
  7001. suggest_connection_header(conn),
  7002. range,
  7003. encoding);
  7004. /* The previous code must not add any header starting with X- to make
  7005. * sure no one of the additional_headers is included twice */
  7006. if (additional_headers != NULL) {
  7007. (void)mg_printf(conn,
  7008. "%.*s\r\n\r\n",
  7009. (int)strlen(additional_headers),
  7010. additional_headers);
  7011. } else {
  7012. (void)mg_printf(conn, "\r\n");
  7013. }
  7014. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  7015. send_file_data(conn, filep, r1, cl);
  7016. }
  7017. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  7018. }
  7019. #if !defined(NO_CACHING)
  7020. static void
  7021. handle_not_modified_static_file_request(struct mg_connection *conn,
  7022. struct mg_file *filep)
  7023. {
  7024. char date[64], lm[64], etag[64];
  7025. time_t curtime = time(NULL);
  7026. if (conn == NULL || filep == NULL) {
  7027. return;
  7028. }
  7029. conn->status_code = 304;
  7030. gmt_time_string(date, sizeof(date), &curtime);
  7031. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  7032. construct_etag(etag, sizeof(etag), &filep->stat);
  7033. (void)mg_printf(conn,
  7034. "HTTP/1.1 %d %s\r\n"
  7035. "Date: %s\r\n",
  7036. conn->status_code,
  7037. mg_get_response_code_text(conn, conn->status_code),
  7038. date);
  7039. send_static_cache_header(conn);
  7040. send_additional_header(conn);
  7041. (void)mg_printf(conn,
  7042. "Last-Modified: %s\r\n"
  7043. "Etag: %s\r\n"
  7044. "Connection: %s\r\n"
  7045. "\r\n",
  7046. lm,
  7047. etag,
  7048. suggest_connection_header(conn));
  7049. }
  7050. #endif
  7051. void
  7052. mg_send_file(struct mg_connection *conn, const char *path)
  7053. {
  7054. mg_send_mime_file(conn, path, NULL);
  7055. }
  7056. void
  7057. mg_send_mime_file(struct mg_connection *conn,
  7058. const char *path,
  7059. const char *mime_type)
  7060. {
  7061. mg_send_mime_file2(conn, path, mime_type, NULL);
  7062. }
  7063. void
  7064. mg_send_mime_file2(struct mg_connection *conn,
  7065. const char *path,
  7066. const char *mime_type,
  7067. const char *additional_headers)
  7068. {
  7069. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7070. if (mg_stat(conn, path, &file.stat)) {
  7071. if (file.stat.is_directory) {
  7072. if (!conn) {
  7073. return;
  7074. }
  7075. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  7076. "yes")) {
  7077. handle_directory_request(conn, path);
  7078. } else {
  7079. mg_send_http_error(conn,
  7080. 403,
  7081. "%s",
  7082. "Error: Directory listing denied");
  7083. }
  7084. } else {
  7085. handle_static_file_request(
  7086. conn, path, &file, mime_type, additional_headers);
  7087. }
  7088. } else {
  7089. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  7090. }
  7091. }
  7092. /* For a given PUT path, create all intermediate subdirectories.
  7093. * Return 0 if the path itself is a directory.
  7094. * Return 1 if the path leads to a file.
  7095. * Return -1 for if the path is too long.
  7096. * Return -2 if path can not be created.
  7097. */
  7098. static int
  7099. put_dir(struct mg_connection *conn, const char *path)
  7100. {
  7101. char buf[PATH_MAX];
  7102. const char *s, *p;
  7103. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7104. size_t len;
  7105. int res = 1;
  7106. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  7107. len = (size_t)(p - path);
  7108. if (len >= sizeof(buf)) {
  7109. /* path too long */
  7110. res = -1;
  7111. break;
  7112. }
  7113. memcpy(buf, path, len);
  7114. buf[len] = '\0';
  7115. /* Try to create intermediate directory */
  7116. DEBUG_TRACE("mkdir(%s)", buf);
  7117. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  7118. /* path does not exixt and can not be created */
  7119. res = -2;
  7120. break;
  7121. }
  7122. /* Is path itself a directory? */
  7123. if (p[1] == '\0') {
  7124. res = 0;
  7125. }
  7126. }
  7127. return res;
  7128. }
  7129. static void
  7130. remove_bad_file(const struct mg_connection *conn, const char *path)
  7131. {
  7132. int r = mg_remove(conn, path);
  7133. if (r != 0) {
  7134. mg_cry(conn, "%s: Cannot remove invalid file %s", __func__, path);
  7135. }
  7136. }
  7137. long long
  7138. mg_store_body(struct mg_connection *conn, const char *path)
  7139. {
  7140. char buf[MG_BUF_LEN];
  7141. long long len = 0;
  7142. int ret, n;
  7143. struct mg_file fi;
  7144. if (conn->consumed_content != 0) {
  7145. mg_cry(conn, "%s: Contents already consumed", __func__);
  7146. return -11;
  7147. }
  7148. ret = put_dir(conn, path);
  7149. if (ret < 0) {
  7150. /* -1 for path too long,
  7151. * -2 for path can not be created. */
  7152. return ret;
  7153. }
  7154. if (ret != 1) {
  7155. /* Return 0 means, path itself is a directory. */
  7156. return 0;
  7157. }
  7158. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  7159. return -12;
  7160. }
  7161. ret = mg_read(conn, buf, sizeof(buf));
  7162. while (ret > 0) {
  7163. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  7164. if (n != ret) {
  7165. (void)mg_fclose(
  7166. &fi.access); /* File is bad and will be removed anyway. */
  7167. remove_bad_file(conn, path);
  7168. return -13;
  7169. }
  7170. len += ret;
  7171. ret = mg_read(conn, buf, sizeof(buf));
  7172. }
  7173. /* File is open for writing. If fclose fails, there was probably an
  7174. * error flushing the buffer to disk, so the file on disk might be
  7175. * broken. Delete it and return an error to the caller. */
  7176. if (mg_fclose(&fi.access) != 0) {
  7177. remove_bad_file(conn, path);
  7178. return -14;
  7179. }
  7180. return len;
  7181. }
  7182. /* Parse HTTP headers from the given buffer, advance buf pointer
  7183. * to the point where parsing stopped.
  7184. * All parameters must be valid pointers (not NULL).
  7185. * Return <0 on error. */
  7186. static int
  7187. parse_http_headers(char **buf, struct mg_request_info *ri)
  7188. {
  7189. int i;
  7190. ri->num_headers = 0;
  7191. for (i = 0; i < (int)ARRAY_SIZE(ri->http_headers); i++) {
  7192. char *dp = *buf;
  7193. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  7194. dp++;
  7195. }
  7196. if (dp == *buf) {
  7197. /* End of headers reached. */
  7198. break;
  7199. }
  7200. if (*dp != ':') {
  7201. /* This is not a valid field. */
  7202. return -1;
  7203. }
  7204. /* End of header key (*dp == ':') */
  7205. /* Truncate here and set the key name */
  7206. *dp = 0;
  7207. ri->http_headers[i].name = *buf;
  7208. do {
  7209. dp++;
  7210. } while (*dp == ' ');
  7211. /* The rest of the line is the value */
  7212. ri->http_headers[i].value = dp;
  7213. *buf = dp + strcspn(dp, "\r\n");
  7214. if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) {
  7215. *buf = NULL;
  7216. }
  7217. ri->num_headers = i + 1;
  7218. if (*buf) {
  7219. (*buf)[0] = 0;
  7220. (*buf)[1] = 0;
  7221. *buf += 2;
  7222. } else {
  7223. *buf = dp;
  7224. break;
  7225. }
  7226. if ((*buf)[0] == '\r') {
  7227. /* This is the end of the header */
  7228. break;
  7229. }
  7230. }
  7231. return ri->num_headers;
  7232. }
  7233. static int
  7234. is_valid_http_method(const char *method)
  7235. {
  7236. /* Check if the method is known to the server. The list of all known
  7237. * HTTP methods can be found here at
  7238. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  7239. */
  7240. return !strcmp(method, "GET") /* HTTP (RFC 2616) */
  7241. || !strcmp(method, "POST") /* HTTP (RFC 2616) */
  7242. || !strcmp(method, "HEAD") /* HTTP (RFC 2616) */
  7243. || !strcmp(method, "PUT") /* HTTP (RFC 2616) */
  7244. || !strcmp(method, "DELETE") /* HTTP (RFC 2616) */
  7245. || !strcmp(method, "OPTIONS") /* HTTP (RFC 2616) */
  7246. /* TRACE method (RFC 2616) is not supported for security reasons */
  7247. || !strcmp(method, "CONNECT") /* HTTP (RFC 2616) */
  7248. || !strcmp(method, "PROPFIND") /* WEBDAV (RFC 2518) */
  7249. || !strcmp(method, "MKCOL") /* WEBDAV (RFC 2518) */
  7250. /* Unsupported WEBDAV Methods: */
  7251. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  7252. /* + 11 methods from RFC 3253 */
  7253. /* ORDERPATCH (RFC 3648) */
  7254. /* ACL (RFC 3744) */
  7255. /* SEARCH (RFC 5323) */
  7256. /* + MicroSoft extensions
  7257. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  7258. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  7259. || !strcmp(method, "PATCH") /* PATCH method (RFC 5789) */
  7260. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  7261. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  7262. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  7263. * to be useful for REST in case a "GET request with body" is
  7264. * required. */
  7265. || !strcmp(method, "REPORT") /* REPORT method (RFC 3253) */
  7266. ;
  7267. }
  7268. /* Parse HTTP request, fill in mg_request_info structure.
  7269. * This function modifies the buffer by NUL-terminating
  7270. * HTTP request components, header names and header values.
  7271. * Parameters:
  7272. * buf (in/out): pointer to the HTTP header to parse and split
  7273. * len (in): length of HTTP header buffer
  7274. * re (out): parsed header as mg_request_info
  7275. * buf and ri must be valid pointers (not NULL), len>0.
  7276. * Returns <0 on error. */
  7277. static int
  7278. parse_http_message(char *buf, int len, struct mg_request_info *ri)
  7279. {
  7280. int is_request, request_length;
  7281. char *start_line;
  7282. request_length = get_request_len(buf, len);
  7283. if (request_length > 0) {
  7284. /* Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_addr,
  7285. * remote_port */
  7286. ri->remote_user = ri->request_method = ri->request_uri =
  7287. ri->http_version = NULL;
  7288. ri->num_headers = 0;
  7289. buf[request_length - 1] = '\0';
  7290. /* RFC says that all initial whitespaces should be ingored */
  7291. while (*buf != '\0' && isspace(*(unsigned char *)buf)) {
  7292. buf++;
  7293. }
  7294. start_line = skip(&buf, "\r\n");
  7295. ri->request_method = skip(&start_line, " ");
  7296. ri->request_uri = skip(&start_line, " ");
  7297. ri->http_version = start_line;
  7298. /* HTTP message could be either HTTP request:
  7299. * "GET / HTTP/1.0 ..."
  7300. * or a HTTP response:
  7301. * "HTTP/1.0 200 OK ..."
  7302. * otherwise it is invalid.
  7303. */
  7304. is_request = is_valid_http_method(ri->request_method);
  7305. if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0)
  7306. || (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
  7307. /* Not a valid request or response: invalid */
  7308. return -1;
  7309. }
  7310. if (is_request) {
  7311. ri->http_version += 5;
  7312. }
  7313. if (parse_http_headers(&buf, ri) < 0) {
  7314. /* Error while parsing headers */
  7315. return -1;
  7316. }
  7317. }
  7318. return request_length;
  7319. }
  7320. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  7321. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  7322. * buffer (which marks the end of HTTP request). Buffer buf may already
  7323. * have some data. The length of the data is stored in nread.
  7324. * Upon every read operation, increase nread by the number of bytes read. */
  7325. static int
  7326. read_request(FILE *fp,
  7327. struct mg_connection *conn,
  7328. char *buf,
  7329. int bufsiz,
  7330. int *nread)
  7331. {
  7332. int request_len, n = 0;
  7333. struct timespec last_action_time;
  7334. double request_timeout;
  7335. if (!conn) {
  7336. return 0;
  7337. }
  7338. memset(&last_action_time, 0, sizeof(last_action_time));
  7339. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  7340. /* value of request_timeout is in seconds, config in milliseconds */
  7341. request_timeout = atof(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  7342. } else {
  7343. request_timeout = -1.0;
  7344. }
  7345. if (conn->handled_requests > 0) {
  7346. if (conn->ctx->config[KEEP_ALIVE_TIMEOUT]) {
  7347. request_timeout =
  7348. atof(conn->ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  7349. }
  7350. }
  7351. request_len = get_request_len(buf, *nread);
  7352. /* first time reading from this connection */
  7353. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  7354. while (request_len == 0) {
  7355. /* Full request not yet received */
  7356. if (conn->ctx->stop_flag != 0) {
  7357. /* Server is to be stopped. */
  7358. return -1;
  7359. }
  7360. if (*nread >= bufsiz) {
  7361. /* Request too long */
  7362. return -2;
  7363. }
  7364. n = pull_inner(
  7365. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  7366. if (n == -2) {
  7367. /* Receive error */
  7368. return -1;
  7369. }
  7370. if (n > 0) {
  7371. *nread += n;
  7372. request_len = get_request_len(buf, *nread);
  7373. } else {
  7374. request_len = 0;
  7375. }
  7376. if ((request_len == 0) && (request_timeout >= 0)) {
  7377. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  7378. > request_timeout) {
  7379. /* Timeout */
  7380. return -1;
  7381. }
  7382. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  7383. }
  7384. }
  7385. return request_len;
  7386. }
  7387. #if !defined(NO_CACHING)
  7388. /* Return True if we should reply 304 Not Modified. */
  7389. static int
  7390. is_not_modified(const struct mg_connection *conn,
  7391. const struct mg_file_stat *filestat)
  7392. {
  7393. char etag[64];
  7394. const char *ims = mg_get_header(conn, "If-Modified-Since");
  7395. const char *inm = mg_get_header(conn, "If-None-Match");
  7396. construct_etag(etag, sizeof(etag), filestat);
  7397. return (inm != NULL && !mg_strcasecmp(etag, inm))
  7398. || ((ims != NULL)
  7399. && (filestat->last_modified <= parse_date_string(ims)));
  7400. }
  7401. #endif /* !NO_CACHING */
  7402. #if !defined(NO_CGI) || !defined(NO_FILES)
  7403. static int
  7404. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  7405. {
  7406. const char *expect, *body;
  7407. char buf[MG_BUF_LEN];
  7408. int to_read, nread, success = 0;
  7409. int64_t buffered_len;
  7410. double timeout = -1.0;
  7411. if (!conn) {
  7412. return 0;
  7413. }
  7414. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  7415. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  7416. }
  7417. expect = mg_get_header(conn, "Expect");
  7418. /* assert(fp != NULL); */
  7419. if (!fp) {
  7420. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  7421. return 0;
  7422. }
  7423. if (conn->content_len == -1 && !conn->is_chunked) {
  7424. /* Content length is not specified by the client. */
  7425. mg_send_http_error(conn,
  7426. 411,
  7427. "%s",
  7428. "Error: Client did not specify content length");
  7429. } else if ((expect != NULL)
  7430. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  7431. /* Client sent an "Expect: xyz" header and xyz is not 100-continue. */
  7432. mg_send_http_error(conn,
  7433. 417,
  7434. "Error: Can not fulfill expectation %s",
  7435. expect);
  7436. } else {
  7437. if (expect != NULL) {
  7438. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  7439. conn->status_code = 100;
  7440. } else {
  7441. conn->status_code = 200;
  7442. }
  7443. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  7444. - conn->consumed_content;
  7445. /* assert(buffered_len >= 0); */
  7446. /* assert(conn->consumed_content == 0); */
  7447. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  7448. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  7449. return 0;
  7450. }
  7451. if (buffered_len > 0) {
  7452. if ((int64_t)buffered_len > conn->content_len) {
  7453. buffered_len = (int)conn->content_len;
  7454. }
  7455. body = conn->buf + conn->request_len + conn->consumed_content;
  7456. push_all(conn->ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  7457. conn->consumed_content += buffered_len;
  7458. }
  7459. nread = 0;
  7460. while (conn->consumed_content < conn->content_len) {
  7461. to_read = sizeof(buf);
  7462. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  7463. to_read = (int)(conn->content_len - conn->consumed_content);
  7464. }
  7465. nread = pull_inner(NULL, conn, buf, to_read, timeout);
  7466. if (nread == -2) {
  7467. /* error */
  7468. break;
  7469. }
  7470. if (nread > 0) {
  7471. if (push_all(conn->ctx, fp, sock, ssl, buf, nread) != nread) {
  7472. break;
  7473. }
  7474. }
  7475. conn->consumed_content += nread;
  7476. }
  7477. if (conn->consumed_content == conn->content_len) {
  7478. success = (nread >= 0);
  7479. }
  7480. /* Each error code path in this function must send an error */
  7481. if (!success) {
  7482. /* NOTE: Maybe some data has already been sent. */
  7483. /* TODO (low): If some data has been sent, a correct error
  7484. * reply can no longer be sent, so just close the connection */
  7485. mg_send_http_error(conn, 500, "%s", "");
  7486. }
  7487. }
  7488. return success;
  7489. }
  7490. #endif
  7491. #if !defined(NO_CGI)
  7492. /* This structure helps to create an environment for the spawned CGI program.
  7493. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  7494. * last element must be NULL.
  7495. * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  7496. * strings must reside in a contiguous buffer. The end of the buffer is
  7497. * marked by two '\0' characters.
  7498. * We satisfy both worlds: we create an envp array (which is vars), all
  7499. * entries are actually pointers inside buf. */
  7500. struct cgi_environment {
  7501. struct mg_connection *conn;
  7502. /* Data block */
  7503. char *buf; /* Environment buffer */
  7504. size_t buflen; /* Space available in buf */
  7505. size_t bufused; /* Space taken in buf */
  7506. /* Index block */
  7507. char **var; /* char **envp */
  7508. size_t varlen; /* Number of variables available in var */
  7509. size_t varused; /* Number of variables stored in var */
  7510. };
  7511. static void addenv(struct cgi_environment *env,
  7512. PRINTF_FORMAT_STRING(const char *fmt),
  7513. ...) PRINTF_ARGS(2, 3);
  7514. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  7515. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  7516. static void
  7517. addenv(struct cgi_environment *env, const char *fmt, ...)
  7518. {
  7519. size_t n, space;
  7520. int truncated = 0;
  7521. char *added;
  7522. va_list ap;
  7523. /* Calculate how much space is left in the buffer */
  7524. space = (env->buflen - env->bufused);
  7525. /* Calculate an estimate for the required space */
  7526. n = strlen(fmt) + 2 + 128;
  7527. do {
  7528. if (space <= n) {
  7529. /* Allocate new buffer */
  7530. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  7531. added = (char *)mg_realloc(env->buf, n);
  7532. if (!added) {
  7533. /* Out of memory */
  7534. mg_cry(env->conn,
  7535. "%s: Cannot allocate memory for CGI variable [%s]",
  7536. __func__,
  7537. fmt);
  7538. return;
  7539. }
  7540. env->buf = added;
  7541. env->buflen = n;
  7542. space = (env->buflen - env->bufused);
  7543. }
  7544. /* Make a pointer to the free space int the buffer */
  7545. added = env->buf + env->bufused;
  7546. /* Copy VARIABLE=VALUE\0 string into the free space */
  7547. va_start(ap, fmt);
  7548. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  7549. va_end(ap);
  7550. /* Do not add truncated strings to the environment */
  7551. if (truncated) {
  7552. /* Reallocate the buffer */
  7553. space = 0;
  7554. n = 1;
  7555. }
  7556. } while (truncated);
  7557. /* Calculate number of bytes added to the environment */
  7558. n = strlen(added) + 1;
  7559. env->bufused += n;
  7560. /* Now update the variable index */
  7561. space = (env->varlen - env->varused);
  7562. if (space < 2) {
  7563. mg_cry(env->conn,
  7564. "%s: Cannot register CGI variable [%s]",
  7565. __func__,
  7566. fmt);
  7567. return;
  7568. }
  7569. /* Append a pointer to the added string into the envp array */
  7570. env->var[env->varused] = added;
  7571. env->varused++;
  7572. }
  7573. static void
  7574. prepare_cgi_environment(struct mg_connection *conn,
  7575. const char *prog,
  7576. struct cgi_environment *env)
  7577. {
  7578. const char *s;
  7579. struct vec var_vec;
  7580. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  7581. int i, truncated, uri_len;
  7582. if (conn == NULL || prog == NULL || env == NULL) {
  7583. return;
  7584. }
  7585. env->conn = conn;
  7586. env->buflen = CGI_ENVIRONMENT_SIZE;
  7587. env->bufused = 0;
  7588. env->buf = (char *)mg_malloc(env->buflen);
  7589. env->varlen = MAX_CGI_ENVIR_VARS;
  7590. env->varused = 0;
  7591. env->var = (char **)mg_malloc(env->buflen * sizeof(char *));
  7592. addenv(env, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  7593. addenv(env, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  7594. addenv(env, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  7595. addenv(env, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  7596. /* Prepare the environment block */
  7597. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  7598. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  7599. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  7600. #if defined(USE_IPV6)
  7601. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  7602. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  7603. } else
  7604. #endif
  7605. {
  7606. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  7607. }
  7608. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  7609. addenv(env, "REMOTE_ADDR=%s", src_addr);
  7610. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  7611. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  7612. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  7613. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  7614. /* SCRIPT_NAME */
  7615. uri_len = (int)strlen(conn->request_info.local_uri);
  7616. if (conn->path_info == NULL) {
  7617. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  7618. /* URI: /path_to_script/script.cgi */
  7619. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  7620. } else {
  7621. /* URI: /path_to_script/ ... using index.cgi */
  7622. const char *index_file = strrchr(prog, '/');
  7623. if (index_file) {
  7624. addenv(env,
  7625. "SCRIPT_NAME=%s%s",
  7626. conn->request_info.local_uri,
  7627. index_file + 1);
  7628. }
  7629. }
  7630. } else {
  7631. /* URI: /path_to_script/script.cgi/path_info */
  7632. addenv(env,
  7633. "SCRIPT_NAME=%.*s",
  7634. uri_len - (int)strlen(conn->path_info),
  7635. conn->request_info.local_uri);
  7636. }
  7637. addenv(env, "SCRIPT_FILENAME=%s", prog);
  7638. if (conn->path_info == NULL) {
  7639. addenv(env, "PATH_TRANSLATED=%s", conn->ctx->config[DOCUMENT_ROOT]);
  7640. } else {
  7641. addenv(env,
  7642. "PATH_TRANSLATED=%s%s",
  7643. conn->ctx->config[DOCUMENT_ROOT],
  7644. conn->path_info);
  7645. }
  7646. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  7647. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  7648. addenv(env, "CONTENT_TYPE=%s", s);
  7649. }
  7650. if (conn->request_info.query_string != NULL) {
  7651. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  7652. }
  7653. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  7654. addenv(env, "CONTENT_LENGTH=%s", s);
  7655. }
  7656. if ((s = getenv("PATH")) != NULL) {
  7657. addenv(env, "PATH=%s", s);
  7658. }
  7659. if (conn->path_info != NULL) {
  7660. addenv(env, "PATH_INFO=%s", conn->path_info);
  7661. }
  7662. if (conn->status_code > 0) {
  7663. /* CGI error handler should show the status code */
  7664. addenv(env, "STATUS=%d", conn->status_code);
  7665. }
  7666. #if defined(_WIN32)
  7667. if ((s = getenv("COMSPEC")) != NULL) {
  7668. addenv(env, "COMSPEC=%s", s);
  7669. }
  7670. if ((s = getenv("SYSTEMROOT")) != NULL) {
  7671. addenv(env, "SYSTEMROOT=%s", s);
  7672. }
  7673. if ((s = getenv("SystemDrive")) != NULL) {
  7674. addenv(env, "SystemDrive=%s", s);
  7675. }
  7676. if ((s = getenv("ProgramFiles")) != NULL) {
  7677. addenv(env, "ProgramFiles=%s", s);
  7678. }
  7679. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  7680. addenv(env, "ProgramFiles(x86)=%s", s);
  7681. }
  7682. #else
  7683. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  7684. addenv(env, "LD_LIBRARY_PATH=%s", s);
  7685. }
  7686. #endif /* _WIN32 */
  7687. if ((s = getenv("PERLLIB")) != NULL) {
  7688. addenv(env, "PERLLIB=%s", s);
  7689. }
  7690. if (conn->request_info.remote_user != NULL) {
  7691. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  7692. addenv(env, "%s", "AUTH_TYPE=Digest");
  7693. }
  7694. /* Add all headers as HTTP_* variables */
  7695. for (i = 0; i < conn->request_info.num_headers; i++) {
  7696. (void)mg_snprintf(conn,
  7697. &truncated,
  7698. http_var_name,
  7699. sizeof(http_var_name),
  7700. "HTTP_%s",
  7701. conn->request_info.http_headers[i].name);
  7702. if (truncated) {
  7703. mg_cry(conn,
  7704. "%s: HTTP header variable too long [%s]",
  7705. __func__,
  7706. conn->request_info.http_headers[i].name);
  7707. continue;
  7708. }
  7709. /* Convert variable name into uppercase, and change - to _ */
  7710. for (p = http_var_name; *p != '\0'; p++) {
  7711. if (*p == '-') {
  7712. *p = '_';
  7713. }
  7714. *p = (char)toupper(*(unsigned char *)p);
  7715. }
  7716. addenv(env,
  7717. "%s=%s",
  7718. http_var_name,
  7719. conn->request_info.http_headers[i].value);
  7720. }
  7721. /* Add user-specified variables */
  7722. s = conn->ctx->config[CGI_ENVIRONMENT];
  7723. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  7724. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  7725. }
  7726. env->var[env->varused] = NULL;
  7727. env->buf[env->bufused] = '\0';
  7728. }
  7729. static void
  7730. handle_cgi_request(struct mg_connection *conn, const char *prog)
  7731. {
  7732. char *buf;
  7733. size_t buflen;
  7734. int headers_len, data_len, i, truncated;
  7735. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  7736. const char *status, *status_text, *connection_state;
  7737. char *pbuf, dir[PATH_MAX], *p;
  7738. struct mg_request_info ri;
  7739. struct cgi_environment blk;
  7740. FILE *in = NULL, *out = NULL, *err = NULL;
  7741. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  7742. pid_t pid = (pid_t)-1;
  7743. if (conn == NULL) {
  7744. return;
  7745. }
  7746. buf = NULL;
  7747. buflen = 16384;
  7748. prepare_cgi_environment(conn, prog, &blk);
  7749. /* CGI must be executed in its own directory. 'dir' must point to the
  7750. * directory containing executable program, 'p' must point to the
  7751. * executable program name relative to 'dir'. */
  7752. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  7753. if (truncated) {
  7754. mg_cry(conn, "Error: CGI program \"%s\": Path too long", prog);
  7755. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  7756. goto done;
  7757. }
  7758. if ((p = strrchr(dir, '/')) != NULL) {
  7759. *p++ = '\0';
  7760. } else {
  7761. dir[0] = '.', dir[1] = '\0';
  7762. p = (char *)prog;
  7763. }
  7764. if (pipe(fdin) != 0 || pipe(fdout) != 0 || pipe(fderr) != 0) {
  7765. status = strerror(ERRNO);
  7766. mg_cry(conn,
  7767. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  7768. prog,
  7769. status);
  7770. mg_send_http_error(conn,
  7771. 500,
  7772. "Error: Cannot create CGI pipe: %s",
  7773. status);
  7774. goto done;
  7775. }
  7776. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  7777. if (pid == (pid_t)-1) {
  7778. status = strerror(ERRNO);
  7779. mg_cry(conn,
  7780. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  7781. prog,
  7782. status);
  7783. mg_send_http_error(conn,
  7784. 500,
  7785. "Error: Cannot spawn CGI process [%s]: %s",
  7786. prog,
  7787. status);
  7788. goto done;
  7789. }
  7790. /* Make sure child closes all pipe descriptors. It must dup them to 0,1 */
  7791. set_close_on_exec((SOCKET)fdin[0], conn); /* stdin read */
  7792. set_close_on_exec((SOCKET)fdout[1], conn); /* stdout write */
  7793. set_close_on_exec((SOCKET)fderr[1], conn); /* stderr write */
  7794. set_close_on_exec((SOCKET)fdin[1], conn); /* stdin write */
  7795. set_close_on_exec((SOCKET)fdout[0], conn); /* stdout read */
  7796. set_close_on_exec((SOCKET)fderr[0], conn); /* stderr read */
  7797. /* Parent closes only one side of the pipes.
  7798. * If we don't mark them as closed, close() attempt before
  7799. * return from this function throws an exception on Windows.
  7800. * Windows does not like when closed descriptor is closed again. */
  7801. (void)close(fdin[0]);
  7802. (void)close(fdout[1]);
  7803. (void)close(fderr[1]);
  7804. fdin[0] = fdout[1] = fderr[1] = -1;
  7805. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  7806. status = strerror(ERRNO);
  7807. mg_cry(conn,
  7808. "Error: CGI program \"%s\": Can not open stdin: %s",
  7809. prog,
  7810. status);
  7811. mg_send_http_error(conn,
  7812. 500,
  7813. "Error: CGI can not open fdin\nfopen: %s",
  7814. status);
  7815. goto done;
  7816. }
  7817. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  7818. status = strerror(ERRNO);
  7819. mg_cry(conn,
  7820. "Error: CGI program \"%s\": Can not open stdout: %s",
  7821. prog,
  7822. status);
  7823. mg_send_http_error(conn,
  7824. 500,
  7825. "Error: CGI can not open fdout\nfopen: %s",
  7826. status);
  7827. goto done;
  7828. }
  7829. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  7830. status = strerror(ERRNO);
  7831. mg_cry(conn,
  7832. "Error: CGI program \"%s\": Can not open stderr: %s",
  7833. prog,
  7834. status);
  7835. mg_send_http_error(conn,
  7836. 500,
  7837. "Error: CGI can not open fdout\nfopen: %s",
  7838. status);
  7839. goto done;
  7840. }
  7841. setbuf(in, NULL);
  7842. setbuf(out, NULL);
  7843. setbuf(err, NULL);
  7844. fout.access.fp = out;
  7845. if ((conn->request_info.content_length > 0) || conn->is_chunked) {
  7846. /* This is a POST/PUT request, or another request with body data. */
  7847. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  7848. /* Error sending the body data */
  7849. mg_cry(conn,
  7850. "Error: CGI program \"%s\": Forward body data failed",
  7851. prog);
  7852. goto done;
  7853. }
  7854. }
  7855. /* Close so child gets an EOF. */
  7856. fclose(in);
  7857. in = NULL;
  7858. fdin[1] = -1;
  7859. /* Now read CGI reply into a buffer. We need to set correct
  7860. * status code, thus we need to see all HTTP headers first.
  7861. * Do not send anything back to client, until we buffer in all
  7862. * HTTP headers. */
  7863. data_len = 0;
  7864. buf = (char *)mg_malloc(buflen);
  7865. if (buf == NULL) {
  7866. mg_send_http_error(conn,
  7867. 500,
  7868. "Error: Not enough memory for CGI buffer (%u bytes)",
  7869. (unsigned int)buflen);
  7870. mg_cry(conn,
  7871. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  7872. "bytes)",
  7873. prog,
  7874. (unsigned int)buflen);
  7875. goto done;
  7876. }
  7877. headers_len = read_request(out, conn, buf, (int)buflen, &data_len);
  7878. if (headers_len <= 0) {
  7879. /* Could not parse the CGI response. Check if some error message on
  7880. * stderr. */
  7881. i = pull_all(err, conn, buf, (int)buflen);
  7882. if (i > 0) {
  7883. mg_cry(conn,
  7884. "Error: CGI program \"%s\" sent error "
  7885. "message: [%.*s]",
  7886. prog,
  7887. i,
  7888. buf);
  7889. mg_send_http_error(conn,
  7890. 500,
  7891. "Error: CGI program \"%s\" sent error "
  7892. "message: [%.*s]",
  7893. prog,
  7894. i,
  7895. buf);
  7896. } else {
  7897. mg_cry(conn,
  7898. "Error: CGI program sent malformed or too big "
  7899. "(>%u bytes) HTTP headers: [%.*s]",
  7900. (unsigned)buflen,
  7901. data_len,
  7902. buf);
  7903. mg_send_http_error(conn,
  7904. 500,
  7905. "Error: CGI program sent malformed or too big "
  7906. "(>%u bytes) HTTP headers: [%.*s]",
  7907. (unsigned)buflen,
  7908. data_len,
  7909. buf);
  7910. }
  7911. goto done;
  7912. }
  7913. pbuf = buf;
  7914. buf[headers_len - 1] = '\0';
  7915. parse_http_headers(&pbuf, &ri);
  7916. /* Make up and send the status line */
  7917. status_text = "OK";
  7918. if ((status = get_header(&ri, "Status")) != NULL) {
  7919. conn->status_code = atoi(status);
  7920. status_text = status;
  7921. while (isdigit(*(const unsigned char *)status_text)
  7922. || *status_text == ' ') {
  7923. status_text++;
  7924. }
  7925. } else if (get_header(&ri, "Location") != NULL) {
  7926. conn->status_code = 302;
  7927. } else {
  7928. conn->status_code = 200;
  7929. }
  7930. connection_state = get_header(&ri, "Connection");
  7931. if (!header_has_option(connection_state, "keep-alive")) {
  7932. conn->must_close = 1;
  7933. }
  7934. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  7935. /* Send headers */
  7936. for (i = 0; i < ri.num_headers; i++) {
  7937. mg_printf(conn,
  7938. "%s: %s\r\n",
  7939. ri.http_headers[i].name,
  7940. ri.http_headers[i].value);
  7941. }
  7942. mg_write(conn, "\r\n", 2);
  7943. /* Send chunk of data that may have been read after the headers */
  7944. conn->num_bytes_sent +=
  7945. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  7946. /* Read the rest of CGI output and send to the client */
  7947. send_file_data(conn, &fout, 0, INT64_MAX);
  7948. done:
  7949. mg_free(blk.var);
  7950. mg_free(blk.buf);
  7951. if (pid != (pid_t)-1) {
  7952. kill(pid, SIGKILL);
  7953. #if !defined(_WIN32)
  7954. {
  7955. int st;
  7956. while (waitpid(pid, &st, 0) != -1)
  7957. ; /* clean zombies */
  7958. }
  7959. #endif
  7960. }
  7961. if (fdin[0] != -1) {
  7962. close(fdin[0]);
  7963. }
  7964. if (fdout[1] != -1) {
  7965. close(fdout[1]);
  7966. }
  7967. if (in != NULL) {
  7968. fclose(in);
  7969. } else if (fdin[1] != -1) {
  7970. close(fdin[1]);
  7971. }
  7972. if (out != NULL) {
  7973. fclose(out);
  7974. } else if (fdout[0] != -1) {
  7975. close(fdout[0]);
  7976. }
  7977. if (err != NULL) {
  7978. fclose(err);
  7979. } else if (fderr[0] != -1) {
  7980. close(fderr[0]);
  7981. }
  7982. if (buf != NULL) {
  7983. mg_free(buf);
  7984. }
  7985. }
  7986. #endif /* !NO_CGI */
  7987. #if !defined(NO_FILES)
  7988. static void
  7989. mkcol(struct mg_connection *conn, const char *path)
  7990. {
  7991. int rc, body_len;
  7992. struct de de;
  7993. char date[64];
  7994. time_t curtime = time(NULL);
  7995. if (conn == NULL) {
  7996. return;
  7997. }
  7998. /* TODO (mid): Check the mg_send_http_error situations in this function */
  7999. memset(&de.file, 0, sizeof(de.file));
  8000. if (!mg_stat(conn, path, &de.file)) {
  8001. mg_cry(conn,
  8002. "%s: mg_stat(%s) failed: %s",
  8003. __func__,
  8004. path,
  8005. strerror(ERRNO));
  8006. }
  8007. if (de.file.last_modified) {
  8008. /* TODO (mid): This check does not seem to make any sense ! */
  8009. /* TODO (mid): Add a webdav unit test first, before changing
  8010. * anything here. */
  8011. mg_send_http_error(
  8012. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  8013. return;
  8014. }
  8015. body_len = conn->data_len - conn->request_len;
  8016. if (body_len > 0) {
  8017. mg_send_http_error(
  8018. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  8019. return;
  8020. }
  8021. rc = mg_mkdir(conn, path, 0755);
  8022. if (rc == 0) {
  8023. conn->status_code = 201;
  8024. gmt_time_string(date, sizeof(date), &curtime);
  8025. mg_printf(conn,
  8026. "HTTP/1.1 %d Created\r\n"
  8027. "Date: %s\r\n",
  8028. conn->status_code,
  8029. date);
  8030. send_static_cache_header(conn);
  8031. send_additional_header(conn);
  8032. mg_printf(conn,
  8033. "Content-Length: 0\r\n"
  8034. "Connection: %s\r\n\r\n",
  8035. suggest_connection_header(conn));
  8036. } else if (rc == -1) {
  8037. if (errno == EEXIST) {
  8038. mg_send_http_error(
  8039. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  8040. } else if (errno == EACCES) {
  8041. mg_send_http_error(
  8042. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  8043. } else if (errno == ENOENT) {
  8044. mg_send_http_error(
  8045. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  8046. } else {
  8047. mg_send_http_error(
  8048. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  8049. }
  8050. }
  8051. }
  8052. static void
  8053. put_file(struct mg_connection *conn, const char *path)
  8054. {
  8055. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8056. const char *range;
  8057. int64_t r1, r2;
  8058. int rc;
  8059. char date[64];
  8060. time_t curtime = time(NULL);
  8061. if (conn == NULL) {
  8062. return;
  8063. }
  8064. if (mg_stat(conn, path, &file.stat)) {
  8065. /* File already exists */
  8066. conn->status_code = 200;
  8067. if (file.stat.is_directory) {
  8068. /* This is an already existing directory,
  8069. * so there is nothing to do for the server. */
  8070. rc = 0;
  8071. } else {
  8072. /* File exists and is not a directory. */
  8073. /* Can it be replaced? */
  8074. if (file.access.membuf != NULL) {
  8075. /* This is an "in-memory" file, that can not be replaced */
  8076. mg_send_http_error(
  8077. conn,
  8078. 405,
  8079. "Error: Put not possible\nReplacing %s is not supported",
  8080. path);
  8081. return;
  8082. }
  8083. /* Check if the server may write this file */
  8084. if (access(path, W_OK) == 0) {
  8085. /* Access granted */
  8086. conn->status_code = 200;
  8087. rc = 1;
  8088. } else {
  8089. mg_send_http_error(
  8090. conn,
  8091. 403,
  8092. "Error: Put not possible\nReplacing %s is not allowed",
  8093. path);
  8094. return;
  8095. }
  8096. }
  8097. } else {
  8098. /* File should be created */
  8099. conn->status_code = 201;
  8100. rc = put_dir(conn, path);
  8101. }
  8102. if (rc == 0) {
  8103. /* put_dir returns 0 if path is a directory */
  8104. gmt_time_string(date, sizeof(date), &curtime);
  8105. mg_printf(conn,
  8106. "HTTP/1.1 %d %s\r\n",
  8107. conn->status_code,
  8108. mg_get_response_code_text(NULL, conn->status_code));
  8109. send_no_cache_header(conn);
  8110. send_additional_header(conn);
  8111. mg_printf(conn,
  8112. "Date: %s\r\n"
  8113. "Content-Length: 0\r\n"
  8114. "Connection: %s\r\n\r\n",
  8115. date,
  8116. suggest_connection_header(conn));
  8117. /* Request to create a directory has been fulfilled successfully.
  8118. * No need to put a file. */
  8119. return;
  8120. }
  8121. if (rc == -1) {
  8122. /* put_dir returns -1 if the path is too long */
  8123. mg_send_http_error(conn,
  8124. 414,
  8125. "Error: Path too long\nput_dir(%s): %s",
  8126. path,
  8127. strerror(ERRNO));
  8128. return;
  8129. }
  8130. if (rc == -2) {
  8131. /* put_dir returns -2 if the directory can not be created */
  8132. mg_send_http_error(conn,
  8133. 500,
  8134. "Error: Can not create directory\nput_dir(%s): %s",
  8135. path,
  8136. strerror(ERRNO));
  8137. return;
  8138. }
  8139. /* A file should be created or overwritten. */
  8140. /* Currently CivetWeb does not nead read+write access. */
  8141. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  8142. || file.access.fp == NULL) {
  8143. (void)mg_fclose(&file.access);
  8144. mg_send_http_error(conn,
  8145. 500,
  8146. "Error: Can not create file\nfopen(%s): %s",
  8147. path,
  8148. strerror(ERRNO));
  8149. return;
  8150. }
  8151. fclose_on_exec(&file.access, conn);
  8152. range = mg_get_header(conn, "Content-Range");
  8153. r1 = r2 = 0;
  8154. if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
  8155. conn->status_code = 206; /* Partial content */
  8156. fseeko(file.access.fp, r1, SEEK_SET);
  8157. }
  8158. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  8159. /* forward_body_data failed.
  8160. * The error code has already been sent to the client,
  8161. * and conn->status_code is already set. */
  8162. (void)mg_fclose(&file.access);
  8163. return;
  8164. }
  8165. if (mg_fclose(&file.access) != 0) {
  8166. /* fclose failed. This might have different reasons, but a likely
  8167. * one is "no space on disk", http 507. */
  8168. conn->status_code = 507;
  8169. }
  8170. gmt_time_string(date, sizeof(date), &curtime);
  8171. mg_printf(conn,
  8172. "HTTP/1.1 %d %s\r\n",
  8173. conn->status_code,
  8174. mg_get_response_code_text(NULL, conn->status_code));
  8175. send_no_cache_header(conn);
  8176. send_additional_header(conn);
  8177. mg_printf(conn,
  8178. "Date: %s\r\n"
  8179. "Content-Length: 0\r\n"
  8180. "Connection: %s\r\n\r\n",
  8181. date,
  8182. suggest_connection_header(conn));
  8183. }
  8184. static void
  8185. delete_file(struct mg_connection *conn, const char *path)
  8186. {
  8187. struct de de;
  8188. memset(&de.file, 0, sizeof(de.file));
  8189. if (!mg_stat(conn, path, &de.file)) {
  8190. /* mg_stat returns 0 if the file does not exist */
  8191. mg_send_http_error(conn,
  8192. 404,
  8193. "Error: Cannot delete file\nFile %s not found",
  8194. path);
  8195. return;
  8196. }
  8197. #if 0 /* Ignore if a file in memory is inside a folder */
  8198. if (de.access.membuf != NULL) {
  8199. /* the file is cached in memory */
  8200. mg_send_http_error(
  8201. conn,
  8202. 405,
  8203. "Error: Delete not possible\nDeleting %s is not supported",
  8204. path);
  8205. return;
  8206. }
  8207. #endif
  8208. if (de.file.is_directory) {
  8209. if (remove_directory(conn, path)) {
  8210. /* Delete is successful: Return 204 without content. */
  8211. mg_send_http_error(conn, 204, "%s", "");
  8212. } else {
  8213. /* Delete is not successful: Return 500 (Server error). */
  8214. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  8215. }
  8216. return;
  8217. }
  8218. /* This is an existing file (not a directory).
  8219. * Check if write permission is granted. */
  8220. if (access(path, W_OK) != 0) {
  8221. /* File is read only */
  8222. mg_send_http_error(
  8223. conn,
  8224. 403,
  8225. "Error: Delete not possible\nDeleting %s is not allowed",
  8226. path);
  8227. return;
  8228. }
  8229. /* Try to delete it. */
  8230. if (mg_remove(conn, path) == 0) {
  8231. /* Delete was successful: Return 204 without content. */
  8232. mg_send_http_error(conn, 204, "%s", "");
  8233. } else {
  8234. /* Delete not successful (file locked). */
  8235. mg_send_http_error(conn,
  8236. 423,
  8237. "Error: Cannot delete file\nremove(%s): %s",
  8238. path,
  8239. strerror(ERRNO));
  8240. }
  8241. }
  8242. #endif /* !NO_FILES */
  8243. static void
  8244. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  8245. static void
  8246. do_ssi_include(struct mg_connection *conn,
  8247. const char *ssi,
  8248. char *tag,
  8249. int include_level)
  8250. {
  8251. char file_name[MG_BUF_LEN], path[512], *p;
  8252. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8253. size_t len;
  8254. int truncated = 0;
  8255. if (conn == NULL) {
  8256. return;
  8257. }
  8258. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  8259. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  8260. * always < MG_BUF_LEN. */
  8261. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  8262. /* File name is relative to the webserver root */
  8263. file_name[511] = 0;
  8264. (void)mg_snprintf(conn,
  8265. &truncated,
  8266. path,
  8267. sizeof(path),
  8268. "%s/%s",
  8269. conn->ctx->config[DOCUMENT_ROOT],
  8270. file_name);
  8271. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  8272. /* File name is relative to the webserver working directory
  8273. * or it is absolute system path */
  8274. file_name[511] = 0;
  8275. (void)
  8276. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  8277. } else if (sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1
  8278. || sscanf(tag, " \"%511[^\"]\"", file_name) == 1) {
  8279. /* File name is relative to the currect document */
  8280. file_name[511] = 0;
  8281. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  8282. if (!truncated) {
  8283. if ((p = strrchr(path, '/')) != NULL) {
  8284. p[1] = '\0';
  8285. }
  8286. len = strlen(path);
  8287. (void)mg_snprintf(conn,
  8288. &truncated,
  8289. path + len,
  8290. sizeof(path) - len,
  8291. "%s",
  8292. file_name);
  8293. }
  8294. } else {
  8295. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  8296. return;
  8297. }
  8298. if (truncated) {
  8299. mg_cry(conn, "SSI #include path length overflow: [%s]", tag);
  8300. return;
  8301. }
  8302. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  8303. mg_cry(conn,
  8304. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  8305. tag,
  8306. path,
  8307. strerror(ERRNO));
  8308. } else {
  8309. fclose_on_exec(&file.access, conn);
  8310. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  8311. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  8312. path) > 0) {
  8313. send_ssi_file(conn, path, &file, include_level + 1);
  8314. } else {
  8315. send_file_data(conn, &file, 0, INT64_MAX);
  8316. }
  8317. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  8318. }
  8319. }
  8320. #if !defined(NO_POPEN)
  8321. static void
  8322. do_ssi_exec(struct mg_connection *conn, char *tag)
  8323. {
  8324. char cmd[1024] = "";
  8325. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8326. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  8327. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  8328. } else {
  8329. cmd[1023] = 0;
  8330. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  8331. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  8332. } else {
  8333. send_file_data(conn, &file, 0, INT64_MAX);
  8334. pclose(file.access.fp);
  8335. }
  8336. }
  8337. }
  8338. #endif /* !NO_POPEN */
  8339. static int
  8340. mg_fgetc(struct mg_file *filep, int offset)
  8341. {
  8342. if (filep == NULL) {
  8343. return EOF;
  8344. }
  8345. if (filep->access.membuf != NULL && offset >= 0
  8346. && ((unsigned int)(offset)) < filep->stat.size) {
  8347. return ((const unsigned char *)filep->access.membuf)[offset];
  8348. } else if (filep->access.fp != NULL) {
  8349. return fgetc(filep->access.fp);
  8350. } else {
  8351. return EOF;
  8352. }
  8353. }
  8354. static void
  8355. send_ssi_file(struct mg_connection *conn,
  8356. const char *path,
  8357. struct mg_file *filep,
  8358. int include_level)
  8359. {
  8360. char buf[MG_BUF_LEN];
  8361. int ch, offset, len, in_ssi_tag;
  8362. if (include_level > 10) {
  8363. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  8364. return;
  8365. }
  8366. in_ssi_tag = len = offset = 0;
  8367. while ((ch = mg_fgetc(filep, offset)) != EOF) {
  8368. if (in_ssi_tag && ch == '>') {
  8369. in_ssi_tag = 0;
  8370. buf[len++] = (char)ch;
  8371. buf[len] = '\0';
  8372. /* assert(len <= (int) sizeof(buf)); */
  8373. if (len > (int)sizeof(buf)) {
  8374. break;
  8375. }
  8376. if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
  8377. /* Not an SSI tag, pass it */
  8378. (void)mg_write(conn, buf, (size_t)len);
  8379. } else {
  8380. if (!memcmp(buf + 5, "include", 7)) {
  8381. do_ssi_include(conn, path, buf + 12, include_level);
  8382. #if !defined(NO_POPEN)
  8383. } else if (!memcmp(buf + 5, "exec", 4)) {
  8384. do_ssi_exec(conn, buf + 9);
  8385. #endif /* !NO_POPEN */
  8386. } else {
  8387. mg_cry(conn,
  8388. "%s: unknown SSI "
  8389. "command: \"%s\"",
  8390. path,
  8391. buf);
  8392. }
  8393. }
  8394. len = 0;
  8395. } else if (in_ssi_tag) {
  8396. if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
  8397. /* Not an SSI tag */
  8398. in_ssi_tag = 0;
  8399. } else if (len == (int)sizeof(buf) - 2) {
  8400. mg_cry(conn, "%s: SSI tag is too large", path);
  8401. len = 0;
  8402. }
  8403. buf[len++] = (char)(ch & 0xff);
  8404. } else if (ch == '<') {
  8405. in_ssi_tag = 1;
  8406. if (len > 0) {
  8407. mg_write(conn, buf, (size_t)len);
  8408. }
  8409. len = 0;
  8410. buf[len++] = (char)(ch & 0xff);
  8411. } else {
  8412. buf[len++] = (char)(ch & 0xff);
  8413. if (len == (int)sizeof(buf)) {
  8414. mg_write(conn, buf, (size_t)len);
  8415. len = 0;
  8416. }
  8417. }
  8418. }
  8419. /* Send the rest of buffered data */
  8420. if (len > 0) {
  8421. mg_write(conn, buf, (size_t)len);
  8422. }
  8423. }
  8424. static void
  8425. handle_ssi_file_request(struct mg_connection *conn,
  8426. const char *path,
  8427. struct mg_file *filep)
  8428. {
  8429. char date[64];
  8430. time_t curtime = time(NULL);
  8431. const char *cors1, *cors2, *cors3;
  8432. if (conn == NULL || path == NULL || filep == NULL) {
  8433. return;
  8434. }
  8435. if (mg_get_header(conn, "Origin")) {
  8436. /* Cross-origin resource sharing (CORS). */
  8437. cors1 = "Access-Control-Allow-Origin: ";
  8438. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  8439. cors3 = "\r\n";
  8440. } else {
  8441. cors1 = cors2 = cors3 = "";
  8442. }
  8443. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8444. /* File exists (precondition for calling this function),
  8445. * but can not be opened by the server. */
  8446. mg_send_http_error(conn,
  8447. 500,
  8448. "Error: Cannot read file\nfopen(%s): %s",
  8449. path,
  8450. strerror(ERRNO));
  8451. } else {
  8452. conn->must_close = 1;
  8453. gmt_time_string(date, sizeof(date), &curtime);
  8454. fclose_on_exec(&filep->access, conn);
  8455. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  8456. send_no_cache_header(conn);
  8457. send_additional_header(conn);
  8458. mg_printf(conn,
  8459. "%s%s%s"
  8460. "Date: %s\r\n"
  8461. "Content-Type: text/html\r\n"
  8462. "Connection: %s\r\n\r\n",
  8463. cors1,
  8464. cors2,
  8465. cors3,
  8466. date,
  8467. suggest_connection_header(conn));
  8468. send_ssi_file(conn, path, filep, 0);
  8469. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  8470. }
  8471. }
  8472. #if !defined(NO_FILES)
  8473. static void
  8474. send_options(struct mg_connection *conn)
  8475. {
  8476. char date[64];
  8477. time_t curtime = time(NULL);
  8478. if (!conn) {
  8479. return;
  8480. }
  8481. conn->status_code = 200;
  8482. conn->must_close = 1;
  8483. gmt_time_string(date, sizeof(date), &curtime);
  8484. /* We do not set a "Cache-Control" header here, but leave the default.
  8485. * Since browsers do not send an OPTIONS request, we can not test the
  8486. * effect anyway. */
  8487. mg_printf(conn,
  8488. "HTTP/1.1 200 OK\r\n"
  8489. "Date: %s\r\n"
  8490. "Connection: %s\r\n"
  8491. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  8492. "PROPFIND, MKCOL\r\n"
  8493. "DAV: 1\r\n",
  8494. date,
  8495. suggest_connection_header(conn));
  8496. send_additional_header(conn);
  8497. mg_printf(conn, "\r\n");
  8498. }
  8499. /* Writes PROPFIND properties for a collection element */
  8500. static void
  8501. print_props(struct mg_connection *conn,
  8502. const char *uri,
  8503. struct mg_file_stat *filep)
  8504. {
  8505. char mtime[64];
  8506. if (conn == NULL || uri == NULL || filep == NULL) {
  8507. return;
  8508. }
  8509. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  8510. conn->num_bytes_sent +=
  8511. mg_printf(conn,
  8512. "<d:response>"
  8513. "<d:href>%s</d:href>"
  8514. "<d:propstat>"
  8515. "<d:prop>"
  8516. "<d:resourcetype>%s</d:resourcetype>"
  8517. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  8518. "<d:getlastmodified>%s</d:getlastmodified>"
  8519. "</d:prop>"
  8520. "<d:status>HTTP/1.1 200 OK</d:status>"
  8521. "</d:propstat>"
  8522. "</d:response>\n",
  8523. uri,
  8524. filep->is_directory ? "<d:collection/>" : "",
  8525. filep->size,
  8526. mtime);
  8527. }
  8528. static void
  8529. print_dav_dir_entry(struct de *de, void *data)
  8530. {
  8531. char href[PATH_MAX];
  8532. char href_encoded[PATH_MAX * 3 /* worst case */];
  8533. int truncated;
  8534. struct mg_connection *conn = (struct mg_connection *)data;
  8535. if (!de || !conn) {
  8536. return;
  8537. }
  8538. mg_snprintf(conn,
  8539. &truncated,
  8540. href,
  8541. sizeof(href),
  8542. "%s%s",
  8543. conn->request_info.local_uri,
  8544. de->file_name);
  8545. if (!truncated) {
  8546. mg_url_encode(href, href_encoded, PATH_MAX * 3);
  8547. print_props(conn, href_encoded, &de->file);
  8548. }
  8549. }
  8550. static void
  8551. handle_propfind(struct mg_connection *conn,
  8552. const char *path,
  8553. struct mg_file_stat *filep)
  8554. {
  8555. const char *depth = mg_get_header(conn, "Depth");
  8556. char date[64];
  8557. time_t curtime = time(NULL);
  8558. gmt_time_string(date, sizeof(date), &curtime);
  8559. if (!conn || !path || !filep || !conn->ctx) {
  8560. return;
  8561. }
  8562. conn->must_close = 1;
  8563. conn->status_code = 207;
  8564. mg_printf(conn,
  8565. "HTTP/1.1 207 Multi-Status\r\n"
  8566. "Date: %s\r\n",
  8567. date);
  8568. send_static_cache_header(conn);
  8569. send_additional_header(conn);
  8570. mg_printf(conn,
  8571. "Connection: %s\r\n"
  8572. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  8573. suggest_connection_header(conn));
  8574. conn->num_bytes_sent +=
  8575. mg_printf(conn,
  8576. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  8577. "<d:multistatus xmlns:d='DAV:'>\n");
  8578. /* Print properties for the requested resource itself */
  8579. print_props(conn, conn->request_info.local_uri, filep);
  8580. /* If it is a directory, print directory entries too if Depth is not 0 */
  8581. if (filep && filep->is_directory
  8582. && !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")
  8583. && (depth == NULL || strcmp(depth, "0") != 0)) {
  8584. scan_directory(conn, path, conn, &print_dav_dir_entry);
  8585. }
  8586. conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");
  8587. }
  8588. #endif
  8589. void
  8590. mg_lock_connection(struct mg_connection *conn)
  8591. {
  8592. if (conn) {
  8593. (void)pthread_mutex_lock(&conn->mutex);
  8594. }
  8595. }
  8596. void
  8597. mg_unlock_connection(struct mg_connection *conn)
  8598. {
  8599. if (conn) {
  8600. (void)pthread_mutex_unlock(&conn->mutex);
  8601. }
  8602. }
  8603. void
  8604. mg_lock_context(struct mg_context *ctx)
  8605. {
  8606. if (ctx) {
  8607. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  8608. }
  8609. }
  8610. void
  8611. mg_unlock_context(struct mg_context *ctx)
  8612. {
  8613. if (ctx) {
  8614. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  8615. }
  8616. }
  8617. #if defined(USE_TIMERS)
  8618. #define TIMER_API static
  8619. #include "timer.inl"
  8620. #endif /* USE_TIMERS */
  8621. #ifdef USE_LUA
  8622. #include "mod_lua.inl"
  8623. #endif /* USE_LUA */
  8624. #ifdef USE_DUKTAPE
  8625. #include "mod_duktape.inl"
  8626. #endif /* USE_DUKTAPE */
  8627. #if defined(USE_WEBSOCKET)
  8628. #if !defined(NO_SSL_DL)
  8629. #define SHA_API static
  8630. #include "sha1.inl"
  8631. #endif
  8632. static int
  8633. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  8634. {
  8635. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  8636. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  8637. SHA_CTX sha_ctx;
  8638. int truncated;
  8639. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  8640. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  8641. if (truncated) {
  8642. conn->must_close = 1;
  8643. return 0;
  8644. }
  8645. SHA1_Init(&sha_ctx);
  8646. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  8647. SHA1_Final((unsigned char *)sha, &sha_ctx);
  8648. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  8649. mg_printf(conn,
  8650. "HTTP/1.1 101 Switching Protocols\r\n"
  8651. "Upgrade: websocket\r\n"
  8652. "Connection: Upgrade\r\n"
  8653. "Sec-WebSocket-Accept: %s\r\n",
  8654. b64_sha);
  8655. if (conn->request_info.acceptedWebSocketSubprotocol) {
  8656. mg_printf(conn,
  8657. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  8658. conn->request_info.acceptedWebSocketSubprotocol);
  8659. } else {
  8660. mg_printf(conn, "%s", "\r\n");
  8661. }
  8662. return 1;
  8663. }
  8664. static void
  8665. read_websocket(struct mg_connection *conn,
  8666. mg_websocket_data_handler ws_data_handler,
  8667. void *callback_data)
  8668. {
  8669. /* Pointer to the beginning of the portion of the incoming websocket
  8670. * message queue.
  8671. * The original websocket upgrade request is never removed, so the queue
  8672. * begins after it. */
  8673. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  8674. int n, error, exit_by_callback;
  8675. /* body_len is the length of the entire queue in bytes
  8676. * len is the length of the current message
  8677. * data_len is the length of the current message's data payload
  8678. * header_len is the length of the current message's header */
  8679. size_t i, len, mask_len = 0, data_len = 0, header_len, body_len;
  8680. /* "The masking key is a 32-bit value chosen at random by the client."
  8681. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  8682. */
  8683. unsigned char mask[4];
  8684. /* data points to the place where the message is stored when passed to
  8685. * the
  8686. * websocket_data callback. This is either mem on the stack, or a
  8687. * dynamically allocated buffer if it is too large. */
  8688. unsigned char mem[4096];
  8689. unsigned char *data = mem;
  8690. unsigned char mop; /* mask flag and opcode */
  8691. double timeout = -1.0;
  8692. if (conn->ctx->config[WEBSOCKET_TIMEOUT]) {
  8693. timeout = atoi(conn->ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  8694. }
  8695. if ((timeout <= 0.0) && (conn->ctx->config[REQUEST_TIMEOUT])) {
  8696. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  8697. }
  8698. mg_set_thread_name("wsock");
  8699. /* Loop continuously, reading messages from the socket, invoking the
  8700. * callback, and waiting repeatedly until an error occurs. */
  8701. while (!conn->ctx->stop_flag) {
  8702. header_len = 0;
  8703. assert(conn->data_len >= conn->request_len);
  8704. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  8705. len = buf[1] & 127;
  8706. mask_len = (buf[1] & 128) ? 4 : 0;
  8707. if ((len < 126) && (body_len >= mask_len)) {
  8708. /* inline 7-bit length field */
  8709. data_len = len;
  8710. header_len = 2 + mask_len;
  8711. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  8712. /* 16-bit length field */
  8713. header_len = 4 + mask_len;
  8714. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  8715. } else if (body_len >= (10 + mask_len)) {
  8716. /* 64-bit length field */
  8717. uint32_t l1, l2;
  8718. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  8719. memcpy(&l2, &buf[6], 4);
  8720. header_len = 10 + mask_len;
  8721. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  8722. }
  8723. }
  8724. if (header_len > 0 && body_len >= header_len) {
  8725. /* Allocate space to hold websocket payload */
  8726. data = mem;
  8727. if (data_len > sizeof(mem)) {
  8728. data = (unsigned char *)mg_malloc(data_len);
  8729. if (data == NULL) {
  8730. /* Allocation failed, exit the loop and then close the
  8731. * connection */
  8732. mg_cry(conn, "websocket out of memory; closing connection");
  8733. break;
  8734. }
  8735. }
  8736. /* Copy the mask before we shift the queue and destroy it */
  8737. if (mask_len > 0) {
  8738. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  8739. } else {
  8740. memset(mask, 0, sizeof(mask));
  8741. }
  8742. /* Read frame payload from the first message in the queue into
  8743. * data and advance the queue by moving the memory in place. */
  8744. assert(body_len >= header_len);
  8745. if (data_len + header_len > body_len) {
  8746. mop = buf[0]; /* current mask and opcode */
  8747. /* Overflow case */
  8748. len = body_len - header_len;
  8749. memcpy(data, buf + header_len, len);
  8750. error = 0;
  8751. while (len < data_len) {
  8752. n = pull_inner(NULL,
  8753. conn,
  8754. (char *)(data + len),
  8755. (int)(data_len - len),
  8756. timeout);
  8757. if (n <= -2) {
  8758. error = 1;
  8759. break;
  8760. } else if (n > 0) {
  8761. len += (size_t)n;
  8762. } else {
  8763. /* Timeout: should retry */
  8764. /* TODO: retry condition */
  8765. }
  8766. }
  8767. if (error) {
  8768. mg_cry(conn, "Websocket pull failed; closing connection");
  8769. break;
  8770. }
  8771. conn->data_len = conn->request_len;
  8772. } else {
  8773. mop = buf[0]; /* current mask and opcode, overwritten by
  8774. * memmove() */
  8775. /* Length of the message being read at the front of the
  8776. * queue */
  8777. len = data_len + header_len;
  8778. /* Copy the data payload into the data pointer for the
  8779. * callback */
  8780. memcpy(data, buf + header_len, data_len);
  8781. /* Move the queue forward len bytes */
  8782. memmove(buf, buf + len, body_len - len);
  8783. /* Mark the queue as advanced */
  8784. conn->data_len -= (int)len;
  8785. }
  8786. /* Apply mask if necessary */
  8787. if (mask_len > 0) {
  8788. for (i = 0; i < data_len; ++i) {
  8789. data[i] ^= mask[i & 3];
  8790. }
  8791. }
  8792. /* Exit the loop if callback signals to exit (server side),
  8793. * or "connection close" opcode received (client side). */
  8794. exit_by_callback = 0;
  8795. if ((ws_data_handler != NULL)
  8796. && !ws_data_handler(
  8797. conn, mop, (char *)data, data_len, callback_data)) {
  8798. exit_by_callback = 1;
  8799. }
  8800. if (data != mem) {
  8801. mg_free(data);
  8802. }
  8803. if (exit_by_callback
  8804. || ((mop & 0xf) == WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  8805. /* Opcode == 8, connection close */
  8806. break;
  8807. }
  8808. /* Not breaking the loop, process next websocket frame. */
  8809. } else {
  8810. /* Read from the socket into the next available location in the
  8811. * message queue. */
  8812. n = pull_inner(NULL,
  8813. conn,
  8814. conn->buf + conn->data_len,
  8815. conn->buf_size - conn->data_len,
  8816. timeout);
  8817. if (n <= -2) {
  8818. /* Error, no bytes read */
  8819. break;
  8820. }
  8821. if (n > 0) {
  8822. conn->data_len += n;
  8823. } else {
  8824. /* Timeout: should retry */
  8825. /* TODO: get timeout def */
  8826. }
  8827. }
  8828. }
  8829. mg_set_thread_name("worker");
  8830. }
  8831. static int
  8832. mg_websocket_write_exec(struct mg_connection *conn,
  8833. int opcode,
  8834. const char *data,
  8835. size_t dataLen,
  8836. uint32_t masking_key)
  8837. {
  8838. unsigned char header[14];
  8839. size_t headerLen = 1;
  8840. int retval = -1;
  8841. #if defined(__GNUC__) || defined(__MINGW32__)
  8842. /* Disable spurious conversion warning for GCC */
  8843. #pragma GCC diagnostic push
  8844. #pragma GCC diagnostic ignored "-Wconversion"
  8845. #endif
  8846. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  8847. #if defined(__GNUC__) || defined(__MINGW32__)
  8848. #pragma GCC diagnostic pop
  8849. #endif
  8850. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  8851. if (dataLen < 126) {
  8852. /* inline 7-bit length field */
  8853. header[1] = (unsigned char)dataLen;
  8854. headerLen = 2;
  8855. } else if (dataLen <= 0xFFFF) {
  8856. /* 16-bit length field */
  8857. uint16_t len = htons((uint16_t)dataLen);
  8858. header[1] = 126;
  8859. memcpy(header + 2, &len, 2);
  8860. headerLen = 4;
  8861. } else {
  8862. /* 64-bit length field */
  8863. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  8864. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  8865. header[1] = 127;
  8866. memcpy(header + 2, &len1, 4);
  8867. memcpy(header + 6, &len2, 4);
  8868. headerLen = 10;
  8869. }
  8870. if (masking_key) {
  8871. /* add mask */
  8872. header[1] |= 0x80;
  8873. memcpy(header + headerLen, &masking_key, 4);
  8874. headerLen += 4;
  8875. }
  8876. /* Note that POSIX/Winsock's send() is threadsafe
  8877. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  8878. * but mongoose's mg_printf/mg_write is not (because of the loop in
  8879. * push(), although that is only a problem if the packet is large or
  8880. * outgoing buffer is full). */
  8881. /* TODO: Check if this lock should be moved to user land.
  8882. * Currently the server sets this lock for websockets, but
  8883. * not for any other connection. It must be set for every
  8884. * conn read/written by more than one thread, no matter if
  8885. * it is a websocket or regular connection. */
  8886. (void)mg_lock_connection(conn);
  8887. retval = mg_write(conn, header, headerLen);
  8888. if (dataLen > 0) {
  8889. retval = mg_write(conn, data, dataLen);
  8890. }
  8891. /* TODO: Remove this unlock as well, when lock is moved. */
  8892. mg_unlock_connection(conn);
  8893. return retval;
  8894. }
  8895. int
  8896. mg_websocket_write(struct mg_connection *conn,
  8897. int opcode,
  8898. const char *data,
  8899. size_t dataLen)
  8900. {
  8901. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  8902. }
  8903. static void
  8904. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  8905. {
  8906. size_t i = 0;
  8907. i = 0;
  8908. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  8909. /* Convert in 32 bit words, if data is 4 byte aligned */
  8910. while (i < (in_len - 3)) {
  8911. *(uint32_t *)(void *)(out + i) =
  8912. *(uint32_t *)(void *)(in + i) ^ masking_key;
  8913. i += 4;
  8914. }
  8915. }
  8916. if (i != in_len) {
  8917. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  8918. while (i < in_len) {
  8919. *(uint8_t *)(void *)(out + i) =
  8920. *(uint8_t *)(void *)(in + i)
  8921. ^ *(((uint8_t *)&masking_key) + (i % 4));
  8922. i++;
  8923. }
  8924. }
  8925. }
  8926. int
  8927. mg_websocket_client_write(struct mg_connection *conn,
  8928. int opcode,
  8929. const char *data,
  8930. size_t dataLen)
  8931. {
  8932. int retval = -1;
  8933. char *masked_data = (char *)mg_malloc(((dataLen + 7) / 4) * 4);
  8934. uint32_t masking_key = (uint32_t)get_random();
  8935. if (masked_data == NULL) {
  8936. /* Return -1 in an error case */
  8937. mg_cry(conn,
  8938. "Cannot allocate buffer for masked websocket response: "
  8939. "Out of memory");
  8940. return -1;
  8941. }
  8942. mask_data(data, dataLen, masking_key, masked_data);
  8943. retval = mg_websocket_write_exec(
  8944. conn, opcode, masked_data, dataLen, masking_key);
  8945. mg_free(masked_data);
  8946. return retval;
  8947. }
  8948. static void
  8949. handle_websocket_request(struct mg_connection *conn,
  8950. const char *path,
  8951. int is_callback_resource,
  8952. struct mg_websocket_subprotocols *subprotocols,
  8953. mg_websocket_connect_handler ws_connect_handler,
  8954. mg_websocket_ready_handler ws_ready_handler,
  8955. mg_websocket_data_handler ws_data_handler,
  8956. mg_websocket_close_handler ws_close_handler,
  8957. void *cbData)
  8958. {
  8959. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  8960. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  8961. int lua_websock = 0;
  8962. #if !defined(USE_LUA)
  8963. (void)path;
  8964. #endif
  8965. /* Step 1: Check websocket protocol version. */
  8966. /* Step 1.1: Check Sec-WebSocket-Key. */
  8967. if (!websock_key) {
  8968. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  8969. * requires a Sec-WebSocket-Key header.
  8970. */
  8971. /* It could be the hixie draft version
  8972. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  8973. */
  8974. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  8975. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  8976. char key3[8];
  8977. if ((key1 != NULL) && (key2 != NULL)) {
  8978. /* This version uses 8 byte body data in a GET request */
  8979. conn->content_len = 8;
  8980. if (8 == mg_read(conn, key3, 8)) {
  8981. /* This is the hixie version */
  8982. mg_send_http_error(conn,
  8983. 426,
  8984. "%s",
  8985. "Protocol upgrade to RFC 6455 required");
  8986. return;
  8987. }
  8988. }
  8989. /* This is an unknown version */
  8990. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  8991. return;
  8992. }
  8993. /* Step 1.2: Check websocket protocol version. */
  8994. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  8995. if (version == NULL || strcmp(version, "13") != 0) {
  8996. /* Reject wrong versions */
  8997. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  8998. return;
  8999. }
  9000. /* Step 1.3: Could check for "Host", but we do not really nead this
  9001. * value for anything, so just ignore it. */
  9002. /* Step 2: If a callback is responsible, call it. */
  9003. if (is_callback_resource) {
  9004. /* Step 2.1 check and select subprotocol */
  9005. const char *protocol = mg_get_header(conn, "Sec-WebSocket-Protocol");
  9006. if (protocol && subprotocols) {
  9007. int idx;
  9008. unsigned long len;
  9009. const char *sep, *curSubProtocol,
  9010. *acceptedWebSocketSubprotocol = NULL;
  9011. /* look for matching subprotocol */
  9012. do {
  9013. sep = strchr(protocol, ',');
  9014. curSubProtocol = protocol;
  9015. len = sep ? (unsigned long)(sep - protocol)
  9016. : (unsigned long)strlen(protocol);
  9017. while (sep && isspace(*++sep)) {
  9018. ; /* ignore leading whitespaces */
  9019. }
  9020. protocol = sep;
  9021. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  9022. if ((strlen(subprotocols->subprotocols[idx]) == len)
  9023. && (strncmp(curSubProtocol,
  9024. subprotocols->subprotocols[idx],
  9025. len) == 0)) {
  9026. acceptedWebSocketSubprotocol =
  9027. subprotocols->subprotocols[idx];
  9028. break;
  9029. }
  9030. }
  9031. } while (sep && !acceptedWebSocketSubprotocol);
  9032. conn->request_info.acceptedWebSocketSubprotocol =
  9033. acceptedWebSocketSubprotocol;
  9034. } else if (protocol) {
  9035. /* keep legacy behavior */
  9036. /* The protocol is a comma seperated list of names. */
  9037. /* The server must only return one value from this list. */
  9038. /* First check if it is a list or just a single value. */
  9039. const char *sep = strrchr(protocol, ',');
  9040. if (sep == NULL) {
  9041. /* Just a single protocol -> accept it. */
  9042. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  9043. } else {
  9044. /* Multiple protocols -> accept the last one. */
  9045. /* This is just a quick fix if the client offers multiple
  9046. * protocols. The handler should have a list of accepted
  9047. * protocols on his own
  9048. * and use it to select one protocol among those the client has
  9049. * offered.
  9050. */
  9051. while (isspace(*++sep)) {
  9052. ; /* ignore leading whitespaces */
  9053. }
  9054. conn->request_info.acceptedWebSocketSubprotocol = sep;
  9055. }
  9056. }
  9057. if (ws_connect_handler != NULL
  9058. && ws_connect_handler(conn, cbData) != 0) {
  9059. /* C callback has returned non-zero, do not proceed with
  9060. * handshake.
  9061. */
  9062. /* Note that C callbacks are no longer called when Lua is
  9063. * responsible, so C can no longer filter callbacks for Lua. */
  9064. return;
  9065. }
  9066. }
  9067. #if defined(USE_LUA)
  9068. /* Step 3: No callback. Check if Lua is responsible. */
  9069. else {
  9070. /* Step 3.1: Check if Lua is responsible. */
  9071. if (conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  9072. lua_websock =
  9073. match_prefix(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  9074. strlen(
  9075. conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  9076. path);
  9077. }
  9078. if (lua_websock) {
  9079. /* Step 3.2: Lua is responsible: call it. */
  9080. conn->lua_websocket_state = lua_websocket_new(path, conn);
  9081. if (!conn->lua_websocket_state) {
  9082. /* Lua rejected the new client */
  9083. return;
  9084. }
  9085. }
  9086. }
  9087. #endif
  9088. /* Step 4: Check if there is a responsible websocket handler. */
  9089. if (!is_callback_resource && !lua_websock) {
  9090. /* There is no callback, and Lua is not responsible either. */
  9091. /* Reply with a 404 Not Found. We are still at a standard
  9092. * HTTP request here, before the websocket handshake, so
  9093. * we can still send standard HTTP error replies. */
  9094. mg_send_http_error(conn, 404, "%s", "Not found");
  9095. return;
  9096. }
  9097. /* Step 5: The websocket connection has been accepted */
  9098. if (!send_websocket_handshake(conn, websock_key)) {
  9099. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  9100. return;
  9101. }
  9102. /* Step 6: Call the ready handler */
  9103. if (is_callback_resource) {
  9104. if (ws_ready_handler != NULL) {
  9105. ws_ready_handler(conn, cbData);
  9106. }
  9107. #if defined(USE_LUA)
  9108. } else if (lua_websock) {
  9109. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  9110. /* the ready handler returned false */
  9111. return;
  9112. }
  9113. #endif
  9114. }
  9115. /* Step 7: Enter the read loop */
  9116. if (is_callback_resource) {
  9117. read_websocket(conn, ws_data_handler, cbData);
  9118. #if defined(USE_LUA)
  9119. } else if (lua_websock) {
  9120. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  9121. #endif
  9122. }
  9123. /* Step 8: Call the close handler */
  9124. if (ws_close_handler) {
  9125. ws_close_handler(conn, cbData);
  9126. }
  9127. }
  9128. static int
  9129. is_websocket_protocol(const struct mg_connection *conn)
  9130. {
  9131. const char *upgrade, *connection;
  9132. /* A websocket protocoll has the following HTTP headers:
  9133. *
  9134. * Connection: Upgrade
  9135. * Upgrade: Websocket
  9136. */
  9137. upgrade = mg_get_header(conn, "Upgrade");
  9138. if (upgrade == NULL) {
  9139. return 0; /* fail early, don't waste time checking other header
  9140. * fields
  9141. */
  9142. }
  9143. if (!mg_strcasestr(upgrade, "websocket")) {
  9144. return 0;
  9145. }
  9146. connection = mg_get_header(conn, "Connection");
  9147. if (connection == NULL) {
  9148. return 0;
  9149. }
  9150. if (!mg_strcasestr(connection, "upgrade")) {
  9151. return 0;
  9152. }
  9153. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  9154. * "Sec-WebSocket-Version" are also required.
  9155. * Don't check them here, since even an unsupported websocket protocol
  9156. * request still IS a websocket request (in contrast to a standard HTTP
  9157. * request). It will fail later in handle_websocket_request.
  9158. */
  9159. return 1;
  9160. }
  9161. #endif /* !USE_WEBSOCKET */
  9162. static int
  9163. isbyte(int n)
  9164. {
  9165. return n >= 0 && n <= 255;
  9166. }
  9167. static int
  9168. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  9169. {
  9170. int n, a, b, c, d, slash = 32, len = 0;
  9171. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5
  9172. || sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) && isbyte(a)
  9173. && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0
  9174. && slash < 33) {
  9175. len = n;
  9176. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  9177. | (uint32_t)d;
  9178. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  9179. }
  9180. return len;
  9181. }
  9182. static int
  9183. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  9184. {
  9185. int throttle = 0;
  9186. struct vec vec, val;
  9187. uint32_t net, mask;
  9188. char mult;
  9189. double v;
  9190. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  9191. mult = ',';
  9192. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  9193. || (v < 0) || ((lowercase(&mult) != 'k')
  9194. && (lowercase(&mult) != 'm') && (mult != ','))) {
  9195. continue;
  9196. }
  9197. v *= (lowercase(&mult) == 'k')
  9198. ? 1024
  9199. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  9200. if (vec.len == 1 && vec.ptr[0] == '*') {
  9201. throttle = (int)v;
  9202. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  9203. if ((remote_ip & mask) == net) {
  9204. throttle = (int)v;
  9205. }
  9206. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  9207. throttle = (int)v;
  9208. }
  9209. }
  9210. return throttle;
  9211. }
  9212. static uint32_t
  9213. get_remote_ip(const struct mg_connection *conn)
  9214. {
  9215. if (!conn) {
  9216. return 0;
  9217. }
  9218. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  9219. }
  9220. /* The mg_upload function is superseeded by mg_handle_form_request. */
  9221. #include "handle_form.inl"
  9222. #if defined(MG_LEGACY_INTERFACE)
  9223. /* Implement the deprecated mg_upload function by calling the new
  9224. * mg_handle_form_request function. While mg_upload could only handle
  9225. * HTML forms sent as POST request in multipart/form-data format
  9226. * containing only file input elements, mg_handle_form_request can
  9227. * handle all form input elements and all standard request methods. */
  9228. struct mg_upload_user_data {
  9229. struct mg_connection *conn;
  9230. const char *destination_dir;
  9231. int num_uploaded_files;
  9232. };
  9233. /* Helper function for deprecated mg_upload. */
  9234. static int
  9235. mg_upload_field_found(const char *key,
  9236. const char *filename,
  9237. char *path,
  9238. size_t pathlen,
  9239. void *user_data)
  9240. {
  9241. int truncated = 0;
  9242. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  9243. (void)key;
  9244. if (!filename) {
  9245. mg_cry(fud->conn, "%s: No filename set", __func__);
  9246. return FORM_FIELD_STORAGE_ABORT;
  9247. }
  9248. mg_snprintf(fud->conn,
  9249. &truncated,
  9250. path,
  9251. pathlen - 1,
  9252. "%s/%s",
  9253. fud->destination_dir,
  9254. filename);
  9255. if (!truncated) {
  9256. mg_cry(fud->conn, "%s: File path too long", __func__);
  9257. return FORM_FIELD_STORAGE_ABORT;
  9258. }
  9259. return FORM_FIELD_STORAGE_STORE;
  9260. }
  9261. /* Helper function for deprecated mg_upload. */
  9262. static int
  9263. mg_upload_field_get(const char *key,
  9264. const char *value,
  9265. size_t value_size,
  9266. void *user_data)
  9267. {
  9268. /* Function should never be called */
  9269. (void)key;
  9270. (void)value;
  9271. (void)value_size;
  9272. (void)user_data;
  9273. return 0;
  9274. }
  9275. /* Helper function for deprecated mg_upload. */
  9276. static int
  9277. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  9278. {
  9279. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  9280. (void)file_size;
  9281. fud->num_uploaded_files++;
  9282. fud->conn->ctx->callbacks.upload(fud->conn, path);
  9283. return 0;
  9284. }
  9285. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  9286. int
  9287. mg_upload(struct mg_connection *conn, const char *destination_dir)
  9288. {
  9289. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  9290. struct mg_form_data_handler fdh = {mg_upload_field_found,
  9291. mg_upload_field_get,
  9292. mg_upload_field_stored,
  9293. 0};
  9294. int ret;
  9295. fdh.user_data = (void *)&fud;
  9296. ret = mg_handle_form_request(conn, &fdh);
  9297. if (ret < 0) {
  9298. mg_cry(conn, "%s: Error while parsing the request", __func__);
  9299. }
  9300. return fud.num_uploaded_files;
  9301. }
  9302. #endif
  9303. static int
  9304. get_first_ssl_listener_index(const struct mg_context *ctx)
  9305. {
  9306. unsigned int i;
  9307. int idx = -1;
  9308. if (ctx) {
  9309. for (i = 0; idx == -1 && i < ctx->num_listening_sockets; i++) {
  9310. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  9311. }
  9312. }
  9313. return idx;
  9314. }
  9315. static void
  9316. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  9317. {
  9318. char host[1025];
  9319. const char *host_header;
  9320. size_t hostlen;
  9321. host_header = mg_get_header(conn, "Host");
  9322. hostlen = sizeof(host);
  9323. if (host_header != NULL) {
  9324. char *pos;
  9325. mg_strlcpy(host, host_header, hostlen);
  9326. host[hostlen - 1] = '\0';
  9327. pos = strchr(host, ':');
  9328. if (pos != NULL) {
  9329. *pos = '\0';
  9330. }
  9331. } else {
  9332. /* Cannot get host from the Host: header.
  9333. * Fallback to our IP address. */
  9334. if (conn) {
  9335. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  9336. }
  9337. }
  9338. /* Send host, port, uri and (if it exists) ?query_string */
  9339. if (conn) {
  9340. mg_printf(conn,
  9341. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  9342. host,
  9343. #if defined(USE_IPV6)
  9344. (conn->ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  9345. == AF_INET6)
  9346. ? (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  9347. .lsa.sin6.sin6_port)
  9348. :
  9349. #endif
  9350. (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  9351. .lsa.sin.sin_port),
  9352. conn->request_info.local_uri,
  9353. (conn->request_info.query_string == NULL) ? "" : "?",
  9354. (conn->request_info.query_string == NULL)
  9355. ? ""
  9356. : conn->request_info.query_string);
  9357. }
  9358. }
  9359. static void
  9360. mg_set_handler_type(struct mg_context *ctx,
  9361. const char *uri,
  9362. int handler_type,
  9363. int is_delete_request,
  9364. mg_request_handler handler,
  9365. struct mg_websocket_subprotocols *subprotocols,
  9366. mg_websocket_connect_handler connect_handler,
  9367. mg_websocket_ready_handler ready_handler,
  9368. mg_websocket_data_handler data_handler,
  9369. mg_websocket_close_handler close_handler,
  9370. mg_authorization_handler auth_handler,
  9371. void *cbdata)
  9372. {
  9373. struct mg_handler_info *tmp_rh, **lastref;
  9374. size_t urilen = strlen(uri);
  9375. if (handler_type == WEBSOCKET_HANDLER) {
  9376. /* assert(handler == NULL); */
  9377. /* assert(is_delete_request || connect_handler!=NULL ||
  9378. * ready_handler!=NULL || data_handler!=NULL ||
  9379. * close_handler!=NULL);
  9380. */
  9381. /* assert(auth_handler == NULL); */
  9382. if (handler != NULL) {
  9383. return;
  9384. }
  9385. if (!is_delete_request && connect_handler == NULL
  9386. && ready_handler == NULL
  9387. && data_handler == NULL
  9388. && close_handler == NULL) {
  9389. return;
  9390. }
  9391. if (auth_handler != NULL) {
  9392. return;
  9393. }
  9394. } else if (handler_type == REQUEST_HANDLER) {
  9395. /* assert(connect_handler==NULL && ready_handler==NULL &&
  9396. * data_handler==NULL && close_handler==NULL); */
  9397. /* assert(is_delete_request || (handler!=NULL));
  9398. */
  9399. /* assert(auth_handler == NULL); */
  9400. if (connect_handler != NULL || ready_handler != NULL
  9401. || data_handler != NULL
  9402. || close_handler != NULL) {
  9403. return;
  9404. }
  9405. if (!is_delete_request && (handler == NULL)) {
  9406. return;
  9407. }
  9408. if (auth_handler != NULL) {
  9409. return;
  9410. }
  9411. } else { /* AUTH_HANDLER */
  9412. /* assert(handler == NULL); */
  9413. /* assert(connect_handler==NULL && ready_handler==NULL &&
  9414. * data_handler==NULL && close_handler==NULL); */
  9415. /* assert(auth_handler != NULL); */
  9416. if (handler != NULL) {
  9417. return;
  9418. }
  9419. if (connect_handler != NULL || ready_handler != NULL
  9420. || data_handler != NULL
  9421. || close_handler != NULL) {
  9422. return;
  9423. }
  9424. if (!is_delete_request && (auth_handler == NULL)) {
  9425. return;
  9426. }
  9427. }
  9428. if (!ctx) {
  9429. return;
  9430. }
  9431. mg_lock_context(ctx);
  9432. /* first try to find an existing handler */
  9433. lastref = &(ctx->handlers);
  9434. for (tmp_rh = ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  9435. if (tmp_rh->handler_type == handler_type) {
  9436. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  9437. if (!is_delete_request) {
  9438. /* update existing handler */
  9439. if (handler_type == REQUEST_HANDLER) {
  9440. tmp_rh->handler = handler;
  9441. } else if (handler_type == WEBSOCKET_HANDLER) {
  9442. tmp_rh->subprotocols = subprotocols;
  9443. tmp_rh->connect_handler = connect_handler;
  9444. tmp_rh->ready_handler = ready_handler;
  9445. tmp_rh->data_handler = data_handler;
  9446. tmp_rh->close_handler = close_handler;
  9447. } else { /* AUTH_HANDLER */
  9448. tmp_rh->auth_handler = auth_handler;
  9449. }
  9450. tmp_rh->cbdata = cbdata;
  9451. } else {
  9452. /* remove existing handler */
  9453. *lastref = tmp_rh->next;
  9454. mg_free(tmp_rh->uri);
  9455. mg_free(tmp_rh);
  9456. }
  9457. mg_unlock_context(ctx);
  9458. return;
  9459. }
  9460. }
  9461. lastref = &(tmp_rh->next);
  9462. }
  9463. if (is_delete_request) {
  9464. /* no handler to set, this was a remove request to a non-existing
  9465. * handler */
  9466. mg_unlock_context(ctx);
  9467. return;
  9468. }
  9469. tmp_rh =
  9470. (struct mg_handler_info *)mg_calloc(sizeof(struct mg_handler_info), 1);
  9471. if (tmp_rh == NULL) {
  9472. mg_unlock_context(ctx);
  9473. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  9474. return;
  9475. }
  9476. tmp_rh->uri = mg_strdup(uri);
  9477. if (!tmp_rh->uri) {
  9478. mg_unlock_context(ctx);
  9479. mg_free(tmp_rh);
  9480. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  9481. return;
  9482. }
  9483. tmp_rh->uri_len = urilen;
  9484. if (handler_type == REQUEST_HANDLER) {
  9485. tmp_rh->handler = handler;
  9486. } else if (handler_type == WEBSOCKET_HANDLER) {
  9487. tmp_rh->subprotocols = subprotocols;
  9488. tmp_rh->connect_handler = connect_handler;
  9489. tmp_rh->ready_handler = ready_handler;
  9490. tmp_rh->data_handler = data_handler;
  9491. tmp_rh->close_handler = close_handler;
  9492. } else { /* AUTH_HANDLER */
  9493. tmp_rh->auth_handler = auth_handler;
  9494. }
  9495. tmp_rh->cbdata = cbdata;
  9496. tmp_rh->handler_type = handler_type;
  9497. tmp_rh->next = NULL;
  9498. *lastref = tmp_rh;
  9499. mg_unlock_context(ctx);
  9500. }
  9501. void
  9502. mg_set_request_handler(struct mg_context *ctx,
  9503. const char *uri,
  9504. mg_request_handler handler,
  9505. void *cbdata)
  9506. {
  9507. mg_set_handler_type(ctx,
  9508. uri,
  9509. REQUEST_HANDLER,
  9510. handler == NULL,
  9511. handler,
  9512. NULL,
  9513. NULL,
  9514. NULL,
  9515. NULL,
  9516. NULL,
  9517. NULL,
  9518. cbdata);
  9519. }
  9520. void
  9521. mg_set_websocket_handler(struct mg_context *ctx,
  9522. const char *uri,
  9523. mg_websocket_connect_handler connect_handler,
  9524. mg_websocket_ready_handler ready_handler,
  9525. mg_websocket_data_handler data_handler,
  9526. mg_websocket_close_handler close_handler,
  9527. void *cbdata)
  9528. {
  9529. mg_set_websocket_handler_with_subprotocols(ctx,
  9530. uri,
  9531. NULL,
  9532. connect_handler,
  9533. ready_handler,
  9534. data_handler,
  9535. close_handler,
  9536. cbdata);
  9537. }
  9538. void
  9539. mg_set_websocket_handler_with_subprotocols(
  9540. struct mg_context *ctx,
  9541. const char *uri,
  9542. struct mg_websocket_subprotocols *subprotocols,
  9543. mg_websocket_connect_handler connect_handler,
  9544. mg_websocket_ready_handler ready_handler,
  9545. mg_websocket_data_handler data_handler,
  9546. mg_websocket_close_handler close_handler,
  9547. void *cbdata)
  9548. {
  9549. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  9550. && (data_handler == NULL)
  9551. && (close_handler == NULL);
  9552. mg_set_handler_type(ctx,
  9553. uri,
  9554. WEBSOCKET_HANDLER,
  9555. is_delete_request,
  9556. NULL,
  9557. subprotocols,
  9558. connect_handler,
  9559. ready_handler,
  9560. data_handler,
  9561. close_handler,
  9562. NULL,
  9563. cbdata);
  9564. }
  9565. void
  9566. mg_set_auth_handler(struct mg_context *ctx,
  9567. const char *uri,
  9568. mg_request_handler handler,
  9569. void *cbdata)
  9570. {
  9571. mg_set_handler_type(ctx,
  9572. uri,
  9573. AUTH_HANDLER,
  9574. handler == NULL,
  9575. NULL,
  9576. NULL,
  9577. NULL,
  9578. NULL,
  9579. NULL,
  9580. NULL,
  9581. handler,
  9582. cbdata);
  9583. }
  9584. static int
  9585. get_request_handler(struct mg_connection *conn,
  9586. int handler_type,
  9587. mg_request_handler *handler,
  9588. struct mg_websocket_subprotocols **subprotocols,
  9589. mg_websocket_connect_handler *connect_handler,
  9590. mg_websocket_ready_handler *ready_handler,
  9591. mg_websocket_data_handler *data_handler,
  9592. mg_websocket_close_handler *close_handler,
  9593. mg_authorization_handler *auth_handler,
  9594. void **cbdata)
  9595. {
  9596. const struct mg_request_info *request_info = mg_get_request_info(conn);
  9597. if (request_info) {
  9598. const char *uri = request_info->local_uri;
  9599. size_t urilen = strlen(uri);
  9600. struct mg_handler_info *tmp_rh;
  9601. if (!conn || !conn->ctx) {
  9602. return 0;
  9603. }
  9604. mg_lock_context(conn->ctx);
  9605. /* first try for an exact match */
  9606. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  9607. tmp_rh = tmp_rh->next) {
  9608. if (tmp_rh->handler_type == handler_type) {
  9609. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  9610. if (handler_type == WEBSOCKET_HANDLER) {
  9611. *subprotocols = tmp_rh->subprotocols;
  9612. *connect_handler = tmp_rh->connect_handler;
  9613. *ready_handler = tmp_rh->ready_handler;
  9614. *data_handler = tmp_rh->data_handler;
  9615. *close_handler = tmp_rh->close_handler;
  9616. } else if (handler_type == REQUEST_HANDLER) {
  9617. *handler = tmp_rh->handler;
  9618. } else { /* AUTH_HANDLER */
  9619. *auth_handler = tmp_rh->auth_handler;
  9620. }
  9621. *cbdata = tmp_rh->cbdata;
  9622. mg_unlock_context(conn->ctx);
  9623. return 1;
  9624. }
  9625. }
  9626. }
  9627. /* next try for a partial match, we will accept uri/something */
  9628. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  9629. tmp_rh = tmp_rh->next) {
  9630. if (tmp_rh->handler_type == handler_type) {
  9631. if (tmp_rh->uri_len < urilen && uri[tmp_rh->uri_len] == '/'
  9632. && memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0) {
  9633. if (handler_type == WEBSOCKET_HANDLER) {
  9634. *subprotocols = tmp_rh->subprotocols;
  9635. *connect_handler = tmp_rh->connect_handler;
  9636. *ready_handler = tmp_rh->ready_handler;
  9637. *data_handler = tmp_rh->data_handler;
  9638. *close_handler = tmp_rh->close_handler;
  9639. } else if (handler_type == REQUEST_HANDLER) {
  9640. *handler = tmp_rh->handler;
  9641. } else { /* AUTH_HANDLER */
  9642. *auth_handler = tmp_rh->auth_handler;
  9643. }
  9644. *cbdata = tmp_rh->cbdata;
  9645. mg_unlock_context(conn->ctx);
  9646. return 1;
  9647. }
  9648. }
  9649. }
  9650. /* finally try for pattern match */
  9651. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  9652. tmp_rh = tmp_rh->next) {
  9653. if (tmp_rh->handler_type == handler_type) {
  9654. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  9655. if (handler_type == WEBSOCKET_HANDLER) {
  9656. *subprotocols = tmp_rh->subprotocols;
  9657. *connect_handler = tmp_rh->connect_handler;
  9658. *ready_handler = tmp_rh->ready_handler;
  9659. *data_handler = tmp_rh->data_handler;
  9660. *close_handler = tmp_rh->close_handler;
  9661. } else if (handler_type == REQUEST_HANDLER) {
  9662. *handler = tmp_rh->handler;
  9663. } else { /* AUTH_HANDLER */
  9664. *auth_handler = tmp_rh->auth_handler;
  9665. }
  9666. *cbdata = tmp_rh->cbdata;
  9667. mg_unlock_context(conn->ctx);
  9668. return 1;
  9669. }
  9670. }
  9671. }
  9672. mg_unlock_context(conn->ctx);
  9673. }
  9674. return 0; /* none found */
  9675. }
  9676. /* Check if the script file is in a path, allowed for script files.
  9677. * This can be used if uploading files is possible not only for the server
  9678. * admin, and the upload mechanism does not check the file extension.
  9679. */
  9680. static int
  9681. is_in_script_path(const struct mg_connection *conn, const char *path)
  9682. {
  9683. /* TODO (Feature): Add config value for allowed script path.
  9684. * Default: All allowed. */
  9685. (void)conn;
  9686. (void)path;
  9687. return 1;
  9688. }
  9689. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  9690. static int
  9691. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  9692. void *cbdata)
  9693. {
  9694. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9695. if (pcallbacks->websocket_connect) {
  9696. return pcallbacks->websocket_connect(conn);
  9697. }
  9698. /* No handler set - assume "OK" */
  9699. return 0;
  9700. }
  9701. static void
  9702. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  9703. {
  9704. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9705. if (pcallbacks->websocket_ready) {
  9706. pcallbacks->websocket_ready(conn);
  9707. }
  9708. }
  9709. static int
  9710. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  9711. int bits,
  9712. char *data,
  9713. size_t len,
  9714. void *cbdata)
  9715. {
  9716. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9717. if (pcallbacks->websocket_data) {
  9718. return pcallbacks->websocket_data(conn, bits, data, len);
  9719. }
  9720. /* No handler set - assume "OK" */
  9721. return 1;
  9722. }
  9723. #endif
  9724. /* This is the heart of the Civetweb's logic.
  9725. * This function is called when the request is read, parsed and validated,
  9726. * and Civetweb must decide what action to take: serve a file, or
  9727. * a directory, or call embedded function, etcetera. */
  9728. static void
  9729. handle_request(struct mg_connection *conn)
  9730. {
  9731. struct mg_request_info *ri = &conn->request_info;
  9732. char path[PATH_MAX];
  9733. int uri_len, ssl_index;
  9734. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  9735. is_put_or_delete_request = 0, is_callback_resource = 0;
  9736. int i;
  9737. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9738. mg_request_handler callback_handler = NULL;
  9739. struct mg_websocket_subprotocols *subprotocols;
  9740. mg_websocket_connect_handler ws_connect_handler = NULL;
  9741. mg_websocket_ready_handler ws_ready_handler = NULL;
  9742. mg_websocket_data_handler ws_data_handler = NULL;
  9743. mg_websocket_close_handler ws_close_handler = NULL;
  9744. void *callback_data = NULL;
  9745. mg_authorization_handler auth_handler = NULL;
  9746. void *auth_callback_data = NULL;
  9747. #if !defined(NO_FILES)
  9748. time_t curtime = time(NULL);
  9749. char date[64];
  9750. #endif
  9751. path[0] = 0;
  9752. /* 1. get the request url */
  9753. /* 1.1. split into url and query string */
  9754. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  9755. != NULL) {
  9756. *((char *)conn->request_info.query_string++) = '\0';
  9757. }
  9758. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  9759. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  9760. ssl_index = get_first_ssl_listener_index(conn->ctx);
  9761. if (ssl_index >= 0) {
  9762. redirect_to_https_port(conn, ssl_index);
  9763. } else {
  9764. /* A http to https forward port has been specified,
  9765. * but no https port to forward to. */
  9766. mg_send_http_error(conn,
  9767. 503,
  9768. "%s",
  9769. "Error: SSL forward not configured properly");
  9770. mg_cry(conn, "Can not redirect to SSL, no SSL port available");
  9771. }
  9772. return;
  9773. }
  9774. uri_len = (int)strlen(ri->local_uri);
  9775. /* 1.3. decode url (if config says so) */
  9776. if (should_decode_url(conn)) {
  9777. mg_url_decode(
  9778. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  9779. }
  9780. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  9781. * not possible */
  9782. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  9783. /* step 1. completed, the url is known now */
  9784. uri_len = (int)strlen(ri->local_uri);
  9785. DEBUG_TRACE("URL: %s", ri->local_uri);
  9786. /* 3. if this ip has limited speed, set it for this connection */
  9787. conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
  9788. get_remote_ip(conn),
  9789. ri->local_uri);
  9790. /* 4. call a "handle everything" callback, if registered */
  9791. if (conn->ctx->callbacks.begin_request != NULL) {
  9792. /* Note that since V1.7 the "begin_request" function is called
  9793. * before an authorization check. If an authorization check is
  9794. * required, use a request_handler instead. */
  9795. i = conn->ctx->callbacks.begin_request(conn);
  9796. if (i > 0) {
  9797. /* callback already processed the request. Store the
  9798. return value as a status code for the access log. */
  9799. conn->status_code = i;
  9800. discard_unread_request_data(conn);
  9801. return;
  9802. } else if (i == 0) {
  9803. /* civetweb should process the request */
  9804. } else {
  9805. /* unspecified - may change with the next version */
  9806. return;
  9807. }
  9808. }
  9809. /* request not yet handled by a handler or redirect, so the request
  9810. * is processed here */
  9811. /* 5. interpret the url to find out how the request must be handled
  9812. */
  9813. /* 5.1. first test, if the request targets the regular http(s)://
  9814. * protocol namespace or the websocket ws(s):// protocol namespace.
  9815. */
  9816. is_websocket_request = is_websocket_protocol(conn);
  9817. /* 5.2. check if the request will be handled by a callback */
  9818. if (get_request_handler(conn,
  9819. is_websocket_request ? WEBSOCKET_HANDLER
  9820. : REQUEST_HANDLER,
  9821. &callback_handler,
  9822. &subprotocols,
  9823. &ws_connect_handler,
  9824. &ws_ready_handler,
  9825. &ws_data_handler,
  9826. &ws_close_handler,
  9827. NULL,
  9828. &callback_data)) {
  9829. /* 5.2.1. A callback will handle this request. All requests
  9830. * handled
  9831. * by a callback have to be considered as requests to a script
  9832. * resource. */
  9833. is_callback_resource = 1;
  9834. is_script_resource = 1;
  9835. is_put_or_delete_request = is_put_or_delete_method(conn);
  9836. } else {
  9837. no_callback_resource:
  9838. /* 5.2.2. No callback is responsible for this request. The URI
  9839. * addresses a file based resource (static content or Lua/cgi
  9840. * scripts in the file system). */
  9841. is_callback_resource = 0;
  9842. interpret_uri(conn,
  9843. path,
  9844. sizeof(path),
  9845. &file.stat,
  9846. &is_found,
  9847. &is_script_resource,
  9848. &is_websocket_request,
  9849. &is_put_or_delete_request);
  9850. }
  9851. /* 6. authorization check */
  9852. /* 6.1. a custom authorization handler is installed */
  9853. if (get_request_handler(conn,
  9854. AUTH_HANDLER,
  9855. NULL,
  9856. NULL,
  9857. NULL,
  9858. NULL,
  9859. NULL,
  9860. NULL,
  9861. &auth_handler,
  9862. &auth_callback_data)) {
  9863. if (!auth_handler(conn, auth_callback_data)) {
  9864. return;
  9865. }
  9866. } else if (is_put_or_delete_request && !is_script_resource
  9867. && !is_callback_resource) {
  9868. /* 6.2. this request is a PUT/DELETE to a real file */
  9869. /* 6.2.1. thus, the server must have real files */
  9870. #if defined(NO_FILES)
  9871. if (1) {
  9872. #else
  9873. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  9874. #endif
  9875. /* This server does not have any real files, thus the
  9876. * PUT/DELETE methods are not valid. */
  9877. mg_send_http_error(conn,
  9878. 405,
  9879. "%s method not allowed",
  9880. conn->request_info.request_method);
  9881. return;
  9882. }
  9883. #if !defined(NO_FILES)
  9884. /* 6.2.2. Check if put authorization for static files is
  9885. * available.
  9886. */
  9887. if (!is_authorized_for_put(conn)) {
  9888. send_authorization_request(conn);
  9889. return;
  9890. }
  9891. #endif
  9892. } else {
  9893. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  9894. * or it is a PUT or DELETE request to a resource that does not
  9895. * correspond to a file. Check authorization. */
  9896. if (!check_authorization(conn, path)) {
  9897. send_authorization_request(conn);
  9898. return;
  9899. }
  9900. }
  9901. /* request is authorized or does not need authorization */
  9902. /* 7. check if there are request handlers for this uri */
  9903. if (is_callback_resource) {
  9904. if (!is_websocket_request) {
  9905. i = callback_handler(conn, callback_data);
  9906. if (i > 0) {
  9907. /* Do nothing, callback has served the request. Store
  9908. * then return value as status code for the log and discard
  9909. * all data from the client not used by the callback. */
  9910. conn->status_code = i;
  9911. discard_unread_request_data(conn);
  9912. } else {
  9913. /* The handler did NOT handle the request. */
  9914. /* Some proper reactions would be:
  9915. * a) close the connections without sending anything
  9916. * b) send a 404 not found
  9917. * c) try if there is a file matching the URI
  9918. * It would be possible to do a, b or c in the callback
  9919. * implementation, and return 1 - we cannot do anything
  9920. * here, that is not possible in the callback.
  9921. *
  9922. * TODO: What would be the best reaction here?
  9923. * (Note: The reaction may change, if there is a better idea.)
  9924. */
  9925. /* For the moment, use option c: We look for a proper file,
  9926. * but since a file request is not always a script resource,
  9927. * the authorization check might be different. */
  9928. interpret_uri(conn,
  9929. path,
  9930. sizeof(path),
  9931. &file.stat,
  9932. &is_found,
  9933. &is_script_resource,
  9934. &is_websocket_request,
  9935. &is_put_or_delete_request);
  9936. callback_handler = NULL;
  9937. /* Here we are at a dead end:
  9938. * According to URI matching, a callback should be
  9939. * responsible for handling the request,
  9940. * we called it, but the callback declared itself
  9941. * not responsible.
  9942. * We use a goto here, to get out of this dead end,
  9943. * and continue with the default handling.
  9944. * A goto here is simpler and better to understand
  9945. * than some curious loop. */
  9946. goto no_callback_resource;
  9947. }
  9948. } else {
  9949. #if defined(USE_WEBSOCKET)
  9950. handle_websocket_request(conn,
  9951. path,
  9952. is_callback_resource,
  9953. subprotocols,
  9954. ws_connect_handler,
  9955. ws_ready_handler,
  9956. ws_data_handler,
  9957. ws_close_handler,
  9958. callback_data);
  9959. #endif
  9960. }
  9961. return;
  9962. }
  9963. /* 8. handle websocket requests */
  9964. #if defined(USE_WEBSOCKET)
  9965. if (is_websocket_request) {
  9966. if (is_script_resource) {
  9967. if (is_in_script_path(conn, path)) {
  9968. /* Websocket Lua script */
  9969. handle_websocket_request(conn,
  9970. path,
  9971. 0 /* Lua Script */,
  9972. NULL,
  9973. NULL,
  9974. NULL,
  9975. NULL,
  9976. NULL,
  9977. &conn->ctx->callbacks);
  9978. } else {
  9979. /* Script was in an illegal path */
  9980. mg_send_http_error(conn, 403, "%s", "Forbidden");
  9981. }
  9982. } else {
  9983. #if defined(MG_LEGACY_INTERFACE)
  9984. handle_websocket_request(
  9985. conn,
  9986. path,
  9987. !is_script_resource /* could be deprecated global callback */,
  9988. NULL,
  9989. deprecated_websocket_connect_wrapper,
  9990. deprecated_websocket_ready_wrapper,
  9991. deprecated_websocket_data_wrapper,
  9992. NULL,
  9993. &conn->ctx->callbacks);
  9994. #else
  9995. mg_send_http_error(conn, 404, "%s", "Not found");
  9996. #endif
  9997. }
  9998. return;
  9999. } else
  10000. #endif
  10001. #if defined(NO_FILES)
  10002. /* 9a. In case the server uses only callbacks, this uri is
  10003. * unknown.
  10004. * Then, all request handling ends here. */
  10005. mg_send_http_error(conn, 404, "%s", "Not Found");
  10006. #else
  10007. /* 9b. This request is either for a static file or resource handled
  10008. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  10009. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  10010. mg_send_http_error(conn, 404, "%s", "Not Found");
  10011. return;
  10012. }
  10013. /* 10. Request is handled by a script */
  10014. if (is_script_resource) {
  10015. handle_file_based_request(conn, path, &file);
  10016. return;
  10017. }
  10018. /* 11. Handle put/delete/mkcol requests */
  10019. if (is_put_or_delete_request) {
  10020. /* 11.1. PUT method */
  10021. if (!strcmp(ri->request_method, "PUT")) {
  10022. put_file(conn, path);
  10023. return;
  10024. }
  10025. /* 11.2. DELETE method */
  10026. if (!strcmp(ri->request_method, "DELETE")) {
  10027. delete_file(conn, path);
  10028. return;
  10029. }
  10030. /* 11.3. MKCOL method */
  10031. if (!strcmp(ri->request_method, "MKCOL")) {
  10032. mkcol(conn, path);
  10033. return;
  10034. }
  10035. /* 11.4. PATCH method
  10036. * This method is not supported for static resources,
  10037. * only for scripts (Lua, CGI) and callbacks. */
  10038. mg_send_http_error(conn,
  10039. 405,
  10040. "%s method not allowed",
  10041. conn->request_info.request_method);
  10042. return;
  10043. }
  10044. /* 11. File does not exist, or it was configured that it should be
  10045. * hidden */
  10046. if (!is_found || (must_hide_file(conn, path))) {
  10047. mg_send_http_error(conn, 404, "%s", "Not found");
  10048. return;
  10049. }
  10050. /* 12. Directory uris should end with a slash */
  10051. if (file.stat.is_directory && (uri_len > 0)
  10052. && (ri->local_uri[uri_len - 1] != '/')) {
  10053. gmt_time_string(date, sizeof(date), &curtime);
  10054. mg_printf(conn,
  10055. "HTTP/1.1 301 Moved Permanently\r\n"
  10056. "Location: %s/\r\n"
  10057. "Date: %s\r\n"
  10058. /* "Cache-Control: private\r\n" (= default) */
  10059. "Content-Length: 0\r\n"
  10060. "Connection: %s\r\n",
  10061. ri->request_uri,
  10062. date,
  10063. suggest_connection_header(conn));
  10064. send_additional_header(conn);
  10065. mg_printf(conn, "\r\n");
  10066. return;
  10067. }
  10068. /* 13. Handle other methods than GET/HEAD */
  10069. /* 13.1. Handle PROPFIND */
  10070. if (!strcmp(ri->request_method, "PROPFIND")) {
  10071. handle_propfind(conn, path, &file.stat);
  10072. return;
  10073. }
  10074. /* 13.2. Handle OPTIONS for files */
  10075. if (!strcmp(ri->request_method, "OPTIONS")) {
  10076. /* This standard handler is only used for real files.
  10077. * Scripts should support the OPTIONS method themselves, to allow a
  10078. * maximum flexibility.
  10079. * Lua and CGI scripts may fully support CORS this way (including
  10080. * preflights). */
  10081. send_options(conn);
  10082. return;
  10083. }
  10084. /* 13.3. everything but GET and HEAD (e.g. POST) */
  10085. if (0 != strcmp(ri->request_method, "GET")
  10086. && 0 != strcmp(ri->request_method, "HEAD")) {
  10087. mg_send_http_error(conn,
  10088. 405,
  10089. "%s method not allowed",
  10090. conn->request_info.request_method);
  10091. return;
  10092. }
  10093. /* 14. directories */
  10094. if (file.stat.is_directory) {
  10095. /* Substitute files have already been handled above. */
  10096. /* Here we can either generate and send a directory listing,
  10097. * or send an "access denied" error. */
  10098. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  10099. "yes")) {
  10100. handle_directory_request(conn, path);
  10101. } else {
  10102. mg_send_http_error(conn,
  10103. 403,
  10104. "%s",
  10105. "Error: Directory listing denied");
  10106. }
  10107. return;
  10108. }
  10109. handle_file_based_request(conn, path, &file);
  10110. #endif /* !defined(NO_FILES) */
  10111. #if 0
  10112. /* Perform redirect and auth checks before calling begin_request()
  10113. * handler.
  10114. * Otherwise, begin_request() would need to perform auth checks and
  10115. * redirects. */
  10116. #endif
  10117. }
  10118. static void
  10119. handle_file_based_request(struct mg_connection *conn,
  10120. const char *path,
  10121. struct mg_file *file)
  10122. {
  10123. if (!conn || !conn->ctx) {
  10124. return;
  10125. }
  10126. if (0) {
  10127. #ifdef USE_LUA
  10128. } else if (match_prefix(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  10129. strlen(
  10130. conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  10131. path) > 0) {
  10132. if (is_in_script_path(conn, path)) {
  10133. /* Lua server page: an SSI like page containing mostly plain html
  10134. * code
  10135. * plus some tags with server generated contents. */
  10136. handle_lsp_request(conn, path, file, NULL);
  10137. } else {
  10138. /* Script was in an illegal path */
  10139. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10140. }
  10141. } else if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  10142. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  10143. path) > 0) {
  10144. if (is_in_script_path(conn, path)) {
  10145. /* Lua in-server module script: a CGI like script used to generate
  10146. * the
  10147. * entire reply. */
  10148. mg_exec_lua_script(conn, path, NULL);
  10149. } else {
  10150. /* Script was in an illegal path */
  10151. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10152. }
  10153. #endif
  10154. #if defined(USE_DUKTAPE)
  10155. } else if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  10156. strlen(
  10157. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  10158. path) > 0) {
  10159. if (is_in_script_path(conn, path)) {
  10160. /* Call duktape to generate the page */
  10161. mg_exec_duktape_script(conn, path);
  10162. } else {
  10163. /* Script was in an illegal path */
  10164. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10165. }
  10166. #endif
  10167. #if !defined(NO_CGI)
  10168. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  10169. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  10170. path) > 0) {
  10171. if (is_in_script_path(conn, path)) {
  10172. /* CGI scripts may support all HTTP methods */
  10173. handle_cgi_request(conn, path);
  10174. } else {
  10175. /* Script was in an illegal path */
  10176. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10177. }
  10178. #endif /* !NO_CGI */
  10179. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  10180. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  10181. path) > 0) {
  10182. if (is_in_script_path(conn, path)) {
  10183. handle_ssi_file_request(conn, path, file);
  10184. } else {
  10185. /* Script was in an illegal path */
  10186. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10187. }
  10188. #if !defined(NO_CACHING)
  10189. } else if ((!conn->in_error_handler)
  10190. && is_not_modified(conn, &file->stat)) {
  10191. /* Send 304 "Not Modified" - this must not send any body data */
  10192. handle_not_modified_static_file_request(conn, file);
  10193. #endif /* !NO_CACHING */
  10194. } else {
  10195. handle_static_file_request(conn, path, file, NULL, NULL);
  10196. }
  10197. }
  10198. static void
  10199. close_all_listening_sockets(struct mg_context *ctx)
  10200. {
  10201. unsigned int i;
  10202. if (!ctx) {
  10203. return;
  10204. }
  10205. for (i = 0; i < ctx->num_listening_sockets; i++) {
  10206. closesocket(ctx->listening_sockets[i].sock);
  10207. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  10208. }
  10209. mg_free(ctx->listening_sockets);
  10210. ctx->listening_sockets = NULL;
  10211. mg_free(ctx->listening_socket_fds);
  10212. ctx->listening_socket_fds = NULL;
  10213. }
  10214. /* Valid listening port specification is: [ip_address:]port[s]
  10215. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  10216. * Examples for IPv6: [::]:80, [::1]:80,
  10217. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  10218. * see https://tools.ietf.org/html/rfc3513#section-2.2
  10219. * In order to bind to both, IPv4 and IPv6, you can either add
  10220. * both ports using 8080,[::]:8080, or the short form +8080.
  10221. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  10222. * one only accepting IPv4 the other only IPv6. +8080 creates
  10223. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  10224. * environment, they might work differently, or might not work
  10225. * at all - it must be tested what options work best in the
  10226. * relevant network environment.
  10227. */
  10228. static int
  10229. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  10230. {
  10231. unsigned int a, b, c, d, port;
  10232. int ch, len;
  10233. #if defined(USE_IPV6)
  10234. char buf[100] = {0};
  10235. #endif
  10236. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  10237. * Also, all-zeroes in the socket address means binding to all addresses
  10238. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  10239. memset(so, 0, sizeof(*so));
  10240. so->lsa.sin.sin_family = AF_INET;
  10241. *ip_version = 0;
  10242. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  10243. == 5) {
  10244. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  10245. so->lsa.sin.sin_addr.s_addr =
  10246. htonl((a << 24) | (b << 16) | (c << 8) | d);
  10247. so->lsa.sin.sin_port = htons((uint16_t)port);
  10248. *ip_version = 4;
  10249. #if defined(USE_IPV6)
  10250. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  10251. && mg_inet_pton(
  10252. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  10253. /* IPv6 address, examples: see above */
  10254. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  10255. */
  10256. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  10257. *ip_version = 6;
  10258. #endif
  10259. } else if ((vec->ptr[0] == '+')
  10260. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  10261. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  10262. /* Add 1 to len for the + character we skipped before */
  10263. len++;
  10264. #if defined(USE_IPV6)
  10265. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  10266. so->lsa.sin6.sin6_family = AF_INET6;
  10267. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  10268. *ip_version = 4 + 6;
  10269. #else
  10270. /* Bind to IPv4 only, since IPv6 is not built in. */
  10271. so->lsa.sin.sin_port = htons((uint16_t)port);
  10272. *ip_version = 4;
  10273. #endif
  10274. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  10275. /* If only port is specified, bind to IPv4, INADDR_ANY */
  10276. so->lsa.sin.sin_port = htons((uint16_t)port);
  10277. *ip_version = 4;
  10278. } else {
  10279. /* Parsing failure. Make port invalid. */
  10280. port = 0;
  10281. len = 0;
  10282. }
  10283. /* sscanf and the option splitting code ensure the following condition
  10284. */
  10285. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  10286. *ip_version = 0;
  10287. return 0;
  10288. }
  10289. ch = vec->ptr[len]; /* Next character after the port number */
  10290. so->is_ssl = (ch == 's');
  10291. so->ssl_redir = (ch == 'r');
  10292. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  10293. if (is_valid_port(port)
  10294. && (ch == '\0' || ch == 's' || ch == 'r' || ch == ',')) {
  10295. return 1;
  10296. }
  10297. /* Reset ip_version to 0 of there is an error */
  10298. *ip_version = 0;
  10299. return 0;
  10300. }
  10301. static int
  10302. set_ports_option(struct mg_context *ctx)
  10303. {
  10304. const char *list;
  10305. int on = 1;
  10306. #if defined(USE_IPV6)
  10307. int off = 0;
  10308. #endif
  10309. struct vec vec;
  10310. struct socket so, *ptr;
  10311. struct pollfd *pfd;
  10312. union usa usa;
  10313. socklen_t len;
  10314. int ip_version;
  10315. int portsTotal = 0;
  10316. int portsOk = 0;
  10317. if (!ctx) {
  10318. return 0;
  10319. }
  10320. memset(&so, 0, sizeof(so));
  10321. memset(&usa, 0, sizeof(usa));
  10322. len = sizeof(usa);
  10323. list = ctx->config[LISTENING_PORTS];
  10324. while ((list = next_option(list, &vec, NULL)) != NULL) {
  10325. portsTotal++;
  10326. if (!parse_port_string(&vec, &so, &ip_version)) {
  10327. mg_cry(fc(ctx),
  10328. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  10329. (int)vec.len,
  10330. vec.ptr,
  10331. portsTotal,
  10332. "[IP_ADDRESS:]PORT[s|r]");
  10333. continue;
  10334. }
  10335. #if !defined(NO_SSL)
  10336. if (so.is_ssl && ctx->ssl_ctx == NULL) {
  10337. mg_cry(fc(ctx),
  10338. "Cannot add SSL socket (entry %i). Is -ssl_certificate "
  10339. "option set?",
  10340. portsTotal);
  10341. continue;
  10342. }
  10343. #endif
  10344. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  10345. == INVALID_SOCKET) {
  10346. mg_cry(fc(ctx), "cannot create socket (entry %i)", portsTotal);
  10347. continue;
  10348. }
  10349. #ifdef _WIN32
  10350. /* Windows SO_REUSEADDR lets many procs binds to a
  10351. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  10352. * if someone already has the socket -- DTL */
  10353. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  10354. * Windows might need a few seconds before
  10355. * the same port can be used again in the
  10356. * same process, so a short Sleep may be
  10357. * required between mg_stop and mg_start.
  10358. */
  10359. if (setsockopt(so.sock,
  10360. SOL_SOCKET,
  10361. SO_EXCLUSIVEADDRUSE,
  10362. (SOCK_OPT_TYPE)&on,
  10363. sizeof(on)) != 0) {
  10364. /* Set reuse option, but don't abort on errors. */
  10365. mg_cry(fc(ctx),
  10366. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  10367. portsTotal);
  10368. }
  10369. #else
  10370. if (setsockopt(so.sock,
  10371. SOL_SOCKET,
  10372. SO_REUSEADDR,
  10373. (SOCK_OPT_TYPE)&on,
  10374. sizeof(on)) != 0) {
  10375. /* Set reuse option, but don't abort on errors. */
  10376. mg_cry(fc(ctx),
  10377. "cannot set socket option SO_REUSEADDR (entry %i)",
  10378. portsTotal);
  10379. }
  10380. #endif
  10381. if (ip_version > 4) {
  10382. #if defined(USE_IPV6)
  10383. if (ip_version == 6) {
  10384. if (so.lsa.sa.sa_family == AF_INET6
  10385. && setsockopt(so.sock,
  10386. IPPROTO_IPV6,
  10387. IPV6_V6ONLY,
  10388. (void *)&off,
  10389. sizeof(off)) != 0) {
  10390. /* Set IPv6 only option, but don't abort on errors. */
  10391. mg_cry(fc(ctx),
  10392. "cannot set socket option IPV6_V6ONLY (entry %i)",
  10393. portsTotal);
  10394. }
  10395. }
  10396. #else
  10397. mg_cry(fc(ctx), "IPv6 not available");
  10398. closesocket(so.sock);
  10399. so.sock = INVALID_SOCKET;
  10400. continue;
  10401. #endif
  10402. }
  10403. if (so.lsa.sa.sa_family == AF_INET) {
  10404. len = sizeof(so.lsa.sin);
  10405. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  10406. mg_cry(fc(ctx),
  10407. "cannot bind to %.*s: %d (%s)",
  10408. (int)vec.len,
  10409. vec.ptr,
  10410. (int)ERRNO,
  10411. strerror(errno));
  10412. closesocket(so.sock);
  10413. so.sock = INVALID_SOCKET;
  10414. continue;
  10415. }
  10416. }
  10417. #if defined(USE_IPV6)
  10418. else if (so.lsa.sa.sa_family == AF_INET6) {
  10419. len = sizeof(so.lsa.sin6);
  10420. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  10421. mg_cry(fc(ctx),
  10422. "cannot bind to IPv6 %.*s: %d (%s)",
  10423. (int)vec.len,
  10424. vec.ptr,
  10425. (int)ERRNO,
  10426. strerror(errno));
  10427. closesocket(so.sock);
  10428. so.sock = INVALID_SOCKET;
  10429. continue;
  10430. }
  10431. }
  10432. #endif
  10433. else {
  10434. mg_cry(fc(ctx),
  10435. "cannot bind: address family not supported (entry %i)",
  10436. portsTotal);
  10437. continue;
  10438. }
  10439. if (listen(so.sock, SOMAXCONN) != 0) {
  10440. mg_cry(fc(ctx),
  10441. "cannot listen to %.*s: %d (%s)",
  10442. (int)vec.len,
  10443. vec.ptr,
  10444. (int)ERRNO,
  10445. strerror(errno));
  10446. closesocket(so.sock);
  10447. so.sock = INVALID_SOCKET;
  10448. continue;
  10449. }
  10450. if (getsockname(so.sock, &(usa.sa), &len) != 0
  10451. || usa.sa.sa_family != so.lsa.sa.sa_family) {
  10452. int err = (int)ERRNO;
  10453. mg_cry(fc(ctx),
  10454. "call to getsockname failed %.*s: %d (%s)",
  10455. (int)vec.len,
  10456. vec.ptr,
  10457. err,
  10458. strerror(errno));
  10459. closesocket(so.sock);
  10460. so.sock = INVALID_SOCKET;
  10461. continue;
  10462. }
  10463. /* Update lsa port in case of random free ports */
  10464. #if defined(USE_IPV6)
  10465. if (so.lsa.sa.sa_family == AF_INET6) {
  10466. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  10467. } else
  10468. #endif
  10469. {
  10470. so.lsa.sin.sin_port = usa.sin.sin_port;
  10471. }
  10472. if ((ptr = (struct socket *)
  10473. mg_realloc(ctx->listening_sockets,
  10474. (ctx->num_listening_sockets + 1)
  10475. * sizeof(ctx->listening_sockets[0]))) == NULL) {
  10476. mg_cry(fc(ctx), "%s", "Out of memory");
  10477. closesocket(so.sock);
  10478. so.sock = INVALID_SOCKET;
  10479. continue;
  10480. }
  10481. if ((pfd = (struct pollfd *)mg_realloc(
  10482. ctx->listening_socket_fds,
  10483. (ctx->num_listening_sockets + 1)
  10484. * sizeof(ctx->listening_socket_fds[0]))) == NULL) {
  10485. mg_cry(fc(ctx), "%s", "Out of memory");
  10486. closesocket(so.sock);
  10487. so.sock = INVALID_SOCKET;
  10488. mg_free(ptr);
  10489. continue;
  10490. }
  10491. set_close_on_exec(so.sock, fc(ctx));
  10492. ctx->listening_sockets = ptr;
  10493. ctx->listening_sockets[ctx->num_listening_sockets] = so;
  10494. ctx->listening_socket_fds = pfd;
  10495. ctx->num_listening_sockets++;
  10496. portsOk++;
  10497. }
  10498. if (portsOk != portsTotal) {
  10499. close_all_listening_sockets(ctx);
  10500. portsOk = 0;
  10501. }
  10502. return portsOk;
  10503. }
  10504. static const char *
  10505. header_val(const struct mg_connection *conn, const char *header)
  10506. {
  10507. const char *header_value;
  10508. if ((header_value = mg_get_header(conn, header)) == NULL) {
  10509. return "-";
  10510. } else {
  10511. return header_value;
  10512. }
  10513. }
  10514. static void
  10515. log_access(const struct mg_connection *conn)
  10516. {
  10517. const struct mg_request_info *ri;
  10518. struct mg_file fi;
  10519. char date[64], src_addr[IP_ADDR_STR_LEN];
  10520. struct tm *tm;
  10521. const char *referer;
  10522. const char *user_agent;
  10523. char buf[4096];
  10524. if (!conn || !conn->ctx) {
  10525. return;
  10526. }
  10527. if (conn->ctx->config[ACCESS_LOG_FILE] != NULL) {
  10528. if (mg_fopen(conn,
  10529. conn->ctx->config[ACCESS_LOG_FILE],
  10530. MG_FOPEN_MODE_APPEND,
  10531. &fi) == 0) {
  10532. fi.access.fp = NULL;
  10533. }
  10534. } else {
  10535. fi.access.fp = NULL;
  10536. }
  10537. /* Log is written to a file and/or a callback. If both are not set,
  10538. * executing the rest of the function is pointless. */
  10539. if ((fi.access.fp == NULL) && (conn->ctx->callbacks.log_access == NULL)) {
  10540. return;
  10541. }
  10542. tm = localtime(&conn->conn_birth_time);
  10543. if (tm != NULL) {
  10544. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  10545. } else {
  10546. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  10547. date[sizeof(date) - 1] = '\0';
  10548. }
  10549. ri = &conn->request_info;
  10550. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  10551. referer = header_val(conn, "Referer");
  10552. user_agent = header_val(conn, "User-Agent");
  10553. mg_snprintf(conn,
  10554. NULL, /* Ignore truncation in access log */
  10555. buf,
  10556. sizeof(buf),
  10557. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  10558. src_addr,
  10559. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  10560. date,
  10561. ri->request_method ? ri->request_method : "-",
  10562. ri->request_uri ? ri->request_uri : "-",
  10563. ri->query_string ? "?" : "",
  10564. ri->query_string ? ri->query_string : "",
  10565. ri->http_version,
  10566. conn->status_code,
  10567. conn->num_bytes_sent,
  10568. referer,
  10569. user_agent);
  10570. if (conn->ctx->callbacks.log_access) {
  10571. conn->ctx->callbacks.log_access(conn, buf);
  10572. }
  10573. if (fi.access.fp) {
  10574. int ok = 1;
  10575. flockfile(fi.access.fp);
  10576. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  10577. ok = 0;
  10578. }
  10579. if (fflush(fi.access.fp) != 0) {
  10580. ok = 0;
  10581. }
  10582. funlockfile(fi.access.fp);
  10583. if (mg_fclose(&fi.access) != 0) {
  10584. ok = 0;
  10585. }
  10586. if (!ok) {
  10587. mg_cry(conn,
  10588. "Error writing log file %s",
  10589. conn->ctx->config[ACCESS_LOG_FILE]);
  10590. }
  10591. }
  10592. }
  10593. /* Verify given socket address against the ACL.
  10594. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  10595. */
  10596. static int
  10597. check_acl(struct mg_context *ctx, uint32_t remote_ip)
  10598. {
  10599. int allowed, flag;
  10600. uint32_t net, mask;
  10601. struct vec vec;
  10602. if (ctx) {
  10603. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  10604. /* If any ACL is set, deny by default */
  10605. allowed = (list == NULL) ? '+' : '-';
  10606. while ((list = next_option(list, &vec, NULL)) != NULL) {
  10607. flag = vec.ptr[0];
  10608. if ((flag != '+' && flag != '-')
  10609. || parse_net(&vec.ptr[1], &net, &mask) == 0) {
  10610. mg_cry(fc(ctx),
  10611. "%s: subnet must be [+|-]x.x.x.x[/x]",
  10612. __func__);
  10613. return -1;
  10614. }
  10615. if (net == (remote_ip & mask)) {
  10616. allowed = flag;
  10617. }
  10618. }
  10619. return allowed == '+';
  10620. }
  10621. return -1;
  10622. }
  10623. #if !defined(_WIN32)
  10624. static int
  10625. set_uid_option(struct mg_context *ctx)
  10626. {
  10627. struct passwd *pw;
  10628. if (ctx) {
  10629. const char *uid = ctx->config[RUN_AS_USER];
  10630. int success = 0;
  10631. if (uid == NULL) {
  10632. success = 1;
  10633. } else {
  10634. if ((pw = getpwnam(uid)) == NULL) {
  10635. mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  10636. } else if (setgid(pw->pw_gid) == -1) {
  10637. mg_cry(fc(ctx),
  10638. "%s: setgid(%s): %s",
  10639. __func__,
  10640. uid,
  10641. strerror(errno));
  10642. } else if (setgroups(0, NULL)) {
  10643. mg_cry(fc(ctx),
  10644. "%s: setgroups(): %s",
  10645. __func__,
  10646. strerror(errno));
  10647. } else if (setuid(pw->pw_uid) == -1) {
  10648. mg_cry(fc(ctx),
  10649. "%s: setuid(%s): %s",
  10650. __func__,
  10651. uid,
  10652. strerror(errno));
  10653. } else {
  10654. success = 1;
  10655. }
  10656. }
  10657. return success;
  10658. }
  10659. return 0;
  10660. }
  10661. #endif /* !_WIN32 */
  10662. static void
  10663. tls_dtor(void *key)
  10664. {
  10665. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  10666. /* key == pthread_getspecific(sTlsKey); */
  10667. if (tls) {
  10668. if (tls->is_master == 2) {
  10669. tls->is_master = -3; /* Mark memory as dead */
  10670. mg_free(tls);
  10671. }
  10672. }
  10673. pthread_setspecific(sTlsKey, NULL);
  10674. }
  10675. #if !defined(NO_SSL)
  10676. static int
  10677. ssl_use_pem_file(struct mg_context *ctx, const char *pem, const char *chain);
  10678. static const char *ssl_error(void);
  10679. static int
  10680. refresh_trust(struct mg_connection *conn)
  10681. {
  10682. static int reload_lock = 0;
  10683. static long int data_check = 0;
  10684. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  10685. struct stat cert_buf;
  10686. long int t;
  10687. const char *pem;
  10688. const char *chain;
  10689. int should_verify_peer;
  10690. if ((pem = conn->ctx->config[SSL_CERTIFICATE]) == NULL) {
  10691. /* If peem is NULL and conn->ctx->callbacks.init_ssl is not,
  10692. * refresh_trust still can not work. */
  10693. return 0;
  10694. }
  10695. chain = conn->ctx->config[SSL_CERTIFICATE_CHAIN];
  10696. if (chain == NULL) {
  10697. chain = pem;
  10698. }
  10699. if ((chain != NULL) && (*chain == 0)) {
  10700. chain = NULL;
  10701. }
  10702. t = data_check;
  10703. if (stat(pem, &cert_buf) != -1) {
  10704. t = (long int)cert_buf.st_mtime;
  10705. }
  10706. if (data_check != t) {
  10707. data_check = t;
  10708. should_verify_peer = 0;
  10709. if (conn->ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  10710. if (mg_strcasecmp(conn->ctx->config[SSL_DO_VERIFY_PEER], "yes")
  10711. == 0) {
  10712. should_verify_peer = 1;
  10713. } else if (mg_strcasecmp(conn->ctx->config[SSL_DO_VERIFY_PEER],
  10714. "optional") == 0) {
  10715. should_verify_peer = 1;
  10716. }
  10717. }
  10718. if (should_verify_peer) {
  10719. char *ca_path = conn->ctx->config[SSL_CA_PATH];
  10720. char *ca_file = conn->ctx->config[SSL_CA_FILE];
  10721. if (SSL_CTX_load_verify_locations(conn->ctx->ssl_ctx,
  10722. ca_file,
  10723. ca_path) != 1) {
  10724. mg_cry(fc(conn->ctx),
  10725. "SSL_CTX_load_verify_locations error: %s "
  10726. "ssl_verify_peer requires setting "
  10727. "either ssl_ca_path or ssl_ca_file. Is any of them "
  10728. "present in "
  10729. "the .conf file?",
  10730. ssl_error());
  10731. return 0;
  10732. }
  10733. }
  10734. if (1 == mg_atomic_inc(p_reload_lock)) {
  10735. if (ssl_use_pem_file(conn->ctx, pem, chain) == 0) {
  10736. return 0;
  10737. }
  10738. *p_reload_lock = 0;
  10739. }
  10740. }
  10741. /* lock while cert is reloading */
  10742. while (*p_reload_lock) {
  10743. sleep(1);
  10744. }
  10745. return 1;
  10746. }
  10747. #ifdef OPENSSL_API_1_1
  10748. #else
  10749. static pthread_mutex_t *ssl_mutexes;
  10750. #endif /* OPENSSL_API_1_1 */
  10751. static int
  10752. sslize(struct mg_connection *conn,
  10753. SSL_CTX *s,
  10754. int (*func)(SSL *),
  10755. volatile int *stop_server)
  10756. {
  10757. int ret, err;
  10758. int short_trust;
  10759. unsigned i;
  10760. if (!conn) {
  10761. return 0;
  10762. }
  10763. short_trust =
  10764. (conn->ctx->config[SSL_SHORT_TRUST] != NULL)
  10765. && (mg_strcasecmp(conn->ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  10766. if (short_trust) {
  10767. int trust_ret = refresh_trust(conn);
  10768. if (!trust_ret) {
  10769. return trust_ret;
  10770. }
  10771. }
  10772. conn->ssl = SSL_new(s);
  10773. if (conn->ssl == NULL) {
  10774. return 0;
  10775. }
  10776. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  10777. if (ret != 1) {
  10778. err = SSL_get_error(conn->ssl, ret);
  10779. (void)err; /* TODO: set some error message */
  10780. SSL_free(conn->ssl);
  10781. conn->ssl = NULL;
  10782. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  10783. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  10784. #ifndef OPENSSL_API_1_1
  10785. ERR_remove_state(0);
  10786. #endif
  10787. return 0;
  10788. }
  10789. /* SSL functions may fail and require to be called again:
  10790. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  10791. * Here "func" could be SSL_connect or SSL_accept. */
  10792. for (i = 16; i <= 1024; i *= 2) {
  10793. ret = func(conn->ssl);
  10794. if (ret != 1) {
  10795. err = SSL_get_error(conn->ssl, ret);
  10796. if ((err == SSL_ERROR_WANT_CONNECT)
  10797. || (err == SSL_ERROR_WANT_ACCEPT)
  10798. || (err == SSL_ERROR_WANT_READ)
  10799. || (err == SSL_ERROR_WANT_WRITE)) {
  10800. /* Need to retry the function call "later".
  10801. * See https://linux.die.net/man/3/ssl_get_error
  10802. * This is typical for non-blocking sockets. */
  10803. if (*stop_server) {
  10804. /* Don't wait if the server is going to be stopped. */
  10805. break;
  10806. }
  10807. mg_sleep(i);
  10808. } else if (err == SSL_ERROR_SYSCALL) {
  10809. /* This is an IO error. Look at errno. */
  10810. err = errno;
  10811. /* TODO: set some error message */
  10812. (void)err;
  10813. break;
  10814. } else {
  10815. /* This is an SSL specific error */
  10816. /* TODO: set some error message */
  10817. break;
  10818. }
  10819. } else {
  10820. /* success */
  10821. break;
  10822. }
  10823. }
  10824. if (ret != 1) {
  10825. SSL_free(conn->ssl);
  10826. conn->ssl = NULL;
  10827. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  10828. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  10829. #ifndef OPENSSL_API_1_1
  10830. ERR_remove_state(0);
  10831. #endif
  10832. return 0;
  10833. }
  10834. return 1;
  10835. }
  10836. /* Return OpenSSL error message (from CRYPTO lib) */
  10837. static const char *
  10838. ssl_error(void)
  10839. {
  10840. unsigned long err;
  10841. err = ERR_get_error();
  10842. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  10843. }
  10844. static int
  10845. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  10846. {
  10847. int i;
  10848. const char hexdigit[] = "0123456789abcdef";
  10849. if (memlen <= 0 || buflen <= 0) {
  10850. return 0;
  10851. }
  10852. if (buflen < (3 * memlen)) {
  10853. return 0;
  10854. }
  10855. for (i = 0; i < memlen; i++) {
  10856. if (i > 0) {
  10857. buf[3 * i - 1] = ' ';
  10858. }
  10859. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  10860. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  10861. }
  10862. buf[3 * memlen - 1] = 0;
  10863. return 1;
  10864. }
  10865. static void
  10866. ssl_get_client_cert_info(struct mg_connection *conn)
  10867. {
  10868. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  10869. if (cert) {
  10870. char str_subject[1024];
  10871. char str_issuer[1024];
  10872. char str_finger[1024];
  10873. unsigned char buf[256];
  10874. char *str_serial = NULL;
  10875. unsigned int ulen;
  10876. int ilen;
  10877. unsigned char *tmp_buf;
  10878. unsigned char *tmp_p;
  10879. /* Handle to algorithm used for fingerprint */
  10880. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  10881. /* Get Subject and issuer */
  10882. X509_NAME *subj = X509_get_subject_name(cert);
  10883. X509_NAME *iss = X509_get_issuer_name(cert);
  10884. /* Get serial number */
  10885. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  10886. /* Translate serial number to a hex string */
  10887. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  10888. str_serial = BN_bn2hex(serial_bn);
  10889. BN_free(serial_bn);
  10890. /* Translate subject and issuer to a string */
  10891. (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
  10892. (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
  10893. /* Calculate SHA1 fingerprint and store as a hex string */
  10894. ulen = 0;
  10895. /* ASN1_digest is deprecated. Do the calculation manually,
  10896. * using EVP_Digest. */
  10897. ilen = i2d_X509((void *)cert, NULL);
  10898. tmp_buf =
  10899. (ilen > 0) ? (unsigned char *)mg_malloc((unsigned)ilen + 1) : NULL;
  10900. if (tmp_buf) {
  10901. tmp_p = tmp_buf;
  10902. (void)i2d_X509((void *)cert, &tmp_p);
  10903. if (!EVP_Digest(
  10904. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  10905. ulen = 0;
  10906. }
  10907. mg_free(tmp_buf);
  10908. }
  10909. if (!hexdump2string(
  10910. buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
  10911. *str_finger = 0;
  10912. }
  10913. conn->request_info.client_cert =
  10914. (struct client_cert *)mg_malloc(sizeof(struct client_cert));
  10915. if (conn->request_info.client_cert) {
  10916. conn->request_info.client_cert->subject = mg_strdup(str_subject);
  10917. conn->request_info.client_cert->issuer = mg_strdup(str_issuer);
  10918. conn->request_info.client_cert->serial = mg_strdup(str_serial);
  10919. conn->request_info.client_cert->finger = mg_strdup(str_finger);
  10920. } else {
  10921. /* TODO: write some OOM message */
  10922. }
  10923. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  10924. * see https://linux.die.net/man/3/bn_bn2hex */
  10925. OPENSSL_free(str_serial);
  10926. /* Free certificate memory */
  10927. X509_free(cert);
  10928. }
  10929. }
  10930. #ifdef OPENSSL_API_1_1
  10931. #else
  10932. static void
  10933. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  10934. {
  10935. (void)line;
  10936. (void)file;
  10937. if (mode & 1) {
  10938. /* 1 is CRYPTO_LOCK */
  10939. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  10940. } else {
  10941. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  10942. }
  10943. }
  10944. #endif /* OPENSSL_API_1_1 */
  10945. #if !defined(NO_SSL_DL)
  10946. static void *
  10947. load_dll(char *ebuf, size_t ebuf_len, const char *dll_name, struct ssl_func *sw)
  10948. {
  10949. union {
  10950. void *p;
  10951. void (*fp)(void);
  10952. } u;
  10953. void *dll_handle;
  10954. struct ssl_func *fp;
  10955. int ok;
  10956. int truncated = 0;
  10957. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  10958. mg_snprintf(NULL,
  10959. NULL, /* No truncation check for ebuf */
  10960. ebuf,
  10961. ebuf_len,
  10962. "%s: cannot load %s",
  10963. __func__,
  10964. dll_name);
  10965. return NULL;
  10966. }
  10967. ok = 1;
  10968. for (fp = sw; fp->name != NULL; fp++) {
  10969. #ifdef _WIN32
  10970. /* GetProcAddress() returns pointer to function */
  10971. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  10972. #else
  10973. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  10974. * pointers to function pointers. We need to use a union to make a
  10975. * cast. */
  10976. u.p = dlsym(dll_handle, fp->name);
  10977. #endif /* _WIN32 */
  10978. if (u.fp == NULL) {
  10979. if (ok) {
  10980. mg_snprintf(NULL,
  10981. &truncated,
  10982. ebuf,
  10983. ebuf_len,
  10984. "%s: %s: cannot find %s",
  10985. __func__,
  10986. dll_name,
  10987. fp->name);
  10988. ok = 0;
  10989. } else {
  10990. size_t cur_len = strlen(ebuf);
  10991. if (!truncated) {
  10992. mg_snprintf(NULL,
  10993. &truncated,
  10994. ebuf + cur_len,
  10995. ebuf_len - cur_len - 3,
  10996. ", %s",
  10997. fp->name);
  10998. if (truncated) {
  10999. /* If truncated, add "..." */
  11000. strcat(ebuf, "...");
  11001. }
  11002. }
  11003. }
  11004. /* Debug:
  11005. * printf("Missing function: %s\n", fp->name); */
  11006. } else {
  11007. fp->ptr = u.fp;
  11008. }
  11009. }
  11010. if (!ok) {
  11011. (void)dlclose(dll_handle);
  11012. return NULL;
  11013. }
  11014. return dll_handle;
  11015. }
  11016. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  11017. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  11018. #endif /* NO_SSL_DL */
  11019. #if defined(SSL_ALREADY_INITIALIZED)
  11020. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  11021. #else
  11022. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  11023. #endif
  11024. static int
  11025. initialize_ssl(char *ebuf, size_t ebuf_len)
  11026. {
  11027. #ifdef OPENSSL_API_1_1
  11028. if (ebuf_len > 0) {
  11029. ebuf[0] = 0;
  11030. }
  11031. #if !defined(NO_SSL_DL)
  11032. if (!cryptolib_dll_handle) {
  11033. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  11034. if (!cryptolib_dll_handle) {
  11035. return 0;
  11036. }
  11037. }
  11038. #endif /* NO_SSL_DL */
  11039. if (mg_atomic_inc(&cryptolib_users) > 1) {
  11040. return 1;
  11041. }
  11042. #else /* not OPENSSL_API_1_1 */
  11043. int i;
  11044. size_t size;
  11045. if (ebuf_len > 0) {
  11046. ebuf[0] = 0;
  11047. }
  11048. #if !defined(NO_SSL_DL)
  11049. if (!cryptolib_dll_handle) {
  11050. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  11051. if (!cryptolib_dll_handle) {
  11052. return 0;
  11053. }
  11054. }
  11055. #endif /* NO_SSL_DL */
  11056. if (mg_atomic_inc(&cryptolib_users) > 1) {
  11057. return 1;
  11058. }
  11059. /* Initialize locking callbacks, needed for thread safety.
  11060. * http://www.openssl.org/support/faq.html#PROG1
  11061. */
  11062. i = CRYPTO_num_locks();
  11063. if (i < 0) {
  11064. i = 0;
  11065. }
  11066. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  11067. if (size == 0) {
  11068. ssl_mutexes = NULL;
  11069. } else if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  11070. mg_snprintf(NULL,
  11071. NULL, /* No truncation check for ebuf */
  11072. ebuf,
  11073. ebuf_len,
  11074. "%s: cannot allocate mutexes: %s",
  11075. __func__,
  11076. ssl_error());
  11077. return 0;
  11078. }
  11079. for (i = 0; i < CRYPTO_num_locks(); i++) {
  11080. pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr);
  11081. }
  11082. CRYPTO_set_locking_callback(&ssl_locking_callback);
  11083. CRYPTO_set_id_callback(&mg_current_thread_id);
  11084. #endif /* OPENSSL_API_1_1 */
  11085. return 1;
  11086. }
  11087. static int
  11088. ssl_use_pem_file(struct mg_context *ctx, const char *pem, const char *chain)
  11089. {
  11090. if (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0) {
  11091. mg_cry(fc(ctx),
  11092. "%s: cannot open certificate file %s: %s",
  11093. __func__,
  11094. pem,
  11095. ssl_error());
  11096. return 0;
  11097. }
  11098. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  11099. if (SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0) {
  11100. mg_cry(fc(ctx),
  11101. "%s: cannot open private key file %s: %s",
  11102. __func__,
  11103. pem,
  11104. ssl_error());
  11105. return 0;
  11106. }
  11107. if (SSL_CTX_check_private_key(ctx->ssl_ctx) == 0) {
  11108. mg_cry(fc(ctx),
  11109. "%s: certificate and private key do not match: %s",
  11110. __func__,
  11111. pem);
  11112. return 0;
  11113. }
  11114. /* In contrast to OpenSSL, wolfSSL does not support certificate
  11115. * chain files that contain private keys and certificates in
  11116. * SSL_CTX_use_certificate_chain_file.
  11117. * The CivetWeb-Server used pem-Files that contained both information.
  11118. * In order to make wolfSSL work, it is split in two files.
  11119. * One file that contains key and certificate used by the server and
  11120. * an optional chain file for the ssl stack.
  11121. */
  11122. if (chain) {
  11123. if (SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, chain) == 0) {
  11124. mg_cry(fc(ctx),
  11125. "%s: cannot use certificate chain file %s: %s",
  11126. __func__,
  11127. pem,
  11128. ssl_error());
  11129. return 0;
  11130. }
  11131. }
  11132. return 1;
  11133. }
  11134. #ifdef OPENSSL_API_1_1
  11135. static unsigned long
  11136. ssl_get_protocol(int version_id)
  11137. {
  11138. long unsigned ret = SSL_OP_ALL;
  11139. if (version_id > 0)
  11140. ret |= SSL_OP_NO_SSLv2;
  11141. if (version_id > 1)
  11142. ret |= SSL_OP_NO_SSLv3;
  11143. if (version_id > 2)
  11144. ret |= SSL_OP_NO_TLSv1;
  11145. if (version_id > 3)
  11146. ret |= SSL_OP_NO_TLSv1_1;
  11147. return ret;
  11148. }
  11149. #else
  11150. static long
  11151. ssl_get_protocol(int version_id)
  11152. {
  11153. long ret = SSL_OP_ALL;
  11154. if (version_id > 0)
  11155. ret |= SSL_OP_NO_SSLv2;
  11156. if (version_id > 1)
  11157. ret |= SSL_OP_NO_SSLv3;
  11158. if (version_id > 2)
  11159. ret |= SSL_OP_NO_TLSv1;
  11160. if (version_id > 3)
  11161. ret |= SSL_OP_NO_TLSv1_1;
  11162. return ret;
  11163. }
  11164. #endif /* OPENSSL_API_1_1 */
  11165. /* Dynamically load SSL library. Set up ctx->ssl_ctx pointer. */
  11166. static int
  11167. set_ssl_option(struct mg_context *ctx)
  11168. {
  11169. const char *pem;
  11170. const char *chain;
  11171. int callback_ret;
  11172. int should_verify_peer;
  11173. int peer_certificate_optional;
  11174. const char *ca_path;
  11175. const char *ca_file;
  11176. int use_default_verify_paths;
  11177. int verify_depth;
  11178. time_t now_rt = time(NULL);
  11179. struct timespec now_mt;
  11180. md5_byte_t ssl_context_id[16];
  11181. md5_state_t md5state;
  11182. int protocol_ver;
  11183. char ebuf[128];
  11184. /* If PEM file is not specified and the init_ssl callback
  11185. * is not specified, skip SSL initialization. */
  11186. if (!ctx) {
  11187. return 0;
  11188. }
  11189. if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL
  11190. && ctx->callbacks.init_ssl == NULL) {
  11191. return 1;
  11192. }
  11193. chain = ctx->config[SSL_CERTIFICATE_CHAIN];
  11194. if (chain == NULL) {
  11195. chain = pem;
  11196. }
  11197. if ((chain != NULL) && (*chain == 0)) {
  11198. chain = NULL;
  11199. }
  11200. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  11201. mg_cry(fc(ctx), "%s", ebuf);
  11202. return 0;
  11203. }
  11204. #if !defined(NO_SSL_DL)
  11205. if (!ssllib_dll_handle) {
  11206. ssllib_dll_handle = load_dll(ebuf, sizeof(ebuf), SSL_LIB, ssl_sw);
  11207. if (!ssllib_dll_handle) {
  11208. mg_cry(fc(ctx), "%s", ebuf);
  11209. return 0;
  11210. }
  11211. }
  11212. #endif /* NO_SSL_DL */
  11213. #ifdef OPENSSL_API_1_1
  11214. /* Initialize SSL library */
  11215. OPENSSL_init_ssl(0, NULL);
  11216. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  11217. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  11218. NULL);
  11219. if ((ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  11220. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  11221. return 0;
  11222. }
  11223. #else
  11224. /* Initialize SSL library */
  11225. SSL_library_init();
  11226. SSL_load_error_strings();
  11227. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  11228. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  11229. return 0;
  11230. }
  11231. #endif /* OPENSSL_API_1_1 */
  11232. SSL_CTX_clear_options(ctx->ssl_ctx,
  11233. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  11234. | SSL_OP_NO_TLSv1_1);
  11235. protocol_ver = atoi(ctx->config[SSL_PROTOCOL_VERSION]);
  11236. SSL_CTX_set_options(ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  11237. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  11238. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  11239. #if !defined(NO_SSL_DL)
  11240. SSL_CTX_set_ecdh_auto(ctx->ssl_ctx, 1);
  11241. #endif /* NO_SSL_DL */
  11242. /* If a callback has been specified, call it. */
  11243. callback_ret =
  11244. (ctx->callbacks.init_ssl == NULL)
  11245. ? 0
  11246. : (ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data));
  11247. /* If callback returns 0, civetweb sets up the SSL certificate.
  11248. * If it returns 1, civetweb assumes the calback already did this.
  11249. * If it returns -1, initializing ssl fails. */
  11250. if (callback_ret < 0) {
  11251. mg_cry(fc(ctx), "SSL callback returned error: %i", callback_ret);
  11252. return 0;
  11253. }
  11254. if (callback_ret > 0) {
  11255. if (pem != NULL) {
  11256. (void)SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
  11257. }
  11258. return 1;
  11259. }
  11260. /* Use some UID as session context ID. */
  11261. md5_init(&md5state);
  11262. md5_append(&md5state, (const md5_byte_t *)&now_rt, sizeof(now_rt));
  11263. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  11264. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  11265. md5_append(&md5state,
  11266. (const md5_byte_t *)ctx->config[LISTENING_PORTS],
  11267. strlen(ctx->config[LISTENING_PORTS]));
  11268. md5_append(&md5state, (const md5_byte_t *)ctx, sizeof(*ctx));
  11269. md5_finish(&md5state, ssl_context_id);
  11270. SSL_CTX_set_session_id_context(ctx->ssl_ctx,
  11271. (const unsigned char *)&ssl_context_id,
  11272. sizeof(ssl_context_id));
  11273. if (pem != NULL) {
  11274. if (!ssl_use_pem_file(ctx, pem, chain)) {
  11275. return 0;
  11276. }
  11277. }
  11278. /* Should we support client certificates? */
  11279. /* Default is "no". */
  11280. should_verify_peer = 0;
  11281. peer_certificate_optional = 0;
  11282. if (ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  11283. if (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  11284. /* Yes, they are mandatory */
  11285. should_verify_peer = 1;
  11286. peer_certificate_optional = 0;
  11287. } else if (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "optional")
  11288. == 0) {
  11289. /* Yes, they are optional */
  11290. should_verify_peer = 1;
  11291. peer_certificate_optional = 1;
  11292. }
  11293. }
  11294. use_default_verify_paths =
  11295. (ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  11296. && (mg_strcasecmp(ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes") == 0);
  11297. if (should_verify_peer) {
  11298. ca_path = ctx->config[SSL_CA_PATH];
  11299. ca_file = ctx->config[SSL_CA_FILE];
  11300. if (SSL_CTX_load_verify_locations(ctx->ssl_ctx, ca_file, ca_path)
  11301. != 1) {
  11302. mg_cry(fc(ctx),
  11303. "SSL_CTX_load_verify_locations error: %s "
  11304. "ssl_verify_peer requires setting "
  11305. "either ssl_ca_path or ssl_ca_file. Is any of them "
  11306. "present in "
  11307. "the .conf file?",
  11308. ssl_error());
  11309. return 0;
  11310. }
  11311. if (peer_certificate_optional) {
  11312. SSL_CTX_set_verify(ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  11313. } else {
  11314. SSL_CTX_set_verify(ctx->ssl_ctx,
  11315. SSL_VERIFY_PEER
  11316. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  11317. NULL);
  11318. }
  11319. if (use_default_verify_paths
  11320. && SSL_CTX_set_default_verify_paths(ctx->ssl_ctx) != 1) {
  11321. mg_cry(fc(ctx),
  11322. "SSL_CTX_set_default_verify_paths error: %s",
  11323. ssl_error());
  11324. return 0;
  11325. }
  11326. if (ctx->config[SSL_VERIFY_DEPTH]) {
  11327. verify_depth = atoi(ctx->config[SSL_VERIFY_DEPTH]);
  11328. SSL_CTX_set_verify_depth(ctx->ssl_ctx, verify_depth);
  11329. }
  11330. }
  11331. if (ctx->config[SSL_CIPHER_LIST] != NULL) {
  11332. if (SSL_CTX_set_cipher_list(ctx->ssl_ctx, ctx->config[SSL_CIPHER_LIST])
  11333. != 1) {
  11334. mg_cry(fc(ctx), "SSL_CTX_set_cipher_list error: %s", ssl_error());
  11335. }
  11336. }
  11337. return 1;
  11338. }
  11339. static void
  11340. uninitialize_ssl(void)
  11341. {
  11342. #ifdef OPENSSL_API_1_1
  11343. if (mg_atomic_dec(&cryptolib_users) == 0) {
  11344. /* Shutdown according to
  11345. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  11346. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  11347. */
  11348. CONF_modules_unload(1);
  11349. #else
  11350. int i;
  11351. if (mg_atomic_dec(&cryptolib_users) == 0) {
  11352. /* Shutdown according to
  11353. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  11354. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  11355. */
  11356. CRYPTO_set_locking_callback(NULL);
  11357. CRYPTO_set_id_callback(NULL);
  11358. ENGINE_cleanup();
  11359. CONF_modules_unload(1);
  11360. ERR_free_strings();
  11361. EVP_cleanup();
  11362. CRYPTO_cleanup_all_ex_data();
  11363. ERR_remove_state(0);
  11364. for (i = 0; i < CRYPTO_num_locks(); i++) {
  11365. pthread_mutex_destroy(&ssl_mutexes[i]);
  11366. }
  11367. mg_free(ssl_mutexes);
  11368. ssl_mutexes = NULL;
  11369. #endif /* OPENSSL_API_1_1 */
  11370. }
  11371. }
  11372. #endif /* !NO_SSL */
  11373. static int
  11374. set_gpass_option(struct mg_context *ctx)
  11375. {
  11376. if (ctx) {
  11377. struct mg_file file = STRUCT_FILE_INITIALIZER;
  11378. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  11379. if (path != NULL && !mg_stat(fc(ctx), path, &file.stat)) {
  11380. mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  11381. return 0;
  11382. }
  11383. return 1;
  11384. }
  11385. return 0;
  11386. }
  11387. static int
  11388. set_acl_option(struct mg_context *ctx)
  11389. {
  11390. return check_acl(ctx, (uint32_t)0x7f000001UL) != -1;
  11391. }
  11392. static void
  11393. reset_per_request_attributes(struct mg_connection *conn)
  11394. {
  11395. if (!conn) {
  11396. return;
  11397. }
  11398. conn->path_info = NULL;
  11399. conn->num_bytes_sent = conn->consumed_content = 0;
  11400. conn->status_code = -1;
  11401. conn->is_chunked = 0;
  11402. conn->must_close = conn->request_len = conn->throttle = 0;
  11403. conn->request_info.content_length = -1;
  11404. conn->request_info.remote_user = NULL;
  11405. conn->request_info.request_method = NULL;
  11406. conn->request_info.request_uri = NULL;
  11407. conn->request_info.local_uri = NULL;
  11408. #if defined(MG_LEGACY_INTERFACE)
  11409. conn->request_info.uri = NULL; /* TODO: cleanup uri,
  11410. * local_uri and request_uri */
  11411. #endif
  11412. conn->request_info.http_version = NULL;
  11413. conn->request_info.num_headers = 0;
  11414. conn->data_len = 0;
  11415. conn->chunk_remainder = 0;
  11416. }
  11417. #if 0
  11418. /* Note: set_sock_timeout is not required for non-blocking sockets.
  11419. * Leave this function here (commented out) for reference until
  11420. * CivetWeb 1.9 is tested, and the tests confirme this function is
  11421. * no longer required.
  11422. */
  11423. static int
  11424. set_sock_timeout(SOCKET sock, int milliseconds)
  11425. {
  11426. int r0 = 0, r1, r2;
  11427. #ifdef _WIN32
  11428. /* Windows specific */
  11429. DWORD tv = (DWORD)milliseconds;
  11430. #else
  11431. /* Linux, ... (not Windows) */
  11432. struct timeval tv;
  11433. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  11434. * max. time waiting for the acknowledged of TCP data before the connection
  11435. * will be forcefully closed and ETIMEDOUT is returned to the application.
  11436. * If this option is not set, the default timeout of 20-30 minutes is used.
  11437. */
  11438. /* #define TCP_USER_TIMEOUT (18) */
  11439. #if defined(TCP_USER_TIMEOUT)
  11440. unsigned int uto = (unsigned int)milliseconds;
  11441. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  11442. #endif
  11443. memset(&tv, 0, sizeof(tv));
  11444. tv.tv_sec = milliseconds / 1000;
  11445. tv.tv_usec = (milliseconds * 1000) % 1000000;
  11446. #endif /* _WIN32 */
  11447. r1 = setsockopt(
  11448. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  11449. r2 = setsockopt(
  11450. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  11451. return r0 || r1 || r2;
  11452. }
  11453. #endif
  11454. static int
  11455. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  11456. {
  11457. if (setsockopt(sock,
  11458. IPPROTO_TCP,
  11459. TCP_NODELAY,
  11460. (SOCK_OPT_TYPE)&nodelay_on,
  11461. sizeof(nodelay_on)) != 0) {
  11462. /* Error */
  11463. return 1;
  11464. }
  11465. /* OK */
  11466. return 0;
  11467. }
  11468. static void
  11469. close_socket_gracefully(struct mg_connection *conn)
  11470. {
  11471. #if defined(_WIN32)
  11472. char buf[MG_BUF_LEN];
  11473. int n;
  11474. #endif
  11475. struct linger linger;
  11476. int error_code = 0;
  11477. int linger_timeout = -2;
  11478. socklen_t opt_len = sizeof(error_code);
  11479. if (!conn) {
  11480. return;
  11481. }
  11482. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  11483. * "Note that enabling a nonzero timeout on a nonblocking socket
  11484. * is not recommended.", so set it to blocking now */
  11485. set_blocking_mode(conn->client.sock, 1);
  11486. /* Send FIN to the client */
  11487. shutdown(conn->client.sock, SHUTDOWN_WR);
  11488. #if defined(_WIN32)
  11489. /* Read and discard pending incoming data. If we do not do that and
  11490. * close
  11491. * the socket, the data in the send buffer may be discarded. This
  11492. * behaviour is seen on Windows, when client keeps sending data
  11493. * when server decides to close the connection; then when client
  11494. * does recv() it gets no data back. */
  11495. do {
  11496. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  11497. } while (n > 0);
  11498. #endif
  11499. if (conn->ctx->config[LINGER_TIMEOUT]) {
  11500. linger_timeout = atoi(conn->ctx->config[LINGER_TIMEOUT]);
  11501. }
  11502. /* Set linger option according to configuration */
  11503. if (linger_timeout >= 0) {
  11504. /* Set linger option to avoid socket hanging out after close. This
  11505. * prevent ephemeral port exhaust problem under high QPS. */
  11506. linger.l_onoff = 1;
  11507. #if defined(_MSC_VER)
  11508. #pragma warning(push)
  11509. #pragma warning(disable : 4244)
  11510. #endif
  11511. linger.l_linger = (linger_timeout + 999) / 1000;
  11512. #if defined(_MSC_VER)
  11513. #pragma warning(pop)
  11514. #endif
  11515. } else {
  11516. linger.l_onoff = 0;
  11517. linger.l_linger = 0;
  11518. }
  11519. if (linger_timeout < -1) {
  11520. /* Default: don't configure any linger */
  11521. } else if (getsockopt(conn->client.sock,
  11522. SOL_SOCKET,
  11523. SO_ERROR,
  11524. (char *)&error_code,
  11525. &opt_len) != 0) {
  11526. /* Cannot determine if socket is already closed. This should
  11527. * not occur and never did in a test. Log an error message
  11528. * and continue. */
  11529. mg_cry(conn,
  11530. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  11531. __func__,
  11532. strerror(ERRNO));
  11533. } else if (error_code == ECONNRESET) {
  11534. /* Socket already closed by client/peer, close socket without linger */
  11535. } else {
  11536. /* Set linger timeout */
  11537. if (setsockopt(conn->client.sock,
  11538. SOL_SOCKET,
  11539. SO_LINGER,
  11540. (char *)&linger,
  11541. sizeof(linger)) != 0) {
  11542. mg_cry(conn,
  11543. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  11544. __func__,
  11545. linger.l_onoff,
  11546. linger.l_linger,
  11547. strerror(ERRNO));
  11548. }
  11549. }
  11550. /* Now we know that our FIN is ACK-ed, safe to close */
  11551. closesocket(conn->client.sock);
  11552. conn->client.sock = INVALID_SOCKET;
  11553. }
  11554. static void
  11555. close_connection(struct mg_connection *conn)
  11556. {
  11557. if (!conn || !conn->ctx) {
  11558. return;
  11559. }
  11560. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  11561. if (conn->lua_websocket_state) {
  11562. lua_websocket_close(conn, conn->lua_websocket_state);
  11563. conn->lua_websocket_state = NULL;
  11564. }
  11565. #endif
  11566. /* call the connection_close callback if assigned */
  11567. if ((conn->ctx->callbacks.connection_close != NULL)
  11568. && (conn->ctx->context_type == 1)) {
  11569. conn->ctx->callbacks.connection_close(conn);
  11570. }
  11571. mg_lock_connection(conn);
  11572. conn->must_close = 1;
  11573. #ifndef NO_SSL
  11574. if (conn->ssl != NULL) {
  11575. /* Run SSL_shutdown twice to ensure completly close SSL connection
  11576. */
  11577. SSL_shutdown(conn->ssl);
  11578. SSL_free(conn->ssl);
  11579. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  11580. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  11581. #ifndef OPENSSL_API_1_1
  11582. ERR_remove_state(0);
  11583. #endif
  11584. conn->ssl = NULL;
  11585. }
  11586. #endif
  11587. if (conn->client.sock != INVALID_SOCKET) {
  11588. close_socket_gracefully(conn);
  11589. conn->client.sock = INVALID_SOCKET;
  11590. }
  11591. mg_unlock_connection(conn);
  11592. }
  11593. void
  11594. mg_close_connection(struct mg_connection *conn)
  11595. {
  11596. struct mg_context *client_ctx = NULL;
  11597. if (conn == NULL) {
  11598. return;
  11599. }
  11600. #if defined(USE_WEBSOCKET)
  11601. if (conn->ctx->context_type == 2) {
  11602. unsigned int i;
  11603. /* ws/wss client */
  11604. client_ctx = conn->ctx;
  11605. /* client context: loops must end */
  11606. conn->ctx->stop_flag = 1;
  11607. /* We need to get the client thread out of the select/recv call here. */
  11608. /* Since we use a sleep quantum of some seconds to check for recv
  11609. * timeouts, we will just wait a few seconds in mg_join_thread. */
  11610. /* join worker thread */
  11611. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  11612. if (client_ctx->worker_threadids[i] != 0) {
  11613. mg_join_thread(client_ctx->worker_threadids[i]);
  11614. }
  11615. }
  11616. }
  11617. #else
  11618. (void)client_ctx;
  11619. #endif
  11620. close_connection(conn);
  11621. #ifndef NO_SSL
  11622. if (conn->client_ssl_ctx != NULL) {
  11623. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  11624. }
  11625. #endif
  11626. if (client_ctx != NULL) {
  11627. /* free context */
  11628. mg_free(client_ctx->worker_threadids);
  11629. mg_free(client_ctx);
  11630. (void)pthread_mutex_destroy(&conn->mutex);
  11631. mg_free(conn);
  11632. } else if (conn->ctx->context_type == 0) { // Client
  11633. mg_free(conn);
  11634. }
  11635. }
  11636. static struct mg_connection *
  11637. mg_connect_client_impl(const struct mg_client_options *client_options,
  11638. int use_ssl,
  11639. char *ebuf,
  11640. size_t ebuf_len)
  11641. {
  11642. static struct mg_context fake_ctx;
  11643. struct mg_connection *conn = NULL;
  11644. SOCKET sock;
  11645. union usa sa;
  11646. if (!connect_socket(&fake_ctx,
  11647. client_options->host,
  11648. client_options->port,
  11649. use_ssl,
  11650. ebuf,
  11651. ebuf_len,
  11652. &sock,
  11653. &sa)) {
  11654. return NULL;
  11655. }
  11656. if ((conn = (struct mg_connection *)
  11657. mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) {
  11658. mg_snprintf(NULL,
  11659. NULL, /* No truncation check for ebuf */
  11660. ebuf,
  11661. ebuf_len,
  11662. "calloc(): %s",
  11663. strerror(ERRNO));
  11664. closesocket(sock);
  11665. return NULL;
  11666. }
  11667. #ifndef NO_SSL
  11668. #ifdef OPENSSL_API_1_1
  11669. if (use_ssl
  11670. && (conn->client_ssl_ctx = SSL_CTX_new(TLS_client_method())) == NULL) {
  11671. mg_snprintf(NULL,
  11672. NULL, /* No truncation check for ebuf */
  11673. ebuf,
  11674. ebuf_len,
  11675. "SSL_CTX_new error");
  11676. closesocket(sock);
  11677. mg_free(conn);
  11678. return NULL;
  11679. }
  11680. #else
  11681. if (use_ssl
  11682. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  11683. == NULL) {
  11684. mg_snprintf(NULL,
  11685. NULL, /* No truncation check for ebuf */
  11686. ebuf,
  11687. ebuf_len,
  11688. "SSL_CTX_new error");
  11689. closesocket(sock);
  11690. mg_free(conn);
  11691. return NULL;
  11692. }
  11693. #endif /* OPENSSL_API_1_1 */
  11694. #endif /* NO_SSL */
  11695. #ifdef USE_IPV6
  11696. socklen_t len = (sa.sa.sa_family == AF_INET)
  11697. ? sizeof(conn->client.rsa.sin)
  11698. : sizeof(conn->client.rsa.sin6);
  11699. struct sockaddr *psa = (sa.sa.sa_family == AF_INET)
  11700. ? (struct sockaddr *)&(conn->client.rsa.sin)
  11701. : (struct sockaddr *)&(conn->client.rsa.sin6);
  11702. #else
  11703. socklen_t len = sizeof(conn->client.rsa.sin);
  11704. struct sockaddr *psa = (struct sockaddr *)&(conn->client.rsa.sin);
  11705. #endif
  11706. conn->buf_size = MAX_REQUEST_SIZE;
  11707. conn->buf = (char *)(conn + 1);
  11708. conn->ctx = &fake_ctx;
  11709. conn->client.sock = sock;
  11710. conn->client.lsa = sa;
  11711. if (getsockname(sock, psa, &len) != 0) {
  11712. mg_cry(conn, "%s: getsockname() failed: %s", __func__, strerror(ERRNO));
  11713. }
  11714. conn->client.is_ssl = use_ssl ? 1 : 0;
  11715. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  11716. #ifndef NO_SSL
  11717. if (use_ssl) {
  11718. fake_ctx.ssl_ctx = conn->client_ssl_ctx;
  11719. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  11720. * SSL_CTX_set_verify call is needed to switch off server
  11721. * certificate checking, which is off by default in OpenSSL and
  11722. * on in yaSSL. */
  11723. /* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  11724. * SSL_VERIFY_PEER, verify_ssl_server); */
  11725. if (client_options->client_cert) {
  11726. if (!ssl_use_pem_file(&fake_ctx,
  11727. client_options->client_cert,
  11728. NULL)) {
  11729. mg_snprintf(NULL,
  11730. NULL, /* No truncation check for ebuf */
  11731. ebuf,
  11732. ebuf_len,
  11733. "Can not use SSL client certificate");
  11734. SSL_CTX_free(conn->client_ssl_ctx);
  11735. closesocket(sock);
  11736. mg_free(conn);
  11737. return NULL;
  11738. }
  11739. }
  11740. if (client_options->server_cert) {
  11741. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  11742. client_options->server_cert,
  11743. NULL);
  11744. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  11745. } else {
  11746. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  11747. }
  11748. if (!sslize(conn,
  11749. conn->client_ssl_ctx,
  11750. SSL_connect,
  11751. &(conn->ctx->stop_flag))) {
  11752. mg_snprintf(NULL,
  11753. NULL, /* No truncation check for ebuf */
  11754. ebuf,
  11755. ebuf_len,
  11756. "SSL connection error");
  11757. SSL_CTX_free(conn->client_ssl_ctx);
  11758. closesocket(sock);
  11759. mg_free(conn);
  11760. return NULL;
  11761. }
  11762. }
  11763. #endif
  11764. set_blocking_mode(sock, 0);
  11765. return conn;
  11766. }
  11767. CIVETWEB_API struct mg_connection *
  11768. mg_connect_client_secure(const struct mg_client_options *client_options,
  11769. char *error_buffer,
  11770. size_t error_buffer_size)
  11771. {
  11772. return mg_connect_client_impl(client_options,
  11773. 1,
  11774. error_buffer,
  11775. error_buffer_size);
  11776. }
  11777. struct mg_connection *
  11778. mg_connect_client(const char *host,
  11779. int port,
  11780. int use_ssl,
  11781. char *error_buffer,
  11782. size_t error_buffer_size)
  11783. {
  11784. struct mg_client_options opts;
  11785. memset(&opts, 0, sizeof(opts));
  11786. opts.host = host;
  11787. opts.port = port;
  11788. return mg_connect_client_impl(&opts,
  11789. use_ssl,
  11790. error_buffer,
  11791. error_buffer_size);
  11792. }
  11793. static const struct {
  11794. const char *proto;
  11795. size_t proto_len;
  11796. unsigned default_port;
  11797. } abs_uri_protocols[] = {{"http://", 7, 80},
  11798. {"https://", 8, 443},
  11799. {"ws://", 5, 80},
  11800. {"wss://", 6, 443},
  11801. {NULL, 0, 0}};
  11802. /* Check if the uri is valid.
  11803. * return 0 for invalid uri,
  11804. * return 1 for *,
  11805. * return 2 for relative uri,
  11806. * return 3 for absolute uri without port,
  11807. * return 4 for absolute uri with port */
  11808. static int
  11809. get_uri_type(const char *uri)
  11810. {
  11811. int i;
  11812. const char *hostend, *portbegin;
  11813. char *portend;
  11814. unsigned long port;
  11815. /* According to the HTTP standard
  11816. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  11817. * URI can be an asterisk (*) or should start with slash (relative uri),
  11818. * or it should start with the protocol (absolute uri). */
  11819. if (uri[0] == '*' && uri[1] == '\0') {
  11820. /* asterisk */
  11821. return 1;
  11822. }
  11823. /* Valid URIs according to RFC 3986
  11824. * (https://www.ietf.org/rfc/rfc3986.txt)
  11825. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  11826. * and unreserved characters A-Z a-z 0-9 and -._~
  11827. * and % encoded symbols.
  11828. */
  11829. for (i = 0; uri[i] != 0; i++) {
  11830. if (uri[i] < 33) {
  11831. /* control characters and spaces are invalid */
  11832. return 0;
  11833. }
  11834. if (uri[i] > 126) {
  11835. /* non-ascii characters must be % encoded */
  11836. return 0;
  11837. } else {
  11838. switch (uri[i]) {
  11839. case '"': /* 34 */
  11840. case '<': /* 60 */
  11841. case '>': /* 62 */
  11842. case '\\': /* 92 */
  11843. case '^': /* 94 */
  11844. case '`': /* 96 */
  11845. case '{': /* 123 */
  11846. case '|': /* 124 */
  11847. case '}': /* 125 */
  11848. return 0;
  11849. default:
  11850. /* character is ok */
  11851. break;
  11852. }
  11853. }
  11854. }
  11855. /* A relative uri starts with a / character */
  11856. if (uri[0] == '/') {
  11857. /* relative uri */
  11858. return 2;
  11859. }
  11860. /* It could be an absolute uri: */
  11861. /* This function only checks if the uri is valid, not if it is
  11862. * addressing the current server. So civetweb can also be used
  11863. * as a proxy server. */
  11864. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  11865. if (mg_strncasecmp(uri,
  11866. abs_uri_protocols[i].proto,
  11867. abs_uri_protocols[i].proto_len) == 0) {
  11868. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  11869. if (!hostend) {
  11870. return 0;
  11871. }
  11872. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  11873. if (!portbegin) {
  11874. return 3;
  11875. }
  11876. port = strtoul(portbegin + 1, &portend, 10);
  11877. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  11878. return 0;
  11879. }
  11880. return 4;
  11881. }
  11882. }
  11883. return 0;
  11884. }
  11885. /* Return NULL or the relative uri at the current server */
  11886. static const char *
  11887. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  11888. {
  11889. const char *server_domain;
  11890. size_t server_domain_len;
  11891. size_t request_domain_len = 0;
  11892. unsigned long port = 0;
  11893. int i, auth_domain_check_enabled;
  11894. const char *hostbegin = NULL;
  11895. const char *hostend = NULL;
  11896. const char *portbegin;
  11897. char *portend;
  11898. auth_domain_check_enabled =
  11899. !strcmp(conn->ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  11900. if (!auth_domain_check_enabled) {
  11901. return 0;
  11902. }
  11903. server_domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  11904. if (!server_domain) {
  11905. return 0;
  11906. }
  11907. server_domain_len = strlen(server_domain);
  11908. if (!server_domain_len) {
  11909. return 0;
  11910. }
  11911. /* DNS is case insensitive, so use case insensitive string compare here
  11912. */
  11913. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  11914. if (mg_strncasecmp(uri,
  11915. abs_uri_protocols[i].proto,
  11916. abs_uri_protocols[i].proto_len) == 0) {
  11917. hostbegin = uri + abs_uri_protocols[i].proto_len;
  11918. hostend = strchr(hostbegin, '/');
  11919. if (!hostend) {
  11920. return 0;
  11921. }
  11922. portbegin = strchr(hostbegin, ':');
  11923. if ((!portbegin) || (portbegin > hostend)) {
  11924. port = abs_uri_protocols[i].default_port;
  11925. request_domain_len = (size_t)(hostend - hostbegin);
  11926. } else {
  11927. port = strtoul(portbegin + 1, &portend, 10);
  11928. if ((portend != hostend) || (port <= 0)
  11929. || !is_valid_port(port)) {
  11930. return 0;
  11931. }
  11932. request_domain_len = (size_t)(portbegin - hostbegin);
  11933. }
  11934. /* protocol found, port set */
  11935. break;
  11936. }
  11937. }
  11938. if (!port) {
  11939. /* port remains 0 if the protocol is not found */
  11940. return 0;
  11941. }
  11942. /* Check if the request is directed to a different server. */
  11943. /* First check if the port is the same (IPv4 and IPv6). */
  11944. #if defined(USE_IPV6)
  11945. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  11946. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  11947. /* Request is directed to a different port */
  11948. return 0;
  11949. }
  11950. } else
  11951. #endif
  11952. {
  11953. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  11954. /* Request is directed to a different port */
  11955. return 0;
  11956. }
  11957. }
  11958. /* Finally check if the server corresponds to the authentication
  11959. * domain of the server (the server domain).
  11960. * Allow full matches (like http://mydomain.com/path/file.ext), and
  11961. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  11962. * but do not allow substrings (like http://notmydomain.com/path/file.ext
  11963. * or http://mydomain.com.fake/path/file.ext).
  11964. */
  11965. if (auth_domain_check_enabled) {
  11966. if ((request_domain_len == server_domain_len)
  11967. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  11968. /* Request is directed to this server - full name match. */
  11969. } else {
  11970. if (request_domain_len < (server_domain_len + 2)) {
  11971. /* Request is directed to another server: The server name is
  11972. * longer
  11973. * than
  11974. * the request name. Drop this case here to avoid overflows in
  11975. * the
  11976. * following checks. */
  11977. return 0;
  11978. }
  11979. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  11980. /* Request is directed to another server: It could be a
  11981. * substring
  11982. * like notmyserver.com */
  11983. return 0;
  11984. }
  11985. if (0 != memcmp(server_domain,
  11986. hostbegin + request_domain_len - server_domain_len,
  11987. server_domain_len)) {
  11988. /* Request is directed to another server:
  11989. * The server name is different. */
  11990. return 0;
  11991. }
  11992. }
  11993. }
  11994. return hostend;
  11995. }
  11996. static int
  11997. getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  11998. {
  11999. const char *cl;
  12000. if (ebuf_len > 0) {
  12001. ebuf[0] = '\0';
  12002. }
  12003. *err = 0;
  12004. reset_per_request_attributes(conn);
  12005. if (!conn) {
  12006. mg_snprintf(conn,
  12007. NULL, /* No truncation check for ebuf */
  12008. ebuf,
  12009. ebuf_len,
  12010. "%s",
  12011. "Internal error");
  12012. *err = 500;
  12013. return 0;
  12014. }
  12015. /* Set the time the request was received. This value should be used for
  12016. * timeouts. */
  12017. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  12018. conn->request_len =
  12019. read_request(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  12020. /* assert(conn->request_len < 0 || conn->data_len >= conn->request_len);
  12021. */
  12022. if (conn->request_len >= 0 && conn->data_len < conn->request_len) {
  12023. mg_snprintf(conn,
  12024. NULL, /* No truncation check for ebuf */
  12025. ebuf,
  12026. ebuf_len,
  12027. "%s",
  12028. "Invalid request size");
  12029. *err = 500;
  12030. return 0;
  12031. }
  12032. if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
  12033. mg_snprintf(conn,
  12034. NULL, /* No truncation check for ebuf */
  12035. ebuf,
  12036. ebuf_len,
  12037. "%s",
  12038. "Request Too Large");
  12039. *err = 413;
  12040. return 0;
  12041. } else if (conn->request_len <= 0) {
  12042. if (conn->data_len > 0) {
  12043. mg_snprintf(conn,
  12044. NULL, /* No truncation check for ebuf */
  12045. ebuf,
  12046. ebuf_len,
  12047. "%s",
  12048. "Client sent malformed request");
  12049. *err = 400;
  12050. } else {
  12051. /* Server did not recv anything -> just close the connection */
  12052. conn->must_close = 1;
  12053. mg_snprintf(conn,
  12054. NULL, /* No truncation check for ebuf */
  12055. ebuf,
  12056. ebuf_len,
  12057. "%s",
  12058. "Client did not send a request");
  12059. *err = 0;
  12060. }
  12061. return 0;
  12062. } else if (parse_http_message(conn->buf,
  12063. conn->buf_size,
  12064. &conn->request_info) <= 0) {
  12065. mg_snprintf(conn,
  12066. NULL, /* No truncation check for ebuf */
  12067. ebuf,
  12068. ebuf_len,
  12069. "%s",
  12070. "Bad Request");
  12071. *err = 400;
  12072. return 0;
  12073. } else {
  12074. /* Message is a valid request or response */
  12075. if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) {
  12076. /* Request/response has content length set */
  12077. char *endptr = NULL;
  12078. conn->content_len = strtoll(cl, &endptr, 10);
  12079. if (endptr == cl) {
  12080. mg_snprintf(conn,
  12081. NULL, /* No truncation check for ebuf */
  12082. ebuf,
  12083. ebuf_len,
  12084. "%s",
  12085. "Bad Request");
  12086. *err = 411;
  12087. return 0;
  12088. }
  12089. /* Publish the content length back to the request info. */
  12090. conn->request_info.content_length = conn->content_len;
  12091. } else if ((cl = get_header(&conn->request_info, "Transfer-Encoding"))
  12092. != NULL
  12093. && !mg_strcasecmp(cl, "chunked")) {
  12094. conn->is_chunked = 1;
  12095. } else if (!mg_strcasecmp(conn->request_info.request_method, "POST")
  12096. || !mg_strcasecmp(conn->request_info.request_method,
  12097. "PUT")) {
  12098. /* POST or PUT request without content length set */
  12099. conn->content_len = -1;
  12100. } else if (!mg_strncasecmp(conn->request_info.request_method,
  12101. "HTTP/",
  12102. 5)) {
  12103. /* Response without content length set */
  12104. conn->content_len = -1;
  12105. } else {
  12106. /* Other request */
  12107. conn->content_len = 0;
  12108. }
  12109. }
  12110. return 1;
  12111. }
  12112. int
  12113. mg_get_response(struct mg_connection *conn,
  12114. char *ebuf,
  12115. size_t ebuf_len,
  12116. int timeout)
  12117. {
  12118. if (conn) {
  12119. /* Implementation of API function for HTTP clients */
  12120. int err, ret;
  12121. struct mg_context *octx = conn->ctx;
  12122. struct mg_context rctx = *(conn->ctx);
  12123. char txt[32]; /* will not overflow */
  12124. if (timeout >= 0) {
  12125. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  12126. rctx.config[REQUEST_TIMEOUT] = txt;
  12127. /* Not required for non-blocking sockets.
  12128. set_sock_timeout(conn->client.sock, timeout);
  12129. */
  12130. } else {
  12131. rctx.config[REQUEST_TIMEOUT] = NULL;
  12132. }
  12133. conn->ctx = &rctx;
  12134. ret = getreq(conn, ebuf, ebuf_len, &err);
  12135. conn->ctx = octx;
  12136. #if defined(MG_LEGACY_INTERFACE)
  12137. /* TODO: 1) uri is deprecated;
  12138. * 2) here, ri.uri is the http response code */
  12139. conn->request_info.uri = conn->request_info.request_uri;
  12140. #endif
  12141. conn->request_info.local_uri = conn->request_info.request_uri;
  12142. /* TODO (mid): Define proper return values - maybe return length?
  12143. * For the first test use <0 for error and >0 for OK */
  12144. return (ret == 0) ? -1 : +1;
  12145. }
  12146. return -1;
  12147. }
  12148. struct mg_connection *
  12149. mg_download(const char *host,
  12150. int port,
  12151. int use_ssl,
  12152. char *ebuf,
  12153. size_t ebuf_len,
  12154. const char *fmt,
  12155. ...)
  12156. {
  12157. struct mg_connection *conn;
  12158. va_list ap;
  12159. int i;
  12160. int reqerr;
  12161. va_start(ap, fmt);
  12162. ebuf[0] = '\0';
  12163. /* open a connection */
  12164. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  12165. if (conn != NULL) {
  12166. i = mg_vprintf(conn, fmt, ap);
  12167. if (i <= 0) {
  12168. mg_snprintf(conn,
  12169. NULL, /* No truncation check for ebuf */
  12170. ebuf,
  12171. ebuf_len,
  12172. "%s",
  12173. "Error sending request");
  12174. } else {
  12175. getreq(conn, ebuf, ebuf_len, &reqerr);
  12176. #if defined(MG_LEGACY_INTERFACE)
  12177. /* TODO: 1) uri is deprecated;
  12178. * 2) here, ri.uri is the http response code */
  12179. conn->request_info.uri = conn->request_info.request_uri;
  12180. #endif
  12181. conn->request_info.local_uri = conn->request_info.request_uri;
  12182. }
  12183. }
  12184. /* if an error occured, close the connection */
  12185. if (ebuf[0] != '\0' && conn != NULL) {
  12186. mg_close_connection(conn);
  12187. conn = NULL;
  12188. }
  12189. va_end(ap);
  12190. return conn;
  12191. }
  12192. struct websocket_client_thread_data {
  12193. struct mg_connection *conn;
  12194. mg_websocket_data_handler data_handler;
  12195. mg_websocket_close_handler close_handler;
  12196. void *callback_data;
  12197. };
  12198. #if defined(USE_WEBSOCKET)
  12199. #ifdef _WIN32
  12200. static unsigned __stdcall websocket_client_thread(void *data)
  12201. #else
  12202. static void *
  12203. websocket_client_thread(void *data)
  12204. #endif
  12205. {
  12206. struct websocket_client_thread_data *cdata =
  12207. (struct websocket_client_thread_data *)data;
  12208. mg_set_thread_name("ws-clnt");
  12209. if (cdata->conn->ctx) {
  12210. if (cdata->conn->ctx->callbacks.init_thread) {
  12211. /* 3 indicates a websocket client thread */
  12212. /* TODO: check if conn->ctx can be set */
  12213. cdata->conn->ctx->callbacks.init_thread(cdata->conn->ctx, 3);
  12214. }
  12215. }
  12216. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  12217. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  12218. if (cdata->close_handler != NULL) {
  12219. cdata->close_handler(cdata->conn, cdata->callback_data);
  12220. }
  12221. /* The websocket_client context has only this thread. If it runs out,
  12222. set the stop_flag to 2 (= "stopped"). */
  12223. cdata->conn->ctx->stop_flag = 2;
  12224. mg_free((void *)cdata);
  12225. #ifdef _WIN32
  12226. return 0;
  12227. #else
  12228. return NULL;
  12229. #endif
  12230. }
  12231. #endif
  12232. struct mg_connection *
  12233. mg_connect_websocket_client(const char *host,
  12234. int port,
  12235. int use_ssl,
  12236. char *error_buffer,
  12237. size_t error_buffer_size,
  12238. const char *path,
  12239. const char *origin,
  12240. mg_websocket_data_handler data_func,
  12241. mg_websocket_close_handler close_func,
  12242. void *user_data)
  12243. {
  12244. struct mg_connection *conn = NULL;
  12245. #if defined(USE_WEBSOCKET)
  12246. struct mg_context *newctx = NULL;
  12247. struct websocket_client_thread_data *thread_data;
  12248. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  12249. static const char *handshake_req;
  12250. if (origin != NULL) {
  12251. handshake_req = "GET %s HTTP/1.1\r\n"
  12252. "Host: %s\r\n"
  12253. "Upgrade: websocket\r\n"
  12254. "Connection: Upgrade\r\n"
  12255. "Sec-WebSocket-Key: %s\r\n"
  12256. "Sec-WebSocket-Version: 13\r\n"
  12257. "Origin: %s\r\n"
  12258. "\r\n";
  12259. } else {
  12260. handshake_req = "GET %s HTTP/1.1\r\n"
  12261. "Host: %s\r\n"
  12262. "Upgrade: websocket\r\n"
  12263. "Connection: Upgrade\r\n"
  12264. "Sec-WebSocket-Key: %s\r\n"
  12265. "Sec-WebSocket-Version: 13\r\n"
  12266. "\r\n";
  12267. }
  12268. /* Establish the client connection and request upgrade */
  12269. conn = mg_download(host,
  12270. port,
  12271. use_ssl,
  12272. error_buffer,
  12273. error_buffer_size,
  12274. handshake_req,
  12275. path,
  12276. host,
  12277. magic,
  12278. origin);
  12279. /* Connection object will be null if something goes wrong */
  12280. if (conn == NULL || (strcmp(conn->request_info.request_uri, "101") != 0)) {
  12281. if (!*error_buffer) {
  12282. /* if there is a connection, but it did not return 101,
  12283. * error_buffer is not yet set */
  12284. mg_snprintf(conn,
  12285. NULL, /* No truncation check for ebuf */
  12286. error_buffer,
  12287. error_buffer_size,
  12288. "Unexpected server reply");
  12289. }
  12290. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  12291. if (conn != NULL) {
  12292. mg_free(conn);
  12293. conn = NULL;
  12294. }
  12295. return conn;
  12296. }
  12297. /* For client connections, mg_context is fake. Since we need to set a
  12298. * callback function, we need to create a copy and modify it. */
  12299. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  12300. memcpy(newctx, conn->ctx, sizeof(struct mg_context));
  12301. newctx->user_data = user_data;
  12302. newctx->context_type = 2; /* ws/wss client context type */
  12303. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  12304. newctx->worker_threadids =
  12305. (pthread_t *)mg_calloc(newctx->cfg_worker_threads, sizeof(pthread_t));
  12306. conn->ctx = newctx;
  12307. thread_data = (struct websocket_client_thread_data *)
  12308. mg_calloc(sizeof(struct websocket_client_thread_data), 1);
  12309. thread_data->conn = conn;
  12310. thread_data->data_handler = data_func;
  12311. thread_data->close_handler = close_func;
  12312. thread_data->callback_data = user_data;
  12313. /* Start a thread to read the websocket client connection
  12314. * This thread will automatically stop when mg_disconnect is
  12315. * called on the client connection */
  12316. if (mg_start_thread_with_id(websocket_client_thread,
  12317. (void *)thread_data,
  12318. newctx->worker_threadids) != 0) {
  12319. mg_free((void *)thread_data);
  12320. mg_free((void *)newctx->worker_threadids);
  12321. mg_free((void *)newctx);
  12322. mg_free((void *)conn);
  12323. conn = NULL;
  12324. DEBUG_TRACE("%s",
  12325. "Websocket client connect thread could not be started\r\n");
  12326. }
  12327. #else
  12328. /* Appease "unused parameter" warnings */
  12329. (void)host;
  12330. (void)port;
  12331. (void)use_ssl;
  12332. (void)error_buffer;
  12333. (void)error_buffer_size;
  12334. (void)path;
  12335. (void)origin;
  12336. (void)user_data;
  12337. (void)data_func;
  12338. (void)close_func;
  12339. #endif
  12340. return conn;
  12341. }
  12342. static void
  12343. process_new_connection(struct mg_connection *conn)
  12344. {
  12345. if (conn && conn->ctx) {
  12346. struct mg_request_info *ri = &conn->request_info;
  12347. int keep_alive_enabled, keep_alive, discard_len;
  12348. char ebuf[100];
  12349. const char *hostend;
  12350. int reqerr, uri_type;
  12351. #if defined(USE_SERVER_STATS)
  12352. int mcon = mg_atomic_inc(&(conn->ctx->total_connections));
  12353. mg_atomic_inc(&(conn->ctx->active_connections));
  12354. if (mcon > (conn->ctx->max_connections)) {
  12355. /* could use atomic compare exchange, but this
  12356. * seems overkill for statistics data */
  12357. conn->ctx->max_connections = mcon;
  12358. }
  12359. #endif
  12360. keep_alive_enabled =
  12361. !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  12362. /* Important: on new connection, reset the receiving buffer. Credit
  12363. * goes to crule42. */
  12364. conn->data_len = 0;
  12365. conn->handled_requests = 0;
  12366. do {
  12367. DEBUG_TRACE("calling getreq (%i times for this connection)",
  12368. conn->handled_requests + 1);
  12369. if (!getreq(conn, ebuf, sizeof(ebuf), &reqerr)) {
  12370. /* The request sent by the client could not be understood by
  12371. * the server, or it was incomplete or a timeout. Send an
  12372. * error message and close the connection. */
  12373. if (reqerr > 0) {
  12374. /*assert(ebuf[0] != '\0');*/
  12375. mg_send_http_error(conn, reqerr, "%s", ebuf);
  12376. }
  12377. } else if (strcmp(ri->http_version, "1.0")
  12378. && strcmp(ri->http_version, "1.1")) {
  12379. mg_snprintf(conn,
  12380. NULL, /* No truncation check for ebuf */
  12381. ebuf,
  12382. sizeof(ebuf),
  12383. "Bad HTTP version: [%s]",
  12384. ri->http_version);
  12385. mg_send_http_error(conn, 505, "%s", ebuf);
  12386. }
  12387. if (ebuf[0] == '\0') {
  12388. uri_type = get_uri_type(conn->request_info.request_uri);
  12389. switch (uri_type) {
  12390. case 1:
  12391. /* Asterisk */
  12392. conn->request_info.local_uri = NULL;
  12393. break;
  12394. case 2:
  12395. /* relative uri */
  12396. conn->request_info.local_uri =
  12397. conn->request_info.request_uri;
  12398. break;
  12399. case 3:
  12400. case 4:
  12401. /* absolute uri (with/without port) */
  12402. hostend = get_rel_url_at_current_server(
  12403. conn->request_info.request_uri, conn);
  12404. if (hostend) {
  12405. conn->request_info.local_uri = hostend;
  12406. } else {
  12407. conn->request_info.local_uri = NULL;
  12408. }
  12409. break;
  12410. default:
  12411. mg_snprintf(conn,
  12412. NULL, /* No truncation check for ebuf */
  12413. ebuf,
  12414. sizeof(ebuf),
  12415. "Invalid URI");
  12416. mg_send_http_error(conn, 400, "%s", ebuf);
  12417. conn->request_info.local_uri = NULL;
  12418. break;
  12419. }
  12420. #if defined(MG_LEGACY_INTERFACE)
  12421. /* TODO: cleanup uri, local_uri and request_uri */
  12422. conn->request_info.uri = conn->request_info.local_uri;
  12423. #endif
  12424. }
  12425. DEBUG_TRACE("http: %s, error: %s",
  12426. (ri->http_version ? ri->http_version : "none"),
  12427. (ebuf[0] ? ebuf : "none"));
  12428. if (ebuf[0] == '\0') {
  12429. if (conn->request_info.local_uri) {
  12430. /* handle request to local server */
  12431. handle_request(conn);
  12432. DEBUG_TRACE("%s", "handle_request done");
  12433. if (conn->ctx->callbacks.end_request != NULL) {
  12434. conn->ctx->callbacks.end_request(conn,
  12435. conn->status_code);
  12436. DEBUG_TRACE("%s", "end_request callback done");
  12437. }
  12438. log_access(conn);
  12439. } else {
  12440. /* TODO: handle non-local request (PROXY) */
  12441. conn->must_close = 1;
  12442. }
  12443. } else {
  12444. conn->must_close = 1;
  12445. }
  12446. if (ri->remote_user != NULL) {
  12447. mg_free((void *)ri->remote_user);
  12448. /* Important! When having connections with and without auth
  12449. * would cause double free and then crash */
  12450. ri->remote_user = NULL;
  12451. }
  12452. /* NOTE(lsm): order is important here. should_keep_alive() call
  12453. * is
  12454. * using parsed request, which will be invalid after memmove's
  12455. * below.
  12456. * Therefore, memorize should_keep_alive() result now for later
  12457. * use
  12458. * in loop exit condition. */
  12459. keep_alive = (conn->ctx->stop_flag == 0) && keep_alive_enabled
  12460. && (conn->content_len >= 0) && should_keep_alive(conn);
  12461. /* Discard all buffered data for this request */
  12462. discard_len = ((conn->content_len >= 0) && (conn->request_len > 0)
  12463. && ((conn->request_len + conn->content_len)
  12464. < (int64_t)conn->data_len))
  12465. ? (int)(conn->request_len + conn->content_len)
  12466. : conn->data_len;
  12467. /*assert(discard_len >= 0);*/
  12468. if (discard_len < 0) {
  12469. DEBUG_TRACE("internal error: discard_len = %li",
  12470. (long int)discard_len);
  12471. break;
  12472. }
  12473. conn->data_len -= discard_len;
  12474. if (conn->data_len > 0) {
  12475. DEBUG_TRACE("discard_len = %lu", (long unsigned)discard_len);
  12476. memmove(conn->buf,
  12477. conn->buf + discard_len,
  12478. (size_t)conn->data_len);
  12479. }
  12480. /* assert(conn->data_len >= 0); */
  12481. /* assert(conn->data_len <= conn->buf_size); */
  12482. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  12483. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  12484. (long int)conn->data_len,
  12485. (long int)conn->buf_size);
  12486. break;
  12487. }
  12488. conn->handled_requests++;
  12489. } while (keep_alive);
  12490. #if defined(USE_SERVER_STATS)
  12491. mg_atomic_add(&(conn->ctx->total_requests), conn->handled_requests);
  12492. mg_atomic_dec(&(conn->ctx->active_connections));
  12493. #endif
  12494. }
  12495. }
  12496. #if defined(ALTERNATIVE_QUEUE)
  12497. static void
  12498. produce_socket(struct mg_context *ctx, const struct socket *sp)
  12499. {
  12500. unsigned int i;
  12501. for (;;) {
  12502. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  12503. /* find a free worker slot and signal it */
  12504. if (ctx->client_socks[i].in_use == 0) {
  12505. ctx->client_socks[i] = *sp;
  12506. ctx->client_socks[i].in_use = 1;
  12507. event_signal(ctx->client_wait_events[i]);
  12508. return;
  12509. }
  12510. }
  12511. /* queue is full */
  12512. mg_sleep(1);
  12513. }
  12514. }
  12515. static int
  12516. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  12517. {
  12518. DEBUG_TRACE("%s", "going idle");
  12519. ctx->client_socks[thread_index].in_use = 0;
  12520. event_wait(ctx->client_wait_events[thread_index]);
  12521. *sp = ctx->client_socks[thread_index];
  12522. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  12523. return !ctx->stop_flag;
  12524. }
  12525. #else /* ALTERNATIVE_QUEUE */
  12526. /* Worker threads take accepted socket from the queue */
  12527. static int
  12528. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  12529. {
  12530. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  12531. (void)thread_index;
  12532. (void)pthread_mutex_lock(&ctx->thread_mutex);
  12533. DEBUG_TRACE("%s", "going idle");
  12534. /* If the queue is empty, wait. We're idle at this point. */
  12535. while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
  12536. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  12537. }
  12538. /* If we're stopping, sq_head may be equal to sq_tail. */
  12539. if (ctx->sq_head > ctx->sq_tail) {
  12540. /* Copy socket from the queue and increment tail */
  12541. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  12542. ctx->sq_tail++;
  12543. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  12544. /* Wrap pointers if needed */
  12545. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  12546. ctx->sq_tail -= QUEUE_SIZE(ctx);
  12547. ctx->sq_head -= QUEUE_SIZE(ctx);
  12548. }
  12549. }
  12550. (void)pthread_cond_signal(&ctx->sq_empty);
  12551. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  12552. return !ctx->stop_flag;
  12553. #undef QUEUE_SIZE
  12554. }
  12555. /* Master thread adds accepted socket to a queue */
  12556. static void
  12557. produce_socket(struct mg_context *ctx, const struct socket *sp)
  12558. {
  12559. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  12560. if (!ctx) {
  12561. return;
  12562. }
  12563. (void)pthread_mutex_lock(&ctx->thread_mutex);
  12564. /* If the queue is full, wait */
  12565. while (ctx->stop_flag == 0
  12566. && ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx)) {
  12567. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  12568. }
  12569. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  12570. /* Copy socket to the queue and increment head */
  12571. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  12572. ctx->sq_head++;
  12573. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  12574. }
  12575. (void)pthread_cond_signal(&ctx->sq_full);
  12576. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  12577. #undef QUEUE_SIZE
  12578. }
  12579. #endif /* ALTERNATIVE_QUEUE */
  12580. struct worker_thread_args {
  12581. struct mg_context *ctx;
  12582. int index;
  12583. };
  12584. static void *
  12585. worker_thread_run(struct worker_thread_args *thread_args)
  12586. {
  12587. struct mg_context *ctx = thread_args->ctx;
  12588. struct mg_connection *conn;
  12589. struct mg_workerTLS tls;
  12590. #if defined(MG_LEGACY_INTERFACE)
  12591. uint32_t addr;
  12592. #endif
  12593. mg_set_thread_name("worker");
  12594. tls.is_master = 0;
  12595. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  12596. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12597. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  12598. #endif
  12599. /* Initialize thread local storage before calling any callback */
  12600. pthread_setspecific(sTlsKey, &tls);
  12601. if (ctx->callbacks.init_thread) {
  12602. /* call init_thread for a worker thread (type 1) */
  12603. ctx->callbacks.init_thread(ctx, 1);
  12604. }
  12605. /* Connection structure has been pre-allocated */
  12606. if (((int)thread_args->index < 0)
  12607. || ((unsigned)thread_args->index
  12608. >= (unsigned)ctx->cfg_worker_threads)) {
  12609. mg_cry(fc(ctx),
  12610. "Internal error: Invalid worker index %i",
  12611. (int)thread_args->index);
  12612. return NULL;
  12613. }
  12614. conn = ctx->worker_connections + thread_args->index;
  12615. /* Request buffers are not pre-allocated. They are private to the
  12616. * request and do not contain any state information that might be
  12617. * of interest to anyone observing a server status. */
  12618. conn->buf = (char *)mg_malloc(MAX_REQUEST_SIZE);
  12619. if (conn->buf == NULL) {
  12620. mg_cry(fc(ctx),
  12621. "Out of memory: Cannot allocate buffer for worker %i",
  12622. (int)thread_args->index);
  12623. return NULL;
  12624. }
  12625. conn->buf_size = MAX_REQUEST_SIZE;
  12626. conn->ctx = ctx;
  12627. conn->thread_index = thread_args->index;
  12628. conn->request_info.user_data = ctx->user_data;
  12629. /* Allocate a mutex for this connection to allow communication both
  12630. * within the request handler and from elsewhere in the application
  12631. */
  12632. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  12633. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  12634. * signal sq_empty condvar to wake up the master waiting in
  12635. * produce_socket() */
  12636. while (consume_socket(ctx, &conn->client, conn->thread_index)) {
  12637. conn->conn_birth_time = time(NULL);
  12638. /* Fill in IP, port info early so even if SSL setup below fails,
  12639. * error handler would have the corresponding info.
  12640. * Thanks to Johannes Winkelmann for the patch.
  12641. */
  12642. #if defined(USE_IPV6)
  12643. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  12644. conn->request_info.remote_port =
  12645. ntohs(conn->client.rsa.sin6.sin6_port);
  12646. } else
  12647. #endif
  12648. {
  12649. conn->request_info.remote_port =
  12650. ntohs(conn->client.rsa.sin.sin_port);
  12651. }
  12652. sockaddr_to_string(conn->request_info.remote_addr,
  12653. sizeof(conn->request_info.remote_addr),
  12654. &conn->client.rsa);
  12655. DEBUG_TRACE("Start processing connection from %s",
  12656. conn->request_info.remote_addr);
  12657. #if defined(MG_LEGACY_INTERFACE)
  12658. /* This legacy interface only works for the IPv4 case */
  12659. addr = ntohl(conn->client.rsa.sin.sin_addr.s_addr);
  12660. memcpy(&conn->request_info.remote_ip, &addr, 4);
  12661. #endif
  12662. conn->request_info.is_ssl = conn->client.is_ssl;
  12663. if (conn->client.is_ssl) {
  12664. #ifndef NO_SSL
  12665. /* HTTPS connection */
  12666. if (sslize(conn,
  12667. conn->ctx->ssl_ctx,
  12668. SSL_accept,
  12669. &(conn->ctx->stop_flag))) {
  12670. /* Get SSL client certificate information (if set) */
  12671. ssl_get_client_cert_info(conn);
  12672. /* process HTTPS connection */
  12673. process_new_connection(conn);
  12674. /* Free client certificate info */
  12675. if (conn->request_info.client_cert) {
  12676. mg_free((void *)(conn->request_info.client_cert->subject));
  12677. mg_free((void *)(conn->request_info.client_cert->issuer));
  12678. mg_free((void *)(conn->request_info.client_cert->serial));
  12679. mg_free((void *)(conn->request_info.client_cert->finger));
  12680. conn->request_info.client_cert->subject = 0;
  12681. conn->request_info.client_cert->issuer = 0;
  12682. conn->request_info.client_cert->serial = 0;
  12683. conn->request_info.client_cert->finger = 0;
  12684. mg_free(conn->request_info.client_cert);
  12685. conn->request_info.client_cert = 0;
  12686. }
  12687. }
  12688. #endif
  12689. } else {
  12690. /* process HTTP connection */
  12691. process_new_connection(conn);
  12692. }
  12693. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  12694. conn->request_info.remote_addr,
  12695. difftime(time(NULL), conn->conn_birth_time));
  12696. close_connection(conn);
  12697. DEBUG_TRACE("%s", "Connection closed");
  12698. }
  12699. pthread_setspecific(sTlsKey, NULL);
  12700. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12701. CloseHandle(tls.pthread_cond_helper_mutex);
  12702. #endif
  12703. pthread_mutex_destroy(&conn->mutex);
  12704. /* Free the request buffer. */
  12705. conn->buf_size = 0;
  12706. mg_free(conn->buf);
  12707. conn->buf = NULL;
  12708. DEBUG_TRACE("%s", "exiting");
  12709. return NULL;
  12710. }
  12711. /* Threads have different return types on Windows and Unix. */
  12712. #ifdef _WIN32
  12713. static unsigned __stdcall worker_thread(void *thread_func_param)
  12714. {
  12715. struct worker_thread_args *pwta =
  12716. (struct worker_thread_args *)thread_func_param;
  12717. worker_thread_run(pwta);
  12718. mg_free(thread_func_param);
  12719. return 0;
  12720. }
  12721. #else
  12722. static void *
  12723. worker_thread(void *thread_func_param)
  12724. {
  12725. struct worker_thread_args *pwta =
  12726. (struct worker_thread_args *)thread_func_param;
  12727. worker_thread_run(pwta);
  12728. mg_free(thread_func_param);
  12729. return NULL;
  12730. }
  12731. #endif /* _WIN32 */
  12732. static void
  12733. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  12734. {
  12735. struct socket so;
  12736. char src_addr[IP_ADDR_STR_LEN];
  12737. socklen_t len = sizeof(so.rsa);
  12738. int on = 1;
  12739. if (!listener) {
  12740. return;
  12741. }
  12742. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  12743. == INVALID_SOCKET) {
  12744. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  12745. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  12746. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  12747. closesocket(so.sock);
  12748. so.sock = INVALID_SOCKET;
  12749. } else {
  12750. /* Put so socket structure into the queue */
  12751. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  12752. set_close_on_exec(so.sock, fc(ctx));
  12753. so.is_ssl = listener->is_ssl;
  12754. so.ssl_redir = listener->ssl_redir;
  12755. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  12756. mg_cry(fc(ctx),
  12757. "%s: getsockname() failed: %s",
  12758. __func__,
  12759. strerror(ERRNO));
  12760. }
  12761. /* Set TCP keep-alive. This is needed because if HTTP-level
  12762. * keep-alive
  12763. * is enabled, and client resets the connection, server won't get
  12764. * TCP FIN or RST and will keep the connection open forever. With
  12765. * TCP keep-alive, next keep-alive handshake will figure out that
  12766. * the client is down and will close the server end.
  12767. * Thanks to Igor Klopov who suggested the patch. */
  12768. if (setsockopt(so.sock,
  12769. SOL_SOCKET,
  12770. SO_KEEPALIVE,
  12771. (SOCK_OPT_TYPE)&on,
  12772. sizeof(on)) != 0) {
  12773. mg_cry(fc(ctx),
  12774. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  12775. __func__,
  12776. strerror(ERRNO));
  12777. }
  12778. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  12779. * to effectively fill up the underlying IP packet payload and
  12780. * reduce the overhead of sending lots of small buffers. However
  12781. * this hurts the server's throughput (ie. operations per second)
  12782. * when HTTP 1.1 persistent connections are used and the responses
  12783. * are relatively small (eg. less than 1400 bytes).
  12784. */
  12785. if ((ctx != NULL) && (ctx->config[CONFIG_TCP_NODELAY] != NULL)
  12786. && (!strcmp(ctx->config[CONFIG_TCP_NODELAY], "1"))) {
  12787. if (set_tcp_nodelay(so.sock, 1) != 0) {
  12788. mg_cry(fc(ctx),
  12789. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  12790. __func__,
  12791. strerror(ERRNO));
  12792. }
  12793. }
  12794. /* We are using non-blocking sockets. Thus, the
  12795. * set_sock_timeout(so.sock, timeout);
  12796. * call is no longer required. */
  12797. set_blocking_mode(so.sock, 0);
  12798. produce_socket(ctx, &so);
  12799. }
  12800. }
  12801. static void
  12802. master_thread_run(void *thread_func_param)
  12803. {
  12804. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  12805. struct mg_workerTLS tls;
  12806. struct pollfd *pfd;
  12807. unsigned int i;
  12808. unsigned int workerthreadcount;
  12809. if (!ctx) {
  12810. return;
  12811. }
  12812. mg_set_thread_name("master");
  12813. /* Increase priority of the master thread */
  12814. #if defined(_WIN32)
  12815. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  12816. #elif defined(USE_MASTER_THREAD_PRIORITY)
  12817. int min_prio = sched_get_priority_min(SCHED_RR);
  12818. int max_prio = sched_get_priority_max(SCHED_RR);
  12819. if ((min_prio >= 0) && (max_prio >= 0)
  12820. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  12821. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  12822. struct sched_param sched_param = {0};
  12823. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  12824. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  12825. }
  12826. #endif
  12827. /* Initialize thread local storage */
  12828. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12829. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  12830. #endif
  12831. tls.is_master = 1;
  12832. pthread_setspecific(sTlsKey, &tls);
  12833. if (ctx->callbacks.init_thread) {
  12834. /* Callback for the master thread (type 0) */
  12835. ctx->callbacks.init_thread(ctx, 0);
  12836. }
  12837. /* Server starts *now* */
  12838. ctx->start_time = time(NULL);
  12839. /* Start the server */
  12840. pfd = ctx->listening_socket_fds;
  12841. while (ctx->stop_flag == 0) {
  12842. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12843. pfd[i].fd = ctx->listening_sockets[i].sock;
  12844. pfd[i].events = POLLIN;
  12845. }
  12846. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  12847. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12848. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  12849. * successful poll, and POLLIN is defined as
  12850. * (POLLRDNORM | POLLRDBAND)
  12851. * Therefore, we're checking pfd[i].revents & POLLIN, not
  12852. * pfd[i].revents == POLLIN. */
  12853. if (ctx->stop_flag == 0 && (pfd[i].revents & POLLIN)) {
  12854. accept_new_connection(&ctx->listening_sockets[i], ctx);
  12855. }
  12856. }
  12857. }
  12858. }
  12859. /* Here stop_flag is 1 - Initiate shutdown. */
  12860. DEBUG_TRACE("%s", "stopping workers");
  12861. /* Stop signal received: somebody called mg_stop. Quit. */
  12862. close_all_listening_sockets(ctx);
  12863. /* Wakeup workers that are waiting for connections to handle. */
  12864. (void)pthread_mutex_lock(&ctx->thread_mutex);
  12865. #if defined(ALTERNATIVE_QUEUE)
  12866. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  12867. event_signal(ctx->client_wait_events[i]);
  12868. /* Since we know all sockets, we can shutdown the connections. */
  12869. if (ctx->client_socks[i].in_use) {
  12870. shutdown(ctx->client_socks[i].sock, SHUTDOWN_BOTH);
  12871. }
  12872. }
  12873. #else
  12874. pthread_cond_broadcast(&ctx->sq_full);
  12875. #endif
  12876. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  12877. /* Join all worker threads to avoid leaking threads. */
  12878. workerthreadcount = ctx->cfg_worker_threads;
  12879. for (i = 0; i < workerthreadcount; i++) {
  12880. if (ctx->worker_threadids[i] != 0) {
  12881. mg_join_thread(ctx->worker_threadids[i]);
  12882. }
  12883. }
  12884. #if defined(USE_LUA)
  12885. /* Free Lua state of lua background task */
  12886. if (ctx->lua_background_state) {
  12887. lua_close((lua_State *)ctx->lua_background_state);
  12888. ctx->lua_background_state = 0;
  12889. }
  12890. #endif
  12891. #if !defined(NO_SSL)
  12892. if (ctx->ssl_ctx != NULL) {
  12893. uninitialize_ssl();
  12894. }
  12895. #endif
  12896. DEBUG_TRACE("%s", "exiting");
  12897. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12898. CloseHandle(tls.pthread_cond_helper_mutex);
  12899. #endif
  12900. pthread_setspecific(sTlsKey, NULL);
  12901. /* Signal mg_stop() that we're done.
  12902. * WARNING: This must be the very last thing this
  12903. * thread does, as ctx becomes invalid after this line. */
  12904. ctx->stop_flag = 2;
  12905. }
  12906. /* Threads have different return types on Windows and Unix. */
  12907. #ifdef _WIN32
  12908. static unsigned __stdcall master_thread(void *thread_func_param)
  12909. {
  12910. master_thread_run(thread_func_param);
  12911. return 0;
  12912. }
  12913. #else
  12914. static void *
  12915. master_thread(void *thread_func_param)
  12916. {
  12917. master_thread_run(thread_func_param);
  12918. return NULL;
  12919. }
  12920. #endif /* _WIN32 */
  12921. static void
  12922. free_context(struct mg_context *ctx)
  12923. {
  12924. int i;
  12925. struct mg_handler_info *tmp_rh;
  12926. if (ctx == NULL) {
  12927. return;
  12928. }
  12929. if (ctx->callbacks.exit_context) {
  12930. ctx->callbacks.exit_context(ctx);
  12931. }
  12932. /* All threads exited, no sync is needed. Destroy thread mutex and
  12933. * condvars
  12934. */
  12935. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  12936. #if defined(ALTERNATIVE_QUEUE)
  12937. mg_free(ctx->client_socks);
  12938. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  12939. event_destroy(ctx->client_wait_events[i]);
  12940. }
  12941. mg_free(ctx->client_wait_events);
  12942. #else
  12943. (void)pthread_cond_destroy(&ctx->sq_empty);
  12944. (void)pthread_cond_destroy(&ctx->sq_full);
  12945. #endif
  12946. /* Destroy other context global data structures mutex */
  12947. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  12948. #if defined(USE_TIMERS)
  12949. timers_exit(ctx);
  12950. #endif
  12951. /* Deallocate config parameters */
  12952. for (i = 0; i < NUM_OPTIONS; i++) {
  12953. if (ctx->config[i] != NULL) {
  12954. #if defined(_MSC_VER)
  12955. #pragma warning(suppress : 6001)
  12956. #endif
  12957. mg_free(ctx->config[i]);
  12958. }
  12959. }
  12960. /* Deallocate request handlers */
  12961. while (ctx->handlers) {
  12962. tmp_rh = ctx->handlers;
  12963. ctx->handlers = tmp_rh->next;
  12964. mg_free(tmp_rh->uri);
  12965. mg_free(tmp_rh);
  12966. }
  12967. #ifndef NO_SSL
  12968. /* Deallocate SSL context */
  12969. if (ctx->ssl_ctx != NULL) {
  12970. SSL_CTX_free(ctx->ssl_ctx);
  12971. }
  12972. #endif /* !NO_SSL */
  12973. /* Deallocate worker thread ID array */
  12974. if (ctx->worker_threadids != NULL) {
  12975. mg_free(ctx->worker_threadids);
  12976. }
  12977. /* Deallocate worker thread ID array */
  12978. if (ctx->worker_connections != NULL) {
  12979. mg_free(ctx->worker_connections);
  12980. }
  12981. /* Deallocate the tls variable */
  12982. if (mg_atomic_dec(&sTlsInit) == 0) {
  12983. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12984. DeleteCriticalSection(&global_log_file_lock);
  12985. #endif /* _WIN32 && !__SYMBIAN32__ */
  12986. #if !defined(_WIN32)
  12987. pthread_mutexattr_destroy(&pthread_mutex_attr);
  12988. #endif
  12989. pthread_key_delete(sTlsKey);
  12990. #if defined(USE_LUA)
  12991. lua_exit_optional_libraries();
  12992. #endif
  12993. }
  12994. /* deallocate system name string */
  12995. mg_free(ctx->systemName);
  12996. /* Deallocate context itself */
  12997. mg_free(ctx);
  12998. }
  12999. void
  13000. mg_stop(struct mg_context *ctx)
  13001. {
  13002. pthread_t mt;
  13003. if (!ctx) {
  13004. return;
  13005. }
  13006. /* We don't use a lock here. Calling mg_stop with the same ctx from
  13007. * two threads is not allowed. */
  13008. mt = ctx->masterthreadid;
  13009. if (mt == 0) {
  13010. return;
  13011. }
  13012. ctx->masterthreadid = 0;
  13013. /* Set stop flag, so all threads know they have to exit. */
  13014. ctx->stop_flag = 1;
  13015. /* Wait until everything has stopped. */
  13016. while (ctx->stop_flag != 2) {
  13017. (void)mg_sleep(10);
  13018. }
  13019. mg_join_thread(mt);
  13020. free_context(ctx);
  13021. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13022. (void)WSACleanup();
  13023. #endif /* _WIN32 && !__SYMBIAN32__ */
  13024. }
  13025. static void
  13026. get_system_name(char **sysName)
  13027. {
  13028. #if defined(_WIN32)
  13029. #if !defined(__SYMBIAN32__)
  13030. #if defined(_WIN32_WCE)
  13031. *sysName = mg_strdup("WinCE");
  13032. #else
  13033. char name[128];
  13034. DWORD dwVersion = 0;
  13035. DWORD dwMajorVersion = 0;
  13036. DWORD dwMinorVersion = 0;
  13037. DWORD dwBuild = 0;
  13038. BOOL wowRet, isWoW = FALSE;
  13039. #ifdef _MSC_VER
  13040. #pragma warning(push)
  13041. /* GetVersion was declared deprecated */
  13042. #pragma warning(disable : 4996)
  13043. #endif
  13044. dwVersion = GetVersion();
  13045. #ifdef _MSC_VER
  13046. #pragma warning(pop)
  13047. #endif
  13048. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  13049. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  13050. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  13051. (void)dwBuild;
  13052. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  13053. sprintf(name,
  13054. "Windows %u.%u%s",
  13055. (unsigned)dwMajorVersion,
  13056. (unsigned)dwMinorVersion,
  13057. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  13058. *sysName = mg_strdup(name);
  13059. #endif
  13060. #else
  13061. *sysName = mg_strdup("Symbian");
  13062. #endif
  13063. #else
  13064. struct utsname name;
  13065. memset(&name, 0, sizeof(name));
  13066. uname(&name);
  13067. *sysName = mg_strdup(name.sysname);
  13068. #endif
  13069. }
  13070. struct mg_context *
  13071. mg_start(const struct mg_callbacks *callbacks,
  13072. void *user_data,
  13073. const char **options)
  13074. {
  13075. struct mg_context *ctx;
  13076. const char *name, *value, *default_value;
  13077. int idx, ok, workerthreadcount;
  13078. unsigned int i;
  13079. void (*exit_callback)(const struct mg_context *ctx) = 0;
  13080. struct mg_workerTLS tls;
  13081. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13082. WSADATA data;
  13083. WSAStartup(MAKEWORD(2, 2), &data);
  13084. #endif /* _WIN32 && !__SYMBIAN32__ */
  13085. /* Allocate context and initialize reasonable general case defaults. */
  13086. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  13087. return NULL;
  13088. }
  13089. /* Random number generator will initialize at the first call */
  13090. ctx->auth_nonce_mask =
  13091. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  13092. if (mg_atomic_inc(&sTlsInit) == 1) {
  13093. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13094. InitializeCriticalSection(&global_log_file_lock);
  13095. #endif /* _WIN32 && !__SYMBIAN32__ */
  13096. #if !defined(_WIN32)
  13097. pthread_mutexattr_init(&pthread_mutex_attr);
  13098. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  13099. #endif
  13100. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  13101. /* Fatal error - abort start. However, this situation should
  13102. * never occur in practice. */
  13103. mg_atomic_dec(&sTlsInit);
  13104. mg_cry(fc(ctx), "Cannot initialize thread local storage");
  13105. mg_free(ctx);
  13106. return NULL;
  13107. }
  13108. #if defined(USE_LUA)
  13109. lua_init_optional_libraries();
  13110. #endif
  13111. } else {
  13112. /* TODO (low): instead of sleeping, check if sTlsKey is already
  13113. * initialized. */
  13114. mg_sleep(1);
  13115. }
  13116. tls.is_master = -1;
  13117. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  13118. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13119. tls.pthread_cond_helper_mutex = NULL;
  13120. #endif
  13121. pthread_setspecific(sTlsKey, &tls);
  13122. /* Dummy use this function - in some #ifdef combinations it's used,
  13123. * while it's not used in others, but GCC seems to stupid to understand
  13124. * #pragma GCC diagnostic ignored "-Wunused-function"
  13125. * in cases the function is unused, and it also complains on
  13126. * __attribute((unused))__ in cases it is used.
  13127. * So dummy use it, to have our peace. */
  13128. (void)mg_current_thread_id();
  13129. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr);
  13130. #if !defined(ALTERNATIVE_QUEUE)
  13131. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  13132. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  13133. #endif
  13134. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr);
  13135. if (!ok) {
  13136. /* Fatal error - abort start. However, this situation should never
  13137. * occur in practice. */
  13138. mg_cry(fc(ctx), "Cannot initialize thread synchronization objects");
  13139. mg_free(ctx);
  13140. pthread_setspecific(sTlsKey, NULL);
  13141. return NULL;
  13142. }
  13143. if (callbacks) {
  13144. ctx->callbacks = *callbacks;
  13145. exit_callback = callbacks->exit_context;
  13146. ctx->callbacks.exit_context = 0;
  13147. }
  13148. ctx->user_data = user_data;
  13149. ctx->handlers = NULL;
  13150. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  13151. ctx->shared_lua_websockets = 0;
  13152. #endif
  13153. while (options && (name = *options++) != NULL) {
  13154. if ((idx = get_option_index(name)) == -1) {
  13155. mg_cry(fc(ctx), "Invalid option: %s", name);
  13156. free_context(ctx);
  13157. pthread_setspecific(sTlsKey, NULL);
  13158. return NULL;
  13159. } else if ((value = *options++) == NULL) {
  13160. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  13161. free_context(ctx);
  13162. pthread_setspecific(sTlsKey, NULL);
  13163. return NULL;
  13164. }
  13165. if (ctx->config[idx] != NULL) {
  13166. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  13167. mg_free(ctx->config[idx]);
  13168. }
  13169. ctx->config[idx] = mg_strdup(value);
  13170. DEBUG_TRACE("[%s] -> [%s]", name, value);
  13171. }
  13172. /* Set default value if needed */
  13173. for (i = 0; config_options[i].name != NULL; i++) {
  13174. default_value = config_options[i].default_value;
  13175. if (ctx->config[i] == NULL && default_value != NULL) {
  13176. ctx->config[i] = mg_strdup(default_value);
  13177. }
  13178. }
  13179. workerthreadcount = atoi(ctx->config[NUM_THREADS]);
  13180. if (workerthreadcount > MAX_WORKER_THREADS) {
  13181. mg_cry(fc(ctx), "Too many worker threads");
  13182. free_context(ctx);
  13183. pthread_setspecific(sTlsKey, NULL);
  13184. return NULL;
  13185. }
  13186. if (workerthreadcount <= 0) {
  13187. mg_cry(fc(ctx), "Invalid number of worker threads");
  13188. free_context(ctx);
  13189. pthread_setspecific(sTlsKey, NULL);
  13190. return NULL;
  13191. }
  13192. #if defined(NO_FILES)
  13193. if (ctx->config[DOCUMENT_ROOT] != NULL) {
  13194. mg_cry(fc(ctx), "%s", "Document root must not be set");
  13195. free_context(ctx);
  13196. pthread_setspecific(sTlsKey, NULL);
  13197. return NULL;
  13198. }
  13199. #endif
  13200. get_system_name(&ctx->systemName);
  13201. #if defined(USE_LUA)
  13202. /* If a Lua background script has been configured, start it. */
  13203. if (ctx->config[LUA_BACKGROUND_SCRIPT] != NULL) {
  13204. char ebuf[256];
  13205. void *state = (void *)mg_prepare_lua_context_script(
  13206. ctx->config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  13207. if (!state) {
  13208. mg_cry(fc(ctx), "lua_background_script error: %s", ebuf);
  13209. free_context(ctx);
  13210. pthread_setspecific(sTlsKey, NULL);
  13211. return NULL;
  13212. }
  13213. ctx->lua_background_state = state;
  13214. } else {
  13215. ctx->lua_background_state = 0;
  13216. }
  13217. #endif
  13218. /* NOTE(lsm): order is important here. SSL certificates must
  13219. * be initialized before listening ports. UID must be set last. */
  13220. if (!set_gpass_option(ctx) ||
  13221. #if !defined(NO_SSL)
  13222. !set_ssl_option(ctx) ||
  13223. #endif
  13224. !set_ports_option(ctx) ||
  13225. #if !defined(_WIN32)
  13226. !set_uid_option(ctx) ||
  13227. #endif
  13228. !set_acl_option(ctx)) {
  13229. free_context(ctx);
  13230. pthread_setspecific(sTlsKey, NULL);
  13231. return NULL;
  13232. }
  13233. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  13234. /* Ignore SIGPIPE signal, so if browser cancels the request, it
  13235. * won't kill the whole process. */
  13236. (void)signal(SIGPIPE, SIG_IGN);
  13237. #endif /* !_WIN32 && !__SYMBIAN32__ */
  13238. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  13239. ctx->worker_threadids =
  13240. (pthread_t *)mg_calloc(ctx->cfg_worker_threads, sizeof(pthread_t));
  13241. if (ctx->worker_threadids == NULL) {
  13242. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  13243. free_context(ctx);
  13244. pthread_setspecific(sTlsKey, NULL);
  13245. return NULL;
  13246. }
  13247. ctx->worker_connections =
  13248. (struct mg_connection *)mg_calloc(ctx->cfg_worker_threads,
  13249. sizeof(struct mg_connection));
  13250. if (ctx->worker_connections == NULL) {
  13251. mg_cry(fc(ctx), "Not enough memory for worker thread connection array");
  13252. free_context(ctx);
  13253. pthread_setspecific(sTlsKey, NULL);
  13254. return NULL;
  13255. }
  13256. #if defined(ALTERNATIVE_QUEUE)
  13257. ctx->client_wait_events =
  13258. mg_calloc(sizeof(ctx->client_wait_events[0]), ctx->cfg_worker_threads);
  13259. if (ctx->client_wait_events == NULL) {
  13260. mg_cry(fc(ctx), "Not enough memory for worker event array");
  13261. mg_free(ctx->worker_threadids);
  13262. free_context(ctx);
  13263. pthread_setspecific(sTlsKey, NULL);
  13264. return NULL;
  13265. }
  13266. ctx->client_socks =
  13267. mg_calloc(sizeof(ctx->client_socks[0]), ctx->cfg_worker_threads);
  13268. if (ctx->client_wait_events == NULL) {
  13269. mg_cry(fc(ctx), "Not enough memory for worker socket array");
  13270. mg_free(ctx->client_socks);
  13271. mg_free(ctx->worker_threadids);
  13272. free_context(ctx);
  13273. pthread_setspecific(sTlsKey, NULL);
  13274. return NULL;
  13275. }
  13276. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  13277. ctx->client_wait_events[i] = event_create();
  13278. if (ctx->client_wait_events[i] == 0) {
  13279. mg_cry(fc(ctx), "Error creating worker event %i", i);
  13280. while (i > 0) {
  13281. i--;
  13282. event_destroy(ctx->client_wait_events[i]);
  13283. }
  13284. mg_free(ctx->client_socks);
  13285. mg_free(ctx->worker_threadids);
  13286. free_context(ctx);
  13287. pthread_setspecific(sTlsKey, NULL);
  13288. return NULL;
  13289. }
  13290. }
  13291. #endif
  13292. #if defined(USE_TIMERS)
  13293. if (timers_init(ctx) != 0) {
  13294. mg_cry(fc(ctx), "Error creating timers");
  13295. free_context(ctx);
  13296. pthread_setspecific(sTlsKey, NULL);
  13297. return NULL;
  13298. }
  13299. #endif
  13300. /* Context has been created - init user libraries */
  13301. if (ctx->callbacks.init_context) {
  13302. ctx->callbacks.init_context(ctx);
  13303. }
  13304. ctx->callbacks.exit_context = exit_callback;
  13305. ctx->context_type = 1; /* server context */
  13306. /* Start master (listening) thread */
  13307. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  13308. /* Start worker threads */
  13309. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  13310. struct worker_thread_args *wta = (struct worker_thread_args *)mg_malloc(
  13311. sizeof(struct worker_thread_args));
  13312. if (wta) {
  13313. wta->ctx = ctx;
  13314. wta->index = (int)i;
  13315. }
  13316. if ((wta == NULL)
  13317. || (mg_start_thread_with_id(worker_thread,
  13318. wta,
  13319. &ctx->worker_threadids[i]) != 0)) {
  13320. /* thread was not created */
  13321. if (wta != NULL) {
  13322. mg_free(wta);
  13323. }
  13324. if (i > 0) {
  13325. mg_cry(fc(ctx),
  13326. "Cannot start worker thread %i: error %ld",
  13327. i + 1,
  13328. (long)ERRNO);
  13329. } else {
  13330. mg_cry(fc(ctx),
  13331. "Cannot create threads: error %ld",
  13332. (long)ERRNO);
  13333. free_context(ctx);
  13334. pthread_setspecific(sTlsKey, NULL);
  13335. return NULL;
  13336. }
  13337. break;
  13338. }
  13339. }
  13340. pthread_setspecific(sTlsKey, NULL);
  13341. return ctx;
  13342. }
  13343. /* Feature check API function */
  13344. unsigned
  13345. mg_check_feature(unsigned feature)
  13346. {
  13347. static const unsigned feature_set = 0
  13348. /* Set bits for available features according to API documentation.
  13349. * This bit mask is created at compile time, according to the active
  13350. * preprocessor defines. It is a single const value at runtime. */
  13351. #if !defined(NO_FILES)
  13352. | 0x0001u
  13353. #endif
  13354. #if !defined(NO_SSL)
  13355. | 0x0002u
  13356. #endif
  13357. #if !defined(NO_CGI)
  13358. | 0x0004u
  13359. #endif
  13360. #if defined(USE_IPV6)
  13361. | 0x0008u
  13362. #endif
  13363. #if defined(USE_WEBSOCKET)
  13364. | 0x0010u
  13365. #endif
  13366. #if defined(USE_LUA)
  13367. | 0x0020u
  13368. #endif
  13369. #if defined(USE_DUKTAPE)
  13370. | 0x0040u
  13371. #endif
  13372. #if !defined(NO_CACHING)
  13373. | 0x0080u
  13374. #endif
  13375. /* Set some extra bits not defined in the API documentation.
  13376. * These bits may change without further notice. */
  13377. #if defined(MG_LEGACY_INTERFACE)
  13378. | 0x8000u
  13379. #endif
  13380. #if defined(MEMORY_DEBUGGING)
  13381. | 0x0100u
  13382. #endif
  13383. #if defined(USE_TIMERS)
  13384. | 0x0200u
  13385. #endif
  13386. #if !defined(NO_NONCE_CHECK)
  13387. | 0x0400u
  13388. #endif
  13389. #if !defined(NO_POPEN)
  13390. | 0x0800u
  13391. #endif
  13392. ;
  13393. return (feature & feature_set);
  13394. }
  13395. /* Get system information. It can be printed or stored by the caller.
  13396. * Return the size of available information. */
  13397. static int
  13398. mg_get_system_info_impl(char *buffer, int buflen)
  13399. {
  13400. char block[256];
  13401. int system_info_length = 0;
  13402. #if defined(_WIN32)
  13403. const char *eol = "\r\n";
  13404. #else
  13405. const char *eol = "\n";
  13406. #endif
  13407. if (buffer == NULL) {
  13408. /* Avoid some warning (although, if some dillweed supplies
  13409. * buffer==NULL combined with buflen>0, he deserves a crash).
  13410. */
  13411. buflen = 0;
  13412. }
  13413. /* Server version */
  13414. {
  13415. const char *version = mg_version();
  13416. mg_snprintf(NULL,
  13417. NULL,
  13418. block,
  13419. sizeof(block),
  13420. "Server Version: %s%s",
  13421. version,
  13422. eol);
  13423. system_info_length += (int)strlen(block);
  13424. if (system_info_length < buflen) {
  13425. strcat(buffer, block);
  13426. }
  13427. }
  13428. /* System info */
  13429. {
  13430. #if defined(_WIN32)
  13431. #if !defined(__SYMBIAN32__)
  13432. DWORD dwVersion = 0;
  13433. DWORD dwMajorVersion = 0;
  13434. DWORD dwMinorVersion = 0;
  13435. SYSTEM_INFO si;
  13436. GetSystemInfo(&si);
  13437. #ifdef _MSC_VER
  13438. #pragma warning(push)
  13439. /* GetVersion was declared deprecated */
  13440. #pragma warning(disable : 4996)
  13441. #endif
  13442. dwVersion = GetVersion();
  13443. #ifdef _MSC_VER
  13444. #pragma warning(pop)
  13445. #endif
  13446. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  13447. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  13448. mg_snprintf(NULL,
  13449. NULL,
  13450. block,
  13451. sizeof(block),
  13452. "Windows %u.%u%s",
  13453. (unsigned)dwMajorVersion,
  13454. (unsigned)dwMinorVersion,
  13455. eol);
  13456. system_info_length += (int)strlen(block);
  13457. if (system_info_length < buflen) {
  13458. strcat(buffer, block);
  13459. }
  13460. mg_snprintf(NULL,
  13461. NULL,
  13462. block,
  13463. sizeof(block),
  13464. "CPU: type %u, cores %u, mask %x%s",
  13465. (unsigned)si.wProcessorArchitecture,
  13466. (unsigned)si.dwNumberOfProcessors,
  13467. (unsigned)si.dwActiveProcessorMask,
  13468. eol);
  13469. system_info_length += (int)strlen(block);
  13470. if (system_info_length < buflen) {
  13471. strcat(buffer, block);
  13472. }
  13473. #else
  13474. mg_snprintf(NULL, NULL, block, sizeof(block), "%s - Symbian%s", eol);
  13475. system_info_length += (int)strlen(block);
  13476. if (system_info_length < buflen) {
  13477. strcat(buffer, block);
  13478. }
  13479. #endif
  13480. #else
  13481. struct utsname name;
  13482. memset(&name, 0, sizeof(name));
  13483. uname(&name);
  13484. mg_snprintf(NULL,
  13485. NULL,
  13486. block,
  13487. sizeof(block),
  13488. "%s %s (%s) - %s%s",
  13489. name.sysname,
  13490. name.version,
  13491. name.release,
  13492. name.machine,
  13493. eol);
  13494. system_info_length += (int)strlen(block);
  13495. if (system_info_length < buflen) {
  13496. strcat(buffer, block);
  13497. }
  13498. #endif
  13499. }
  13500. /* Features */
  13501. {
  13502. mg_snprintf(NULL,
  13503. NULL,
  13504. block,
  13505. sizeof(block),
  13506. "Features: %X%s%s%s%s%s%s%s%s%s%s",
  13507. mg_check_feature(0xFFFFFFFFu),
  13508. eol,
  13509. mg_check_feature(1) ? " Files" : "",
  13510. mg_check_feature(2) ? " HTTPS" : "",
  13511. mg_check_feature(4) ? " CGI" : "",
  13512. mg_check_feature(8) ? " IPv6" : "",
  13513. mg_check_feature(16) ? " WebSockets" : "",
  13514. mg_check_feature(32) ? " Lua" : "",
  13515. mg_check_feature(64) ? " JavaScript" : "",
  13516. mg_check_feature(128) ? " Cache" : "",
  13517. eol);
  13518. system_info_length += (int)strlen(block);
  13519. if (system_info_length < buflen) {
  13520. strcat(buffer, block);
  13521. }
  13522. #ifdef USE_LUA
  13523. mg_snprintf(NULL,
  13524. NULL,
  13525. block,
  13526. sizeof(block),
  13527. "Lua Version: %u (%s)%s",
  13528. (unsigned)LUA_VERSION_NUM,
  13529. LUA_RELEASE,
  13530. eol);
  13531. system_info_length += (int)strlen(block);
  13532. if (system_info_length < buflen) {
  13533. strcat(buffer, block);
  13534. }
  13535. #endif
  13536. #if defined(USE_DUKTAPE)
  13537. mg_snprintf(NULL,
  13538. NULL,
  13539. block,
  13540. sizeof(block),
  13541. "JavaScript: Duktape %u.%u.%u%s",
  13542. (unsigned)DUK_VERSION / 10000,
  13543. ((unsigned)DUK_VERSION / 100) % 100,
  13544. (unsigned)DUK_VERSION % 100,
  13545. eol);
  13546. system_info_length += (int)strlen(block);
  13547. if (system_info_length < buflen) {
  13548. strcat(buffer, block);
  13549. }
  13550. #endif
  13551. }
  13552. /* Build date */
  13553. {
  13554. mg_snprintf(
  13555. NULL, NULL, block, sizeof(block), "Build: %s%s", __DATE__, eol);
  13556. system_info_length += (int)strlen(block);
  13557. if (system_info_length < buflen) {
  13558. strcat(buffer, block);
  13559. }
  13560. }
  13561. /* Compiler information */
  13562. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  13563. {
  13564. #if defined(_MSC_VER)
  13565. mg_snprintf(NULL,
  13566. NULL,
  13567. block,
  13568. sizeof(block),
  13569. "MSC: %u (%u)%s",
  13570. (unsigned)_MSC_VER,
  13571. (unsigned)_MSC_FULL_VER,
  13572. eol);
  13573. system_info_length += (int)strlen(block);
  13574. if (system_info_length < buflen) {
  13575. strcat(buffer, block);
  13576. }
  13577. #elif defined(__MINGW64__)
  13578. mg_snprintf(NULL,
  13579. NULL,
  13580. block,
  13581. sizeof(block),
  13582. "MinGW64: %u.%u%s",
  13583. (unsigned)__MINGW64_VERSION_MAJOR,
  13584. (unsigned)__MINGW64_VERSION_MINOR,
  13585. eol);
  13586. system_info_length += (int)strlen(block);
  13587. if (system_info_length < buflen) {
  13588. strcat(buffer, block);
  13589. }
  13590. mg_snprintf(NULL,
  13591. NULL,
  13592. block,
  13593. sizeof(block),
  13594. "MinGW32: %u.%u%s",
  13595. (unsigned)__MINGW32_MAJOR_VERSION,
  13596. (unsigned)__MINGW32_MINOR_VERSION,
  13597. eol);
  13598. system_info_length += (int)strlen(block);
  13599. if (system_info_length < buflen) {
  13600. strcat(buffer, block);
  13601. }
  13602. #elif defined(__MINGW32__)
  13603. mg_snprintf(NULL,
  13604. NULL,
  13605. block,
  13606. sizeof(block),
  13607. "MinGW32: %u.%u%s",
  13608. (unsigned)__MINGW32_MAJOR_VERSION,
  13609. (unsigned)__MINGW32_MINOR_VERSION,
  13610. eol);
  13611. system_info_length += (int)strlen(block);
  13612. if (system_info_length < buflen) {
  13613. strcat(buffer, block);
  13614. }
  13615. #elif defined(__clang__)
  13616. mg_snprintf(NULL,
  13617. NULL,
  13618. block,
  13619. sizeof(block),
  13620. "clang: %u.%u.%u (%s)%s",
  13621. __clang_major__,
  13622. __clang_minor__,
  13623. __clang_patchlevel__,
  13624. __clang_version__,
  13625. eol);
  13626. system_info_length += (int)strlen(block);
  13627. if (system_info_length < buflen) {
  13628. strcat(buffer, block);
  13629. }
  13630. #elif defined(__GNUC__)
  13631. mg_snprintf(NULL,
  13632. NULL,
  13633. block,
  13634. sizeof(block),
  13635. "gcc: %u.%u.%u%s",
  13636. (unsigned)__GNUC__,
  13637. (unsigned)__GNUC_MINOR__,
  13638. (unsigned)__GNUC_PATCHLEVEL__,
  13639. eol);
  13640. system_info_length += (int)strlen(block);
  13641. if (system_info_length < buflen) {
  13642. strcat(buffer, block);
  13643. }
  13644. #elif defined(__INTEL_COMPILER)
  13645. mg_snprintf(NULL,
  13646. NULL,
  13647. block,
  13648. sizeof(block),
  13649. "Intel C/C++: %u%s",
  13650. (unsigned)__INTEL_COMPILER,
  13651. eol);
  13652. system_info_length += (int)strlen(block);
  13653. if (system_info_length < buflen) {
  13654. strcat(buffer, block);
  13655. }
  13656. #elif defined(__BORLANDC__)
  13657. mg_snprintf(NULL,
  13658. NULL,
  13659. block,
  13660. sizeof(block),
  13661. "Borland C: 0x%x%s",
  13662. (unsigned)__BORLANDC__,
  13663. eol);
  13664. system_info_length += (int)strlen(block);
  13665. if (system_info_length < buflen) {
  13666. strcat(buffer, block);
  13667. }
  13668. #elif defined(__SUNPRO_C)
  13669. mg_snprintf(NULL,
  13670. NULL,
  13671. block,
  13672. sizeof(block),
  13673. "Solaris: 0x%x%s",
  13674. (unsigned)__SUNPRO_C,
  13675. eol);
  13676. system_info_length += (int)strlen(block);
  13677. if (system_info_length < buflen) {
  13678. strcat(buffer, block);
  13679. }
  13680. #else
  13681. mg_snprintf(NULL, NULL, block, sizeof(block), "Other compiler%s", eol);
  13682. system_info_length += (int)strlen(block);
  13683. if (system_info_length < buflen) {
  13684. strcat(buffer, block);
  13685. }
  13686. #endif
  13687. }
  13688. /* Determine 32/64 bit data mode.
  13689. * see https://en.wikipedia.org/wiki/64-bit_computing */
  13690. {
  13691. mg_snprintf(NULL,
  13692. NULL,
  13693. block,
  13694. sizeof(block),
  13695. "Data model: int:%u/%u/%u/%u, float:%u/%u/%u, char:%u/%u, "
  13696. "ptr:%u, size:%u, time:%u%s",
  13697. (unsigned)sizeof(short),
  13698. (unsigned)sizeof(int),
  13699. (unsigned)sizeof(long),
  13700. (unsigned)sizeof(long long),
  13701. (unsigned)sizeof(float),
  13702. (unsigned)sizeof(double),
  13703. (unsigned)sizeof(long double),
  13704. (unsigned)sizeof(char),
  13705. (unsigned)sizeof(wchar_t),
  13706. (unsigned)sizeof(void *),
  13707. (unsigned)sizeof(size_t),
  13708. (unsigned)sizeof(time_t),
  13709. eol);
  13710. system_info_length += (int)strlen(block);
  13711. if (system_info_length < buflen) {
  13712. strcat(buffer, block);
  13713. }
  13714. }
  13715. return system_info_length;
  13716. }
  13717. /* Get system information. It can be printed or stored by the caller.
  13718. * Return the size of available information. */
  13719. int
  13720. mg_get_system_info(char *buffer, int buflen)
  13721. {
  13722. if ((buffer == NULL) || (buflen < 1)) {
  13723. return mg_get_system_info_impl(NULL, 0);
  13724. } else {
  13725. /* Reset buffer, so we can always use strcat. */
  13726. buffer[0] = 0;
  13727. return mg_get_system_info_impl(buffer, buflen);
  13728. }
  13729. }
  13730. /* mg_init_library counter */
  13731. static int mg_init_library_called = 0;
  13732. #if !defined(NO_SSL)
  13733. static int mg_ssl_initialized = 0;
  13734. #endif
  13735. /* Initialize this library. This function does not need to be thread safe. */
  13736. unsigned
  13737. mg_init_library(unsigned features)
  13738. {
  13739. #if !defined(NO_SSL)
  13740. char ebuf[128];
  13741. #endif
  13742. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  13743. unsigned features_inited = features_to_init;
  13744. #if !defined(NO_SSL)
  13745. if (features_to_init & 2) {
  13746. if (!mg_ssl_initialized) {
  13747. if (initialize_ssl(ebuf, sizeof(ebuf))) {
  13748. mg_ssl_initialized = 1;
  13749. } else {
  13750. (void)ebuf;
  13751. /* TODO: print error */
  13752. features_inited &= ~(2u);
  13753. }
  13754. } else {
  13755. /* ssl already initialized */
  13756. }
  13757. }
  13758. #endif
  13759. /* Start Windows. */
  13760. if (mg_init_library_called <= 0) {
  13761. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13762. WSADATA data;
  13763. WSAStartup(MAKEWORD(2, 2), &data);
  13764. #endif /* _WIN32 && !__SYMBIAN32__ */
  13765. mg_init_library_called = 1;
  13766. } else {
  13767. mg_init_library_called++;
  13768. }
  13769. return features_inited;
  13770. }
  13771. /* Un-initialize this library. */
  13772. unsigned
  13773. mg_exit_library(void)
  13774. {
  13775. if (mg_init_library_called <= 0) {
  13776. return 0;
  13777. }
  13778. mg_init_library_called--;
  13779. if (mg_init_library_called == 0) {
  13780. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13781. (void)WSACleanup();
  13782. #endif /* _WIN32 && !__SYMBIAN32__ */
  13783. #if !defined(NO_SSL)
  13784. if (mg_ssl_initialized) {
  13785. uninitialize_ssl();
  13786. mg_ssl_initialized = 0;
  13787. }
  13788. #endif
  13789. }
  13790. return 1;
  13791. }
  13792. /* End of civetweb.c */