civetweb.c 413 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678
  1. /* Copyright (c) 2013-2017 the Civetweb developers
  2. * Copyright (c) 2004-2013 Sergey Lyubka
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. * THE SOFTWARE.
  21. */
  22. #if defined(_WIN32)
  23. #if !defined(_CRT_SECURE_NO_WARNINGS)
  24. #define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */
  25. #endif
  26. #ifndef _WIN32_WINNT /* defined for tdm-gcc so we can use getnameinfo */
  27. #define _WIN32_WINNT 0x0501
  28. #endif
  29. #else
  30. #if defined(__GNUC__) && !defined(_GNU_SOURCE)
  31. #define _GNU_SOURCE /* for setgroups() */
  32. #endif
  33. #if defined(__linux__) && !defined(_XOPEN_SOURCE)
  34. #define _XOPEN_SOURCE 600 /* For flockfile() on Linux */
  35. #endif
  36. #ifndef _LARGEFILE_SOURCE
  37. #define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
  38. #endif
  39. #ifndef _FILE_OFFSET_BITS
  40. #define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
  41. #endif
  42. #ifndef __STDC_FORMAT_MACROS
  43. #define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
  44. #endif
  45. #ifndef __STDC_LIMIT_MACROS
  46. #define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
  47. #endif
  48. #ifdef __sun
  49. #define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */
  50. #define __inline inline /* not recognized on older compiler versions */
  51. #endif
  52. #endif
  53. #if defined(USE_LUA)
  54. #define USE_TIMERS
  55. #endif
  56. #if defined(_MSC_VER)
  57. /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
  58. #pragma warning(disable : 4306)
  59. /* conditional expression is constant: introduced by FD_SET(..) */
  60. #pragma warning(disable : 4127)
  61. /* non-constant aggregate initializer: issued due to missing C99 support */
  62. #pragma warning(disable : 4204)
  63. /* padding added after data member */
  64. #pragma warning(disable : 4820)
  65. /* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
  66. #pragma warning(disable : 4668)
  67. /* no function prototype given: converting '()' to '(void)' */
  68. #pragma warning(disable : 4255)
  69. /* function has been selected for automatic inline expansion */
  70. #pragma warning(disable : 4711)
  71. #endif
  72. /* This code uses static_assert to check some conditions.
  73. * Unfortunately some compilers still do not support it, so we have a
  74. * replacement function here. */
  75. #if defined(_MSC_VER) && (_MSC_VER >= 1600)
  76. #define mg_static_assert static_assert
  77. #elif defined(__cplusplus) && (__cplusplus >= 201103L)
  78. #define mg_static_assert static_assert
  79. #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)
  80. #define mg_static_assert _Static_assert
  81. #else
  82. char static_assert_replacement[1];
  83. #define mg_static_assert(cond, txt) \
  84. extern char static_assert_replacement[(cond) ? 1 : -1]
  85. #endif
  86. mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
  87. "int data type size check");
  88. mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
  89. "pointer data type size check");
  90. mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
  91. /* DTL -- including winsock2.h works better if lean and mean */
  92. #ifndef WIN32_LEAN_AND_MEAN
  93. #define WIN32_LEAN_AND_MEAN
  94. #endif
  95. #if defined(__SYMBIAN32__)
  96. #define NO_SSL /* SSL is not supported */
  97. #define NO_CGI /* CGI is not supported */
  98. #define PATH_MAX FILENAME_MAX
  99. #endif /* __SYMBIAN32__ */
  100. #ifndef CIVETWEB_HEADER_INCLUDED
  101. /* Include the header file here, so the CivetWeb interface is defined for the
  102. * entire implementation, including the following forward definitions. */
  103. #include "civetweb.h"
  104. #endif
  105. #ifndef IGNORE_UNUSED_RESULT
  106. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  107. #endif
  108. #ifndef _WIN32_WCE /* Some ANSI #includes are not available on Windows CE */
  109. #include <sys/types.h>
  110. #include <sys/stat.h>
  111. #include <errno.h>
  112. #include <signal.h>
  113. #include <fcntl.h>
  114. #endif /* !_WIN32_WCE */
  115. #ifdef __clang__
  116. /* When using -Weverything, clang does not accept it's own headers
  117. * in a release build configuration. Disable what is too much in
  118. * -Weverything. */
  119. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  120. #endif
  121. #ifdef __MACH__ /* Apple OSX section */
  122. #ifdef __clang__
  123. /* Avoid warnings for Xopen 7.00 and higher */
  124. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  125. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  126. #endif
  127. #define CLOCK_MONOTONIC (1)
  128. #define CLOCK_REALTIME (2)
  129. #include <sys/errno.h>
  130. #include <sys/time.h>
  131. #include <mach/clock.h>
  132. #include <mach/mach.h>
  133. #include <mach/mach_time.h>
  134. #include <assert.h>
  135. /* clock_gettime is not implemented on OSX prior to 10.12 */
  136. static int
  137. _civet_clock_gettime(int clk_id, struct timespec *t)
  138. {
  139. memset(t, 0, sizeof(*t));
  140. if (clk_id == CLOCK_REALTIME) {
  141. struct timeval now;
  142. int rv = gettimeofday(&now, NULL);
  143. if (rv) {
  144. return rv;
  145. }
  146. t->tv_sec = now.tv_sec;
  147. t->tv_nsec = now.tv_usec * 1000;
  148. return 0;
  149. } else if (clk_id == CLOCK_MONOTONIC) {
  150. static uint64_t clock_start_time = 0;
  151. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  152. uint64_t now = mach_absolute_time();
  153. if (clock_start_time == 0) {
  154. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  155. #if defined(DEBUG)
  156. assert(mach_status == KERN_SUCCESS);
  157. #else
  158. /* appease "unused variable" warning for release builds */
  159. (void)mach_status;
  160. #endif
  161. clock_start_time = now;
  162. }
  163. now = (uint64_t)((double)(now - clock_start_time)
  164. * (double)timebase_ifo.numer
  165. / (double)timebase_ifo.denom);
  166. t->tv_sec = now / 1000000000;
  167. t->tv_nsec = now % 1000000000;
  168. return 0;
  169. }
  170. return -1; /* EINVAL - Clock ID is unknown */
  171. }
  172. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  173. #ifdef __CLOCK_AVAILABILITY
  174. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  175. * declared but it may be NULL at runtime. So we need to check before using
  176. * it. */
  177. static int
  178. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  179. {
  180. if (clock_gettime) {
  181. return clock_gettime(clk_id, t);
  182. }
  183. return _civet_clock_gettime(clk_id, t);
  184. }
  185. #define clock_gettime _civet_safe_clock_gettime
  186. #else
  187. #define clock_gettime _civet_clock_gettime
  188. #endif
  189. #endif
  190. #include <time.h>
  191. #include <stdlib.h>
  192. #include <stdarg.h>
  193. #include <assert.h>
  194. #include <string.h>
  195. #include <ctype.h>
  196. #include <limits.h>
  197. #include <stddef.h>
  198. #include <stdio.h>
  199. #include <stdint.h>
  200. #ifndef INT64_MAX
  201. #define INT64_MAX (9223372036854775807)
  202. #endif
  203. #ifndef MAX_WORKER_THREADS
  204. #define MAX_WORKER_THREADS (1024 * 64)
  205. #endif
  206. #ifndef SOCKET_TIMEOUT_QUANTUM /* in ms */
  207. #define SOCKET_TIMEOUT_QUANTUM (2000)
  208. #endif
  209. #define SHUTDOWN_RD (0)
  210. #define SHUTDOWN_WR (1)
  211. #define SHUTDOWN_BOTH (2)
  212. mg_static_assert(MAX_WORKER_THREADS >= 1,
  213. "worker threads must be a positive number");
  214. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  215. "size_t data type size check");
  216. #if defined(_WIN32) \
  217. && !defined(__SYMBIAN32__) /* WINDOWS / UNIX include block */
  218. #include <windows.h>
  219. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  220. #include <ws2tcpip.h>
  221. typedef const char *SOCK_OPT_TYPE;
  222. #if !defined(PATH_MAX)
  223. #define PATH_MAX (MAX_PATH)
  224. #endif
  225. #if !defined(PATH_MAX)
  226. #define PATH_MAX (4096)
  227. #endif
  228. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  229. #ifndef _IN_PORT_T
  230. #ifndef in_port_t
  231. #define in_port_t u_short
  232. #endif
  233. #endif
  234. #ifndef _WIN32_WCE
  235. #include <process.h>
  236. #include <direct.h>
  237. #include <io.h>
  238. #else /* _WIN32_WCE */
  239. #define NO_CGI /* WinCE has no pipes */
  240. #define NO_POPEN /* WinCE has no popen */
  241. typedef long off_t;
  242. #define errno ((int)(GetLastError()))
  243. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  244. #endif /* _WIN32_WCE */
  245. #define MAKEUQUAD(lo, hi) \
  246. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  247. #define RATE_DIFF (10000000) /* 100 nsecs */
  248. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  249. #define SYS2UNIX_TIME(lo, hi) \
  250. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  251. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  252. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  253. * Also use _strtoui64 on modern M$ compilers */
  254. #if defined(_MSC_VER)
  255. #if (_MSC_VER < 1300)
  256. #define STRX(x) #x
  257. #define STR(x) STRX(x)
  258. #define __func__ __FILE__ ":" STR(__LINE__)
  259. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  260. #define strtoll(x, y, z) (_atoi64(x))
  261. #else
  262. #define __func__ __FUNCTION__
  263. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  264. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  265. #endif
  266. #endif /* _MSC_VER */
  267. #define ERRNO ((int)(GetLastError()))
  268. #define NO_SOCKLEN_T
  269. #if defined(_WIN64) || defined(__MINGW64__)
  270. #define SSL_LIB "ssleay64.dll"
  271. #define CRYPTO_LIB "libeay64.dll"
  272. #else
  273. #define SSL_LIB "ssleay32.dll"
  274. #define CRYPTO_LIB "libeay32.dll"
  275. #endif
  276. #define O_NONBLOCK (0)
  277. #ifndef W_OK
  278. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  279. #endif
  280. #if !defined(EWOULDBLOCK)
  281. #define EWOULDBLOCK WSAEWOULDBLOCK
  282. #endif /* !EWOULDBLOCK */
  283. #define _POSIX_
  284. #define INT64_FMT "I64d"
  285. #define UINT64_FMT "I64u"
  286. #define WINCDECL __cdecl
  287. #define vsnprintf_impl _vsnprintf
  288. #define access _access
  289. #define mg_sleep(x) (Sleep(x))
  290. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  291. #ifndef popen
  292. #define popen(x, y) (_popen(x, y))
  293. #endif
  294. #ifndef pclose
  295. #define pclose(x) (_pclose(x))
  296. #endif
  297. #define close(x) (_close(x))
  298. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  299. #define RTLD_LAZY (0)
  300. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  301. #define fdopen(x, y) (_fdopen((x), (y)))
  302. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  303. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  304. #define flockfile(x) (EnterCriticalSection(&global_log_file_lock))
  305. #define funlockfile(x) (LeaveCriticalSection(&global_log_file_lock))
  306. #define sleep(x) (Sleep((x)*1000))
  307. #define rmdir(x) (_rmdir(x))
  308. #define timegm(x) (_mkgmtime(x))
  309. #if !defined(fileno)
  310. #define fileno(x) (_fileno(x))
  311. #endif /* !fileno MINGW #defines fileno */
  312. typedef HANDLE pthread_mutex_t;
  313. typedef DWORD pthread_key_t;
  314. typedef HANDLE pthread_t;
  315. typedef struct {
  316. CRITICAL_SECTION threadIdSec;
  317. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  318. } pthread_cond_t;
  319. #ifndef __clockid_t_defined
  320. typedef DWORD clockid_t;
  321. #endif
  322. #ifndef CLOCK_MONOTONIC
  323. #define CLOCK_MONOTONIC (1)
  324. #endif
  325. #ifndef CLOCK_REALTIME
  326. #define CLOCK_REALTIME (2)
  327. #endif
  328. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  329. #define _TIMESPEC_DEFINED
  330. #endif
  331. #ifndef _TIMESPEC_DEFINED
  332. struct timespec {
  333. time_t tv_sec; /* seconds */
  334. long tv_nsec; /* nanoseconds */
  335. };
  336. #endif
  337. #if !defined(WIN_PTHREADS_TIME_H)
  338. #define MUST_IMPLEMENT_CLOCK_GETTIME
  339. #endif
  340. #ifdef MUST_IMPLEMENT_CLOCK_GETTIME
  341. #define clock_gettime mg_clock_gettime
  342. static int
  343. clock_gettime(clockid_t clk_id, struct timespec *tp)
  344. {
  345. FILETIME ft;
  346. ULARGE_INTEGER li;
  347. BOOL ok = FALSE;
  348. double d;
  349. static double perfcnt_per_sec = 0.0;
  350. if (tp) {
  351. memset(tp, 0, sizeof(*tp));
  352. if (clk_id == CLOCK_REALTIME) {
  353. GetSystemTimeAsFileTime(&ft);
  354. li.LowPart = ft.dwLowDateTime;
  355. li.HighPart = ft.dwHighDateTime;
  356. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  357. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  358. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  359. ok = TRUE;
  360. } else if (clk_id == CLOCK_MONOTONIC) {
  361. if (perfcnt_per_sec == 0.0) {
  362. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  363. perfcnt_per_sec = 1.0 / li.QuadPart;
  364. }
  365. if (perfcnt_per_sec != 0.0) {
  366. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  367. d = li.QuadPart * perfcnt_per_sec;
  368. tp->tv_sec = (time_t)d;
  369. d -= tp->tv_sec;
  370. tp->tv_nsec = (long)(d * 1.0E9);
  371. ok = TRUE;
  372. }
  373. }
  374. }
  375. return ok ? 0 : -1;
  376. }
  377. #endif
  378. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  379. static int pthread_mutex_lock(pthread_mutex_t *);
  380. static int pthread_mutex_unlock(pthread_mutex_t *);
  381. static void path_to_unicode(const struct mg_connection *conn,
  382. const char *path,
  383. wchar_t *wbuf,
  384. size_t wbuf_len);
  385. /* All file operations need to be rewritten to solve #246. */
  386. #include "file_ops.inl"
  387. struct mg_file;
  388. static const char *
  389. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p);
  390. /* POSIX dirent interface */
  391. struct dirent {
  392. char d_name[PATH_MAX];
  393. };
  394. typedef struct DIR {
  395. HANDLE handle;
  396. WIN32_FIND_DATAW info;
  397. struct dirent result;
  398. } DIR;
  399. #if defined(_WIN32) && !defined(POLLIN)
  400. #ifndef HAVE_POLL
  401. struct pollfd {
  402. SOCKET fd;
  403. short events;
  404. short revents;
  405. };
  406. #define POLLIN (0x0300)
  407. #endif
  408. #endif
  409. /* Mark required libraries */
  410. #if defined(_MSC_VER)
  411. #pragma comment(lib, "Ws2_32.lib")
  412. #endif
  413. #else /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  414. WINDOWS / UNIX include block */
  415. #include <sys/wait.h>
  416. #include <sys/socket.h>
  417. #include <sys/poll.h>
  418. #include <netinet/in.h>
  419. #include <arpa/inet.h>
  420. #include <sys/time.h>
  421. #include <sys/utsname.h>
  422. #include <stdint.h>
  423. #include <inttypes.h>
  424. #include <netdb.h>
  425. #include <netinet/tcp.h>
  426. typedef const void *SOCK_OPT_TYPE;
  427. #if defined(ANDROID)
  428. typedef unsigned short int in_port_t;
  429. #endif
  430. #include <pwd.h>
  431. #include <unistd.h>
  432. #include <grp.h>
  433. #include <dirent.h>
  434. #define vsnprintf_impl vsnprintf
  435. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  436. #include <dlfcn.h>
  437. #endif
  438. #include <pthread.h>
  439. #if defined(__MACH__)
  440. #define SSL_LIB "libssl.dylib"
  441. #define CRYPTO_LIB "libcrypto.dylib"
  442. #else
  443. #if !defined(SSL_LIB)
  444. #define SSL_LIB "libssl.so"
  445. #endif
  446. #if !defined(CRYPTO_LIB)
  447. #define CRYPTO_LIB "libcrypto.so"
  448. #endif
  449. #endif
  450. #ifndef O_BINARY
  451. #define O_BINARY (0)
  452. #endif /* O_BINARY */
  453. #define closesocket(a) (close(a))
  454. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  455. #define mg_remove(conn, x) (remove(x))
  456. #define mg_sleep(x) (usleep((x)*1000))
  457. #define mg_opendir(conn, x) (opendir(x))
  458. #define mg_closedir(x) (closedir(x))
  459. #define mg_readdir(x) (readdir(x))
  460. #define ERRNO (errno)
  461. #define INVALID_SOCKET (-1)
  462. #define INT64_FMT PRId64
  463. #define UINT64_FMT PRIu64
  464. typedef int SOCKET;
  465. #define WINCDECL
  466. #if defined(__hpux)
  467. /* HPUX 11 does not have monotonic, fall back to realtime */
  468. #ifndef CLOCK_MONOTONIC
  469. #define CLOCK_MONOTONIC CLOCK_REALTIME
  470. #endif
  471. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  472. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  473. * the prototypes use int* rather than socklen_t* which matches the
  474. * actual library expectation. When called with the wrong size arg
  475. * accept() returns a zero client inet addr and check_acl() always
  476. * fails. Since socklen_t is widely used below, just force replace
  477. * their typedef with int. - DTL
  478. */
  479. #define socklen_t int
  480. #endif /* hpux */
  481. #endif /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  482. WINDOWS / UNIX include block */
  483. /* va_copy should always be a macro, C99 and C++11 - DTL */
  484. #ifndef va_copy
  485. #define va_copy(x, y) ((x) = (y))
  486. #endif
  487. #ifdef _WIN32
  488. /* Create substitutes for POSIX functions in Win32. */
  489. #if defined(__MINGW32__)
  490. /* Show no warning in case system functions are not used. */
  491. #pragma GCC diagnostic push
  492. #pragma GCC diagnostic ignored "-Wunused-function"
  493. #endif
  494. static CRITICAL_SECTION global_log_file_lock;
  495. static DWORD
  496. pthread_self(void)
  497. {
  498. return GetCurrentThreadId();
  499. }
  500. static int
  501. pthread_key_create(
  502. pthread_key_t *key,
  503. void (*_ignored)(void *) /* destructor not supported for Windows */
  504. )
  505. {
  506. (void)_ignored;
  507. if ((key != 0)) {
  508. *key = TlsAlloc();
  509. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  510. }
  511. return -2;
  512. }
  513. static int
  514. pthread_key_delete(pthread_key_t key)
  515. {
  516. return TlsFree(key) ? 0 : 1;
  517. }
  518. static int
  519. pthread_setspecific(pthread_key_t key, void *value)
  520. {
  521. return TlsSetValue(key, value) ? 0 : 1;
  522. }
  523. static void *
  524. pthread_getspecific(pthread_key_t key)
  525. {
  526. return TlsGetValue(key);
  527. }
  528. #if defined(__MINGW32__)
  529. /* Enable unused function warning again */
  530. #pragma GCC diagnostic pop
  531. #endif
  532. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  533. #else
  534. static pthread_mutexattr_t pthread_mutex_attr;
  535. #endif /* _WIN32 */
  536. #define PASSWORDS_FILE_NAME ".htpasswd"
  537. #define CGI_ENVIRONMENT_SIZE (4096)
  538. #define MAX_CGI_ENVIR_VARS (256)
  539. #define MG_BUF_LEN (8192)
  540. #ifndef MAX_REQUEST_SIZE
  541. #define MAX_REQUEST_SIZE (16384)
  542. #endif
  543. mg_static_assert(MAX_REQUEST_SIZE >= 256,
  544. "request size length must be a positive number");
  545. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  546. #if defined(_WIN32_WCE)
  547. /* Create substitutes for POSIX functions in Win32. */
  548. #if defined(__MINGW32__)
  549. /* Show no warning in case system functions are not used. */
  550. #pragma GCC diagnostic push
  551. #pragma GCC diagnostic ignored "-Wunused-function"
  552. #endif
  553. static time_t
  554. time(time_t *ptime)
  555. {
  556. time_t t;
  557. SYSTEMTIME st;
  558. FILETIME ft;
  559. GetSystemTime(&st);
  560. SystemTimeToFileTime(&st, &ft);
  561. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  562. if (ptime != NULL) {
  563. *ptime = t;
  564. }
  565. return t;
  566. }
  567. static struct tm *
  568. localtime_s(const time_t *ptime, struct tm *ptm)
  569. {
  570. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  571. FILETIME ft, lft;
  572. SYSTEMTIME st;
  573. TIME_ZONE_INFORMATION tzinfo;
  574. if (ptm == NULL) {
  575. return NULL;
  576. }
  577. *(int64_t *)&ft = t;
  578. FileTimeToLocalFileTime(&ft, &lft);
  579. FileTimeToSystemTime(&lft, &st);
  580. ptm->tm_year = st.wYear - 1900;
  581. ptm->tm_mon = st.wMonth - 1;
  582. ptm->tm_wday = st.wDayOfWeek;
  583. ptm->tm_mday = st.wDay;
  584. ptm->tm_hour = st.wHour;
  585. ptm->tm_min = st.wMinute;
  586. ptm->tm_sec = st.wSecond;
  587. ptm->tm_yday = 0; /* hope nobody uses this */
  588. ptm->tm_isdst =
  589. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  590. return ptm;
  591. }
  592. static struct tm *
  593. gmtime_s(const time_t *ptime, struct tm *ptm)
  594. {
  595. /* FIXME(lsm): fix this. */
  596. return localtime_s(ptime, ptm);
  597. }
  598. static int mg_atomic_inc(volatile int *addr);
  599. static struct tm tm_array[MAX_WORKER_THREADS];
  600. static int tm_index = 0;
  601. static struct tm *
  602. localtime(const time_t *ptime)
  603. {
  604. int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0]));
  605. return localtime_s(ptime, tm_array + i);
  606. }
  607. static struct tm *
  608. gmtime(const time_t *ptime)
  609. {
  610. int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  611. return gmtime_s(ptime, tm_array + i);
  612. }
  613. static size_t
  614. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  615. {
  616. /* TODO: (void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  617. * for WinCE"); */
  618. return 0;
  619. }
  620. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  621. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  622. #define remove(f) mg_remove(NULL, f)
  623. static int
  624. rename(const char *a, const char *b)
  625. {
  626. wchar_t wa[PATH_MAX];
  627. wchar_t wb[PATH_MAX];
  628. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  629. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  630. return MoveFileW(wa, wb) ? 0 : -1;
  631. }
  632. struct stat {
  633. int64_t st_size;
  634. time_t st_mtime;
  635. };
  636. static int
  637. stat(const char *name, struct stat *st)
  638. {
  639. wchar_t wbuf[PATH_MAX];
  640. WIN32_FILE_ATTRIBUTE_DATA attr;
  641. time_t creation_time, write_time;
  642. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  643. memset(&attr, 0, sizeof(attr));
  644. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  645. st->st_size =
  646. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  647. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  648. attr.ftLastWriteTime.dwHighDateTime);
  649. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  650. attr.ftCreationTime.dwHighDateTime);
  651. if (creation_time > write_time) {
  652. st->st_mtime = creation_time;
  653. } else {
  654. st->st_mtime = write_time;
  655. }
  656. return 0;
  657. }
  658. #define access(x, a) 1 /* not required anyway */
  659. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  660. /* Values from errno.h in Windows SDK (Visual Studio). */
  661. #define EEXIST 17
  662. #define EACCES 13
  663. #define ENOENT 2
  664. #if defined(__MINGW32__)
  665. /* Enable unused function warning again */
  666. #pragma GCC diagnostic pop
  667. #endif
  668. #endif /* defined(_WIN32_WCE) */
  669. static int
  670. mg_atomic_inc(volatile int *addr)
  671. {
  672. int ret;
  673. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  674. /* Depending on the SDK, this function uses either
  675. * (volatile unsigned int *) or (volatile LONG *),
  676. * so whatever you use, the other SDK is likely to raise a warning. */
  677. ret = InterlockedIncrement((volatile long *)addr);
  678. #elif defined(__GNUC__) \
  679. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  680. ret = __sync_add_and_fetch(addr, 1);
  681. #else
  682. ret = (++(*addr));
  683. #endif
  684. return ret;
  685. }
  686. static int
  687. mg_atomic_dec(volatile int *addr)
  688. {
  689. int ret;
  690. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  691. /* Depending on the SDK, this function uses either
  692. * (volatile unsigned int *) or (volatile LONG *),
  693. * so whatever you use, the other SDK is likely to raise a warning. */
  694. ret = InterlockedDecrement((volatile long *)addr);
  695. #elif defined(__GNUC__) \
  696. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  697. ret = __sync_sub_and_fetch(addr, 1);
  698. #else
  699. ret = (--(*addr));
  700. #endif
  701. return ret;
  702. }
  703. #if defined(MEMORY_DEBUGGING)
  704. static unsigned long mg_memory_debug_blockCount = 0;
  705. static unsigned long mg_memory_debug_totalMemUsed = 0;
  706. static void *
  707. mg_malloc_ex(size_t size, const char *file, unsigned line)
  708. {
  709. void *data = malloc(size + sizeof(size_t));
  710. void *memory = 0;
  711. char mallocStr[256];
  712. if (data) {
  713. *(size_t *)data = size;
  714. mg_memory_debug_totalMemUsed += size;
  715. mg_memory_debug_blockCount++;
  716. memory = (void *)(((char *)data) + sizeof(size_t));
  717. }
  718. sprintf(mallocStr,
  719. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  720. memory,
  721. (unsigned long)size,
  722. mg_memory_debug_totalMemUsed,
  723. mg_memory_debug_blockCount,
  724. file,
  725. line);
  726. #if defined(_WIN32)
  727. OutputDebugStringA(mallocStr);
  728. #else
  729. DEBUG_TRACE("%s", mallocStr);
  730. #endif
  731. return memory;
  732. }
  733. static void *
  734. mg_calloc_ex(size_t count, size_t size, const char *file, unsigned line)
  735. {
  736. void *data = mg_malloc_ex(size * count, file, line);
  737. if (data) {
  738. memset(data, 0, size * count);
  739. }
  740. return data;
  741. }
  742. static void
  743. mg_free_ex(void *memory, const char *file, unsigned line)
  744. {
  745. char mallocStr[256];
  746. void *data = (void *)(((char *)memory) - sizeof(size_t));
  747. size_t size;
  748. if (memory) {
  749. size = *(size_t *)data;
  750. mg_memory_debug_totalMemUsed -= size;
  751. mg_memory_debug_blockCount--;
  752. sprintf(mallocStr,
  753. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  754. memory,
  755. (unsigned long)size,
  756. mg_memory_debug_totalMemUsed,
  757. mg_memory_debug_blockCount,
  758. file,
  759. line);
  760. #if defined(_WIN32)
  761. OutputDebugStringA(mallocStr);
  762. #else
  763. DEBUG_TRACE("%s", mallocStr);
  764. #endif
  765. free(data);
  766. }
  767. }
  768. static void *
  769. mg_realloc_ex(void *memory, size_t newsize, const char *file, unsigned line)
  770. {
  771. char mallocStr[256];
  772. void *data;
  773. void *_realloc;
  774. size_t oldsize;
  775. if (newsize) {
  776. if (memory) {
  777. data = (void *)(((char *)memory) - sizeof(size_t));
  778. oldsize = *(size_t *)data;
  779. _realloc = realloc(data, newsize + sizeof(size_t));
  780. if (_realloc) {
  781. data = _realloc;
  782. mg_memory_debug_totalMemUsed -= oldsize;
  783. sprintf(mallocStr,
  784. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  785. memory,
  786. (unsigned long)oldsize,
  787. mg_memory_debug_totalMemUsed,
  788. mg_memory_debug_blockCount,
  789. file,
  790. line);
  791. #if defined(_WIN32)
  792. OutputDebugStringA(mallocStr);
  793. #else
  794. DEBUG_TRACE("%s", mallocStr);
  795. #endif
  796. mg_memory_debug_totalMemUsed += newsize;
  797. sprintf(mallocStr,
  798. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  799. memory,
  800. (unsigned long)newsize,
  801. mg_memory_debug_totalMemUsed,
  802. mg_memory_debug_blockCount,
  803. file,
  804. line);
  805. #if defined(_WIN32)
  806. OutputDebugStringA(mallocStr);
  807. #else
  808. DEBUG_TRACE("%s", mallocStr);
  809. #endif
  810. *(size_t *)data = newsize;
  811. data = (void *)(((char *)data) + sizeof(size_t));
  812. } else {
  813. #if defined(_WIN32)
  814. OutputDebugStringA("MEM: realloc failed\n");
  815. #else
  816. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  817. #endif
  818. return _realloc;
  819. }
  820. } else {
  821. data = mg_malloc_ex(newsize, file, line);
  822. }
  823. } else {
  824. data = 0;
  825. mg_free_ex(memory, file, line);
  826. }
  827. return data;
  828. }
  829. #define mg_malloc(a) mg_malloc_ex(a, __FILE__, __LINE__)
  830. #define mg_calloc(a, b) mg_calloc_ex(a, b, __FILE__, __LINE__)
  831. #define mg_realloc(a, b) mg_realloc_ex(a, b, __FILE__, __LINE__)
  832. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  833. #else
  834. static __inline void *
  835. mg_malloc(size_t a)
  836. {
  837. return malloc(a);
  838. }
  839. static __inline void *
  840. mg_calloc(size_t a, size_t b)
  841. {
  842. return calloc(a, b);
  843. }
  844. static __inline void *
  845. mg_realloc(void *a, size_t b)
  846. {
  847. return realloc(a, b);
  848. }
  849. static __inline void
  850. mg_free(void *a)
  851. {
  852. free(a);
  853. }
  854. #endif
  855. static void mg_vsnprintf(const struct mg_connection *conn,
  856. int *truncated,
  857. char *buf,
  858. size_t buflen,
  859. const char *fmt,
  860. va_list ap);
  861. static void mg_snprintf(const struct mg_connection *conn,
  862. int *truncated,
  863. char *buf,
  864. size_t buflen,
  865. PRINTF_FORMAT_STRING(const char *fmt),
  866. ...) PRINTF_ARGS(5, 6);
  867. /* This following lines are just meant as a reminder to use the mg-functions
  868. * for memory management */
  869. #ifdef malloc
  870. #undef malloc
  871. #endif
  872. #ifdef calloc
  873. #undef calloc
  874. #endif
  875. #ifdef realloc
  876. #undef realloc
  877. #endif
  878. #ifdef free
  879. #undef free
  880. #endif
  881. #ifdef snprintf
  882. #undef snprintf
  883. #endif
  884. #ifdef vsnprintf
  885. #undef vsnprintf
  886. #endif
  887. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  888. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  889. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  890. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  891. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  892. #ifdef _WIN32 /* vsnprintf must not be used in any system, * \ \ \ \
  893. * but this define only works well for Windows. */
  894. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  895. #endif
  896. static pthread_key_t sTlsKey; /* Thread local storage index */
  897. static int sTlsInit = 0;
  898. static int thread_idx_max = 0;
  899. struct mg_workerTLS {
  900. int is_master;
  901. unsigned long thread_idx;
  902. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  903. HANDLE pthread_cond_helper_mutex;
  904. struct mg_workerTLS *next_waiting_thread;
  905. #endif
  906. };
  907. #if defined(__GNUC__) || defined(__MINGW32__)
  908. /* Show no warning in case system functions are not used. */
  909. #pragma GCC diagnostic push
  910. #pragma GCC diagnostic ignored "-Wunused-function"
  911. #endif
  912. #if defined(__clang__)
  913. /* Show no warning in case system functions are not used. */
  914. #pragma clang diagnostic push
  915. #pragma clang diagnostic ignored "-Wunused-function"
  916. #endif
  917. /* Get a unique thread ID as unsigned long, independent from the data type
  918. * of thread IDs defined by the operating system API.
  919. * If two calls to mg_current_thread_id return the same value, they calls
  920. * are done from the same thread. If they return different values, they are
  921. * done from different threads. (Provided this function is used in the same
  922. * process context and threads are not repeatedly created and deleted, but
  923. * CivetWeb does not do that).
  924. * This function must match the signature required for SSL id callbacks:
  925. * CRYPTO_set_id_callback
  926. */
  927. static unsigned long
  928. mg_current_thread_id(void)
  929. {
  930. #ifdef _WIN32
  931. return GetCurrentThreadId();
  932. #else
  933. #ifdef __clang__
  934. #pragma clang diagnostic push
  935. #pragma clang diagnostic ignored "-Wunreachable-code"
  936. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  937. * or not, so one of the two conditions will be unreachable by construction.
  938. * Unfortunately the C standard does not define a way to check this at
  939. * compile time, since the #if preprocessor conditions can not use the sizeof
  940. * operator as an argument. */
  941. #endif
  942. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  943. /* This is the problematic case for CRYPTO_set_id_callback:
  944. * The OS pthread_t can not be cast to unsigned long. */
  945. struct mg_workerTLS *tls =
  946. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  947. if (tls == NULL) {
  948. /* SSL called from an unknown thread: Create some thread index.
  949. */
  950. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  951. tls->is_master = -2; /* -2 means "3rd party thread" */
  952. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  953. pthread_setspecific(sTlsKey, tls);
  954. }
  955. return tls->thread_idx;
  956. } else {
  957. /* pthread_t may be any data type, so a simple cast to unsigned long
  958. * can rise a warning/error, depending on the platform.
  959. * Here memcpy is used as an anything-to-anything cast. */
  960. unsigned long ret = 0;
  961. pthread_t t = pthread_self();
  962. memcpy(&ret, &t, sizeof(pthread_t));
  963. return ret;
  964. }
  965. #ifdef __clang__
  966. #pragma clang diagnostic pop
  967. #endif
  968. #endif
  969. }
  970. static uint64_t
  971. mg_get_current_time_ns()
  972. {
  973. struct timespec tsnow;
  974. clock_gettime(CLOCK_REALTIME, &tsnow);
  975. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  976. }
  977. #if defined(__GNUC__)
  978. /* Show no warning in case system functions are not used. */
  979. #pragma GCC diagnostic pop
  980. #endif
  981. #if defined(__clang__)
  982. /* Show no warning in case system functions are not used. */
  983. #pragma clang diagnostic pop
  984. #endif
  985. #if !defined(DEBUG_TRACE)
  986. #if defined(DEBUG)
  987. static void DEBUG_TRACE_FUNC(const char *func,
  988. unsigned line,
  989. PRINTF_FORMAT_STRING(const char *fmt),
  990. ...) PRINTF_ARGS(3, 4);
  991. static void
  992. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  993. {
  994. va_list args;
  995. uint64_t nsnow;
  996. static uint64_t nslast;
  997. struct timespec tsnow;
  998. /* Get some operating system independent thread id */
  999. unsigned long thread_id = mg_current_thread_id();
  1000. clock_gettime(CLOCK_REALTIME, &tsnow);
  1001. nsnow = ((uint64_t)tsnow.tv_sec) * ((uint64_t)1000000000)
  1002. + ((uint64_t)tsnow.tv_nsec);
  1003. if (!nslast) {
  1004. nslast = nsnow;
  1005. }
  1006. flockfile(stdout);
  1007. printf("*** %lu.%09lu %12" INT64_FMT " %lu %s:%u: ",
  1008. (unsigned long)tsnow.tv_sec,
  1009. (unsigned long)tsnow.tv_nsec,
  1010. nsnow - nslast,
  1011. thread_id,
  1012. func,
  1013. line);
  1014. va_start(args, fmt);
  1015. vprintf(fmt, args);
  1016. va_end(args);
  1017. putchar('\n');
  1018. fflush(stdout);
  1019. funlockfile(stdout);
  1020. nslast = nsnow;
  1021. }
  1022. #define DEBUG_TRACE(fmt, ...) \
  1023. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  1024. #else
  1025. #define DEBUG_TRACE(fmt, ...) \
  1026. do { \
  1027. } while (0)
  1028. #endif /* DEBUG */
  1029. #endif /* DEBUG_TRACE */
  1030. #define MD5_STATIC static
  1031. #include "md5.inl"
  1032. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1033. #ifdef NO_SOCKLEN_T
  1034. typedef int socklen_t;
  1035. #endif /* NO_SOCKLEN_T */
  1036. #define _DARWIN_UNLIMITED_SELECT
  1037. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1038. #if !defined(MSG_NOSIGNAL)
  1039. #define MSG_NOSIGNAL (0)
  1040. #endif
  1041. #if !defined(SOMAXCONN)
  1042. #define SOMAXCONN (100)
  1043. #endif
  1044. /* Size of the accepted socket queue */
  1045. #if !defined(MGSQLEN)
  1046. #define MGSQLEN (20)
  1047. #endif
  1048. #if defined(NO_SSL)
  1049. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1050. typedef struct SSL_CTX SSL_CTX;
  1051. #else
  1052. #if defined(NO_SSL_DL)
  1053. #include <openssl/ssl.h>
  1054. #include <openssl/err.h>
  1055. #include <openssl/crypto.h>
  1056. #include <openssl/x509.h>
  1057. #include <openssl/pem.h>
  1058. #include <openssl/engine.h>
  1059. #include <openssl/conf.h>
  1060. #include <openssl/dh.h>
  1061. #include <openssl/bn.h>
  1062. #include <openssl/opensslv.h>
  1063. #else
  1064. /* SSL loaded dynamically from DLL.
  1065. * I put the prototypes here to be independent from OpenSSL source
  1066. * installation. */
  1067. typedef struct ssl_st SSL;
  1068. typedef struct ssl_method_st SSL_METHOD;
  1069. typedef struct ssl_ctx_st SSL_CTX;
  1070. typedef struct x509_store_ctx_st X509_STORE_CTX;
  1071. typedef struct x509_name X509_NAME;
  1072. typedef struct asn1_integer ASN1_INTEGER;
  1073. typedef struct bignum BIGNUM;
  1074. typedef struct ossl_init_settings_st OPENSSL_INIT_SETTINGS;
  1075. typedef struct evp_md EVP_MD;
  1076. typedef struct x509 X509;
  1077. #define SSL_CTRL_OPTIONS (32)
  1078. #define SSL_CTRL_CLEAR_OPTIONS (77)
  1079. #define SSL_CTRL_SET_ECDH_AUTO (94)
  1080. #define OPENSSL_INIT_NO_LOAD_SSL_STRINGS 0x00100000L
  1081. #define OPENSSL_INIT_LOAD_SSL_STRINGS 0x00200000L
  1082. #define OPENSSL_INIT_LOAD_CRYPTO_STRINGS 0x00000002L
  1083. #define SSL_VERIFY_NONE (0)
  1084. #define SSL_VERIFY_PEER (1)
  1085. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  1086. #define SSL_VERIFY_CLIENT_ONCE (4)
  1087. #define SSL_OP_ALL ((long)(0x80000BFFUL))
  1088. #define SSL_OP_NO_SSLv2 (0x01000000L)
  1089. #define SSL_OP_NO_SSLv3 (0x02000000L)
  1090. #define SSL_OP_NO_TLSv1 (0x04000000L)
  1091. #define SSL_OP_NO_TLSv1_2 (0x08000000L)
  1092. #define SSL_OP_NO_TLSv1_1 (0x10000000L)
  1093. #define SSL_OP_SINGLE_DH_USE (0x00100000L)
  1094. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000L)
  1095. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000L)
  1096. #define SSL_ERROR_NONE (0)
  1097. #define SSL_ERROR_SSL (1)
  1098. #define SSL_ERROR_WANT_READ (2)
  1099. #define SSL_ERROR_WANT_WRITE (3)
  1100. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  1101. #define SSL_ERROR_SYSCALL (5) /* see errno */
  1102. #define SSL_ERROR_ZERO_RETURN (6)
  1103. #define SSL_ERROR_WANT_CONNECT (7)
  1104. #define SSL_ERROR_WANT_ACCEPT (8)
  1105. struct ssl_func {
  1106. const char *name; /* SSL function name */
  1107. void (*ptr)(void); /* Function pointer */
  1108. };
  1109. #ifdef OPENSSL_API_1_1
  1110. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1111. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1112. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1113. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1114. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1115. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1116. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1117. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  1118. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  1119. #define TLS_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  1120. #define OPENSSL_init_ssl \
  1121. (*(int (*)(uint64_t opts, \
  1122. const OPENSSL_INIT_SETTINGS *settings))ssl_sw[10].ptr)
  1123. #define SSL_CTX_use_PrivateKey_file \
  1124. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1125. #define SSL_CTX_use_certificate_file \
  1126. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1127. #define SSL_CTX_set_default_passwd_cb \
  1128. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1129. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1130. #define SSL_CTX_use_certificate_chain_file \
  1131. (*(int (*)(SSL_CTX *, const char *))ssl_sw[15].ptr)
  1132. #define TLS_client_method (*(SSL_METHOD * (*)(void))ssl_sw[16].ptr)
  1133. #define SSL_pending (*(int (*)(SSL *))ssl_sw[17].ptr)
  1134. #define SSL_CTX_set_verify \
  1135. (*(void (*)(SSL_CTX *, \
  1136. int, \
  1137. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[18].ptr)
  1138. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[19].ptr)
  1139. #define SSL_CTX_load_verify_locations \
  1140. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[20].ptr)
  1141. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[21].ptr)
  1142. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[22].ptr)
  1143. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[23].ptr)
  1144. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[24].ptr)
  1145. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[25].ptr)
  1146. #define SSL_CIPHER_get_name \
  1147. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[26].ptr)
  1148. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[27].ptr)
  1149. #define SSL_CTX_set_session_id_context \
  1150. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[28].ptr)
  1151. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[29].ptr)
  1152. #define SSL_CTX_set_cipher_list \
  1153. (*(int (*)(SSL_CTX *, const char *))ssl_sw[30].ptr)
  1154. #define SSL_CTX_set_options \
  1155. (*(unsigned long (*)(SSL_CTX *, unsigned long))ssl_sw[31].ptr)
  1156. #define SSL_CTX_clear_options(ctx, op) \
  1157. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1158. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1159. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1160. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1161. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1162. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[0].ptr)
  1163. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[1].ptr)
  1164. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[2].ptr)
  1165. #define CONF_modules_unload (*(void (*)(int))crypto_sw[3].ptr)
  1166. #define X509_free (*(void (*)(X509 *))crypto_sw[4].ptr)
  1167. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[5].ptr)
  1168. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[6].ptr)
  1169. #define X509_NAME_oneline \
  1170. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[7].ptr)
  1171. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[8].ptr)
  1172. #define EVP_get_digestbyname \
  1173. (*(const EVP_MD *(*)(const char *))crypto_sw[9].ptr)
  1174. #define ASN1_digest \
  1175. (*(int (*)(int (*)(void *, unsigned char **), \
  1176. const EVP_MD *, \
  1177. char *, \
  1178. unsigned char *, \
  1179. unsigned int *))crypto_sw[10].ptr)
  1180. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[11].ptr)
  1181. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[12].ptr)
  1182. #define ASN1_INTEGER_to_BN \
  1183. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn))crypto_sw[13].ptr)
  1184. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[14].ptr)
  1185. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[15].ptr)
  1186. #define OPENSSL_free(a) CRYPTO_free(a)
  1187. /* set_ssl_option() function updates this array.
  1188. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1189. * of respective functions. The macros above (like SSL_connect()) are really
  1190. * just calling these functions indirectly via the pointer. */
  1191. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1192. {"SSL_accept", NULL},
  1193. {"SSL_connect", NULL},
  1194. {"SSL_read", NULL},
  1195. {"SSL_write", NULL},
  1196. {"SSL_get_error", NULL},
  1197. {"SSL_set_fd", NULL},
  1198. {"SSL_new", NULL},
  1199. {"SSL_CTX_new", NULL},
  1200. {"TLS_server_method", NULL},
  1201. {"OPENSSL_init_ssl", NULL},
  1202. {"SSL_CTX_use_PrivateKey_file", NULL},
  1203. {"SSL_CTX_use_certificate_file", NULL},
  1204. {"SSL_CTX_set_default_passwd_cb", NULL},
  1205. {"SSL_CTX_free", NULL},
  1206. {"SSL_CTX_use_certificate_chain_file", NULL},
  1207. {"TLS_client_method", NULL},
  1208. {"SSL_pending", NULL},
  1209. {"SSL_CTX_set_verify", NULL},
  1210. {"SSL_shutdown", NULL},
  1211. {"SSL_CTX_load_verify_locations", NULL},
  1212. {"SSL_CTX_set_default_verify_paths", NULL},
  1213. {"SSL_CTX_set_verify_depth", NULL},
  1214. {"SSL_get_peer_certificate", NULL},
  1215. {"SSL_get_version", NULL},
  1216. {"SSL_get_current_cipher", NULL},
  1217. {"SSL_CIPHER_get_name", NULL},
  1218. {"SSL_CTX_check_private_key", NULL},
  1219. {"SSL_CTX_set_session_id_context", NULL},
  1220. {"SSL_CTX_ctrl", NULL},
  1221. {"SSL_CTX_set_cipher_list", NULL},
  1222. {"SSL_CTX_set_options", NULL},
  1223. {NULL, NULL}};
  1224. /* Similar array as ssl_sw. These functions could be located in different
  1225. * lib. */
  1226. static struct ssl_func crypto_sw[] = {{"ERR_get_error", NULL},
  1227. {"ERR_error_string", NULL},
  1228. {"ERR_remove_state", NULL},
  1229. {"CONF_modules_unload", NULL},
  1230. {"X509_free", NULL},
  1231. {"X509_get_subject_name", NULL},
  1232. {"X509_get_issuer_name", NULL},
  1233. {"X509_NAME_oneline", NULL},
  1234. {"X509_get_serialNumber", NULL},
  1235. {"EVP_get_digestbyname", NULL},
  1236. {"ASN1_digest", NULL},
  1237. {"i2d_X509", NULL},
  1238. {"BN_bn2hex", NULL},
  1239. {"ASN1_INTEGER_to_BN", NULL},
  1240. {"BN_free", NULL},
  1241. {"CRYPTO_free", NULL},
  1242. {NULL, NULL}};
  1243. #else
  1244. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1245. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1246. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1247. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1248. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1249. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1250. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1251. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  1252. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  1253. #define SSLv23_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  1254. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  1255. #define SSL_CTX_use_PrivateKey_file \
  1256. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1257. #define SSL_CTX_use_certificate_file \
  1258. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1259. #define SSL_CTX_set_default_passwd_cb \
  1260. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1261. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1262. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  1263. #define SSL_CTX_use_certificate_chain_file \
  1264. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  1265. #define SSLv23_client_method (*(SSL_METHOD * (*)(void))ssl_sw[17].ptr)
  1266. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  1267. #define SSL_CTX_set_verify \
  1268. (*(void (*)(SSL_CTX *, \
  1269. int, \
  1270. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19].ptr)
  1271. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  1272. #define SSL_CTX_load_verify_locations \
  1273. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  1274. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  1275. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  1276. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[24].ptr)
  1277. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  1278. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[26].ptr)
  1279. #define SSL_CIPHER_get_name \
  1280. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  1281. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  1282. #define SSL_CTX_set_session_id_context \
  1283. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  1284. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  1285. #define SSL_CTX_set_cipher_list \
  1286. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  1287. #define SSL_CTX_set_options(ctx, op) \
  1288. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  1289. #define SSL_CTX_clear_options(ctx, op) \
  1290. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1291. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1292. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1293. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1294. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1295. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  1296. #define CRYPTO_set_locking_callback \
  1297. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  1298. #define CRYPTO_set_id_callback \
  1299. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  1300. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  1301. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  1302. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  1303. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  1304. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  1305. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  1306. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  1307. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  1308. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  1309. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[12].ptr)
  1310. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[13].ptr)
  1311. #define X509_NAME_oneline \
  1312. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  1313. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[15].ptr)
  1314. #define i2c_ASN1_INTEGER \
  1315. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  1316. #define EVP_get_digestbyname \
  1317. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1318. #define ASN1_digest \
  1319. (*(int (*)(int (*)(), \
  1320. const EVP_MD *, \
  1321. char *, \
  1322. unsigned char *, \
  1323. unsigned int *))crypto_sw[18].ptr)
  1324. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1325. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[20].ptr)
  1326. #define ASN1_INTEGER_to_BN \
  1327. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn))crypto_sw[21].ptr)
  1328. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[22].ptr)
  1329. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[23].ptr)
  1330. #define OPENSSL_free(a) CRYPTO_free(a)
  1331. /* set_ssl_option() function updates this array.
  1332. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1333. * of respective functions. The macros above (like SSL_connect()) are really
  1334. * just calling these functions indirectly via the pointer. */
  1335. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1336. {"SSL_accept", NULL},
  1337. {"SSL_connect", NULL},
  1338. {"SSL_read", NULL},
  1339. {"SSL_write", NULL},
  1340. {"SSL_get_error", NULL},
  1341. {"SSL_set_fd", NULL},
  1342. {"SSL_new", NULL},
  1343. {"SSL_CTX_new", NULL},
  1344. {"SSLv23_server_method", NULL},
  1345. {"SSL_library_init", NULL},
  1346. {"SSL_CTX_use_PrivateKey_file", NULL},
  1347. {"SSL_CTX_use_certificate_file", NULL},
  1348. {"SSL_CTX_set_default_passwd_cb", NULL},
  1349. {"SSL_CTX_free", NULL},
  1350. {"SSL_load_error_strings", NULL},
  1351. {"SSL_CTX_use_certificate_chain_file", NULL},
  1352. {"SSLv23_client_method", NULL},
  1353. {"SSL_pending", NULL},
  1354. {"SSL_CTX_set_verify", NULL},
  1355. {"SSL_shutdown", NULL},
  1356. {"SSL_CTX_load_verify_locations", NULL},
  1357. {"SSL_CTX_set_default_verify_paths", NULL},
  1358. {"SSL_CTX_set_verify_depth", NULL},
  1359. {"SSL_get_peer_certificate", NULL},
  1360. {"SSL_get_version", NULL},
  1361. {"SSL_get_current_cipher", NULL},
  1362. {"SSL_CIPHER_get_name", NULL},
  1363. {"SSL_CTX_check_private_key", NULL},
  1364. {"SSL_CTX_set_session_id_context", NULL},
  1365. {"SSL_CTX_ctrl", NULL},
  1366. {"SSL_CTX_set_cipher_list", NULL},
  1367. {NULL, NULL}};
  1368. /* Similar array as ssl_sw. These functions could be located in different
  1369. * lib. */
  1370. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  1371. {"CRYPTO_set_locking_callback", NULL},
  1372. {"CRYPTO_set_id_callback", NULL},
  1373. {"ERR_get_error", NULL},
  1374. {"ERR_error_string", NULL},
  1375. {"ERR_remove_state", NULL},
  1376. {"ERR_free_strings", NULL},
  1377. {"ENGINE_cleanup", NULL},
  1378. {"CONF_modules_unload", NULL},
  1379. {"CRYPTO_cleanup_all_ex_data", NULL},
  1380. {"EVP_cleanup", NULL},
  1381. {"X509_free", NULL},
  1382. {"X509_get_subject_name", NULL},
  1383. {"X509_get_issuer_name", NULL},
  1384. {"X509_NAME_oneline", NULL},
  1385. {"X509_get_serialNumber", NULL},
  1386. {"i2c_ASN1_INTEGER", NULL},
  1387. {"EVP_get_digestbyname", NULL},
  1388. {"ASN1_digest", NULL},
  1389. {"i2d_X509", NULL},
  1390. {"BN_bn2hex", NULL},
  1391. {"ASN1_INTEGER_to_BN", NULL},
  1392. {"BN_free", NULL},
  1393. {"CRYPTO_free", NULL},
  1394. {NULL, NULL}};
  1395. #endif /* OPENSSL_API_1_1 */
  1396. #endif /* NO_SSL_DL */
  1397. #endif /* NO_SSL */
  1398. #if !defined(NO_CACHING)
  1399. static const char *month_names[] = {"Jan",
  1400. "Feb",
  1401. "Mar",
  1402. "Apr",
  1403. "May",
  1404. "Jun",
  1405. "Jul",
  1406. "Aug",
  1407. "Sep",
  1408. "Oct",
  1409. "Nov",
  1410. "Dec"};
  1411. #endif /* !NO_CACHING */
  1412. /* Unified socket address. For IPv6 support, add IPv6 address structure in the
  1413. * union u. */
  1414. union usa {
  1415. struct sockaddr sa;
  1416. struct sockaddr_in sin;
  1417. #if defined(USE_IPV6)
  1418. struct sockaddr_in6 sin6;
  1419. #endif
  1420. };
  1421. /* Describes a string (chunk of memory). */
  1422. struct vec {
  1423. const char *ptr;
  1424. size_t len;
  1425. };
  1426. struct mg_file_stat {
  1427. /* File properties filled by mg_stat: */
  1428. uint64_t size;
  1429. time_t last_modified;
  1430. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1431. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1432. * case we need a "Content-Eencoding: gzip" header */
  1433. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1434. };
  1435. struct mg_file_in_memory {
  1436. char *p;
  1437. uint32_t pos;
  1438. char mode;
  1439. };
  1440. struct mg_file_access {
  1441. /* File properties filled by mg_fopen: */
  1442. FILE *fp;
  1443. /* TODO (low): Replace "membuf" implementation by a "file in memory"
  1444. * support library. Use some struct mg_file_in_memory *mf; instead of
  1445. * membuf char pointer. */
  1446. const char *membuf;
  1447. };
  1448. struct mg_file {
  1449. struct mg_file_stat stat;
  1450. struct mg_file_access access;
  1451. };
  1452. #define STRUCT_FILE_INITIALIZER \
  1453. { \
  1454. { \
  1455. (uint64_t)0, (time_t)0, 0, 0, 0 \
  1456. } \
  1457. , \
  1458. { \
  1459. (FILE *) NULL, (const char *)NULL \
  1460. } \
  1461. }
  1462. /* Describes listening socket, or socket which was accept()-ed by the master
  1463. * thread and queued for future handling by the worker thread. */
  1464. struct socket {
  1465. SOCKET sock; /* Listening socket */
  1466. union usa lsa; /* Local socket address */
  1467. union usa rsa; /* Remote socket address */
  1468. unsigned char is_ssl; /* Is port SSL-ed */
  1469. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1470. * port */
  1471. unsigned char in_use; /* Is valid */
  1472. };
  1473. /* NOTE(lsm): this enum shoulds be in sync with the config_options below. */
  1474. enum {
  1475. CGI_EXTENSIONS,
  1476. CGI_ENVIRONMENT,
  1477. PUT_DELETE_PASSWORDS_FILE,
  1478. CGI_INTERPRETER,
  1479. PROTECT_URI,
  1480. AUTHENTICATION_DOMAIN,
  1481. ENABLE_AUTH_DOMAIN_CHECK,
  1482. SSI_EXTENSIONS,
  1483. THROTTLE,
  1484. ACCESS_LOG_FILE,
  1485. ENABLE_DIRECTORY_LISTING,
  1486. ERROR_LOG_FILE,
  1487. GLOBAL_PASSWORDS_FILE,
  1488. INDEX_FILES,
  1489. ENABLE_KEEP_ALIVE,
  1490. ACCESS_CONTROL_LIST,
  1491. EXTRA_MIME_TYPES,
  1492. LISTENING_PORTS,
  1493. DOCUMENT_ROOT,
  1494. SSL_CERTIFICATE,
  1495. NUM_THREADS,
  1496. RUN_AS_USER,
  1497. REWRITE,
  1498. HIDE_FILES,
  1499. REQUEST_TIMEOUT,
  1500. KEEP_ALIVE_TIMEOUT,
  1501. LINGER_TIMEOUT,
  1502. SSL_DO_VERIFY_PEER,
  1503. SSL_CA_PATH,
  1504. SSL_CA_FILE,
  1505. SSL_VERIFY_DEPTH,
  1506. SSL_DEFAULT_VERIFY_PATHS,
  1507. SSL_CIPHER_LIST,
  1508. SSL_PROTOCOL_VERSION,
  1509. SSL_SHORT_TRUST,
  1510. #if defined(USE_WEBSOCKET)
  1511. WEBSOCKET_TIMEOUT,
  1512. #endif
  1513. DECODE_URL,
  1514. #if defined(USE_LUA)
  1515. LUA_PRELOAD_FILE,
  1516. LUA_SCRIPT_EXTENSIONS,
  1517. LUA_SERVER_PAGE_EXTENSIONS,
  1518. #endif
  1519. #if defined(USE_DUKTAPE)
  1520. DUKTAPE_SCRIPT_EXTENSIONS,
  1521. #endif
  1522. #if defined(USE_WEBSOCKET)
  1523. WEBSOCKET_ROOT,
  1524. #endif
  1525. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1526. LUA_WEBSOCKET_EXTENSIONS,
  1527. #endif
  1528. ACCESS_CONTROL_ALLOW_ORIGIN,
  1529. ERROR_PAGES,
  1530. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1531. * socket option typedef TCP_NODELAY. */
  1532. #if !defined(NO_CACHING)
  1533. STATIC_FILE_MAX_AGE,
  1534. #endif
  1535. #if defined(__linux__)
  1536. ALLOW_SENDFILE_CALL,
  1537. #endif
  1538. #if defined(_WIN32)
  1539. CASE_SENSITIVE_FILES,
  1540. #endif
  1541. #if defined(USE_LUA)
  1542. LUA_BACKGROUND_SCRIPT,
  1543. #endif
  1544. NUM_OPTIONS
  1545. };
  1546. /* Config option name, config types, default value */
  1547. static struct mg_option config_options[] = {
  1548. {"cgi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1549. {"cgi_environment", CONFIG_TYPE_STRING, NULL},
  1550. {"put_delete_auth_file", CONFIG_TYPE_FILE, NULL},
  1551. {"cgi_interpreter", CONFIG_TYPE_FILE, NULL},
  1552. {"protect_uri", CONFIG_TYPE_STRING, NULL},
  1553. {"authentication_domain", CONFIG_TYPE_STRING, "mydomain.com"},
  1554. {"enable_auth_domain_check", CONFIG_TYPE_BOOLEAN, "yes"},
  1555. {"ssi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1556. {"throttle", CONFIG_TYPE_STRING, NULL},
  1557. {"access_log_file", CONFIG_TYPE_FILE, NULL},
  1558. {"enable_directory_listing", CONFIG_TYPE_BOOLEAN, "yes"},
  1559. {"error_log_file", CONFIG_TYPE_FILE, NULL},
  1560. {"global_auth_file", CONFIG_TYPE_FILE, NULL},
  1561. {"index_files",
  1562. CONFIG_TYPE_STRING,
  1563. #ifdef USE_LUA
  1564. "index.xhtml,index.html,index.htm,index.lp,index.lsp,index.lua,index.cgi,"
  1565. "index.shtml,index.php"},
  1566. #else
  1567. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1568. #endif
  1569. {"enable_keep_alive", CONFIG_TYPE_BOOLEAN, "no"},
  1570. {"access_control_list", CONFIG_TYPE_STRING, NULL},
  1571. {"extra_mime_types", CONFIG_TYPE_STRING, NULL},
  1572. {"listening_ports", CONFIG_TYPE_STRING, "8080"},
  1573. {"document_root", CONFIG_TYPE_DIRECTORY, NULL},
  1574. {"ssl_certificate", CONFIG_TYPE_FILE, NULL},
  1575. {"num_threads", CONFIG_TYPE_NUMBER, "50"},
  1576. {"run_as_user", CONFIG_TYPE_STRING, NULL},
  1577. {"url_rewrite_patterns", CONFIG_TYPE_STRING, NULL},
  1578. {"hide_files_patterns", CONFIG_TYPE_EXT_PATTERN, NULL},
  1579. {"request_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1580. {"keep_alive_timeout_ms", CONFIG_TYPE_NUMBER, "500"},
  1581. {"linger_timeout_ms", CONFIG_TYPE_NUMBER, NULL},
  1582. {"ssl_verify_peer", CONFIG_TYPE_BOOLEAN, "no"},
  1583. {"ssl_ca_path", CONFIG_TYPE_DIRECTORY, NULL},
  1584. {"ssl_ca_file", CONFIG_TYPE_FILE, NULL},
  1585. {"ssl_verify_depth", CONFIG_TYPE_NUMBER, "9"},
  1586. {"ssl_default_verify_paths", CONFIG_TYPE_BOOLEAN, "yes"},
  1587. {"ssl_cipher_list", CONFIG_TYPE_STRING, NULL},
  1588. {"ssl_protocol_version", CONFIG_TYPE_NUMBER, "0"},
  1589. {"ssl_short_trust", CONFIG_TYPE_BOOLEAN, "no"},
  1590. #if defined(USE_WEBSOCKET)
  1591. {"websocket_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1592. #endif
  1593. {"decode_url", CONFIG_TYPE_BOOLEAN, "yes"},
  1594. #if defined(USE_LUA)
  1595. {"lua_preload_file", CONFIG_TYPE_FILE, NULL},
  1596. {"lua_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1597. {"lua_server_page_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1598. #endif
  1599. #if defined(USE_DUKTAPE)
  1600. /* The support for duktape is still in alpha version state.
  1601. * The name of this config option might change. */
  1602. {"duktape_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1603. #endif
  1604. #if defined(USE_WEBSOCKET)
  1605. {"websocket_root", CONFIG_TYPE_DIRECTORY, NULL},
  1606. #endif
  1607. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1608. {"lua_websocket_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1609. #endif
  1610. {"access_control_allow_origin", CONFIG_TYPE_STRING, "*"},
  1611. {"error_pages", CONFIG_TYPE_DIRECTORY, NULL},
  1612. {"tcp_nodelay", CONFIG_TYPE_NUMBER, "0"},
  1613. #if !defined(NO_CACHING)
  1614. {"static_file_max_age", CONFIG_TYPE_NUMBER, "3600"},
  1615. #endif
  1616. #if defined(__linux__)
  1617. {"allow_sendfile_call", CONFIG_TYPE_BOOLEAN, "yes"},
  1618. #endif
  1619. #if defined(_WIN32)
  1620. {"case_sensitive", CONFIG_TYPE_BOOLEAN, "no"},
  1621. #endif
  1622. #if defined(USE_LUA)
  1623. {"lua_background_script", CONFIG_TYPE_FILE, NULL},
  1624. #endif
  1625. {NULL, CONFIG_TYPE_UNKNOWN, NULL}};
  1626. /* Check if the config_options and the corresponding enum have compatible
  1627. * sizes. */
  1628. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1629. == (NUM_OPTIONS + 1),
  1630. "config_options and enum not sync");
  1631. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1632. struct mg_handler_info {
  1633. /* Name/Pattern of the URI. */
  1634. char *uri;
  1635. size_t uri_len;
  1636. /* handler type */
  1637. int handler_type;
  1638. /* Handler for http/https or authorization requests. */
  1639. mg_request_handler handler;
  1640. /* Handler for ws/wss (websocket) requests. */
  1641. mg_websocket_connect_handler connect_handler;
  1642. mg_websocket_ready_handler ready_handler;
  1643. mg_websocket_data_handler data_handler;
  1644. mg_websocket_close_handler close_handler;
  1645. /* accepted subprotocols for ws/wss requests. */
  1646. struct mg_websocket_subprotocols *subprotocols;
  1647. /* Handler for authorization requests */
  1648. mg_authorization_handler auth_handler;
  1649. /* User supplied argument for the handler function. */
  1650. void *cbdata;
  1651. /* next handler in a linked list */
  1652. struct mg_handler_info *next;
  1653. };
  1654. struct mg_context {
  1655. volatile int stop_flag; /* Should we stop event loop */
  1656. SSL_CTX *ssl_ctx; /* SSL context */
  1657. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1658. struct mg_callbacks callbacks; /* User-defined callback function */
  1659. void *user_data; /* User-defined data */
  1660. int context_type; /* 1 = server context,
  1661. * 2 = ws/wss client context,
  1662. */
  1663. struct socket *listening_sockets;
  1664. struct pollfd *listening_socket_fds;
  1665. unsigned int num_listening_sockets;
  1666. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  1667. #ifdef ALTERNATIVE_QUEUE
  1668. struct socket *client_socks;
  1669. void **client_wait_events;
  1670. #else
  1671. struct socket queue[MGSQLEN]; /* Accepted sockets */
  1672. volatile int sq_head; /* Head of the socket queue */
  1673. volatile int sq_tail; /* Tail of the socket queue */
  1674. pthread_cond_t sq_full; /* Signaled when socket is produced */
  1675. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  1676. #endif
  1677. pthread_t masterthreadid; /* The master thread ID */
  1678. unsigned int
  1679. cfg_worker_threads; /* The number of configured worker threads. */
  1680. pthread_t *worker_threadids; /* The worker thread IDs */
  1681. struct mg_connection *worker_connections; /* The connection struct, pre-
  1682. * allocated for each worker */
  1683. time_t start_time; /* Server start time, used for authentication */
  1684. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1685. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  1686. unsigned long nonce_count; /* Used nonces, used for authentication */
  1687. char *systemName; /* What operating system is running */
  1688. /* linked list of uri handlers */
  1689. struct mg_handler_info *handlers;
  1690. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1691. /* linked list of shared lua websockets */
  1692. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1693. #endif
  1694. #if defined(USE_TIMERS)
  1695. struct ttimers *timers;
  1696. #endif
  1697. #if defined(USE_LUA)
  1698. void *lua_background_state;
  1699. #endif
  1700. };
  1701. struct mg_connection {
  1702. struct mg_request_info request_info;
  1703. struct mg_context *ctx;
  1704. SSL *ssl; /* SSL descriptor */
  1705. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  1706. struct socket client; /* Connected client */
  1707. time_t conn_birth_time; /* Time (wall clock) when connection was
  1708. * established */
  1709. struct timespec req_time; /* Time (since system start) when the request
  1710. * was received */
  1711. int64_t num_bytes_sent; /* Total bytes sent to client */
  1712. int64_t content_len; /* Content-Length header value */
  1713. int64_t consumed_content; /* How many bytes of content have been read */
  1714. int is_chunked; /* Transfer-Encoding is chunked: 0=no, 1=yes:
  1715. * data available, 2: all data read */
  1716. size_t chunk_remainder; /* Unread data from the last chunk */
  1717. char *buf; /* Buffer for received data */
  1718. char *path_info; /* PATH_INFO part of the URL */
  1719. int must_close; /* 1 if connection must be closed */
  1720. int in_error_handler; /* 1 if in handler for user defined error
  1721. * pages */
  1722. int handled_requests; /* Number of requests handled by this connection */
  1723. int buf_size; /* Buffer size */
  1724. int request_len; /* Size of the request + headers in a buffer */
  1725. int data_len; /* Total size of data in a buffer */
  1726. int status_code; /* HTTP reply status code, e.g. 200 */
  1727. int throttle; /* Throttling, bytes/sec. <= 0 means no
  1728. * throttle */
  1729. time_t last_throttle_time; /* Last time throttled data was sent */
  1730. int64_t last_throttle_bytes; /* Bytes sent this second */
  1731. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  1732. * atomic transmissions for websockets */
  1733. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1734. void *lua_websocket_state; /* Lua_State for a websocket connection */
  1735. #endif
  1736. int thread_index; /* Thread index within ctx */
  1737. };
  1738. /* Directory entry */
  1739. struct de {
  1740. struct mg_connection *conn;
  1741. char *file_name;
  1742. struct mg_file_stat file;
  1743. };
  1744. #if defined(USE_WEBSOCKET)
  1745. static int is_websocket_protocol(const struct mg_connection *conn);
  1746. #else
  1747. #define is_websocket_protocol(conn) (0)
  1748. #endif
  1749. #if !defined(NO_THREAD_NAME)
  1750. #if defined(_WIN32) && defined(_MSC_VER)
  1751. /* Set the thread name for debugging purposes in Visual Studio
  1752. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  1753. */
  1754. #pragma pack(push, 8)
  1755. typedef struct tagTHREADNAME_INFO {
  1756. DWORD dwType; /* Must be 0x1000. */
  1757. LPCSTR szName; /* Pointer to name (in user addr space). */
  1758. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  1759. DWORD dwFlags; /* Reserved for future use, must be zero. */
  1760. } THREADNAME_INFO;
  1761. #pragma pack(pop)
  1762. #elif defined(__linux__)
  1763. #include <sys/prctl.h>
  1764. #include <sys/sendfile.h>
  1765. #include <sys/eventfd.h>
  1766. #if defined(ALTERNATIVE_QUEUE)
  1767. static void *
  1768. event_create(void)
  1769. {
  1770. int ret = eventfd(0, EFD_CLOEXEC);
  1771. if (ret == -1) {
  1772. /* Linux uses -1 on error, Windows NULL. */
  1773. /* However, Linux does not return 0 on success either. */
  1774. return 0;
  1775. }
  1776. return (void *)ret;
  1777. }
  1778. static int
  1779. event_wait(void *eventhdl)
  1780. {
  1781. uint64_t u;
  1782. int s = (int)read((int)eventhdl, &u, sizeof(u));
  1783. if (s != sizeof(uint64_t)) {
  1784. /* error */
  1785. return 0;
  1786. }
  1787. (void)u; /* the value is not required */
  1788. return 1;
  1789. }
  1790. static int
  1791. event_signal(void *eventhdl)
  1792. {
  1793. uint64_t u = 1;
  1794. int s = (int)write((int)eventhdl, &u, sizeof(u));
  1795. if (s != sizeof(uint64_t)) {
  1796. /* error */
  1797. return 0;
  1798. }
  1799. return 1;
  1800. }
  1801. static void
  1802. event_destroy(void *eventhdl)
  1803. {
  1804. close((int)eventhdl);
  1805. }
  1806. #endif
  1807. #endif
  1808. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  1809. struct posix_event {
  1810. pthread_mutex_t mutex;
  1811. pthread_cond_t cond;
  1812. };
  1813. static void *
  1814. event_create(void)
  1815. {
  1816. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  1817. if (ret == 0) {
  1818. /* out of memory */
  1819. return 0;
  1820. }
  1821. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  1822. /* pthread mutex not available */
  1823. mg_free(ret);
  1824. return 0;
  1825. }
  1826. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  1827. /* pthread cond not available */
  1828. pthread_mutex_destroy(&(ret->mutex));
  1829. mg_free(ret);
  1830. return 0;
  1831. }
  1832. return (void *)ret;
  1833. }
  1834. static int
  1835. event_wait(void *eventhdl)
  1836. {
  1837. struct posix_event *ev = (struct posix_event *)eventhdl;
  1838. pthread_mutex_lock(&(ev->mutex));
  1839. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  1840. pthread_mutex_unlock(&(ev->mutex));
  1841. return 1;
  1842. }
  1843. static int
  1844. event_signal(void *eventhdl)
  1845. {
  1846. struct posix_event *ev = (struct posix_event *)eventhdl;
  1847. pthread_mutex_lock(&(ev->mutex));
  1848. pthread_cond_signal(&(ev->cond));
  1849. pthread_mutex_unlock(&(ev->mutex));
  1850. return 1;
  1851. }
  1852. static void
  1853. event_destroy(void *eventhdl)
  1854. {
  1855. struct posix_event *ev = (struct posix_event *)eventhdl;
  1856. pthread_cond_destroy(&(ev->cond));
  1857. pthread_mutex_destroy(&(ev->mutex));
  1858. mg_free(ev);
  1859. }
  1860. #endif
  1861. static void
  1862. mg_set_thread_name(const char *name)
  1863. {
  1864. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  1865. mg_snprintf(
  1866. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  1867. #if defined(_WIN32)
  1868. #if defined(_MSC_VER)
  1869. /* Windows and Visual Studio Compiler */
  1870. __try
  1871. {
  1872. THREADNAME_INFO info;
  1873. info.dwType = 0x1000;
  1874. info.szName = threadName;
  1875. info.dwThreadID = ~0U;
  1876. info.dwFlags = 0;
  1877. RaiseException(0x406D1388,
  1878. 0,
  1879. sizeof(info) / sizeof(ULONG_PTR),
  1880. (ULONG_PTR *)&info);
  1881. }
  1882. __except(EXCEPTION_EXECUTE_HANDLER)
  1883. {
  1884. }
  1885. #elif defined(__MINGW32__)
  1886. /* No option known to set thread name for MinGW */
  1887. #endif
  1888. #elif defined(__GLIBC__) \
  1889. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  1890. /* pthread_setname_np first appeared in glibc in version 2.12*/
  1891. (void)pthread_setname_np(pthread_self(), threadName);
  1892. #elif defined(__linux__)
  1893. /* on linux we can use the old prctl function */
  1894. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  1895. #endif
  1896. }
  1897. #else /* !defined(NO_THREAD_NAME) */
  1898. void
  1899. mg_set_thread_name(const char *threadName)
  1900. {
  1901. }
  1902. #endif
  1903. #if defined(MG_LEGACY_INTERFACE)
  1904. const char **
  1905. mg_get_valid_option_names(void)
  1906. {
  1907. /* This function is deprecated. Use mg_get_valid_options instead. */
  1908. static const char *
  1909. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  1910. int i;
  1911. for (i = 0; config_options[i].name != NULL; i++) {
  1912. data[i * 2] = config_options[i].name;
  1913. data[i * 2 + 1] = config_options[i].default_value;
  1914. }
  1915. return data;
  1916. }
  1917. #endif
  1918. const struct mg_option *
  1919. mg_get_valid_options(void)
  1920. {
  1921. return config_options;
  1922. }
  1923. /* Do not open file (used in is_file_in_memory) */
  1924. #define MG_FOPEN_MODE_NONE (0)
  1925. /* Open file for read only access */
  1926. #define MG_FOPEN_MODE_READ (1)
  1927. /* Open file for writing, create and overwrite */
  1928. #define MG_FOPEN_MODE_WRITE (2)
  1929. /* Open file for writing, create and append */
  1930. #define MG_FOPEN_MODE_APPEND (4)
  1931. /* If a file is in memory, set all "stat" members and the membuf pointer of
  1932. * output filep and return 1, otherwise return 0 and don't modify anything. */
  1933. static int
  1934. open_file_in_memory(const struct mg_connection *conn,
  1935. const char *path,
  1936. struct mg_file *filep,
  1937. int mode)
  1938. {
  1939. #if defined(MG_USE_OPEN_FILE)
  1940. size_t size = 0;
  1941. const char *buf = NULL;
  1942. if (!conn) {
  1943. return 0;
  1944. }
  1945. if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
  1946. return 0;
  1947. }
  1948. if (conn->ctx->callbacks.open_file) {
  1949. buf = conn->ctx->callbacks.open_file(conn, path, &size);
  1950. if (buf != NULL) {
  1951. if (filep == NULL) {
  1952. /* This is a file in memory, but we cannot store the properties
  1953. * now.
  1954. * Called from "is_file_in_memory" function. */
  1955. return 1;
  1956. }
  1957. /* NOTE: override filep->size only on success. Otherwise, it might
  1958. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  1959. filep->access.membuf = buf;
  1960. filep->access.fp = NULL;
  1961. /* Size was set by the callback */
  1962. filep->stat.size = size;
  1963. /* Assume the data may change during runtime by setting
  1964. * last_modified = now */
  1965. filep->stat.last_modified = time(NULL);
  1966. filep->stat.is_directory = 0;
  1967. filep->stat.is_gzipped = 0;
  1968. }
  1969. }
  1970. return (buf != NULL);
  1971. #else
  1972. (void)conn;
  1973. (void)path;
  1974. (void)filep;
  1975. (void)mode;
  1976. return 0;
  1977. #endif
  1978. }
  1979. static int
  1980. is_file_in_memory(const struct mg_connection *conn, const char *path)
  1981. {
  1982. return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
  1983. }
  1984. static int
  1985. is_file_opened(const struct mg_file_access *fileacc)
  1986. {
  1987. if (!fileacc) {
  1988. return 0;
  1989. }
  1990. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  1991. }
  1992. static int mg_stat(const struct mg_connection *conn,
  1993. const char *path,
  1994. struct mg_file_stat *filep);
  1995. /* mg_fopen will open a file either in memory or on the disk.
  1996. * The input parameter path is a string in UTF-8 encoding.
  1997. * The input parameter mode is MG_FOPEN_MODE_*
  1998. * On success, either fp or membuf will be set in the output
  1999. * struct file. All status members will also be set.
  2000. * The function returns 1 on success, 0 on error. */
  2001. static int
  2002. mg_fopen(const struct mg_connection *conn,
  2003. const char *path,
  2004. int mode,
  2005. struct mg_file *filep)
  2006. {
  2007. int found;
  2008. if (!filep) {
  2009. return 0;
  2010. }
  2011. filep->access.fp = NULL;
  2012. filep->access.membuf = NULL;
  2013. if (!is_file_in_memory(conn, path)) {
  2014. /* filep is initialized in mg_stat: all fields with memset to,
  2015. * some fields like size and modification date with values */
  2016. found = mg_stat(conn, path, &(filep->stat));
  2017. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2018. /* file does not exist and will not be created */
  2019. return 0;
  2020. }
  2021. #ifdef _WIN32
  2022. {
  2023. wchar_t wbuf[PATH_MAX];
  2024. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2025. switch (mode) {
  2026. case MG_FOPEN_MODE_READ:
  2027. filep->access.fp = _wfopen(wbuf, L"rb");
  2028. break;
  2029. case MG_FOPEN_MODE_WRITE:
  2030. filep->access.fp = _wfopen(wbuf, L"wb");
  2031. break;
  2032. case MG_FOPEN_MODE_APPEND:
  2033. filep->access.fp = _wfopen(wbuf, L"ab");
  2034. break;
  2035. }
  2036. }
  2037. #else
  2038. /* Linux et al already use unicode. No need to convert. */
  2039. switch (mode) {
  2040. case MG_FOPEN_MODE_READ:
  2041. filep->access.fp = fopen(path, "r");
  2042. break;
  2043. case MG_FOPEN_MODE_WRITE:
  2044. filep->access.fp = fopen(path, "w");
  2045. break;
  2046. case MG_FOPEN_MODE_APPEND:
  2047. filep->access.fp = fopen(path, "a");
  2048. break;
  2049. }
  2050. #endif
  2051. if (!found) {
  2052. /* File did not exist before fopen was called.
  2053. * Maybe it has been created now. Get stat info
  2054. * like creation time now. */
  2055. found = mg_stat(conn, path, &(filep->stat));
  2056. (void)found;
  2057. }
  2058. /* file is on disk */
  2059. return (filep->access.fp != NULL);
  2060. } else {
  2061. /* is_file_in_memory returned true */
  2062. if (open_file_in_memory(conn, path, filep, mode)) {
  2063. /* file is in memory */
  2064. return (filep->access.membuf != NULL);
  2065. }
  2066. }
  2067. /* Open failed */
  2068. return 0;
  2069. }
  2070. /* return 0 on success, just like fclose */
  2071. static int
  2072. mg_fclose(struct mg_file_access *fileacc)
  2073. {
  2074. int ret = -1;
  2075. if (fileacc != NULL) {
  2076. if (fileacc->fp != NULL) {
  2077. ret = fclose(fileacc->fp);
  2078. } else if (fileacc->membuf != NULL) {
  2079. ret = 0;
  2080. }
  2081. /* reset all members of fileacc */
  2082. memset(fileacc, 0, sizeof(*fileacc));
  2083. }
  2084. return ret;
  2085. }
  2086. static void
  2087. mg_strlcpy(register char *dst, register const char *src, size_t n)
  2088. {
  2089. for (; *src != '\0' && n > 1; n--) {
  2090. *dst++ = *src++;
  2091. }
  2092. *dst = '\0';
  2093. }
  2094. static int
  2095. lowercase(const char *s)
  2096. {
  2097. return tolower(*(const unsigned char *)s);
  2098. }
  2099. int
  2100. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2101. {
  2102. int diff = 0;
  2103. if (len > 0) {
  2104. do {
  2105. diff = lowercase(s1++) - lowercase(s2++);
  2106. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2107. }
  2108. return diff;
  2109. }
  2110. int
  2111. mg_strcasecmp(const char *s1, const char *s2)
  2112. {
  2113. int diff;
  2114. do {
  2115. diff = lowercase(s1++) - lowercase(s2++);
  2116. } while (diff == 0 && s1[-1] != '\0');
  2117. return diff;
  2118. }
  2119. static char *
  2120. mg_strndup(const char *ptr, size_t len)
  2121. {
  2122. char *p;
  2123. if ((p = (char *)mg_malloc(len + 1)) != NULL) {
  2124. mg_strlcpy(p, ptr, len + 1);
  2125. }
  2126. return p;
  2127. }
  2128. static char *
  2129. mg_strdup(const char *str)
  2130. {
  2131. return mg_strndup(str, strlen(str));
  2132. }
  2133. static const char *
  2134. mg_strcasestr(const char *big_str, const char *small_str)
  2135. {
  2136. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2137. if (big_len >= small_len) {
  2138. for (i = 0; i <= (big_len - small_len); i++) {
  2139. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2140. return big_str + i;
  2141. }
  2142. }
  2143. }
  2144. return NULL;
  2145. }
  2146. /* Return null terminated string of given maximum length.
  2147. * Report errors if length is exceeded. */
  2148. static void
  2149. mg_vsnprintf(const struct mg_connection *conn,
  2150. int *truncated,
  2151. char *buf,
  2152. size_t buflen,
  2153. const char *fmt,
  2154. va_list ap)
  2155. {
  2156. int n, ok;
  2157. if (buflen == 0) {
  2158. return;
  2159. }
  2160. #ifdef __clang__
  2161. #pragma clang diagnostic push
  2162. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2163. /* Using fmt as a non-literal is intended here, since it is mostly called
  2164. * indirectly by mg_snprintf */
  2165. #endif
  2166. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2167. ok = (n >= 0) && ((size_t)n < buflen);
  2168. #ifdef __clang__
  2169. #pragma clang diagnostic pop
  2170. #endif
  2171. if (ok) {
  2172. if (truncated) {
  2173. *truncated = 0;
  2174. }
  2175. } else {
  2176. if (truncated) {
  2177. *truncated = 1;
  2178. }
  2179. mg_cry(conn,
  2180. "truncating vsnprintf buffer: [%.*s]",
  2181. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2182. buf);
  2183. n = (int)buflen - 1;
  2184. }
  2185. buf[n] = '\0';
  2186. }
  2187. static void
  2188. mg_snprintf(const struct mg_connection *conn,
  2189. int *truncated,
  2190. char *buf,
  2191. size_t buflen,
  2192. const char *fmt,
  2193. ...)
  2194. {
  2195. va_list ap;
  2196. va_start(ap, fmt);
  2197. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2198. va_end(ap);
  2199. }
  2200. static int
  2201. get_option_index(const char *name)
  2202. {
  2203. int i;
  2204. for (i = 0; config_options[i].name != NULL; i++) {
  2205. if (strcmp(config_options[i].name, name) == 0) {
  2206. return i;
  2207. }
  2208. }
  2209. return -1;
  2210. }
  2211. const char *
  2212. mg_get_option(const struct mg_context *ctx, const char *name)
  2213. {
  2214. int i;
  2215. if ((i = get_option_index(name)) == -1) {
  2216. return NULL;
  2217. } else if (!ctx || ctx->config[i] == NULL) {
  2218. return "";
  2219. } else {
  2220. return ctx->config[i];
  2221. }
  2222. }
  2223. struct mg_context *
  2224. mg_get_context(const struct mg_connection *conn)
  2225. {
  2226. return (conn == NULL) ? (struct mg_context *)NULL : (conn->ctx);
  2227. }
  2228. void *
  2229. mg_get_user_data(const struct mg_context *ctx)
  2230. {
  2231. return (ctx == NULL) ? NULL : ctx->user_data;
  2232. }
  2233. void
  2234. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  2235. {
  2236. if (conn != NULL) {
  2237. conn->request_info.conn_data = data;
  2238. }
  2239. }
  2240. void *
  2241. mg_get_user_connection_data(const struct mg_connection *conn)
  2242. {
  2243. if (conn != NULL) {
  2244. return conn->request_info.conn_data;
  2245. }
  2246. return NULL;
  2247. }
  2248. size_t
  2249. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  2250. {
  2251. size_t i;
  2252. if (!ctx) {
  2253. return 0;
  2254. }
  2255. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  2256. ssl[i] = ctx->listening_sockets[i].is_ssl;
  2257. ports[i] =
  2258. #if defined(USE_IPV6)
  2259. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2260. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2261. :
  2262. #endif
  2263. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2264. }
  2265. return i;
  2266. }
  2267. int
  2268. mg_get_server_ports(const struct mg_context *ctx,
  2269. int size,
  2270. struct mg_server_ports *ports)
  2271. {
  2272. int i, cnt = 0;
  2273. if (size <= 0) {
  2274. return -1;
  2275. }
  2276. memset(ports, 0, sizeof(*ports) * (size_t)size);
  2277. if (!ctx) {
  2278. return -1;
  2279. }
  2280. if (!ctx->listening_sockets) {
  2281. return -1;
  2282. }
  2283. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  2284. ports[cnt].port =
  2285. #if defined(USE_IPV6)
  2286. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2287. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2288. :
  2289. #endif
  2290. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2291. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  2292. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  2293. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  2294. /* IPv4 */
  2295. ports[cnt].protocol = 1;
  2296. cnt++;
  2297. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  2298. /* IPv6 */
  2299. ports[cnt].protocol = 3;
  2300. cnt++;
  2301. }
  2302. }
  2303. return cnt;
  2304. }
  2305. static void
  2306. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  2307. {
  2308. buf[0] = '\0';
  2309. if (!usa) {
  2310. return;
  2311. }
  2312. if (usa->sa.sa_family == AF_INET) {
  2313. getnameinfo(&usa->sa,
  2314. sizeof(usa->sin),
  2315. buf,
  2316. (unsigned)len,
  2317. NULL,
  2318. 0,
  2319. NI_NUMERICHOST);
  2320. }
  2321. #if defined(USE_IPV6)
  2322. else if (usa->sa.sa_family == AF_INET6) {
  2323. getnameinfo(&usa->sa,
  2324. sizeof(usa->sin6),
  2325. buf,
  2326. (unsigned)len,
  2327. NULL,
  2328. 0,
  2329. NI_NUMERICHOST);
  2330. }
  2331. #endif
  2332. }
  2333. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  2334. * included in all responses other than 100, 101, 5xx. */
  2335. static void
  2336. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  2337. {
  2338. struct tm *tm;
  2339. tm = ((t != NULL) ? gmtime(t) : NULL);
  2340. if (tm != NULL) {
  2341. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  2342. } else {
  2343. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  2344. buf[buf_len - 1] = '\0';
  2345. }
  2346. }
  2347. /* difftime for struct timespec. Return value is in seconds. */
  2348. static double
  2349. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  2350. {
  2351. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  2352. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  2353. }
  2354. /* Print error message to the opened error log stream. */
  2355. void
  2356. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  2357. {
  2358. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  2359. va_list ap;
  2360. struct mg_file fi;
  2361. time_t timestamp;
  2362. va_start(ap, fmt);
  2363. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  2364. va_end(ap);
  2365. buf[sizeof(buf) - 1] = 0;
  2366. if (!conn) {
  2367. puts(buf);
  2368. return;
  2369. }
  2370. /* Do not lock when getting the callback value, here and below.
  2371. * I suppose this is fine, since function cannot disappear in the
  2372. * same way string option can. */
  2373. if ((conn->ctx->callbacks.log_message == NULL)
  2374. || (conn->ctx->callbacks.log_message(conn, buf) == 0)) {
  2375. if (conn->ctx->config[ERROR_LOG_FILE] != NULL) {
  2376. if (mg_fopen(conn,
  2377. conn->ctx->config[ERROR_LOG_FILE],
  2378. MG_FOPEN_MODE_APPEND,
  2379. &fi) == 0) {
  2380. fi.access.fp = NULL;
  2381. }
  2382. } else {
  2383. fi.access.fp = NULL;
  2384. }
  2385. if (fi.access.fp != NULL) {
  2386. flockfile(fi.access.fp);
  2387. timestamp = time(NULL);
  2388. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  2389. fprintf(fi.access.fp,
  2390. "[%010lu] [error] [client %s] ",
  2391. (unsigned long)timestamp,
  2392. src_addr);
  2393. if (conn->request_info.request_method != NULL) {
  2394. fprintf(fi.access.fp,
  2395. "%s %s: ",
  2396. conn->request_info.request_method,
  2397. conn->request_info.request_uri);
  2398. }
  2399. fprintf(fi.access.fp, "%s", buf);
  2400. fputc('\n', fi.access.fp);
  2401. fflush(fi.access.fp);
  2402. funlockfile(fi.access.fp);
  2403. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  2404. * mg_cry here anyway ;-) */
  2405. }
  2406. }
  2407. }
  2408. /* Return fake connection structure. Used for logging, if connection
  2409. * is not applicable at the moment of logging. */
  2410. static struct mg_connection *
  2411. fc(struct mg_context *ctx)
  2412. {
  2413. static struct mg_connection fake_connection;
  2414. fake_connection.ctx = ctx;
  2415. return &fake_connection;
  2416. }
  2417. const char *
  2418. mg_version(void)
  2419. {
  2420. return CIVETWEB_VERSION;
  2421. }
  2422. const struct mg_request_info *
  2423. mg_get_request_info(const struct mg_connection *conn)
  2424. {
  2425. if (!conn) {
  2426. return NULL;
  2427. }
  2428. return &conn->request_info;
  2429. }
  2430. int
  2431. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  2432. {
  2433. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  2434. return -1;
  2435. } else {
  2436. int truncated = 0;
  2437. const struct mg_request_info *ri = &conn->request_info;
  2438. #ifdef __clang__
  2439. #pragma clang diagnostic push
  2440. #pragma clang diagnostic ignored "-Wunreachable-code"
  2441. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  2442. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  2443. * unreachable, but splitting into four different #ifdef clauses here is more
  2444. * complicated.
  2445. */
  2446. #endif
  2447. const char *proto =
  2448. (is_websocket_protocol(conn) ? (ri->is_ssl ? "wss" : "ws")
  2449. : (ri->is_ssl ? "https" : "http"));
  2450. #ifdef __clang__
  2451. #pragma clang diagnostic pop
  2452. #endif
  2453. if (ri->local_uri == NULL) {
  2454. return -1;
  2455. }
  2456. if ((ri->request_uri != NULL)
  2457. && strcmp(ri->local_uri, ri->request_uri)) {
  2458. mg_snprintf(conn,
  2459. &truncated,
  2460. buf,
  2461. buflen,
  2462. "%s://%s",
  2463. proto,
  2464. ri->request_uri);
  2465. if (truncated) {
  2466. return -1;
  2467. }
  2468. return 0;
  2469. } else {
  2470. #if defined(USE_IPV6)
  2471. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  2472. int port = is_ipv6 ? htons(conn->client.lsa.sin6.sin6_port)
  2473. : htons(conn->client.lsa.sin.sin_port);
  2474. #else
  2475. int port = htons(conn->client.lsa.sin.sin_port);
  2476. #endif
  2477. int def_port = ri->is_ssl ? 443 : 80;
  2478. int auth_domain_check_enabled =
  2479. conn->ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  2480. && (!strcmp(conn->ctx->config[ENABLE_AUTH_DOMAIN_CHECK],
  2481. "yes"));
  2482. const char *server_domain =
  2483. conn->ctx->config[AUTHENTICATION_DOMAIN];
  2484. char portstr[16];
  2485. char server_ip[48];
  2486. if (port != def_port) {
  2487. sprintf(portstr, ":%u", (unsigned)port);
  2488. } else {
  2489. portstr[0] = 0;
  2490. }
  2491. if (!auth_domain_check_enabled || !server_domain) {
  2492. sockaddr_to_string(server_ip,
  2493. sizeof(server_ip),
  2494. &conn->client.lsa);
  2495. server_domain = server_ip;
  2496. }
  2497. mg_snprintf(conn,
  2498. &truncated,
  2499. buf,
  2500. buflen,
  2501. "%s://%s%s%s",
  2502. proto,
  2503. server_domain,
  2504. portstr,
  2505. ri->local_uri);
  2506. if (truncated) {
  2507. return -1;
  2508. }
  2509. return 0;
  2510. }
  2511. }
  2512. }
  2513. /* Skip the characters until one of the delimiters characters found.
  2514. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  2515. * Advance pointer to buffer to the next word. Return found 0-terminated word.
  2516. * Delimiters can be quoted with quotechar. */
  2517. static char *
  2518. skip_quoted(char **buf,
  2519. const char *delimiters,
  2520. const char *whitespace,
  2521. char quotechar)
  2522. {
  2523. char *p, *begin_word, *end_word, *end_whitespace;
  2524. begin_word = *buf;
  2525. end_word = begin_word + strcspn(begin_word, delimiters);
  2526. /* Check for quotechar */
  2527. if (end_word > begin_word) {
  2528. p = end_word - 1;
  2529. while (*p == quotechar) {
  2530. /* While the delimiter is quoted, look for the next delimiter. */
  2531. /* This happens, e.g., in calls from parse_auth_header,
  2532. * if the user name contains a " character. */
  2533. /* If there is anything beyond end_word, copy it. */
  2534. if (*end_word != '\0') {
  2535. size_t end_off = strcspn(end_word + 1, delimiters);
  2536. memmove(p, end_word, end_off + 1);
  2537. p += end_off; /* p must correspond to end_word - 1 */
  2538. end_word += end_off + 1;
  2539. } else {
  2540. *p = '\0';
  2541. break;
  2542. }
  2543. }
  2544. for (p++; p < end_word; p++) {
  2545. *p = '\0';
  2546. }
  2547. }
  2548. if (*end_word == '\0') {
  2549. *buf = end_word;
  2550. } else {
  2551. #if defined(__GNUC__) || defined(__MINGW32__)
  2552. /* Disable spurious conversion warning for GCC */
  2553. #pragma GCC diagnostic push
  2554. #pragma GCC diagnostic ignored "-Wsign-conversion"
  2555. #endif
  2556. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  2557. #if defined(__GNUC__) || defined(__MINGW32__)
  2558. #pragma GCC diagnostic pop
  2559. #endif
  2560. for (p = end_word; p < end_whitespace; p++) {
  2561. *p = '\0';
  2562. }
  2563. *buf = end_whitespace;
  2564. }
  2565. return begin_word;
  2566. }
  2567. /* Simplified version of skip_quoted without quote char
  2568. * and whitespace == delimiters */
  2569. static char *
  2570. skip(char **buf, const char *delimiters)
  2571. {
  2572. return skip_quoted(buf, delimiters, delimiters, 0);
  2573. }
  2574. /* Return HTTP header value, or NULL if not found. */
  2575. static const char *
  2576. get_header(const struct mg_request_info *ri, const char *name)
  2577. {
  2578. int i;
  2579. if (ri) {
  2580. for (i = 0; i < ri->num_headers; i++) {
  2581. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  2582. return ri->http_headers[i].value;
  2583. }
  2584. }
  2585. }
  2586. return NULL;
  2587. }
  2588. const char *
  2589. mg_get_header(const struct mg_connection *conn, const char *name)
  2590. {
  2591. if (!conn) {
  2592. return NULL;
  2593. }
  2594. return get_header(&conn->request_info, name);
  2595. }
  2596. /* A helper function for traversing a comma separated list of values.
  2597. * It returns a list pointer shifted to the next value, or NULL if the end
  2598. * of the list found.
  2599. * Value is stored in val vector. If value has form "x=y", then eq_val
  2600. * vector is initialized to point to the "y" part, and val vector length
  2601. * is adjusted to point only to "x". */
  2602. static const char *
  2603. next_option(const char *list, struct vec *val, struct vec *eq_val)
  2604. {
  2605. int end;
  2606. reparse:
  2607. if (val == NULL || list == NULL || *list == '\0') {
  2608. /* End of the list */
  2609. list = NULL;
  2610. } else {
  2611. /* Skip over leading LWS */
  2612. while (*list == ' ' || *list == '\t')
  2613. list++;
  2614. val->ptr = list;
  2615. if ((list = strchr(val->ptr, ',')) != NULL) {
  2616. /* Comma found. Store length and shift the list ptr */
  2617. val->len = ((size_t)(list - val->ptr));
  2618. list++;
  2619. } else {
  2620. /* This value is the last one */
  2621. list = val->ptr + strlen(val->ptr);
  2622. val->len = ((size_t)(list - val->ptr));
  2623. }
  2624. /* Adjust length for trailing LWS */
  2625. end = (int)val->len - 1;
  2626. while (end >= 0 && (val->ptr[end] == ' ' || val->ptr[end] == '\t'))
  2627. end--;
  2628. val->len = (size_t)(end + 1);
  2629. if (val->len == 0) {
  2630. /* Ignore any empty entries. */
  2631. goto reparse;
  2632. }
  2633. if (eq_val != NULL) {
  2634. /* Value has form "x=y", adjust pointers and lengths
  2635. * so that val points to "x", and eq_val points to "y". */
  2636. eq_val->len = 0;
  2637. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  2638. if (eq_val->ptr != NULL) {
  2639. eq_val->ptr++; /* Skip over '=' character */
  2640. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  2641. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  2642. }
  2643. }
  2644. }
  2645. return list;
  2646. }
  2647. /* A helper function for checking if a comma separated list of values contains
  2648. * the given option (case insensitvely).
  2649. * 'header' can be NULL, in which case false is returned. */
  2650. static int
  2651. header_has_option(const char *header, const char *option)
  2652. {
  2653. struct vec opt_vec;
  2654. struct vec eq_vec;
  2655. assert(option != NULL);
  2656. assert(option[0] != '\0');
  2657. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  2658. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  2659. return 1;
  2660. }
  2661. return 0;
  2662. }
  2663. /* Perform case-insensitive match of string against pattern */
  2664. static int
  2665. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  2666. {
  2667. const char *or_str;
  2668. size_t i;
  2669. int j, len, res;
  2670. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  2671. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  2672. return (res > 0) ? res : match_prefix(or_str + 1,
  2673. (size_t)((pattern + pattern_len)
  2674. - (or_str + 1)),
  2675. str);
  2676. }
  2677. for (i = 0, j = 0; i < pattern_len; i++, j++) {
  2678. if (pattern[i] == '?' && str[j] != '\0') {
  2679. continue;
  2680. } else if (pattern[i] == '$') {
  2681. return (str[j] == '\0') ? j : -1;
  2682. } else if (pattern[i] == '*') {
  2683. i++;
  2684. if (pattern[i] == '*') {
  2685. i++;
  2686. len = (int)strlen(str + j);
  2687. } else {
  2688. len = (int)strcspn(str + j, "/");
  2689. }
  2690. if (i == pattern_len) {
  2691. return j + len;
  2692. }
  2693. do {
  2694. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  2695. } while (res == -1 && len-- > 0);
  2696. return (res == -1) ? -1 : j + res + len;
  2697. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  2698. return -1;
  2699. }
  2700. }
  2701. return j;
  2702. }
  2703. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  2704. * This function must tolerate situations when connection info is not
  2705. * set up, for example if request parsing failed. */
  2706. static int
  2707. should_keep_alive(const struct mg_connection *conn)
  2708. {
  2709. if (conn != NULL) {
  2710. const char *http_version = conn->request_info.http_version;
  2711. const char *header = mg_get_header(conn, "Connection");
  2712. if (conn->must_close || conn->status_code == 401
  2713. || mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0
  2714. || (header != NULL && !header_has_option(header, "keep-alive"))
  2715. || (header == NULL && http_version
  2716. && 0 != strcmp(http_version, "1.1"))) {
  2717. return 0;
  2718. }
  2719. return 1;
  2720. }
  2721. return 0;
  2722. }
  2723. static int
  2724. should_decode_url(const struct mg_connection *conn)
  2725. {
  2726. if (!conn || !conn->ctx) {
  2727. return 0;
  2728. }
  2729. return (mg_strcasecmp(conn->ctx->config[DECODE_URL], "yes") == 0);
  2730. }
  2731. static const char *
  2732. suggest_connection_header(const struct mg_connection *conn)
  2733. {
  2734. return should_keep_alive(conn) ? "keep-alive" : "close";
  2735. }
  2736. static int
  2737. send_no_cache_header(struct mg_connection *conn)
  2738. {
  2739. /* Send all current and obsolete cache opt-out directives. */
  2740. return mg_printf(conn,
  2741. "Cache-Control: no-cache, no-store, "
  2742. "must-revalidate, private, max-age=0\r\n"
  2743. "Pragma: no-cache\r\n"
  2744. "Expires: 0\r\n");
  2745. }
  2746. static int
  2747. send_static_cache_header(struct mg_connection *conn)
  2748. {
  2749. #if !defined(NO_CACHING)
  2750. /* Read the server config to check how long a file may be cached.
  2751. * The configuration is in seconds. */
  2752. int max_age = atoi(conn->ctx->config[STATIC_FILE_MAX_AGE]);
  2753. if (max_age <= 0) {
  2754. /* 0 means "do not cache". All values <0 are reserved
  2755. * and may be used differently in the future. */
  2756. /* If a file should not be cached, do not only send
  2757. * max-age=0, but also pragmas and Expires headers. */
  2758. return send_no_cache_header(conn);
  2759. }
  2760. /* Use "Cache-Control: max-age" instead of "Expires" header.
  2761. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  2762. /* See also https://www.mnot.net/cache_docs/ */
  2763. /* According to RFC 2616, Section 14.21, caching times should not exceed
  2764. * one year. A year with 365 days corresponds to 31536000 seconds, a leap
  2765. * year to 31622400 seconds. For the moment, we just send whatever has
  2766. * been configured, still the behavior for >1 year should be considered
  2767. * as undefined. */
  2768. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  2769. #else /* NO_CACHING */
  2770. return send_no_cache_header(conn);
  2771. #endif /* !NO_CACHING */
  2772. }
  2773. static int
  2774. send_additional_header(struct mg_connection *conn)
  2775. {
  2776. int i = 0;
  2777. #if 0
  2778. i += mg_printf(conn, "Strict-Transport-Security: max-age=%u\r\n", 3600);
  2779. #endif
  2780. i += mg_printf(conn, "X-Some-Test-Header: %u\r\n", 42);
  2781. return i;
  2782. }
  2783. static void handle_file_based_request(struct mg_connection *conn,
  2784. const char *path,
  2785. struct mg_file *filep);
  2786. const char *
  2787. mg_get_response_code_text(struct mg_connection *conn, int response_code)
  2788. {
  2789. /* See IANA HTTP status code assignment:
  2790. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  2791. */
  2792. switch (response_code) {
  2793. /* RFC2616 Section 10.1 - Informational 1xx */
  2794. case 100:
  2795. return "Continue"; /* RFC2616 Section 10.1.1 */
  2796. case 101:
  2797. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  2798. case 102:
  2799. return "Processing"; /* RFC2518 Section 10.1 */
  2800. /* RFC2616 Section 10.2 - Successful 2xx */
  2801. case 200:
  2802. return "OK"; /* RFC2616 Section 10.2.1 */
  2803. case 201:
  2804. return "Created"; /* RFC2616 Section 10.2.2 */
  2805. case 202:
  2806. return "Accepted"; /* RFC2616 Section 10.2.3 */
  2807. case 203:
  2808. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  2809. case 204:
  2810. return "No Content"; /* RFC2616 Section 10.2.5 */
  2811. case 205:
  2812. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  2813. case 206:
  2814. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  2815. case 207:
  2816. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1 */
  2817. case 208:
  2818. return "Already Reported"; /* RFC5842 Section 7.1 */
  2819. case 226:
  2820. return "IM used"; /* RFC3229 Section 10.4.1 */
  2821. /* RFC2616 Section 10.3 - Redirection 3xx */
  2822. case 300:
  2823. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  2824. case 301:
  2825. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  2826. case 302:
  2827. return "Found"; /* RFC2616 Section 10.3.3 */
  2828. case 303:
  2829. return "See Other"; /* RFC2616 Section 10.3.4 */
  2830. case 304:
  2831. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  2832. case 305:
  2833. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  2834. case 307:
  2835. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  2836. case 308:
  2837. return "Permanent Redirect"; /* RFC7238 Section 3 */
  2838. /* RFC2616 Section 10.4 - Client Error 4xx */
  2839. case 400:
  2840. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  2841. case 401:
  2842. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  2843. case 402:
  2844. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  2845. case 403:
  2846. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  2847. case 404:
  2848. return "Not Found"; /* RFC2616 Section 10.4.5 */
  2849. case 405:
  2850. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  2851. case 406:
  2852. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  2853. case 407:
  2854. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  2855. case 408:
  2856. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  2857. case 409:
  2858. return "Conflict"; /* RFC2616 Section 10.4.10 */
  2859. case 410:
  2860. return "Gone"; /* RFC2616 Section 10.4.11 */
  2861. case 411:
  2862. return "Length Required"; /* RFC2616 Section 10.4.12 */
  2863. case 412:
  2864. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  2865. case 413:
  2866. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  2867. case 414:
  2868. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  2869. case 415:
  2870. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  2871. case 416:
  2872. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17 */
  2873. case 417:
  2874. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  2875. case 421:
  2876. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  2877. case 422:
  2878. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  2879. * Section 11.2 */
  2880. case 423:
  2881. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  2882. case 424:
  2883. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  2884. * Section 11.4 */
  2885. case 426:
  2886. return "Upgrade Required"; /* RFC 2817 Section 4 */
  2887. case 428:
  2888. return "Precondition Required"; /* RFC 6585, Section 3 */
  2889. case 429:
  2890. return "Too Many Requests"; /* RFC 6585, Section 4 */
  2891. case 431:
  2892. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  2893. case 451:
  2894. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  2895. * Section 3 */
  2896. /* RFC2616 Section 10.5 - Server Error 5xx */
  2897. case 500:
  2898. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  2899. case 501:
  2900. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  2901. case 502:
  2902. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  2903. case 503:
  2904. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  2905. case 504:
  2906. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  2907. case 505:
  2908. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  2909. case 506:
  2910. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  2911. case 507:
  2912. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  2913. * Section 11.5 */
  2914. case 508:
  2915. return "Loop Detected"; /* RFC5842 Section 7.1 */
  2916. case 510:
  2917. return "Not Extended"; /* RFC 2774, Section 7 */
  2918. case 511:
  2919. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  2920. /* Other status codes, not shown in the IANA HTTP status code assignment.
  2921. * E.g., "de facto" standards due to common use, ... */
  2922. case 418:
  2923. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  2924. case 419:
  2925. return "Authentication Timeout"; /* common use */
  2926. case 420:
  2927. return "Enhance Your Calm"; /* common use */
  2928. case 440:
  2929. return "Login Timeout"; /* common use */
  2930. case 509:
  2931. return "Bandwidth Limit Exceeded"; /* common use */
  2932. default:
  2933. /* This error code is unknown. This should not happen. */
  2934. if (conn) {
  2935. mg_cry(conn, "Unknown HTTP response code: %u", response_code);
  2936. }
  2937. /* Return at least a category according to RFC 2616 Section 10. */
  2938. if (response_code >= 100 && response_code < 200) {
  2939. /* Unknown informational status code */
  2940. return "Information";
  2941. }
  2942. if (response_code >= 200 && response_code < 300) {
  2943. /* Unknown success code */
  2944. return "Success";
  2945. }
  2946. if (response_code >= 300 && response_code < 400) {
  2947. /* Unknown redirection code */
  2948. return "Redirection";
  2949. }
  2950. if (response_code >= 400 && response_code < 500) {
  2951. /* Unknown request error code */
  2952. return "Client Error";
  2953. }
  2954. if (response_code >= 500 && response_code < 600) {
  2955. /* Unknown server error code */
  2956. return "Server Error";
  2957. }
  2958. /* Response code not even within reasonable range */
  2959. return "";
  2960. }
  2961. }
  2962. static void send_http_error(struct mg_connection *,
  2963. int,
  2964. PRINTF_FORMAT_STRING(const char *fmt),
  2965. ...) PRINTF_ARGS(3, 4);
  2966. static void
  2967. send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  2968. {
  2969. char buf[MG_BUF_LEN];
  2970. va_list ap;
  2971. int len, i, page_handler_found, scope, truncated, has_body;
  2972. char date[64];
  2973. time_t curtime = time(NULL);
  2974. const char *error_handler = NULL;
  2975. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  2976. const char *error_page_file_ext, *tstr;
  2977. const char *status_text = mg_get_response_code_text(conn, status);
  2978. if (conn == NULL) {
  2979. return;
  2980. }
  2981. conn->status_code = status;
  2982. if (conn->in_error_handler || conn->ctx->callbacks.http_error == NULL
  2983. || conn->ctx->callbacks.http_error(conn, status)) {
  2984. if (!conn->in_error_handler) {
  2985. /* Send user defined error pages, if defined */
  2986. error_handler = conn->ctx->config[ERROR_PAGES];
  2987. error_page_file_ext = conn->ctx->config[INDEX_FILES];
  2988. page_handler_found = 0;
  2989. if (error_handler != NULL) {
  2990. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  2991. switch (scope) {
  2992. case 1: /* Handler for specific error, e.g. 404 error */
  2993. mg_snprintf(conn,
  2994. &truncated,
  2995. buf,
  2996. sizeof(buf) - 32,
  2997. "%serror%03u.",
  2998. error_handler,
  2999. status);
  3000. break;
  3001. case 2: /* Handler for error group, e.g., 5xx error handler
  3002. * for all server errors (500-599) */
  3003. mg_snprintf(conn,
  3004. &truncated,
  3005. buf,
  3006. sizeof(buf) - 32,
  3007. "%serror%01uxx.",
  3008. error_handler,
  3009. status / 100);
  3010. break;
  3011. default: /* Handler for all errors */
  3012. mg_snprintf(conn,
  3013. &truncated,
  3014. buf,
  3015. sizeof(buf) - 32,
  3016. "%serror.",
  3017. error_handler);
  3018. break;
  3019. }
  3020. /* String truncation in buf may only occur if error_handler
  3021. * is too long. This string is from the config, not from a
  3022. * client. */
  3023. (void)truncated;
  3024. len = (int)strlen(buf);
  3025. tstr = strchr(error_page_file_ext, '.');
  3026. while (tstr) {
  3027. for (i = 1; i < 32 && tstr[i] != 0 && tstr[i] != ',';
  3028. i++)
  3029. buf[len + i - 1] = tstr[i];
  3030. buf[len + i - 1] = 0;
  3031. if (mg_stat(conn, buf, &error_page_file.stat)) {
  3032. page_handler_found = 1;
  3033. break;
  3034. }
  3035. tstr = strchr(tstr + i, '.');
  3036. }
  3037. }
  3038. }
  3039. if (page_handler_found) {
  3040. conn->in_error_handler = 1;
  3041. handle_file_based_request(conn, buf, &error_page_file);
  3042. conn->in_error_handler = 0;
  3043. return;
  3044. }
  3045. }
  3046. /* No custom error page. Send default error page. */
  3047. gmt_time_string(date, sizeof(date), &curtime);
  3048. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3049. has_body = (status > 199 && status != 204 && status != 304);
  3050. conn->must_close = 1;
  3051. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  3052. send_no_cache_header(conn);
  3053. send_additional_header(conn);
  3054. if (has_body) {
  3055. mg_printf(conn,
  3056. "%s",
  3057. "Content-Type: text/plain; charset=utf-8\r\n");
  3058. }
  3059. mg_printf(conn,
  3060. "Date: %s\r\n"
  3061. "Connection: close\r\n\r\n",
  3062. date);
  3063. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3064. if (has_body) {
  3065. mg_printf(conn, "Error %d: %s\n", status, status_text);
  3066. if (fmt != NULL) {
  3067. va_start(ap, fmt);
  3068. mg_vsnprintf(conn, NULL, buf, sizeof(buf), fmt, ap);
  3069. va_end(ap);
  3070. mg_write(conn, buf, strlen(buf));
  3071. DEBUG_TRACE("Error %i - [%s]", status, buf);
  3072. }
  3073. } else {
  3074. /* No body allowed. Close the connection. */
  3075. DEBUG_TRACE("Error %i", status);
  3076. }
  3077. }
  3078. }
  3079. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  3080. /* Create substitutes for POSIX functions in Win32. */
  3081. #if defined(__MINGW32__)
  3082. /* Show no warning in case system functions are not used. */
  3083. #pragma GCC diagnostic push
  3084. #pragma GCC diagnostic ignored "-Wunused-function"
  3085. #endif
  3086. static int
  3087. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  3088. {
  3089. (void)unused;
  3090. *mutex = CreateMutex(NULL, FALSE, NULL);
  3091. return (*mutex == NULL) ? -1 : 0;
  3092. }
  3093. static int
  3094. pthread_mutex_destroy(pthread_mutex_t *mutex)
  3095. {
  3096. return (CloseHandle(*mutex) == 0) ? -1 : 0;
  3097. }
  3098. static int
  3099. pthread_mutex_lock(pthread_mutex_t *mutex)
  3100. {
  3101. return (WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0) ? 0 : -1;
  3102. }
  3103. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  3104. static int
  3105. pthread_mutex_trylock(pthread_mutex_t *mutex)
  3106. {
  3107. switch (WaitForSingleObject(*mutex, 0)) {
  3108. case WAIT_OBJECT_0:
  3109. return 0;
  3110. case WAIT_TIMEOUT:
  3111. return -2; /* EBUSY */
  3112. }
  3113. return -1;
  3114. }
  3115. #endif
  3116. static int
  3117. pthread_mutex_unlock(pthread_mutex_t *mutex)
  3118. {
  3119. return (ReleaseMutex(*mutex) == 0) ? -1 : 0;
  3120. }
  3121. static int
  3122. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  3123. {
  3124. (void)unused;
  3125. InitializeCriticalSection(&cv->threadIdSec);
  3126. cv->waiting_thread = NULL;
  3127. return 0;
  3128. }
  3129. static int
  3130. pthread_cond_timedwait(pthread_cond_t *cv,
  3131. pthread_mutex_t *mutex,
  3132. const struct timespec *abstime)
  3133. {
  3134. struct mg_workerTLS **ptls,
  3135. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3136. int ok;
  3137. int64_t nsnow, nswaitabs, nswaitrel;
  3138. DWORD mswaitrel;
  3139. EnterCriticalSection(&cv->threadIdSec);
  3140. /* Add this thread to cv's waiting list */
  3141. ptls = &cv->waiting_thread;
  3142. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  3143. ;
  3144. tls->next_waiting_thread = NULL;
  3145. *ptls = tls;
  3146. LeaveCriticalSection(&cv->threadIdSec);
  3147. if (abstime) {
  3148. nsnow = mg_get_current_time_ns();
  3149. nswaitabs =
  3150. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  3151. nswaitrel = nswaitabs - nsnow;
  3152. if (nswaitrel < 0) {
  3153. nswaitrel = 0;
  3154. }
  3155. mswaitrel = (DWORD)(nswaitrel / 1000000);
  3156. } else {
  3157. mswaitrel = INFINITE;
  3158. }
  3159. pthread_mutex_unlock(mutex);
  3160. ok = (WAIT_OBJECT_0
  3161. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  3162. if (!ok) {
  3163. ok = 1;
  3164. EnterCriticalSection(&cv->threadIdSec);
  3165. ptls = &cv->waiting_thread;
  3166. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  3167. if (*ptls == tls) {
  3168. *ptls = tls->next_waiting_thread;
  3169. ok = 0;
  3170. break;
  3171. }
  3172. }
  3173. LeaveCriticalSection(&cv->threadIdSec);
  3174. if (ok) {
  3175. WaitForSingleObject(tls->pthread_cond_helper_mutex, INFINITE);
  3176. }
  3177. }
  3178. /* This thread has been removed from cv's waiting list */
  3179. pthread_mutex_lock(mutex);
  3180. return ok ? 0 : -1;
  3181. }
  3182. static int
  3183. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  3184. {
  3185. return pthread_cond_timedwait(cv, mutex, NULL);
  3186. }
  3187. static int
  3188. pthread_cond_signal(pthread_cond_t *cv)
  3189. {
  3190. HANDLE wkup = NULL;
  3191. BOOL ok = FALSE;
  3192. EnterCriticalSection(&cv->threadIdSec);
  3193. if (cv->waiting_thread) {
  3194. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  3195. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  3196. ok = SetEvent(wkup);
  3197. assert(ok);
  3198. }
  3199. LeaveCriticalSection(&cv->threadIdSec);
  3200. return ok ? 0 : 1;
  3201. }
  3202. static int
  3203. pthread_cond_broadcast(pthread_cond_t *cv)
  3204. {
  3205. EnterCriticalSection(&cv->threadIdSec);
  3206. while (cv->waiting_thread) {
  3207. pthread_cond_signal(cv);
  3208. }
  3209. LeaveCriticalSection(&cv->threadIdSec);
  3210. return 0;
  3211. }
  3212. static int
  3213. pthread_cond_destroy(pthread_cond_t *cv)
  3214. {
  3215. EnterCriticalSection(&cv->threadIdSec);
  3216. assert(cv->waiting_thread == NULL);
  3217. LeaveCriticalSection(&cv->threadIdSec);
  3218. DeleteCriticalSection(&cv->threadIdSec);
  3219. return 0;
  3220. }
  3221. #ifdef ALTERNATIVE_QUEUE
  3222. static void *
  3223. event_create(void)
  3224. {
  3225. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  3226. }
  3227. static int
  3228. event_wait(void *eventhdl)
  3229. {
  3230. int res = WaitForSingleObject((HANDLE)eventhdl, INFINITE);
  3231. return (res == WAIT_OBJECT_0);
  3232. }
  3233. static int
  3234. event_signal(void *eventhdl)
  3235. {
  3236. return (int)SetEvent((HANDLE)eventhdl);
  3237. }
  3238. static void
  3239. event_destroy(void *eventhdl)
  3240. {
  3241. CloseHandle((HANDLE)eventhdl);
  3242. }
  3243. #endif
  3244. #if defined(__MINGW32__)
  3245. /* Enable unused function warning again */
  3246. #pragma GCC diagnostic pop
  3247. #endif
  3248. /* For Windows, change all slashes to backslashes in path names. */
  3249. static void
  3250. change_slashes_to_backslashes(char *path)
  3251. {
  3252. int i;
  3253. for (i = 0; path[i] != '\0'; i++) {
  3254. if (path[i] == '/') {
  3255. path[i] = '\\';
  3256. }
  3257. /* remove double backslash (check i > 0 to preserve UNC paths,
  3258. * like \\server\file.txt) */
  3259. if ((path[i] == '\\') && (i > 0)) {
  3260. while (path[i + 1] == '\\' || path[i + 1] == '/') {
  3261. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  3262. }
  3263. }
  3264. }
  3265. }
  3266. static int
  3267. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  3268. {
  3269. int diff;
  3270. do {
  3271. diff = tolower(*s1) - tolower(*s2);
  3272. s1++;
  3273. s2++;
  3274. } while (diff == 0 && s1[-1] != '\0');
  3275. return diff;
  3276. }
  3277. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  3278. * wbuf and wbuf_len is a target buffer and its length. */
  3279. static void
  3280. path_to_unicode(const struct mg_connection *conn,
  3281. const char *path,
  3282. wchar_t *wbuf,
  3283. size_t wbuf_len)
  3284. {
  3285. char buf[PATH_MAX], buf2[PATH_MAX];
  3286. wchar_t wbuf2[MAX_PATH + 1];
  3287. DWORD long_len, err;
  3288. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  3289. mg_strlcpy(buf, path, sizeof(buf));
  3290. change_slashes_to_backslashes(buf);
  3291. /* Convert to Unicode and back. If doubly-converted string does not
  3292. * match the original, something is fishy, reject. */
  3293. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  3294. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  3295. WideCharToMultiByte(
  3296. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  3297. if (strcmp(buf, buf2) != 0) {
  3298. wbuf[0] = L'\0';
  3299. }
  3300. /* Windows file systems are not case sensitive, but you can still use
  3301. * uppercase and lowercase letters (on all modern file systems).
  3302. * The server can check if the URI uses the same upper/lowercase
  3303. * letters an the file system, effectively making Windows servers
  3304. * case sensitive (like Linux servers are). It is still not possible
  3305. * to use two files with the same name in different cases on Windows
  3306. * (like /a and /A) - this would be possible in Linux.
  3307. * As a default, Windows is not case sensitive, but the case sensitive
  3308. * file name check can be activated by an additional configuration. */
  3309. if (conn) {
  3310. if (conn->ctx->config[CASE_SENSITIVE_FILES]
  3311. && !mg_strcasecmp(conn->ctx->config[CASE_SENSITIVE_FILES], "yes")) {
  3312. /* Use case sensitive compare function */
  3313. fcompare = wcscmp;
  3314. }
  3315. }
  3316. (void)conn; /* conn is currently unused */
  3317. #if !defined(_WIN32_WCE)
  3318. /* Only accept a full file path, not a Windows short (8.3) path. */
  3319. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  3320. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  3321. if (long_len == 0) {
  3322. err = GetLastError();
  3323. if (err == ERROR_FILE_NOT_FOUND) {
  3324. /* File does not exist. This is not always a problem here. */
  3325. return;
  3326. }
  3327. }
  3328. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  3329. /* Short name is used. */
  3330. wbuf[0] = L'\0';
  3331. }
  3332. #else
  3333. (void)long_len;
  3334. (void)wbuf2;
  3335. (void)err;
  3336. if (strchr(path, '~')) {
  3337. wbuf[0] = L'\0';
  3338. }
  3339. #endif
  3340. }
  3341. /* Windows happily opens files with some garbage at the end of file name.
  3342. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  3343. * "a.cgi", despite one would expect an error back.
  3344. * This function returns non-0 if path ends with some garbage. */
  3345. static int
  3346. path_cannot_disclose_cgi(const char *path)
  3347. {
  3348. static const char *allowed_last_characters = "_-";
  3349. int last = path[strlen(path) - 1];
  3350. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  3351. }
  3352. static int
  3353. mg_stat(const struct mg_connection *conn,
  3354. const char *path,
  3355. struct mg_file_stat *filep)
  3356. {
  3357. wchar_t wbuf[PATH_MAX];
  3358. WIN32_FILE_ATTRIBUTE_DATA info;
  3359. time_t creation_time;
  3360. if (!filep) {
  3361. return 0;
  3362. }
  3363. memset(filep, 0, sizeof(*filep));
  3364. if (conn && is_file_in_memory(conn, path)) {
  3365. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  3366. * memset */
  3367. /* Quick fix (for 1.9.x): */
  3368. /* mg_stat must fill all fields, also for files in memory */
  3369. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  3370. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  3371. filep->size = tmp_file.stat.size;
  3372. filep->location = 2;
  3373. /* TODO: for 1.10: restructure how files in memory are handled */
  3374. filep->last_modified = time(NULL); /* xxxxxxxx */
  3375. /* last_modified = now ... assumes the file may change during runtime,
  3376. * so every mg_fopen call may return different data */
  3377. /* last_modified = conn->ctx.start_time;
  3378. * May be used it the data does not change during runtime. This allows
  3379. * browser caching. Since we do not know, we have to assume the file
  3380. * in memory may change. */
  3381. return 1;
  3382. }
  3383. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3384. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  3385. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  3386. filep->last_modified =
  3387. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  3388. info.ftLastWriteTime.dwHighDateTime);
  3389. /* On Windows, the file creation time can be higher than the
  3390. * modification time, e.g. when a file is copied.
  3391. * Since the Last-Modified timestamp is used for caching
  3392. * it should be based on the most recent timestamp. */
  3393. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  3394. info.ftCreationTime.dwHighDateTime);
  3395. if (creation_time > filep->last_modified) {
  3396. filep->last_modified = creation_time;
  3397. }
  3398. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  3399. /* If file name is fishy, reset the file structure and return
  3400. * error.
  3401. * Note it is important to reset, not just return the error, cause
  3402. * functions like is_file_opened() check the struct. */
  3403. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  3404. memset(filep, 0, sizeof(*filep));
  3405. return 0;
  3406. }
  3407. return 1;
  3408. }
  3409. return 0;
  3410. }
  3411. static int
  3412. mg_remove(const struct mg_connection *conn, const char *path)
  3413. {
  3414. wchar_t wbuf[PATH_MAX];
  3415. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3416. return DeleteFileW(wbuf) ? 0 : -1;
  3417. }
  3418. static int
  3419. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  3420. {
  3421. wchar_t wbuf[PATH_MAX];
  3422. (void)mode;
  3423. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3424. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  3425. }
  3426. /* Create substitutes for POSIX functions in Win32. */
  3427. #if defined(__MINGW32__)
  3428. /* Show no warning in case system functions are not used. */
  3429. #pragma GCC diagnostic push
  3430. #pragma GCC diagnostic ignored "-Wunused-function"
  3431. #endif
  3432. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  3433. static DIR *
  3434. mg_opendir(const struct mg_connection *conn, const char *name)
  3435. {
  3436. DIR *dir = NULL;
  3437. wchar_t wpath[PATH_MAX];
  3438. DWORD attrs;
  3439. if (name == NULL) {
  3440. SetLastError(ERROR_BAD_ARGUMENTS);
  3441. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  3442. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  3443. } else {
  3444. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  3445. attrs = GetFileAttributesW(wpath);
  3446. if (attrs != 0xFFFFFFFF && ((attrs & FILE_ATTRIBUTE_DIRECTORY)
  3447. == FILE_ATTRIBUTE_DIRECTORY)) {
  3448. (void)wcscat(wpath, L"\\*");
  3449. dir->handle = FindFirstFileW(wpath, &dir->info);
  3450. dir->result.d_name[0] = '\0';
  3451. } else {
  3452. mg_free(dir);
  3453. dir = NULL;
  3454. }
  3455. }
  3456. return dir;
  3457. }
  3458. static int
  3459. mg_closedir(DIR *dir)
  3460. {
  3461. int result = 0;
  3462. if (dir != NULL) {
  3463. if (dir->handle != INVALID_HANDLE_VALUE)
  3464. result = FindClose(dir->handle) ? 0 : -1;
  3465. mg_free(dir);
  3466. } else {
  3467. result = -1;
  3468. SetLastError(ERROR_BAD_ARGUMENTS);
  3469. }
  3470. return result;
  3471. }
  3472. static struct dirent *
  3473. mg_readdir(DIR *dir)
  3474. {
  3475. struct dirent *result = 0;
  3476. if (dir) {
  3477. if (dir->handle != INVALID_HANDLE_VALUE) {
  3478. result = &dir->result;
  3479. (void)WideCharToMultiByte(CP_UTF8,
  3480. 0,
  3481. dir->info.cFileName,
  3482. -1,
  3483. result->d_name,
  3484. sizeof(result->d_name),
  3485. NULL,
  3486. NULL);
  3487. if (!FindNextFileW(dir->handle, &dir->info)) {
  3488. (void)FindClose(dir->handle);
  3489. dir->handle = INVALID_HANDLE_VALUE;
  3490. }
  3491. } else {
  3492. SetLastError(ERROR_FILE_NOT_FOUND);
  3493. }
  3494. } else {
  3495. SetLastError(ERROR_BAD_ARGUMENTS);
  3496. }
  3497. return result;
  3498. }
  3499. #ifndef HAVE_POLL
  3500. static int
  3501. poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  3502. {
  3503. struct timeval tv;
  3504. fd_set set;
  3505. unsigned int i;
  3506. int result;
  3507. SOCKET maxfd = 0;
  3508. memset(&tv, 0, sizeof(tv));
  3509. tv.tv_sec = milliseconds / 1000;
  3510. tv.tv_usec = (milliseconds % 1000) * 1000;
  3511. FD_ZERO(&set);
  3512. for (i = 0; i < n; i++) {
  3513. FD_SET((SOCKET)pfd[i].fd, &set);
  3514. pfd[i].revents = 0;
  3515. if (pfd[i].fd > maxfd) {
  3516. maxfd = pfd[i].fd;
  3517. }
  3518. }
  3519. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  3520. for (i = 0; i < n; i++) {
  3521. if (FD_ISSET(pfd[i].fd, &set)) {
  3522. pfd[i].revents = POLLIN;
  3523. }
  3524. }
  3525. }
  3526. /* We should subtract the time used in select from remaining
  3527. * "milliseconds", in particular if called from mg_poll with a
  3528. * timeout quantum.
  3529. * Unfortunately, the remaining time is not stored in "tv" in all
  3530. * implementations, so the result in "tv" must be considered undefined.
  3531. * See http://man7.org/linux/man-pages/man2/select.2.html */
  3532. return result;
  3533. }
  3534. #endif /* HAVE_POLL */
  3535. #if defined(__MINGW32__)
  3536. /* Enable unused function warning again */
  3537. #pragma GCC diagnostic pop
  3538. #endif
  3539. static void
  3540. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  3541. {
  3542. (void)conn; /* Unused. */
  3543. #if defined(_WIN32_WCE)
  3544. (void)sock;
  3545. #else
  3546. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  3547. #endif
  3548. }
  3549. int
  3550. mg_start_thread(mg_thread_func_t f, void *p)
  3551. {
  3552. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3553. /* Compile-time option to control stack size, e.g. -DUSE_STACK_SIZE=16384
  3554. */
  3555. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  3556. == ((uintptr_t)(-1L)))
  3557. ? -1
  3558. : 0);
  3559. #else
  3560. return (
  3561. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  3562. ? -1
  3563. : 0);
  3564. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3565. }
  3566. /* Start a thread storing the thread context. */
  3567. static int
  3568. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  3569. void *p,
  3570. pthread_t *threadidptr)
  3571. {
  3572. uintptr_t uip;
  3573. HANDLE threadhandle;
  3574. int result = -1;
  3575. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  3576. threadhandle = (HANDLE)uip;
  3577. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  3578. *threadidptr = threadhandle;
  3579. result = 0;
  3580. }
  3581. return result;
  3582. }
  3583. /* Wait for a thread to finish. */
  3584. static int
  3585. mg_join_thread(pthread_t threadid)
  3586. {
  3587. int result;
  3588. DWORD dwevent;
  3589. result = -1;
  3590. dwevent = WaitForSingleObject(threadid, INFINITE);
  3591. if (dwevent == WAIT_FAILED) {
  3592. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  3593. } else {
  3594. if (dwevent == WAIT_OBJECT_0) {
  3595. CloseHandle(threadid);
  3596. result = 0;
  3597. }
  3598. }
  3599. return result;
  3600. }
  3601. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  3602. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  3603. /* Create substitutes for POSIX functions in Win32. */
  3604. #if defined(__MINGW32__)
  3605. /* Show no warning in case system functions are not used. */
  3606. #pragma GCC diagnostic push
  3607. #pragma GCC diagnostic ignored "-Wunused-function"
  3608. #endif
  3609. static HANDLE
  3610. dlopen(const char *dll_name, int flags)
  3611. {
  3612. wchar_t wbuf[PATH_MAX];
  3613. (void)flags;
  3614. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  3615. return LoadLibraryW(wbuf);
  3616. }
  3617. static int
  3618. dlclose(void *handle)
  3619. {
  3620. int result;
  3621. if (FreeLibrary((HMODULE)handle) != 0) {
  3622. result = 0;
  3623. } else {
  3624. result = -1;
  3625. }
  3626. return result;
  3627. }
  3628. #if defined(__MINGW32__)
  3629. /* Enable unused function warning again */
  3630. #pragma GCC diagnostic pop
  3631. #endif
  3632. #endif
  3633. #if !defined(NO_CGI)
  3634. #define SIGKILL (0)
  3635. static int
  3636. kill(pid_t pid, int sig_num)
  3637. {
  3638. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  3639. (void)CloseHandle((HANDLE)pid);
  3640. return 0;
  3641. }
  3642. static void
  3643. trim_trailing_whitespaces(char *s)
  3644. {
  3645. char *e = s + strlen(s) - 1;
  3646. while (e > s && isspace(*(unsigned char *)e)) {
  3647. *e-- = '\0';
  3648. }
  3649. }
  3650. static pid_t
  3651. spawn_process(struct mg_connection *conn,
  3652. const char *prog,
  3653. char *envblk,
  3654. char *envp[],
  3655. int fdin[2],
  3656. int fdout[2],
  3657. int fderr[2],
  3658. const char *dir)
  3659. {
  3660. HANDLE me;
  3661. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  3662. cmdline[PATH_MAX], buf[PATH_MAX];
  3663. int truncated;
  3664. struct mg_file file = STRUCT_FILE_INITIALIZER;
  3665. STARTUPINFOA si;
  3666. PROCESS_INFORMATION pi = {0};
  3667. (void)envp;
  3668. memset(&si, 0, sizeof(si));
  3669. si.cb = sizeof(si);
  3670. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  3671. si.wShowWindow = SW_HIDE;
  3672. me = GetCurrentProcess();
  3673. DuplicateHandle(me,
  3674. (HANDLE)_get_osfhandle(fdin[0]),
  3675. me,
  3676. &si.hStdInput,
  3677. 0,
  3678. TRUE,
  3679. DUPLICATE_SAME_ACCESS);
  3680. DuplicateHandle(me,
  3681. (HANDLE)_get_osfhandle(fdout[1]),
  3682. me,
  3683. &si.hStdOutput,
  3684. 0,
  3685. TRUE,
  3686. DUPLICATE_SAME_ACCESS);
  3687. DuplicateHandle(me,
  3688. (HANDLE)_get_osfhandle(fderr[1]),
  3689. me,
  3690. &si.hStdError,
  3691. 0,
  3692. TRUE,
  3693. DUPLICATE_SAME_ACCESS);
  3694. /* Mark handles that should not be inherited. See
  3695. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  3696. */
  3697. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  3698. HANDLE_FLAG_INHERIT,
  3699. 0);
  3700. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  3701. HANDLE_FLAG_INHERIT,
  3702. 0);
  3703. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  3704. HANDLE_FLAG_INHERIT,
  3705. 0);
  3706. /* If CGI file is a script, try to read the interpreter line */
  3707. interp = conn->ctx->config[CGI_INTERPRETER];
  3708. if (interp == NULL) {
  3709. buf[0] = buf[1] = '\0';
  3710. /* Read the first line of the script into the buffer */
  3711. mg_snprintf(
  3712. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  3713. if (truncated) {
  3714. pi.hProcess = (pid_t)-1;
  3715. goto spawn_cleanup;
  3716. }
  3717. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  3718. p = (char *)file.access.membuf;
  3719. mg_fgets(buf, sizeof(buf), &file, &p);
  3720. (void)mg_fclose(&file.access); /* ignore error on read only file */
  3721. buf[sizeof(buf) - 1] = '\0';
  3722. }
  3723. if (buf[0] == '#' && buf[1] == '!') {
  3724. trim_trailing_whitespaces(buf + 2);
  3725. } else {
  3726. buf[2] = '\0';
  3727. }
  3728. interp = buf + 2;
  3729. }
  3730. if (interp[0] != '\0') {
  3731. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  3732. interp = full_interp;
  3733. }
  3734. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  3735. if (interp[0] != '\0') {
  3736. mg_snprintf(conn,
  3737. &truncated,
  3738. cmdline,
  3739. sizeof(cmdline),
  3740. "\"%s\" \"%s\\%s\"",
  3741. interp,
  3742. full_dir,
  3743. prog);
  3744. } else {
  3745. mg_snprintf(conn,
  3746. &truncated,
  3747. cmdline,
  3748. sizeof(cmdline),
  3749. "\"%s\\%s\"",
  3750. full_dir,
  3751. prog);
  3752. }
  3753. if (truncated) {
  3754. pi.hProcess = (pid_t)-1;
  3755. goto spawn_cleanup;
  3756. }
  3757. DEBUG_TRACE("Running [%s]", cmdline);
  3758. if (CreateProcessA(NULL,
  3759. cmdline,
  3760. NULL,
  3761. NULL,
  3762. TRUE,
  3763. CREATE_NEW_PROCESS_GROUP,
  3764. envblk,
  3765. NULL,
  3766. &si,
  3767. &pi) == 0) {
  3768. mg_cry(
  3769. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  3770. pi.hProcess = (pid_t)-1;
  3771. /* goto spawn_cleanup; */
  3772. }
  3773. spawn_cleanup:
  3774. (void)CloseHandle(si.hStdOutput);
  3775. (void)CloseHandle(si.hStdError);
  3776. (void)CloseHandle(si.hStdInput);
  3777. if (pi.hThread != NULL) {
  3778. (void)CloseHandle(pi.hThread);
  3779. }
  3780. return (pid_t)pi.hProcess;
  3781. }
  3782. #endif /* !NO_CGI */
  3783. static int
  3784. set_blocking_mode(SOCKET sock, int blocking)
  3785. {
  3786. unsigned long non_blocking = !blocking;
  3787. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  3788. }
  3789. #else
  3790. static int
  3791. mg_stat(const struct mg_connection *conn,
  3792. const char *path,
  3793. struct mg_file_stat *filep)
  3794. {
  3795. struct stat st;
  3796. if (!filep) {
  3797. return 0;
  3798. }
  3799. memset(filep, 0, sizeof(*filep));
  3800. if (conn && is_file_in_memory(conn, path)) {
  3801. /* Quick fix (for 1.9.x): */
  3802. /* mg_stat must fill all fields, also for files in memory */
  3803. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  3804. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  3805. filep->size = tmp_file.stat.size;
  3806. filep->last_modified = time(NULL);
  3807. filep->location = 2;
  3808. /* TODO: for 1.10: restructure how files in memory are handled */
  3809. return 1;
  3810. }
  3811. if (0 == stat(path, &st)) {
  3812. filep->size = (uint64_t)(st.st_size);
  3813. filep->last_modified = st.st_mtime;
  3814. filep->is_directory = S_ISDIR(st.st_mode);
  3815. return 1;
  3816. }
  3817. return 0;
  3818. }
  3819. static void
  3820. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  3821. {
  3822. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  3823. if (conn) {
  3824. mg_cry(conn,
  3825. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  3826. __func__,
  3827. strerror(ERRNO));
  3828. }
  3829. }
  3830. }
  3831. int
  3832. mg_start_thread(mg_thread_func_t func, void *param)
  3833. {
  3834. pthread_t thread_id;
  3835. pthread_attr_t attr;
  3836. int result;
  3837. (void)pthread_attr_init(&attr);
  3838. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  3839. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3840. /* Compile-time option to control stack size,
  3841. * e.g. -DUSE_STACK_SIZE=16384 */
  3842. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3843. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3844. result = pthread_create(&thread_id, &attr, func, param);
  3845. pthread_attr_destroy(&attr);
  3846. return result;
  3847. }
  3848. /* Start a thread storing the thread context. */
  3849. static int
  3850. mg_start_thread_with_id(mg_thread_func_t func,
  3851. void *param,
  3852. pthread_t *threadidptr)
  3853. {
  3854. pthread_t thread_id;
  3855. pthread_attr_t attr;
  3856. int result;
  3857. (void)pthread_attr_init(&attr);
  3858. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3859. /* Compile-time option to control stack size,
  3860. * e.g. -DUSE_STACK_SIZE=16384 */
  3861. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3862. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  3863. result = pthread_create(&thread_id, &attr, func, param);
  3864. pthread_attr_destroy(&attr);
  3865. if ((result == 0) && (threadidptr != NULL)) {
  3866. *threadidptr = thread_id;
  3867. }
  3868. return result;
  3869. }
  3870. /* Wait for a thread to finish. */
  3871. static int
  3872. mg_join_thread(pthread_t threadid)
  3873. {
  3874. int result;
  3875. result = pthread_join(threadid, NULL);
  3876. return result;
  3877. }
  3878. #ifndef NO_CGI
  3879. static pid_t
  3880. spawn_process(struct mg_connection *conn,
  3881. const char *prog,
  3882. char *envblk,
  3883. char *envp[],
  3884. int fdin[2],
  3885. int fdout[2],
  3886. int fderr[2],
  3887. const char *dir)
  3888. {
  3889. pid_t pid;
  3890. const char *interp;
  3891. (void)envblk;
  3892. if (conn == NULL) {
  3893. return 0;
  3894. }
  3895. if ((pid = fork()) == -1) {
  3896. /* Parent */
  3897. send_http_error(conn,
  3898. 500,
  3899. "Error: Creating CGI process\nfork(): %s",
  3900. strerror(ERRNO));
  3901. } else if (pid == 0) {
  3902. /* Child */
  3903. if (chdir(dir) != 0) {
  3904. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  3905. } else if (dup2(fdin[0], 0) == -1) {
  3906. mg_cry(conn,
  3907. "%s: dup2(%d, 0): %s",
  3908. __func__,
  3909. fdin[0],
  3910. strerror(ERRNO));
  3911. } else if (dup2(fdout[1], 1) == -1) {
  3912. mg_cry(conn,
  3913. "%s: dup2(%d, 1): %s",
  3914. __func__,
  3915. fdout[1],
  3916. strerror(ERRNO));
  3917. } else if (dup2(fderr[1], 2) == -1) {
  3918. mg_cry(conn,
  3919. "%s: dup2(%d, 2): %s",
  3920. __func__,
  3921. fderr[1],
  3922. strerror(ERRNO));
  3923. } else {
  3924. /* Keep stderr and stdout in two different pipes.
  3925. * Stdout will be sent back to the client,
  3926. * stderr should go into a server error log. */
  3927. (void)close(fdin[0]);
  3928. (void)close(fdout[1]);
  3929. (void)close(fderr[1]);
  3930. /* Close write end fdin and read end fdout and fderr */
  3931. (void)close(fdin[1]);
  3932. (void)close(fdout[0]);
  3933. (void)close(fderr[0]);
  3934. /* After exec, all signal handlers are restored to their default
  3935. * values, with one exception of SIGCHLD. According to
  3936. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler will
  3937. * leave unchanged after exec if it was set to be ignored. Restore
  3938. * it to default action. */
  3939. signal(SIGCHLD, SIG_DFL);
  3940. interp = conn->ctx->config[CGI_INTERPRETER];
  3941. if (interp == NULL) {
  3942. (void)execle(prog, prog, NULL, envp);
  3943. mg_cry(conn,
  3944. "%s: execle(%s): %s",
  3945. __func__,
  3946. prog,
  3947. strerror(ERRNO));
  3948. } else {
  3949. (void)execle(interp, interp, prog, NULL, envp);
  3950. mg_cry(conn,
  3951. "%s: execle(%s %s): %s",
  3952. __func__,
  3953. interp,
  3954. prog,
  3955. strerror(ERRNO));
  3956. }
  3957. }
  3958. exit(EXIT_FAILURE);
  3959. }
  3960. return pid;
  3961. }
  3962. #endif /* !NO_CGI */
  3963. static int
  3964. set_blocking_mode(SOCKET sock, int blocking)
  3965. {
  3966. int flags;
  3967. flags = fcntl(sock, F_GETFL, 0);
  3968. if (blocking) {
  3969. (void)fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  3970. } else {
  3971. (void)fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK)));
  3972. }
  3973. return 0;
  3974. }
  3975. #endif /* _WIN32 */
  3976. /* End of initial operating system specific define block. */
  3977. /* Get a random number (independent of C rand function) */
  3978. static uint64_t
  3979. get_random(void)
  3980. {
  3981. static uint64_t lfsr = 0; /* Linear feedback shift register */
  3982. static uint64_t lcg = 0; /* Linear congruential generator */
  3983. uint64_t now = mg_get_current_time_ns();
  3984. if (lfsr == 0) {
  3985. /* lfsr will be only 0 if has not been initialized,
  3986. * so this code is called only once. */
  3987. lfsr = mg_get_current_time_ns();
  3988. lcg = mg_get_current_time_ns();
  3989. } else {
  3990. /* Get the next step of both random number generators. */
  3991. lfsr = (lfsr >> 1)
  3992. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  3993. << 63);
  3994. lcg = lcg * 6364136223846793005 + 1442695040888963407;
  3995. }
  3996. /* Combining two pseudo-random number generators and a high resolution part
  3997. * of the current server time will make it hard (impossible?) to guess the
  3998. * next number. */
  3999. return (lfsr ^ lcg ^ now);
  4000. }
  4001. static int
  4002. mg_poll(struct pollfd *pfd,
  4003. unsigned int n,
  4004. int milliseconds,
  4005. volatile int *stop_server)
  4006. {
  4007. int ms_now, result;
  4008. /* Call poll, but only for a maximum time of a few seconds.
  4009. * This will allow to stop the server after some seconds, instead
  4010. * of having to wait for a long socket timeout. */
  4011. ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  4012. do {
  4013. if (*stop_server) {
  4014. /* Shut down signal */
  4015. return -2;
  4016. }
  4017. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  4018. ms_now = milliseconds;
  4019. }
  4020. result = poll(pfd, n, ms_now);
  4021. if (result != 0) {
  4022. /* Poll returned either success (1) or error (-1).
  4023. * Forward both to the caller. */
  4024. return result;
  4025. }
  4026. /* Poll returned timeout (0). */
  4027. if (milliseconds > 0) {
  4028. milliseconds -= ms_now;
  4029. }
  4030. } while (milliseconds != 0);
  4031. return result;
  4032. }
  4033. /* Write data to the IO channel - opened file descriptor, socket or SSL
  4034. * descriptor. Return number of bytes written. */
  4035. static int
  4036. push(struct mg_context *ctx,
  4037. FILE *fp,
  4038. SOCKET sock,
  4039. SSL *ssl,
  4040. const char *buf,
  4041. int len,
  4042. double timeout)
  4043. {
  4044. uint64_t start = 0, now = 0, timeout_ns = 0;
  4045. int n, err;
  4046. #ifdef _WIN32
  4047. typedef int len_t;
  4048. #else
  4049. typedef size_t len_t;
  4050. #endif
  4051. if (timeout > 0) {
  4052. start = mg_get_current_time_ns();
  4053. timeout_ns = (uint64_t)(timeout * 1.0E9);
  4054. }
  4055. if (ctx == NULL) {
  4056. return -1;
  4057. }
  4058. #ifdef NO_SSL
  4059. if (ssl) {
  4060. return -1;
  4061. }
  4062. #endif
  4063. do {
  4064. #ifndef NO_SSL
  4065. if (ssl != NULL) {
  4066. n = SSL_write(ssl, buf, len);
  4067. if (n <= 0) {
  4068. err = SSL_get_error(ssl, n);
  4069. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  4070. err = ERRNO;
  4071. } else if ((err == SSL_ERROR_WANT_READ)
  4072. || (err == SSL_ERROR_WANT_WRITE)) {
  4073. n = 0;
  4074. } else {
  4075. DEBUG_TRACE("SSL_write() failed, error %d", err);
  4076. return -1;
  4077. }
  4078. } else {
  4079. err = 0;
  4080. }
  4081. } else
  4082. #endif
  4083. if (fp != NULL) {
  4084. n = (int)fwrite(buf, 1, (size_t)len, fp);
  4085. if (ferror(fp)) {
  4086. n = -1;
  4087. err = ERRNO;
  4088. } else {
  4089. err = 0;
  4090. }
  4091. } else {
  4092. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  4093. err = (n < 0) ? ERRNO : 0;
  4094. #ifdef _WIN32
  4095. if (err == WSAEWOULDBLOCK) {
  4096. err = 0;
  4097. n = 0;
  4098. }
  4099. #else
  4100. if (err == EWOULDBLOCK) {
  4101. err = 0;
  4102. n = 0;
  4103. }
  4104. #endif
  4105. if (n < 0) {
  4106. /* shutdown of the socket at client side */
  4107. return -1;
  4108. }
  4109. }
  4110. if (ctx->stop_flag) {
  4111. return -1;
  4112. }
  4113. if ((n > 0) || (n == 0 && len == 0)) {
  4114. /* some data has been read, or no data was requested */
  4115. return n;
  4116. }
  4117. if (n < 0) {
  4118. /* socket error - check errno */
  4119. DEBUG_TRACE("send() failed, error %d", err);
  4120. /* TODO (mid): error handling depending on the error code.
  4121. * These codes are different between Windows and Linux.
  4122. * Currently there is no problem with failing send calls,
  4123. * if there is a reproducible situation, it should be
  4124. * investigated in detail.
  4125. */
  4126. return -1;
  4127. }
  4128. /* Only in case n=0 (timeout), repeat calling the write function */
  4129. if (timeout >= 0) {
  4130. now = mg_get_current_time_ns();
  4131. }
  4132. } while ((timeout <= 0) || ((start - now) <= timeout_ns));
  4133. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  4134. used */
  4135. return -1;
  4136. }
  4137. static int64_t
  4138. push_all(struct mg_context *ctx,
  4139. FILE *fp,
  4140. SOCKET sock,
  4141. SSL *ssl,
  4142. const char *buf,
  4143. int64_t len)
  4144. {
  4145. double timeout = -1.0;
  4146. int64_t n, nwritten = 0;
  4147. if (ctx == NULL) {
  4148. return -1;
  4149. }
  4150. if (ctx->config[REQUEST_TIMEOUT]) {
  4151. timeout = atoi(ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  4152. }
  4153. while (len > 0 && ctx->stop_flag == 0) {
  4154. n = push(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  4155. if (n < 0) {
  4156. if (nwritten == 0) {
  4157. nwritten = n; /* Propagate the error */
  4158. }
  4159. break;
  4160. } else if (n == 0) {
  4161. break; /* No more data to write */
  4162. } else {
  4163. nwritten += n;
  4164. len -= n;
  4165. }
  4166. }
  4167. return nwritten;
  4168. }
  4169. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  4170. * Return value:
  4171. * >=0 .. number of bytes successfully read
  4172. * -1 .. timeout
  4173. * -2 .. error
  4174. */
  4175. static int
  4176. pull_inner(FILE *fp,
  4177. struct mg_connection *conn,
  4178. char *buf,
  4179. int len,
  4180. double timeout)
  4181. {
  4182. int nread, err = 0;
  4183. #ifdef _WIN32
  4184. typedef int len_t;
  4185. #else
  4186. typedef size_t len_t;
  4187. #endif
  4188. #ifndef NO_SSL
  4189. int ssl_pending;
  4190. #endif
  4191. /* We need an additional wait loop around this, because in some cases
  4192. * with TLSwe may get data from the socket but not from SSL_read.
  4193. * In this case we need to repeat at least once.
  4194. */
  4195. if (fp != NULL) {
  4196. #if !defined(_WIN32_WCE)
  4197. /* Use read() instead of fread(), because if we're reading from the
  4198. * CGI pipe, fread() may block until IO buffer is filled up. We
  4199. * cannot afford to block and must pass all read bytes immediately
  4200. * to the client. */
  4201. nread = (int)read(fileno(fp), buf, (size_t)len);
  4202. #else
  4203. /* WinCE does not support CGI pipes */
  4204. nread = (int)fread(buf, 1, (size_t)len, fp);
  4205. #endif
  4206. err = (nread < 0) ? ERRNO : 0;
  4207. #ifndef NO_SSL
  4208. } else if ((conn->ssl != NULL)
  4209. && ((ssl_pending = SSL_pending(conn->ssl)) > 0)) {
  4210. /* We already know there is no more data buffered in conn->buf
  4211. * but there is more available in the SSL layer. So don't poll
  4212. * conn->client.sock yet. */
  4213. if (ssl_pending > len) {
  4214. ssl_pending = len;
  4215. }
  4216. nread = SSL_read(conn->ssl, buf, ssl_pending);
  4217. if (nread <= 0) {
  4218. err = SSL_get_error(conn->ssl, nread);
  4219. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  4220. err = ERRNO;
  4221. } else if ((err == SSL_ERROR_WANT_READ)
  4222. || (err == SSL_ERROR_WANT_WRITE)) {
  4223. nread = 0;
  4224. } else {
  4225. DEBUG_TRACE("SSL_read() failed, error %d", err);
  4226. return -1;
  4227. }
  4228. } else {
  4229. err = 0;
  4230. }
  4231. } else if (conn->ssl != NULL) {
  4232. struct pollfd pfd[1];
  4233. int pollres;
  4234. pfd[0].fd = conn->client.sock;
  4235. pfd[0].events = POLLIN;
  4236. pollres =
  4237. mg_poll(pfd, 1, (int)(timeout * 1000.0), &(conn->ctx->stop_flag));
  4238. if (conn->ctx->stop_flag) {
  4239. return -2;
  4240. }
  4241. if (pollres > 0) {
  4242. nread = SSL_read(conn->ssl, buf, len);
  4243. if (nread <= 0) {
  4244. err = SSL_get_error(conn->ssl, nread);
  4245. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  4246. err = ERRNO;
  4247. } else if ((err == SSL_ERROR_WANT_READ)
  4248. || (err == SSL_ERROR_WANT_WRITE)) {
  4249. nread = 0;
  4250. } else {
  4251. DEBUG_TRACE("SSL_read() failed, error %d", err);
  4252. return -2;
  4253. }
  4254. } else {
  4255. err = 0;
  4256. }
  4257. } else if (pollres < 0) {
  4258. /* Error */
  4259. return -2;
  4260. } else {
  4261. /* pollres = 0 means timeout */
  4262. nread = 0;
  4263. }
  4264. #endif
  4265. } else {
  4266. struct pollfd pfd[1];
  4267. int pollres;
  4268. pfd[0].fd = conn->client.sock;
  4269. pfd[0].events = POLLIN;
  4270. pollres =
  4271. mg_poll(pfd, 1, (int)(timeout * 1000.0), &(conn->ctx->stop_flag));
  4272. if (conn->ctx->stop_flag) {
  4273. return -2;
  4274. }
  4275. if (pollres > 0) {
  4276. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  4277. err = (nread < 0) ? ERRNO : 0;
  4278. if (nread <= 0) {
  4279. /* shutdown of the socket at client side */
  4280. return -2;
  4281. }
  4282. } else if (pollres < 0) {
  4283. /* error callint poll */
  4284. return -2;
  4285. } else {
  4286. /* pollres = 0 means timeout */
  4287. nread = 0;
  4288. }
  4289. }
  4290. if (conn->ctx->stop_flag) {
  4291. return -2;
  4292. }
  4293. if ((nread > 0) || (nread == 0 && len == 0)) {
  4294. /* some data has been read, or no data was requested */
  4295. return nread;
  4296. }
  4297. if (nread < 0) {
  4298. /* socket error - check errno */
  4299. #ifdef _WIN32
  4300. if (err == WSAEWOULDBLOCK) {
  4301. /* TODO (low): check if this is still required */
  4302. /* standard case if called from close_socket_gracefully */
  4303. return -2;
  4304. } else if (err == WSAETIMEDOUT) {
  4305. /* TODO (low): check if this is still required */
  4306. /* timeout is handled by the while loop */
  4307. return 0;
  4308. } else if (err == WSAECONNABORTED) {
  4309. /* See https://www.chilkatsoft.com/p/p_299.asp */
  4310. return -2;
  4311. } else {
  4312. DEBUG_TRACE("recv() failed, error %d", err);
  4313. return -2;
  4314. }
  4315. #else
  4316. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  4317. * if the timeout is reached and if the socket was set to non-
  4318. * blocking in close_socket_gracefully, so we can not distinguish
  4319. * here. We have to wait for the timeout in both cases for now.
  4320. */
  4321. if (err == EAGAIN || err == EWOULDBLOCK || err == EINTR) {
  4322. /* TODO (low): check if this is still required */
  4323. /* EAGAIN/EWOULDBLOCK:
  4324. * standard case if called from close_socket_gracefully
  4325. * => should return -1 */
  4326. /* or timeout occured
  4327. * => the code must stay in the while loop */
  4328. /* EINTR can be generated on a socket with a timeout set even
  4329. * when SA_RESTART is effective for all relevant signals
  4330. * (see signal(7)).
  4331. * => stay in the while loop */
  4332. } else {
  4333. DEBUG_TRACE("recv() failed, error %d", err);
  4334. return -2;
  4335. }
  4336. #endif
  4337. }
  4338. /* Timeout occured, but no data available. */
  4339. return -1;
  4340. }
  4341. static int
  4342. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  4343. {
  4344. int n, nread = 0;
  4345. double timeout = -1.0;
  4346. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  4347. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  4348. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  4349. }
  4350. if (timeout >= 0.0) {
  4351. start_time = mg_get_current_time_ns();
  4352. timeout_ns = (uint64_t)(timeout * 1.0E9);
  4353. }
  4354. while (len > 0 && conn->ctx->stop_flag == 0) {
  4355. n = pull_inner(fp, conn, buf + nread, len, timeout);
  4356. if (n == -2) {
  4357. if (nread == 0) {
  4358. nread = -1; /* Propagate the error */
  4359. }
  4360. break;
  4361. } else if (n == -1) {
  4362. /* timeout */
  4363. if (timeout >= 0.0) {
  4364. now = mg_get_current_time_ns();
  4365. if ((now - start_time) <= timeout_ns) {
  4366. continue;
  4367. }
  4368. }
  4369. break;
  4370. } else if (n == 0) {
  4371. break; /* No more data to read */
  4372. } else {
  4373. conn->consumed_content += n;
  4374. nread += n;
  4375. len -= n;
  4376. }
  4377. }
  4378. return nread;
  4379. }
  4380. static void
  4381. discard_unread_request_data(struct mg_connection *conn)
  4382. {
  4383. char buf[MG_BUF_LEN];
  4384. size_t to_read;
  4385. int nread;
  4386. if (conn == NULL) {
  4387. return;
  4388. }
  4389. to_read = sizeof(buf);
  4390. if (conn->is_chunked) {
  4391. /* Chunked encoding: 1=chunk not read completely, 2=chunk read
  4392. * completely */
  4393. while (conn->is_chunked == 1) {
  4394. nread = mg_read(conn, buf, to_read);
  4395. if (nread <= 0) {
  4396. break;
  4397. }
  4398. }
  4399. } else {
  4400. /* Not chunked: content length is known */
  4401. while (conn->consumed_content < conn->content_len) {
  4402. if (to_read
  4403. > (size_t)(conn->content_len - conn->consumed_content)) {
  4404. to_read = (size_t)(conn->content_len - conn->consumed_content);
  4405. }
  4406. nread = mg_read(conn, buf, to_read);
  4407. if (nread <= 0) {
  4408. break;
  4409. }
  4410. }
  4411. }
  4412. }
  4413. static int
  4414. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  4415. {
  4416. int64_t n, buffered_len, nread;
  4417. int64_t len64 =
  4418. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  4419. * int, we may not read more
  4420. * bytes */
  4421. const char *body;
  4422. if (conn == NULL) {
  4423. return 0;
  4424. }
  4425. /* If Content-Length is not set for a PUT or POST request, read until
  4426. * socket is closed */
  4427. if (conn->consumed_content == 0 && conn->content_len == -1) {
  4428. conn->content_len = INT64_MAX;
  4429. conn->must_close = 1;
  4430. }
  4431. nread = 0;
  4432. if (conn->consumed_content < conn->content_len) {
  4433. /* Adjust number of bytes to read. */
  4434. int64_t left_to_read = conn->content_len - conn->consumed_content;
  4435. if (left_to_read < len64) {
  4436. /* Do not read more than the total content length of the request.
  4437. */
  4438. len64 = left_to_read;
  4439. }
  4440. /* Return buffered data */
  4441. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  4442. - conn->consumed_content;
  4443. if (buffered_len > 0) {
  4444. if (len64 < buffered_len) {
  4445. buffered_len = len64;
  4446. }
  4447. body = conn->buf + conn->request_len + conn->consumed_content;
  4448. memcpy(buf, body, (size_t)buffered_len);
  4449. len64 -= buffered_len;
  4450. conn->consumed_content += buffered_len;
  4451. nread += buffered_len;
  4452. buf = (char *)buf + buffered_len;
  4453. }
  4454. /* We have returned all buffered data. Read new data from the remote
  4455. * socket.
  4456. */
  4457. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  4458. nread += n;
  4459. } else {
  4460. nread = ((nread > 0) ? nread : n);
  4461. }
  4462. }
  4463. return (int)nread;
  4464. }
  4465. static char
  4466. mg_getc(struct mg_connection *conn)
  4467. {
  4468. char c;
  4469. if (conn == NULL) {
  4470. return 0;
  4471. }
  4472. conn->content_len++;
  4473. if (mg_read_inner(conn, &c, 1) <= 0) {
  4474. return (char)0;
  4475. }
  4476. return c;
  4477. }
  4478. int
  4479. mg_read(struct mg_connection *conn, void *buf, size_t len)
  4480. {
  4481. if (len > INT_MAX) {
  4482. len = INT_MAX;
  4483. }
  4484. if (conn == NULL) {
  4485. return 0;
  4486. }
  4487. if (conn->is_chunked) {
  4488. size_t all_read = 0;
  4489. while (len > 0) {
  4490. if (conn->is_chunked == 2) {
  4491. /* No more data left to read */
  4492. return 0;
  4493. }
  4494. if (conn->chunk_remainder) {
  4495. /* copy from the remainder of the last received chunk */
  4496. long read_ret;
  4497. size_t read_now =
  4498. ((conn->chunk_remainder > len) ? (len)
  4499. : (conn->chunk_remainder));
  4500. conn->content_len += (int)read_now;
  4501. read_ret =
  4502. mg_read_inner(conn, (char *)buf + all_read, read_now);
  4503. if (read_ret < 1) {
  4504. /* read error */
  4505. return -1;
  4506. }
  4507. all_read += (size_t)read_ret;
  4508. conn->chunk_remainder -= (size_t)read_ret;
  4509. len -= (size_t)read_ret;
  4510. if (conn->chunk_remainder == 0) {
  4511. /* Add data bytes in the current chunk have been read,
  4512. * so we are expecting \r\n now. */
  4513. char x1 = mg_getc(conn);
  4514. char x2 = mg_getc(conn);
  4515. if ((x1 != '\r') || (x2 != '\n')) {
  4516. /* Protocol violation */
  4517. return -1;
  4518. }
  4519. }
  4520. } else {
  4521. /* fetch a new chunk */
  4522. int i = 0;
  4523. char lenbuf[64];
  4524. char *end = 0;
  4525. unsigned long chunkSize = 0;
  4526. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  4527. lenbuf[i] = mg_getc(conn);
  4528. if (i > 0 && lenbuf[i] == '\r' && lenbuf[i - 1] != '\r') {
  4529. continue;
  4530. }
  4531. if (i > 1 && lenbuf[i] == '\n' && lenbuf[i - 1] == '\r') {
  4532. lenbuf[i + 1] = 0;
  4533. chunkSize = strtoul(lenbuf, &end, 16);
  4534. if (chunkSize == 0) {
  4535. /* regular end of content */
  4536. conn->is_chunked = 2;
  4537. }
  4538. break;
  4539. }
  4540. if (!isxdigit(lenbuf[i])) {
  4541. /* illegal character for chunk length */
  4542. return -1;
  4543. }
  4544. }
  4545. if ((end == NULL) || (*end != '\r')) {
  4546. /* chunksize not set correctly */
  4547. return -1;
  4548. }
  4549. if (chunkSize == 0) {
  4550. break;
  4551. }
  4552. conn->chunk_remainder = chunkSize;
  4553. }
  4554. }
  4555. return (int)all_read;
  4556. }
  4557. return mg_read_inner(conn, buf, len);
  4558. }
  4559. int
  4560. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  4561. {
  4562. time_t now;
  4563. int64_t n, total, allowed;
  4564. if (conn == NULL) {
  4565. return 0;
  4566. }
  4567. if (conn->throttle > 0) {
  4568. if ((now = time(NULL)) != conn->last_throttle_time) {
  4569. conn->last_throttle_time = now;
  4570. conn->last_throttle_bytes = 0;
  4571. }
  4572. allowed = conn->throttle - conn->last_throttle_bytes;
  4573. if (allowed > (int64_t)len) {
  4574. allowed = (int64_t)len;
  4575. }
  4576. if ((total = push_all(conn->ctx,
  4577. NULL,
  4578. conn->client.sock,
  4579. conn->ssl,
  4580. (const char *)buf,
  4581. (int64_t)allowed)) == allowed) {
  4582. buf = (const char *)buf + total;
  4583. conn->last_throttle_bytes += total;
  4584. while (total < (int64_t)len && conn->ctx->stop_flag == 0) {
  4585. allowed = (conn->throttle > ((int64_t)len - total))
  4586. ? (int64_t)len - total
  4587. : conn->throttle;
  4588. if ((n = push_all(conn->ctx,
  4589. NULL,
  4590. conn->client.sock,
  4591. conn->ssl,
  4592. (const char *)buf,
  4593. (int64_t)allowed)) != allowed) {
  4594. break;
  4595. }
  4596. sleep(1);
  4597. conn->last_throttle_bytes = allowed;
  4598. conn->last_throttle_time = time(NULL);
  4599. buf = (const char *)buf + n;
  4600. total += n;
  4601. }
  4602. }
  4603. } else {
  4604. total = push_all(conn->ctx,
  4605. NULL,
  4606. conn->client.sock,
  4607. conn->ssl,
  4608. (const char *)buf,
  4609. (int64_t)len);
  4610. }
  4611. return (int)total;
  4612. }
  4613. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  4614. int
  4615. mg_send_chunk(struct mg_connection *conn,
  4616. const char *chunk,
  4617. unsigned int chunk_len)
  4618. {
  4619. char lenbuf[16];
  4620. size_t lenbuf_len;
  4621. int ret;
  4622. int t;
  4623. /* First store the length information in a text buffer. */
  4624. sprintf(lenbuf, "%x\r\n", chunk_len);
  4625. lenbuf_len = strlen(lenbuf);
  4626. /* Then send length information, chunk and terminating \r\n. */
  4627. ret = mg_write(conn, lenbuf, lenbuf_len);
  4628. if (ret != (int)lenbuf_len) {
  4629. return -1;
  4630. }
  4631. t = ret;
  4632. ret = mg_write(conn, chunk, chunk_len);
  4633. if (ret != (int)chunk_len) {
  4634. return -1;
  4635. }
  4636. t += ret;
  4637. ret = mg_write(conn, "\r\n", 2);
  4638. if (ret != 2) {
  4639. return -1;
  4640. }
  4641. t += ret;
  4642. return t;
  4643. }
  4644. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  4645. static int
  4646. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  4647. {
  4648. va_list ap_copy;
  4649. size_t size = MG_BUF_LEN / 4;
  4650. int len = -1;
  4651. *buf = NULL;
  4652. while (len < 0) {
  4653. if (*buf) {
  4654. mg_free(*buf);
  4655. }
  4656. size *= 4;
  4657. *buf = (char *)mg_malloc(size);
  4658. if (!*buf) {
  4659. break;
  4660. }
  4661. va_copy(ap_copy, ap);
  4662. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  4663. va_end(ap_copy);
  4664. (*buf)[size - 1] = 0;
  4665. }
  4666. return len;
  4667. }
  4668. /* Print message to buffer. If buffer is large enough to hold the message,
  4669. * return buffer. If buffer is to small, allocate large enough buffer on heap,
  4670. * and return allocated buffer. */
  4671. static int
  4672. alloc_vprintf(char **out_buf,
  4673. char *prealloc_buf,
  4674. size_t prealloc_size,
  4675. const char *fmt,
  4676. va_list ap)
  4677. {
  4678. va_list ap_copy;
  4679. int len;
  4680. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  4681. * buffer is too small. Also, older versions of msvcrt.dll do not have
  4682. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  4683. * Therefore, we make two passes: on first pass, get required message
  4684. * length.
  4685. * On second pass, actually print the message. */
  4686. va_copy(ap_copy, ap);
  4687. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  4688. va_end(ap_copy);
  4689. if (len < 0) {
  4690. /* C runtime is not standard compliant, vsnprintf() returned -1.
  4691. * Switch to alternative code path that uses incremental allocations.
  4692. */
  4693. va_copy(ap_copy, ap);
  4694. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  4695. va_end(ap_copy);
  4696. } else if ((size_t)(len) >= prealloc_size) {
  4697. /* The pre-allocated buffer not large enough. */
  4698. /* Allocate a new buffer. */
  4699. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  4700. if (!*out_buf) {
  4701. /* Allocation failed. Return -1 as "out of memory" error. */
  4702. return -1;
  4703. }
  4704. /* Buffer allocation successful. Store the string there. */
  4705. va_copy(ap_copy, ap);
  4706. IGNORE_UNUSED_RESULT(
  4707. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  4708. va_end(ap_copy);
  4709. } else {
  4710. /* The pre-allocated buffer is large enough.
  4711. * Use it to store the string and return the address. */
  4712. va_copy(ap_copy, ap);
  4713. IGNORE_UNUSED_RESULT(
  4714. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  4715. va_end(ap_copy);
  4716. *out_buf = prealloc_buf;
  4717. }
  4718. return len;
  4719. }
  4720. static int
  4721. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  4722. {
  4723. char mem[MG_BUF_LEN];
  4724. char *buf = NULL;
  4725. int len;
  4726. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  4727. len = mg_write(conn, buf, (size_t)len);
  4728. }
  4729. if (buf != mem && buf != NULL) {
  4730. mg_free(buf);
  4731. }
  4732. return len;
  4733. }
  4734. int
  4735. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  4736. {
  4737. va_list ap;
  4738. int result;
  4739. va_start(ap, fmt);
  4740. result = mg_vprintf(conn, fmt, ap);
  4741. va_end(ap);
  4742. return result;
  4743. }
  4744. int
  4745. mg_url_decode(const char *src,
  4746. int src_len,
  4747. char *dst,
  4748. int dst_len,
  4749. int is_form_url_encoded)
  4750. {
  4751. int i, j, a, b;
  4752. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  4753. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  4754. if (i < src_len - 2 && src[i] == '%'
  4755. && isxdigit(*(const unsigned char *)(src + i + 1))
  4756. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  4757. a = tolower(*(const unsigned char *)(src + i + 1));
  4758. b = tolower(*(const unsigned char *)(src + i + 2));
  4759. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  4760. i += 2;
  4761. } else if (is_form_url_encoded && src[i] == '+') {
  4762. dst[j] = ' ';
  4763. } else {
  4764. dst[j] = src[i];
  4765. }
  4766. }
  4767. dst[j] = '\0'; /* Null-terminate the destination */
  4768. return (i >= src_len) ? j : -1;
  4769. }
  4770. int
  4771. mg_get_var(const char *data,
  4772. size_t data_len,
  4773. const char *name,
  4774. char *dst,
  4775. size_t dst_len)
  4776. {
  4777. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  4778. }
  4779. int
  4780. mg_get_var2(const char *data,
  4781. size_t data_len,
  4782. const char *name,
  4783. char *dst,
  4784. size_t dst_len,
  4785. size_t occurrence)
  4786. {
  4787. const char *p, *e, *s;
  4788. size_t name_len;
  4789. int len;
  4790. if (dst == NULL || dst_len == 0) {
  4791. len = -2;
  4792. } else if (data == NULL || name == NULL || data_len == 0) {
  4793. len = -1;
  4794. dst[0] = '\0';
  4795. } else {
  4796. name_len = strlen(name);
  4797. e = data + data_len;
  4798. len = -1;
  4799. dst[0] = '\0';
  4800. /* data is "var1=val1&var2=val2...". Find variable first */
  4801. for (p = data; p + name_len < e; p++) {
  4802. if ((p == data || p[-1] == '&') && p[name_len] == '='
  4803. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  4804. /* Point p to variable value */
  4805. p += name_len + 1;
  4806. /* Point s to the end of the value */
  4807. s = (const char *)memchr(p, '&', (size_t)(e - p));
  4808. if (s == NULL) {
  4809. s = e;
  4810. }
  4811. /* assert(s >= p); */
  4812. if (s < p) {
  4813. return -3;
  4814. }
  4815. /* Decode variable into destination buffer */
  4816. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  4817. /* Redirect error code from -1 to -2 (destination buffer too
  4818. * small). */
  4819. if (len == -1) {
  4820. len = -2;
  4821. }
  4822. break;
  4823. }
  4824. }
  4825. }
  4826. return len;
  4827. }
  4828. /* HCP24: some changes to compare hole var_name */
  4829. int
  4830. mg_get_cookie(const char *cookie_header,
  4831. const char *var_name,
  4832. char *dst,
  4833. size_t dst_size)
  4834. {
  4835. const char *s, *p, *end;
  4836. int name_len, len = -1;
  4837. if (dst == NULL || dst_size == 0) {
  4838. return -2;
  4839. }
  4840. dst[0] = '\0';
  4841. if (var_name == NULL || (s = cookie_header) == NULL) {
  4842. return -1;
  4843. }
  4844. name_len = (int)strlen(var_name);
  4845. end = s + strlen(s);
  4846. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  4847. if (s[name_len] == '=') {
  4848. /* HCP24: now check is it a substring or a full cookie name */
  4849. if ((s == cookie_header) || (s[-1] == ' ')) {
  4850. s += name_len + 1;
  4851. if ((p = strchr(s, ' ')) == NULL) {
  4852. p = end;
  4853. }
  4854. if (p[-1] == ';') {
  4855. p--;
  4856. }
  4857. if (*s == '"' && p[-1] == '"' && p > s + 1) {
  4858. s++;
  4859. p--;
  4860. }
  4861. if ((size_t)(p - s) < dst_size) {
  4862. len = (int)(p - s);
  4863. mg_strlcpy(dst, s, (size_t)len + 1);
  4864. } else {
  4865. len = -3;
  4866. }
  4867. break;
  4868. }
  4869. }
  4870. }
  4871. return len;
  4872. }
  4873. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  4874. static void
  4875. base64_encode(const unsigned char *src, int src_len, char *dst)
  4876. {
  4877. static const char *b64 =
  4878. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  4879. int i, j, a, b, c;
  4880. for (i = j = 0; i < src_len; i += 3) {
  4881. a = src[i];
  4882. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  4883. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  4884. dst[j++] = b64[a >> 2];
  4885. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  4886. if (i + 1 < src_len) {
  4887. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  4888. }
  4889. if (i + 2 < src_len) {
  4890. dst[j++] = b64[c & 63];
  4891. }
  4892. }
  4893. while (j % 4 != 0) {
  4894. dst[j++] = '=';
  4895. }
  4896. dst[j++] = '\0';
  4897. }
  4898. #endif
  4899. #if defined(USE_LUA)
  4900. static unsigned char
  4901. b64reverse(char letter)
  4902. {
  4903. if (letter >= 'A' && letter <= 'Z') {
  4904. return letter - 'A';
  4905. }
  4906. if (letter >= 'a' && letter <= 'z') {
  4907. return letter - 'a' + 26;
  4908. }
  4909. if (letter >= '0' && letter <= '9') {
  4910. return letter - '0' + 52;
  4911. }
  4912. if (letter == '+') {
  4913. return 62;
  4914. }
  4915. if (letter == '/') {
  4916. return 63;
  4917. }
  4918. if (letter == '=') {
  4919. return 255; /* normal end */
  4920. }
  4921. return 254; /* error */
  4922. }
  4923. static int
  4924. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  4925. {
  4926. int i;
  4927. unsigned char a, b, c, d;
  4928. *dst_len = 0;
  4929. for (i = 0; i < src_len; i += 4) {
  4930. a = b64reverse(src[i]);
  4931. if (a >= 254) {
  4932. return i;
  4933. }
  4934. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  4935. if (b >= 254) {
  4936. return i + 1;
  4937. }
  4938. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  4939. if (c == 254) {
  4940. return i + 2;
  4941. }
  4942. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  4943. if (d == 254) {
  4944. return i + 3;
  4945. }
  4946. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  4947. if (c != 255) {
  4948. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  4949. if (d != 255) {
  4950. dst[(*dst_len)++] = (c << 6) + d;
  4951. }
  4952. }
  4953. }
  4954. return -1;
  4955. }
  4956. #endif
  4957. static int
  4958. is_put_or_delete_method(const struct mg_connection *conn)
  4959. {
  4960. if (conn) {
  4961. const char *s = conn->request_info.request_method;
  4962. return s != NULL && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  4963. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  4964. }
  4965. return 0;
  4966. }
  4967. #if !defined(NO_FILES)
  4968. static int
  4969. extention_matches_script(
  4970. struct mg_connection *conn, /* in: request (must be valid) */
  4971. const char *filename /* in: filename (must be valid) */
  4972. )
  4973. {
  4974. #if !defined(NO_CGI)
  4975. if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  4976. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4977. filename) > 0) {
  4978. return 1;
  4979. }
  4980. #endif
  4981. #if defined(USE_LUA)
  4982. if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  4983. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  4984. filename) > 0) {
  4985. return 1;
  4986. }
  4987. #endif
  4988. #if defined(USE_DUKTAPE)
  4989. if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  4990. strlen(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  4991. filename) > 0) {
  4992. return 1;
  4993. }
  4994. #endif
  4995. /* filename and conn could be unused, if all preocessor conditions
  4996. * are false (no script language supported). */
  4997. (void)filename;
  4998. (void)conn;
  4999. return 0;
  5000. }
  5001. /* For given directory path, substitute it to valid index file.
  5002. * Return 1 if index file has been found, 0 if not found.
  5003. * If the file is found, it's stats is returned in stp. */
  5004. static int
  5005. substitute_index_file(struct mg_connection *conn,
  5006. char *path,
  5007. size_t path_len,
  5008. struct mg_file_stat *filestat)
  5009. {
  5010. const char *list = conn->ctx->config[INDEX_FILES];
  5011. struct vec filename_vec;
  5012. size_t n = strlen(path);
  5013. int found = 0;
  5014. /* The 'path' given to us points to the directory. Remove all trailing
  5015. * directory separator characters from the end of the path, and
  5016. * then append single directory separator character. */
  5017. while (n > 0 && path[n - 1] == '/') {
  5018. n--;
  5019. }
  5020. path[n] = '/';
  5021. /* Traverse index files list. For each entry, append it to the given
  5022. * path and see if the file exists. If it exists, break the loop */
  5023. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  5024. /* Ignore too long entries that may overflow path buffer */
  5025. if (filename_vec.len > path_len - (n + 2)) {
  5026. continue;
  5027. }
  5028. /* Prepare full path to the index file */
  5029. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  5030. /* Does it exist? */
  5031. if (mg_stat(conn, path, filestat)) {
  5032. /* Yes it does, break the loop */
  5033. found = 1;
  5034. break;
  5035. }
  5036. }
  5037. /* If no index file exists, restore directory path */
  5038. if (!found) {
  5039. path[n] = '\0';
  5040. }
  5041. return found;
  5042. }
  5043. #endif
  5044. static void
  5045. interpret_uri(struct mg_connection *conn, /* in: request (must be valid) */
  5046. char *filename, /* out: filename */
  5047. size_t filename_buf_len, /* in: size of filename buffer */
  5048. struct mg_file_stat *filestat, /* out: file status structure */
  5049. int *is_found, /* out: file found (directly) */
  5050. int *is_script_resource, /* out: handled by a script? */
  5051. int *is_websocket_request, /* out: websocket connetion? */
  5052. int *is_put_or_delete_request /* out: put/delete a file? */
  5053. )
  5054. {
  5055. #if !defined(NO_FILES)
  5056. const char *uri = conn->request_info.local_uri;
  5057. const char *root = conn->ctx->config[DOCUMENT_ROOT];
  5058. const char *rewrite;
  5059. struct vec a, b;
  5060. int match_len;
  5061. char gz_path[PATH_MAX];
  5062. char const *accept_encoding;
  5063. int truncated;
  5064. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  5065. char *tmp_str;
  5066. size_t tmp_str_len, sep_pos;
  5067. #endif
  5068. #else
  5069. (void)filename_buf_len; /* unused if NO_FILES is defined */
  5070. #endif
  5071. /* Step 1: Set all initially unknown outputs to zero */
  5072. memset(filestat, 0, sizeof(*filestat));
  5073. *filename = 0;
  5074. *is_found = 0;
  5075. *is_script_resource = 0;
  5076. /* Step 2: Check if the request attempts to modify the file system */
  5077. *is_put_or_delete_request = is_put_or_delete_method(conn);
  5078. /* Step 3: Check if it is a websocket request, and modify the document
  5079. * root if required */
  5080. #if defined(USE_WEBSOCKET)
  5081. *is_websocket_request = is_websocket_protocol(conn);
  5082. #if !defined(NO_FILES)
  5083. if (*is_websocket_request && conn->ctx->config[WEBSOCKET_ROOT]) {
  5084. root = conn->ctx->config[WEBSOCKET_ROOT];
  5085. }
  5086. #endif /* !NO_FILES */
  5087. #else /* USE_WEBSOCKET */
  5088. *is_websocket_request = 0;
  5089. #endif /* USE_WEBSOCKET */
  5090. #if !defined(NO_FILES)
  5091. /* Step 4: If there is no root directory, don't look for files. */
  5092. /* Note that root == NULL is a regular use case here. This occurs,
  5093. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  5094. * config is not required. */
  5095. if (root == NULL) {
  5096. /* all file related outputs have already been set to 0, just return
  5097. */
  5098. return;
  5099. }
  5100. /* Step 5: Determine the local file path from the root path and the
  5101. * request uri. */
  5102. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  5103. * part of the path one byte on the right. */
  5104. mg_snprintf(
  5105. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  5106. if (truncated) {
  5107. goto interpret_cleanup;
  5108. }
  5109. /* Step 6: URI rewriting */
  5110. rewrite = conn->ctx->config[REWRITE];
  5111. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  5112. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  5113. mg_snprintf(conn,
  5114. &truncated,
  5115. filename,
  5116. filename_buf_len - 1,
  5117. "%.*s%s",
  5118. (int)b.len,
  5119. b.ptr,
  5120. uri + match_len);
  5121. break;
  5122. }
  5123. }
  5124. if (truncated) {
  5125. goto interpret_cleanup;
  5126. }
  5127. /* Step 7: Check if the file exists at the server */
  5128. /* Local file path and name, corresponding to requested URI
  5129. * is now stored in "filename" variable. */
  5130. if (mg_stat(conn, filename, filestat)) {
  5131. /* 7.1: File exists. */
  5132. *is_found = 1;
  5133. /* 7.2: Check if it is a script type. */
  5134. if (extention_matches_script(conn, filename)) {
  5135. /* The request addresses a CGI resource, Lua script or
  5136. * server-side javascript.
  5137. * The URI corresponds to the script itself (like
  5138. * /path/script.cgi), and there is no additional resource
  5139. * path (like /path/script.cgi/something).
  5140. * Requests that modify (replace or delete) a resource, like
  5141. * PUT and DELETE requests, should replace/delete the script
  5142. * file.
  5143. * Requests that read or write from/to a resource, like GET and
  5144. * POST requests, should call the script and return the
  5145. * generated response. */
  5146. *is_script_resource = (!*is_put_or_delete_request);
  5147. }
  5148. /* 7.3: If the request target is a directory, there could be
  5149. * a substitute file (index.html, index.cgi, ...). */
  5150. if (filestat->is_directory) {
  5151. /* Use a local copy here, since substitute_index_file will
  5152. * change the content of the file status */
  5153. struct mg_file_stat tmp_filestat;
  5154. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  5155. if (substitute_index_file(
  5156. conn, filename, filename_buf_len, &tmp_filestat)) {
  5157. /* Substitute file found. Copy stat to the output, then
  5158. * check if the file is a script file */
  5159. *filestat = tmp_filestat;
  5160. if (extention_matches_script(conn, filename)) {
  5161. /* Substitute file is a script file */
  5162. *is_script_resource = 1;
  5163. } else {
  5164. /* Substitute file is a regular file */
  5165. *is_script_resource = 0;
  5166. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  5167. }
  5168. }
  5169. /* If there is no substitute file, the server could return
  5170. * a directory listing in a later step */
  5171. }
  5172. return;
  5173. }
  5174. /* Step 8: Check for zipped files: */
  5175. /* If we can't find the actual file, look for the file
  5176. * with the same name but a .gz extension. If we find it,
  5177. * use that and set the gzipped flag in the file struct
  5178. * to indicate that the response need to have the content-
  5179. * encoding: gzip header.
  5180. * We can only do this if the browser declares support. */
  5181. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  5182. if (strstr(accept_encoding, "gzip") != NULL) {
  5183. mg_snprintf(
  5184. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  5185. if (truncated) {
  5186. goto interpret_cleanup;
  5187. }
  5188. if (mg_stat(conn, gz_path, filestat)) {
  5189. if (filestat) {
  5190. filestat->is_gzipped = 1;
  5191. *is_found = 1;
  5192. }
  5193. /* Currently gz files can not be scripts. */
  5194. return;
  5195. }
  5196. }
  5197. }
  5198. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  5199. /* Step 9: Script resources may handle sub-resources */
  5200. /* Support PATH_INFO for CGI scripts. */
  5201. tmp_str_len = strlen(filename);
  5202. tmp_str = mg_malloc(tmp_str_len + PATH_MAX + 1);
  5203. if (!tmp_str) {
  5204. /* Out of memory */
  5205. goto interpret_cleanup;
  5206. }
  5207. memcpy(tmp_str, filename, tmp_str_len + 1);
  5208. sep_pos = tmp_str_len;
  5209. while (sep_pos > 0) {
  5210. sep_pos--;
  5211. if (tmp_str[sep_pos] == '/') {
  5212. int is_script = 0, does_exist = 0;
  5213. tmp_str[sep_pos] = 0;
  5214. if (tmp_str[0]) {
  5215. is_script = extention_matches_script(conn, tmp_str);
  5216. does_exist = mg_stat(conn, tmp_str, filestat);
  5217. }
  5218. if (does_exist && is_script) {
  5219. filename[sep_pos] = 0;
  5220. memmove(filename + sep_pos + 2,
  5221. filename + sep_pos + 1,
  5222. strlen(filename + sep_pos + 1) + 1);
  5223. conn->path_info = filename + sep_pos + 1;
  5224. filename[sep_pos + 1] = '/';
  5225. *is_script_resource = 1;
  5226. *is_found = 1;
  5227. break;
  5228. }
  5229. if (substitute_index_file(
  5230. conn, tmp_str, tmp_str_len + PATH_MAX, filestat)) {
  5231. /* some intermediate directory has an index file */
  5232. if (extention_matches_script(conn, tmp_str)) {
  5233. /* this index file is a script */
  5234. char *tmp_str2 = mg_strdup(filename + sep_pos + 1);
  5235. mg_snprintf(conn,
  5236. &truncated,
  5237. filename,
  5238. filename_buf_len,
  5239. "%s//%s",
  5240. tmp_str,
  5241. tmp_str2);
  5242. mg_free(tmp_str2);
  5243. if (truncated) {
  5244. mg_free(tmp_str);
  5245. tmp_str = NULL;
  5246. goto interpret_cleanup;
  5247. }
  5248. sep_pos = strlen(tmp_str);
  5249. filename[sep_pos] = 0;
  5250. conn->path_info = filename + sep_pos + 1;
  5251. *is_script_resource = 1;
  5252. *is_found = 1;
  5253. break;
  5254. } else {
  5255. /* non-script files will not have sub-resources */
  5256. filename[sep_pos] = 0;
  5257. conn->path_info = 0;
  5258. *is_script_resource = 0;
  5259. *is_found = 0;
  5260. break;
  5261. }
  5262. }
  5263. tmp_str[sep_pos] = '/';
  5264. }
  5265. }
  5266. mg_free(tmp_str);
  5267. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  5268. #endif /* !defined(NO_FILES) */
  5269. return;
  5270. #if !defined(NO_FILES)
  5271. /* Reset all outputs */
  5272. interpret_cleanup:
  5273. memset(filestat, 0, sizeof(*filestat));
  5274. *filename = 0;
  5275. *is_found = 0;
  5276. *is_script_resource = 0;
  5277. *is_websocket_request = 0;
  5278. *is_put_or_delete_request = 0;
  5279. #endif /* !defined(NO_FILES) */
  5280. }
  5281. /* Check whether full request is buffered. Return:
  5282. * -1 if request is malformed
  5283. * 0 if request is not yet fully buffered
  5284. * >0 actual request length, including last \r\n\r\n */
  5285. static int
  5286. get_request_len(const char *buf, int buflen)
  5287. {
  5288. const char *s, *e;
  5289. int len = 0;
  5290. for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
  5291. /* Control characters are not allowed but >=128 is. */
  5292. if (!isprint(*(const unsigned char *)s) && *s != '\r' && *s != '\n'
  5293. && *(const unsigned char *)s < 128) {
  5294. len = -1;
  5295. break; /* [i_a] abort scan as soon as one malformed character is
  5296. * found; */
  5297. /* don't let subsequent \r\n\r\n win us over anyhow */
  5298. } else if (s[0] == '\n' && s[1] == '\n') {
  5299. len = (int)(s - buf) + 2;
  5300. } else if (s[0] == '\n' && &s[1] < e && s[1] == '\r' && s[2] == '\n') {
  5301. len = (int)(s - buf) + 3;
  5302. }
  5303. return len;
  5304. }
  5305. #if !defined(NO_CACHING)
  5306. /* Convert month to the month number. Return -1 on error, or month number */
  5307. static int
  5308. get_month_index(const char *s)
  5309. {
  5310. size_t i;
  5311. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  5312. if (!strcmp(s, month_names[i])) {
  5313. return (int)i;
  5314. }
  5315. }
  5316. return -1;
  5317. }
  5318. /* Parse UTC date-time string, and return the corresponding time_t value. */
  5319. static time_t
  5320. parse_date_string(const char *datetime)
  5321. {
  5322. char month_str[32] = {0};
  5323. int second, minute, hour, day, month, year;
  5324. time_t result = (time_t)0;
  5325. struct tm tm;
  5326. if ((sscanf(datetime,
  5327. "%d/%3s/%d %d:%d:%d",
  5328. &day,
  5329. month_str,
  5330. &year,
  5331. &hour,
  5332. &minute,
  5333. &second) == 6) || (sscanf(datetime,
  5334. "%d %3s %d %d:%d:%d",
  5335. &day,
  5336. month_str,
  5337. &year,
  5338. &hour,
  5339. &minute,
  5340. &second) == 6)
  5341. || (sscanf(datetime,
  5342. "%*3s, %d %3s %d %d:%d:%d",
  5343. &day,
  5344. month_str,
  5345. &year,
  5346. &hour,
  5347. &minute,
  5348. &second) == 6) || (sscanf(datetime,
  5349. "%d-%3s-%d %d:%d:%d",
  5350. &day,
  5351. month_str,
  5352. &year,
  5353. &hour,
  5354. &minute,
  5355. &second) == 6)) {
  5356. month = get_month_index(month_str);
  5357. if ((month >= 0) && (year >= 1970)) {
  5358. memset(&tm, 0, sizeof(tm));
  5359. tm.tm_year = year - 1900;
  5360. tm.tm_mon = month;
  5361. tm.tm_mday = day;
  5362. tm.tm_hour = hour;
  5363. tm.tm_min = minute;
  5364. tm.tm_sec = second;
  5365. result = timegm(&tm);
  5366. }
  5367. }
  5368. return result;
  5369. }
  5370. #endif /* !NO_CACHING */
  5371. /* Protect against directory disclosure attack by removing '..',
  5372. * excessive '/' and '\' characters */
  5373. static void
  5374. remove_double_dots_and_double_slashes(char *s)
  5375. {
  5376. char *p = s;
  5377. while ((s[0] == '.') && (s[1] == '.')) {
  5378. s++;
  5379. }
  5380. while (*s != '\0') {
  5381. *p++ = *s++;
  5382. if (s[-1] == '/' || s[-1] == '\\') {
  5383. /* Skip all following slashes, backslashes and double-dots */
  5384. while (s[0] != '\0') {
  5385. if (s[0] == '/' || s[0] == '\\') {
  5386. s++;
  5387. } else if (s[0] == '.' && s[1] == '.') {
  5388. s += 2;
  5389. } else {
  5390. break;
  5391. }
  5392. }
  5393. }
  5394. }
  5395. *p = '\0';
  5396. }
  5397. static const struct {
  5398. const char *extension;
  5399. size_t ext_len;
  5400. const char *mime_type;
  5401. } builtin_mime_types[] = {
  5402. /* IANA registered MIME types (http://www.iana.org/assignments/media-types)
  5403. * application types */
  5404. {".doc", 4, "application/msword"},
  5405. {".eps", 4, "application/postscript"},
  5406. {".exe", 4, "application/octet-stream"},
  5407. {".js", 3, "application/javascript"},
  5408. {".json", 5, "application/json"},
  5409. {".pdf", 4, "application/pdf"},
  5410. {".ps", 3, "application/postscript"},
  5411. {".rtf", 4, "application/rtf"},
  5412. {".xhtml", 6, "application/xhtml+xml"},
  5413. {".xsl", 4, "application/xml"},
  5414. {".xslt", 5, "application/xml"},
  5415. /* fonts */
  5416. {".ttf", 4, "application/font-sfnt"},
  5417. {".cff", 4, "application/font-sfnt"},
  5418. {".otf", 4, "application/font-sfnt"},
  5419. {".aat", 4, "application/font-sfnt"},
  5420. {".sil", 4, "application/font-sfnt"},
  5421. {".pfr", 4, "application/font-tdpfr"},
  5422. {".woff", 5, "application/font-woff"},
  5423. /* audio */
  5424. {".mp3", 4, "audio/mpeg"},
  5425. {".oga", 4, "audio/ogg"},
  5426. {".ogg", 4, "audio/ogg"},
  5427. /* image */
  5428. {".gif", 4, "image/gif"},
  5429. {".ief", 4, "image/ief"},
  5430. {".jpeg", 5, "image/jpeg"},
  5431. {".jpg", 4, "image/jpeg"},
  5432. {".jpm", 4, "image/jpm"},
  5433. {".jpx", 4, "image/jpx"},
  5434. {".png", 4, "image/png"},
  5435. {".svg", 4, "image/svg+xml"},
  5436. {".tif", 4, "image/tiff"},
  5437. {".tiff", 5, "image/tiff"},
  5438. /* model */
  5439. {".wrl", 4, "model/vrml"},
  5440. /* text */
  5441. {".css", 4, "text/css"},
  5442. {".csv", 4, "text/csv"},
  5443. {".htm", 4, "text/html"},
  5444. {".html", 5, "text/html"},
  5445. {".sgm", 4, "text/sgml"},
  5446. {".shtm", 5, "text/html"},
  5447. {".shtml", 6, "text/html"},
  5448. {".txt", 4, "text/plain"},
  5449. {".xml", 4, "text/xml"},
  5450. /* video */
  5451. {".mov", 4, "video/quicktime"},
  5452. {".mp4", 4, "video/mp4"},
  5453. {".mpeg", 5, "video/mpeg"},
  5454. {".mpg", 4, "video/mpeg"},
  5455. {".ogv", 4, "video/ogg"},
  5456. {".qt", 3, "video/quicktime"},
  5457. /* not registered types
  5458. * (http://reference.sitepoint.com/html/mime-types-full,
  5459. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  5460. {".arj", 4, "application/x-arj-compressed"},
  5461. {".gz", 3, "application/x-gunzip"},
  5462. {".rar", 4, "application/x-arj-compressed"},
  5463. {".swf", 4, "application/x-shockwave-flash"},
  5464. {".tar", 4, "application/x-tar"},
  5465. {".tgz", 4, "application/x-tar-gz"},
  5466. {".torrent", 8, "application/x-bittorrent"},
  5467. {".ppt", 4, "application/x-mspowerpoint"},
  5468. {".xls", 4, "application/x-msexcel"},
  5469. {".zip", 4, "application/x-zip-compressed"},
  5470. {".aac",
  5471. 4,
  5472. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  5473. {".aif", 4, "audio/x-aif"},
  5474. {".m3u", 4, "audio/x-mpegurl"},
  5475. {".mid", 4, "audio/x-midi"},
  5476. {".ra", 3, "audio/x-pn-realaudio"},
  5477. {".ram", 4, "audio/x-pn-realaudio"},
  5478. {".wav", 4, "audio/x-wav"},
  5479. {".bmp", 4, "image/bmp"},
  5480. {".ico", 4, "image/x-icon"},
  5481. {".pct", 4, "image/x-pct"},
  5482. {".pict", 5, "image/pict"},
  5483. {".rgb", 4, "image/x-rgb"},
  5484. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  5485. {".asf", 4, "video/x-ms-asf"},
  5486. {".avi", 4, "video/x-msvideo"},
  5487. {".m4v", 4, "video/x-m4v"},
  5488. {NULL, 0, NULL}};
  5489. const char *
  5490. mg_get_builtin_mime_type(const char *path)
  5491. {
  5492. const char *ext;
  5493. size_t i, path_len;
  5494. path_len = strlen(path);
  5495. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  5496. ext = path + (path_len - builtin_mime_types[i].ext_len);
  5497. if (path_len > builtin_mime_types[i].ext_len
  5498. && mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {
  5499. return builtin_mime_types[i].mime_type;
  5500. }
  5501. }
  5502. return "text/plain";
  5503. }
  5504. /* Look at the "path" extension and figure what mime type it has.
  5505. * Store mime type in the vector. */
  5506. static void
  5507. get_mime_type(struct mg_context *ctx, const char *path, struct vec *vec)
  5508. {
  5509. struct vec ext_vec, mime_vec;
  5510. const char *list, *ext;
  5511. size_t path_len;
  5512. path_len = strlen(path);
  5513. if (ctx == NULL || vec == NULL) {
  5514. return;
  5515. }
  5516. /* Scan user-defined mime types first, in case user wants to
  5517. * override default mime types. */
  5518. list = ctx->config[EXTRA_MIME_TYPES];
  5519. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  5520. /* ext now points to the path suffix */
  5521. ext = path + path_len - ext_vec.len;
  5522. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  5523. *vec = mime_vec;
  5524. return;
  5525. }
  5526. }
  5527. vec->ptr = mg_get_builtin_mime_type(path);
  5528. vec->len = strlen(vec->ptr);
  5529. }
  5530. /* Stringify binary data. Output buffer must be twice as big as input,
  5531. * because each byte takes 2 bytes in string representation */
  5532. static void
  5533. bin2str(char *to, const unsigned char *p, size_t len)
  5534. {
  5535. static const char *hex = "0123456789abcdef";
  5536. for (; len--; p++) {
  5537. *to++ = hex[p[0] >> 4];
  5538. *to++ = hex[p[0] & 0x0f];
  5539. }
  5540. *to = '\0';
  5541. }
  5542. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes. */
  5543. char *
  5544. mg_md5(char buf[33], ...)
  5545. {
  5546. md5_byte_t hash[16];
  5547. const char *p;
  5548. va_list ap;
  5549. md5_state_t ctx;
  5550. md5_init(&ctx);
  5551. va_start(ap, buf);
  5552. while ((p = va_arg(ap, const char *)) != NULL) {
  5553. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  5554. }
  5555. va_end(ap);
  5556. md5_finish(&ctx, hash);
  5557. bin2str(buf, hash, sizeof(hash));
  5558. return buf;
  5559. }
  5560. /* Check the user's password, return 1 if OK */
  5561. static int
  5562. check_password(const char *method,
  5563. const char *ha1,
  5564. const char *uri,
  5565. const char *nonce,
  5566. const char *nc,
  5567. const char *cnonce,
  5568. const char *qop,
  5569. const char *response)
  5570. {
  5571. char ha2[32 + 1], expected_response[32 + 1];
  5572. /* Some of the parameters may be NULL */
  5573. if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL
  5574. || qop == NULL
  5575. || response == NULL) {
  5576. return 0;
  5577. }
  5578. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  5579. if (strlen(response) != 32) {
  5580. return 0;
  5581. }
  5582. mg_md5(ha2, method, ":", uri, NULL);
  5583. mg_md5(expected_response,
  5584. ha1,
  5585. ":",
  5586. nonce,
  5587. ":",
  5588. nc,
  5589. ":",
  5590. cnonce,
  5591. ":",
  5592. qop,
  5593. ":",
  5594. ha2,
  5595. NULL);
  5596. return mg_strcasecmp(response, expected_response) == 0;
  5597. }
  5598. /* Use the global passwords file, if specified by auth_gpass option,
  5599. * or search for .htpasswd in the requested directory. */
  5600. static void
  5601. open_auth_file(struct mg_connection *conn,
  5602. const char *path,
  5603. struct mg_file *filep)
  5604. {
  5605. if (conn != NULL && conn->ctx != NULL) {
  5606. char name[PATH_MAX];
  5607. const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
  5608. int truncated;
  5609. if (gpass != NULL) {
  5610. /* Use global passwords file */
  5611. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  5612. #ifdef DEBUG
  5613. /* Use mg_cry here, since gpass has been configured. */
  5614. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  5615. #endif
  5616. }
  5617. /* Important: using local struct mg_file to test path for
  5618. * is_directory flag. If filep is used, mg_stat() makes it
  5619. * appear as if auth file was opened.
  5620. * TODO(mid): Check if this is still required after rewriting
  5621. * mg_stat */
  5622. } else if (mg_stat(conn, path, &filep->stat)
  5623. && filep->stat.is_directory) {
  5624. mg_snprintf(conn,
  5625. &truncated,
  5626. name,
  5627. sizeof(name),
  5628. "%s/%s",
  5629. path,
  5630. PASSWORDS_FILE_NAME);
  5631. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  5632. #ifdef DEBUG
  5633. /* Don't use mg_cry here, but only a trace, since this is
  5634. * a typical case. It will occur for every directory
  5635. * without a password file. */
  5636. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  5637. #endif
  5638. }
  5639. } else {
  5640. /* Try to find .htpasswd in requested directory. */
  5641. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  5642. if (e[0] == '/') {
  5643. break;
  5644. }
  5645. }
  5646. mg_snprintf(conn,
  5647. &truncated,
  5648. name,
  5649. sizeof(name),
  5650. "%.*s/%s",
  5651. (int)(e - p),
  5652. p,
  5653. PASSWORDS_FILE_NAME);
  5654. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  5655. #ifdef DEBUG
  5656. /* Don't use mg_cry here, but only a trace, since this is
  5657. * a typical case. It will occur for every directory
  5658. * without a password file. */
  5659. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  5660. #endif
  5661. }
  5662. }
  5663. }
  5664. }
  5665. /* Parsed Authorization header */
  5666. struct ah {
  5667. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  5668. };
  5669. /* Return 1 on success. Always initializes the ah structure. */
  5670. static int
  5671. parse_auth_header(struct mg_connection *conn,
  5672. char *buf,
  5673. size_t buf_size,
  5674. struct ah *ah)
  5675. {
  5676. char *name, *value, *s;
  5677. const char *auth_header;
  5678. uint64_t nonce;
  5679. if (!ah || !conn) {
  5680. return 0;
  5681. }
  5682. (void)memset(ah, 0, sizeof(*ah));
  5683. if ((auth_header = mg_get_header(conn, "Authorization")) == NULL
  5684. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  5685. return 0;
  5686. }
  5687. /* Make modifiable copy of the auth header */
  5688. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  5689. s = buf;
  5690. /* Parse authorization header */
  5691. for (;;) {
  5692. /* Gobble initial spaces */
  5693. while (isspace(*(unsigned char *)s)) {
  5694. s++;
  5695. }
  5696. name = skip_quoted(&s, "=", " ", 0);
  5697. /* Value is either quote-delimited, or ends at first comma or space. */
  5698. if (s[0] == '\"') {
  5699. s++;
  5700. value = skip_quoted(&s, "\"", " ", '\\');
  5701. if (s[0] == ',') {
  5702. s++;
  5703. }
  5704. } else {
  5705. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  5706. * spaces */
  5707. }
  5708. if (*name == '\0') {
  5709. break;
  5710. }
  5711. if (!strcmp(name, "username")) {
  5712. ah->user = value;
  5713. } else if (!strcmp(name, "cnonce")) {
  5714. ah->cnonce = value;
  5715. } else if (!strcmp(name, "response")) {
  5716. ah->response = value;
  5717. } else if (!strcmp(name, "uri")) {
  5718. ah->uri = value;
  5719. } else if (!strcmp(name, "qop")) {
  5720. ah->qop = value;
  5721. } else if (!strcmp(name, "nc")) {
  5722. ah->nc = value;
  5723. } else if (!strcmp(name, "nonce")) {
  5724. ah->nonce = value;
  5725. }
  5726. }
  5727. #ifndef NO_NONCE_CHECK
  5728. /* Read the nonce from the response. */
  5729. if (ah->nonce == NULL) {
  5730. return 0;
  5731. }
  5732. s = NULL;
  5733. nonce = strtoull(ah->nonce, &s, 10);
  5734. if ((s == NULL) || (*s != 0)) {
  5735. return 0;
  5736. }
  5737. /* Convert the nonce from the client to a number. */
  5738. nonce ^= conn->ctx->auth_nonce_mask;
  5739. /* The converted number corresponds to the time the nounce has been
  5740. * created. This should not be earlier than the server start. */
  5741. /* Server side nonce check is valuable in all situations but one:
  5742. * if the server restarts frequently, but the client should not see
  5743. * that, so the server should accept nonces from previous starts. */
  5744. /* However, the reasonable default is to not accept a nonce from a
  5745. * previous start, so if anyone changed the access rights between
  5746. * two restarts, a new login is required. */
  5747. if (nonce < (uint64_t)conn->ctx->start_time) {
  5748. /* nonce is from a previous start of the server and no longer valid
  5749. * (replay attack?) */
  5750. return 0;
  5751. }
  5752. /* Check if the nonce is too high, so it has not (yet) been used by the
  5753. * server. */
  5754. if (nonce >= ((uint64_t)conn->ctx->start_time + conn->ctx->nonce_count)) {
  5755. return 0;
  5756. }
  5757. #else
  5758. (void)nonce;
  5759. #endif
  5760. /* CGI needs it as REMOTE_USER */
  5761. if (ah->user != NULL) {
  5762. conn->request_info.remote_user = mg_strdup(ah->user);
  5763. } else {
  5764. return 0;
  5765. }
  5766. return 1;
  5767. }
  5768. static const char *
  5769. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  5770. {
  5771. const char *eof;
  5772. size_t len;
  5773. const char *memend;
  5774. if (!filep) {
  5775. return NULL;
  5776. }
  5777. if (filep->access.membuf != NULL && *p != NULL) {
  5778. memend = (const char *)&filep->access.membuf[filep->stat.size];
  5779. /* Search for \n from p till the end of stream */
  5780. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  5781. if (eof != NULL) {
  5782. eof += 1; /* Include \n */
  5783. } else {
  5784. eof = memend; /* Copy remaining data */
  5785. }
  5786. len =
  5787. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  5788. memcpy(buf, *p, len);
  5789. buf[len] = '\0';
  5790. *p += len;
  5791. return len ? eof : NULL;
  5792. } else if (filep->access.fp != NULL) {
  5793. return fgets(buf, (int)size, filep->access.fp);
  5794. } else {
  5795. return NULL;
  5796. }
  5797. }
  5798. /* Define the initial recursion depth for procesesing htpasswd files that
  5799. * include other htpasswd
  5800. * (or even the same) files. It is not difficult to provide a file or files
  5801. * s.t. they force civetweb
  5802. * to infinitely recurse and then crash.
  5803. */
  5804. #define INITIAL_DEPTH 9
  5805. #if INITIAL_DEPTH <= 0
  5806. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  5807. #endif
  5808. struct read_auth_file_struct {
  5809. struct mg_connection *conn;
  5810. struct ah ah;
  5811. char *domain;
  5812. char buf[256 + 256 + 40];
  5813. char *f_user;
  5814. char *f_domain;
  5815. char *f_ha1;
  5816. };
  5817. static int
  5818. read_auth_file(struct mg_file *filep,
  5819. struct read_auth_file_struct *workdata,
  5820. int depth)
  5821. {
  5822. char *p;
  5823. int is_authorized = 0;
  5824. struct mg_file fp;
  5825. size_t l;
  5826. if (!filep || !workdata || 0 == depth) {
  5827. return 0;
  5828. }
  5829. /* Loop over passwords file */
  5830. p = (char *)filep->access.membuf;
  5831. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  5832. l = strlen(workdata->buf);
  5833. while (l > 0) {
  5834. if (isspace(workdata->buf[l - 1])
  5835. || iscntrl(workdata->buf[l - 1])) {
  5836. l--;
  5837. workdata->buf[l] = 0;
  5838. } else
  5839. break;
  5840. }
  5841. if (l < 1) {
  5842. continue;
  5843. }
  5844. workdata->f_user = workdata->buf;
  5845. if (workdata->f_user[0] == ':') {
  5846. /* user names may not contain a ':' and may not be empty,
  5847. * so lines starting with ':' may be used for a special purpose */
  5848. if (workdata->f_user[1] == '#') {
  5849. /* :# is a comment */
  5850. continue;
  5851. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  5852. if (mg_fopen(workdata->conn,
  5853. workdata->f_user + 9,
  5854. MG_FOPEN_MODE_READ,
  5855. &fp)) {
  5856. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  5857. (void)mg_fclose(
  5858. &fp.access); /* ignore error on read only file */
  5859. /* No need to continue processing files once we have a
  5860. * match, since nothing will reset it back
  5861. * to 0.
  5862. */
  5863. if (is_authorized) {
  5864. return is_authorized;
  5865. }
  5866. } else {
  5867. mg_cry(workdata->conn,
  5868. "%s: cannot open authorization file: %s",
  5869. __func__,
  5870. workdata->buf);
  5871. }
  5872. continue;
  5873. }
  5874. /* everything is invalid for the moment (might change in the
  5875. * future) */
  5876. mg_cry(workdata->conn,
  5877. "%s: syntax error in authorization file: %s",
  5878. __func__,
  5879. workdata->buf);
  5880. continue;
  5881. }
  5882. workdata->f_domain = strchr(workdata->f_user, ':');
  5883. if (workdata->f_domain == NULL) {
  5884. mg_cry(workdata->conn,
  5885. "%s: syntax error in authorization file: %s",
  5886. __func__,
  5887. workdata->buf);
  5888. continue;
  5889. }
  5890. *(workdata->f_domain) = 0;
  5891. (workdata->f_domain)++;
  5892. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  5893. if (workdata->f_ha1 == NULL) {
  5894. mg_cry(workdata->conn,
  5895. "%s: syntax error in authorization file: %s",
  5896. __func__,
  5897. workdata->buf);
  5898. continue;
  5899. }
  5900. *(workdata->f_ha1) = 0;
  5901. (workdata->f_ha1)++;
  5902. if (!strcmp(workdata->ah.user, workdata->f_user)
  5903. && !strcmp(workdata->domain, workdata->f_domain)) {
  5904. return check_password(workdata->conn->request_info.request_method,
  5905. workdata->f_ha1,
  5906. workdata->ah.uri,
  5907. workdata->ah.nonce,
  5908. workdata->ah.nc,
  5909. workdata->ah.cnonce,
  5910. workdata->ah.qop,
  5911. workdata->ah.response);
  5912. }
  5913. }
  5914. return is_authorized;
  5915. }
  5916. /* Authorize against the opened passwords file. Return 1 if authorized. */
  5917. static int
  5918. authorize(struct mg_connection *conn, struct mg_file *filep)
  5919. {
  5920. struct read_auth_file_struct workdata;
  5921. char buf[MG_BUF_LEN];
  5922. if (!conn || !conn->ctx) {
  5923. return 0;
  5924. }
  5925. memset(&workdata, 0, sizeof(workdata));
  5926. workdata.conn = conn;
  5927. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  5928. return 0;
  5929. }
  5930. workdata.domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  5931. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  5932. }
  5933. /* Return 1 if request is authorised, 0 otherwise. */
  5934. static int
  5935. check_authorization(struct mg_connection *conn, const char *path)
  5936. {
  5937. char fname[PATH_MAX];
  5938. struct vec uri_vec, filename_vec;
  5939. const char *list;
  5940. struct mg_file file = STRUCT_FILE_INITIALIZER;
  5941. int authorized = 1, truncated;
  5942. if (!conn || !conn->ctx) {
  5943. return 0;
  5944. }
  5945. list = conn->ctx->config[PROTECT_URI];
  5946. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  5947. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  5948. mg_snprintf(conn,
  5949. &truncated,
  5950. fname,
  5951. sizeof(fname),
  5952. "%.*s",
  5953. (int)filename_vec.len,
  5954. filename_vec.ptr);
  5955. if (truncated
  5956. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  5957. mg_cry(conn,
  5958. "%s: cannot open %s: %s",
  5959. __func__,
  5960. fname,
  5961. strerror(errno));
  5962. }
  5963. break;
  5964. }
  5965. }
  5966. if (!is_file_opened(&file.access)) {
  5967. open_auth_file(conn, path, &file);
  5968. }
  5969. if (is_file_opened(&file.access)) {
  5970. authorized = authorize(conn, &file);
  5971. (void)mg_fclose(&file.access); /* ignore error on read only file */
  5972. }
  5973. return authorized;
  5974. }
  5975. static void
  5976. send_authorization_request(struct mg_connection *conn)
  5977. {
  5978. char date[64];
  5979. time_t curtime = time(NULL);
  5980. if (conn && conn->ctx) {
  5981. uint64_t nonce = (uint64_t)(conn->ctx->start_time);
  5982. (void)pthread_mutex_lock(&conn->ctx->nonce_mutex);
  5983. nonce += conn->ctx->nonce_count;
  5984. ++conn->ctx->nonce_count;
  5985. (void)pthread_mutex_unlock(&conn->ctx->nonce_mutex);
  5986. nonce ^= conn->ctx->auth_nonce_mask;
  5987. conn->status_code = 401;
  5988. conn->must_close = 1;
  5989. gmt_time_string(date, sizeof(date), &curtime);
  5990. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  5991. send_no_cache_header(conn);
  5992. send_additional_header(conn);
  5993. mg_printf(conn,
  5994. "Date: %s\r\n"
  5995. "Connection: %s\r\n"
  5996. "Content-Length: 0\r\n"
  5997. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  5998. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  5999. date,
  6000. suggest_connection_header(conn),
  6001. conn->ctx->config[AUTHENTICATION_DOMAIN],
  6002. nonce);
  6003. }
  6004. }
  6005. #if !defined(NO_FILES)
  6006. static int
  6007. is_authorized_for_put(struct mg_connection *conn)
  6008. {
  6009. if (conn) {
  6010. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6011. const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
  6012. int ret = 0;
  6013. if (passfile != NULL
  6014. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  6015. ret = authorize(conn, &file);
  6016. (void)mg_fclose(&file.access); /* ignore error on read only file */
  6017. }
  6018. return ret;
  6019. }
  6020. return 0;
  6021. }
  6022. #endif
  6023. int
  6024. mg_modify_passwords_file(const char *fname,
  6025. const char *domain,
  6026. const char *user,
  6027. const char *pass)
  6028. {
  6029. int found, i;
  6030. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  6031. FILE *fp, *fp2;
  6032. found = 0;
  6033. fp = fp2 = NULL;
  6034. /* Regard empty password as no password - remove user record. */
  6035. if (pass != NULL && pass[0] == '\0') {
  6036. pass = NULL;
  6037. }
  6038. /* Other arguments must not be empty */
  6039. if (fname == NULL || domain == NULL || user == NULL) {
  6040. return 0;
  6041. }
  6042. /* Using the given file format, user name and domain must not contain ':'
  6043. */
  6044. if (strchr(user, ':') != NULL) {
  6045. return 0;
  6046. }
  6047. if (strchr(domain, ':') != NULL) {
  6048. return 0;
  6049. }
  6050. /* Do not allow control characters like newline in user name and domain.
  6051. * Do not allow excessively long names either. */
  6052. for (i = 0; i < 255 && user[i] != 0; i++) {
  6053. if (iscntrl(user[i])) {
  6054. return 0;
  6055. }
  6056. }
  6057. if (user[i]) {
  6058. return 0;
  6059. }
  6060. for (i = 0; i < 255 && domain[i] != 0; i++) {
  6061. if (iscntrl(domain[i])) {
  6062. return 0;
  6063. }
  6064. }
  6065. if (domain[i]) {
  6066. return 0;
  6067. }
  6068. /* The maximum length of the path to the password file is limited */
  6069. if ((strlen(fname) + 4) >= PATH_MAX) {
  6070. return 0;
  6071. }
  6072. /* Create a temporary file name. Length has been checked before. */
  6073. strcpy(tmp, fname);
  6074. strcat(tmp, ".tmp");
  6075. /* Create the file if does not exist */
  6076. /* Use of fopen here is OK, since fname is only ASCII */
  6077. if ((fp = fopen(fname, "a+")) != NULL) {
  6078. (void)fclose(fp);
  6079. }
  6080. /* Open the given file and temporary file */
  6081. if ((fp = fopen(fname, "r")) == NULL) {
  6082. return 0;
  6083. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  6084. fclose(fp);
  6085. return 0;
  6086. }
  6087. /* Copy the stuff to temporary file */
  6088. while (fgets(line, sizeof(line), fp) != NULL) {
  6089. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  6090. continue;
  6091. }
  6092. u[255] = 0;
  6093. d[255] = 0;
  6094. if (!strcmp(u, user) && !strcmp(d, domain)) {
  6095. found++;
  6096. if (pass != NULL) {
  6097. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  6098. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  6099. }
  6100. } else {
  6101. fprintf(fp2, "%s", line);
  6102. }
  6103. }
  6104. /* If new user, just add it */
  6105. if (!found && pass != NULL) {
  6106. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  6107. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  6108. }
  6109. /* Close files */
  6110. fclose(fp);
  6111. fclose(fp2);
  6112. /* Put the temp file in place of real file */
  6113. IGNORE_UNUSED_RESULT(remove(fname));
  6114. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  6115. return 1;
  6116. }
  6117. static int
  6118. is_valid_port(unsigned long port)
  6119. {
  6120. return (port <= 0xffff);
  6121. }
  6122. static int
  6123. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  6124. {
  6125. struct addrinfo hints, *res, *ressave;
  6126. int func_ret = 0;
  6127. int gai_ret;
  6128. memset(&hints, 0, sizeof(struct addrinfo));
  6129. hints.ai_family = af;
  6130. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  6131. if (gai_ret != 0) {
  6132. /* gai_strerror could be used to convert gai_ret to a string */
  6133. /* POSIX return values: see
  6134. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  6135. */
  6136. /* Windows return values: see
  6137. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  6138. */
  6139. return 0;
  6140. }
  6141. ressave = res;
  6142. while (res) {
  6143. if (dstlen >= res->ai_addrlen) {
  6144. memcpy(dst, res->ai_addr, res->ai_addrlen);
  6145. func_ret = 1;
  6146. }
  6147. res = res->ai_next;
  6148. }
  6149. freeaddrinfo(ressave);
  6150. return func_ret;
  6151. }
  6152. static int
  6153. connect_socket(struct mg_context *ctx /* may be NULL */,
  6154. const char *host,
  6155. int port,
  6156. int use_ssl,
  6157. char *ebuf,
  6158. size_t ebuf_len,
  6159. SOCKET *sock /* output: socket, must not be NULL */,
  6160. union usa *sa /* output: socket address, must not be NULL */
  6161. )
  6162. {
  6163. int ip_ver = 0;
  6164. *sock = INVALID_SOCKET;
  6165. memset(sa, 0, sizeof(*sa));
  6166. if (ebuf_len > 0) {
  6167. *ebuf = 0;
  6168. }
  6169. if (host == NULL) {
  6170. mg_snprintf(NULL,
  6171. NULL, /* No truncation check for ebuf */
  6172. ebuf,
  6173. ebuf_len,
  6174. "%s",
  6175. "NULL host");
  6176. return 0;
  6177. }
  6178. if (port <= 0 || !is_valid_port((unsigned)port)) {
  6179. mg_snprintf(NULL,
  6180. NULL, /* No truncation check for ebuf */
  6181. ebuf,
  6182. ebuf_len,
  6183. "%s",
  6184. "invalid port");
  6185. return 0;
  6186. }
  6187. #if !defined(NO_SSL)
  6188. #if !defined(NO_SSL_DL)
  6189. #ifdef OPENSSL_API_1_1
  6190. if (use_ssl && (TLS_client_method == NULL)) {
  6191. mg_snprintf(NULL,
  6192. NULL, /* No truncation check for ebuf */
  6193. ebuf,
  6194. ebuf_len,
  6195. "%s",
  6196. "SSL is not initialized");
  6197. return 0;
  6198. }
  6199. #else
  6200. if (use_ssl && (SSLv23_client_method == NULL)) {
  6201. mg_snprintf(NULL,
  6202. NULL, /* No truncation check for ebuf */
  6203. ebuf,
  6204. ebuf_len,
  6205. "%s",
  6206. "SSL is not initialized");
  6207. return 0;
  6208. }
  6209. #endif /* OPENSSL_API_1_1 */
  6210. #else
  6211. (void)use_ssl;
  6212. #endif /* NO_SSL_DL */
  6213. #else
  6214. (void)use_ssl;
  6215. #endif /* !defined(NO_SSL) */
  6216. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  6217. sa->sin.sin_port = htons((uint16_t)port);
  6218. ip_ver = 4;
  6219. #ifdef USE_IPV6
  6220. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  6221. sa->sin6.sin6_port = htons((uint16_t)port);
  6222. ip_ver = 6;
  6223. } else if (host[0] == '[') {
  6224. /* While getaddrinfo on Windows will work with [::1],
  6225. * getaddrinfo on Linux only works with ::1 (without []). */
  6226. size_t l = strlen(host + 1);
  6227. char *h = (l > 1) ? mg_strdup(host + 1) : NULL;
  6228. if (h) {
  6229. h[l - 1] = 0;
  6230. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  6231. sa->sin6.sin6_port = htons((uint16_t)port);
  6232. ip_ver = 6;
  6233. }
  6234. mg_free(h);
  6235. }
  6236. #endif
  6237. }
  6238. if (ip_ver == 0) {
  6239. mg_snprintf(NULL,
  6240. NULL, /* No truncation check for ebuf */
  6241. ebuf,
  6242. ebuf_len,
  6243. "%s",
  6244. "host not found");
  6245. return 0;
  6246. }
  6247. if (ip_ver == 4) {
  6248. *sock = socket(PF_INET, SOCK_STREAM, 0);
  6249. }
  6250. #ifdef USE_IPV6
  6251. else if (ip_ver == 6) {
  6252. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  6253. }
  6254. #endif
  6255. if (*sock == INVALID_SOCKET) {
  6256. mg_snprintf(NULL,
  6257. NULL, /* No truncation check for ebuf */
  6258. ebuf,
  6259. ebuf_len,
  6260. "socket(): %s",
  6261. strerror(ERRNO));
  6262. return 0;
  6263. }
  6264. set_close_on_exec(*sock, fc(ctx));
  6265. if ((ip_ver == 4)
  6266. && (connect(*sock, (struct sockaddr *)&sa->sin, sizeof(sa->sin))
  6267. == 0)) {
  6268. /* connected with IPv4 */
  6269. set_blocking_mode(*sock, 0);
  6270. return 1;
  6271. }
  6272. #ifdef USE_IPV6
  6273. if ((ip_ver == 6)
  6274. && (connect(*sock, (struct sockaddr *)&sa->sin6, sizeof(sa->sin6))
  6275. == 0)) {
  6276. /* connected with IPv6 */
  6277. set_blocking_mode(*sock, 0);
  6278. return 1;
  6279. }
  6280. #endif
  6281. /* Not connected */
  6282. mg_snprintf(NULL,
  6283. NULL, /* No truncation check for ebuf */
  6284. ebuf,
  6285. ebuf_len,
  6286. "connect(%s:%d): %s",
  6287. host,
  6288. port,
  6289. strerror(ERRNO));
  6290. closesocket(*sock);
  6291. *sock = INVALID_SOCKET;
  6292. return 0;
  6293. }
  6294. int
  6295. mg_url_encode(const char *src, char *dst, size_t dst_len)
  6296. {
  6297. static const char *dont_escape = "._-$,;~()";
  6298. static const char *hex = "0123456789abcdef";
  6299. char *pos = dst;
  6300. const char *end = dst + dst_len - 1;
  6301. for (; *src != '\0' && pos < end; src++, pos++) {
  6302. if (isalnum(*(const unsigned char *)src)
  6303. || strchr(dont_escape, *(const unsigned char *)src) != NULL) {
  6304. *pos = *src;
  6305. } else if (pos + 2 < end) {
  6306. pos[0] = '%';
  6307. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  6308. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  6309. pos += 2;
  6310. } else {
  6311. break;
  6312. }
  6313. }
  6314. *pos = '\0';
  6315. return (*src == '\0') ? (int)(pos - dst) : -1;
  6316. }
  6317. static void
  6318. print_dir_entry(struct de *de)
  6319. {
  6320. char size[64], mod[64], href[PATH_MAX * 3 /* worst case */];
  6321. struct tm *tm;
  6322. if (de->file.is_directory) {
  6323. mg_snprintf(de->conn,
  6324. NULL, /* Buffer is big enough */
  6325. size,
  6326. sizeof(size),
  6327. "%s",
  6328. "[DIRECTORY]");
  6329. } else {
  6330. /* We use (signed) cast below because MSVC 6 compiler cannot
  6331. * convert unsigned __int64 to double. Sigh. */
  6332. if (de->file.size < 1024) {
  6333. mg_snprintf(de->conn,
  6334. NULL, /* Buffer is big enough */
  6335. size,
  6336. sizeof(size),
  6337. "%d",
  6338. (int)de->file.size);
  6339. } else if (de->file.size < 0x100000) {
  6340. mg_snprintf(de->conn,
  6341. NULL, /* Buffer is big enough */
  6342. size,
  6343. sizeof(size),
  6344. "%.1fk",
  6345. (double)de->file.size / 1024.0);
  6346. } else if (de->file.size < 0x40000000) {
  6347. mg_snprintf(de->conn,
  6348. NULL, /* Buffer is big enough */
  6349. size,
  6350. sizeof(size),
  6351. "%.1fM",
  6352. (double)de->file.size / 1048576);
  6353. } else {
  6354. mg_snprintf(de->conn,
  6355. NULL, /* Buffer is big enough */
  6356. size,
  6357. sizeof(size),
  6358. "%.1fG",
  6359. (double)de->file.size / 1073741824);
  6360. }
  6361. }
  6362. /* Note: mg_snprintf will not cause a buffer overflow above.
  6363. * So, string truncation checks are not required here. */
  6364. tm = localtime(&de->file.last_modified);
  6365. if (tm != NULL) {
  6366. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  6367. } else {
  6368. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  6369. mod[sizeof(mod) - 1] = '\0';
  6370. }
  6371. mg_url_encode(de->file_name, href, sizeof(href));
  6372. de->conn->num_bytes_sent +=
  6373. mg_printf(de->conn,
  6374. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  6375. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  6376. de->conn->request_info.local_uri,
  6377. href,
  6378. de->file.is_directory ? "/" : "",
  6379. de->file_name,
  6380. de->file.is_directory ? "/" : "",
  6381. mod,
  6382. size);
  6383. }
  6384. /* This function is called from send_directory() and used for
  6385. * sorting directory entries by size, or name, or modification time.
  6386. * On windows, __cdecl specification is needed in case if project is built
  6387. * with __stdcall convention. qsort always requires __cdels callback. */
  6388. static int WINCDECL
  6389. compare_dir_entries(const void *p1, const void *p2)
  6390. {
  6391. if (p1 && p2) {
  6392. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  6393. const char *query_string = a->conn->request_info.query_string;
  6394. int cmp_result = 0;
  6395. if (query_string == NULL) {
  6396. query_string = "na";
  6397. }
  6398. if (a->file.is_directory && !b->file.is_directory) {
  6399. return -1; /* Always put directories on top */
  6400. } else if (!a->file.is_directory && b->file.is_directory) {
  6401. return 1; /* Always put directories on top */
  6402. } else if (*query_string == 'n') {
  6403. cmp_result = strcmp(a->file_name, b->file_name);
  6404. } else if (*query_string == 's') {
  6405. cmp_result = (a->file.size == b->file.size)
  6406. ? 0
  6407. : ((a->file.size > b->file.size) ? 1 : -1);
  6408. } else if (*query_string == 'd') {
  6409. cmp_result =
  6410. (a->file.last_modified == b->file.last_modified)
  6411. ? 0
  6412. : ((a->file.last_modified > b->file.last_modified) ? 1
  6413. : -1);
  6414. }
  6415. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  6416. }
  6417. return 0;
  6418. }
  6419. static int
  6420. must_hide_file(struct mg_connection *conn, const char *path)
  6421. {
  6422. if (conn && conn->ctx) {
  6423. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  6424. const char *pattern = conn->ctx->config[HIDE_FILES];
  6425. return match_prefix(pw_pattern, strlen(pw_pattern), path) > 0
  6426. || (pattern != NULL
  6427. && match_prefix(pattern, strlen(pattern), path) > 0);
  6428. }
  6429. return 0;
  6430. }
  6431. static int
  6432. scan_directory(struct mg_connection *conn,
  6433. const char *dir,
  6434. void *data,
  6435. void (*cb)(struct de *, void *))
  6436. {
  6437. char path[PATH_MAX];
  6438. struct dirent *dp;
  6439. DIR *dirp;
  6440. struct de de;
  6441. int truncated;
  6442. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  6443. return 0;
  6444. } else {
  6445. de.conn = conn;
  6446. while ((dp = mg_readdir(dirp)) != NULL) {
  6447. /* Do not show current dir and hidden files */
  6448. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  6449. || must_hide_file(conn, dp->d_name)) {
  6450. continue;
  6451. }
  6452. mg_snprintf(
  6453. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  6454. /* If we don't memset stat structure to zero, mtime will have
  6455. * garbage and strftime() will segfault later on in
  6456. * print_dir_entry(). memset is required only if mg_stat()
  6457. * fails. For more details, see
  6458. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  6459. memset(&de.file, 0, sizeof(de.file));
  6460. if (truncated) {
  6461. /* If the path is not complete, skip processing. */
  6462. continue;
  6463. }
  6464. if (!mg_stat(conn, path, &de.file)) {
  6465. mg_cry(conn,
  6466. "%s: mg_stat(%s) failed: %s",
  6467. __func__,
  6468. path,
  6469. strerror(ERRNO));
  6470. }
  6471. de.file_name = dp->d_name;
  6472. cb(&de, data);
  6473. }
  6474. (void)mg_closedir(dirp);
  6475. }
  6476. return 1;
  6477. }
  6478. #if !defined(NO_FILES)
  6479. static int
  6480. remove_directory(struct mg_connection *conn, const char *dir)
  6481. {
  6482. char path[PATH_MAX];
  6483. struct dirent *dp;
  6484. DIR *dirp;
  6485. struct de de;
  6486. int truncated;
  6487. int ok = 1;
  6488. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  6489. return 0;
  6490. } else {
  6491. de.conn = conn;
  6492. while ((dp = mg_readdir(dirp)) != NULL) {
  6493. /* Do not show current dir (but show hidden files as they will
  6494. * also be removed) */
  6495. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  6496. continue;
  6497. }
  6498. mg_snprintf(
  6499. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  6500. /* If we don't memset stat structure to zero, mtime will have
  6501. * garbage and strftime() will segfault later on in
  6502. * print_dir_entry(). memset is required only if mg_stat()
  6503. * fails. For more details, see
  6504. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  6505. memset(&de.file, 0, sizeof(de.file));
  6506. if (truncated) {
  6507. /* Do not delete anything shorter */
  6508. ok = 0;
  6509. continue;
  6510. }
  6511. if (!mg_stat(conn, path, &de.file)) {
  6512. mg_cry(conn,
  6513. "%s: mg_stat(%s) failed: %s",
  6514. __func__,
  6515. path,
  6516. strerror(ERRNO));
  6517. ok = 0;
  6518. }
  6519. if (de.file.is_directory) {
  6520. if (remove_directory(conn, path) == 0) {
  6521. ok = 0;
  6522. }
  6523. } else {
  6524. /* This will fail file is the file is in memory */
  6525. if (mg_remove(conn, path) == 0) {
  6526. ok = 0;
  6527. }
  6528. }
  6529. }
  6530. (void)mg_closedir(dirp);
  6531. IGNORE_UNUSED_RESULT(rmdir(dir));
  6532. }
  6533. return ok;
  6534. }
  6535. #endif
  6536. struct dir_scan_data {
  6537. struct de *entries;
  6538. unsigned int num_entries;
  6539. unsigned int arr_size;
  6540. };
  6541. /* Behaves like realloc(), but frees original pointer on failure */
  6542. static void *
  6543. realloc2(void *ptr, size_t size)
  6544. {
  6545. void *new_ptr = mg_realloc(ptr, size);
  6546. if (new_ptr == NULL) {
  6547. mg_free(ptr);
  6548. }
  6549. return new_ptr;
  6550. }
  6551. static void
  6552. dir_scan_callback(struct de *de, void *data)
  6553. {
  6554. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  6555. if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {
  6556. dsd->arr_size *= 2;
  6557. dsd->entries =
  6558. (struct de *)realloc2(dsd->entries,
  6559. dsd->arr_size * sizeof(dsd->entries[0]));
  6560. }
  6561. if (dsd->entries == NULL) {
  6562. /* TODO(lsm, low): propagate an error to the caller */
  6563. dsd->num_entries = 0;
  6564. } else {
  6565. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  6566. dsd->entries[dsd->num_entries].file = de->file;
  6567. dsd->entries[dsd->num_entries].conn = de->conn;
  6568. dsd->num_entries++;
  6569. }
  6570. }
  6571. static void
  6572. handle_directory_request(struct mg_connection *conn, const char *dir)
  6573. {
  6574. unsigned int i;
  6575. int sort_direction;
  6576. struct dir_scan_data data = {NULL, 0, 128};
  6577. char date[64];
  6578. time_t curtime = time(NULL);
  6579. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  6580. send_http_error(conn,
  6581. 500,
  6582. "Error: Cannot open directory\nopendir(%s): %s",
  6583. dir,
  6584. strerror(ERRNO));
  6585. return;
  6586. }
  6587. gmt_time_string(date, sizeof(date), &curtime);
  6588. if (!conn) {
  6589. return;
  6590. }
  6591. sort_direction = ((conn->request_info.query_string != NULL)
  6592. && (conn->request_info.query_string[1] == 'd'))
  6593. ? 'a'
  6594. : 'd';
  6595. conn->must_close = 1;
  6596. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  6597. send_static_cache_header(conn);
  6598. send_additional_header(conn);
  6599. mg_printf(conn,
  6600. "Date: %s\r\n"
  6601. "Connection: close\r\n"
  6602. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  6603. date);
  6604. conn->num_bytes_sent +=
  6605. mg_printf(conn,
  6606. "<html><head><title>Index of %s</title>"
  6607. "<style>th {text-align: left;}</style></head>"
  6608. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  6609. "<tr><th><a href=\"?n%c\">Name</a></th>"
  6610. "<th><a href=\"?d%c\">Modified</a></th>"
  6611. "<th><a href=\"?s%c\">Size</a></th></tr>"
  6612. "<tr><td colspan=\"3\"><hr></td></tr>",
  6613. conn->request_info.local_uri,
  6614. conn->request_info.local_uri,
  6615. sort_direction,
  6616. sort_direction,
  6617. sort_direction);
  6618. /* Print first entry - link to a parent directory */
  6619. conn->num_bytes_sent +=
  6620. mg_printf(conn,
  6621. "<tr><td><a href=\"%s%s\">%s</a></td>"
  6622. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  6623. conn->request_info.local_uri,
  6624. "..",
  6625. "Parent directory",
  6626. "-",
  6627. "-");
  6628. /* Sort and print directory entries */
  6629. if (data.entries != NULL) {
  6630. qsort(data.entries,
  6631. (size_t)data.num_entries,
  6632. sizeof(data.entries[0]),
  6633. compare_dir_entries);
  6634. for (i = 0; i < data.num_entries; i++) {
  6635. print_dir_entry(&data.entries[i]);
  6636. mg_free(data.entries[i].file_name);
  6637. }
  6638. mg_free(data.entries);
  6639. }
  6640. conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");
  6641. conn->status_code = 200;
  6642. }
  6643. /* Send len bytes from the opened file to the client. */
  6644. static void
  6645. send_file_data(struct mg_connection *conn,
  6646. struct mg_file *filep,
  6647. int64_t offset,
  6648. int64_t len)
  6649. {
  6650. char buf[MG_BUF_LEN];
  6651. int to_read, num_read, num_written;
  6652. int64_t size;
  6653. if (!filep || !conn) {
  6654. return;
  6655. }
  6656. /* Sanity check the offset */
  6657. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  6658. : (int64_t)(filep->stat.size);
  6659. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  6660. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  6661. /* file stored in memory */
  6662. if (len > size - offset) {
  6663. len = size - offset;
  6664. }
  6665. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  6666. } else if (len > 0 && filep->access.fp != NULL) {
  6667. /* file stored on disk */
  6668. #if defined(__linux__)
  6669. /* sendfile is only available for Linux */
  6670. if ((conn->ssl == 0) && (conn->throttle == 0)
  6671. && (!mg_strcasecmp(conn->ctx->config[ALLOW_SENDFILE_CALL],
  6672. "yes"))) {
  6673. off_t sf_offs = (off_t)offset;
  6674. ssize_t sf_sent;
  6675. int sf_file = fileno(filep->access.fp);
  6676. int loop_cnt = 0;
  6677. do {
  6678. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  6679. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  6680. size_t sf_tosend =
  6681. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  6682. sf_sent =
  6683. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  6684. if (sf_sent > 0) {
  6685. conn->num_bytes_sent += sf_sent;
  6686. len -= sf_sent;
  6687. offset += sf_sent;
  6688. } else if (loop_cnt == 0) {
  6689. /* This file can not be sent using sendfile.
  6690. * This might be the case for pseudo-files in the
  6691. * /sys/ and /proc/ file system.
  6692. * Use the regular user mode copy code instead. */
  6693. break;
  6694. } else if (sf_sent == 0) {
  6695. /* No error, but 0 bytes sent. May be EOF? */
  6696. return;
  6697. }
  6698. loop_cnt++;
  6699. } while ((len > 0) && (sf_sent >= 0));
  6700. if (sf_sent > 0) {
  6701. return; /* OK */
  6702. }
  6703. /* sf_sent<0 means error, thus fall back to the classic way */
  6704. /* This is always the case, if sf_file is not a "normal" file,
  6705. * e.g., for sending data from the output of a CGI process. */
  6706. offset = (int64_t)sf_offs;
  6707. }
  6708. #endif
  6709. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  6710. mg_cry(conn, "%s: fseeko() failed: %s", __func__, strerror(ERRNO));
  6711. send_http_error(
  6712. conn,
  6713. 500,
  6714. "%s",
  6715. "Error: Unable to access file at requested position.");
  6716. } else {
  6717. while (len > 0) {
  6718. /* Calculate how much to read from the file in the buffer */
  6719. to_read = sizeof(buf);
  6720. if ((int64_t)to_read > len) {
  6721. to_read = (int)len;
  6722. }
  6723. /* Read from file, exit the loop on error */
  6724. if ((num_read =
  6725. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  6726. <= 0) {
  6727. break;
  6728. }
  6729. /* Send read bytes to the client, exit the loop on error */
  6730. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  6731. != num_read) {
  6732. break;
  6733. }
  6734. /* Both read and were successful, adjust counters */
  6735. conn->num_bytes_sent += num_written;
  6736. len -= num_written;
  6737. }
  6738. }
  6739. }
  6740. }
  6741. static int
  6742. parse_range_header(const char *header, int64_t *a, int64_t *b)
  6743. {
  6744. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  6745. }
  6746. static void
  6747. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  6748. {
  6749. if (filestat != NULL && buf != NULL) {
  6750. mg_snprintf(NULL,
  6751. NULL, /* All calls to construct_etag use 64 byte buffer */
  6752. buf,
  6753. buf_len,
  6754. "\"%lx.%" INT64_FMT "\"",
  6755. (unsigned long)filestat->last_modified,
  6756. filestat->size);
  6757. }
  6758. }
  6759. static void
  6760. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  6761. {
  6762. if (filep != NULL && filep->fp != NULL) {
  6763. #ifdef _WIN32
  6764. (void)conn; /* Unused. */
  6765. #else
  6766. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  6767. mg_cry(conn,
  6768. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  6769. __func__,
  6770. strerror(ERRNO));
  6771. }
  6772. #endif
  6773. }
  6774. }
  6775. static void
  6776. handle_static_file_request(struct mg_connection *conn,
  6777. const char *path,
  6778. struct mg_file *filep,
  6779. const char *mime_type,
  6780. const char *additional_headers)
  6781. {
  6782. char date[64], lm[64], etag[64];
  6783. char range[128]; /* large enough, so there will be no overflow */
  6784. const char *msg = "OK", *hdr;
  6785. time_t curtime = time(NULL);
  6786. int64_t cl, r1, r2;
  6787. struct vec mime_vec;
  6788. int n, truncated;
  6789. char gz_path[PATH_MAX];
  6790. const char *encoding = "";
  6791. const char *cors1, *cors2, *cors3;
  6792. if (conn == NULL || conn->ctx == NULL || filep == NULL) {
  6793. return;
  6794. }
  6795. if (mime_type == NULL) {
  6796. get_mime_type(conn->ctx, path, &mime_vec);
  6797. } else {
  6798. mime_vec.ptr = mime_type;
  6799. mime_vec.len = strlen(mime_type);
  6800. }
  6801. if (filep->stat.size > INT64_MAX) {
  6802. send_http_error(conn,
  6803. 500,
  6804. "Error: File size is too large to send\n%" INT64_FMT,
  6805. filep->stat.size);
  6806. }
  6807. cl = (int64_t)filep->stat.size;
  6808. conn->status_code = 200;
  6809. range[0] = '\0';
  6810. /* if this file is in fact a pre-gzipped file, rewrite its filename
  6811. * it's important to rewrite the filename after resolving
  6812. * the mime type from it, to preserve the actual file's type */
  6813. if (filep->stat.is_gzipped) {
  6814. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  6815. if (truncated) {
  6816. send_http_error(conn,
  6817. 500,
  6818. "Error: Path of zipped file too long (%s)",
  6819. path);
  6820. return;
  6821. }
  6822. path = gz_path;
  6823. encoding = "Content-Encoding: gzip\r\n";
  6824. }
  6825. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  6826. send_http_error(conn,
  6827. 500,
  6828. "Error: Cannot open file\nfopen(%s): %s",
  6829. path,
  6830. strerror(ERRNO));
  6831. return;
  6832. }
  6833. fclose_on_exec(&filep->access, conn);
  6834. /* If Range: header specified, act accordingly */
  6835. r1 = r2 = 0;
  6836. hdr = mg_get_header(conn, "Range");
  6837. if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 && r1 >= 0
  6838. && r2 >= 0) {
  6839. /* actually, range requests don't play well with a pre-gzipped
  6840. * file (since the range is specified in the uncompressed space) */
  6841. if (filep->stat.is_gzipped) {
  6842. send_http_error(
  6843. conn,
  6844. 501,
  6845. "%s",
  6846. "Error: Range requests in gzipped files are not supported");
  6847. (void)mg_fclose(
  6848. &filep->access); /* ignore error on read only file */
  6849. return;
  6850. }
  6851. conn->status_code = 206;
  6852. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  6853. mg_snprintf(conn,
  6854. NULL, /* range buffer is big enough */
  6855. range,
  6856. sizeof(range),
  6857. "Content-Range: bytes "
  6858. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  6859. r1,
  6860. r1 + cl - 1,
  6861. filep->stat.size);
  6862. msg = "Partial Content";
  6863. }
  6864. hdr = mg_get_header(conn, "Origin");
  6865. if (hdr) {
  6866. /* Cross-origin resource sharing (CORS), see
  6867. * http://www.html5rocks.com/en/tutorials/cors/,
  6868. * http://www.html5rocks.com/static/images/cors_server_flowchart.png -
  6869. * preflight is not supported for files. */
  6870. cors1 = "Access-Control-Allow-Origin: ";
  6871. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  6872. cors3 = "\r\n";
  6873. } else {
  6874. cors1 = cors2 = cors3 = "";
  6875. }
  6876. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
  6877. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  6878. gmt_time_string(date, sizeof(date), &curtime);
  6879. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  6880. construct_etag(etag, sizeof(etag), &filep->stat);
  6881. (void)mg_printf(conn,
  6882. "HTTP/1.1 %d %s\r\n"
  6883. "%s%s%s"
  6884. "Date: %s\r\n",
  6885. conn->status_code,
  6886. msg,
  6887. cors1,
  6888. cors2,
  6889. cors3,
  6890. date);
  6891. send_static_cache_header(conn);
  6892. send_additional_header(conn);
  6893. (void)mg_printf(conn,
  6894. "Last-Modified: %s\r\n"
  6895. "Etag: %s\r\n"
  6896. "Content-Type: %.*s\r\n"
  6897. "Content-Length: %" INT64_FMT "\r\n"
  6898. "Connection: %s\r\n"
  6899. "Accept-Ranges: bytes\r\n"
  6900. "%s%s",
  6901. lm,
  6902. etag,
  6903. (int)mime_vec.len,
  6904. mime_vec.ptr,
  6905. cl,
  6906. suggest_connection_header(conn),
  6907. range,
  6908. encoding);
  6909. /* The previous code must not add any header starting with X- to make
  6910. * sure no one of the additional_headers is included twice */
  6911. if (additional_headers != NULL) {
  6912. (void)mg_printf(conn,
  6913. "%.*s\r\n\r\n",
  6914. (int)strlen(additional_headers),
  6915. additional_headers);
  6916. } else {
  6917. (void)mg_printf(conn, "\r\n");
  6918. }
  6919. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  6920. send_file_data(conn, filep, r1, cl);
  6921. }
  6922. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  6923. }
  6924. #if !defined(NO_CACHING)
  6925. static void
  6926. handle_not_modified_static_file_request(struct mg_connection *conn,
  6927. struct mg_file *filep)
  6928. {
  6929. char date[64], lm[64], etag[64];
  6930. time_t curtime = time(NULL);
  6931. if (conn == NULL || filep == NULL) {
  6932. return;
  6933. }
  6934. conn->status_code = 304;
  6935. gmt_time_string(date, sizeof(date), &curtime);
  6936. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  6937. construct_etag(etag, sizeof(etag), &filep->stat);
  6938. (void)mg_printf(conn,
  6939. "HTTP/1.1 %d %s\r\n"
  6940. "Date: %s\r\n",
  6941. conn->status_code,
  6942. mg_get_response_code_text(conn, conn->status_code),
  6943. date);
  6944. send_static_cache_header(conn);
  6945. send_additional_header(conn);
  6946. (void)mg_printf(conn,
  6947. "Last-Modified: %s\r\n"
  6948. "Etag: %s\r\n"
  6949. "Connection: %s\r\n"
  6950. "\r\n",
  6951. lm,
  6952. etag,
  6953. suggest_connection_header(conn));
  6954. }
  6955. #endif
  6956. void
  6957. mg_send_file(struct mg_connection *conn, const char *path)
  6958. {
  6959. mg_send_mime_file(conn, path, NULL);
  6960. }
  6961. void
  6962. mg_send_mime_file(struct mg_connection *conn,
  6963. const char *path,
  6964. const char *mime_type)
  6965. {
  6966. mg_send_mime_file2(conn, path, mime_type, NULL);
  6967. }
  6968. void
  6969. mg_send_mime_file2(struct mg_connection *conn,
  6970. const char *path,
  6971. const char *mime_type,
  6972. const char *additional_headers)
  6973. {
  6974. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6975. if (mg_stat(conn, path, &file.stat)) {
  6976. if (file.stat.is_directory) {
  6977. if (!conn) {
  6978. return;
  6979. }
  6980. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  6981. "yes")) {
  6982. handle_directory_request(conn, path);
  6983. } else {
  6984. send_http_error(conn,
  6985. 403,
  6986. "%s",
  6987. "Error: Directory listing denied");
  6988. }
  6989. } else {
  6990. handle_static_file_request(
  6991. conn, path, &file, mime_type, additional_headers);
  6992. }
  6993. } else {
  6994. send_http_error(conn, 404, "%s", "Error: File not found");
  6995. }
  6996. }
  6997. /* For a given PUT path, create all intermediate subdirectories.
  6998. * Return 0 if the path itself is a directory.
  6999. * Return 1 if the path leads to a file.
  7000. * Return -1 for if the path is too long.
  7001. * Return -2 if path can not be created.
  7002. */
  7003. static int
  7004. put_dir(struct mg_connection *conn, const char *path)
  7005. {
  7006. char buf[PATH_MAX];
  7007. const char *s, *p;
  7008. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7009. size_t len;
  7010. int res = 1;
  7011. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  7012. len = (size_t)(p - path);
  7013. if (len >= sizeof(buf)) {
  7014. /* path too long */
  7015. res = -1;
  7016. break;
  7017. }
  7018. memcpy(buf, path, len);
  7019. buf[len] = '\0';
  7020. /* Try to create intermediate directory */
  7021. DEBUG_TRACE("mkdir(%s)", buf);
  7022. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  7023. /* path does not exixt and can not be created */
  7024. res = -2;
  7025. break;
  7026. }
  7027. /* Is path itself a directory? */
  7028. if (p[1] == '\0') {
  7029. res = 0;
  7030. }
  7031. }
  7032. return res;
  7033. }
  7034. static void
  7035. remove_bad_file(const struct mg_connection *conn, const char *path)
  7036. {
  7037. int r = mg_remove(conn, path);
  7038. if (r != 0) {
  7039. mg_cry(conn, "%s: Cannot remove invalid file %s", __func__, path);
  7040. }
  7041. }
  7042. long long
  7043. mg_store_body(struct mg_connection *conn, const char *path)
  7044. {
  7045. char buf[MG_BUF_LEN];
  7046. long long len = 0;
  7047. int ret, n;
  7048. struct mg_file fi;
  7049. if (conn->consumed_content != 0) {
  7050. mg_cry(conn, "%s: Contents already consumed", __func__);
  7051. return -11;
  7052. }
  7053. ret = put_dir(conn, path);
  7054. if (ret < 0) {
  7055. /* -1 for path too long,
  7056. * -2 for path can not be created. */
  7057. return ret;
  7058. }
  7059. if (ret != 1) {
  7060. /* Return 0 means, path itself is a directory. */
  7061. return 0;
  7062. }
  7063. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  7064. return -12;
  7065. }
  7066. ret = mg_read(conn, buf, sizeof(buf));
  7067. while (ret > 0) {
  7068. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  7069. if (n != ret) {
  7070. (void)mg_fclose(
  7071. &fi.access); /* File is bad and will be removed anyway. */
  7072. remove_bad_file(conn, path);
  7073. return -13;
  7074. }
  7075. len += ret;
  7076. ret = mg_read(conn, buf, sizeof(buf));
  7077. }
  7078. /* File is open for writing. If fclose fails, there was probably an
  7079. * error flushing the buffer to disk, so the file on disk might be
  7080. * broken. Delete it and return an error to the caller. */
  7081. if (mg_fclose(&fi.access) != 0) {
  7082. remove_bad_file(conn, path);
  7083. return -14;
  7084. }
  7085. return len;
  7086. }
  7087. /* Parse HTTP headers from the given buffer, advance buf pointer
  7088. * to the point where parsing stopped.
  7089. * All parameters must be valid pointers (not NULL).
  7090. * Return <0 on error. */
  7091. static int
  7092. parse_http_headers(char **buf, struct mg_request_info *ri)
  7093. {
  7094. int i;
  7095. ri->num_headers = 0;
  7096. for (i = 0; i < (int)ARRAY_SIZE(ri->http_headers); i++) {
  7097. char *dp = *buf;
  7098. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  7099. dp++;
  7100. }
  7101. if (dp == *buf) {
  7102. /* End of headers reached. */
  7103. break;
  7104. }
  7105. if (*dp != ':') {
  7106. /* This is not a valid field. */
  7107. return -1;
  7108. }
  7109. /* End of header key (*dp == ':') */
  7110. /* Truncate here and set the key name */
  7111. *dp = 0;
  7112. ri->http_headers[i].name = *buf;
  7113. do {
  7114. dp++;
  7115. } while (*dp == ' ');
  7116. /* The rest of the line is the value */
  7117. ri->http_headers[i].value = dp;
  7118. *buf = dp + strcspn(dp, "\r\n");
  7119. if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) {
  7120. *buf = NULL;
  7121. }
  7122. ri->num_headers = i + 1;
  7123. if (*buf) {
  7124. (*buf)[0] = 0;
  7125. (*buf)[1] = 0;
  7126. *buf += 2;
  7127. } else {
  7128. *buf = dp;
  7129. break;
  7130. }
  7131. if ((*buf)[0] == '\r') {
  7132. /* This is the end of the header */
  7133. break;
  7134. }
  7135. }
  7136. return ri->num_headers;
  7137. }
  7138. static int
  7139. is_valid_http_method(const char *method)
  7140. {
  7141. /* Check if the method is known to the server. The list of all known
  7142. * HTTP methods can be found here at
  7143. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  7144. */
  7145. return !strcmp(method, "GET") /* HTTP (RFC 2616) */
  7146. || !strcmp(method, "POST") /* HTTP (RFC 2616) */
  7147. || !strcmp(method, "HEAD") /* HTTP (RFC 2616) */
  7148. || !strcmp(method, "PUT") /* HTTP (RFC 2616) */
  7149. || !strcmp(method, "DELETE") /* HTTP (RFC 2616) */
  7150. || !strcmp(method, "OPTIONS") /* HTTP (RFC 2616) */
  7151. /* TRACE method (RFC 2616) is not supported for security reasons */
  7152. || !strcmp(method, "CONNECT") /* HTTP (RFC 2616) */
  7153. || !strcmp(method, "PROPFIND") /* WEBDAV (RFC 2518) */
  7154. || !strcmp(method, "MKCOL") /* WEBDAV (RFC 2518) */
  7155. /* Unsupported WEBDAV Methods: */
  7156. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  7157. /* + 11 methods from RFC 3253 */
  7158. /* ORDERPATCH (RFC 3648) */
  7159. /* ACL (RFC 3744) */
  7160. /* SEARCH (RFC 5323) */
  7161. /* + MicroSoft extensions
  7162. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  7163. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  7164. || !strcmp(method, "PATCH") /* PATCH method (RFC 5789) */
  7165. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  7166. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  7167. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  7168. * to be useful for REST in case a "GET request with body" is
  7169. * required. */
  7170. || !strcmp(method, "REPORT") /* REPORT method (RFC 3253) */
  7171. ;
  7172. }
  7173. /* Parse HTTP request, fill in mg_request_info structure.
  7174. * This function modifies the buffer by NUL-terminating
  7175. * HTTP request components, header names and header values.
  7176. * Parameters:
  7177. * buf (in/out): pointer to the HTTP header to parse and split
  7178. * len (in): length of HTTP header buffer
  7179. * re (out): parsed header as mg_request_info
  7180. * buf and ri must be valid pointers (not NULL), len>0.
  7181. * Returns <0 on error. */
  7182. static int
  7183. parse_http_message(char *buf, int len, struct mg_request_info *ri)
  7184. {
  7185. int is_request, request_length;
  7186. char *start_line;
  7187. request_length = get_request_len(buf, len);
  7188. if (request_length > 0) {
  7189. /* Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_addr,
  7190. * remote_port */
  7191. ri->remote_user = ri->request_method = ri->request_uri =
  7192. ri->http_version = NULL;
  7193. ri->num_headers = 0;
  7194. buf[request_length - 1] = '\0';
  7195. /* RFC says that all initial whitespaces should be ingored */
  7196. while (*buf != '\0' && isspace(*(unsigned char *)buf)) {
  7197. buf++;
  7198. }
  7199. start_line = skip(&buf, "\r\n");
  7200. ri->request_method = skip(&start_line, " ");
  7201. ri->request_uri = skip(&start_line, " ");
  7202. ri->http_version = start_line;
  7203. /* HTTP message could be either HTTP request:
  7204. * "GET / HTTP/1.0 ..."
  7205. * or a HTTP response:
  7206. * "HTTP/1.0 200 OK ..."
  7207. * otherwise it is invalid.
  7208. */
  7209. is_request = is_valid_http_method(ri->request_method);
  7210. if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0)
  7211. || (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
  7212. /* Not a valid request or response: invalid */
  7213. return -1;
  7214. }
  7215. if (is_request) {
  7216. ri->http_version += 5;
  7217. }
  7218. if (parse_http_headers(&buf, ri) < 0) {
  7219. /* Error while parsing headers */
  7220. return -1;
  7221. }
  7222. }
  7223. return request_length;
  7224. }
  7225. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  7226. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  7227. * buffer (which marks the end of HTTP request). Buffer buf may already
  7228. * have some data. The length of the data is stored in nread.
  7229. * Upon every read operation, increase nread by the number of bytes read. */
  7230. static int
  7231. read_request(FILE *fp,
  7232. struct mg_connection *conn,
  7233. char *buf,
  7234. int bufsiz,
  7235. int *nread)
  7236. {
  7237. int request_len, n = 0;
  7238. struct timespec last_action_time;
  7239. double request_timeout;
  7240. if (!conn) {
  7241. return 0;
  7242. }
  7243. memset(&last_action_time, 0, sizeof(last_action_time));
  7244. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  7245. /* value of request_timeout is in seconds, config in milliseconds */
  7246. request_timeout = atof(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  7247. } else {
  7248. request_timeout = -1.0;
  7249. }
  7250. if (conn->handled_requests > 0) {
  7251. if (conn->ctx->config[KEEP_ALIVE_TIMEOUT]) {
  7252. request_timeout =
  7253. atof(conn->ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  7254. }
  7255. }
  7256. request_len = get_request_len(buf, *nread);
  7257. /* first time reading from this connection */
  7258. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  7259. while (request_len == 0) {
  7260. /* Full request not yet received */
  7261. if (conn->ctx->stop_flag != 0) {
  7262. /* Server is to be stopped. */
  7263. return -1;
  7264. }
  7265. if (*nread >= bufsiz) {
  7266. /* Request too long */
  7267. return -2;
  7268. }
  7269. n = pull_inner(
  7270. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  7271. if (n == -2) {
  7272. /* Receive error */
  7273. return -1;
  7274. }
  7275. if (n > 0) {
  7276. *nread += n;
  7277. request_len = get_request_len(buf, *nread);
  7278. } else {
  7279. request_len = 0;
  7280. }
  7281. if ((request_len == 0) && (request_timeout >= 0)) {
  7282. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  7283. > request_timeout) {
  7284. /* Timeout */
  7285. return -1;
  7286. }
  7287. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  7288. }
  7289. }
  7290. return request_len;
  7291. }
  7292. #if !defined(NO_CACHING)
  7293. /* Return True if we should reply 304 Not Modified. */
  7294. static int
  7295. is_not_modified(const struct mg_connection *conn,
  7296. const struct mg_file_stat *filestat)
  7297. {
  7298. char etag[64];
  7299. const char *ims = mg_get_header(conn, "If-Modified-Since");
  7300. const char *inm = mg_get_header(conn, "If-None-Match");
  7301. construct_etag(etag, sizeof(etag), filestat);
  7302. return (inm != NULL && !mg_strcasecmp(etag, inm))
  7303. || ((ims != NULL)
  7304. && (filestat->last_modified <= parse_date_string(ims)));
  7305. }
  7306. #endif /* !NO_CACHING */
  7307. #if !defined(NO_CGI) || !defined(NO_FILES)
  7308. static int
  7309. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  7310. {
  7311. const char *expect, *body;
  7312. char buf[MG_BUF_LEN];
  7313. int to_read, nread, success = 0;
  7314. int64_t buffered_len;
  7315. double timeout = -1.0;
  7316. if (!conn) {
  7317. return 0;
  7318. }
  7319. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  7320. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  7321. }
  7322. expect = mg_get_header(conn, "Expect");
  7323. /* assert(fp != NULL); */
  7324. if (!fp) {
  7325. send_http_error(conn, 500, "%s", "Error: NULL File");
  7326. return 0;
  7327. }
  7328. if (conn->content_len == -1 && !conn->is_chunked) {
  7329. /* Content length is not specified by the client. */
  7330. send_http_error(conn,
  7331. 411,
  7332. "%s",
  7333. "Error: Client did not specify content length");
  7334. } else if ((expect != NULL)
  7335. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  7336. /* Client sent an "Expect: xyz" header and xyz is not 100-continue. */
  7337. send_http_error(conn,
  7338. 417,
  7339. "Error: Can not fulfill expectation %s",
  7340. expect);
  7341. } else {
  7342. if (expect != NULL) {
  7343. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  7344. conn->status_code = 100;
  7345. } else {
  7346. conn->status_code = 200;
  7347. }
  7348. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  7349. - conn->consumed_content;
  7350. /* assert(buffered_len >= 0); */
  7351. /* assert(conn->consumed_content == 0); */
  7352. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  7353. send_http_error(conn, 500, "%s", "Error: Size mismatch");
  7354. return 0;
  7355. }
  7356. if (buffered_len > 0) {
  7357. if ((int64_t)buffered_len > conn->content_len) {
  7358. buffered_len = (int)conn->content_len;
  7359. }
  7360. body = conn->buf + conn->request_len + conn->consumed_content;
  7361. push_all(conn->ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  7362. conn->consumed_content += buffered_len;
  7363. }
  7364. nread = 0;
  7365. while (conn->consumed_content < conn->content_len) {
  7366. to_read = sizeof(buf);
  7367. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  7368. to_read = (int)(conn->content_len - conn->consumed_content);
  7369. }
  7370. nread = pull_inner(NULL, conn, buf, to_read, timeout);
  7371. if (nread == -2) {
  7372. /* error */
  7373. break;
  7374. }
  7375. if (nread > 0) {
  7376. if (push_all(conn->ctx, fp, sock, ssl, buf, nread) != nread) {
  7377. break;
  7378. }
  7379. }
  7380. conn->consumed_content += nread;
  7381. }
  7382. if (conn->consumed_content == conn->content_len) {
  7383. success = (nread >= 0);
  7384. }
  7385. /* Each error code path in this function must send an error */
  7386. if (!success) {
  7387. /* NOTE: Maybe some data has already been sent. */
  7388. /* TODO (low): If some data has been sent, a correct error
  7389. * reply can no longer be sent, so just close the connection */
  7390. send_http_error(conn, 500, "%s", "");
  7391. }
  7392. }
  7393. return success;
  7394. }
  7395. #endif
  7396. #if !defined(NO_CGI)
  7397. /* This structure helps to create an environment for the spawned CGI program.
  7398. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  7399. * last element must be NULL.
  7400. * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  7401. * strings must reside in a contiguous buffer. The end of the buffer is
  7402. * marked by two '\0' characters.
  7403. * We satisfy both worlds: we create an envp array (which is vars), all
  7404. * entries are actually pointers inside buf. */
  7405. struct cgi_environment {
  7406. struct mg_connection *conn;
  7407. /* Data block */
  7408. char *buf; /* Environment buffer */
  7409. size_t buflen; /* Space available in buf */
  7410. size_t bufused; /* Space taken in buf */
  7411. /* Index block */
  7412. char **var; /* char **envp */
  7413. size_t varlen; /* Number of variables available in var */
  7414. size_t varused; /* Number of variables stored in var */
  7415. };
  7416. static void addenv(struct cgi_environment *env,
  7417. PRINTF_FORMAT_STRING(const char *fmt),
  7418. ...) PRINTF_ARGS(2, 3);
  7419. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  7420. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  7421. static void
  7422. addenv(struct cgi_environment *env, const char *fmt, ...)
  7423. {
  7424. size_t n, space;
  7425. int truncated = 0;
  7426. char *added;
  7427. va_list ap;
  7428. /* Calculate how much space is left in the buffer */
  7429. space = (env->buflen - env->bufused);
  7430. /* Calculate an estimate for the required space */
  7431. n = strlen(fmt) + 2 + 128;
  7432. do {
  7433. if (space <= n) {
  7434. /* Allocate new buffer */
  7435. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  7436. added = (char *)mg_realloc(env->buf, n);
  7437. if (!added) {
  7438. /* Out of memory */
  7439. mg_cry(env->conn,
  7440. "%s: Cannot allocate memory for CGI variable [%s]",
  7441. __func__,
  7442. fmt);
  7443. return;
  7444. }
  7445. env->buf = added;
  7446. env->buflen = n;
  7447. space = (env->buflen - env->bufused);
  7448. }
  7449. /* Make a pointer to the free space int the buffer */
  7450. added = env->buf + env->bufused;
  7451. /* Copy VARIABLE=VALUE\0 string into the free space */
  7452. va_start(ap, fmt);
  7453. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  7454. va_end(ap);
  7455. /* Do not add truncated strings to the environment */
  7456. if (truncated) {
  7457. /* Reallocate the buffer */
  7458. space = 0;
  7459. n = 1;
  7460. }
  7461. } while (truncated);
  7462. /* Calculate number of bytes added to the environment */
  7463. n = strlen(added) + 1;
  7464. env->bufused += n;
  7465. /* Now update the variable index */
  7466. space = (env->varlen - env->varused);
  7467. if (space < 2) {
  7468. mg_cry(env->conn,
  7469. "%s: Cannot register CGI variable [%s]",
  7470. __func__,
  7471. fmt);
  7472. return;
  7473. }
  7474. /* Append a pointer to the added string into the envp array */
  7475. env->var[env->varused] = added;
  7476. env->varused++;
  7477. }
  7478. static void
  7479. prepare_cgi_environment(struct mg_connection *conn,
  7480. const char *prog,
  7481. struct cgi_environment *env)
  7482. {
  7483. const char *s;
  7484. struct vec var_vec;
  7485. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  7486. int i, truncated, uri_len;
  7487. if (conn == NULL || prog == NULL || env == NULL) {
  7488. return;
  7489. }
  7490. env->conn = conn;
  7491. env->buflen = CGI_ENVIRONMENT_SIZE;
  7492. env->bufused = 0;
  7493. env->buf = (char *)mg_malloc(env->buflen);
  7494. env->varlen = MAX_CGI_ENVIR_VARS;
  7495. env->varused = 0;
  7496. env->var = (char **)mg_malloc(env->buflen * sizeof(char *));
  7497. addenv(env, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  7498. addenv(env, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  7499. addenv(env, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  7500. addenv(env, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  7501. /* Prepare the environment block */
  7502. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  7503. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  7504. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  7505. #if defined(USE_IPV6)
  7506. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  7507. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  7508. } else
  7509. #endif
  7510. {
  7511. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  7512. }
  7513. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  7514. addenv(env, "REMOTE_ADDR=%s", src_addr);
  7515. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  7516. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  7517. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  7518. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  7519. /* SCRIPT_NAME */
  7520. uri_len = (int)strlen(conn->request_info.local_uri);
  7521. if (conn->path_info == NULL) {
  7522. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  7523. /* URI: /path_to_script/script.cgi */
  7524. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  7525. } else {
  7526. /* URI: /path_to_script/ ... using index.cgi */
  7527. const char *index_file = strrchr(prog, '/');
  7528. if (index_file) {
  7529. addenv(env,
  7530. "SCRIPT_NAME=%s%s",
  7531. conn->request_info.local_uri,
  7532. index_file + 1);
  7533. }
  7534. }
  7535. } else {
  7536. /* URI: /path_to_script/script.cgi/path_info */
  7537. addenv(env,
  7538. "SCRIPT_NAME=%.*s",
  7539. uri_len - (int)strlen(conn->path_info),
  7540. conn->request_info.local_uri);
  7541. }
  7542. addenv(env, "SCRIPT_FILENAME=%s", prog);
  7543. if (conn->path_info == NULL) {
  7544. addenv(env, "PATH_TRANSLATED=%s", conn->ctx->config[DOCUMENT_ROOT]);
  7545. } else {
  7546. addenv(env,
  7547. "PATH_TRANSLATED=%s%s",
  7548. conn->ctx->config[DOCUMENT_ROOT],
  7549. conn->path_info);
  7550. }
  7551. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  7552. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  7553. addenv(env, "CONTENT_TYPE=%s", s);
  7554. }
  7555. if (conn->request_info.query_string != NULL) {
  7556. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  7557. }
  7558. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  7559. addenv(env, "CONTENT_LENGTH=%s", s);
  7560. }
  7561. if ((s = getenv("PATH")) != NULL) {
  7562. addenv(env, "PATH=%s", s);
  7563. }
  7564. if (conn->path_info != NULL) {
  7565. addenv(env, "PATH_INFO=%s", conn->path_info);
  7566. }
  7567. if (conn->status_code > 0) {
  7568. /* CGI error handler should show the status code */
  7569. addenv(env, "STATUS=%d", conn->status_code);
  7570. }
  7571. #if defined(_WIN32)
  7572. if ((s = getenv("COMSPEC")) != NULL) {
  7573. addenv(env, "COMSPEC=%s", s);
  7574. }
  7575. if ((s = getenv("SYSTEMROOT")) != NULL) {
  7576. addenv(env, "SYSTEMROOT=%s", s);
  7577. }
  7578. if ((s = getenv("SystemDrive")) != NULL) {
  7579. addenv(env, "SystemDrive=%s", s);
  7580. }
  7581. if ((s = getenv("ProgramFiles")) != NULL) {
  7582. addenv(env, "ProgramFiles=%s", s);
  7583. }
  7584. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  7585. addenv(env, "ProgramFiles(x86)=%s", s);
  7586. }
  7587. #else
  7588. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  7589. addenv(env, "LD_LIBRARY_PATH=%s", s);
  7590. }
  7591. #endif /* _WIN32 */
  7592. if ((s = getenv("PERLLIB")) != NULL) {
  7593. addenv(env, "PERLLIB=%s", s);
  7594. }
  7595. if (conn->request_info.remote_user != NULL) {
  7596. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  7597. addenv(env, "%s", "AUTH_TYPE=Digest");
  7598. }
  7599. /* Add all headers as HTTP_* variables */
  7600. for (i = 0; i < conn->request_info.num_headers; i++) {
  7601. (void)mg_snprintf(conn,
  7602. &truncated,
  7603. http_var_name,
  7604. sizeof(http_var_name),
  7605. "HTTP_%s",
  7606. conn->request_info.http_headers[i].name);
  7607. if (truncated) {
  7608. mg_cry(conn,
  7609. "%s: HTTP header variable too long [%s]",
  7610. __func__,
  7611. conn->request_info.http_headers[i].name);
  7612. continue;
  7613. }
  7614. /* Convert variable name into uppercase, and change - to _ */
  7615. for (p = http_var_name; *p != '\0'; p++) {
  7616. if (*p == '-') {
  7617. *p = '_';
  7618. }
  7619. *p = (char)toupper(*(unsigned char *)p);
  7620. }
  7621. addenv(env,
  7622. "%s=%s",
  7623. http_var_name,
  7624. conn->request_info.http_headers[i].value);
  7625. }
  7626. /* Add user-specified variables */
  7627. s = conn->ctx->config[CGI_ENVIRONMENT];
  7628. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  7629. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  7630. }
  7631. env->var[env->varused] = NULL;
  7632. env->buf[env->bufused] = '\0';
  7633. }
  7634. static void
  7635. handle_cgi_request(struct mg_connection *conn, const char *prog)
  7636. {
  7637. char *buf;
  7638. size_t buflen;
  7639. int headers_len, data_len, i, truncated;
  7640. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  7641. const char *status, *status_text, *connection_state;
  7642. char *pbuf, dir[PATH_MAX], *p;
  7643. struct mg_request_info ri;
  7644. struct cgi_environment blk;
  7645. FILE *in = NULL, *out = NULL, *err = NULL;
  7646. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  7647. pid_t pid = (pid_t)-1;
  7648. if (conn == NULL) {
  7649. return;
  7650. }
  7651. buf = NULL;
  7652. buflen = 16384;
  7653. prepare_cgi_environment(conn, prog, &blk);
  7654. /* CGI must be executed in its own directory. 'dir' must point to the
  7655. * directory containing executable program, 'p' must point to the
  7656. * executable program name relative to 'dir'. */
  7657. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  7658. if (truncated) {
  7659. mg_cry(conn, "Error: CGI program \"%s\": Path too long", prog);
  7660. send_http_error(conn, 500, "Error: %s", "CGI path too long");
  7661. goto done;
  7662. }
  7663. if ((p = strrchr(dir, '/')) != NULL) {
  7664. *p++ = '\0';
  7665. } else {
  7666. dir[0] = '.', dir[1] = '\0';
  7667. p = (char *)prog;
  7668. }
  7669. if (pipe(fdin) != 0 || pipe(fdout) != 0 || pipe(fderr) != 0) {
  7670. status = strerror(ERRNO);
  7671. mg_cry(conn,
  7672. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  7673. prog,
  7674. status);
  7675. send_http_error(conn, 500, "Error: Cannot create CGI pipe: %s", status);
  7676. goto done;
  7677. }
  7678. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  7679. if (pid == (pid_t)-1) {
  7680. status = strerror(ERRNO);
  7681. mg_cry(conn,
  7682. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  7683. prog,
  7684. status);
  7685. send_http_error(conn,
  7686. 500,
  7687. "Error: Cannot spawn CGI process [%s]: %s",
  7688. prog,
  7689. status);
  7690. goto done;
  7691. }
  7692. /* Make sure child closes all pipe descriptors. It must dup them to 0,1 */
  7693. set_close_on_exec((SOCKET)fdin[0], conn); /* stdin read */
  7694. set_close_on_exec((SOCKET)fdout[1], conn); /* stdout write */
  7695. set_close_on_exec((SOCKET)fderr[1], conn); /* stderr write */
  7696. set_close_on_exec((SOCKET)fdin[1], conn); /* stdin write */
  7697. set_close_on_exec((SOCKET)fdout[0], conn); /* stdout read */
  7698. set_close_on_exec((SOCKET)fderr[0], conn); /* stderr read */
  7699. /* Parent closes only one side of the pipes.
  7700. * If we don't mark them as closed, close() attempt before
  7701. * return from this function throws an exception on Windows.
  7702. * Windows does not like when closed descriptor is closed again. */
  7703. (void)close(fdin[0]);
  7704. (void)close(fdout[1]);
  7705. (void)close(fderr[1]);
  7706. fdin[0] = fdout[1] = fderr[1] = -1;
  7707. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  7708. status = strerror(ERRNO);
  7709. mg_cry(conn,
  7710. "Error: CGI program \"%s\": Can not open stdin: %s",
  7711. prog,
  7712. status);
  7713. send_http_error(conn,
  7714. 500,
  7715. "Error: CGI can not open fdin\nfopen: %s",
  7716. status);
  7717. goto done;
  7718. }
  7719. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  7720. status = strerror(ERRNO);
  7721. mg_cry(conn,
  7722. "Error: CGI program \"%s\": Can not open stdout: %s",
  7723. prog,
  7724. status);
  7725. send_http_error(conn,
  7726. 500,
  7727. "Error: CGI can not open fdout\nfopen: %s",
  7728. status);
  7729. goto done;
  7730. }
  7731. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  7732. status = strerror(ERRNO);
  7733. mg_cry(conn,
  7734. "Error: CGI program \"%s\": Can not open stderr: %s",
  7735. prog,
  7736. status);
  7737. send_http_error(conn,
  7738. 500,
  7739. "Error: CGI can not open fdout\nfopen: %s",
  7740. status);
  7741. goto done;
  7742. }
  7743. setbuf(in, NULL);
  7744. setbuf(out, NULL);
  7745. setbuf(err, NULL);
  7746. fout.access.fp = out;
  7747. if ((conn->request_info.content_length > 0) || conn->is_chunked) {
  7748. /* This is a POST/PUT request, or another request with body data. */
  7749. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  7750. /* Error sending the body data */
  7751. mg_cry(conn,
  7752. "Error: CGI program \"%s\": Forward body data failed",
  7753. prog);
  7754. goto done;
  7755. }
  7756. }
  7757. /* Close so child gets an EOF. */
  7758. fclose(in);
  7759. in = NULL;
  7760. fdin[1] = -1;
  7761. /* Now read CGI reply into a buffer. We need to set correct
  7762. * status code, thus we need to see all HTTP headers first.
  7763. * Do not send anything back to client, until we buffer in all
  7764. * HTTP headers. */
  7765. data_len = 0;
  7766. buf = (char *)mg_malloc(buflen);
  7767. if (buf == NULL) {
  7768. send_http_error(conn,
  7769. 500,
  7770. "Error: Not enough memory for CGI buffer (%u bytes)",
  7771. (unsigned int)buflen);
  7772. mg_cry(conn,
  7773. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  7774. "bytes)",
  7775. prog,
  7776. (unsigned int)buflen);
  7777. goto done;
  7778. }
  7779. headers_len = read_request(out, conn, buf, (int)buflen, &data_len);
  7780. if (headers_len <= 0) {
  7781. /* Could not parse the CGI response. Check if some error message on
  7782. * stderr. */
  7783. i = pull_all(err, conn, buf, (int)buflen);
  7784. if (i > 0) {
  7785. mg_cry(conn,
  7786. "Error: CGI program \"%s\" sent error "
  7787. "message: [%.*s]",
  7788. prog,
  7789. i,
  7790. buf);
  7791. send_http_error(conn,
  7792. 500,
  7793. "Error: CGI program \"%s\" sent error "
  7794. "message: [%.*s]",
  7795. prog,
  7796. i,
  7797. buf);
  7798. } else {
  7799. mg_cry(conn,
  7800. "Error: CGI program sent malformed or too big "
  7801. "(>%u bytes) HTTP headers: [%.*s]",
  7802. (unsigned)buflen,
  7803. data_len,
  7804. buf);
  7805. send_http_error(conn,
  7806. 500,
  7807. "Error: CGI program sent malformed or too big "
  7808. "(>%u bytes) HTTP headers: [%.*s]",
  7809. (unsigned)buflen,
  7810. data_len,
  7811. buf);
  7812. }
  7813. goto done;
  7814. }
  7815. pbuf = buf;
  7816. buf[headers_len - 1] = '\0';
  7817. parse_http_headers(&pbuf, &ri);
  7818. /* Make up and send the status line */
  7819. status_text = "OK";
  7820. if ((status = get_header(&ri, "Status")) != NULL) {
  7821. conn->status_code = atoi(status);
  7822. status_text = status;
  7823. while (isdigit(*(const unsigned char *)status_text)
  7824. || *status_text == ' ') {
  7825. status_text++;
  7826. }
  7827. } else if (get_header(&ri, "Location") != NULL) {
  7828. conn->status_code = 302;
  7829. } else {
  7830. conn->status_code = 200;
  7831. }
  7832. connection_state = get_header(&ri, "Connection");
  7833. if (!header_has_option(connection_state, "keep-alive")) {
  7834. conn->must_close = 1;
  7835. }
  7836. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  7837. /* Send headers */
  7838. for (i = 0; i < ri.num_headers; i++) {
  7839. mg_printf(conn,
  7840. "%s: %s\r\n",
  7841. ri.http_headers[i].name,
  7842. ri.http_headers[i].value);
  7843. }
  7844. mg_write(conn, "\r\n", 2);
  7845. /* Send chunk of data that may have been read after the headers */
  7846. conn->num_bytes_sent +=
  7847. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  7848. /* Read the rest of CGI output and send to the client */
  7849. send_file_data(conn, &fout, 0, INT64_MAX);
  7850. done:
  7851. mg_free(blk.var);
  7852. mg_free(blk.buf);
  7853. if (pid != (pid_t)-1) {
  7854. kill(pid, SIGKILL);
  7855. #if !defined(_WIN32)
  7856. {
  7857. int st;
  7858. while (waitpid(pid, &st, 0) != -1)
  7859. ; /* clean zombies */
  7860. }
  7861. #endif
  7862. }
  7863. if (fdin[0] != -1) {
  7864. close(fdin[0]);
  7865. }
  7866. if (fdout[1] != -1) {
  7867. close(fdout[1]);
  7868. }
  7869. if (in != NULL) {
  7870. fclose(in);
  7871. } else if (fdin[1] != -1) {
  7872. close(fdin[1]);
  7873. }
  7874. if (out != NULL) {
  7875. fclose(out);
  7876. } else if (fdout[0] != -1) {
  7877. close(fdout[0]);
  7878. }
  7879. if (err != NULL) {
  7880. fclose(err);
  7881. } else if (fderr[0] != -1) {
  7882. close(fderr[0]);
  7883. }
  7884. if (buf != NULL) {
  7885. mg_free(buf);
  7886. }
  7887. }
  7888. #endif /* !NO_CGI */
  7889. #if !defined(NO_FILES)
  7890. static void
  7891. mkcol(struct mg_connection *conn, const char *path)
  7892. {
  7893. int rc, body_len;
  7894. struct de de;
  7895. char date[64];
  7896. time_t curtime = time(NULL);
  7897. if (conn == NULL) {
  7898. return;
  7899. }
  7900. /* TODO (mid): Check the send_http_error situations in this function */
  7901. memset(&de.file, 0, sizeof(de.file));
  7902. if (!mg_stat(conn, path, &de.file)) {
  7903. mg_cry(conn,
  7904. "%s: mg_stat(%s) failed: %s",
  7905. __func__,
  7906. path,
  7907. strerror(ERRNO));
  7908. }
  7909. if (de.file.last_modified) {
  7910. /* TODO (mid): This check does not seem to make any sense ! */
  7911. /* TODO (mid): Add a webdav unit test first, before changing
  7912. * anything here. */
  7913. send_http_error(
  7914. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7915. return;
  7916. }
  7917. body_len = conn->data_len - conn->request_len;
  7918. if (body_len > 0) {
  7919. send_http_error(
  7920. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7921. return;
  7922. }
  7923. rc = mg_mkdir(conn, path, 0755);
  7924. if (rc == 0) {
  7925. conn->status_code = 201;
  7926. gmt_time_string(date, sizeof(date), &curtime);
  7927. mg_printf(conn,
  7928. "HTTP/1.1 %d Created\r\n"
  7929. "Date: %s\r\n",
  7930. conn->status_code,
  7931. date);
  7932. send_static_cache_header(conn);
  7933. send_additional_header(conn);
  7934. mg_printf(conn,
  7935. "Content-Length: 0\r\n"
  7936. "Connection: %s\r\n\r\n",
  7937. suggest_connection_header(conn));
  7938. } else if (rc == -1) {
  7939. if (errno == EEXIST) {
  7940. send_http_error(
  7941. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7942. } else if (errno == EACCES) {
  7943. send_http_error(
  7944. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7945. } else if (errno == ENOENT) {
  7946. send_http_error(
  7947. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7948. } else {
  7949. send_http_error(conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  7950. }
  7951. }
  7952. }
  7953. static void
  7954. put_file(struct mg_connection *conn, const char *path)
  7955. {
  7956. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7957. const char *range;
  7958. int64_t r1, r2;
  7959. int rc;
  7960. char date[64];
  7961. time_t curtime = time(NULL);
  7962. if (conn == NULL) {
  7963. return;
  7964. }
  7965. if (mg_stat(conn, path, &file.stat)) {
  7966. /* File already exists */
  7967. conn->status_code = 200;
  7968. if (file.stat.is_directory) {
  7969. /* This is an already existing directory,
  7970. * so there is nothing to do for the server. */
  7971. rc = 0;
  7972. } else {
  7973. /* File exists and is not a directory. */
  7974. /* Can it be replaced? */
  7975. if (file.access.membuf != NULL) {
  7976. /* This is an "in-memory" file, that can not be replaced */
  7977. send_http_error(
  7978. conn,
  7979. 405,
  7980. "Error: Put not possible\nReplacing %s is not supported",
  7981. path);
  7982. return;
  7983. }
  7984. /* Check if the server may write this file */
  7985. if (access(path, W_OK) == 0) {
  7986. /* Access granted */
  7987. conn->status_code = 200;
  7988. rc = 1;
  7989. } else {
  7990. send_http_error(
  7991. conn,
  7992. 403,
  7993. "Error: Put not possible\nReplacing %s is not allowed",
  7994. path);
  7995. return;
  7996. }
  7997. }
  7998. } else {
  7999. /* File should be created */
  8000. conn->status_code = 201;
  8001. rc = put_dir(conn, path);
  8002. }
  8003. if (rc == 0) {
  8004. /* put_dir returns 0 if path is a directory */
  8005. gmt_time_string(date, sizeof(date), &curtime);
  8006. mg_printf(conn,
  8007. "HTTP/1.1 %d %s\r\n",
  8008. conn->status_code,
  8009. mg_get_response_code_text(NULL, conn->status_code));
  8010. send_no_cache_header(conn);
  8011. send_additional_header(conn);
  8012. mg_printf(conn,
  8013. "Date: %s\r\n"
  8014. "Content-Length: 0\r\n"
  8015. "Connection: %s\r\n\r\n",
  8016. date,
  8017. suggest_connection_header(conn));
  8018. /* Request to create a directory has been fulfilled successfully.
  8019. * No need to put a file. */
  8020. return;
  8021. }
  8022. if (rc == -1) {
  8023. /* put_dir returns -1 if the path is too long */
  8024. send_http_error(conn,
  8025. 414,
  8026. "Error: Path too long\nput_dir(%s): %s",
  8027. path,
  8028. strerror(ERRNO));
  8029. return;
  8030. }
  8031. if (rc == -2) {
  8032. /* put_dir returns -2 if the directory can not be created */
  8033. send_http_error(conn,
  8034. 500,
  8035. "Error: Can not create directory\nput_dir(%s): %s",
  8036. path,
  8037. strerror(ERRNO));
  8038. return;
  8039. }
  8040. /* A file should be created or overwritten. */
  8041. /* Currently CivetWeb does not nead read+write access. */
  8042. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  8043. || file.access.fp == NULL) {
  8044. (void)mg_fclose(&file.access);
  8045. send_http_error(conn,
  8046. 500,
  8047. "Error: Can not create file\nfopen(%s): %s",
  8048. path,
  8049. strerror(ERRNO));
  8050. return;
  8051. }
  8052. fclose_on_exec(&file.access, conn);
  8053. range = mg_get_header(conn, "Content-Range");
  8054. r1 = r2 = 0;
  8055. if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
  8056. conn->status_code = 206; /* Partial content */
  8057. fseeko(file.access.fp, r1, SEEK_SET);
  8058. }
  8059. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  8060. /* forward_body_data failed.
  8061. * The error code has already been sent to the client,
  8062. * and conn->status_code is already set. */
  8063. (void)mg_fclose(&file.access);
  8064. return;
  8065. }
  8066. if (mg_fclose(&file.access) != 0) {
  8067. /* fclose failed. This might have different reasons, but a likely
  8068. * one is "no space on disk", http 507. */
  8069. conn->status_code = 507;
  8070. }
  8071. gmt_time_string(date, sizeof(date), &curtime);
  8072. mg_printf(conn,
  8073. "HTTP/1.1 %d %s\r\n",
  8074. conn->status_code,
  8075. mg_get_response_code_text(NULL, conn->status_code));
  8076. send_no_cache_header(conn);
  8077. send_additional_header(conn);
  8078. mg_printf(conn,
  8079. "Date: %s\r\n"
  8080. "Content-Length: 0\r\n"
  8081. "Connection: %s\r\n\r\n",
  8082. date,
  8083. suggest_connection_header(conn));
  8084. }
  8085. static void
  8086. delete_file(struct mg_connection *conn, const char *path)
  8087. {
  8088. struct de de;
  8089. memset(&de.file, 0, sizeof(de.file));
  8090. if (!mg_stat(conn, path, &de.file)) {
  8091. /* mg_stat returns 0 if the file does not exist */
  8092. send_http_error(conn,
  8093. 404,
  8094. "Error: Cannot delete file\nFile %s not found",
  8095. path);
  8096. return;
  8097. }
  8098. #if 0 /* Ignore if a file in memory is inside a folder */
  8099. if (de.access.membuf != NULL) {
  8100. /* the file is cached in memory */
  8101. send_http_error(
  8102. conn,
  8103. 405,
  8104. "Error: Delete not possible\nDeleting %s is not supported",
  8105. path);
  8106. return;
  8107. }
  8108. #endif
  8109. if (de.file.is_directory) {
  8110. if (remove_directory(conn, path)) {
  8111. /* Delete is successful: Return 204 without content. */
  8112. send_http_error(conn, 204, "%s", "");
  8113. } else {
  8114. /* Delete is not successful: Return 500 (Server error). */
  8115. send_http_error(conn, 500, "Error: Could not delete %s", path);
  8116. }
  8117. return;
  8118. }
  8119. /* This is an existing file (not a directory).
  8120. * Check if write permission is granted. */
  8121. if (access(path, W_OK) != 0) {
  8122. /* File is read only */
  8123. send_http_error(
  8124. conn,
  8125. 403,
  8126. "Error: Delete not possible\nDeleting %s is not allowed",
  8127. path);
  8128. return;
  8129. }
  8130. /* Try to delete it. */
  8131. if (mg_remove(conn, path) == 0) {
  8132. /* Delete was successful: Return 204 without content. */
  8133. send_http_error(conn, 204, "%s", "");
  8134. } else {
  8135. /* Delete not successful (file locked). */
  8136. send_http_error(conn,
  8137. 423,
  8138. "Error: Cannot delete file\nremove(%s): %s",
  8139. path,
  8140. strerror(ERRNO));
  8141. }
  8142. }
  8143. #endif /* !NO_FILES */
  8144. static void
  8145. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  8146. static void
  8147. do_ssi_include(struct mg_connection *conn,
  8148. const char *ssi,
  8149. char *tag,
  8150. int include_level)
  8151. {
  8152. char file_name[MG_BUF_LEN], path[512], *p;
  8153. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8154. size_t len;
  8155. int truncated = 0;
  8156. if (conn == NULL) {
  8157. return;
  8158. }
  8159. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  8160. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  8161. * always < MG_BUF_LEN. */
  8162. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  8163. /* File name is relative to the webserver root */
  8164. file_name[511] = 0;
  8165. (void)mg_snprintf(conn,
  8166. &truncated,
  8167. path,
  8168. sizeof(path),
  8169. "%s/%s",
  8170. conn->ctx->config[DOCUMENT_ROOT],
  8171. file_name);
  8172. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  8173. /* File name is relative to the webserver working directory
  8174. * or it is absolute system path */
  8175. file_name[511] = 0;
  8176. (void)
  8177. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  8178. } else if (sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1
  8179. || sscanf(tag, " \"%511[^\"]\"", file_name) == 1) {
  8180. /* File name is relative to the currect document */
  8181. file_name[511] = 0;
  8182. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  8183. if (!truncated) {
  8184. if ((p = strrchr(path, '/')) != NULL) {
  8185. p[1] = '\0';
  8186. }
  8187. len = strlen(path);
  8188. (void)mg_snprintf(conn,
  8189. &truncated,
  8190. path + len,
  8191. sizeof(path) - len,
  8192. "%s",
  8193. file_name);
  8194. }
  8195. } else {
  8196. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  8197. return;
  8198. }
  8199. if (truncated) {
  8200. mg_cry(conn, "SSI #include path length overflow: [%s]", tag);
  8201. return;
  8202. }
  8203. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  8204. mg_cry(conn,
  8205. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  8206. tag,
  8207. path,
  8208. strerror(ERRNO));
  8209. } else {
  8210. fclose_on_exec(&file.access, conn);
  8211. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  8212. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  8213. path) > 0) {
  8214. send_ssi_file(conn, path, &file, include_level + 1);
  8215. } else {
  8216. send_file_data(conn, &file, 0, INT64_MAX);
  8217. }
  8218. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  8219. }
  8220. }
  8221. #if !defined(NO_POPEN)
  8222. static void
  8223. do_ssi_exec(struct mg_connection *conn, char *tag)
  8224. {
  8225. char cmd[1024] = "";
  8226. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8227. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  8228. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  8229. } else {
  8230. cmd[1023] = 0;
  8231. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  8232. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  8233. } else {
  8234. send_file_data(conn, &file, 0, INT64_MAX);
  8235. pclose(file.access.fp);
  8236. }
  8237. }
  8238. }
  8239. #endif /* !NO_POPEN */
  8240. static int
  8241. mg_fgetc(struct mg_file *filep, int offset)
  8242. {
  8243. if (filep == NULL) {
  8244. return EOF;
  8245. }
  8246. if (filep->access.membuf != NULL && offset >= 0
  8247. && ((unsigned int)(offset)) < filep->stat.size) {
  8248. return ((const unsigned char *)filep->access.membuf)[offset];
  8249. } else if (filep->access.fp != NULL) {
  8250. return fgetc(filep->access.fp);
  8251. } else {
  8252. return EOF;
  8253. }
  8254. }
  8255. static void
  8256. send_ssi_file(struct mg_connection *conn,
  8257. const char *path,
  8258. struct mg_file *filep,
  8259. int include_level)
  8260. {
  8261. char buf[MG_BUF_LEN];
  8262. int ch, offset, len, in_ssi_tag;
  8263. if (include_level > 10) {
  8264. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  8265. return;
  8266. }
  8267. in_ssi_tag = len = offset = 0;
  8268. while ((ch = mg_fgetc(filep, offset)) != EOF) {
  8269. if (in_ssi_tag && ch == '>') {
  8270. in_ssi_tag = 0;
  8271. buf[len++] = (char)ch;
  8272. buf[len] = '\0';
  8273. /* assert(len <= (int) sizeof(buf)); */
  8274. if (len > (int)sizeof(buf)) {
  8275. break;
  8276. }
  8277. if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
  8278. /* Not an SSI tag, pass it */
  8279. (void)mg_write(conn, buf, (size_t)len);
  8280. } else {
  8281. if (!memcmp(buf + 5, "include", 7)) {
  8282. do_ssi_include(conn, path, buf + 12, include_level);
  8283. #if !defined(NO_POPEN)
  8284. } else if (!memcmp(buf + 5, "exec", 4)) {
  8285. do_ssi_exec(conn, buf + 9);
  8286. #endif /* !NO_POPEN */
  8287. } else {
  8288. mg_cry(conn,
  8289. "%s: unknown SSI "
  8290. "command: \"%s\"",
  8291. path,
  8292. buf);
  8293. }
  8294. }
  8295. len = 0;
  8296. } else if (in_ssi_tag) {
  8297. if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
  8298. /* Not an SSI tag */
  8299. in_ssi_tag = 0;
  8300. } else if (len == (int)sizeof(buf) - 2) {
  8301. mg_cry(conn, "%s: SSI tag is too large", path);
  8302. len = 0;
  8303. }
  8304. buf[len++] = (char)(ch & 0xff);
  8305. } else if (ch == '<') {
  8306. in_ssi_tag = 1;
  8307. if (len > 0) {
  8308. mg_write(conn, buf, (size_t)len);
  8309. }
  8310. len = 0;
  8311. buf[len++] = (char)(ch & 0xff);
  8312. } else {
  8313. buf[len++] = (char)(ch & 0xff);
  8314. if (len == (int)sizeof(buf)) {
  8315. mg_write(conn, buf, (size_t)len);
  8316. len = 0;
  8317. }
  8318. }
  8319. }
  8320. /* Send the rest of buffered data */
  8321. if (len > 0) {
  8322. mg_write(conn, buf, (size_t)len);
  8323. }
  8324. }
  8325. static void
  8326. handle_ssi_file_request(struct mg_connection *conn,
  8327. const char *path,
  8328. struct mg_file *filep)
  8329. {
  8330. char date[64];
  8331. time_t curtime = time(NULL);
  8332. const char *cors1, *cors2, *cors3;
  8333. if (conn == NULL || path == NULL || filep == NULL) {
  8334. return;
  8335. }
  8336. if (mg_get_header(conn, "Origin")) {
  8337. /* Cross-origin resource sharing (CORS). */
  8338. cors1 = "Access-Control-Allow-Origin: ";
  8339. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  8340. cors3 = "\r\n";
  8341. } else {
  8342. cors1 = cors2 = cors3 = "";
  8343. }
  8344. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8345. /* File exists (precondition for calling this function),
  8346. * but can not be opened by the server. */
  8347. send_http_error(conn,
  8348. 500,
  8349. "Error: Cannot read file\nfopen(%s): %s",
  8350. path,
  8351. strerror(ERRNO));
  8352. } else {
  8353. conn->must_close = 1;
  8354. gmt_time_string(date, sizeof(date), &curtime);
  8355. fclose_on_exec(&filep->access, conn);
  8356. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  8357. send_no_cache_header(conn);
  8358. send_additional_header(conn);
  8359. mg_printf(conn,
  8360. "%s%s%s"
  8361. "Date: %s\r\n"
  8362. "Content-Type: text/html\r\n"
  8363. "Connection: %s\r\n\r\n",
  8364. cors1,
  8365. cors2,
  8366. cors3,
  8367. date,
  8368. suggest_connection_header(conn));
  8369. send_ssi_file(conn, path, filep, 0);
  8370. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  8371. }
  8372. }
  8373. #if !defined(NO_FILES)
  8374. static void
  8375. send_options(struct mg_connection *conn)
  8376. {
  8377. char date[64];
  8378. time_t curtime = time(NULL);
  8379. if (!conn) {
  8380. return;
  8381. }
  8382. conn->status_code = 200;
  8383. conn->must_close = 1;
  8384. gmt_time_string(date, sizeof(date), &curtime);
  8385. /* We do not set a "Cache-Control" header here, but leave the default.
  8386. * Since browsers do not send an OPTIONS request, we can not test the
  8387. * effect anyway. */
  8388. mg_printf(conn,
  8389. "HTTP/1.1 200 OK\r\n"
  8390. "Date: %s\r\n"
  8391. "Connection: %s\r\n"
  8392. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  8393. "PROPFIND, MKCOL\r\n"
  8394. "DAV: 1\r\n",
  8395. date,
  8396. suggest_connection_header(conn));
  8397. send_additional_header(conn);
  8398. mg_printf(conn, "\r\n");
  8399. }
  8400. /* Writes PROPFIND properties for a collection element */
  8401. static void
  8402. print_props(struct mg_connection *conn,
  8403. const char *uri,
  8404. struct mg_file_stat *filep)
  8405. {
  8406. char mtime[64];
  8407. if (conn == NULL || uri == NULL || filep == NULL) {
  8408. return;
  8409. }
  8410. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  8411. conn->num_bytes_sent +=
  8412. mg_printf(conn,
  8413. "<d:response>"
  8414. "<d:href>%s</d:href>"
  8415. "<d:propstat>"
  8416. "<d:prop>"
  8417. "<d:resourcetype>%s</d:resourcetype>"
  8418. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  8419. "<d:getlastmodified>%s</d:getlastmodified>"
  8420. "</d:prop>"
  8421. "<d:status>HTTP/1.1 200 OK</d:status>"
  8422. "</d:propstat>"
  8423. "</d:response>\n",
  8424. uri,
  8425. filep->is_directory ? "<d:collection/>" : "",
  8426. filep->size,
  8427. mtime);
  8428. }
  8429. static void
  8430. print_dav_dir_entry(struct de *de, void *data)
  8431. {
  8432. char href[PATH_MAX];
  8433. char href_encoded[PATH_MAX * 3 /* worst case */];
  8434. int truncated;
  8435. struct mg_connection *conn = (struct mg_connection *)data;
  8436. if (!de || !conn) {
  8437. return;
  8438. }
  8439. mg_snprintf(conn,
  8440. &truncated,
  8441. href,
  8442. sizeof(href),
  8443. "%s%s",
  8444. conn->request_info.local_uri,
  8445. de->file_name);
  8446. if (!truncated) {
  8447. mg_url_encode(href, href_encoded, PATH_MAX * 3);
  8448. print_props(conn, href_encoded, &de->file);
  8449. }
  8450. }
  8451. static void
  8452. handle_propfind(struct mg_connection *conn,
  8453. const char *path,
  8454. struct mg_file_stat *filep)
  8455. {
  8456. const char *depth = mg_get_header(conn, "Depth");
  8457. char date[64];
  8458. time_t curtime = time(NULL);
  8459. gmt_time_string(date, sizeof(date), &curtime);
  8460. if (!conn || !path || !filep || !conn->ctx) {
  8461. return;
  8462. }
  8463. conn->must_close = 1;
  8464. conn->status_code = 207;
  8465. mg_printf(conn,
  8466. "HTTP/1.1 207 Multi-Status\r\n"
  8467. "Date: %s\r\n",
  8468. date);
  8469. send_static_cache_header(conn);
  8470. send_additional_header(conn);
  8471. mg_printf(conn,
  8472. "Connection: %s\r\n"
  8473. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  8474. suggest_connection_header(conn));
  8475. conn->num_bytes_sent +=
  8476. mg_printf(conn,
  8477. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  8478. "<d:multistatus xmlns:d='DAV:'>\n");
  8479. /* Print properties for the requested resource itself */
  8480. print_props(conn, conn->request_info.local_uri, filep);
  8481. /* If it is a directory, print directory entries too if Depth is not 0 */
  8482. if (filep && filep->is_directory
  8483. && !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")
  8484. && (depth == NULL || strcmp(depth, "0") != 0)) {
  8485. scan_directory(conn, path, conn, &print_dav_dir_entry);
  8486. }
  8487. conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");
  8488. }
  8489. #endif
  8490. void
  8491. mg_lock_connection(struct mg_connection *conn)
  8492. {
  8493. if (conn) {
  8494. (void)pthread_mutex_lock(&conn->mutex);
  8495. }
  8496. }
  8497. void
  8498. mg_unlock_connection(struct mg_connection *conn)
  8499. {
  8500. if (conn) {
  8501. (void)pthread_mutex_unlock(&conn->mutex);
  8502. }
  8503. }
  8504. void
  8505. mg_lock_context(struct mg_context *ctx)
  8506. {
  8507. if (ctx) {
  8508. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  8509. }
  8510. }
  8511. void
  8512. mg_unlock_context(struct mg_context *ctx)
  8513. {
  8514. if (ctx) {
  8515. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  8516. }
  8517. }
  8518. #if defined(USE_TIMERS)
  8519. #define TIMER_API static
  8520. #include "timer.inl"
  8521. #endif /* USE_TIMERS */
  8522. #ifdef USE_LUA
  8523. #include "mod_lua.inl"
  8524. #endif /* USE_LUA */
  8525. #ifdef USE_DUKTAPE
  8526. #include "mod_duktape.inl"
  8527. #endif /* USE_DUKTAPE */
  8528. #if defined(USE_WEBSOCKET)
  8529. #if !defined(NO_SSL_DL)
  8530. #define SHA_API static
  8531. #include "sha1.inl"
  8532. #endif
  8533. static int
  8534. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  8535. {
  8536. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  8537. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  8538. SHA_CTX sha_ctx;
  8539. int truncated;
  8540. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  8541. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  8542. if (truncated) {
  8543. conn->must_close = 1;
  8544. return 0;
  8545. }
  8546. SHA1_Init(&sha_ctx);
  8547. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  8548. SHA1_Final((unsigned char *)sha, &sha_ctx);
  8549. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  8550. mg_printf(conn,
  8551. "HTTP/1.1 101 Switching Protocols\r\n"
  8552. "Upgrade: websocket\r\n"
  8553. "Connection: Upgrade\r\n"
  8554. "Sec-WebSocket-Accept: %s\r\n",
  8555. b64_sha);
  8556. if (conn->request_info.acceptedWebSocketSubprotocol) {
  8557. mg_printf(conn,
  8558. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  8559. conn->request_info.acceptedWebSocketSubprotocol);
  8560. } else {
  8561. mg_printf(conn, "%s", "\r\n");
  8562. }
  8563. return 1;
  8564. }
  8565. static void
  8566. read_websocket(struct mg_connection *conn,
  8567. mg_websocket_data_handler ws_data_handler,
  8568. void *callback_data)
  8569. {
  8570. /* Pointer to the beginning of the portion of the incoming websocket
  8571. * message queue.
  8572. * The original websocket upgrade request is never removed, so the queue
  8573. * begins after it. */
  8574. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  8575. int n, error, exit_by_callback;
  8576. /* body_len is the length of the entire queue in bytes
  8577. * len is the length of the current message
  8578. * data_len is the length of the current message's data payload
  8579. * header_len is the length of the current message's header */
  8580. size_t i, len, mask_len = 0, data_len = 0, header_len, body_len;
  8581. /* "The masking key is a 32-bit value chosen at random by the client."
  8582. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  8583. */
  8584. unsigned char mask[4];
  8585. /* data points to the place where the message is stored when passed to
  8586. * the
  8587. * websocket_data callback. This is either mem on the stack, or a
  8588. * dynamically allocated buffer if it is too large. */
  8589. unsigned char mem[4096];
  8590. unsigned char *data = mem;
  8591. unsigned char mop; /* mask flag and opcode */
  8592. double timeout = -1.0;
  8593. if (conn->ctx->config[WEBSOCKET_TIMEOUT]) {
  8594. timeout = atoi(conn->ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  8595. }
  8596. if ((timeout <= 0.0) && (conn->ctx->config[REQUEST_TIMEOUT])) {
  8597. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  8598. }
  8599. mg_set_thread_name("wsock");
  8600. /* Loop continuously, reading messages from the socket, invoking the
  8601. * callback, and waiting repeatedly until an error occurs. */
  8602. while (!conn->ctx->stop_flag) {
  8603. header_len = 0;
  8604. assert(conn->data_len >= conn->request_len);
  8605. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  8606. len = buf[1] & 127;
  8607. mask_len = (buf[1] & 128) ? 4 : 0;
  8608. if ((len < 126) && (body_len >= mask_len)) {
  8609. /* inline 7-bit length field */
  8610. data_len = len;
  8611. header_len = 2 + mask_len;
  8612. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  8613. /* 16-bit length field */
  8614. header_len = 4 + mask_len;
  8615. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  8616. } else if (body_len >= (10 + mask_len)) {
  8617. /* 64-bit length field */
  8618. uint32_t l1, l2;
  8619. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  8620. memcpy(&l2, &buf[6], 4);
  8621. header_len = 10 + mask_len;
  8622. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  8623. }
  8624. }
  8625. if (header_len > 0 && body_len >= header_len) {
  8626. /* Allocate space to hold websocket payload */
  8627. data = mem;
  8628. if (data_len > sizeof(mem)) {
  8629. data = (unsigned char *)mg_malloc(data_len);
  8630. if (data == NULL) {
  8631. /* Allocation failed, exit the loop and then close the
  8632. * connection */
  8633. mg_cry(conn, "websocket out of memory; closing connection");
  8634. break;
  8635. }
  8636. }
  8637. /* Copy the mask before we shift the queue and destroy it */
  8638. if (mask_len > 0) {
  8639. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  8640. } else {
  8641. memset(mask, 0, sizeof(mask));
  8642. }
  8643. /* Read frame payload from the first message in the queue into
  8644. * data and advance the queue by moving the memory in place. */
  8645. assert(body_len >= header_len);
  8646. if (data_len + header_len > body_len) {
  8647. mop = buf[0]; /* current mask and opcode */
  8648. /* Overflow case */
  8649. len = body_len - header_len;
  8650. memcpy(data, buf + header_len, len);
  8651. error = 0;
  8652. while (len < data_len) {
  8653. n = pull_inner(NULL,
  8654. conn,
  8655. (char *)(data + len),
  8656. (int)(data_len - len),
  8657. timeout);
  8658. if (n <= -2) {
  8659. error = 1;
  8660. break;
  8661. } else if (n > 0) {
  8662. len += (size_t)n;
  8663. } else {
  8664. /* Timeout: should retry */
  8665. /* TODO: retry condition */
  8666. }
  8667. }
  8668. if (error) {
  8669. mg_cry(conn, "Websocket pull failed; closing connection");
  8670. break;
  8671. }
  8672. conn->data_len = conn->request_len;
  8673. } else {
  8674. mop = buf[0]; /* current mask and opcode, overwritten by
  8675. * memmove() */
  8676. /* Length of the message being read at the front of the
  8677. * queue */
  8678. len = data_len + header_len;
  8679. /* Copy the data payload into the data pointer for the
  8680. * callback */
  8681. memcpy(data, buf + header_len, data_len);
  8682. /* Move the queue forward len bytes */
  8683. memmove(buf, buf + len, body_len - len);
  8684. /* Mark the queue as advanced */
  8685. conn->data_len -= (int)len;
  8686. }
  8687. /* Apply mask if necessary */
  8688. if (mask_len > 0) {
  8689. for (i = 0; i < data_len; ++i) {
  8690. data[i] ^= mask[i & 3];
  8691. }
  8692. }
  8693. /* Exit the loop if callback signals to exit (server side),
  8694. * or "connection close" opcode received (client side). */
  8695. exit_by_callback = 0;
  8696. if ((ws_data_handler != NULL)
  8697. && !ws_data_handler(
  8698. conn, mop, (char *)data, data_len, callback_data)) {
  8699. exit_by_callback = 1;
  8700. }
  8701. if (data != mem) {
  8702. mg_free(data);
  8703. }
  8704. if (exit_by_callback
  8705. || ((mop & 0xf) == WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  8706. /* Opcode == 8, connection close */
  8707. break;
  8708. }
  8709. /* Not breaking the loop, process next websocket frame. */
  8710. } else {
  8711. /* Read from the socket into the next available location in the
  8712. * message queue. */
  8713. n = pull_inner(NULL,
  8714. conn,
  8715. conn->buf + conn->data_len,
  8716. conn->buf_size - conn->data_len,
  8717. timeout);
  8718. if (n <= -2) {
  8719. /* Error, no bytes read */
  8720. break;
  8721. }
  8722. if (n > 0) {
  8723. conn->data_len += n;
  8724. } else {
  8725. /* Timeout: should retry */
  8726. /* TODO: get timeout def */
  8727. }
  8728. }
  8729. }
  8730. mg_set_thread_name("worker");
  8731. }
  8732. static int
  8733. mg_websocket_write_exec(struct mg_connection *conn,
  8734. int opcode,
  8735. const char *data,
  8736. size_t dataLen,
  8737. uint32_t masking_key)
  8738. {
  8739. unsigned char header[14];
  8740. size_t headerLen = 1;
  8741. int retval = -1;
  8742. #if defined(__GNUC__) || defined(__MINGW32__)
  8743. /* Disable spurious conversion warning for GCC */
  8744. #pragma GCC diagnostic push
  8745. #pragma GCC diagnostic ignored "-Wconversion"
  8746. #endif
  8747. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  8748. #if defined(__GNUC__) || defined(__MINGW32__)
  8749. #pragma GCC diagnostic pop
  8750. #endif
  8751. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  8752. if (dataLen < 126) {
  8753. /* inline 7-bit length field */
  8754. header[1] = (unsigned char)dataLen;
  8755. headerLen = 2;
  8756. } else if (dataLen <= 0xFFFF) {
  8757. /* 16-bit length field */
  8758. uint16_t len = htons((uint16_t)dataLen);
  8759. header[1] = 126;
  8760. memcpy(header + 2, &len, 2);
  8761. headerLen = 4;
  8762. } else {
  8763. /* 64-bit length field */
  8764. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  8765. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  8766. header[1] = 127;
  8767. memcpy(header + 2, &len1, 4);
  8768. memcpy(header + 6, &len2, 4);
  8769. headerLen = 10;
  8770. }
  8771. if (masking_key) {
  8772. /* add mask */
  8773. header[1] |= 0x80;
  8774. memcpy(header + headerLen, &masking_key, 4);
  8775. headerLen += 4;
  8776. }
  8777. /* Note that POSIX/Winsock's send() is threadsafe
  8778. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  8779. * but mongoose's mg_printf/mg_write is not (because of the loop in
  8780. * push(), although that is only a problem if the packet is large or
  8781. * outgoing buffer is full). */
  8782. (void)mg_lock_connection(conn);
  8783. retval = mg_write(conn, header, headerLen);
  8784. if (dataLen > 0) {
  8785. retval = mg_write(conn, data, dataLen);
  8786. }
  8787. mg_unlock_connection(conn);
  8788. return retval;
  8789. }
  8790. int
  8791. mg_websocket_write(struct mg_connection *conn,
  8792. int opcode,
  8793. const char *data,
  8794. size_t dataLen)
  8795. {
  8796. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  8797. }
  8798. static void
  8799. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  8800. {
  8801. size_t i = 0;
  8802. i = 0;
  8803. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  8804. /* Convert in 32 bit words, if data is 4 byte aligned */
  8805. while (i < (in_len - 3)) {
  8806. *(uint32_t *)(void *)(out + i) =
  8807. *(uint32_t *)(void *)(in + i) ^ masking_key;
  8808. i += 4;
  8809. }
  8810. }
  8811. if (i != in_len) {
  8812. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  8813. while (i < in_len) {
  8814. *(uint8_t *)(void *)(out + i) =
  8815. *(uint8_t *)(void *)(in + i)
  8816. ^ *(((uint8_t *)&masking_key) + (i % 4));
  8817. i++;
  8818. }
  8819. }
  8820. }
  8821. int
  8822. mg_websocket_client_write(struct mg_connection *conn,
  8823. int opcode,
  8824. const char *data,
  8825. size_t dataLen)
  8826. {
  8827. int retval = -1;
  8828. char *masked_data = (char *)mg_malloc(((dataLen + 7) / 4) * 4);
  8829. uint32_t masking_key = (uint32_t)get_random();
  8830. if (masked_data == NULL) {
  8831. /* Return -1 in an error case */
  8832. mg_cry(conn,
  8833. "Cannot allocate buffer for masked websocket response: "
  8834. "Out of memory");
  8835. return -1;
  8836. }
  8837. mask_data(data, dataLen, masking_key, masked_data);
  8838. retval = mg_websocket_write_exec(
  8839. conn, opcode, masked_data, dataLen, masking_key);
  8840. mg_free(masked_data);
  8841. return retval;
  8842. }
  8843. static void
  8844. handle_websocket_request(struct mg_connection *conn,
  8845. const char *path,
  8846. int is_callback_resource,
  8847. struct mg_websocket_subprotocols *subprotocols,
  8848. mg_websocket_connect_handler ws_connect_handler,
  8849. mg_websocket_ready_handler ws_ready_handler,
  8850. mg_websocket_data_handler ws_data_handler,
  8851. mg_websocket_close_handler ws_close_handler,
  8852. void *cbData)
  8853. {
  8854. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  8855. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  8856. int lua_websock = 0;
  8857. #if !defined(USE_LUA)
  8858. (void)path;
  8859. #endif
  8860. /* Step 1: Check websocket protocol version. */
  8861. /* Step 1.1: Check Sec-WebSocket-Key. */
  8862. if (!websock_key) {
  8863. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  8864. * requires a Sec-WebSocket-Key header.
  8865. */
  8866. /* It could be the hixie draft version
  8867. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  8868. */
  8869. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  8870. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  8871. char key3[8];
  8872. if ((key1 != NULL) && (key2 != NULL)) {
  8873. /* This version uses 8 byte body data in a GET request */
  8874. conn->content_len = 8;
  8875. if (8 == mg_read(conn, key3, 8)) {
  8876. /* This is the hixie version */
  8877. send_http_error(conn,
  8878. 426,
  8879. "%s",
  8880. "Protocol upgrade to RFC 6455 required");
  8881. return;
  8882. }
  8883. }
  8884. /* This is an unknown version */
  8885. send_http_error(conn, 400, "%s", "Malformed websocket request");
  8886. return;
  8887. }
  8888. /* Step 1.2: Check websocket protocol version. */
  8889. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  8890. if (version == NULL || strcmp(version, "13") != 0) {
  8891. /* Reject wrong versions */
  8892. send_http_error(conn, 426, "%s", "Protocol upgrade required");
  8893. return;
  8894. }
  8895. /* Step 1.3: Could check for "Host", but we do not really nead this
  8896. * value for anything, so just ignore it. */
  8897. /* Step 2: If a callback is responsible, call it. */
  8898. if (is_callback_resource) {
  8899. /* Step 2.1 check and select subprotocol */
  8900. const char *protocol = mg_get_header(conn, "Sec-WebSocket-Protocol");
  8901. if (protocol && subprotocols) {
  8902. int idx;
  8903. unsigned long len;
  8904. const char *sep, *curSubProtocol,
  8905. *acceptedWebSocketSubprotocol = NULL;
  8906. /* look for matching subprotocol */
  8907. do {
  8908. sep = strchr(protocol, ',');
  8909. curSubProtocol = protocol;
  8910. len = sep ? (unsigned long)(sep - protocol)
  8911. : (unsigned long)strlen(protocol);
  8912. while (sep && isspace(*++sep)) {
  8913. ; /* ignore leading whitespaces */
  8914. }
  8915. protocol = sep;
  8916. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  8917. if ((strlen(subprotocols->subprotocols[idx]) == len)
  8918. && (strncmp(curSubProtocol,
  8919. subprotocols->subprotocols[idx],
  8920. len) == 0)) {
  8921. acceptedWebSocketSubprotocol =
  8922. subprotocols->subprotocols[idx];
  8923. break;
  8924. }
  8925. }
  8926. } while (sep && !acceptedWebSocketSubprotocol);
  8927. conn->request_info.acceptedWebSocketSubprotocol =
  8928. acceptedWebSocketSubprotocol;
  8929. } else if (protocol) {
  8930. /* keep legacy behavior */
  8931. /* The protocol is a comma seperated list of names. */
  8932. /* The server must only return one value from this list. */
  8933. /* First check if it is a list or just a single value. */
  8934. const char *sep = strrchr(protocol, ',');
  8935. if (sep == NULL) {
  8936. /* Just a single protocol -> accept it. */
  8937. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  8938. } else {
  8939. /* Multiple protocols -> accept the last one. */
  8940. /* This is just a quick fix if the client offers multiple
  8941. * protocols. The handler should have a list of accepted
  8942. * protocols on his own
  8943. * and use it to select one protocol among those the client has
  8944. * offered.
  8945. */
  8946. while (isspace(*++sep)) {
  8947. ; /* ignore leading whitespaces */
  8948. }
  8949. conn->request_info.acceptedWebSocketSubprotocol = sep;
  8950. }
  8951. }
  8952. if (ws_connect_handler != NULL
  8953. && ws_connect_handler(conn, cbData) != 0) {
  8954. /* C callback has returned non-zero, do not proceed with
  8955. * handshake.
  8956. */
  8957. /* Note that C callbacks are no longer called when Lua is
  8958. * responsible, so C can no longer filter callbacks for Lua. */
  8959. return;
  8960. }
  8961. }
  8962. #if defined(USE_LUA)
  8963. /* Step 3: No callback. Check if Lua is responsible. */
  8964. else {
  8965. /* Step 3.1: Check if Lua is responsible. */
  8966. if (conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  8967. lua_websock =
  8968. match_prefix(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  8969. strlen(
  8970. conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  8971. path);
  8972. }
  8973. if (lua_websock) {
  8974. /* Step 3.2: Lua is responsible: call it. */
  8975. conn->lua_websocket_state = lua_websocket_new(path, conn);
  8976. if (!conn->lua_websocket_state) {
  8977. /* Lua rejected the new client */
  8978. return;
  8979. }
  8980. }
  8981. }
  8982. #endif
  8983. /* Step 4: Check if there is a responsible websocket handler. */
  8984. if (!is_callback_resource && !lua_websock) {
  8985. /* There is no callback, and Lua is not responsible either. */
  8986. /* Reply with a 404 Not Found. We are still at a standard
  8987. * HTTP request here, before the websocket handshake, so
  8988. * we can still send standard HTTP error replies. */
  8989. send_http_error(conn, 404, "%s", "Not found");
  8990. return;
  8991. }
  8992. /* Step 5: The websocket connection has been accepted */
  8993. if (!send_websocket_handshake(conn, websock_key)) {
  8994. send_http_error(conn, 500, "%s", "Websocket handshake failed");
  8995. return;
  8996. }
  8997. /* Step 6: Call the ready handler */
  8998. if (is_callback_resource) {
  8999. if (ws_ready_handler != NULL) {
  9000. ws_ready_handler(conn, cbData);
  9001. }
  9002. #if defined(USE_LUA)
  9003. } else if (lua_websock) {
  9004. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  9005. /* the ready handler returned false */
  9006. return;
  9007. }
  9008. #endif
  9009. }
  9010. /* Step 7: Enter the read loop */
  9011. if (is_callback_resource) {
  9012. read_websocket(conn, ws_data_handler, cbData);
  9013. #if defined(USE_LUA)
  9014. } else if (lua_websock) {
  9015. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  9016. #endif
  9017. }
  9018. /* Step 8: Call the close handler */
  9019. if (ws_close_handler) {
  9020. ws_close_handler(conn, cbData);
  9021. }
  9022. }
  9023. static int
  9024. is_websocket_protocol(const struct mg_connection *conn)
  9025. {
  9026. const char *upgrade, *connection;
  9027. /* A websocket protocoll has the following HTTP headers:
  9028. *
  9029. * Connection: Upgrade
  9030. * Upgrade: Websocket
  9031. */
  9032. upgrade = mg_get_header(conn, "Upgrade");
  9033. if (upgrade == NULL) {
  9034. return 0; /* fail early, don't waste time checking other header
  9035. * fields
  9036. */
  9037. }
  9038. if (!mg_strcasestr(upgrade, "websocket")) {
  9039. return 0;
  9040. }
  9041. connection = mg_get_header(conn, "Connection");
  9042. if (connection == NULL) {
  9043. return 0;
  9044. }
  9045. if (!mg_strcasestr(connection, "upgrade")) {
  9046. return 0;
  9047. }
  9048. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  9049. * "Sec-WebSocket-Version" are also required.
  9050. * Don't check them here, since even an unsupported websocket protocol
  9051. * request still IS a websocket request (in contrast to a standard HTTP
  9052. * request). It will fail later in handle_websocket_request.
  9053. */
  9054. return 1;
  9055. }
  9056. #endif /* !USE_WEBSOCKET */
  9057. static int
  9058. isbyte(int n)
  9059. {
  9060. return n >= 0 && n <= 255;
  9061. }
  9062. static int
  9063. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  9064. {
  9065. int n, a, b, c, d, slash = 32, len = 0;
  9066. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5
  9067. || sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) && isbyte(a)
  9068. && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0
  9069. && slash < 33) {
  9070. len = n;
  9071. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  9072. | (uint32_t)d;
  9073. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  9074. }
  9075. return len;
  9076. }
  9077. static int
  9078. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  9079. {
  9080. int throttle = 0;
  9081. struct vec vec, val;
  9082. uint32_t net, mask;
  9083. char mult;
  9084. double v;
  9085. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  9086. mult = ',';
  9087. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  9088. || (v < 0) || ((lowercase(&mult) != 'k')
  9089. && (lowercase(&mult) != 'm') && (mult != ','))) {
  9090. continue;
  9091. }
  9092. v *= (lowercase(&mult) == 'k')
  9093. ? 1024
  9094. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  9095. if (vec.len == 1 && vec.ptr[0] == '*') {
  9096. throttle = (int)v;
  9097. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  9098. if ((remote_ip & mask) == net) {
  9099. throttle = (int)v;
  9100. }
  9101. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  9102. throttle = (int)v;
  9103. }
  9104. }
  9105. return throttle;
  9106. }
  9107. static uint32_t
  9108. get_remote_ip(const struct mg_connection *conn)
  9109. {
  9110. if (!conn) {
  9111. return 0;
  9112. }
  9113. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  9114. }
  9115. /* The mg_upload function is superseeded by mg_handle_form_request. */
  9116. #include "handle_form.inl"
  9117. #if defined(MG_LEGACY_INTERFACE)
  9118. /* Implement the deprecated mg_upload function by calling the new
  9119. * mg_handle_form_request function. While mg_upload could only handle
  9120. * HTML forms sent as POST request in multipart/form-data format
  9121. * containing only file input elements, mg_handle_form_request can
  9122. * handle all form input elements and all standard request methods. */
  9123. struct mg_upload_user_data {
  9124. struct mg_connection *conn;
  9125. const char *destination_dir;
  9126. int num_uploaded_files;
  9127. };
  9128. /* Helper function for deprecated mg_upload. */
  9129. static int
  9130. mg_upload_field_found(const char *key,
  9131. const char *filename,
  9132. char *path,
  9133. size_t pathlen,
  9134. void *user_data)
  9135. {
  9136. int truncated = 0;
  9137. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  9138. (void)key;
  9139. if (!filename) {
  9140. mg_cry(fud->conn, "%s: No filename set", __func__);
  9141. return FORM_FIELD_STORAGE_ABORT;
  9142. }
  9143. mg_snprintf(fud->conn,
  9144. &truncated,
  9145. path,
  9146. pathlen - 1,
  9147. "%s/%s",
  9148. fud->destination_dir,
  9149. filename);
  9150. if (!truncated) {
  9151. mg_cry(fud->conn, "%s: File path too long", __func__);
  9152. return FORM_FIELD_STORAGE_ABORT;
  9153. }
  9154. return FORM_FIELD_STORAGE_STORE;
  9155. }
  9156. /* Helper function for deprecated mg_upload. */
  9157. static int
  9158. mg_upload_field_get(const char *key,
  9159. const char *value,
  9160. size_t value_size,
  9161. void *user_data)
  9162. {
  9163. /* Function should never be called */
  9164. (void)key;
  9165. (void)value;
  9166. (void)value_size;
  9167. (void)user_data;
  9168. return 0;
  9169. }
  9170. /* Helper function for deprecated mg_upload. */
  9171. static int
  9172. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  9173. {
  9174. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  9175. (void)file_size;
  9176. fud->num_uploaded_files++;
  9177. fud->conn->ctx->callbacks.upload(fud->conn, path);
  9178. return 0;
  9179. }
  9180. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  9181. int
  9182. mg_upload(struct mg_connection *conn, const char *destination_dir)
  9183. {
  9184. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  9185. struct mg_form_data_handler fdh = {mg_upload_field_found,
  9186. mg_upload_field_get,
  9187. mg_upload_field_stored,
  9188. 0};
  9189. int ret;
  9190. fdh.user_data = (void *)&fud;
  9191. ret = mg_handle_form_request(conn, &fdh);
  9192. if (ret < 0) {
  9193. mg_cry(conn, "%s: Error while parsing the request", __func__);
  9194. }
  9195. return fud.num_uploaded_files;
  9196. }
  9197. #endif
  9198. static int
  9199. get_first_ssl_listener_index(const struct mg_context *ctx)
  9200. {
  9201. unsigned int i;
  9202. int idx = -1;
  9203. if (ctx) {
  9204. for (i = 0; idx == -1 && i < ctx->num_listening_sockets; i++) {
  9205. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  9206. }
  9207. }
  9208. return idx;
  9209. }
  9210. static void
  9211. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  9212. {
  9213. char host[1025];
  9214. const char *host_header;
  9215. size_t hostlen;
  9216. host_header = mg_get_header(conn, "Host");
  9217. hostlen = sizeof(host);
  9218. if (host_header != NULL) {
  9219. char *pos;
  9220. mg_strlcpy(host, host_header, hostlen);
  9221. host[hostlen - 1] = '\0';
  9222. pos = strchr(host, ':');
  9223. if (pos != NULL) {
  9224. *pos = '\0';
  9225. }
  9226. } else {
  9227. /* Cannot get host from the Host: header.
  9228. * Fallback to our IP address. */
  9229. if (conn) {
  9230. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  9231. }
  9232. }
  9233. /* Send host, port, uri and (if it exists) ?query_string */
  9234. if (conn) {
  9235. mg_printf(conn,
  9236. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  9237. host,
  9238. #if defined(USE_IPV6)
  9239. (conn->ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  9240. == AF_INET6)
  9241. ? (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  9242. .lsa.sin6.sin6_port)
  9243. :
  9244. #endif
  9245. (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  9246. .lsa.sin.sin_port),
  9247. conn->request_info.local_uri,
  9248. (conn->request_info.query_string == NULL) ? "" : "?",
  9249. (conn->request_info.query_string == NULL)
  9250. ? ""
  9251. : conn->request_info.query_string);
  9252. }
  9253. }
  9254. static void
  9255. mg_set_handler_type(struct mg_context *ctx,
  9256. const char *uri,
  9257. int handler_type,
  9258. int is_delete_request,
  9259. mg_request_handler handler,
  9260. struct mg_websocket_subprotocols *subprotocols,
  9261. mg_websocket_connect_handler connect_handler,
  9262. mg_websocket_ready_handler ready_handler,
  9263. mg_websocket_data_handler data_handler,
  9264. mg_websocket_close_handler close_handler,
  9265. mg_authorization_handler auth_handler,
  9266. void *cbdata)
  9267. {
  9268. struct mg_handler_info *tmp_rh, **lastref;
  9269. size_t urilen = strlen(uri);
  9270. if (handler_type == WEBSOCKET_HANDLER) {
  9271. /* assert(handler == NULL); */
  9272. /* assert(is_delete_request || connect_handler!=NULL ||
  9273. * ready_handler!=NULL || data_handler!=NULL ||
  9274. * close_handler!=NULL);
  9275. */
  9276. /* assert(auth_handler == NULL); */
  9277. if (handler != NULL) {
  9278. return;
  9279. }
  9280. if (!is_delete_request && connect_handler == NULL
  9281. && ready_handler == NULL
  9282. && data_handler == NULL
  9283. && close_handler == NULL) {
  9284. return;
  9285. }
  9286. if (auth_handler != NULL) {
  9287. return;
  9288. }
  9289. } else if (handler_type == REQUEST_HANDLER) {
  9290. /* assert(connect_handler==NULL && ready_handler==NULL &&
  9291. * data_handler==NULL && close_handler==NULL); */
  9292. /* assert(is_delete_request || (handler!=NULL));
  9293. */
  9294. /* assert(auth_handler == NULL); */
  9295. if (connect_handler != NULL || ready_handler != NULL
  9296. || data_handler != NULL
  9297. || close_handler != NULL) {
  9298. return;
  9299. }
  9300. if (!is_delete_request && (handler == NULL)) {
  9301. return;
  9302. }
  9303. if (auth_handler != NULL) {
  9304. return;
  9305. }
  9306. } else { /* AUTH_HANDLER */
  9307. /* assert(handler == NULL); */
  9308. /* assert(connect_handler==NULL && ready_handler==NULL &&
  9309. * data_handler==NULL && close_handler==NULL); */
  9310. /* assert(auth_handler != NULL); */
  9311. if (handler != NULL) {
  9312. return;
  9313. }
  9314. if (connect_handler != NULL || ready_handler != NULL
  9315. || data_handler != NULL
  9316. || close_handler != NULL) {
  9317. return;
  9318. }
  9319. if (!is_delete_request && (auth_handler == NULL)) {
  9320. return;
  9321. }
  9322. }
  9323. if (!ctx) {
  9324. return;
  9325. }
  9326. mg_lock_context(ctx);
  9327. /* first try to find an existing handler */
  9328. lastref = &(ctx->handlers);
  9329. for (tmp_rh = ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  9330. if (tmp_rh->handler_type == handler_type) {
  9331. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  9332. if (!is_delete_request) {
  9333. /* update existing handler */
  9334. if (handler_type == REQUEST_HANDLER) {
  9335. tmp_rh->handler = handler;
  9336. } else if (handler_type == WEBSOCKET_HANDLER) {
  9337. tmp_rh->subprotocols = subprotocols;
  9338. tmp_rh->connect_handler = connect_handler;
  9339. tmp_rh->ready_handler = ready_handler;
  9340. tmp_rh->data_handler = data_handler;
  9341. tmp_rh->close_handler = close_handler;
  9342. } else { /* AUTH_HANDLER */
  9343. tmp_rh->auth_handler = auth_handler;
  9344. }
  9345. tmp_rh->cbdata = cbdata;
  9346. } else {
  9347. /* remove existing handler */
  9348. *lastref = tmp_rh->next;
  9349. mg_free(tmp_rh->uri);
  9350. mg_free(tmp_rh);
  9351. }
  9352. mg_unlock_context(ctx);
  9353. return;
  9354. }
  9355. }
  9356. lastref = &(tmp_rh->next);
  9357. }
  9358. if (is_delete_request) {
  9359. /* no handler to set, this was a remove request to a non-existing
  9360. * handler */
  9361. mg_unlock_context(ctx);
  9362. return;
  9363. }
  9364. tmp_rh =
  9365. (struct mg_handler_info *)mg_calloc(sizeof(struct mg_handler_info), 1);
  9366. if (tmp_rh == NULL) {
  9367. mg_unlock_context(ctx);
  9368. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  9369. return;
  9370. }
  9371. tmp_rh->uri = mg_strdup(uri);
  9372. if (!tmp_rh->uri) {
  9373. mg_unlock_context(ctx);
  9374. mg_free(tmp_rh);
  9375. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  9376. return;
  9377. }
  9378. tmp_rh->uri_len = urilen;
  9379. if (handler_type == REQUEST_HANDLER) {
  9380. tmp_rh->handler = handler;
  9381. } else if (handler_type == WEBSOCKET_HANDLER) {
  9382. tmp_rh->subprotocols = subprotocols;
  9383. tmp_rh->connect_handler = connect_handler;
  9384. tmp_rh->ready_handler = ready_handler;
  9385. tmp_rh->data_handler = data_handler;
  9386. tmp_rh->close_handler = close_handler;
  9387. } else { /* AUTH_HANDLER */
  9388. tmp_rh->auth_handler = auth_handler;
  9389. }
  9390. tmp_rh->cbdata = cbdata;
  9391. tmp_rh->handler_type = handler_type;
  9392. tmp_rh->next = NULL;
  9393. *lastref = tmp_rh;
  9394. mg_unlock_context(ctx);
  9395. }
  9396. void
  9397. mg_set_request_handler(struct mg_context *ctx,
  9398. const char *uri,
  9399. mg_request_handler handler,
  9400. void *cbdata)
  9401. {
  9402. mg_set_handler_type(ctx,
  9403. uri,
  9404. REQUEST_HANDLER,
  9405. handler == NULL,
  9406. handler,
  9407. NULL,
  9408. NULL,
  9409. NULL,
  9410. NULL,
  9411. NULL,
  9412. NULL,
  9413. cbdata);
  9414. }
  9415. void
  9416. mg_set_websocket_handler(struct mg_context *ctx,
  9417. const char *uri,
  9418. mg_websocket_connect_handler connect_handler,
  9419. mg_websocket_ready_handler ready_handler,
  9420. mg_websocket_data_handler data_handler,
  9421. mg_websocket_close_handler close_handler,
  9422. void *cbdata)
  9423. {
  9424. mg_set_websocket_handler_with_subprotocols(ctx,
  9425. uri,
  9426. NULL,
  9427. connect_handler,
  9428. ready_handler,
  9429. data_handler,
  9430. close_handler,
  9431. cbdata);
  9432. }
  9433. void
  9434. mg_set_websocket_handler_with_subprotocols(
  9435. struct mg_context *ctx,
  9436. const char *uri,
  9437. struct mg_websocket_subprotocols *subprotocols,
  9438. mg_websocket_connect_handler connect_handler,
  9439. mg_websocket_ready_handler ready_handler,
  9440. mg_websocket_data_handler data_handler,
  9441. mg_websocket_close_handler close_handler,
  9442. void *cbdata)
  9443. {
  9444. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  9445. && (data_handler == NULL)
  9446. && (close_handler == NULL);
  9447. mg_set_handler_type(ctx,
  9448. uri,
  9449. WEBSOCKET_HANDLER,
  9450. is_delete_request,
  9451. NULL,
  9452. subprotocols,
  9453. connect_handler,
  9454. ready_handler,
  9455. data_handler,
  9456. close_handler,
  9457. NULL,
  9458. cbdata);
  9459. }
  9460. void
  9461. mg_set_auth_handler(struct mg_context *ctx,
  9462. const char *uri,
  9463. mg_request_handler handler,
  9464. void *cbdata)
  9465. {
  9466. mg_set_handler_type(ctx,
  9467. uri,
  9468. AUTH_HANDLER,
  9469. handler == NULL,
  9470. NULL,
  9471. NULL,
  9472. NULL,
  9473. NULL,
  9474. NULL,
  9475. NULL,
  9476. handler,
  9477. cbdata);
  9478. }
  9479. static int
  9480. get_request_handler(struct mg_connection *conn,
  9481. int handler_type,
  9482. mg_request_handler *handler,
  9483. struct mg_websocket_subprotocols **subprotocols,
  9484. mg_websocket_connect_handler *connect_handler,
  9485. mg_websocket_ready_handler *ready_handler,
  9486. mg_websocket_data_handler *data_handler,
  9487. mg_websocket_close_handler *close_handler,
  9488. mg_authorization_handler *auth_handler,
  9489. void **cbdata)
  9490. {
  9491. const struct mg_request_info *request_info = mg_get_request_info(conn);
  9492. if (request_info) {
  9493. const char *uri = request_info->local_uri;
  9494. size_t urilen = strlen(uri);
  9495. struct mg_handler_info *tmp_rh;
  9496. if (!conn || !conn->ctx) {
  9497. return 0;
  9498. }
  9499. mg_lock_context(conn->ctx);
  9500. /* first try for an exact match */
  9501. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  9502. tmp_rh = tmp_rh->next) {
  9503. if (tmp_rh->handler_type == handler_type) {
  9504. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  9505. if (handler_type == WEBSOCKET_HANDLER) {
  9506. *subprotocols = tmp_rh->subprotocols;
  9507. *connect_handler = tmp_rh->connect_handler;
  9508. *ready_handler = tmp_rh->ready_handler;
  9509. *data_handler = tmp_rh->data_handler;
  9510. *close_handler = tmp_rh->close_handler;
  9511. } else if (handler_type == REQUEST_HANDLER) {
  9512. *handler = tmp_rh->handler;
  9513. } else { /* AUTH_HANDLER */
  9514. *auth_handler = tmp_rh->auth_handler;
  9515. }
  9516. *cbdata = tmp_rh->cbdata;
  9517. mg_unlock_context(conn->ctx);
  9518. return 1;
  9519. }
  9520. }
  9521. }
  9522. /* next try for a partial match, we will accept uri/something */
  9523. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  9524. tmp_rh = tmp_rh->next) {
  9525. if (tmp_rh->handler_type == handler_type) {
  9526. if (tmp_rh->uri_len < urilen && uri[tmp_rh->uri_len] == '/'
  9527. && memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0) {
  9528. if (handler_type == WEBSOCKET_HANDLER) {
  9529. *subprotocols = tmp_rh->subprotocols;
  9530. *connect_handler = tmp_rh->connect_handler;
  9531. *ready_handler = tmp_rh->ready_handler;
  9532. *data_handler = tmp_rh->data_handler;
  9533. *close_handler = tmp_rh->close_handler;
  9534. } else if (handler_type == REQUEST_HANDLER) {
  9535. *handler = tmp_rh->handler;
  9536. } else { /* AUTH_HANDLER */
  9537. *auth_handler = tmp_rh->auth_handler;
  9538. }
  9539. *cbdata = tmp_rh->cbdata;
  9540. mg_unlock_context(conn->ctx);
  9541. return 1;
  9542. }
  9543. }
  9544. }
  9545. /* finally try for pattern match */
  9546. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  9547. tmp_rh = tmp_rh->next) {
  9548. if (tmp_rh->handler_type == handler_type) {
  9549. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  9550. if (handler_type == WEBSOCKET_HANDLER) {
  9551. *subprotocols = tmp_rh->subprotocols;
  9552. *connect_handler = tmp_rh->connect_handler;
  9553. *ready_handler = tmp_rh->ready_handler;
  9554. *data_handler = tmp_rh->data_handler;
  9555. *close_handler = tmp_rh->close_handler;
  9556. } else if (handler_type == REQUEST_HANDLER) {
  9557. *handler = tmp_rh->handler;
  9558. } else { /* AUTH_HANDLER */
  9559. *auth_handler = tmp_rh->auth_handler;
  9560. }
  9561. *cbdata = tmp_rh->cbdata;
  9562. mg_unlock_context(conn->ctx);
  9563. return 1;
  9564. }
  9565. }
  9566. }
  9567. mg_unlock_context(conn->ctx);
  9568. }
  9569. return 0; /* none found */
  9570. }
  9571. /* Check if the script file is in a path, allowed for script files.
  9572. * This can be used if uploading files is possible not only for the server
  9573. * admin, and the upload mechanism does not check the file extension.
  9574. */
  9575. static int
  9576. is_in_script_path(const struct mg_connection *conn, const char *path)
  9577. {
  9578. /* TODO: Add config value for allowed script path.
  9579. * Default: All allowed. */
  9580. (void)conn;
  9581. (void)path;
  9582. return 1;
  9583. }
  9584. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  9585. static int
  9586. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  9587. void *cbdata)
  9588. {
  9589. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9590. if (pcallbacks->websocket_connect) {
  9591. return pcallbacks->websocket_connect(conn);
  9592. }
  9593. /* No handler set - assume "OK" */
  9594. return 0;
  9595. }
  9596. static void
  9597. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  9598. {
  9599. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9600. if (pcallbacks->websocket_ready) {
  9601. pcallbacks->websocket_ready(conn);
  9602. }
  9603. }
  9604. static int
  9605. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  9606. int bits,
  9607. char *data,
  9608. size_t len,
  9609. void *cbdata)
  9610. {
  9611. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9612. if (pcallbacks->websocket_data) {
  9613. return pcallbacks->websocket_data(conn, bits, data, len);
  9614. }
  9615. /* No handler set - assume "OK" */
  9616. return 1;
  9617. }
  9618. #endif
  9619. /* This is the heart of the Civetweb's logic.
  9620. * This function is called when the request is read, parsed and validated,
  9621. * and Civetweb must decide what action to take: serve a file, or
  9622. * a directory, or call embedded function, etcetera. */
  9623. static void
  9624. handle_request(struct mg_connection *conn)
  9625. {
  9626. struct mg_request_info *ri = &conn->request_info;
  9627. char path[PATH_MAX];
  9628. int uri_len, ssl_index;
  9629. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  9630. is_put_or_delete_request = 0, is_callback_resource = 0;
  9631. int i;
  9632. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9633. mg_request_handler callback_handler = NULL;
  9634. struct mg_websocket_subprotocols *subprotocols;
  9635. mg_websocket_connect_handler ws_connect_handler = NULL;
  9636. mg_websocket_ready_handler ws_ready_handler = NULL;
  9637. mg_websocket_data_handler ws_data_handler = NULL;
  9638. mg_websocket_close_handler ws_close_handler = NULL;
  9639. void *callback_data = NULL;
  9640. mg_authorization_handler auth_handler = NULL;
  9641. void *auth_callback_data = NULL;
  9642. #if !defined(NO_FILES)
  9643. time_t curtime = time(NULL);
  9644. char date[64];
  9645. #endif
  9646. path[0] = 0;
  9647. /* 1. get the request url */
  9648. /* 1.1. split into url and query string */
  9649. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  9650. != NULL) {
  9651. *((char *)conn->request_info.query_string++) = '\0';
  9652. }
  9653. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  9654. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  9655. ssl_index = get_first_ssl_listener_index(conn->ctx);
  9656. if (ssl_index >= 0) {
  9657. redirect_to_https_port(conn, ssl_index);
  9658. } else {
  9659. /* A http to https forward port has been specified,
  9660. * but no https port to forward to. */
  9661. send_http_error(conn,
  9662. 503,
  9663. "%s",
  9664. "Error: SSL forward not configured properly");
  9665. mg_cry(conn, "Can not redirect to SSL, no SSL port available");
  9666. }
  9667. return;
  9668. }
  9669. uri_len = (int)strlen(ri->local_uri);
  9670. /* 1.3. decode url (if config says so) */
  9671. if (should_decode_url(conn)) {
  9672. mg_url_decode(
  9673. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  9674. }
  9675. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  9676. * not possible */
  9677. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  9678. /* step 1. completed, the url is known now */
  9679. uri_len = (int)strlen(ri->local_uri);
  9680. DEBUG_TRACE("URL: %s", ri->local_uri);
  9681. /* 3. if this ip has limited speed, set it for this connection */
  9682. conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
  9683. get_remote_ip(conn),
  9684. ri->local_uri);
  9685. /* 4. call a "handle everything" callback, if registered */
  9686. if (conn->ctx->callbacks.begin_request != NULL) {
  9687. /* Note that since V1.7 the "begin_request" function is called
  9688. * before an authorization check. If an authorization check is
  9689. * required, use a request_handler instead. */
  9690. i = conn->ctx->callbacks.begin_request(conn);
  9691. if (i > 0) {
  9692. /* callback already processed the request. Store the
  9693. return value as a status code for the access log. */
  9694. conn->status_code = i;
  9695. discard_unread_request_data(conn);
  9696. return;
  9697. } else if (i == 0) {
  9698. /* civetweb should process the request */
  9699. } else {
  9700. /* unspecified - may change with the next version */
  9701. return;
  9702. }
  9703. }
  9704. /* request not yet handled by a handler or redirect, so the request
  9705. * is processed here */
  9706. /* 5. interpret the url to find out how the request must be handled
  9707. */
  9708. /* 5.1. first test, if the request targets the regular http(s)://
  9709. * protocol namespace or the websocket ws(s):// protocol namespace.
  9710. */
  9711. is_websocket_request = is_websocket_protocol(conn);
  9712. /* 5.2. check if the request will be handled by a callback */
  9713. if (get_request_handler(conn,
  9714. is_websocket_request ? WEBSOCKET_HANDLER
  9715. : REQUEST_HANDLER,
  9716. &callback_handler,
  9717. &subprotocols,
  9718. &ws_connect_handler,
  9719. &ws_ready_handler,
  9720. &ws_data_handler,
  9721. &ws_close_handler,
  9722. NULL,
  9723. &callback_data)) {
  9724. /* 5.2.1. A callback will handle this request. All requests
  9725. * handled
  9726. * by a callback have to be considered as requests to a script
  9727. * resource. */
  9728. is_callback_resource = 1;
  9729. is_script_resource = 1;
  9730. is_put_or_delete_request = is_put_or_delete_method(conn);
  9731. } else {
  9732. no_callback_resource:
  9733. /* 5.2.2. No callback is responsible for this request. The URI
  9734. * addresses a file based resource (static content or Lua/cgi
  9735. * scripts in the file system). */
  9736. is_callback_resource = 0;
  9737. interpret_uri(conn,
  9738. path,
  9739. sizeof(path),
  9740. &file.stat,
  9741. &is_found,
  9742. &is_script_resource,
  9743. &is_websocket_request,
  9744. &is_put_or_delete_request);
  9745. }
  9746. /* 6. authorization check */
  9747. /* 6.1. a custom authorization handler is installed */
  9748. if (get_request_handler(conn,
  9749. AUTH_HANDLER,
  9750. NULL,
  9751. NULL,
  9752. NULL,
  9753. NULL,
  9754. NULL,
  9755. NULL,
  9756. &auth_handler,
  9757. &auth_callback_data)) {
  9758. if (!auth_handler(conn, auth_callback_data)) {
  9759. return;
  9760. }
  9761. } else if (is_put_or_delete_request && !is_script_resource
  9762. && !is_callback_resource) {
  9763. /* 6.2. this request is a PUT/DELETE to a real file */
  9764. /* 6.2.1. thus, the server must have real files */
  9765. #if defined(NO_FILES)
  9766. if (1) {
  9767. #else
  9768. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  9769. #endif
  9770. /* This server does not have any real files, thus the
  9771. * PUT/DELETE methods are not valid. */
  9772. send_http_error(conn,
  9773. 405,
  9774. "%s method not allowed",
  9775. conn->request_info.request_method);
  9776. return;
  9777. }
  9778. #if !defined(NO_FILES)
  9779. /* 6.2.2. Check if put authorization for static files is
  9780. * available.
  9781. */
  9782. if (!is_authorized_for_put(conn)) {
  9783. send_authorization_request(conn);
  9784. return;
  9785. }
  9786. #endif
  9787. } else {
  9788. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  9789. * or it is a PUT or DELETE request to a resource that does not
  9790. * correspond to a file. Check authorization. */
  9791. if (!check_authorization(conn, path)) {
  9792. send_authorization_request(conn);
  9793. return;
  9794. }
  9795. }
  9796. /* request is authorized or does not need authorization */
  9797. /* 7. check if there are request handlers for this uri */
  9798. if (is_callback_resource) {
  9799. if (!is_websocket_request) {
  9800. i = callback_handler(conn, callback_data);
  9801. if (i > 0) {
  9802. /* Do nothing, callback has served the request. Store
  9803. * then return value as status code for the log and discard
  9804. * all data from the client not used by the callback. */
  9805. conn->status_code = i;
  9806. discard_unread_request_data(conn);
  9807. } else {
  9808. /* The handler did NOT handle the request. */
  9809. /* Some proper reactions would be:
  9810. * a) close the connections without sending anything
  9811. * b) send a 404 not found
  9812. * c) try if there is a file matching the URI
  9813. * It would be possible to do a, b or c in the callback
  9814. * implementation, and return 1 - we cannot do anything
  9815. * here, that is not possible in the callback.
  9816. *
  9817. * TODO: What would be the best reaction here?
  9818. * (Note: The reaction may change, if there is a better idea.)
  9819. */
  9820. /* For the moment, use option c: We look for a proper file,
  9821. * but since a file request is not always a script resource,
  9822. * the authorization check might be different. */
  9823. interpret_uri(conn,
  9824. path,
  9825. sizeof(path),
  9826. &file.stat,
  9827. &is_found,
  9828. &is_script_resource,
  9829. &is_websocket_request,
  9830. &is_put_or_delete_request);
  9831. callback_handler = NULL;
  9832. /* Here we are at a dead end:
  9833. * According to URI matching, a callback should be
  9834. * responsible for handling the request,
  9835. * we called it, but the callback declared itself
  9836. * not responsible.
  9837. * We use a goto here, to get out of this dead end,
  9838. * and continue with the default handling.
  9839. * A goto here is simpler and better to understand
  9840. * than some curious loop. */
  9841. goto no_callback_resource;
  9842. }
  9843. } else {
  9844. #if defined(USE_WEBSOCKET)
  9845. handle_websocket_request(conn,
  9846. path,
  9847. is_callback_resource,
  9848. subprotocols,
  9849. ws_connect_handler,
  9850. ws_ready_handler,
  9851. ws_data_handler,
  9852. ws_close_handler,
  9853. callback_data);
  9854. #endif
  9855. }
  9856. return;
  9857. }
  9858. /* 8. handle websocket requests */
  9859. #if defined(USE_WEBSOCKET)
  9860. if (is_websocket_request) {
  9861. if (is_script_resource) {
  9862. if (is_in_script_path(conn, path)) {
  9863. /* Websocket Lua script */
  9864. handle_websocket_request(conn,
  9865. path,
  9866. 0 /* Lua Script */,
  9867. NULL,
  9868. NULL,
  9869. NULL,
  9870. NULL,
  9871. NULL,
  9872. &conn->ctx->callbacks);
  9873. } else {
  9874. /* Script was in an illegal path */
  9875. send_http_error(conn, 403, "%s", "Forbidden");
  9876. }
  9877. } else {
  9878. #if defined(MG_LEGACY_INTERFACE)
  9879. handle_websocket_request(
  9880. conn,
  9881. path,
  9882. !is_script_resource /* could be deprecated global callback */,
  9883. NULL,
  9884. deprecated_websocket_connect_wrapper,
  9885. deprecated_websocket_ready_wrapper,
  9886. deprecated_websocket_data_wrapper,
  9887. NULL,
  9888. &conn->ctx->callbacks);
  9889. #else
  9890. send_http_error(conn, 404, "%s", "Not found");
  9891. #endif
  9892. }
  9893. return;
  9894. } else
  9895. #endif
  9896. #if defined(NO_FILES)
  9897. /* 9a. In case the server uses only callbacks, this uri is
  9898. * unknown.
  9899. * Then, all request handling ends here. */
  9900. send_http_error(conn, 404, "%s", "Not Found");
  9901. #else
  9902. /* 9b. This request is either for a static file or resource handled
  9903. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  9904. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  9905. send_http_error(conn, 404, "%s", "Not Found");
  9906. return;
  9907. }
  9908. /* 10. Request is handled by a script */
  9909. if (is_script_resource) {
  9910. handle_file_based_request(conn, path, &file);
  9911. return;
  9912. }
  9913. /* 11. Handle put/delete/mkcol requests */
  9914. if (is_put_or_delete_request) {
  9915. /* 11.1. PUT method */
  9916. if (!strcmp(ri->request_method, "PUT")) {
  9917. put_file(conn, path);
  9918. return;
  9919. }
  9920. /* 11.2. DELETE method */
  9921. if (!strcmp(ri->request_method, "DELETE")) {
  9922. delete_file(conn, path);
  9923. return;
  9924. }
  9925. /* 11.3. MKCOL method */
  9926. if (!strcmp(ri->request_method, "MKCOL")) {
  9927. mkcol(conn, path);
  9928. return;
  9929. }
  9930. /* 11.4. PATCH method
  9931. * This method is not supported for static resources,
  9932. * only for scripts (Lua, CGI) and callbacks. */
  9933. send_http_error(conn,
  9934. 405,
  9935. "%s method not allowed",
  9936. conn->request_info.request_method);
  9937. return;
  9938. }
  9939. /* 11. File does not exist, or it was configured that it should be
  9940. * hidden */
  9941. if (!is_found || (must_hide_file(conn, path))) {
  9942. send_http_error(conn, 404, "%s", "Not found");
  9943. return;
  9944. }
  9945. /* 12. Directory uris should end with a slash */
  9946. if (file.stat.is_directory && (uri_len > 0)
  9947. && (ri->local_uri[uri_len - 1] != '/')) {
  9948. gmt_time_string(date, sizeof(date), &curtime);
  9949. mg_printf(conn,
  9950. "HTTP/1.1 301 Moved Permanently\r\n"
  9951. "Location: %s/\r\n"
  9952. "Date: %s\r\n"
  9953. /* "Cache-Control: private\r\n" (= default) */
  9954. "Content-Length: 0\r\n"
  9955. "Connection: %s\r\n",
  9956. ri->request_uri,
  9957. date,
  9958. suggest_connection_header(conn));
  9959. send_additional_header(conn);
  9960. mg_printf(conn, "\r\n");
  9961. return;
  9962. }
  9963. /* 13. Handle other methods than GET/HEAD */
  9964. /* 13.1. Handle PROPFIND */
  9965. if (!strcmp(ri->request_method, "PROPFIND")) {
  9966. handle_propfind(conn, path, &file.stat);
  9967. return;
  9968. }
  9969. /* 13.2. Handle OPTIONS for files */
  9970. if (!strcmp(ri->request_method, "OPTIONS")) {
  9971. /* This standard handler is only used for real files.
  9972. * Scripts should support the OPTIONS method themselves, to allow a
  9973. * maximum flexibility.
  9974. * Lua and CGI scripts may fully support CORS this way (including
  9975. * preflights). */
  9976. send_options(conn);
  9977. return;
  9978. }
  9979. /* 13.3. everything but GET and HEAD (e.g. POST) */
  9980. if (0 != strcmp(ri->request_method, "GET")
  9981. && 0 != strcmp(ri->request_method, "HEAD")) {
  9982. send_http_error(conn,
  9983. 405,
  9984. "%s method not allowed",
  9985. conn->request_info.request_method);
  9986. return;
  9987. }
  9988. /* 14. directories */
  9989. if (file.stat.is_directory) {
  9990. /* Substitute files have already been handled above. */
  9991. /* Here we can either generate and send a directory listing,
  9992. * or send an "access denied" error. */
  9993. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  9994. "yes")) {
  9995. handle_directory_request(conn, path);
  9996. } else {
  9997. send_http_error(conn, 403, "%s", "Error: Directory listing denied");
  9998. }
  9999. return;
  10000. }
  10001. handle_file_based_request(conn, path, &file);
  10002. #endif /* !defined(NO_FILES) */
  10003. #if 0
  10004. /* Perform redirect and auth checks before calling begin_request()
  10005. * handler.
  10006. * Otherwise, begin_request() would need to perform auth checks and
  10007. * redirects. */
  10008. #endif
  10009. }
  10010. static void
  10011. handle_file_based_request(struct mg_connection *conn,
  10012. const char *path,
  10013. struct mg_file *file)
  10014. {
  10015. if (!conn || !conn->ctx) {
  10016. return;
  10017. }
  10018. if (0) {
  10019. #ifdef USE_LUA
  10020. } else if (match_prefix(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  10021. strlen(
  10022. conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  10023. path) > 0) {
  10024. if (is_in_script_path(conn, path)) {
  10025. /* Lua server page: an SSI like page containing mostly plain html
  10026. * code
  10027. * plus some tags with server generated contents. */
  10028. handle_lsp_request(conn, path, file, NULL);
  10029. } else {
  10030. /* Script was in an illegal path */
  10031. send_http_error(conn, 403, "%s", "Forbidden");
  10032. }
  10033. } else if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  10034. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  10035. path) > 0) {
  10036. if (is_in_script_path(conn, path)) {
  10037. /* Lua in-server module script: a CGI like script used to generate
  10038. * the
  10039. * entire reply. */
  10040. mg_exec_lua_script(conn, path, NULL);
  10041. } else {
  10042. /* Script was in an illegal path */
  10043. send_http_error(conn, 403, "%s", "Forbidden");
  10044. }
  10045. #endif
  10046. #if defined(USE_DUKTAPE)
  10047. } else if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  10048. strlen(
  10049. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  10050. path) > 0) {
  10051. if (is_in_script_path(conn, path)) {
  10052. /* Call duktape to generate the page */
  10053. mg_exec_duktape_script(conn, path);
  10054. } else {
  10055. /* Script was in an illegal path */
  10056. send_http_error(conn, 403, "%s", "Forbidden");
  10057. }
  10058. #endif
  10059. #if !defined(NO_CGI)
  10060. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  10061. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  10062. path) > 0) {
  10063. if (is_in_script_path(conn, path)) {
  10064. /* CGI scripts may support all HTTP methods */
  10065. handle_cgi_request(conn, path);
  10066. } else {
  10067. /* Script was in an illegal path */
  10068. send_http_error(conn, 403, "%s", "Forbidden");
  10069. }
  10070. #endif /* !NO_CGI */
  10071. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  10072. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  10073. path) > 0) {
  10074. if (is_in_script_path(conn, path)) {
  10075. handle_ssi_file_request(conn, path, file);
  10076. } else {
  10077. /* Script was in an illegal path */
  10078. send_http_error(conn, 403, "%s", "Forbidden");
  10079. }
  10080. #if !defined(NO_CACHING)
  10081. } else if ((!conn->in_error_handler)
  10082. && is_not_modified(conn, &file->stat)) {
  10083. /* Send 304 "Not Modified" - this must not send any body data */
  10084. handle_not_modified_static_file_request(conn, file);
  10085. #endif /* !NO_CACHING */
  10086. } else {
  10087. handle_static_file_request(conn, path, file, NULL, NULL);
  10088. }
  10089. }
  10090. static void
  10091. close_all_listening_sockets(struct mg_context *ctx)
  10092. {
  10093. unsigned int i;
  10094. if (!ctx) {
  10095. return;
  10096. }
  10097. for (i = 0; i < ctx->num_listening_sockets; i++) {
  10098. closesocket(ctx->listening_sockets[i].sock);
  10099. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  10100. }
  10101. mg_free(ctx->listening_sockets);
  10102. ctx->listening_sockets = NULL;
  10103. mg_free(ctx->listening_socket_fds);
  10104. ctx->listening_socket_fds = NULL;
  10105. }
  10106. /* Valid listening port specification is: [ip_address:]port[s]
  10107. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  10108. * Examples for IPv6: [::]:80, [::1]:80,
  10109. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  10110. * see https://tools.ietf.org/html/rfc3513#section-2.2
  10111. * In order to bind to both, IPv4 and IPv6, you can either add
  10112. * both ports using 8080,[::]:8080, or the short form +8080.
  10113. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  10114. * one only accepting IPv4 the other only IPv6. +8080 creates
  10115. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  10116. * environment, they might work differently, or might not work
  10117. * at all - it must be tested what options work best in the
  10118. * relevant network environment.
  10119. */
  10120. static int
  10121. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  10122. {
  10123. unsigned int a, b, c, d, port;
  10124. int ch, len;
  10125. #if defined(USE_IPV6)
  10126. char buf[100] = {0};
  10127. #endif
  10128. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  10129. * Also, all-zeroes in the socket address means binding to all addresses
  10130. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  10131. memset(so, 0, sizeof(*so));
  10132. so->lsa.sin.sin_family = AF_INET;
  10133. *ip_version = 0;
  10134. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  10135. == 5) {
  10136. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  10137. so->lsa.sin.sin_addr.s_addr =
  10138. htonl((a << 24) | (b << 16) | (c << 8) | d);
  10139. so->lsa.sin.sin_port = htons((uint16_t)port);
  10140. *ip_version = 4;
  10141. #if defined(USE_IPV6)
  10142. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  10143. && mg_inet_pton(
  10144. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  10145. /* IPv6 address, examples: see above */
  10146. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  10147. */
  10148. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  10149. *ip_version = 6;
  10150. #endif
  10151. } else if ((vec->ptr[0] == '+')
  10152. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  10153. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  10154. /* Add 1 to len for the + character we skipped before */
  10155. len++;
  10156. #if defined(USE_IPV6)
  10157. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  10158. so->lsa.sin6.sin6_family = AF_INET6;
  10159. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  10160. *ip_version = 4 + 6;
  10161. #else
  10162. /* Bind to IPv4 only, since IPv6 is not built in. */
  10163. so->lsa.sin.sin_port = htons((uint16_t)port);
  10164. *ip_version = 4;
  10165. #endif
  10166. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  10167. /* If only port is specified, bind to IPv4, INADDR_ANY */
  10168. so->lsa.sin.sin_port = htons((uint16_t)port);
  10169. *ip_version = 4;
  10170. } else {
  10171. /* Parsing failure. Make port invalid. */
  10172. port = 0;
  10173. len = 0;
  10174. }
  10175. /* sscanf and the option splitting code ensure the following condition
  10176. */
  10177. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  10178. *ip_version = 0;
  10179. return 0;
  10180. }
  10181. ch = vec->ptr[len]; /* Next character after the port number */
  10182. so->is_ssl = (ch == 's');
  10183. so->ssl_redir = (ch == 'r');
  10184. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  10185. if (is_valid_port(port)
  10186. && (ch == '\0' || ch == 's' || ch == 'r' || ch == ',')) {
  10187. return 1;
  10188. }
  10189. /* Reset ip_version to 0 of there is an error */
  10190. *ip_version = 0;
  10191. return 0;
  10192. }
  10193. static int
  10194. set_ports_option(struct mg_context *ctx)
  10195. {
  10196. const char *list;
  10197. int on = 1;
  10198. #if defined(USE_IPV6)
  10199. int off = 0;
  10200. #endif
  10201. struct vec vec;
  10202. struct socket so, *ptr;
  10203. struct pollfd *pfd;
  10204. union usa usa;
  10205. socklen_t len;
  10206. int ip_version;
  10207. int portsTotal = 0;
  10208. int portsOk = 0;
  10209. if (!ctx) {
  10210. return 0;
  10211. }
  10212. memset(&so, 0, sizeof(so));
  10213. memset(&usa, 0, sizeof(usa));
  10214. len = sizeof(usa);
  10215. list = ctx->config[LISTENING_PORTS];
  10216. while ((list = next_option(list, &vec, NULL)) != NULL) {
  10217. portsTotal++;
  10218. if (!parse_port_string(&vec, &so, &ip_version)) {
  10219. mg_cry(fc(ctx),
  10220. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  10221. (int)vec.len,
  10222. vec.ptr,
  10223. portsTotal,
  10224. "[IP_ADDRESS:]PORT[s|r]");
  10225. continue;
  10226. }
  10227. #if !defined(NO_SSL)
  10228. if (so.is_ssl && ctx->ssl_ctx == NULL) {
  10229. mg_cry(fc(ctx),
  10230. "Cannot add SSL socket (entry %i). Is -ssl_certificate "
  10231. "option set?",
  10232. portsTotal);
  10233. continue;
  10234. }
  10235. #endif
  10236. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  10237. == INVALID_SOCKET) {
  10238. mg_cry(fc(ctx), "cannot create socket (entry %i)", portsTotal);
  10239. continue;
  10240. }
  10241. #ifdef _WIN32
  10242. /* Windows SO_REUSEADDR lets many procs binds to a
  10243. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  10244. * if someone already has the socket -- DTL */
  10245. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  10246. * Windows might need a few seconds before
  10247. * the same port can be used again in the
  10248. * same process, so a short Sleep may be
  10249. * required between mg_stop and mg_start.
  10250. */
  10251. if (setsockopt(so.sock,
  10252. SOL_SOCKET,
  10253. SO_EXCLUSIVEADDRUSE,
  10254. (SOCK_OPT_TYPE)&on,
  10255. sizeof(on)) != 0) {
  10256. /* Set reuse option, but don't abort on errors. */
  10257. mg_cry(fc(ctx),
  10258. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  10259. portsTotal);
  10260. }
  10261. #else
  10262. if (setsockopt(so.sock,
  10263. SOL_SOCKET,
  10264. SO_REUSEADDR,
  10265. (SOCK_OPT_TYPE)&on,
  10266. sizeof(on)) != 0) {
  10267. /* Set reuse option, but don't abort on errors. */
  10268. mg_cry(fc(ctx),
  10269. "cannot set socket option SO_REUSEADDR (entry %i)",
  10270. portsTotal);
  10271. }
  10272. #endif
  10273. if (ip_version > 4) {
  10274. #if defined(USE_IPV6)
  10275. if (ip_version == 6) {
  10276. if (so.lsa.sa.sa_family == AF_INET6
  10277. && setsockopt(so.sock,
  10278. IPPROTO_IPV6,
  10279. IPV6_V6ONLY,
  10280. (void *)&off,
  10281. sizeof(off)) != 0) {
  10282. /* Set IPv6 only option, but don't abort on errors. */
  10283. mg_cry(fc(ctx),
  10284. "cannot set socket option IPV6_V6ONLY (entry %i)",
  10285. portsTotal);
  10286. }
  10287. }
  10288. #else
  10289. mg_cry(fc(ctx), "IPv6 not available");
  10290. closesocket(so.sock);
  10291. so.sock = INVALID_SOCKET;
  10292. continue;
  10293. #endif
  10294. }
  10295. if (so.lsa.sa.sa_family == AF_INET) {
  10296. len = sizeof(so.lsa.sin);
  10297. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  10298. mg_cry(fc(ctx),
  10299. "cannot bind to %.*s: %d (%s)",
  10300. (int)vec.len,
  10301. vec.ptr,
  10302. (int)ERRNO,
  10303. strerror(errno));
  10304. closesocket(so.sock);
  10305. so.sock = INVALID_SOCKET;
  10306. continue;
  10307. }
  10308. }
  10309. #if defined(USE_IPV6)
  10310. else if (so.lsa.sa.sa_family == AF_INET6) {
  10311. len = sizeof(so.lsa.sin6);
  10312. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  10313. mg_cry(fc(ctx),
  10314. "cannot bind to IPv6 %.*s: %d (%s)",
  10315. (int)vec.len,
  10316. vec.ptr,
  10317. (int)ERRNO,
  10318. strerror(errno));
  10319. closesocket(so.sock);
  10320. so.sock = INVALID_SOCKET;
  10321. continue;
  10322. }
  10323. }
  10324. #endif
  10325. else {
  10326. mg_cry(fc(ctx),
  10327. "cannot bind: address family not supported (entry %i)",
  10328. portsTotal);
  10329. continue;
  10330. }
  10331. if (listen(so.sock, SOMAXCONN) != 0) {
  10332. mg_cry(fc(ctx),
  10333. "cannot listen to %.*s: %d (%s)",
  10334. (int)vec.len,
  10335. vec.ptr,
  10336. (int)ERRNO,
  10337. strerror(errno));
  10338. closesocket(so.sock);
  10339. so.sock = INVALID_SOCKET;
  10340. continue;
  10341. }
  10342. if (getsockname(so.sock, &(usa.sa), &len) != 0
  10343. || usa.sa.sa_family != so.lsa.sa.sa_family) {
  10344. int err = (int)ERRNO;
  10345. mg_cry(fc(ctx),
  10346. "call to getsockname failed %.*s: %d (%s)",
  10347. (int)vec.len,
  10348. vec.ptr,
  10349. err,
  10350. strerror(errno));
  10351. closesocket(so.sock);
  10352. so.sock = INVALID_SOCKET;
  10353. continue;
  10354. }
  10355. /* Update lsa port in case of random free ports */
  10356. #if defined(USE_IPV6)
  10357. if (so.lsa.sa.sa_family == AF_INET6) {
  10358. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  10359. } else
  10360. #endif
  10361. {
  10362. so.lsa.sin.sin_port = usa.sin.sin_port;
  10363. }
  10364. if ((ptr = (struct socket *)
  10365. mg_realloc(ctx->listening_sockets,
  10366. (ctx->num_listening_sockets + 1)
  10367. * sizeof(ctx->listening_sockets[0]))) == NULL) {
  10368. mg_cry(fc(ctx), "%s", "Out of memory");
  10369. closesocket(so.sock);
  10370. so.sock = INVALID_SOCKET;
  10371. continue;
  10372. }
  10373. if ((pfd = (struct pollfd *)mg_realloc(
  10374. ctx->listening_socket_fds,
  10375. (ctx->num_listening_sockets + 1)
  10376. * sizeof(ctx->listening_socket_fds[0]))) == NULL) {
  10377. mg_cry(fc(ctx), "%s", "Out of memory");
  10378. closesocket(so.sock);
  10379. so.sock = INVALID_SOCKET;
  10380. mg_free(ptr);
  10381. continue;
  10382. }
  10383. set_close_on_exec(so.sock, fc(ctx));
  10384. ctx->listening_sockets = ptr;
  10385. ctx->listening_sockets[ctx->num_listening_sockets] = so;
  10386. ctx->listening_socket_fds = pfd;
  10387. ctx->num_listening_sockets++;
  10388. portsOk++;
  10389. }
  10390. if (portsOk != portsTotal) {
  10391. close_all_listening_sockets(ctx);
  10392. portsOk = 0;
  10393. }
  10394. return portsOk;
  10395. }
  10396. static const char *
  10397. header_val(const struct mg_connection *conn, const char *header)
  10398. {
  10399. const char *header_value;
  10400. if ((header_value = mg_get_header(conn, header)) == NULL) {
  10401. return "-";
  10402. } else {
  10403. return header_value;
  10404. }
  10405. }
  10406. static void
  10407. log_access(const struct mg_connection *conn)
  10408. {
  10409. const struct mg_request_info *ri;
  10410. struct mg_file fi;
  10411. char date[64], src_addr[IP_ADDR_STR_LEN];
  10412. struct tm *tm;
  10413. const char *referer;
  10414. const char *user_agent;
  10415. char buf[4096];
  10416. if (!conn || !conn->ctx) {
  10417. return;
  10418. }
  10419. if (conn->ctx->config[ACCESS_LOG_FILE] != NULL) {
  10420. if (mg_fopen(conn,
  10421. conn->ctx->config[ACCESS_LOG_FILE],
  10422. MG_FOPEN_MODE_APPEND,
  10423. &fi) == 0) {
  10424. fi.access.fp = NULL;
  10425. }
  10426. } else {
  10427. fi.access.fp = NULL;
  10428. }
  10429. /* Log is written to a file and/or a callback. If both are not set,
  10430. * executing the rest of the function is pointless. */
  10431. if ((fi.access.fp == NULL) && (conn->ctx->callbacks.log_access == NULL)) {
  10432. return;
  10433. }
  10434. tm = localtime(&conn->conn_birth_time);
  10435. if (tm != NULL) {
  10436. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  10437. } else {
  10438. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  10439. date[sizeof(date) - 1] = '\0';
  10440. }
  10441. ri = &conn->request_info;
  10442. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  10443. referer = header_val(conn, "Referer");
  10444. user_agent = header_val(conn, "User-Agent");
  10445. mg_snprintf(conn,
  10446. NULL, /* Ignore truncation in access log */
  10447. buf,
  10448. sizeof(buf),
  10449. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  10450. src_addr,
  10451. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  10452. date,
  10453. ri->request_method ? ri->request_method : "-",
  10454. ri->request_uri ? ri->request_uri : "-",
  10455. ri->query_string ? "?" : "",
  10456. ri->query_string ? ri->query_string : "",
  10457. ri->http_version,
  10458. conn->status_code,
  10459. conn->num_bytes_sent,
  10460. referer,
  10461. user_agent);
  10462. if (conn->ctx->callbacks.log_access) {
  10463. conn->ctx->callbacks.log_access(conn, buf);
  10464. }
  10465. if (fi.access.fp) {
  10466. int ok = 1;
  10467. flockfile(fi.access.fp);
  10468. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  10469. ok = 0;
  10470. }
  10471. if (fflush(fi.access.fp) != 0) {
  10472. ok = 0;
  10473. }
  10474. funlockfile(fi.access.fp);
  10475. if (mg_fclose(&fi.access) != 0) {
  10476. ok = 0;
  10477. }
  10478. if (!ok) {
  10479. mg_cry(conn,
  10480. "Error writing log file %s",
  10481. conn->ctx->config[ACCESS_LOG_FILE]);
  10482. }
  10483. }
  10484. }
  10485. /* Verify given socket address against the ACL.
  10486. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  10487. */
  10488. static int
  10489. check_acl(struct mg_context *ctx, uint32_t remote_ip)
  10490. {
  10491. int allowed, flag;
  10492. uint32_t net, mask;
  10493. struct vec vec;
  10494. if (ctx) {
  10495. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  10496. /* If any ACL is set, deny by default */
  10497. allowed = (list == NULL) ? '+' : '-';
  10498. while ((list = next_option(list, &vec, NULL)) != NULL) {
  10499. flag = vec.ptr[0];
  10500. if ((flag != '+' && flag != '-')
  10501. || parse_net(&vec.ptr[1], &net, &mask) == 0) {
  10502. mg_cry(fc(ctx),
  10503. "%s: subnet must be [+|-]x.x.x.x[/x]",
  10504. __func__);
  10505. return -1;
  10506. }
  10507. if (net == (remote_ip & mask)) {
  10508. allowed = flag;
  10509. }
  10510. }
  10511. return allowed == '+';
  10512. }
  10513. return -1;
  10514. }
  10515. #if !defined(_WIN32)
  10516. static int
  10517. set_uid_option(struct mg_context *ctx)
  10518. {
  10519. struct passwd *pw;
  10520. if (ctx) {
  10521. const char *uid = ctx->config[RUN_AS_USER];
  10522. int success = 0;
  10523. if (uid == NULL) {
  10524. success = 1;
  10525. } else {
  10526. if ((pw = getpwnam(uid)) == NULL) {
  10527. mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  10528. } else if (setgid(pw->pw_gid) == -1) {
  10529. mg_cry(fc(ctx),
  10530. "%s: setgid(%s): %s",
  10531. __func__,
  10532. uid,
  10533. strerror(errno));
  10534. } else if (setgroups(0, NULL)) {
  10535. mg_cry(fc(ctx),
  10536. "%s: setgroups(): %s",
  10537. __func__,
  10538. strerror(errno));
  10539. } else if (setuid(pw->pw_uid) == -1) {
  10540. mg_cry(fc(ctx),
  10541. "%s: setuid(%s): %s",
  10542. __func__,
  10543. uid,
  10544. strerror(errno));
  10545. } else {
  10546. success = 1;
  10547. }
  10548. }
  10549. return success;
  10550. }
  10551. return 0;
  10552. }
  10553. #endif /* !_WIN32 */
  10554. static void
  10555. tls_dtor(void *key)
  10556. {
  10557. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  10558. /* key == pthread_getspecific(sTlsKey); */
  10559. if (tls) {
  10560. if (tls->is_master == 2) {
  10561. tls->is_master = -3; /* Mark memory as dead */
  10562. mg_free(tls);
  10563. }
  10564. }
  10565. pthread_setspecific(sTlsKey, NULL);
  10566. }
  10567. #if !defined(NO_SSL)
  10568. static int ssl_use_pem_file(struct mg_context *ctx, const char *pem);
  10569. static const char *ssl_error(void);
  10570. static int
  10571. refresh_trust(struct mg_connection *conn)
  10572. {
  10573. static int reload_lock = 0;
  10574. static long int data_check = 0;
  10575. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  10576. struct stat cert_buf;
  10577. long int t;
  10578. char *pem;
  10579. int should_verify_peer;
  10580. if ((pem = conn->ctx->config[SSL_CERTIFICATE]) == NULL) {
  10581. /* If peem is NULL and conn->ctx->callbacks.init_ssl is not,
  10582. * refresh_trust still can not work. */
  10583. return 0;
  10584. }
  10585. t = data_check;
  10586. if (stat(pem, &cert_buf) != -1) {
  10587. t = (long int)cert_buf.st_mtime;
  10588. }
  10589. if (data_check != t) {
  10590. data_check = t;
  10591. should_verify_peer =
  10592. (conn->ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  10593. && (mg_strcasecmp(conn->ctx->config[SSL_DO_VERIFY_PEER], "yes")
  10594. == 0);
  10595. if (should_verify_peer) {
  10596. char *ca_path = conn->ctx->config[SSL_CA_PATH];
  10597. char *ca_file = conn->ctx->config[SSL_CA_FILE];
  10598. if (SSL_CTX_load_verify_locations(conn->ctx->ssl_ctx,
  10599. ca_file,
  10600. ca_path) != 1) {
  10601. mg_cry(fc(conn->ctx),
  10602. "SSL_CTX_load_verify_locations error: %s "
  10603. "ssl_verify_peer requires setting "
  10604. "either ssl_ca_path or ssl_ca_file. Is any of them "
  10605. "present in "
  10606. "the .conf file?",
  10607. ssl_error());
  10608. return 0;
  10609. }
  10610. }
  10611. if (1 == mg_atomic_inc(p_reload_lock)) {
  10612. if (ssl_use_pem_file(conn->ctx, pem) == 0) {
  10613. return 0;
  10614. }
  10615. *p_reload_lock = 0;
  10616. }
  10617. }
  10618. /* lock while cert is reloading */
  10619. while (*p_reload_lock) {
  10620. sleep(1);
  10621. }
  10622. return 1;
  10623. }
  10624. #ifdef OPENSSL_API_1_1
  10625. #else
  10626. static pthread_mutex_t *ssl_mutexes;
  10627. #endif /* OPENSSL_API_1_1 */
  10628. static int
  10629. sslize(struct mg_connection *conn,
  10630. SSL_CTX *s,
  10631. int (*func)(SSL *),
  10632. volatile int *stop_server)
  10633. {
  10634. int ret, err;
  10635. int short_trust;
  10636. unsigned i;
  10637. if (!conn) {
  10638. return 0;
  10639. }
  10640. short_trust =
  10641. (conn->ctx->config[SSL_SHORT_TRUST] != NULL)
  10642. && (mg_strcasecmp(conn->ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  10643. if (short_trust) {
  10644. int trust_ret = refresh_trust(conn);
  10645. if (!trust_ret) {
  10646. return trust_ret;
  10647. }
  10648. }
  10649. conn->ssl = SSL_new(s);
  10650. if (conn->ssl == NULL) {
  10651. return 0;
  10652. }
  10653. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  10654. if (ret != 1) {
  10655. err = SSL_get_error(conn->ssl, ret);
  10656. (void)err; /* TODO: set some error message */
  10657. SSL_free(conn->ssl);
  10658. conn->ssl = NULL;
  10659. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  10660. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  10661. #ifndef OPENSSL_API_1_1
  10662. ERR_remove_state(0);
  10663. #endif
  10664. return 0;
  10665. }
  10666. /* SSL functions may fail and require to be called again:
  10667. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  10668. * Here "func" could be SSL_connect or SSL_accept. */
  10669. for (i = 16; i <= 1024; i *= 2) {
  10670. ret = func(conn->ssl);
  10671. if (ret != 1) {
  10672. err = SSL_get_error(conn->ssl, ret);
  10673. if ((err == SSL_ERROR_WANT_CONNECT)
  10674. || (err == SSL_ERROR_WANT_ACCEPT)
  10675. || (err == SSL_ERROR_WANT_READ)
  10676. || (err == SSL_ERROR_WANT_WRITE)) {
  10677. /* Need to retry the function call "later".
  10678. * See https://linux.die.net/man/3/ssl_get_error
  10679. * This is typical for non-blocking sockets. */
  10680. if (*stop_server) {
  10681. /* Don't wait if the server is going to be stopped. */
  10682. break;
  10683. }
  10684. mg_sleep(i);
  10685. } else if (err == SSL_ERROR_SYSCALL) {
  10686. /* This is an IO error. Look at errno. */
  10687. err = errno;
  10688. /* TODO: set some error message */
  10689. break;
  10690. } else {
  10691. /* This is an SSL specific error */
  10692. /* TODO: set some error message */
  10693. break;
  10694. }
  10695. } else {
  10696. /* success */
  10697. break;
  10698. }
  10699. }
  10700. if (ret != 1) {
  10701. SSL_free(conn->ssl);
  10702. conn->ssl = NULL;
  10703. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  10704. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  10705. #ifndef OPENSSL_API_1_1
  10706. ERR_remove_state(0);
  10707. #endif
  10708. return 0;
  10709. }
  10710. return 1;
  10711. }
  10712. /* Return OpenSSL error message (from CRYPTO lib) */
  10713. static const char *
  10714. ssl_error(void)
  10715. {
  10716. unsigned long err;
  10717. err = ERR_get_error();
  10718. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  10719. }
  10720. static int
  10721. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  10722. {
  10723. int i;
  10724. const char hexdigit[] = "0123456789abcdef";
  10725. if (memlen <= 0 || buflen <= 0) {
  10726. return 0;
  10727. }
  10728. if (buflen < (3 * memlen)) {
  10729. return 0;
  10730. }
  10731. for (i = 0; i < memlen; i++) {
  10732. if (i > 0) {
  10733. buf[3 * i - 1] = ' ';
  10734. }
  10735. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  10736. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  10737. }
  10738. buf[3 * memlen - 1] = 0;
  10739. return 1;
  10740. }
  10741. static void
  10742. ssl_get_client_cert_info(struct mg_connection *conn)
  10743. {
  10744. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  10745. if (cert) {
  10746. char str_subject[1024];
  10747. char str_issuer[1024];
  10748. char str_finger[1024];
  10749. unsigned char buf[256];
  10750. char *str_serial = NULL;
  10751. unsigned int ulen;
  10752. /* Handle to algorithm used for fingerprint */
  10753. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  10754. /* Get Subject and issuer */
  10755. X509_NAME *subj = X509_get_subject_name(cert);
  10756. X509_NAME *iss = X509_get_issuer_name(cert);
  10757. /* Get serial number */
  10758. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  10759. /* Translate serial number to a hex string */
  10760. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  10761. str_serial = BN_bn2hex(serial_bn);
  10762. BN_free(serial_bn);
  10763. /* Translate subject and issuer to a string */
  10764. (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
  10765. (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
  10766. /* Calculate SHA1 fingerprint and store as a hex string */
  10767. ulen = 0;
  10768. ASN1_digest((int (*)(void *, unsigned char **))i2d_X509,
  10769. digest,
  10770. (char *)cert,
  10771. buf,
  10772. &ulen);
  10773. if (!hexdump2string(
  10774. buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
  10775. *str_finger = 0;
  10776. }
  10777. conn->request_info.client_cert =
  10778. (struct client_cert *)mg_malloc(sizeof(struct client_cert));
  10779. if (conn->request_info.client_cert) {
  10780. conn->request_info.client_cert->subject = mg_strdup(str_subject);
  10781. conn->request_info.client_cert->issuer = mg_strdup(str_issuer);
  10782. conn->request_info.client_cert->serial = mg_strdup(str_serial);
  10783. conn->request_info.client_cert->finger = mg_strdup(str_finger);
  10784. } else {
  10785. /* TODO: write some OOM message */
  10786. }
  10787. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  10788. * see https://linux.die.net/man/3/bn_bn2hex */
  10789. OPENSSL_free(str_serial);
  10790. /* Free certificate memory */
  10791. X509_free(cert);
  10792. }
  10793. }
  10794. #ifdef OPENSSL_API_1_1
  10795. #else
  10796. static void
  10797. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  10798. {
  10799. (void)line;
  10800. (void)file;
  10801. if (mode & 1) {
  10802. /* 1 is CRYPTO_LOCK */
  10803. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  10804. } else {
  10805. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  10806. }
  10807. }
  10808. #endif /* OPENSSL_API_1_1 */
  10809. #if !defined(NO_SSL_DL)
  10810. static void *
  10811. load_dll(char *ebuf, size_t ebuf_len, const char *dll_name, struct ssl_func *sw)
  10812. {
  10813. union {
  10814. void *p;
  10815. void (*fp)(void);
  10816. } u;
  10817. void *dll_handle;
  10818. struct ssl_func *fp;
  10819. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  10820. mg_snprintf(NULL,
  10821. NULL, /* No truncation check for ebuf */
  10822. ebuf,
  10823. ebuf_len,
  10824. "%s: cannot load %s",
  10825. __func__,
  10826. dll_name);
  10827. return NULL;
  10828. }
  10829. for (fp = sw; fp->name != NULL; fp++) {
  10830. #ifdef _WIN32
  10831. /* GetProcAddress() returns pointer to function */
  10832. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  10833. #else
  10834. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  10835. * pointers to function pointers. We need to use a union to make a
  10836. * cast. */
  10837. u.p = dlsym(dll_handle, fp->name);
  10838. #endif /* _WIN32 */
  10839. if (u.fp == NULL) {
  10840. mg_snprintf(NULL,
  10841. NULL, /* No truncation check for ebuf */
  10842. ebuf,
  10843. ebuf_len,
  10844. "%s: %s: cannot find %s",
  10845. __func__,
  10846. dll_name,
  10847. fp->name);
  10848. dlclose(dll_handle);
  10849. return NULL;
  10850. } else {
  10851. fp->ptr = u.fp;
  10852. }
  10853. }
  10854. return dll_handle;
  10855. }
  10856. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  10857. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  10858. #endif /* NO_SSL_DL */
  10859. #if defined(SSL_ALREADY_INITIALIZED)
  10860. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  10861. #else
  10862. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  10863. #endif
  10864. static int
  10865. initialize_ssl(char *ebuf, size_t ebuf_len)
  10866. {
  10867. if (ebuf_len > 0) {
  10868. ebuf[0] = 0;
  10869. }
  10870. #ifdef OPENSSL_API_1_1
  10871. #if !defined(NO_SSL_DL)
  10872. if (!cryptolib_dll_handle) {
  10873. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  10874. if (!cryptolib_dll_handle) {
  10875. return 0;
  10876. }
  10877. }
  10878. #endif /* NO_SSL_DL */
  10879. if (mg_atomic_inc(&cryptolib_users) > 1) {
  10880. return 1;
  10881. }
  10882. #else
  10883. int i;
  10884. size_t size;
  10885. #if !defined(NO_SSL_DL)
  10886. if (!cryptolib_dll_handle) {
  10887. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  10888. if (!cryptolib_dll_handle) {
  10889. return 0;
  10890. }
  10891. }
  10892. #endif /* NO_SSL_DL */
  10893. if (mg_atomic_inc(&cryptolib_users) > 1) {
  10894. return 1;
  10895. }
  10896. /* Initialize locking callbacks, needed for thread safety.
  10897. * http://www.openssl.org/support/faq.html#PROG1
  10898. */
  10899. i = CRYPTO_num_locks();
  10900. if (i < 0) {
  10901. i = 0;
  10902. }
  10903. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  10904. if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  10905. mg_snprintf(NULL,
  10906. NULL, /* No truncation check for ebuf */
  10907. ebuf,
  10908. ebuf_len,
  10909. "%s: cannot allocate mutexes: %s",
  10910. __func__,
  10911. ssl_error());
  10912. return 0;
  10913. }
  10914. for (i = 0; i < CRYPTO_num_locks(); i++) {
  10915. pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr);
  10916. }
  10917. CRYPTO_set_locking_callback(&ssl_locking_callback);
  10918. CRYPTO_set_id_callback(&mg_current_thread_id);
  10919. #endif /* OPENSSL_API_1_1 */
  10920. return 1;
  10921. }
  10922. static int
  10923. ssl_use_pem_file(struct mg_context *ctx, const char *pem)
  10924. {
  10925. if (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0) {
  10926. mg_cry(fc(ctx),
  10927. "%s: cannot open certificate file %s: %s",
  10928. __func__,
  10929. pem,
  10930. ssl_error());
  10931. return 0;
  10932. }
  10933. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  10934. if (SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0) {
  10935. mg_cry(fc(ctx),
  10936. "%s: cannot open private key file %s: %s",
  10937. __func__,
  10938. pem,
  10939. ssl_error());
  10940. return 0;
  10941. }
  10942. if (SSL_CTX_check_private_key(ctx->ssl_ctx) == 0) {
  10943. mg_cry(fc(ctx),
  10944. "%s: certificate and private key do not match: %s",
  10945. __func__,
  10946. pem);
  10947. return 0;
  10948. }
  10949. if (SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem) == 0) {
  10950. mg_cry(fc(ctx),
  10951. "%s: cannot use certificate chain file %s: %s",
  10952. __func__,
  10953. pem,
  10954. ssl_error());
  10955. return 0;
  10956. }
  10957. return 1;
  10958. }
  10959. #ifdef OPENSSL_API_1_1
  10960. static unsigned long
  10961. ssl_get_protocol(int version_id)
  10962. {
  10963. long unsigned ret = SSL_OP_ALL;
  10964. if (version_id > 0)
  10965. ret |= SSL_OP_NO_SSLv2;
  10966. if (version_id > 1)
  10967. ret |= SSL_OP_NO_SSLv3;
  10968. if (version_id > 2)
  10969. ret |= SSL_OP_NO_TLSv1;
  10970. if (version_id > 3)
  10971. ret |= SSL_OP_NO_TLSv1_1;
  10972. return ret;
  10973. }
  10974. #else
  10975. static long
  10976. ssl_get_protocol(int version_id)
  10977. {
  10978. long ret = SSL_OP_ALL;
  10979. if (version_id > 0)
  10980. ret |= SSL_OP_NO_SSLv2;
  10981. if (version_id > 1)
  10982. ret |= SSL_OP_NO_SSLv3;
  10983. if (version_id > 2)
  10984. ret |= SSL_OP_NO_TLSv1;
  10985. if (version_id > 3)
  10986. ret |= SSL_OP_NO_TLSv1_1;
  10987. return ret;
  10988. }
  10989. #endif /* OPENSSL_API_1_1 */
  10990. /* Dynamically load SSL library. Set up ctx->ssl_ctx pointer. */
  10991. static int
  10992. set_ssl_option(struct mg_context *ctx)
  10993. {
  10994. const char *pem;
  10995. int callback_ret;
  10996. int should_verify_peer;
  10997. const char *ca_path;
  10998. const char *ca_file;
  10999. int use_default_verify_paths;
  11000. int verify_depth;
  11001. time_t now_rt = time(NULL);
  11002. struct timespec now_mt;
  11003. md5_byte_t ssl_context_id[16];
  11004. md5_state_t md5state;
  11005. int protocol_ver;
  11006. char ebuf[128];
  11007. /* If PEM file is not specified and the init_ssl callback
  11008. * is not specified, skip SSL initialization. */
  11009. if (!ctx) {
  11010. return 0;
  11011. }
  11012. if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL
  11013. && ctx->callbacks.init_ssl == NULL) {
  11014. return 1;
  11015. }
  11016. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  11017. mg_cry(fc(ctx), "%s", ebuf);
  11018. return 0;
  11019. }
  11020. #if !defined(NO_SSL_DL)
  11021. if (!ssllib_dll_handle) {
  11022. ssllib_dll_handle = load_dll(ebuf, sizeof(ebuf), SSL_LIB, ssl_sw);
  11023. if (!ssllib_dll_handle) {
  11024. mg_cry(fc(ctx), "%s", ebuf);
  11025. return 0;
  11026. }
  11027. }
  11028. #endif /* NO_SSL_DL */
  11029. #ifdef OPENSSL_API_1_1
  11030. /* Initialize SSL library */
  11031. OPENSSL_init_ssl(0, NULL);
  11032. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  11033. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  11034. NULL);
  11035. if ((ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  11036. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  11037. return 0;
  11038. }
  11039. #else
  11040. /* Initialize SSL library */
  11041. SSL_library_init();
  11042. SSL_load_error_strings();
  11043. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  11044. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  11045. return 0;
  11046. }
  11047. #endif /* OPENSSL_API_1_1 */
  11048. SSL_CTX_clear_options(ctx->ssl_ctx,
  11049. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  11050. | SSL_OP_NO_TLSv1_1);
  11051. protocol_ver = atoi(ctx->config[SSL_PROTOCOL_VERSION]);
  11052. SSL_CTX_set_options(ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  11053. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  11054. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  11055. #if !defined(NO_SSL_DL)
  11056. SSL_CTX_set_ecdh_auto(ctx->ssl_ctx, 1);
  11057. #endif /* NO_SSL_DL */
  11058. /* If a callback has been specified, call it. */
  11059. callback_ret =
  11060. (ctx->callbacks.init_ssl == NULL)
  11061. ? 0
  11062. : (ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data));
  11063. /* If callback returns 0, civetweb sets up the SSL certificate.
  11064. * If it returns 1, civetweb assumes the calback already did this.
  11065. * If it returns -1, initializing ssl fails. */
  11066. if (callback_ret < 0) {
  11067. mg_cry(fc(ctx), "SSL callback returned error: %i", callback_ret);
  11068. return 0;
  11069. }
  11070. if (callback_ret > 0) {
  11071. if (pem != NULL) {
  11072. (void)SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
  11073. }
  11074. return 1;
  11075. }
  11076. /* Use some UID as session context ID. */
  11077. md5_init(&md5state);
  11078. md5_append(&md5state, (const md5_byte_t *)&now_rt, sizeof(now_rt));
  11079. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  11080. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  11081. md5_append(&md5state,
  11082. (const md5_byte_t *)ctx->config[LISTENING_PORTS],
  11083. strlen(ctx->config[LISTENING_PORTS]));
  11084. md5_append(&md5state, (const md5_byte_t *)ctx, sizeof(*ctx));
  11085. md5_finish(&md5state, ssl_context_id);
  11086. SSL_CTX_set_session_id_context(ctx->ssl_ctx,
  11087. (const unsigned char *)&ssl_context_id,
  11088. sizeof(ssl_context_id));
  11089. if (pem != NULL) {
  11090. if (!ssl_use_pem_file(ctx, pem)) {
  11091. return 0;
  11092. }
  11093. }
  11094. should_verify_peer =
  11095. (ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  11096. && (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0);
  11097. use_default_verify_paths =
  11098. (ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  11099. && (mg_strcasecmp(ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes") == 0);
  11100. if (should_verify_peer) {
  11101. ca_path = ctx->config[SSL_CA_PATH];
  11102. ca_file = ctx->config[SSL_CA_FILE];
  11103. if (SSL_CTX_load_verify_locations(ctx->ssl_ctx, ca_file, ca_path)
  11104. != 1) {
  11105. mg_cry(fc(ctx),
  11106. "SSL_CTX_load_verify_locations error: %s "
  11107. "ssl_verify_peer requires setting "
  11108. "either ssl_ca_path or ssl_ca_file. Is any of them "
  11109. "present in "
  11110. "the .conf file?",
  11111. ssl_error());
  11112. return 0;
  11113. }
  11114. SSL_CTX_set_verify(ctx->ssl_ctx,
  11115. SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  11116. NULL);
  11117. if (use_default_verify_paths
  11118. && SSL_CTX_set_default_verify_paths(ctx->ssl_ctx) != 1) {
  11119. mg_cry(fc(ctx),
  11120. "SSL_CTX_set_default_verify_paths error: %s",
  11121. ssl_error());
  11122. return 0;
  11123. }
  11124. if (ctx->config[SSL_VERIFY_DEPTH]) {
  11125. verify_depth = atoi(ctx->config[SSL_VERIFY_DEPTH]);
  11126. SSL_CTX_set_verify_depth(ctx->ssl_ctx, verify_depth);
  11127. }
  11128. }
  11129. if (ctx->config[SSL_CIPHER_LIST] != NULL) {
  11130. if (SSL_CTX_set_cipher_list(ctx->ssl_ctx, ctx->config[SSL_CIPHER_LIST])
  11131. != 1) {
  11132. mg_cry(fc(ctx), "SSL_CTX_set_cipher_list error: %s", ssl_error());
  11133. }
  11134. }
  11135. return 1;
  11136. }
  11137. static void
  11138. uninitialize_ssl(void)
  11139. {
  11140. #ifdef OPENSSL_API_1_1
  11141. if (mg_atomic_dec(&cryptolib_users) == 0) {
  11142. /* Shutdown according to
  11143. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  11144. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  11145. */
  11146. CONF_modules_unload(1);
  11147. #else
  11148. int i;
  11149. if (mg_atomic_dec(&cryptolib_users) == 0) {
  11150. /* Shutdown according to
  11151. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  11152. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  11153. */
  11154. CRYPTO_set_locking_callback(NULL);
  11155. CRYPTO_set_id_callback(NULL);
  11156. ENGINE_cleanup();
  11157. CONF_modules_unload(1);
  11158. ERR_free_strings();
  11159. EVP_cleanup();
  11160. CRYPTO_cleanup_all_ex_data();
  11161. ERR_remove_state(0);
  11162. for (i = 0; i < CRYPTO_num_locks(); i++) {
  11163. pthread_mutex_destroy(&ssl_mutexes[i]);
  11164. }
  11165. mg_free(ssl_mutexes);
  11166. ssl_mutexes = NULL;
  11167. #endif /* OPENSSL_API_1_1 */
  11168. }
  11169. }
  11170. #endif /* !NO_SSL */
  11171. static int
  11172. set_gpass_option(struct mg_context *ctx)
  11173. {
  11174. if (ctx) {
  11175. struct mg_file file = STRUCT_FILE_INITIALIZER;
  11176. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  11177. if (path != NULL && !mg_stat(fc(ctx), path, &file.stat)) {
  11178. mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  11179. return 0;
  11180. }
  11181. return 1;
  11182. }
  11183. return 0;
  11184. }
  11185. static int
  11186. set_acl_option(struct mg_context *ctx)
  11187. {
  11188. return check_acl(ctx, (uint32_t)0x7f000001UL) != -1;
  11189. }
  11190. static void
  11191. reset_per_request_attributes(struct mg_connection *conn)
  11192. {
  11193. if (!conn) {
  11194. return;
  11195. }
  11196. conn->path_info = NULL;
  11197. conn->num_bytes_sent = conn->consumed_content = 0;
  11198. conn->status_code = -1;
  11199. conn->is_chunked = 0;
  11200. conn->must_close = conn->request_len = conn->throttle = 0;
  11201. conn->request_info.content_length = -1;
  11202. conn->request_info.remote_user = NULL;
  11203. conn->request_info.request_method = NULL;
  11204. conn->request_info.request_uri = NULL;
  11205. conn->request_info.local_uri = NULL;
  11206. #if defined(MG_LEGACY_INTERFACE)
  11207. conn->request_info.uri = NULL; /* TODO: cleanup uri,
  11208. * local_uri and request_uri */
  11209. #endif
  11210. conn->request_info.http_version = NULL;
  11211. conn->request_info.num_headers = 0;
  11212. conn->data_len = 0;
  11213. conn->chunk_remainder = 0;
  11214. }
  11215. #if 0
  11216. /* Note: set_sock_timeout is not required for non-blocking sockets.
  11217. * Leave this function here (commented out) for reference until
  11218. * CivetWeb 1.9 is tested, and the tests confirme this function is
  11219. * no longer required.
  11220. */
  11221. static int
  11222. set_sock_timeout(SOCKET sock, int milliseconds)
  11223. {
  11224. int r0 = 0, r1, r2;
  11225. #ifdef _WIN32
  11226. /* Windows specific */
  11227. DWORD tv = (DWORD)milliseconds;
  11228. #else
  11229. /* Linux, ... (not Windows) */
  11230. struct timeval tv;
  11231. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  11232. * max. time waiting for the acknowledged of TCP data before the connection
  11233. * will be forcefully closed and ETIMEDOUT is returned to the application.
  11234. * If this option is not set, the default timeout of 20-30 minutes is used.
  11235. */
  11236. /* #define TCP_USER_TIMEOUT (18) */
  11237. #if defined(TCP_USER_TIMEOUT)
  11238. unsigned int uto = (unsigned int)milliseconds;
  11239. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  11240. #endif
  11241. memset(&tv, 0, sizeof(tv));
  11242. tv.tv_sec = milliseconds / 1000;
  11243. tv.tv_usec = (milliseconds * 1000) % 1000000;
  11244. #endif /* _WIN32 */
  11245. r1 = setsockopt(
  11246. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  11247. r2 = setsockopt(
  11248. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  11249. return r0 || r1 || r2;
  11250. }
  11251. #endif
  11252. static int
  11253. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  11254. {
  11255. if (setsockopt(sock,
  11256. IPPROTO_TCP,
  11257. TCP_NODELAY,
  11258. (SOCK_OPT_TYPE)&nodelay_on,
  11259. sizeof(nodelay_on)) != 0) {
  11260. /* Error */
  11261. return 1;
  11262. }
  11263. /* OK */
  11264. return 0;
  11265. }
  11266. static void
  11267. close_socket_gracefully(struct mg_connection *conn)
  11268. {
  11269. #if defined(_WIN32)
  11270. char buf[MG_BUF_LEN];
  11271. int n;
  11272. #endif
  11273. struct linger linger;
  11274. int error_code = 0;
  11275. int linger_timeout = -2;
  11276. socklen_t opt_len = sizeof(error_code);
  11277. if (!conn) {
  11278. return;
  11279. }
  11280. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  11281. * "Note that enabling a nonzero timeout on a nonblocking socket
  11282. * is not recommended.", so set it to blocking now */
  11283. set_blocking_mode(conn->client.sock, 1);
  11284. /* Send FIN to the client */
  11285. shutdown(conn->client.sock, SHUTDOWN_WR);
  11286. #if defined(_WIN32)
  11287. /* Read and discard pending incoming data. If we do not do that and
  11288. * close
  11289. * the socket, the data in the send buffer may be discarded. This
  11290. * behaviour is seen on Windows, when client keeps sending data
  11291. * when server decides to close the connection; then when client
  11292. * does recv() it gets no data back. */
  11293. do {
  11294. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  11295. } while (n > 0);
  11296. #endif
  11297. if (conn->ctx->config[LINGER_TIMEOUT]) {
  11298. linger_timeout = atoi(conn->ctx->config[LINGER_TIMEOUT]);
  11299. }
  11300. /* Set linger option according to configuration */
  11301. if (linger_timeout >= 0) {
  11302. /* Set linger option to avoid socket hanging out after close. This
  11303. * prevent ephemeral port exhaust problem under high QPS. */
  11304. linger.l_onoff = 1;
  11305. #if defined(_MSC_VER)
  11306. #pragma warning(push)
  11307. #pragma warning(disable : 4244)
  11308. #endif
  11309. linger.l_linger = (linger_timeout + 999) / 1000;
  11310. #if defined(_MSC_VER)
  11311. #pragma warning(pop)
  11312. #endif
  11313. } else {
  11314. linger.l_onoff = 0;
  11315. linger.l_linger = 0;
  11316. }
  11317. if (linger_timeout < -1) {
  11318. /* Default: don't configure any linger */
  11319. } else if (getsockopt(conn->client.sock,
  11320. SOL_SOCKET,
  11321. SO_ERROR,
  11322. (char *)&error_code,
  11323. &opt_len) != 0) {
  11324. /* Cannot determine if socket is already closed. This should
  11325. * not occur and never did in a test. Log an error message
  11326. * and continue. */
  11327. mg_cry(conn,
  11328. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  11329. __func__,
  11330. strerror(ERRNO));
  11331. } else if (error_code == ECONNRESET) {
  11332. /* Socket already closed by client/peer, close socket without linger */
  11333. } else {
  11334. /* Set linger timeout */
  11335. if (setsockopt(conn->client.sock,
  11336. SOL_SOCKET,
  11337. SO_LINGER,
  11338. (char *)&linger,
  11339. sizeof(linger)) != 0) {
  11340. mg_cry(conn,
  11341. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  11342. __func__,
  11343. linger.l_onoff,
  11344. linger.l_linger,
  11345. strerror(ERRNO));
  11346. }
  11347. }
  11348. /* Now we know that our FIN is ACK-ed, safe to close */
  11349. closesocket(conn->client.sock);
  11350. conn->client.sock = INVALID_SOCKET;
  11351. }
  11352. static void
  11353. close_connection(struct mg_connection *conn)
  11354. {
  11355. if (!conn || !conn->ctx) {
  11356. return;
  11357. }
  11358. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  11359. if (conn->lua_websocket_state) {
  11360. lua_websocket_close(conn, conn->lua_websocket_state);
  11361. conn->lua_websocket_state = NULL;
  11362. }
  11363. #endif
  11364. /* call the connection_close callback if assigned */
  11365. if ((conn->ctx->callbacks.connection_close != NULL)
  11366. && (conn->ctx->context_type == 1)) {
  11367. conn->ctx->callbacks.connection_close(conn);
  11368. }
  11369. mg_lock_connection(conn);
  11370. conn->must_close = 1;
  11371. #ifndef NO_SSL
  11372. if (conn->ssl != NULL) {
  11373. /* Run SSL_shutdown twice to ensure completly close SSL connection
  11374. */
  11375. SSL_shutdown(conn->ssl);
  11376. SSL_free(conn->ssl);
  11377. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  11378. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  11379. #ifndef OPENSSL_API_1_1
  11380. ERR_remove_state(0);
  11381. #endif
  11382. conn->ssl = NULL;
  11383. }
  11384. #endif
  11385. if (conn->client.sock != INVALID_SOCKET) {
  11386. close_socket_gracefully(conn);
  11387. conn->client.sock = INVALID_SOCKET;
  11388. }
  11389. mg_unlock_connection(conn);
  11390. }
  11391. void
  11392. mg_close_connection(struct mg_connection *conn)
  11393. {
  11394. struct mg_context *client_ctx = NULL;
  11395. if (conn == NULL) {
  11396. return;
  11397. }
  11398. #if defined(USE_WEBSOCKET)
  11399. if (conn->ctx->context_type == 2) {
  11400. unsigned int i;
  11401. /* ws/wss client */
  11402. client_ctx = conn->ctx;
  11403. /* client context: loops must end */
  11404. conn->ctx->stop_flag = 1;
  11405. /* We need to get the client thread out of the select/recv call here. */
  11406. /* Since we use a sleep quantum of some seconds to check for recv
  11407. * timeouts, we will just wait a few seconds in mg_join_thread. */
  11408. /* join worker thread */
  11409. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  11410. if (client_ctx->worker_threadids[i] != 0) {
  11411. mg_join_thread(client_ctx->worker_threadids[i]);
  11412. }
  11413. }
  11414. }
  11415. #else
  11416. (void)client_ctx;
  11417. #endif
  11418. close_connection(conn);
  11419. #ifndef NO_SSL
  11420. if (conn->client_ssl_ctx != NULL) {
  11421. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  11422. }
  11423. #endif
  11424. if (client_ctx != NULL) {
  11425. /* free context */
  11426. mg_free(client_ctx->worker_threadids);
  11427. mg_free(client_ctx);
  11428. (void)pthread_mutex_destroy(&conn->mutex);
  11429. mg_free(conn);
  11430. }
  11431. }
  11432. static struct mg_connection *
  11433. mg_connect_client_impl(const struct mg_client_options *client_options,
  11434. int use_ssl,
  11435. char *ebuf,
  11436. size_t ebuf_len)
  11437. {
  11438. static struct mg_context fake_ctx;
  11439. struct mg_connection *conn = NULL;
  11440. SOCKET sock;
  11441. union usa sa;
  11442. if (!connect_socket(&fake_ctx,
  11443. client_options->host,
  11444. client_options->port,
  11445. use_ssl,
  11446. ebuf,
  11447. ebuf_len,
  11448. &sock,
  11449. &sa)) {
  11450. ;
  11451. } else if ((conn = (struct mg_connection *)
  11452. mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) {
  11453. mg_snprintf(NULL,
  11454. NULL, /* No truncation check for ebuf */
  11455. ebuf,
  11456. ebuf_len,
  11457. "calloc(): %s",
  11458. strerror(ERRNO));
  11459. closesocket(sock);
  11460. #ifndef NO_SSL
  11461. #ifdef OPENSSL_API_1_1
  11462. } else if (use_ssl
  11463. && (conn->client_ssl_ctx = SSL_CTX_new(TLS_client_method()))
  11464. == NULL) {
  11465. mg_snprintf(NULL,
  11466. NULL, /* No truncation check for ebuf */
  11467. ebuf,
  11468. ebuf_len,
  11469. "SSL_CTX_new error");
  11470. closesocket(sock);
  11471. mg_free(conn);
  11472. conn = NULL;
  11473. #else
  11474. } else if (use_ssl
  11475. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  11476. == NULL) {
  11477. mg_snprintf(NULL,
  11478. NULL, /* No truncation check for ebuf */
  11479. ebuf,
  11480. ebuf_len,
  11481. "SSL_CTX_new error");
  11482. closesocket(sock);
  11483. mg_free(conn);
  11484. conn = NULL;
  11485. #endif /* OPENSSL_API_1_1 */
  11486. #endif /* NO_SSL */
  11487. } else {
  11488. #ifdef USE_IPV6
  11489. socklen_t len = (sa.sa.sa_family == AF_INET)
  11490. ? sizeof(conn->client.rsa.sin)
  11491. : sizeof(conn->client.rsa.sin6);
  11492. struct sockaddr *psa =
  11493. (sa.sa.sa_family == AF_INET)
  11494. ? (struct sockaddr *)&(conn->client.rsa.sin)
  11495. : (struct sockaddr *)&(conn->client.rsa.sin6);
  11496. #else
  11497. socklen_t len = sizeof(conn->client.rsa.sin);
  11498. struct sockaddr *psa = (struct sockaddr *)&(conn->client.rsa.sin);
  11499. #endif
  11500. conn->buf_size = MAX_REQUEST_SIZE;
  11501. conn->buf = (char *)(conn + 1);
  11502. conn->ctx = &fake_ctx;
  11503. conn->client.sock = sock;
  11504. conn->client.lsa = sa;
  11505. if (getsockname(sock, psa, &len) != 0) {
  11506. mg_cry(conn,
  11507. "%s: getsockname() failed: %s",
  11508. __func__,
  11509. strerror(ERRNO));
  11510. }
  11511. conn->client.is_ssl = use_ssl ? 1 : 0;
  11512. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  11513. #ifndef NO_SSL
  11514. if (use_ssl) {
  11515. fake_ctx.ssl_ctx = conn->client_ssl_ctx;
  11516. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  11517. * SSL_CTX_set_verify call is needed to switch off server
  11518. * certificate checking, which is off by default in OpenSSL and
  11519. * on in yaSSL. */
  11520. /* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  11521. * SSL_VERIFY_PEER, verify_ssl_server); */
  11522. if (client_options->client_cert) {
  11523. if (!ssl_use_pem_file(&fake_ctx, client_options->client_cert)) {
  11524. mg_snprintf(NULL,
  11525. NULL, /* No truncation check for ebuf */
  11526. ebuf,
  11527. ebuf_len,
  11528. "Can not use SSL client certificate");
  11529. SSL_CTX_free(conn->client_ssl_ctx);
  11530. closesocket(sock);
  11531. mg_free(conn);
  11532. conn = NULL;
  11533. }
  11534. }
  11535. if (client_options->server_cert) {
  11536. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  11537. client_options->server_cert,
  11538. NULL);
  11539. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  11540. } else {
  11541. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  11542. }
  11543. if (!sslize(conn,
  11544. conn->client_ssl_ctx,
  11545. SSL_connect,
  11546. &(conn->ctx->stop_flag))) {
  11547. mg_snprintf(NULL,
  11548. NULL, /* No truncation check for ebuf */
  11549. ebuf,
  11550. ebuf_len,
  11551. "SSL connection error");
  11552. SSL_CTX_free(conn->client_ssl_ctx);
  11553. closesocket(sock);
  11554. mg_free(conn);
  11555. conn = NULL;
  11556. }
  11557. }
  11558. #endif
  11559. }
  11560. if (conn) {
  11561. set_blocking_mode(sock, 0);
  11562. }
  11563. return conn;
  11564. }
  11565. CIVETWEB_API struct mg_connection *
  11566. mg_connect_client_secure(const struct mg_client_options *client_options,
  11567. char *error_buffer,
  11568. size_t error_buffer_size)
  11569. {
  11570. return mg_connect_client_impl(client_options,
  11571. 1,
  11572. error_buffer,
  11573. error_buffer_size);
  11574. }
  11575. struct mg_connection *
  11576. mg_connect_client(const char *host,
  11577. int port,
  11578. int use_ssl,
  11579. char *error_buffer,
  11580. size_t error_buffer_size)
  11581. {
  11582. struct mg_client_options opts;
  11583. memset(&opts, 0, sizeof(opts));
  11584. opts.host = host;
  11585. opts.port = port;
  11586. return mg_connect_client_impl(&opts,
  11587. use_ssl,
  11588. error_buffer,
  11589. error_buffer_size);
  11590. }
  11591. static const struct {
  11592. const char *proto;
  11593. size_t proto_len;
  11594. unsigned default_port;
  11595. } abs_uri_protocols[] = {{"http://", 7, 80},
  11596. {"https://", 8, 443},
  11597. {"ws://", 5, 80},
  11598. {"wss://", 6, 443},
  11599. {NULL, 0, 0}};
  11600. /* Check if the uri is valid.
  11601. * return 0 for invalid uri,
  11602. * return 1 for *,
  11603. * return 2 for relative uri,
  11604. * return 3 for absolute uri without port,
  11605. * return 4 for absolute uri with port */
  11606. static int
  11607. get_uri_type(const char *uri)
  11608. {
  11609. int i;
  11610. const char *hostend, *portbegin;
  11611. char *portend;
  11612. unsigned long port;
  11613. /* According to the HTTP standard
  11614. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  11615. * URI can be an asterisk (*) or should start with slash (relative uri),
  11616. * or it should start with the protocol (absolute uri). */
  11617. if (uri[0] == '*' && uri[1] == '\0') {
  11618. /* asterisk */
  11619. return 1;
  11620. }
  11621. /* Valid URIs according to RFC 3986
  11622. * (https://www.ietf.org/rfc/rfc3986.txt)
  11623. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  11624. * and unreserved characters A-Z a-z 0-9 and -._~
  11625. * and % encoded symbols.
  11626. */
  11627. for (i = 0; uri[i] != 0; i++) {
  11628. if (uri[i] < 33) {
  11629. /* control characters and spaces are invalid */
  11630. return 0;
  11631. }
  11632. if (uri[i] > 126) {
  11633. /* non-ascii characters must be % encoded */
  11634. return 0;
  11635. } else {
  11636. switch (uri[i]) {
  11637. case '"': /* 34 */
  11638. case '<': /* 60 */
  11639. case '>': /* 62 */
  11640. case '\\': /* 92 */
  11641. case '^': /* 94 */
  11642. case '`': /* 96 */
  11643. case '{': /* 123 */
  11644. case '|': /* 124 */
  11645. case '}': /* 125 */
  11646. return 0;
  11647. default:
  11648. /* character is ok */
  11649. break;
  11650. }
  11651. }
  11652. }
  11653. /* A relative uri starts with a / character */
  11654. if (uri[0] == '/') {
  11655. /* relative uri */
  11656. return 2;
  11657. }
  11658. /* It could be an absolute uri: */
  11659. /* This function only checks if the uri is valid, not if it is
  11660. * addressing the current server. So civetweb can also be used
  11661. * as a proxy server. */
  11662. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  11663. if (mg_strncasecmp(uri,
  11664. abs_uri_protocols[i].proto,
  11665. abs_uri_protocols[i].proto_len) == 0) {
  11666. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  11667. if (!hostend) {
  11668. return 0;
  11669. }
  11670. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  11671. if (!portbegin) {
  11672. return 3;
  11673. }
  11674. port = strtoul(portbegin + 1, &portend, 10);
  11675. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  11676. return 0;
  11677. }
  11678. return 4;
  11679. }
  11680. }
  11681. return 0;
  11682. }
  11683. /* Return NULL or the relative uri at the current server */
  11684. static const char *
  11685. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  11686. {
  11687. const char *server_domain;
  11688. size_t server_domain_len;
  11689. size_t request_domain_len = 0;
  11690. unsigned long port = 0;
  11691. int i, auth_domain_check_enabled;
  11692. const char *hostbegin = NULL;
  11693. const char *hostend = NULL;
  11694. const char *portbegin;
  11695. char *portend;
  11696. auth_domain_check_enabled =
  11697. !strcmp(conn->ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  11698. if (!auth_domain_check_enabled) {
  11699. return 0;
  11700. }
  11701. server_domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  11702. if (!server_domain) {
  11703. return 0;
  11704. }
  11705. server_domain_len = strlen(server_domain);
  11706. if (!server_domain_len) {
  11707. return 0;
  11708. }
  11709. /* DNS is case insensitive, so use case insensitive string compare here
  11710. */
  11711. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  11712. if (mg_strncasecmp(uri,
  11713. abs_uri_protocols[i].proto,
  11714. abs_uri_protocols[i].proto_len) == 0) {
  11715. hostbegin = uri + abs_uri_protocols[i].proto_len;
  11716. hostend = strchr(hostbegin, '/');
  11717. if (!hostend) {
  11718. return 0;
  11719. }
  11720. portbegin = strchr(hostbegin, ':');
  11721. if ((!portbegin) || (portbegin > hostend)) {
  11722. port = abs_uri_protocols[i].default_port;
  11723. request_domain_len = (size_t)(hostend - hostbegin);
  11724. } else {
  11725. port = strtoul(portbegin + 1, &portend, 10);
  11726. if ((portend != hostend) || (port <= 0)
  11727. || !is_valid_port(port)) {
  11728. return 0;
  11729. }
  11730. request_domain_len = (size_t)(portbegin - hostbegin);
  11731. }
  11732. /* protocol found, port set */
  11733. break;
  11734. }
  11735. }
  11736. if (!port) {
  11737. /* port remains 0 if the protocol is not found */
  11738. return 0;
  11739. }
  11740. /* Check if the request is directed to a different server. */
  11741. /* First check if the port is the same (IPv4 and IPv6). */
  11742. #if defined(USE_IPV6)
  11743. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  11744. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  11745. /* Request is directed to a different port */
  11746. return 0;
  11747. }
  11748. } else
  11749. #endif
  11750. {
  11751. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  11752. /* Request is directed to a different port */
  11753. return 0;
  11754. }
  11755. }
  11756. /* Finally check if the server corresponds to the authentication
  11757. * domain of the server (the server domain).
  11758. * Allow full matches (like http://mydomain.com/path/file.ext), and
  11759. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  11760. * but do not allow substrings (like http://notmydomain.com/path/file.ext
  11761. * or http://mydomain.com.fake/path/file.ext).
  11762. */
  11763. if (auth_domain_check_enabled) {
  11764. if ((request_domain_len == server_domain_len)
  11765. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  11766. /* Request is directed to this server - full name match. */
  11767. } else {
  11768. if (request_domain_len < (server_domain_len + 2)) {
  11769. /* Request is directed to another server: The server name is
  11770. * longer
  11771. * than
  11772. * the request name. Drop this case here to avoid overflows in
  11773. * the
  11774. * following checks. */
  11775. return 0;
  11776. }
  11777. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  11778. /* Request is directed to another server: It could be a
  11779. * substring
  11780. * like notmyserver.com */
  11781. return 0;
  11782. }
  11783. if (0 != memcmp(server_domain,
  11784. hostbegin + request_domain_len - server_domain_len,
  11785. server_domain_len)) {
  11786. /* Request is directed to another server:
  11787. * The server name is different. */
  11788. return 0;
  11789. }
  11790. }
  11791. }
  11792. return hostend;
  11793. }
  11794. static int
  11795. getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  11796. {
  11797. const char *cl;
  11798. if (ebuf_len > 0) {
  11799. ebuf[0] = '\0';
  11800. }
  11801. *err = 0;
  11802. reset_per_request_attributes(conn);
  11803. if (!conn) {
  11804. mg_snprintf(conn,
  11805. NULL, /* No truncation check for ebuf */
  11806. ebuf,
  11807. ebuf_len,
  11808. "%s",
  11809. "Internal error");
  11810. *err = 500;
  11811. return 0;
  11812. }
  11813. /* Set the time the request was received. This value should be used for
  11814. * timeouts. */
  11815. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  11816. conn->request_len =
  11817. read_request(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  11818. /* assert(conn->request_len < 0 || conn->data_len >= conn->request_len);
  11819. */
  11820. if (conn->request_len >= 0 && conn->data_len < conn->request_len) {
  11821. mg_snprintf(conn,
  11822. NULL, /* No truncation check for ebuf */
  11823. ebuf,
  11824. ebuf_len,
  11825. "%s",
  11826. "Invalid request size");
  11827. *err = 500;
  11828. return 0;
  11829. }
  11830. if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
  11831. mg_snprintf(conn,
  11832. NULL, /* No truncation check for ebuf */
  11833. ebuf,
  11834. ebuf_len,
  11835. "%s",
  11836. "Request Too Large");
  11837. *err = 413;
  11838. return 0;
  11839. } else if (conn->request_len <= 0) {
  11840. if (conn->data_len > 0) {
  11841. mg_snprintf(conn,
  11842. NULL, /* No truncation check for ebuf */
  11843. ebuf,
  11844. ebuf_len,
  11845. "%s",
  11846. "Client sent malformed request");
  11847. *err = 400;
  11848. } else {
  11849. /* Server did not recv anything -> just close the connection */
  11850. conn->must_close = 1;
  11851. mg_snprintf(conn,
  11852. NULL, /* No truncation check for ebuf */
  11853. ebuf,
  11854. ebuf_len,
  11855. "%s",
  11856. "Client did not send a request");
  11857. *err = 0;
  11858. }
  11859. return 0;
  11860. } else if (parse_http_message(conn->buf,
  11861. conn->buf_size,
  11862. &conn->request_info) <= 0) {
  11863. mg_snprintf(conn,
  11864. NULL, /* No truncation check for ebuf */
  11865. ebuf,
  11866. ebuf_len,
  11867. "%s",
  11868. "Bad Request");
  11869. *err = 400;
  11870. return 0;
  11871. } else {
  11872. /* Message is a valid request or response */
  11873. if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) {
  11874. /* Request/response has content length set */
  11875. char *endptr = NULL;
  11876. conn->content_len = strtoll(cl, &endptr, 10);
  11877. if (endptr == cl) {
  11878. mg_snprintf(conn,
  11879. NULL, /* No truncation check for ebuf */
  11880. ebuf,
  11881. ebuf_len,
  11882. "%s",
  11883. "Bad Request");
  11884. *err = 411;
  11885. return 0;
  11886. }
  11887. /* Publish the content length back to the request info. */
  11888. conn->request_info.content_length = conn->content_len;
  11889. } else if ((cl = get_header(&conn->request_info, "Transfer-Encoding"))
  11890. != NULL
  11891. && !mg_strcasecmp(cl, "chunked")) {
  11892. conn->is_chunked = 1;
  11893. } else if (!mg_strcasecmp(conn->request_info.request_method, "POST")
  11894. || !mg_strcasecmp(conn->request_info.request_method,
  11895. "PUT")) {
  11896. /* POST or PUT request without content length set */
  11897. conn->content_len = -1;
  11898. } else if (!mg_strncasecmp(conn->request_info.request_method,
  11899. "HTTP/",
  11900. 5)) {
  11901. /* Response without content length set */
  11902. conn->content_len = -1;
  11903. } else {
  11904. /* Other request */
  11905. conn->content_len = 0;
  11906. }
  11907. }
  11908. return 1;
  11909. }
  11910. int
  11911. mg_get_response(struct mg_connection *conn,
  11912. char *ebuf,
  11913. size_t ebuf_len,
  11914. int timeout)
  11915. {
  11916. if (conn) {
  11917. /* Implementation of API function for HTTP clients */
  11918. int err, ret;
  11919. struct mg_context *octx = conn->ctx;
  11920. struct mg_context rctx = *(conn->ctx);
  11921. char txt[32]; /* will not overflow */
  11922. if (timeout >= 0) {
  11923. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  11924. rctx.config[REQUEST_TIMEOUT] = txt;
  11925. /* Not required for non-blocking sockets.
  11926. set_sock_timeout(conn->client.sock, timeout);
  11927. */
  11928. } else {
  11929. rctx.config[REQUEST_TIMEOUT] = NULL;
  11930. }
  11931. conn->ctx = &rctx;
  11932. ret = getreq(conn, ebuf, ebuf_len, &err);
  11933. conn->ctx = octx;
  11934. #if defined(MG_LEGACY_INTERFACE)
  11935. /* TODO: 1) uri is deprecated;
  11936. * 2) here, ri.uri is the http response code */
  11937. conn->request_info.uri = conn->request_info.request_uri;
  11938. #endif
  11939. conn->request_info.local_uri = conn->request_info.request_uri;
  11940. /* TODO (mid): Define proper return values - maybe return length?
  11941. * For the first test use <0 for error and >0 for OK */
  11942. return (ret == 0) ? -1 : +1;
  11943. }
  11944. return -1;
  11945. }
  11946. struct mg_connection *
  11947. mg_download(const char *host,
  11948. int port,
  11949. int use_ssl,
  11950. char *ebuf,
  11951. size_t ebuf_len,
  11952. const char *fmt,
  11953. ...)
  11954. {
  11955. struct mg_connection *conn;
  11956. va_list ap;
  11957. int i;
  11958. int reqerr;
  11959. va_start(ap, fmt);
  11960. ebuf[0] = '\0';
  11961. /* open a connection */
  11962. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  11963. if (conn != NULL) {
  11964. i = mg_vprintf(conn, fmt, ap);
  11965. if (i <= 0) {
  11966. mg_snprintf(conn,
  11967. NULL, /* No truncation check for ebuf */
  11968. ebuf,
  11969. ebuf_len,
  11970. "%s",
  11971. "Error sending request");
  11972. } else {
  11973. getreq(conn, ebuf, ebuf_len, &reqerr);
  11974. #if defined(MG_LEGACY_INTERFACE)
  11975. /* TODO: 1) uri is deprecated;
  11976. * 2) here, ri.uri is the http response code */
  11977. conn->request_info.uri = conn->request_info.request_uri;
  11978. #endif
  11979. conn->request_info.local_uri = conn->request_info.request_uri;
  11980. }
  11981. }
  11982. /* if an error occured, close the connection */
  11983. if (ebuf[0] != '\0' && conn != NULL) {
  11984. mg_close_connection(conn);
  11985. conn = NULL;
  11986. }
  11987. va_end(ap);
  11988. return conn;
  11989. }
  11990. struct websocket_client_thread_data {
  11991. struct mg_connection *conn;
  11992. mg_websocket_data_handler data_handler;
  11993. mg_websocket_close_handler close_handler;
  11994. void *callback_data;
  11995. };
  11996. #if defined(USE_WEBSOCKET)
  11997. #ifdef _WIN32
  11998. static unsigned __stdcall websocket_client_thread(void *data)
  11999. #else
  12000. static void *
  12001. websocket_client_thread(void *data)
  12002. #endif
  12003. {
  12004. struct websocket_client_thread_data *cdata =
  12005. (struct websocket_client_thread_data *)data;
  12006. mg_set_thread_name("ws-clnt");
  12007. if (cdata->conn->ctx) {
  12008. if (cdata->conn->ctx->callbacks.init_thread) {
  12009. /* 3 indicates a websocket client thread */
  12010. /* TODO: check if conn->ctx can be set */
  12011. cdata->conn->ctx->callbacks.init_thread(cdata->conn->ctx, 3);
  12012. }
  12013. }
  12014. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  12015. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  12016. if (cdata->close_handler != NULL) {
  12017. cdata->close_handler(cdata->conn, cdata->callback_data);
  12018. }
  12019. /* The websocket_client context has only this thread. If it runs out,
  12020. set the stop_flag to 2 (= "stopped"). */
  12021. cdata->conn->ctx->stop_flag = 2;
  12022. mg_free((void *)cdata);
  12023. #ifdef _WIN32
  12024. return 0;
  12025. #else
  12026. return NULL;
  12027. #endif
  12028. }
  12029. #endif
  12030. struct mg_connection *
  12031. mg_connect_websocket_client(const char *host,
  12032. int port,
  12033. int use_ssl,
  12034. char *error_buffer,
  12035. size_t error_buffer_size,
  12036. const char *path,
  12037. const char *origin,
  12038. mg_websocket_data_handler data_func,
  12039. mg_websocket_close_handler close_func,
  12040. void *user_data)
  12041. {
  12042. struct mg_connection *conn = NULL;
  12043. #if defined(USE_WEBSOCKET)
  12044. struct mg_context *newctx = NULL;
  12045. struct websocket_client_thread_data *thread_data;
  12046. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  12047. static const char *handshake_req;
  12048. if (origin != NULL) {
  12049. handshake_req = "GET %s HTTP/1.1\r\n"
  12050. "Host: %s\r\n"
  12051. "Upgrade: websocket\r\n"
  12052. "Connection: Upgrade\r\n"
  12053. "Sec-WebSocket-Key: %s\r\n"
  12054. "Sec-WebSocket-Version: 13\r\n"
  12055. "Origin: %s\r\n"
  12056. "\r\n";
  12057. } else {
  12058. handshake_req = "GET %s HTTP/1.1\r\n"
  12059. "Host: %s\r\n"
  12060. "Upgrade: websocket\r\n"
  12061. "Connection: Upgrade\r\n"
  12062. "Sec-WebSocket-Key: %s\r\n"
  12063. "Sec-WebSocket-Version: 13\r\n"
  12064. "\r\n";
  12065. }
  12066. /* Establish the client connection and request upgrade */
  12067. conn = mg_download(host,
  12068. port,
  12069. use_ssl,
  12070. error_buffer,
  12071. error_buffer_size,
  12072. handshake_req,
  12073. path,
  12074. host,
  12075. magic,
  12076. origin);
  12077. /* Connection object will be null if something goes wrong */
  12078. if (conn == NULL || (strcmp(conn->request_info.request_uri, "101") != 0)) {
  12079. if (!*error_buffer) {
  12080. /* if there is a connection, but it did not return 101,
  12081. * error_buffer is not yet set */
  12082. mg_snprintf(conn,
  12083. NULL, /* No truncation check for ebuf */
  12084. error_buffer,
  12085. error_buffer_size,
  12086. "Unexpected server reply");
  12087. }
  12088. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  12089. if (conn != NULL) {
  12090. mg_free(conn);
  12091. conn = NULL;
  12092. }
  12093. return conn;
  12094. }
  12095. /* For client connections, mg_context is fake. Since we need to set a
  12096. * callback function, we need to create a copy and modify it. */
  12097. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  12098. memcpy(newctx, conn->ctx, sizeof(struct mg_context));
  12099. newctx->user_data = user_data;
  12100. newctx->context_type = 2; /* ws/wss client context type */
  12101. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  12102. newctx->worker_threadids =
  12103. (pthread_t *)mg_calloc(newctx->cfg_worker_threads, sizeof(pthread_t));
  12104. conn->ctx = newctx;
  12105. thread_data = (struct websocket_client_thread_data *)
  12106. mg_calloc(sizeof(struct websocket_client_thread_data), 1);
  12107. thread_data->conn = conn;
  12108. thread_data->data_handler = data_func;
  12109. thread_data->close_handler = close_func;
  12110. thread_data->callback_data = user_data;
  12111. /* Start a thread to read the websocket client connection
  12112. * This thread will automatically stop when mg_disconnect is
  12113. * called on the client connection */
  12114. if (mg_start_thread_with_id(websocket_client_thread,
  12115. (void *)thread_data,
  12116. newctx->worker_threadids) != 0) {
  12117. mg_free((void *)thread_data);
  12118. mg_free((void *)newctx->worker_threadids);
  12119. mg_free((void *)newctx);
  12120. mg_free((void *)conn);
  12121. conn = NULL;
  12122. DEBUG_TRACE("%s",
  12123. "Websocket client connect thread could not be started\r\n");
  12124. }
  12125. #else
  12126. /* Appease "unused parameter" warnings */
  12127. (void)host;
  12128. (void)port;
  12129. (void)use_ssl;
  12130. (void)error_buffer;
  12131. (void)error_buffer_size;
  12132. (void)path;
  12133. (void)origin;
  12134. (void)user_data;
  12135. (void)data_func;
  12136. (void)close_func;
  12137. #endif
  12138. return conn;
  12139. }
  12140. static void
  12141. process_new_connection(struct mg_connection *conn)
  12142. {
  12143. if (conn && conn->ctx) {
  12144. struct mg_request_info *ri = &conn->request_info;
  12145. int keep_alive_enabled, keep_alive, discard_len;
  12146. char ebuf[100];
  12147. const char *hostend;
  12148. int reqerr, uri_type;
  12149. keep_alive_enabled =
  12150. !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  12151. /* Important: on new connection, reset the receiving buffer. Credit
  12152. * goes to crule42. */
  12153. conn->data_len = 0;
  12154. conn->handled_requests = 0;
  12155. do {
  12156. DEBUG_TRACE("calling getreq (%i times for this connection)",
  12157. conn->handled_requests + 1);
  12158. if (!getreq(conn, ebuf, sizeof(ebuf), &reqerr)) {
  12159. /* The request sent by the client could not be understood by
  12160. * the server, or it was incomplete or a timeout. Send an
  12161. * error message and close the connection. */
  12162. if (reqerr > 0) {
  12163. /*assert(ebuf[0] != '\0');*/
  12164. send_http_error(conn, reqerr, "%s", ebuf);
  12165. }
  12166. } else if (strcmp(ri->http_version, "1.0")
  12167. && strcmp(ri->http_version, "1.1")) {
  12168. mg_snprintf(conn,
  12169. NULL, /* No truncation check for ebuf */
  12170. ebuf,
  12171. sizeof(ebuf),
  12172. "Bad HTTP version: [%s]",
  12173. ri->http_version);
  12174. send_http_error(conn, 505, "%s", ebuf);
  12175. }
  12176. if (ebuf[0] == '\0') {
  12177. uri_type = get_uri_type(conn->request_info.request_uri);
  12178. switch (uri_type) {
  12179. case 1:
  12180. /* Asterisk */
  12181. conn->request_info.local_uri = NULL;
  12182. break;
  12183. case 2:
  12184. /* relative uri */
  12185. conn->request_info.local_uri =
  12186. conn->request_info.request_uri;
  12187. break;
  12188. case 3:
  12189. case 4:
  12190. /* absolute uri (with/without port) */
  12191. hostend = get_rel_url_at_current_server(
  12192. conn->request_info.request_uri, conn);
  12193. if (hostend) {
  12194. conn->request_info.local_uri = hostend;
  12195. } else {
  12196. conn->request_info.local_uri = NULL;
  12197. }
  12198. break;
  12199. default:
  12200. mg_snprintf(conn,
  12201. NULL, /* No truncation check for ebuf */
  12202. ebuf,
  12203. sizeof(ebuf),
  12204. "Invalid URI");
  12205. send_http_error(conn, 400, "%s", ebuf);
  12206. conn->request_info.local_uri = NULL;
  12207. break;
  12208. }
  12209. #if defined(MG_LEGACY_INTERFACE)
  12210. /* TODO: cleanup uri, local_uri and request_uri */
  12211. conn->request_info.uri = conn->request_info.local_uri;
  12212. #endif
  12213. }
  12214. DEBUG_TRACE("http: %s, error: %s",
  12215. (ri->http_version ? ri->http_version : "none"),
  12216. (ebuf[0] ? ebuf : "none"));
  12217. if (ebuf[0] == '\0') {
  12218. if (conn->request_info.local_uri) {
  12219. /* handle request to local server */
  12220. handle_request(conn);
  12221. DEBUG_TRACE("%s", "handle_request done");
  12222. if (conn->ctx->callbacks.end_request != NULL) {
  12223. conn->ctx->callbacks.end_request(conn,
  12224. conn->status_code);
  12225. DEBUG_TRACE("%s", "end_request callback done");
  12226. }
  12227. log_access(conn);
  12228. } else {
  12229. /* TODO: handle non-local request (PROXY) */
  12230. conn->must_close = 1;
  12231. }
  12232. } else {
  12233. conn->must_close = 1;
  12234. }
  12235. if (ri->remote_user != NULL) {
  12236. mg_free((void *)ri->remote_user);
  12237. /* Important! When having connections with and without auth
  12238. * would cause double free and then crash */
  12239. ri->remote_user = NULL;
  12240. }
  12241. /* NOTE(lsm): order is important here. should_keep_alive() call
  12242. * is
  12243. * using parsed request, which will be invalid after memmove's
  12244. * below.
  12245. * Therefore, memorize should_keep_alive() result now for later
  12246. * use
  12247. * in loop exit condition. */
  12248. keep_alive = (conn->ctx->stop_flag == 0) && keep_alive_enabled
  12249. && (conn->content_len >= 0) && should_keep_alive(conn);
  12250. /* Discard all buffered data for this request */
  12251. discard_len = ((conn->content_len >= 0) && (conn->request_len > 0)
  12252. && ((conn->request_len + conn->content_len)
  12253. < (int64_t)conn->data_len))
  12254. ? (int)(conn->request_len + conn->content_len)
  12255. : conn->data_len;
  12256. /*assert(discard_len >= 0);*/
  12257. if (discard_len < 0) {
  12258. DEBUG_TRACE("internal error: discard_len = %li",
  12259. (long int)discard_len);
  12260. break;
  12261. }
  12262. conn->data_len -= discard_len;
  12263. if (conn->data_len > 0) {
  12264. DEBUG_TRACE("discard_len = %lu", (long unsigned)discard_len);
  12265. memmove(conn->buf,
  12266. conn->buf + discard_len,
  12267. (size_t)conn->data_len);
  12268. }
  12269. /* assert(conn->data_len >= 0); */
  12270. /* assert(conn->data_len <= conn->buf_size); */
  12271. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  12272. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  12273. (long int)conn->data_len,
  12274. (long int)conn->buf_size);
  12275. break;
  12276. }
  12277. conn->handled_requests++;
  12278. } while (keep_alive);
  12279. }
  12280. }
  12281. #if defined(ALTERNATIVE_QUEUE)
  12282. static void
  12283. produce_socket(struct mg_context *ctx, const struct socket *sp)
  12284. {
  12285. unsigned int i;
  12286. for (;;) {
  12287. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  12288. /* find a free worker slot and signal it */
  12289. if (ctx->client_socks[i].in_use == 0) {
  12290. ctx->client_socks[i] = *sp;
  12291. ctx->client_socks[i].in_use = 1;
  12292. event_signal(ctx->client_wait_events[i]);
  12293. return;
  12294. }
  12295. }
  12296. /* queue is full */
  12297. mg_sleep(1);
  12298. }
  12299. }
  12300. static int
  12301. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  12302. {
  12303. DEBUG_TRACE("%s", "going idle");
  12304. ctx->client_socks[thread_index].in_use = 0;
  12305. event_wait(ctx->client_wait_events[thread_index]);
  12306. *sp = ctx->client_socks[thread_index];
  12307. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  12308. return !ctx->stop_flag;
  12309. }
  12310. #else /* ALTERNATIVE_QUEUE */
  12311. /* Worker threads take accepted socket from the queue */
  12312. static int
  12313. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  12314. {
  12315. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  12316. (void)thread_index;
  12317. (void)pthread_mutex_lock(&ctx->thread_mutex);
  12318. DEBUG_TRACE("%s", "going idle");
  12319. /* If the queue is empty, wait. We're idle at this point. */
  12320. while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
  12321. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  12322. }
  12323. /* If we're stopping, sq_head may be equal to sq_tail. */
  12324. if (ctx->sq_head > ctx->sq_tail) {
  12325. /* Copy socket from the queue and increment tail */
  12326. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  12327. ctx->sq_tail++;
  12328. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  12329. /* Wrap pointers if needed */
  12330. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  12331. ctx->sq_tail -= QUEUE_SIZE(ctx);
  12332. ctx->sq_head -= QUEUE_SIZE(ctx);
  12333. }
  12334. }
  12335. (void)pthread_cond_signal(&ctx->sq_empty);
  12336. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  12337. return !ctx->stop_flag;
  12338. #undef QUEUE_SIZE
  12339. }
  12340. /* Master thread adds accepted socket to a queue */
  12341. static void
  12342. produce_socket(struct mg_context *ctx, const struct socket *sp)
  12343. {
  12344. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  12345. if (!ctx) {
  12346. return;
  12347. }
  12348. (void)pthread_mutex_lock(&ctx->thread_mutex);
  12349. /* If the queue is full, wait */
  12350. while (ctx->stop_flag == 0
  12351. && ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx)) {
  12352. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  12353. }
  12354. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  12355. /* Copy socket to the queue and increment head */
  12356. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  12357. ctx->sq_head++;
  12358. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  12359. }
  12360. (void)pthread_cond_signal(&ctx->sq_full);
  12361. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  12362. #undef QUEUE_SIZE
  12363. }
  12364. #endif /* ALTERNATIVE_QUEUE */
  12365. struct worker_thread_args {
  12366. struct mg_context *ctx;
  12367. int index;
  12368. };
  12369. static void *
  12370. worker_thread_run(struct worker_thread_args *thread_args)
  12371. {
  12372. struct mg_context *ctx = thread_args->ctx;
  12373. struct mg_connection *conn;
  12374. struct mg_workerTLS tls;
  12375. #if defined(MG_LEGACY_INTERFACE)
  12376. uint32_t addr;
  12377. #endif
  12378. mg_set_thread_name("worker");
  12379. tls.is_master = 0;
  12380. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  12381. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12382. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  12383. #endif
  12384. /* Initialize thread local storage before calling any callback */
  12385. pthread_setspecific(sTlsKey, &tls);
  12386. if (ctx->callbacks.init_thread) {
  12387. /* call init_thread for a worker thread (type 1) */
  12388. ctx->callbacks.init_thread(ctx, 1);
  12389. }
  12390. /* Connection structure has been pre-allocated */
  12391. if (((int)thread_args->index < 0)
  12392. || ((unsigned)thread_args->index
  12393. >= (unsigned)ctx->cfg_worker_threads)) {
  12394. mg_cry(fc(ctx),
  12395. "Internal error: Invalid worker index %i",
  12396. (int)thread_args->index);
  12397. return NULL;
  12398. }
  12399. conn = ctx->worker_connections + thread_args->index;
  12400. /* Request buffers are not pre-allocated. They are private to the
  12401. * request and do not contain any state information that might be
  12402. * of interest to anyone observing a server status. */
  12403. conn->buf = (char *)mg_malloc(MAX_REQUEST_SIZE);
  12404. if (conn->buf == NULL) {
  12405. mg_cry(fc(ctx),
  12406. "Out of memory: Cannot allocate buffer for worker %i",
  12407. (int)thread_args->index);
  12408. return NULL;
  12409. }
  12410. conn->buf_size = MAX_REQUEST_SIZE;
  12411. conn->ctx = ctx;
  12412. conn->thread_index = thread_args->index;
  12413. conn->request_info.user_data = ctx->user_data;
  12414. /* Allocate a mutex for this connection to allow communication both
  12415. * within the request handler and from elsewhere in the application
  12416. */
  12417. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  12418. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  12419. * signal sq_empty condvar to wake up the master waiting in
  12420. * produce_socket() */
  12421. while (consume_socket(ctx, &conn->client, conn->thread_index)) {
  12422. conn->conn_birth_time = time(NULL);
  12423. /* Fill in IP, port info early so even if SSL setup below fails,
  12424. * error handler would have the corresponding info.
  12425. * Thanks to Johannes Winkelmann for the patch.
  12426. */
  12427. #if defined(USE_IPV6)
  12428. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  12429. conn->request_info.remote_port =
  12430. ntohs(conn->client.rsa.sin6.sin6_port);
  12431. } else
  12432. #endif
  12433. {
  12434. conn->request_info.remote_port =
  12435. ntohs(conn->client.rsa.sin.sin_port);
  12436. }
  12437. sockaddr_to_string(conn->request_info.remote_addr,
  12438. sizeof(conn->request_info.remote_addr),
  12439. &conn->client.rsa);
  12440. DEBUG_TRACE("Start processing connection from %s",
  12441. conn->request_info.remote_addr);
  12442. #if defined(MG_LEGACY_INTERFACE)
  12443. /* This legacy interface only works for the IPv4 case */
  12444. addr = ntohl(conn->client.rsa.sin.sin_addr.s_addr);
  12445. memcpy(&conn->request_info.remote_ip, &addr, 4);
  12446. #endif
  12447. conn->request_info.is_ssl = conn->client.is_ssl;
  12448. if (conn->client.is_ssl) {
  12449. #ifndef NO_SSL
  12450. /* HTTPS connection */
  12451. if (sslize(conn,
  12452. conn->ctx->ssl_ctx,
  12453. SSL_accept,
  12454. &(conn->ctx->stop_flag))) {
  12455. /* Get SSL client certificate information (if set) */
  12456. ssl_get_client_cert_info(conn);
  12457. /* process HTTPS connection */
  12458. process_new_connection(conn);
  12459. /* Free client certificate info */
  12460. if (conn->request_info.client_cert) {
  12461. mg_free((void *)(conn->request_info.client_cert->subject));
  12462. mg_free((void *)(conn->request_info.client_cert->issuer));
  12463. mg_free((void *)(conn->request_info.client_cert->serial));
  12464. mg_free((void *)(conn->request_info.client_cert->finger));
  12465. conn->request_info.client_cert->subject = 0;
  12466. conn->request_info.client_cert->issuer = 0;
  12467. conn->request_info.client_cert->serial = 0;
  12468. conn->request_info.client_cert->finger = 0;
  12469. mg_free(conn->request_info.client_cert);
  12470. conn->request_info.client_cert = 0;
  12471. }
  12472. }
  12473. #endif
  12474. } else {
  12475. /* process HTTP connection */
  12476. process_new_connection(conn);
  12477. }
  12478. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  12479. conn->request_info.remote_addr,
  12480. difftime(time(NULL), conn->conn_birth_time));
  12481. close_connection(conn);
  12482. DEBUG_TRACE("%s", "Connection closed");
  12483. }
  12484. pthread_setspecific(sTlsKey, NULL);
  12485. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12486. CloseHandle(tls.pthread_cond_helper_mutex);
  12487. #endif
  12488. pthread_mutex_destroy(&conn->mutex);
  12489. /* Free the request buffer. */
  12490. conn->buf_size = 0;
  12491. mg_free(conn->buf);
  12492. conn->buf = NULL;
  12493. DEBUG_TRACE("%s", "exiting");
  12494. return NULL;
  12495. }
  12496. /* Threads have different return types on Windows and Unix. */
  12497. #ifdef _WIN32
  12498. static unsigned __stdcall worker_thread(void *thread_func_param)
  12499. {
  12500. struct worker_thread_args *pwta =
  12501. (struct worker_thread_args *)thread_func_param;
  12502. worker_thread_run(pwta);
  12503. mg_free(thread_func_param);
  12504. return 0;
  12505. }
  12506. #else
  12507. static void *
  12508. worker_thread(void *thread_func_param)
  12509. {
  12510. struct worker_thread_args *pwta =
  12511. (struct worker_thread_args *)thread_func_param;
  12512. worker_thread_run(pwta);
  12513. mg_free(thread_func_param);
  12514. return NULL;
  12515. }
  12516. #endif /* _WIN32 */
  12517. static void
  12518. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  12519. {
  12520. struct socket so;
  12521. char src_addr[IP_ADDR_STR_LEN];
  12522. socklen_t len = sizeof(so.rsa);
  12523. int on = 1;
  12524. if (!listener) {
  12525. return;
  12526. }
  12527. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  12528. == INVALID_SOCKET) {
  12529. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  12530. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  12531. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  12532. closesocket(so.sock);
  12533. so.sock = INVALID_SOCKET;
  12534. } else {
  12535. /* Put so socket structure into the queue */
  12536. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  12537. set_close_on_exec(so.sock, fc(ctx));
  12538. so.is_ssl = listener->is_ssl;
  12539. so.ssl_redir = listener->ssl_redir;
  12540. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  12541. mg_cry(fc(ctx),
  12542. "%s: getsockname() failed: %s",
  12543. __func__,
  12544. strerror(ERRNO));
  12545. }
  12546. /* Set TCP keep-alive. This is needed because if HTTP-level
  12547. * keep-alive
  12548. * is enabled, and client resets the connection, server won't get
  12549. * TCP FIN or RST and will keep the connection open forever. With
  12550. * TCP keep-alive, next keep-alive handshake will figure out that
  12551. * the client is down and will close the server end.
  12552. * Thanks to Igor Klopov who suggested the patch. */
  12553. if (setsockopt(so.sock,
  12554. SOL_SOCKET,
  12555. SO_KEEPALIVE,
  12556. (SOCK_OPT_TYPE)&on,
  12557. sizeof(on)) != 0) {
  12558. mg_cry(fc(ctx),
  12559. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  12560. __func__,
  12561. strerror(ERRNO));
  12562. }
  12563. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  12564. * to effectively fill up the underlying IP packet payload and
  12565. * reduce the overhead of sending lots of small buffers. However
  12566. * this hurts the server's throughput (ie. operations per second)
  12567. * when HTTP 1.1 persistent connections are used and the responses
  12568. * are relatively small (eg. less than 1400 bytes).
  12569. */
  12570. if ((ctx != NULL) && (ctx->config[CONFIG_TCP_NODELAY] != NULL)
  12571. && (!strcmp(ctx->config[CONFIG_TCP_NODELAY], "1"))) {
  12572. if (set_tcp_nodelay(so.sock, 1) != 0) {
  12573. mg_cry(fc(ctx),
  12574. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  12575. __func__,
  12576. strerror(ERRNO));
  12577. }
  12578. }
  12579. /* We are using non-blocking sockets. Thus, the
  12580. * set_sock_timeout(so.sock, timeout);
  12581. * call is no longer required. */
  12582. set_blocking_mode(so.sock, 0);
  12583. produce_socket(ctx, &so);
  12584. }
  12585. }
  12586. static void
  12587. master_thread_run(void *thread_func_param)
  12588. {
  12589. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  12590. struct mg_workerTLS tls;
  12591. struct pollfd *pfd;
  12592. unsigned int i;
  12593. unsigned int workerthreadcount;
  12594. if (!ctx) {
  12595. return;
  12596. }
  12597. mg_set_thread_name("master");
  12598. /* Increase priority of the master thread */
  12599. #if defined(_WIN32)
  12600. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  12601. #elif defined(USE_MASTER_THREAD_PRIORITY)
  12602. int min_prio = sched_get_priority_min(SCHED_RR);
  12603. int max_prio = sched_get_priority_max(SCHED_RR);
  12604. if ((min_prio >= 0) && (max_prio >= 0)
  12605. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  12606. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  12607. struct sched_param sched_param = {0};
  12608. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  12609. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  12610. }
  12611. #endif
  12612. /* Initialize thread local storage */
  12613. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12614. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  12615. #endif
  12616. tls.is_master = 1;
  12617. pthread_setspecific(sTlsKey, &tls);
  12618. if (ctx->callbacks.init_thread) {
  12619. /* Callback for the master thread (type 0) */
  12620. ctx->callbacks.init_thread(ctx, 0);
  12621. }
  12622. /* Server starts *now* */
  12623. ctx->start_time = time(NULL);
  12624. /* Start the server */
  12625. pfd = ctx->listening_socket_fds;
  12626. while (ctx->stop_flag == 0) {
  12627. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12628. pfd[i].fd = ctx->listening_sockets[i].sock;
  12629. pfd[i].events = POLLIN;
  12630. }
  12631. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  12632. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12633. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  12634. * successful poll, and POLLIN is defined as
  12635. * (POLLRDNORM | POLLRDBAND)
  12636. * Therefore, we're checking pfd[i].revents & POLLIN, not
  12637. * pfd[i].revents == POLLIN. */
  12638. if (ctx->stop_flag == 0 && (pfd[i].revents & POLLIN)) {
  12639. accept_new_connection(&ctx->listening_sockets[i], ctx);
  12640. }
  12641. }
  12642. }
  12643. }
  12644. /* Here stop_flag is 1 - Initiate shutdown. */
  12645. DEBUG_TRACE("%s", "stopping workers");
  12646. /* Stop signal received: somebody called mg_stop. Quit. */
  12647. close_all_listening_sockets(ctx);
  12648. /* Wakeup workers that are waiting for connections to handle. */
  12649. (void)pthread_mutex_lock(&ctx->thread_mutex);
  12650. #if defined(ALTERNATIVE_QUEUE)
  12651. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  12652. event_signal(ctx->client_wait_events[i]);
  12653. /* Since we know all sockets, we can shutdown the connections. */
  12654. if (ctx->client_socks[i].in_use) {
  12655. shutdown(ctx->client_socks[i].sock, SHUTDOWN_BOTH);
  12656. }
  12657. }
  12658. #else
  12659. pthread_cond_broadcast(&ctx->sq_full);
  12660. #endif
  12661. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  12662. /* Join all worker threads to avoid leaking threads. */
  12663. workerthreadcount = ctx->cfg_worker_threads;
  12664. for (i = 0; i < workerthreadcount; i++) {
  12665. if (ctx->worker_threadids[i] != 0) {
  12666. mg_join_thread(ctx->worker_threadids[i]);
  12667. }
  12668. }
  12669. #if defined(USE_LUA)
  12670. /* Free Lua state of lua background task */
  12671. if (ctx->lua_background_state) {
  12672. lua_close((lua_State *)ctx->lua_background_state);
  12673. ctx->lua_background_state = 0;
  12674. }
  12675. #endif
  12676. #if !defined(NO_SSL)
  12677. if (ctx->ssl_ctx != NULL) {
  12678. uninitialize_ssl();
  12679. }
  12680. #endif
  12681. DEBUG_TRACE("%s", "exiting");
  12682. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12683. CloseHandle(tls.pthread_cond_helper_mutex);
  12684. #endif
  12685. pthread_setspecific(sTlsKey, NULL);
  12686. /* Signal mg_stop() that we're done.
  12687. * WARNING: This must be the very last thing this
  12688. * thread does, as ctx becomes invalid after this line. */
  12689. ctx->stop_flag = 2;
  12690. }
  12691. /* Threads have different return types on Windows and Unix. */
  12692. #ifdef _WIN32
  12693. static unsigned __stdcall master_thread(void *thread_func_param)
  12694. {
  12695. master_thread_run(thread_func_param);
  12696. return 0;
  12697. }
  12698. #else
  12699. static void *
  12700. master_thread(void *thread_func_param)
  12701. {
  12702. master_thread_run(thread_func_param);
  12703. return NULL;
  12704. }
  12705. #endif /* _WIN32 */
  12706. static void
  12707. free_context(struct mg_context *ctx)
  12708. {
  12709. int i;
  12710. struct mg_handler_info *tmp_rh;
  12711. if (ctx == NULL) {
  12712. return;
  12713. }
  12714. if (ctx->callbacks.exit_context) {
  12715. ctx->callbacks.exit_context(ctx);
  12716. }
  12717. /* All threads exited, no sync is needed. Destroy thread mutex and
  12718. * condvars
  12719. */
  12720. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  12721. #if defined(ALTERNATIVE_QUEUE)
  12722. mg_free(ctx->client_socks);
  12723. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  12724. event_destroy(ctx->client_wait_events[i]);
  12725. }
  12726. mg_free(ctx->client_wait_events);
  12727. #else
  12728. (void)pthread_cond_destroy(&ctx->sq_empty);
  12729. (void)pthread_cond_destroy(&ctx->sq_full);
  12730. #endif
  12731. /* Destroy other context global data structures mutex */
  12732. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  12733. #if defined(USE_TIMERS)
  12734. timers_exit(ctx);
  12735. #endif
  12736. /* Deallocate config parameters */
  12737. for (i = 0; i < NUM_OPTIONS; i++) {
  12738. if (ctx->config[i] != NULL) {
  12739. #if defined(_MSC_VER)
  12740. #pragma warning(suppress : 6001)
  12741. #endif
  12742. mg_free(ctx->config[i]);
  12743. }
  12744. }
  12745. /* Deallocate request handlers */
  12746. while (ctx->handlers) {
  12747. tmp_rh = ctx->handlers;
  12748. ctx->handlers = tmp_rh->next;
  12749. mg_free(tmp_rh->uri);
  12750. mg_free(tmp_rh);
  12751. }
  12752. #ifndef NO_SSL
  12753. /* Deallocate SSL context */
  12754. if (ctx->ssl_ctx != NULL) {
  12755. SSL_CTX_free(ctx->ssl_ctx);
  12756. }
  12757. #endif /* !NO_SSL */
  12758. /* Deallocate worker thread ID array */
  12759. if (ctx->worker_threadids != NULL) {
  12760. mg_free(ctx->worker_threadids);
  12761. }
  12762. /* Deallocate worker thread ID array */
  12763. if (ctx->worker_connections != NULL) {
  12764. mg_free(ctx->worker_connections);
  12765. }
  12766. /* Deallocate the tls variable */
  12767. if (mg_atomic_dec(&sTlsInit) == 0) {
  12768. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12769. DeleteCriticalSection(&global_log_file_lock);
  12770. #endif /* _WIN32 && !__SYMBIAN32__ */
  12771. #if !defined(_WIN32)
  12772. pthread_mutexattr_destroy(&pthread_mutex_attr);
  12773. #endif
  12774. pthread_key_delete(sTlsKey);
  12775. #if defined(USE_LUA)
  12776. lua_exit_optional_libraries();
  12777. #endif
  12778. }
  12779. /* deallocate system name string */
  12780. mg_free(ctx->systemName);
  12781. /* Deallocate context itself */
  12782. mg_free(ctx);
  12783. }
  12784. void
  12785. mg_stop(struct mg_context *ctx)
  12786. {
  12787. pthread_t mt;
  12788. if (!ctx) {
  12789. return;
  12790. }
  12791. /* We don't use a lock here. Calling mg_stop with the same ctx from
  12792. * two threads is not allowed. */
  12793. mt = ctx->masterthreadid;
  12794. if (mt == 0) {
  12795. return;
  12796. }
  12797. ctx->masterthreadid = 0;
  12798. /* Set stop flag, so all threads know they have to exit. */
  12799. ctx->stop_flag = 1;
  12800. /* Wait until everything has stopped. */
  12801. while (ctx->stop_flag != 2) {
  12802. (void)mg_sleep(10);
  12803. }
  12804. mg_join_thread(mt);
  12805. free_context(ctx);
  12806. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12807. (void)WSACleanup();
  12808. #endif /* _WIN32 && !__SYMBIAN32__ */
  12809. }
  12810. static void
  12811. get_system_name(char **sysName)
  12812. {
  12813. #if defined(_WIN32)
  12814. #if !defined(__SYMBIAN32__)
  12815. #if defined(_WIN32_WCE)
  12816. *sysName = mg_strdup("WinCE");
  12817. #else
  12818. char name[128];
  12819. DWORD dwVersion = 0;
  12820. DWORD dwMajorVersion = 0;
  12821. DWORD dwMinorVersion = 0;
  12822. DWORD dwBuild = 0;
  12823. BOOL wowRet, isWoW = FALSE;
  12824. #ifdef _MSC_VER
  12825. #pragma warning(push)
  12826. /* GetVersion was declared deprecated */
  12827. #pragma warning(disable : 4996)
  12828. #endif
  12829. dwVersion = GetVersion();
  12830. #ifdef _MSC_VER
  12831. #pragma warning(pop)
  12832. #endif
  12833. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  12834. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  12835. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  12836. (void)dwBuild;
  12837. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  12838. sprintf(name,
  12839. "Windows %u.%u%s",
  12840. (unsigned)dwMajorVersion,
  12841. (unsigned)dwMinorVersion,
  12842. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  12843. *sysName = mg_strdup(name);
  12844. #endif
  12845. #else
  12846. *sysName = mg_strdup("Symbian");
  12847. #endif
  12848. #else
  12849. struct utsname name;
  12850. memset(&name, 0, sizeof(name));
  12851. uname(&name);
  12852. *sysName = mg_strdup(name.sysname);
  12853. #endif
  12854. }
  12855. struct mg_context *
  12856. mg_start(const struct mg_callbacks *callbacks,
  12857. void *user_data,
  12858. const char **options)
  12859. {
  12860. struct mg_context *ctx;
  12861. const char *name, *value, *default_value;
  12862. int idx, ok, workerthreadcount;
  12863. unsigned int i;
  12864. void (*exit_callback)(const struct mg_context *ctx) = 0;
  12865. struct mg_workerTLS tls;
  12866. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12867. WSADATA data;
  12868. WSAStartup(MAKEWORD(2, 2), &data);
  12869. #endif /* _WIN32 && !__SYMBIAN32__ */
  12870. /* Allocate context and initialize reasonable general case defaults. */
  12871. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  12872. return NULL;
  12873. }
  12874. /* Random number generator will initialize at the first call */
  12875. ctx->auth_nonce_mask =
  12876. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  12877. if (mg_atomic_inc(&sTlsInit) == 1) {
  12878. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12879. InitializeCriticalSection(&global_log_file_lock);
  12880. #endif /* _WIN32 && !__SYMBIAN32__ */
  12881. #if !defined(_WIN32)
  12882. pthread_mutexattr_init(&pthread_mutex_attr);
  12883. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  12884. #endif
  12885. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  12886. /* Fatal error - abort start. However, this situation should
  12887. * never occur in practice. */
  12888. mg_atomic_dec(&sTlsInit);
  12889. mg_cry(fc(ctx), "Cannot initialize thread local storage");
  12890. mg_free(ctx);
  12891. return NULL;
  12892. }
  12893. #if defined(USE_LUA)
  12894. lua_init_optional_libraries();
  12895. #endif
  12896. } else {
  12897. /* TODO (low): instead of sleeping, check if sTlsKey is already
  12898. * initialized. */
  12899. mg_sleep(1);
  12900. }
  12901. tls.is_master = -1;
  12902. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  12903. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12904. tls.pthread_cond_helper_mutex = NULL;
  12905. #endif
  12906. pthread_setspecific(sTlsKey, &tls);
  12907. /* Dummy use this function - in some #ifdef combinations it's used,
  12908. * while it's not used in others, but GCC seems to stupid to understand
  12909. * #pragma GCC diagnostic ignored "-Wunused-function"
  12910. * in cases the function is unused, and it also complains on
  12911. * __attribute((unused))__ in cases it is used.
  12912. * So dummy use it, to have our peace. */
  12913. (void)mg_current_thread_id();
  12914. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr);
  12915. #if !defined(ALTERNATIVE_QUEUE)
  12916. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  12917. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  12918. #endif
  12919. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr);
  12920. if (!ok) {
  12921. /* Fatal error - abort start. However, this situation should never
  12922. * occur in practice. */
  12923. mg_cry(fc(ctx), "Cannot initialize thread synchronization objects");
  12924. mg_free(ctx);
  12925. pthread_setspecific(sTlsKey, NULL);
  12926. return NULL;
  12927. }
  12928. if (callbacks) {
  12929. ctx->callbacks = *callbacks;
  12930. exit_callback = callbacks->exit_context;
  12931. ctx->callbacks.exit_context = 0;
  12932. }
  12933. ctx->user_data = user_data;
  12934. ctx->handlers = NULL;
  12935. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  12936. ctx->shared_lua_websockets = 0;
  12937. #endif
  12938. while (options && (name = *options++) != NULL) {
  12939. if ((idx = get_option_index(name)) == -1) {
  12940. mg_cry(fc(ctx), "Invalid option: %s", name);
  12941. free_context(ctx);
  12942. pthread_setspecific(sTlsKey, NULL);
  12943. return NULL;
  12944. } else if ((value = *options++) == NULL) {
  12945. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  12946. free_context(ctx);
  12947. pthread_setspecific(sTlsKey, NULL);
  12948. return NULL;
  12949. }
  12950. if (ctx->config[idx] != NULL) {
  12951. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  12952. mg_free(ctx->config[idx]);
  12953. }
  12954. ctx->config[idx] = mg_strdup(value);
  12955. DEBUG_TRACE("[%s] -> [%s]", name, value);
  12956. }
  12957. /* Set default value if needed */
  12958. for (i = 0; config_options[i].name != NULL; i++) {
  12959. default_value = config_options[i].default_value;
  12960. if (ctx->config[i] == NULL && default_value != NULL) {
  12961. ctx->config[i] = mg_strdup(default_value);
  12962. }
  12963. }
  12964. workerthreadcount = atoi(ctx->config[NUM_THREADS]);
  12965. if (workerthreadcount > MAX_WORKER_THREADS) {
  12966. mg_cry(fc(ctx), "Too many worker threads");
  12967. free_context(ctx);
  12968. pthread_setspecific(sTlsKey, NULL);
  12969. return NULL;
  12970. }
  12971. if (workerthreadcount <= 0) {
  12972. mg_cry(fc(ctx), "Invalid number of worker threads");
  12973. free_context(ctx);
  12974. pthread_setspecific(sTlsKey, NULL);
  12975. return NULL;
  12976. }
  12977. #if defined(NO_FILES)
  12978. if (ctx->config[DOCUMENT_ROOT] != NULL) {
  12979. mg_cry(fc(ctx), "%s", "Document root must not be set");
  12980. free_context(ctx);
  12981. pthread_setspecific(sTlsKey, NULL);
  12982. return NULL;
  12983. }
  12984. #endif
  12985. get_system_name(&ctx->systemName);
  12986. #if defined(USE_LUA)
  12987. /* If a Lua background script has been configured, start it. */
  12988. if (ctx->config[LUA_BACKGROUND_SCRIPT] != NULL) {
  12989. char ebuf[256];
  12990. void *state = (void *)mg_prepare_lua_context_script(
  12991. ctx->config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  12992. if (!state) {
  12993. mg_cry(fc(ctx), "lua_background_script error: %s", ebuf);
  12994. free_context(ctx);
  12995. pthread_setspecific(sTlsKey, NULL);
  12996. return NULL;
  12997. }
  12998. ctx->lua_background_state = state;
  12999. } else {
  13000. ctx->lua_background_state = 0;
  13001. }
  13002. #endif
  13003. /* NOTE(lsm): order is important here. SSL certificates must
  13004. * be initialized before listening ports. UID must be set last. */
  13005. if (!set_gpass_option(ctx) ||
  13006. #if !defined(NO_SSL)
  13007. !set_ssl_option(ctx) ||
  13008. #endif
  13009. !set_ports_option(ctx) ||
  13010. #if !defined(_WIN32)
  13011. !set_uid_option(ctx) ||
  13012. #endif
  13013. !set_acl_option(ctx)) {
  13014. free_context(ctx);
  13015. pthread_setspecific(sTlsKey, NULL);
  13016. return NULL;
  13017. }
  13018. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  13019. /* Ignore SIGPIPE signal, so if browser cancels the request, it
  13020. * won't kill the whole process. */
  13021. (void)signal(SIGPIPE, SIG_IGN);
  13022. #endif /* !_WIN32 && !__SYMBIAN32__ */
  13023. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  13024. ctx->worker_threadids =
  13025. (pthread_t *)mg_calloc(ctx->cfg_worker_threads, sizeof(pthread_t));
  13026. if (ctx->worker_threadids == NULL) {
  13027. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  13028. free_context(ctx);
  13029. pthread_setspecific(sTlsKey, NULL);
  13030. return NULL;
  13031. }
  13032. ctx->worker_connections =
  13033. (struct mg_connection *)mg_calloc(ctx->cfg_worker_threads,
  13034. sizeof(struct mg_connection));
  13035. if (ctx->worker_connections == NULL) {
  13036. mg_cry(fc(ctx), "Not enough memory for worker thread connection array");
  13037. free_context(ctx);
  13038. pthread_setspecific(sTlsKey, NULL);
  13039. return NULL;
  13040. }
  13041. #if defined(ALTERNATIVE_QUEUE)
  13042. ctx->client_wait_events =
  13043. mg_calloc(sizeof(ctx->client_wait_events[0]), ctx->cfg_worker_threads);
  13044. if (ctx->client_wait_events == NULL) {
  13045. mg_cry(fc(ctx), "Not enough memory for worker event array");
  13046. mg_free(ctx->worker_threadids);
  13047. free_context(ctx);
  13048. pthread_setspecific(sTlsKey, NULL);
  13049. return NULL;
  13050. }
  13051. ctx->client_socks =
  13052. mg_calloc(sizeof(ctx->client_socks[0]), ctx->cfg_worker_threads);
  13053. if (ctx->client_wait_events == NULL) {
  13054. mg_cry(fc(ctx), "Not enough memory for worker socket array");
  13055. mg_free(ctx->client_socks);
  13056. mg_free(ctx->worker_threadids);
  13057. free_context(ctx);
  13058. pthread_setspecific(sTlsKey, NULL);
  13059. return NULL;
  13060. }
  13061. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  13062. ctx->client_wait_events[i] = event_create();
  13063. if (ctx->client_wait_events[i] == 0) {
  13064. mg_cry(fc(ctx), "Error creating worker event %i", i);
  13065. while (i > 0) {
  13066. i--;
  13067. event_destroy(ctx->client_wait_events[i]);
  13068. }
  13069. mg_free(ctx->client_socks);
  13070. mg_free(ctx->worker_threadids);
  13071. free_context(ctx);
  13072. pthread_setspecific(sTlsKey, NULL);
  13073. return NULL;
  13074. }
  13075. }
  13076. #endif
  13077. #if defined(USE_TIMERS)
  13078. if (timers_init(ctx) != 0) {
  13079. mg_cry(fc(ctx), "Error creating timers");
  13080. free_context(ctx);
  13081. pthread_setspecific(sTlsKey, NULL);
  13082. return NULL;
  13083. }
  13084. #endif
  13085. /* Context has been created - init user libraries */
  13086. if (ctx->callbacks.init_context) {
  13087. ctx->callbacks.init_context(ctx);
  13088. }
  13089. ctx->callbacks.exit_context = exit_callback;
  13090. ctx->context_type = 1; /* server context */
  13091. /* Start master (listening) thread */
  13092. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  13093. /* Start worker threads */
  13094. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  13095. struct worker_thread_args *wta = (struct worker_thread_args *)mg_malloc(
  13096. sizeof(struct worker_thread_args));
  13097. if (wta) {
  13098. wta->ctx = ctx;
  13099. wta->index = (int)i;
  13100. }
  13101. if ((wta == NULL)
  13102. || (mg_start_thread_with_id(worker_thread,
  13103. wta,
  13104. &ctx->worker_threadids[i]) != 0)) {
  13105. /* thread was not created */
  13106. if (wta != NULL) {
  13107. mg_free(wta);
  13108. }
  13109. if (i > 0) {
  13110. mg_cry(fc(ctx),
  13111. "Cannot start worker thread %i: error %ld",
  13112. i + 1,
  13113. (long)ERRNO);
  13114. } else {
  13115. mg_cry(fc(ctx),
  13116. "Cannot create threads: error %ld",
  13117. (long)ERRNO);
  13118. free_context(ctx);
  13119. pthread_setspecific(sTlsKey, NULL);
  13120. return NULL;
  13121. }
  13122. break;
  13123. }
  13124. }
  13125. pthread_setspecific(sTlsKey, NULL);
  13126. return ctx;
  13127. }
  13128. /* Feature check API function */
  13129. unsigned
  13130. mg_check_feature(unsigned feature)
  13131. {
  13132. static const unsigned feature_set = 0
  13133. /* Set bits for available features according to API documentation.
  13134. * This bit mask is created at compile time, according to the active
  13135. * preprocessor defines. It is a single const value at runtime. */
  13136. #if !defined(NO_FILES)
  13137. | 0x0001u
  13138. #endif
  13139. #if !defined(NO_SSL)
  13140. | 0x0002u
  13141. #endif
  13142. #if !defined(NO_CGI)
  13143. | 0x0004u
  13144. #endif
  13145. #if defined(USE_IPV6)
  13146. | 0x0008u
  13147. #endif
  13148. #if defined(USE_WEBSOCKET)
  13149. | 0x0010u
  13150. #endif
  13151. #if defined(USE_LUA)
  13152. | 0x0020u
  13153. #endif
  13154. #if defined(USE_DUKTAPE)
  13155. | 0x0040u
  13156. #endif
  13157. #if !defined(NO_CACHING)
  13158. | 0x0080u
  13159. #endif
  13160. /* Set some extra bits not defined in the API documentation.
  13161. * These bits may change without further notice. */
  13162. #if defined(MG_LEGACY_INTERFACE)
  13163. | 0x8000u
  13164. #endif
  13165. #if defined(MEMORY_DEBUGGING)
  13166. | 0x0100u
  13167. #endif
  13168. #if defined(USE_TIMERS)
  13169. | 0x0200u
  13170. #endif
  13171. #if !defined(NO_NONCE_CHECK)
  13172. | 0x0400u
  13173. #endif
  13174. #if !defined(NO_POPEN)
  13175. | 0x0800u
  13176. #endif
  13177. ;
  13178. return (feature & feature_set);
  13179. }
  13180. /* Get system information. It can be printed or stored by the caller.
  13181. * Return the size of available information. */
  13182. static int
  13183. mg_get_system_info_impl(char *buffer, int buflen)
  13184. {
  13185. char block[256];
  13186. int system_info_length = 0;
  13187. #if defined(_WIN32)
  13188. const char *eol = "\r\n";
  13189. #else
  13190. const char *eol = "\n";
  13191. #endif
  13192. /* Server version */
  13193. {
  13194. const char *version = mg_version();
  13195. mg_snprintf(NULL,
  13196. NULL,
  13197. block,
  13198. sizeof(block),
  13199. "Server Version: %s%s",
  13200. version,
  13201. eol);
  13202. system_info_length += (int)strlen(block);
  13203. if (system_info_length < buflen) {
  13204. strcat(buffer, block);
  13205. }
  13206. }
  13207. /* System info */
  13208. {
  13209. #if defined(_WIN32)
  13210. #if !defined(__SYMBIAN32__)
  13211. DWORD dwVersion = 0;
  13212. DWORD dwMajorVersion = 0;
  13213. DWORD dwMinorVersion = 0;
  13214. SYSTEM_INFO si;
  13215. GetSystemInfo(&si);
  13216. #ifdef _MSC_VER
  13217. #pragma warning(push)
  13218. /* GetVersion was declared deprecated */
  13219. #pragma warning(disable : 4996)
  13220. #endif
  13221. dwVersion = GetVersion();
  13222. #ifdef _MSC_VER
  13223. #pragma warning(pop)
  13224. #endif
  13225. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  13226. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  13227. mg_snprintf(NULL,
  13228. NULL,
  13229. block,
  13230. sizeof(block),
  13231. "Windows %u.%u%s",
  13232. (unsigned)dwMajorVersion,
  13233. (unsigned)dwMinorVersion,
  13234. eol);
  13235. system_info_length += (int)strlen(block);
  13236. if (system_info_length < buflen) {
  13237. strcat(buffer, block);
  13238. }
  13239. mg_snprintf(NULL,
  13240. NULL,
  13241. block,
  13242. sizeof(block),
  13243. "CPU: type %u, cores %u, mask %x%s",
  13244. (unsigned)si.wProcessorArchitecture,
  13245. (unsigned)si.dwNumberOfProcessors,
  13246. (unsigned)si.dwActiveProcessorMask,
  13247. eol);
  13248. system_info_length += (int)strlen(block);
  13249. if (system_info_length < buflen) {
  13250. strcat(buffer, block);
  13251. }
  13252. #else
  13253. mg_snprintf(NULL, NULL, block, sizeof(block), "%s - Symbian%s", eol);
  13254. system_info_length += (int)strlen(block);
  13255. if (system_info_length < buflen) {
  13256. strcat(buffer, block);
  13257. }
  13258. #endif
  13259. #else
  13260. struct utsname name;
  13261. memset(&name, 0, sizeof(name));
  13262. uname(&name);
  13263. mg_snprintf(NULL,
  13264. NULL,
  13265. block,
  13266. sizeof(block),
  13267. "%s %s (%s) - %s%s",
  13268. name.sysname,
  13269. name.version,
  13270. name.release,
  13271. name.machine,
  13272. eol);
  13273. system_info_length += (int)strlen(block);
  13274. if (system_info_length < buflen) {
  13275. strcat(buffer, block);
  13276. }
  13277. #endif
  13278. }
  13279. /* Features */
  13280. {
  13281. mg_snprintf(NULL,
  13282. NULL,
  13283. block,
  13284. sizeof(block),
  13285. "Features: %X%s%s%s%s%s%s%s%s%s%s",
  13286. mg_check_feature(0xFFFFFFFFu),
  13287. eol,
  13288. mg_check_feature(1) ? " Files" : "",
  13289. mg_check_feature(2) ? " HTTPS" : "",
  13290. mg_check_feature(4) ? " CGI" : "",
  13291. mg_check_feature(8) ? " IPv6" : "",
  13292. mg_check_feature(16) ? " WebSockets" : "",
  13293. mg_check_feature(32) ? " Lua" : "",
  13294. mg_check_feature(64) ? " JavaScript" : "",
  13295. mg_check_feature(128) ? " Cache" : "",
  13296. eol);
  13297. system_info_length += (int)strlen(block);
  13298. if (system_info_length < buflen) {
  13299. strcat(buffer, block);
  13300. }
  13301. #ifdef USE_LUA
  13302. mg_snprintf(NULL,
  13303. NULL,
  13304. block,
  13305. sizeof(block),
  13306. "Lua Version: %u (%s)%s",
  13307. (unsigned)LUA_VERSION_NUM,
  13308. LUA_RELEASE,
  13309. eol);
  13310. system_info_length += (int)strlen(block);
  13311. if (system_info_length < buflen) {
  13312. strcat(buffer, block);
  13313. }
  13314. #endif
  13315. #if defined(USE_DUKTAPE)
  13316. mg_snprintf(NULL,
  13317. NULL,
  13318. block,
  13319. sizeof(block),
  13320. "JavaScript: Duktape %u.%u.%u%s",
  13321. (unsigned)DUK_VERSION / 10000,
  13322. ((unsigned)DUK_VERSION / 100) % 100,
  13323. (unsigned)DUK_VERSION % 100,
  13324. eol);
  13325. system_info_length += (int)strlen(block);
  13326. if (system_info_length < buflen) {
  13327. strcat(buffer, block);
  13328. }
  13329. #endif
  13330. }
  13331. /* Build date */
  13332. {
  13333. mg_snprintf(
  13334. NULL, NULL, block, sizeof(block), "Build: %s%s", __DATE__, eol);
  13335. system_info_length += (int)strlen(block);
  13336. if (system_info_length < buflen) {
  13337. strcat(buffer, block);
  13338. }
  13339. }
  13340. /* Compiler information */
  13341. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  13342. {
  13343. #if defined(_MSC_VER)
  13344. mg_snprintf(NULL,
  13345. NULL,
  13346. block,
  13347. sizeof(block),
  13348. "MSC: %u (%u)%s",
  13349. (unsigned)_MSC_VER,
  13350. (unsigned)_MSC_FULL_VER,
  13351. eol);
  13352. system_info_length += (int)strlen(block);
  13353. if (system_info_length < buflen) {
  13354. strcat(buffer, block);
  13355. }
  13356. #elif defined(__MINGW64__)
  13357. mg_snprintf(NULL,
  13358. NULL,
  13359. block,
  13360. sizeof(block),
  13361. "MinGW64: %u.%u%s",
  13362. (unsigned)__MINGW64_VERSION_MAJOR,
  13363. (unsigned)__MINGW64_VERSION_MINOR,
  13364. eol);
  13365. system_info_length += (int)strlen(block);
  13366. if (system_info_length < buflen) {
  13367. strcat(buffer, block);
  13368. }
  13369. mg_snprintf(NULL,
  13370. NULL,
  13371. block,
  13372. sizeof(block),
  13373. "MinGW32: %u.%u%s",
  13374. (unsigned)__MINGW32_MAJOR_VERSION,
  13375. (unsigned)__MINGW32_MINOR_VERSION,
  13376. eol);
  13377. system_info_length += (int)strlen(block);
  13378. if (system_info_length < buflen) {
  13379. strcat(buffer, block);
  13380. }
  13381. #elif defined(__MINGW32__)
  13382. mg_snprintf(NULL,
  13383. NULL,
  13384. block,
  13385. sizeof(block),
  13386. "MinGW32: %u.%u%s",
  13387. (unsigned)__MINGW32_MAJOR_VERSION,
  13388. (unsigned)__MINGW32_MINOR_VERSION,
  13389. eol);
  13390. system_info_length += (int)strlen(block);
  13391. if (system_info_length < buflen) {
  13392. strcat(buffer, block);
  13393. }
  13394. #elif defined(__clang__)
  13395. mg_snprintf(NULL,
  13396. NULL,
  13397. block,
  13398. sizeof(block),
  13399. "clang: %u.%u.%u (%s)%s",
  13400. __clang_major__,
  13401. __clang_minor__,
  13402. __clang_patchlevel__,
  13403. __clang_version__,
  13404. eol);
  13405. system_info_length += (int)strlen(block);
  13406. if (system_info_length < buflen) {
  13407. strcat(buffer, block);
  13408. }
  13409. #elif defined(__GNUC__)
  13410. mg_snprintf(NULL,
  13411. NULL,
  13412. block,
  13413. sizeof(block),
  13414. "gcc: %u.%u.%u%s",
  13415. (unsigned)__GNUC__,
  13416. (unsigned)__GNUC_MINOR__,
  13417. (unsigned)__GNUC_PATCHLEVEL__,
  13418. eol);
  13419. system_info_length += (int)strlen(block);
  13420. if (system_info_length < buflen) {
  13421. strcat(buffer, block);
  13422. }
  13423. #elif defined(__INTEL_COMPILER)
  13424. mg_snprintf(NULL,
  13425. NULL,
  13426. block,
  13427. sizeof(block),
  13428. "Intel C/C++: %u%s",
  13429. (unsigned)__INTEL_COMPILER,
  13430. eol);
  13431. system_info_length += (int)strlen(block);
  13432. if (system_info_length < buflen) {
  13433. strcat(buffer, block);
  13434. }
  13435. #elif defined(__BORLANDC__)
  13436. mg_snprintf(NULL,
  13437. NULL,
  13438. block,
  13439. sizeof(block),
  13440. "Borland C: 0x%x%s",
  13441. (unsigned)__BORLANDC__,
  13442. eol);
  13443. system_info_length += (int)strlen(block);
  13444. if (system_info_length < buflen) {
  13445. strcat(buffer, block);
  13446. }
  13447. #elif defined(__SUNPRO_C)
  13448. mg_snprintf(NULL,
  13449. NULL,
  13450. block,
  13451. sizeof(block),
  13452. "Solaris: 0x%x%s",
  13453. (unsigned)__SUNPRO_C,
  13454. eol);
  13455. system_info_length += (int)strlen(block);
  13456. if (system_info_length < buflen) {
  13457. strcat(buffer, block);
  13458. }
  13459. #else
  13460. mg_snprintf(NULL, NULL, block, sizeof(block), "Other compiler%s", eol);
  13461. system_info_length += (int)strlen(block);
  13462. if (system_info_length < buflen) {
  13463. strcat(buffer, block);
  13464. }
  13465. #endif
  13466. }
  13467. /* Determine 32/64 bit data mode.
  13468. * see https://en.wikipedia.org/wiki/64-bit_computing */
  13469. {
  13470. mg_snprintf(NULL,
  13471. NULL,
  13472. block,
  13473. sizeof(block),
  13474. "Data model: int:%u/%u/%u/%u, float:%u/%u/%u, char:%u/%u, "
  13475. "ptr:%u, size:%u, time:%u%s",
  13476. (unsigned)sizeof(short),
  13477. (unsigned)sizeof(int),
  13478. (unsigned)sizeof(long),
  13479. (unsigned)sizeof(long long),
  13480. (unsigned)sizeof(float),
  13481. (unsigned)sizeof(double),
  13482. (unsigned)sizeof(long double),
  13483. (unsigned)sizeof(char),
  13484. (unsigned)sizeof(wchar_t),
  13485. (unsigned)sizeof(void *),
  13486. (unsigned)sizeof(size_t),
  13487. (unsigned)sizeof(time_t),
  13488. eol);
  13489. system_info_length += (int)strlen(block);
  13490. if (system_info_length < buflen) {
  13491. strcat(buffer, block);
  13492. }
  13493. }
  13494. return system_info_length;
  13495. }
  13496. /* Get system information. It can be printed or stored by the caller.
  13497. * Return the size of available information. */
  13498. int
  13499. mg_get_system_info(char *buffer, int buflen)
  13500. {
  13501. if ((buffer == NULL) || (buflen < 1)) {
  13502. return mg_get_system_info_impl(NULL, 0);
  13503. } else {
  13504. /* Reset buffer, so we can always use strcat. */
  13505. buffer[0] = 0;
  13506. return mg_get_system_info_impl(buffer, buflen);
  13507. }
  13508. }
  13509. /* mg_init_library counter */
  13510. static int mg_init_library_called = 0;
  13511. static int mg_ssl_initialized = 0;
  13512. /* Initialize this library. This function does not need to be thread safe. */
  13513. unsigned
  13514. mg_init_library(unsigned features)
  13515. {
  13516. #if !defined(NO_SSL)
  13517. char ebuf[128];
  13518. #endif
  13519. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  13520. unsigned features_inited = features_to_init;
  13521. #if !defined(NO_SSL)
  13522. if (features_to_init & 2) {
  13523. if (!mg_ssl_initialized) {
  13524. if (initialize_ssl(ebuf, sizeof(ebuf))) {
  13525. mg_ssl_initialized = 1;
  13526. } else {
  13527. (void)ebuf;
  13528. /* TODO: print error */
  13529. features_inited &= ~(2u);
  13530. }
  13531. } else {
  13532. /* ssl already initialized */
  13533. }
  13534. }
  13535. #endif
  13536. /* Start Windows. */
  13537. if (mg_init_library_called <= 0) {
  13538. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13539. WSADATA data;
  13540. WSAStartup(MAKEWORD(2, 2), &data);
  13541. #endif /* _WIN32 && !__SYMBIAN32__ */
  13542. mg_init_library_called = 1;
  13543. } else {
  13544. mg_init_library_called++;
  13545. }
  13546. return features_inited;
  13547. }
  13548. /* Un-initialize this library. */
  13549. unsigned
  13550. mg_exit_library(void)
  13551. {
  13552. if (mg_init_library_called <= 0) {
  13553. return 0;
  13554. }
  13555. mg_init_library_called--;
  13556. if (mg_init_library_called == 0) {
  13557. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13558. (void)WSACleanup();
  13559. #endif /* _WIN32 && !__SYMBIAN32__ */
  13560. #if !defined(NO_SSL)
  13561. if (mg_ssl_initialized) {
  13562. uninitialize_ssl();
  13563. mg_ssl_initialized = 0;
  13564. }
  13565. #endif
  13566. }
  13567. return 1;
  13568. }
  13569. /* End of civetweb.c */