civetweb.c 415 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759
  1. /* Copyright (c) 2013-2017 the Civetweb developers
  2. * Copyright (c) 2004-2013 Sergey Lyubka
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. * THE SOFTWARE.
  21. */
  22. #if defined(_WIN32)
  23. #if !defined(_CRT_SECURE_NO_WARNINGS)
  24. #define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */
  25. #endif
  26. #ifndef _WIN32_WINNT /* defined for tdm-gcc so we can use getnameinfo */
  27. #define _WIN32_WINNT 0x0501
  28. #endif
  29. #else
  30. #if defined(__GNUC__) && !defined(_GNU_SOURCE)
  31. #define _GNU_SOURCE /* for setgroups() */
  32. #endif
  33. #if defined(__linux__) && !defined(_XOPEN_SOURCE)
  34. #define _XOPEN_SOURCE 600 /* For flockfile() on Linux */
  35. #endif
  36. #ifndef _LARGEFILE_SOURCE
  37. #define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
  38. #endif
  39. #ifndef _FILE_OFFSET_BITS
  40. #define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
  41. #endif
  42. #ifndef __STDC_FORMAT_MACROS
  43. #define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
  44. #endif
  45. #ifndef __STDC_LIMIT_MACROS
  46. #define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
  47. #endif
  48. #ifdef __sun
  49. #define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */
  50. #define __inline inline /* not recognized on older compiler versions */
  51. #endif
  52. #endif
  53. #if defined(USE_LUA)
  54. #define USE_TIMERS
  55. #endif
  56. #if defined(_MSC_VER)
  57. /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
  58. #pragma warning(disable : 4306)
  59. /* conditional expression is constant: introduced by FD_SET(..) */
  60. #pragma warning(disable : 4127)
  61. /* non-constant aggregate initializer: issued due to missing C99 support */
  62. #pragma warning(disable : 4204)
  63. /* padding added after data member */
  64. #pragma warning(disable : 4820)
  65. /* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
  66. #pragma warning(disable : 4668)
  67. /* no function prototype given: converting '()' to '(void)' */
  68. #pragma warning(disable : 4255)
  69. /* function has been selected for automatic inline expansion */
  70. #pragma warning(disable : 4711)
  71. #endif
  72. /* This code uses static_assert to check some conditions.
  73. * Unfortunately some compilers still do not support it, so we have a
  74. * replacement function here. */
  75. #if defined(_MSC_VER) && (_MSC_VER >= 1600)
  76. #define mg_static_assert static_assert
  77. #elif defined(__cplusplus) && (__cplusplus >= 201103L)
  78. #define mg_static_assert static_assert
  79. #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)
  80. #define mg_static_assert _Static_assert
  81. #else
  82. char static_assert_replacement[1];
  83. #define mg_static_assert(cond, txt) \
  84. extern char static_assert_replacement[(cond) ? 1 : -1]
  85. #endif
  86. mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
  87. "int data type size check");
  88. mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
  89. "pointer data type size check");
  90. mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
  91. /* DTL -- including winsock2.h works better if lean and mean */
  92. #ifndef WIN32_LEAN_AND_MEAN
  93. #define WIN32_LEAN_AND_MEAN
  94. #endif
  95. #if defined(__SYMBIAN32__)
  96. #define NO_SSL /* SSL is not supported */
  97. #define NO_CGI /* CGI is not supported */
  98. #define PATH_MAX FILENAME_MAX
  99. #endif /* __SYMBIAN32__ */
  100. #ifndef CIVETWEB_HEADER_INCLUDED
  101. /* Include the header file here, so the CivetWeb interface is defined for the
  102. * entire implementation, including the following forward definitions. */
  103. #include "civetweb.h"
  104. #endif
  105. #ifndef IGNORE_UNUSED_RESULT
  106. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  107. #endif
  108. #ifndef _WIN32_WCE /* Some ANSI #includes are not available on Windows CE */
  109. #include <sys/types.h>
  110. #include <sys/stat.h>
  111. #include <errno.h>
  112. #include <signal.h>
  113. #include <fcntl.h>
  114. #endif /* !_WIN32_WCE */
  115. #ifdef __clang__
  116. /* When using -Weverything, clang does not accept it's own headers
  117. * in a release build configuration. Disable what is too much in
  118. * -Weverything. */
  119. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  120. #endif
  121. #ifdef __MACH__ /* Apple OSX section */
  122. #ifdef __clang__
  123. /* Avoid warnings for Xopen 7.00 and higher */
  124. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  125. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  126. #endif
  127. #define CLOCK_MONOTONIC (1)
  128. #define CLOCK_REALTIME (2)
  129. #include <sys/errno.h>
  130. #include <sys/time.h>
  131. #include <mach/clock.h>
  132. #include <mach/mach.h>
  133. #include <mach/mach_time.h>
  134. #include <assert.h>
  135. /* clock_gettime is not implemented on OSX prior to 10.12 */
  136. static int
  137. _civet_clock_gettime(int clk_id, struct timespec *t)
  138. {
  139. memset(t, 0, sizeof(*t));
  140. if (clk_id == CLOCK_REALTIME) {
  141. struct timeval now;
  142. int rv = gettimeofday(&now, NULL);
  143. if (rv) {
  144. return rv;
  145. }
  146. t->tv_sec = now.tv_sec;
  147. t->tv_nsec = now.tv_usec * 1000;
  148. return 0;
  149. } else if (clk_id == CLOCK_MONOTONIC) {
  150. static uint64_t clock_start_time = 0;
  151. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  152. uint64_t now = mach_absolute_time();
  153. if (clock_start_time == 0) {
  154. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  155. #if defined(DEBUG)
  156. assert(mach_status == KERN_SUCCESS);
  157. #else
  158. /* appease "unused variable" warning for release builds */
  159. (void)mach_status;
  160. #endif
  161. clock_start_time = now;
  162. }
  163. now = (uint64_t)((double)(now - clock_start_time)
  164. * (double)timebase_ifo.numer
  165. / (double)timebase_ifo.denom);
  166. t->tv_sec = now / 1000000000;
  167. t->tv_nsec = now % 1000000000;
  168. return 0;
  169. }
  170. return -1; /* EINVAL - Clock ID is unknown */
  171. }
  172. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  173. #ifdef __CLOCK_AVAILABILITY
  174. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  175. * declared but it may be NULL at runtime. So we need to check before using
  176. * it. */
  177. static int
  178. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  179. {
  180. if (clock_gettime) {
  181. return clock_gettime(clk_id, t);
  182. }
  183. return _civet_clock_gettime(clk_id, t);
  184. }
  185. #define clock_gettime _civet_safe_clock_gettime
  186. #else
  187. #define clock_gettime _civet_clock_gettime
  188. #endif
  189. #endif
  190. #include <time.h>
  191. #include <stdlib.h>
  192. #include <stdarg.h>
  193. #include <assert.h>
  194. #include <string.h>
  195. #include <ctype.h>
  196. #include <limits.h>
  197. #include <stddef.h>
  198. #include <stdio.h>
  199. #include <stdint.h>
  200. #ifndef INT64_MAX
  201. #define INT64_MAX (9223372036854775807)
  202. #endif
  203. #ifndef MAX_WORKER_THREADS
  204. #define MAX_WORKER_THREADS (1024 * 64)
  205. #endif
  206. #ifndef SOCKET_TIMEOUT_QUANTUM /* in ms */
  207. #define SOCKET_TIMEOUT_QUANTUM (2000)
  208. #endif
  209. #define SHUTDOWN_RD (0)
  210. #define SHUTDOWN_WR (1)
  211. #define SHUTDOWN_BOTH (2)
  212. mg_static_assert(MAX_WORKER_THREADS >= 1,
  213. "worker threads must be a positive number");
  214. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  215. "size_t data type size check");
  216. #if defined(_WIN32) \
  217. && !defined(__SYMBIAN32__) /* WINDOWS / UNIX include block */
  218. #include <windows.h>
  219. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  220. #include <ws2tcpip.h>
  221. typedef const char *SOCK_OPT_TYPE;
  222. #if !defined(PATH_MAX)
  223. #define PATH_MAX (MAX_PATH)
  224. #endif
  225. #if !defined(PATH_MAX)
  226. #define PATH_MAX (4096)
  227. #endif
  228. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  229. #ifndef _IN_PORT_T
  230. #ifndef in_port_t
  231. #define in_port_t u_short
  232. #endif
  233. #endif
  234. #ifndef _WIN32_WCE
  235. #include <process.h>
  236. #include <direct.h>
  237. #include <io.h>
  238. #else /* _WIN32_WCE */
  239. #define NO_CGI /* WinCE has no pipes */
  240. #define NO_POPEN /* WinCE has no popen */
  241. typedef long off_t;
  242. #define errno ((int)(GetLastError()))
  243. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  244. #endif /* _WIN32_WCE */
  245. #define MAKEUQUAD(lo, hi) \
  246. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  247. #define RATE_DIFF (10000000) /* 100 nsecs */
  248. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  249. #define SYS2UNIX_TIME(lo, hi) \
  250. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  251. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  252. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  253. * Also use _strtoui64 on modern M$ compilers */
  254. #if defined(_MSC_VER)
  255. #if (_MSC_VER < 1300)
  256. #define STRX(x) #x
  257. #define STR(x) STRX(x)
  258. #define __func__ __FILE__ ":" STR(__LINE__)
  259. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  260. #define strtoll(x, y, z) (_atoi64(x))
  261. #else
  262. #define __func__ __FUNCTION__
  263. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  264. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  265. #endif
  266. #endif /* _MSC_VER */
  267. #define ERRNO ((int)(GetLastError()))
  268. #define NO_SOCKLEN_T
  269. #if defined(_WIN64) || defined(__MINGW64__)
  270. #define SSL_LIB "ssleay64.dll"
  271. #define CRYPTO_LIB "libeay64.dll"
  272. #else
  273. #define SSL_LIB "ssleay32.dll"
  274. #define CRYPTO_LIB "libeay32.dll"
  275. #endif
  276. #define O_NONBLOCK (0)
  277. #ifndef W_OK
  278. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  279. #endif
  280. #if !defined(EWOULDBLOCK)
  281. #define EWOULDBLOCK WSAEWOULDBLOCK
  282. #endif /* !EWOULDBLOCK */
  283. #define _POSIX_
  284. #define INT64_FMT "I64d"
  285. #define UINT64_FMT "I64u"
  286. #define WINCDECL __cdecl
  287. #define vsnprintf_impl _vsnprintf
  288. #define access _access
  289. #define mg_sleep(x) (Sleep(x))
  290. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  291. #ifndef popen
  292. #define popen(x, y) (_popen(x, y))
  293. #endif
  294. #ifndef pclose
  295. #define pclose(x) (_pclose(x))
  296. #endif
  297. #define close(x) (_close(x))
  298. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  299. #define RTLD_LAZY (0)
  300. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  301. #define fdopen(x, y) (_fdopen((x), (y)))
  302. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  303. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  304. #define flockfile(x) (EnterCriticalSection(&global_log_file_lock))
  305. #define funlockfile(x) (LeaveCriticalSection(&global_log_file_lock))
  306. #define sleep(x) (Sleep((x)*1000))
  307. #define rmdir(x) (_rmdir(x))
  308. #define timegm(x) (_mkgmtime(x))
  309. #if !defined(fileno)
  310. #define fileno(x) (_fileno(x))
  311. #endif /* !fileno MINGW #defines fileno */
  312. typedef HANDLE pthread_mutex_t;
  313. typedef DWORD pthread_key_t;
  314. typedef HANDLE pthread_t;
  315. typedef struct {
  316. CRITICAL_SECTION threadIdSec;
  317. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  318. } pthread_cond_t;
  319. #ifndef __clockid_t_defined
  320. typedef DWORD clockid_t;
  321. #endif
  322. #ifndef CLOCK_MONOTONIC
  323. #define CLOCK_MONOTONIC (1)
  324. #endif
  325. #ifndef CLOCK_REALTIME
  326. #define CLOCK_REALTIME (2)
  327. #endif
  328. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  329. #define _TIMESPEC_DEFINED
  330. #endif
  331. #ifndef _TIMESPEC_DEFINED
  332. struct timespec {
  333. time_t tv_sec; /* seconds */
  334. long tv_nsec; /* nanoseconds */
  335. };
  336. #endif
  337. #if !defined(WIN_PTHREADS_TIME_H)
  338. #define MUST_IMPLEMENT_CLOCK_GETTIME
  339. #endif
  340. #ifdef MUST_IMPLEMENT_CLOCK_GETTIME
  341. #define clock_gettime mg_clock_gettime
  342. static int
  343. clock_gettime(clockid_t clk_id, struct timespec *tp)
  344. {
  345. FILETIME ft;
  346. ULARGE_INTEGER li;
  347. BOOL ok = FALSE;
  348. double d;
  349. static double perfcnt_per_sec = 0.0;
  350. if (tp) {
  351. memset(tp, 0, sizeof(*tp));
  352. if (clk_id == CLOCK_REALTIME) {
  353. GetSystemTimeAsFileTime(&ft);
  354. li.LowPart = ft.dwLowDateTime;
  355. li.HighPart = ft.dwHighDateTime;
  356. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  357. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  358. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  359. ok = TRUE;
  360. } else if (clk_id == CLOCK_MONOTONIC) {
  361. if (perfcnt_per_sec == 0.0) {
  362. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  363. perfcnt_per_sec = 1.0 / li.QuadPart;
  364. }
  365. if (perfcnt_per_sec != 0.0) {
  366. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  367. d = li.QuadPart * perfcnt_per_sec;
  368. tp->tv_sec = (time_t)d;
  369. d -= tp->tv_sec;
  370. tp->tv_nsec = (long)(d * 1.0E9);
  371. ok = TRUE;
  372. }
  373. }
  374. }
  375. return ok ? 0 : -1;
  376. }
  377. #endif
  378. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  379. static int pthread_mutex_lock(pthread_mutex_t *);
  380. static int pthread_mutex_unlock(pthread_mutex_t *);
  381. static void path_to_unicode(const struct mg_connection *conn,
  382. const char *path,
  383. wchar_t *wbuf,
  384. size_t wbuf_len);
  385. /* All file operations need to be rewritten to solve #246. */
  386. #include "file_ops.inl"
  387. struct mg_file;
  388. static const char *
  389. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p);
  390. /* POSIX dirent interface */
  391. struct dirent {
  392. char d_name[PATH_MAX];
  393. };
  394. typedef struct DIR {
  395. HANDLE handle;
  396. WIN32_FIND_DATAW info;
  397. struct dirent result;
  398. } DIR;
  399. #if defined(_WIN32) && !defined(POLLIN)
  400. #ifndef HAVE_POLL
  401. struct pollfd {
  402. SOCKET fd;
  403. short events;
  404. short revents;
  405. };
  406. #define POLLIN (0x0300)
  407. #endif
  408. #endif
  409. /* Mark required libraries */
  410. #if defined(_MSC_VER)
  411. #pragma comment(lib, "Ws2_32.lib")
  412. #endif
  413. #else /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  414. WINDOWS / UNIX include block */
  415. #include <sys/wait.h>
  416. #include <sys/socket.h>
  417. #include <sys/poll.h>
  418. #include <netinet/in.h>
  419. #include <arpa/inet.h>
  420. #include <sys/time.h>
  421. #include <sys/utsname.h>
  422. #include <stdint.h>
  423. #include <inttypes.h>
  424. #include <netdb.h>
  425. #include <netinet/tcp.h>
  426. typedef const void *SOCK_OPT_TYPE;
  427. #if defined(ANDROID)
  428. typedef unsigned short int in_port_t;
  429. #endif
  430. #include <pwd.h>
  431. #include <unistd.h>
  432. #include <grp.h>
  433. #include <dirent.h>
  434. #define vsnprintf_impl vsnprintf
  435. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  436. #include <dlfcn.h>
  437. #endif
  438. #include <pthread.h>
  439. #if defined(__MACH__)
  440. #define SSL_LIB "libssl.dylib"
  441. #define CRYPTO_LIB "libcrypto.dylib"
  442. #else
  443. #if !defined(SSL_LIB)
  444. #define SSL_LIB "libssl.so"
  445. #endif
  446. #if !defined(CRYPTO_LIB)
  447. #define CRYPTO_LIB "libcrypto.so"
  448. #endif
  449. #endif
  450. #ifndef O_BINARY
  451. #define O_BINARY (0)
  452. #endif /* O_BINARY */
  453. #define closesocket(a) (close(a))
  454. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  455. #define mg_remove(conn, x) (remove(x))
  456. #define mg_sleep(x) (usleep((x)*1000))
  457. #define mg_opendir(conn, x) (opendir(x))
  458. #define mg_closedir(x) (closedir(x))
  459. #define mg_readdir(x) (readdir(x))
  460. #define ERRNO (errno)
  461. #define INVALID_SOCKET (-1)
  462. #define INT64_FMT PRId64
  463. #define UINT64_FMT PRIu64
  464. typedef int SOCKET;
  465. #define WINCDECL
  466. #if defined(__hpux)
  467. /* HPUX 11 does not have monotonic, fall back to realtime */
  468. #ifndef CLOCK_MONOTONIC
  469. #define CLOCK_MONOTONIC CLOCK_REALTIME
  470. #endif
  471. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  472. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  473. * the prototypes use int* rather than socklen_t* which matches the
  474. * actual library expectation. When called with the wrong size arg
  475. * accept() returns a zero client inet addr and check_acl() always
  476. * fails. Since socklen_t is widely used below, just force replace
  477. * their typedef with int. - DTL
  478. */
  479. #define socklen_t int
  480. #endif /* hpux */
  481. #endif /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  482. WINDOWS / UNIX include block */
  483. /* va_copy should always be a macro, C99 and C++11 - DTL */
  484. #ifndef va_copy
  485. #define va_copy(x, y) ((x) = (y))
  486. #endif
  487. #ifdef _WIN32
  488. /* Create substitutes for POSIX functions in Win32. */
  489. #if defined(__MINGW32__)
  490. /* Show no warning in case system functions are not used. */
  491. #pragma GCC diagnostic push
  492. #pragma GCC diagnostic ignored "-Wunused-function"
  493. #endif
  494. static CRITICAL_SECTION global_log_file_lock;
  495. static DWORD
  496. pthread_self(void)
  497. {
  498. return GetCurrentThreadId();
  499. }
  500. static int
  501. pthread_key_create(
  502. pthread_key_t *key,
  503. void (*_ignored)(void *) /* destructor not supported for Windows */
  504. )
  505. {
  506. (void)_ignored;
  507. if ((key != 0)) {
  508. *key = TlsAlloc();
  509. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  510. }
  511. return -2;
  512. }
  513. static int
  514. pthread_key_delete(pthread_key_t key)
  515. {
  516. return TlsFree(key) ? 0 : 1;
  517. }
  518. static int
  519. pthread_setspecific(pthread_key_t key, void *value)
  520. {
  521. return TlsSetValue(key, value) ? 0 : 1;
  522. }
  523. static void *
  524. pthread_getspecific(pthread_key_t key)
  525. {
  526. return TlsGetValue(key);
  527. }
  528. #if defined(__MINGW32__)
  529. /* Enable unused function warning again */
  530. #pragma GCC diagnostic pop
  531. #endif
  532. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  533. #else
  534. static pthread_mutexattr_t pthread_mutex_attr;
  535. #endif /* _WIN32 */
  536. #define PASSWORDS_FILE_NAME ".htpasswd"
  537. #define CGI_ENVIRONMENT_SIZE (4096)
  538. #define MAX_CGI_ENVIR_VARS (256)
  539. #define MG_BUF_LEN (8192)
  540. #ifndef MAX_REQUEST_SIZE
  541. #define MAX_REQUEST_SIZE (16384)
  542. #endif
  543. mg_static_assert(MAX_REQUEST_SIZE >= 256,
  544. "request size length must be a positive number");
  545. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  546. #if defined(_WIN32_WCE)
  547. /* Create substitutes for POSIX functions in Win32. */
  548. #if defined(__MINGW32__)
  549. /* Show no warning in case system functions are not used. */
  550. #pragma GCC diagnostic push
  551. #pragma GCC diagnostic ignored "-Wunused-function"
  552. #endif
  553. static time_t
  554. time(time_t *ptime)
  555. {
  556. time_t t;
  557. SYSTEMTIME st;
  558. FILETIME ft;
  559. GetSystemTime(&st);
  560. SystemTimeToFileTime(&st, &ft);
  561. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  562. if (ptime != NULL) {
  563. *ptime = t;
  564. }
  565. return t;
  566. }
  567. static struct tm *
  568. localtime_s(const time_t *ptime, struct tm *ptm)
  569. {
  570. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  571. FILETIME ft, lft;
  572. SYSTEMTIME st;
  573. TIME_ZONE_INFORMATION tzinfo;
  574. if (ptm == NULL) {
  575. return NULL;
  576. }
  577. *(int64_t *)&ft = t;
  578. FileTimeToLocalFileTime(&ft, &lft);
  579. FileTimeToSystemTime(&lft, &st);
  580. ptm->tm_year = st.wYear - 1900;
  581. ptm->tm_mon = st.wMonth - 1;
  582. ptm->tm_wday = st.wDayOfWeek;
  583. ptm->tm_mday = st.wDay;
  584. ptm->tm_hour = st.wHour;
  585. ptm->tm_min = st.wMinute;
  586. ptm->tm_sec = st.wSecond;
  587. ptm->tm_yday = 0; /* hope nobody uses this */
  588. ptm->tm_isdst =
  589. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  590. return ptm;
  591. }
  592. static struct tm *
  593. gmtime_s(const time_t *ptime, struct tm *ptm)
  594. {
  595. /* FIXME(lsm): fix this. */
  596. return localtime_s(ptime, ptm);
  597. }
  598. static int mg_atomic_inc(volatile int *addr);
  599. static struct tm tm_array[MAX_WORKER_THREADS];
  600. static int tm_index = 0;
  601. static struct tm *
  602. localtime(const time_t *ptime)
  603. {
  604. int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0]));
  605. return localtime_s(ptime, tm_array + i);
  606. }
  607. static struct tm *
  608. gmtime(const time_t *ptime)
  609. {
  610. int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  611. return gmtime_s(ptime, tm_array + i);
  612. }
  613. static size_t
  614. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  615. {
  616. /* TODO: (void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  617. * for WinCE"); */
  618. return 0;
  619. }
  620. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  621. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  622. #define remove(f) mg_remove(NULL, f)
  623. static int
  624. rename(const char *a, const char *b)
  625. {
  626. wchar_t wa[PATH_MAX];
  627. wchar_t wb[PATH_MAX];
  628. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  629. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  630. return MoveFileW(wa, wb) ? 0 : -1;
  631. }
  632. struct stat {
  633. int64_t st_size;
  634. time_t st_mtime;
  635. };
  636. static int
  637. stat(const char *name, struct stat *st)
  638. {
  639. wchar_t wbuf[PATH_MAX];
  640. WIN32_FILE_ATTRIBUTE_DATA attr;
  641. time_t creation_time, write_time;
  642. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  643. memset(&attr, 0, sizeof(attr));
  644. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  645. st->st_size =
  646. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  647. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  648. attr.ftLastWriteTime.dwHighDateTime);
  649. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  650. attr.ftCreationTime.dwHighDateTime);
  651. if (creation_time > write_time) {
  652. st->st_mtime = creation_time;
  653. } else {
  654. st->st_mtime = write_time;
  655. }
  656. return 0;
  657. }
  658. #define access(x, a) 1 /* not required anyway */
  659. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  660. /* Values from errno.h in Windows SDK (Visual Studio). */
  661. #define EEXIST 17
  662. #define EACCES 13
  663. #define ENOENT 2
  664. #if defined(__MINGW32__)
  665. /* Enable unused function warning again */
  666. #pragma GCC diagnostic pop
  667. #endif
  668. #endif /* defined(_WIN32_WCE) */
  669. static int
  670. mg_atomic_inc(volatile int *addr)
  671. {
  672. int ret;
  673. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  674. /* Depending on the SDK, this function uses either
  675. * (volatile unsigned int *) or (volatile LONG *),
  676. * so whatever you use, the other SDK is likely to raise a warning. */
  677. ret = InterlockedIncrement((volatile long *)addr);
  678. #elif defined(__GNUC__) \
  679. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  680. ret = __sync_add_and_fetch(addr, 1);
  681. #else
  682. ret = (++(*addr));
  683. #endif
  684. return ret;
  685. }
  686. static int
  687. mg_atomic_dec(volatile int *addr)
  688. {
  689. int ret;
  690. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  691. /* Depending on the SDK, this function uses either
  692. * (volatile unsigned int *) or (volatile LONG *),
  693. * so whatever you use, the other SDK is likely to raise a warning. */
  694. ret = InterlockedDecrement((volatile long *)addr);
  695. #elif defined(__GNUC__) \
  696. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  697. ret = __sync_sub_and_fetch(addr, 1);
  698. #else
  699. ret = (--(*addr));
  700. #endif
  701. return ret;
  702. }
  703. #if defined(MEMORY_DEBUGGING)
  704. static unsigned long mg_memory_debug_blockCount = 0;
  705. static unsigned long mg_memory_debug_totalMemUsed = 0;
  706. static void *
  707. mg_malloc_ex(size_t size, const char *file, unsigned line)
  708. {
  709. void *data = malloc(size + sizeof(size_t));
  710. void *memory = 0;
  711. char mallocStr[256];
  712. if (data) {
  713. *(size_t *)data = size;
  714. mg_memory_debug_totalMemUsed += size;
  715. mg_memory_debug_blockCount++;
  716. memory = (void *)(((char *)data) + sizeof(size_t));
  717. }
  718. sprintf(mallocStr,
  719. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  720. memory,
  721. (unsigned long)size,
  722. mg_memory_debug_totalMemUsed,
  723. mg_memory_debug_blockCount,
  724. file,
  725. line);
  726. #if defined(_WIN32)
  727. OutputDebugStringA(mallocStr);
  728. #else
  729. DEBUG_TRACE("%s", mallocStr);
  730. #endif
  731. return memory;
  732. }
  733. static void *
  734. mg_calloc_ex(size_t count, size_t size, const char *file, unsigned line)
  735. {
  736. void *data = mg_malloc_ex(size * count, file, line);
  737. if (data) {
  738. memset(data, 0, size * count);
  739. }
  740. return data;
  741. }
  742. static void
  743. mg_free_ex(void *memory, const char *file, unsigned line)
  744. {
  745. char mallocStr[256];
  746. void *data = (void *)(((char *)memory) - sizeof(size_t));
  747. size_t size;
  748. if (memory) {
  749. size = *(size_t *)data;
  750. mg_memory_debug_totalMemUsed -= size;
  751. mg_memory_debug_blockCount--;
  752. sprintf(mallocStr,
  753. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  754. memory,
  755. (unsigned long)size,
  756. mg_memory_debug_totalMemUsed,
  757. mg_memory_debug_blockCount,
  758. file,
  759. line);
  760. #if defined(_WIN32)
  761. OutputDebugStringA(mallocStr);
  762. #else
  763. DEBUG_TRACE("%s", mallocStr);
  764. #endif
  765. free(data);
  766. }
  767. }
  768. static void *
  769. mg_realloc_ex(void *memory, size_t newsize, const char *file, unsigned line)
  770. {
  771. char mallocStr[256];
  772. void *data;
  773. void *_realloc;
  774. size_t oldsize;
  775. if (newsize) {
  776. if (memory) {
  777. data = (void *)(((char *)memory) - sizeof(size_t));
  778. oldsize = *(size_t *)data;
  779. _realloc = realloc(data, newsize + sizeof(size_t));
  780. if (_realloc) {
  781. data = _realloc;
  782. mg_memory_debug_totalMemUsed -= oldsize;
  783. sprintf(mallocStr,
  784. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  785. memory,
  786. (unsigned long)oldsize,
  787. mg_memory_debug_totalMemUsed,
  788. mg_memory_debug_blockCount,
  789. file,
  790. line);
  791. #if defined(_WIN32)
  792. OutputDebugStringA(mallocStr);
  793. #else
  794. DEBUG_TRACE("%s", mallocStr);
  795. #endif
  796. mg_memory_debug_totalMemUsed += newsize;
  797. sprintf(mallocStr,
  798. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  799. memory,
  800. (unsigned long)newsize,
  801. mg_memory_debug_totalMemUsed,
  802. mg_memory_debug_blockCount,
  803. file,
  804. line);
  805. #if defined(_WIN32)
  806. OutputDebugStringA(mallocStr);
  807. #else
  808. DEBUG_TRACE("%s", mallocStr);
  809. #endif
  810. *(size_t *)data = newsize;
  811. data = (void *)(((char *)data) + sizeof(size_t));
  812. } else {
  813. #if defined(_WIN32)
  814. OutputDebugStringA("MEM: realloc failed\n");
  815. #else
  816. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  817. #endif
  818. return _realloc;
  819. }
  820. } else {
  821. data = mg_malloc_ex(newsize, file, line);
  822. }
  823. } else {
  824. data = 0;
  825. mg_free_ex(memory, file, line);
  826. }
  827. return data;
  828. }
  829. #define mg_malloc(a) mg_malloc_ex(a, __FILE__, __LINE__)
  830. #define mg_calloc(a, b) mg_calloc_ex(a, b, __FILE__, __LINE__)
  831. #define mg_realloc(a, b) mg_realloc_ex(a, b, __FILE__, __LINE__)
  832. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  833. #else
  834. static __inline void *
  835. mg_malloc(size_t a)
  836. {
  837. return malloc(a);
  838. }
  839. static __inline void *
  840. mg_calloc(size_t a, size_t b)
  841. {
  842. return calloc(a, b);
  843. }
  844. static __inline void *
  845. mg_realloc(void *a, size_t b)
  846. {
  847. return realloc(a, b);
  848. }
  849. static __inline void
  850. mg_free(void *a)
  851. {
  852. free(a);
  853. }
  854. #endif
  855. static void mg_vsnprintf(const struct mg_connection *conn,
  856. int *truncated,
  857. char *buf,
  858. size_t buflen,
  859. const char *fmt,
  860. va_list ap);
  861. static void mg_snprintf(const struct mg_connection *conn,
  862. int *truncated,
  863. char *buf,
  864. size_t buflen,
  865. PRINTF_FORMAT_STRING(const char *fmt),
  866. ...) PRINTF_ARGS(5, 6);
  867. /* This following lines are just meant as a reminder to use the mg-functions
  868. * for memory management */
  869. #ifdef malloc
  870. #undef malloc
  871. #endif
  872. #ifdef calloc
  873. #undef calloc
  874. #endif
  875. #ifdef realloc
  876. #undef realloc
  877. #endif
  878. #ifdef free
  879. #undef free
  880. #endif
  881. #ifdef snprintf
  882. #undef snprintf
  883. #endif
  884. #ifdef vsnprintf
  885. #undef vsnprintf
  886. #endif
  887. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  888. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  889. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  890. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  891. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  892. #ifdef _WIN32 /* vsnprintf must not be used in any system, * \ \ \ \
  893. * but this define only works well for Windows. */
  894. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  895. #endif
  896. static pthread_key_t sTlsKey; /* Thread local storage index */
  897. static int sTlsInit = 0;
  898. static int thread_idx_max = 0;
  899. struct mg_workerTLS {
  900. int is_master;
  901. unsigned long thread_idx;
  902. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  903. HANDLE pthread_cond_helper_mutex;
  904. struct mg_workerTLS *next_waiting_thread;
  905. #endif
  906. };
  907. #if defined(__GNUC__) || defined(__MINGW32__)
  908. /* Show no warning in case system functions are not used. */
  909. #pragma GCC diagnostic push
  910. #pragma GCC diagnostic ignored "-Wunused-function"
  911. #endif
  912. #if defined(__clang__)
  913. /* Show no warning in case system functions are not used. */
  914. #pragma clang diagnostic push
  915. #pragma clang diagnostic ignored "-Wunused-function"
  916. #endif
  917. /* Get a unique thread ID as unsigned long, independent from the data type
  918. * of thread IDs defined by the operating system API.
  919. * If two calls to mg_current_thread_id return the same value, they calls
  920. * are done from the same thread. If they return different values, they are
  921. * done from different threads. (Provided this function is used in the same
  922. * process context and threads are not repeatedly created and deleted, but
  923. * CivetWeb does not do that).
  924. * This function must match the signature required for SSL id callbacks:
  925. * CRYPTO_set_id_callback
  926. */
  927. static unsigned long
  928. mg_current_thread_id(void)
  929. {
  930. #ifdef _WIN32
  931. return GetCurrentThreadId();
  932. #else
  933. #ifdef __clang__
  934. #pragma clang diagnostic push
  935. #pragma clang diagnostic ignored "-Wunreachable-code"
  936. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  937. * or not, so one of the two conditions will be unreachable by construction.
  938. * Unfortunately the C standard does not define a way to check this at
  939. * compile time, since the #if preprocessor conditions can not use the sizeof
  940. * operator as an argument. */
  941. #endif
  942. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  943. /* This is the problematic case for CRYPTO_set_id_callback:
  944. * The OS pthread_t can not be cast to unsigned long. */
  945. struct mg_workerTLS *tls =
  946. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  947. if (tls == NULL) {
  948. /* SSL called from an unknown thread: Create some thread index.
  949. */
  950. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  951. tls->is_master = -2; /* -2 means "3rd party thread" */
  952. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  953. pthread_setspecific(sTlsKey, tls);
  954. }
  955. return tls->thread_idx;
  956. } else {
  957. /* pthread_t may be any data type, so a simple cast to unsigned long
  958. * can rise a warning/error, depending on the platform.
  959. * Here memcpy is used as an anything-to-anything cast. */
  960. unsigned long ret = 0;
  961. pthread_t t = pthread_self();
  962. memcpy(&ret, &t, sizeof(pthread_t));
  963. return ret;
  964. }
  965. #ifdef __clang__
  966. #pragma clang diagnostic pop
  967. #endif
  968. #endif
  969. }
  970. static uint64_t
  971. mg_get_current_time_ns()
  972. {
  973. struct timespec tsnow;
  974. clock_gettime(CLOCK_REALTIME, &tsnow);
  975. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  976. }
  977. #if defined(__GNUC__)
  978. /* Show no warning in case system functions are not used. */
  979. #pragma GCC diagnostic pop
  980. #endif
  981. #if defined(__clang__)
  982. /* Show no warning in case system functions are not used. */
  983. #pragma clang diagnostic pop
  984. #endif
  985. #if !defined(DEBUG_TRACE)
  986. #if defined(DEBUG)
  987. static void DEBUG_TRACE_FUNC(const char *func,
  988. unsigned line,
  989. PRINTF_FORMAT_STRING(const char *fmt),
  990. ...) PRINTF_ARGS(3, 4);
  991. static void
  992. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  993. {
  994. va_list args;
  995. uint64_t nsnow;
  996. static uint64_t nslast;
  997. struct timespec tsnow;
  998. /* Get some operating system independent thread id */
  999. unsigned long thread_id = mg_current_thread_id();
  1000. clock_gettime(CLOCK_REALTIME, &tsnow);
  1001. nsnow = ((uint64_t)tsnow.tv_sec) * ((uint64_t)1000000000)
  1002. + ((uint64_t)tsnow.tv_nsec);
  1003. if (!nslast) {
  1004. nslast = nsnow;
  1005. }
  1006. flockfile(stdout);
  1007. printf("*** %lu.%09lu %12" INT64_FMT " %lu %s:%u: ",
  1008. (unsigned long)tsnow.tv_sec,
  1009. (unsigned long)tsnow.tv_nsec,
  1010. nsnow - nslast,
  1011. thread_id,
  1012. func,
  1013. line);
  1014. va_start(args, fmt);
  1015. vprintf(fmt, args);
  1016. va_end(args);
  1017. putchar('\n');
  1018. fflush(stdout);
  1019. funlockfile(stdout);
  1020. nslast = nsnow;
  1021. }
  1022. #define DEBUG_TRACE(fmt, ...) \
  1023. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  1024. #else
  1025. #define DEBUG_TRACE(fmt, ...) \
  1026. do { \
  1027. } while (0)
  1028. #endif /* DEBUG */
  1029. #endif /* DEBUG_TRACE */
  1030. #define MD5_STATIC static
  1031. #include "md5.inl"
  1032. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1033. #ifdef NO_SOCKLEN_T
  1034. typedef int socklen_t;
  1035. #endif /* NO_SOCKLEN_T */
  1036. #define _DARWIN_UNLIMITED_SELECT
  1037. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1038. #if !defined(MSG_NOSIGNAL)
  1039. #define MSG_NOSIGNAL (0)
  1040. #endif
  1041. #if !defined(SOMAXCONN)
  1042. #define SOMAXCONN (100)
  1043. #endif
  1044. /* Size of the accepted socket queue */
  1045. #if !defined(MGSQLEN)
  1046. #define MGSQLEN (20)
  1047. #endif
  1048. #if defined(NO_SSL)
  1049. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1050. typedef struct SSL_CTX SSL_CTX;
  1051. #else
  1052. #if defined(NO_SSL_DL)
  1053. #include <openssl/ssl.h>
  1054. #include <openssl/err.h>
  1055. #include <openssl/crypto.h>
  1056. #include <openssl/x509.h>
  1057. #include <openssl/pem.h>
  1058. #include <openssl/engine.h>
  1059. #include <openssl/conf.h>
  1060. #include <openssl/dh.h>
  1061. #include <openssl/bn.h>
  1062. #include <openssl/opensslv.h>
  1063. #else
  1064. /* SSL loaded dynamically from DLL.
  1065. * I put the prototypes here to be independent from OpenSSL source
  1066. * installation. */
  1067. typedef struct ssl_st SSL;
  1068. typedef struct ssl_method_st SSL_METHOD;
  1069. typedef struct ssl_ctx_st SSL_CTX;
  1070. typedef struct x509_store_ctx_st X509_STORE_CTX;
  1071. typedef struct x509_name X509_NAME;
  1072. typedef struct asn1_integer ASN1_INTEGER;
  1073. typedef struct bignum BIGNUM;
  1074. typedef struct ossl_init_settings_st OPENSSL_INIT_SETTINGS;
  1075. typedef struct evp_md EVP_MD;
  1076. typedef struct x509 X509;
  1077. #define SSL_CTRL_OPTIONS (32)
  1078. #define SSL_CTRL_CLEAR_OPTIONS (77)
  1079. #define SSL_CTRL_SET_ECDH_AUTO (94)
  1080. #define OPENSSL_INIT_NO_LOAD_SSL_STRINGS 0x00100000L
  1081. #define OPENSSL_INIT_LOAD_SSL_STRINGS 0x00200000L
  1082. #define OPENSSL_INIT_LOAD_CRYPTO_STRINGS 0x00000002L
  1083. #define SSL_VERIFY_NONE (0)
  1084. #define SSL_VERIFY_PEER (1)
  1085. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  1086. #define SSL_VERIFY_CLIENT_ONCE (4)
  1087. #define SSL_OP_ALL ((long)(0x80000BFFUL))
  1088. #define SSL_OP_NO_SSLv2 (0x01000000L)
  1089. #define SSL_OP_NO_SSLv3 (0x02000000L)
  1090. #define SSL_OP_NO_TLSv1 (0x04000000L)
  1091. #define SSL_OP_NO_TLSv1_2 (0x08000000L)
  1092. #define SSL_OP_NO_TLSv1_1 (0x10000000L)
  1093. #define SSL_OP_SINGLE_DH_USE (0x00100000L)
  1094. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000L)
  1095. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000L)
  1096. #define SSL_ERROR_NONE (0)
  1097. #define SSL_ERROR_SSL (1)
  1098. #define SSL_ERROR_WANT_READ (2)
  1099. #define SSL_ERROR_WANT_WRITE (3)
  1100. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  1101. #define SSL_ERROR_SYSCALL (5) /* see errno */
  1102. #define SSL_ERROR_ZERO_RETURN (6)
  1103. #define SSL_ERROR_WANT_CONNECT (7)
  1104. #define SSL_ERROR_WANT_ACCEPT (8)
  1105. struct ssl_func {
  1106. const char *name; /* SSL function name */
  1107. void (*ptr)(void); /* Function pointer */
  1108. };
  1109. #ifdef OPENSSL_API_1_1
  1110. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1111. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1112. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1113. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1114. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1115. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1116. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1117. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  1118. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  1119. #define TLS_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  1120. #define OPENSSL_init_ssl \
  1121. (*(int (*)(uint64_t opts, \
  1122. const OPENSSL_INIT_SETTINGS *settings))ssl_sw[10].ptr)
  1123. #define SSL_CTX_use_PrivateKey_file \
  1124. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1125. #define SSL_CTX_use_certificate_file \
  1126. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1127. #define SSL_CTX_set_default_passwd_cb \
  1128. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1129. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1130. #define SSL_CTX_use_certificate_chain_file \
  1131. (*(int (*)(SSL_CTX *, const char *))ssl_sw[15].ptr)
  1132. #define TLS_client_method (*(SSL_METHOD * (*)(void))ssl_sw[16].ptr)
  1133. #define SSL_pending (*(int (*)(SSL *))ssl_sw[17].ptr)
  1134. #define SSL_CTX_set_verify \
  1135. (*(void (*)(SSL_CTX *, \
  1136. int, \
  1137. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[18].ptr)
  1138. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[19].ptr)
  1139. #define SSL_CTX_load_verify_locations \
  1140. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[20].ptr)
  1141. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[21].ptr)
  1142. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[22].ptr)
  1143. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[23].ptr)
  1144. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[24].ptr)
  1145. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[25].ptr)
  1146. #define SSL_CIPHER_get_name \
  1147. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[26].ptr)
  1148. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[27].ptr)
  1149. #define SSL_CTX_set_session_id_context \
  1150. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[28].ptr)
  1151. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[29].ptr)
  1152. #define SSL_CTX_set_cipher_list \
  1153. (*(int (*)(SSL_CTX *, const char *))ssl_sw[30].ptr)
  1154. #define SSL_CTX_set_options \
  1155. (*(unsigned long (*)(SSL_CTX *, unsigned long))ssl_sw[31].ptr)
  1156. #define SSL_CTX_clear_options(ctx, op) \
  1157. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1158. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1159. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1160. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1161. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1162. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[0].ptr)
  1163. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[1].ptr)
  1164. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[2].ptr)
  1165. #define CONF_modules_unload (*(void (*)(int))crypto_sw[3].ptr)
  1166. #define X509_free (*(void (*)(X509 *))crypto_sw[4].ptr)
  1167. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[5].ptr)
  1168. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[6].ptr)
  1169. #define X509_NAME_oneline \
  1170. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[7].ptr)
  1171. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[8].ptr)
  1172. #define EVP_get_digestbyname \
  1173. (*(const EVP_MD *(*)(const char *))crypto_sw[9].ptr)
  1174. #define EVP_Digest \
  1175. (*(int (*)( \
  1176. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1177. crypto_sw[10].ptr)
  1178. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[11].ptr)
  1179. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[12].ptr)
  1180. #define ASN1_INTEGER_to_BN \
  1181. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn))crypto_sw[13].ptr)
  1182. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[14].ptr)
  1183. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[15].ptr)
  1184. #define OPENSSL_free(a) CRYPTO_free(a)
  1185. /* set_ssl_option() function updates this array.
  1186. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1187. * of respective functions. The macros above (like SSL_connect()) are really
  1188. * just calling these functions indirectly via the pointer. */
  1189. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1190. {"SSL_accept", NULL},
  1191. {"SSL_connect", NULL},
  1192. {"SSL_read", NULL},
  1193. {"SSL_write", NULL},
  1194. {"SSL_get_error", NULL},
  1195. {"SSL_set_fd", NULL},
  1196. {"SSL_new", NULL},
  1197. {"SSL_CTX_new", NULL},
  1198. {"TLS_server_method", NULL},
  1199. {"OPENSSL_init_ssl", NULL},
  1200. {"SSL_CTX_use_PrivateKey_file", NULL},
  1201. {"SSL_CTX_use_certificate_file", NULL},
  1202. {"SSL_CTX_set_default_passwd_cb", NULL},
  1203. {"SSL_CTX_free", NULL},
  1204. {"SSL_CTX_use_certificate_chain_file", NULL},
  1205. {"TLS_client_method", NULL},
  1206. {"SSL_pending", NULL},
  1207. {"SSL_CTX_set_verify", NULL},
  1208. {"SSL_shutdown", NULL},
  1209. {"SSL_CTX_load_verify_locations", NULL},
  1210. {"SSL_CTX_set_default_verify_paths", NULL},
  1211. {"SSL_CTX_set_verify_depth", NULL},
  1212. {"SSL_get_peer_certificate", NULL},
  1213. {"SSL_get_version", NULL},
  1214. {"SSL_get_current_cipher", NULL},
  1215. {"SSL_CIPHER_get_name", NULL},
  1216. {"SSL_CTX_check_private_key", NULL},
  1217. {"SSL_CTX_set_session_id_context", NULL},
  1218. {"SSL_CTX_ctrl", NULL},
  1219. {"SSL_CTX_set_cipher_list", NULL},
  1220. {"SSL_CTX_set_options", NULL},
  1221. {NULL, NULL}};
  1222. /* Similar array as ssl_sw. These functions could be located in different
  1223. * lib. */
  1224. static struct ssl_func crypto_sw[] = {{"ERR_get_error", NULL},
  1225. {"ERR_error_string", NULL},
  1226. {"ERR_remove_state", NULL},
  1227. {"CONF_modules_unload", NULL},
  1228. {"X509_free", NULL},
  1229. {"X509_get_subject_name", NULL},
  1230. {"X509_get_issuer_name", NULL},
  1231. {"X509_NAME_oneline", NULL},
  1232. {"X509_get_serialNumber", NULL},
  1233. {"EVP_get_digestbyname", NULL},
  1234. {"EVP_Digest", NULL},
  1235. {"i2d_X509", NULL},
  1236. {"BN_bn2hex", NULL},
  1237. {"ASN1_INTEGER_to_BN", NULL},
  1238. {"BN_free", NULL},
  1239. {"CRYPTO_free", NULL},
  1240. {NULL, NULL}};
  1241. #else
  1242. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1243. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1244. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1245. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1246. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1247. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1248. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1249. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  1250. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  1251. #define SSLv23_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  1252. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  1253. #define SSL_CTX_use_PrivateKey_file \
  1254. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1255. #define SSL_CTX_use_certificate_file \
  1256. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1257. #define SSL_CTX_set_default_passwd_cb \
  1258. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1259. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1260. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  1261. #define SSL_CTX_use_certificate_chain_file \
  1262. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  1263. #define SSLv23_client_method (*(SSL_METHOD * (*)(void))ssl_sw[17].ptr)
  1264. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  1265. #define SSL_CTX_set_verify \
  1266. (*(void (*)(SSL_CTX *, \
  1267. int, \
  1268. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19].ptr)
  1269. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  1270. #define SSL_CTX_load_verify_locations \
  1271. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  1272. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  1273. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  1274. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[24].ptr)
  1275. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  1276. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[26].ptr)
  1277. #define SSL_CIPHER_get_name \
  1278. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  1279. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  1280. #define SSL_CTX_set_session_id_context \
  1281. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  1282. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  1283. #define SSL_CTX_set_cipher_list \
  1284. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  1285. #define SSL_CTX_set_options(ctx, op) \
  1286. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  1287. #define SSL_CTX_clear_options(ctx, op) \
  1288. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1289. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1290. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1291. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1292. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1293. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  1294. #define CRYPTO_set_locking_callback \
  1295. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  1296. #define CRYPTO_set_id_callback \
  1297. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  1298. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  1299. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  1300. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  1301. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  1302. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  1303. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  1304. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  1305. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  1306. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  1307. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[12].ptr)
  1308. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[13].ptr)
  1309. #define X509_NAME_oneline \
  1310. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  1311. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[15].ptr)
  1312. #define i2c_ASN1_INTEGER \
  1313. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  1314. #define EVP_get_digestbyname \
  1315. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1316. #define EVP_Digest \
  1317. (*(int (*)( \
  1318. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1319. crypto_sw[18].ptr)
  1320. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1321. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[20].ptr)
  1322. #define ASN1_INTEGER_to_BN \
  1323. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn))crypto_sw[21].ptr)
  1324. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[22].ptr)
  1325. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[23].ptr)
  1326. #define OPENSSL_free(a) CRYPTO_free(a)
  1327. /* set_ssl_option() function updates this array.
  1328. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1329. * of respective functions. The macros above (like SSL_connect()) are really
  1330. * just calling these functions indirectly via the pointer. */
  1331. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1332. {"SSL_accept", NULL},
  1333. {"SSL_connect", NULL},
  1334. {"SSL_read", NULL},
  1335. {"SSL_write", NULL},
  1336. {"SSL_get_error", NULL},
  1337. {"SSL_set_fd", NULL},
  1338. {"SSL_new", NULL},
  1339. {"SSL_CTX_new", NULL},
  1340. {"SSLv23_server_method", NULL},
  1341. {"SSL_library_init", NULL},
  1342. {"SSL_CTX_use_PrivateKey_file", NULL},
  1343. {"SSL_CTX_use_certificate_file", NULL},
  1344. {"SSL_CTX_set_default_passwd_cb", NULL},
  1345. {"SSL_CTX_free", NULL},
  1346. {"SSL_load_error_strings", NULL},
  1347. {"SSL_CTX_use_certificate_chain_file", NULL},
  1348. {"SSLv23_client_method", NULL},
  1349. {"SSL_pending", NULL},
  1350. {"SSL_CTX_set_verify", NULL},
  1351. {"SSL_shutdown", NULL},
  1352. {"SSL_CTX_load_verify_locations", NULL},
  1353. {"SSL_CTX_set_default_verify_paths", NULL},
  1354. {"SSL_CTX_set_verify_depth", NULL},
  1355. {"SSL_get_peer_certificate", NULL},
  1356. {"SSL_get_version", NULL},
  1357. {"SSL_get_current_cipher", NULL},
  1358. {"SSL_CIPHER_get_name", NULL},
  1359. {"SSL_CTX_check_private_key", NULL},
  1360. {"SSL_CTX_set_session_id_context", NULL},
  1361. {"SSL_CTX_ctrl", NULL},
  1362. {"SSL_CTX_set_cipher_list", NULL},
  1363. {NULL, NULL}};
  1364. /* Similar array as ssl_sw. These functions could be located in different
  1365. * lib. */
  1366. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  1367. {"CRYPTO_set_locking_callback", NULL},
  1368. {"CRYPTO_set_id_callback", NULL},
  1369. {"ERR_get_error", NULL},
  1370. {"ERR_error_string", NULL},
  1371. {"ERR_remove_state", NULL},
  1372. {"ERR_free_strings", NULL},
  1373. {"ENGINE_cleanup", NULL},
  1374. {"CONF_modules_unload", NULL},
  1375. {"CRYPTO_cleanup_all_ex_data", NULL},
  1376. {"EVP_cleanup", NULL},
  1377. {"X509_free", NULL},
  1378. {"X509_get_subject_name", NULL},
  1379. {"X509_get_issuer_name", NULL},
  1380. {"X509_NAME_oneline", NULL},
  1381. {"X509_get_serialNumber", NULL},
  1382. {"i2c_ASN1_INTEGER", NULL},
  1383. {"EVP_get_digestbyname", NULL},
  1384. {"EVP_Digest", NULL},
  1385. {"i2d_X509", NULL},
  1386. {"BN_bn2hex", NULL},
  1387. {"ASN1_INTEGER_to_BN", NULL},
  1388. {"BN_free", NULL},
  1389. {"CRYPTO_free", NULL},
  1390. {NULL, NULL}};
  1391. #endif /* OPENSSL_API_1_1 */
  1392. #endif /* NO_SSL_DL */
  1393. #endif /* NO_SSL */
  1394. #if !defined(NO_CACHING)
  1395. static const char *month_names[] = {"Jan",
  1396. "Feb",
  1397. "Mar",
  1398. "Apr",
  1399. "May",
  1400. "Jun",
  1401. "Jul",
  1402. "Aug",
  1403. "Sep",
  1404. "Oct",
  1405. "Nov",
  1406. "Dec"};
  1407. #endif /* !NO_CACHING */
  1408. /* Unified socket address. For IPv6 support, add IPv6 address structure in the
  1409. * union u. */
  1410. union usa {
  1411. struct sockaddr sa;
  1412. struct sockaddr_in sin;
  1413. #if defined(USE_IPV6)
  1414. struct sockaddr_in6 sin6;
  1415. #endif
  1416. };
  1417. /* Describes a string (chunk of memory). */
  1418. struct vec {
  1419. const char *ptr;
  1420. size_t len;
  1421. };
  1422. struct mg_file_stat {
  1423. /* File properties filled by mg_stat: */
  1424. uint64_t size;
  1425. time_t last_modified;
  1426. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1427. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1428. * case we need a "Content-Eencoding: gzip" header */
  1429. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1430. };
  1431. struct mg_file_in_memory {
  1432. char *p;
  1433. uint32_t pos;
  1434. char mode;
  1435. };
  1436. struct mg_file_access {
  1437. /* File properties filled by mg_fopen: */
  1438. FILE *fp;
  1439. /* TODO (low): Replace "membuf" implementation by a "file in memory"
  1440. * support library. Use some struct mg_file_in_memory *mf; instead of
  1441. * membuf char pointer. */
  1442. const char *membuf;
  1443. };
  1444. struct mg_file {
  1445. struct mg_file_stat stat;
  1446. struct mg_file_access access;
  1447. };
  1448. #define STRUCT_FILE_INITIALIZER \
  1449. { \
  1450. { \
  1451. (uint64_t)0, (time_t)0, 0, 0, 0 \
  1452. } \
  1453. , \
  1454. { \
  1455. (FILE *) NULL, (const char *)NULL \
  1456. } \
  1457. }
  1458. /* Describes listening socket, or socket which was accept()-ed by the master
  1459. * thread and queued for future handling by the worker thread. */
  1460. struct socket {
  1461. SOCKET sock; /* Listening socket */
  1462. union usa lsa; /* Local socket address */
  1463. union usa rsa; /* Remote socket address */
  1464. unsigned char is_ssl; /* Is port SSL-ed */
  1465. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1466. * port */
  1467. unsigned char in_use; /* Is valid */
  1468. };
  1469. /* NOTE(lsm): this enum shoulds be in sync with the config_options below. */
  1470. enum {
  1471. CGI_EXTENSIONS,
  1472. CGI_ENVIRONMENT,
  1473. PUT_DELETE_PASSWORDS_FILE,
  1474. CGI_INTERPRETER,
  1475. PROTECT_URI,
  1476. AUTHENTICATION_DOMAIN,
  1477. ENABLE_AUTH_DOMAIN_CHECK,
  1478. SSI_EXTENSIONS,
  1479. THROTTLE,
  1480. ACCESS_LOG_FILE,
  1481. ENABLE_DIRECTORY_LISTING,
  1482. ERROR_LOG_FILE,
  1483. GLOBAL_PASSWORDS_FILE,
  1484. INDEX_FILES,
  1485. ENABLE_KEEP_ALIVE,
  1486. ACCESS_CONTROL_LIST,
  1487. EXTRA_MIME_TYPES,
  1488. LISTENING_PORTS,
  1489. DOCUMENT_ROOT,
  1490. SSL_CERTIFICATE,
  1491. SSL_CERTIFICATE_CHAIN,
  1492. NUM_THREADS,
  1493. RUN_AS_USER,
  1494. REWRITE,
  1495. HIDE_FILES,
  1496. REQUEST_TIMEOUT,
  1497. KEEP_ALIVE_TIMEOUT,
  1498. LINGER_TIMEOUT,
  1499. SSL_DO_VERIFY_PEER,
  1500. SSL_CA_PATH,
  1501. SSL_CA_FILE,
  1502. SSL_VERIFY_DEPTH,
  1503. SSL_DEFAULT_VERIFY_PATHS,
  1504. SSL_CIPHER_LIST,
  1505. SSL_PROTOCOL_VERSION,
  1506. SSL_SHORT_TRUST,
  1507. #if defined(USE_WEBSOCKET)
  1508. WEBSOCKET_TIMEOUT,
  1509. #endif
  1510. DECODE_URL,
  1511. #if defined(USE_LUA)
  1512. LUA_PRELOAD_FILE,
  1513. LUA_SCRIPT_EXTENSIONS,
  1514. LUA_SERVER_PAGE_EXTENSIONS,
  1515. #endif
  1516. #if defined(USE_DUKTAPE)
  1517. DUKTAPE_SCRIPT_EXTENSIONS,
  1518. #endif
  1519. #if defined(USE_WEBSOCKET)
  1520. WEBSOCKET_ROOT,
  1521. #endif
  1522. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1523. LUA_WEBSOCKET_EXTENSIONS,
  1524. #endif
  1525. ACCESS_CONTROL_ALLOW_ORIGIN,
  1526. ERROR_PAGES,
  1527. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1528. * socket option typedef TCP_NODELAY. */
  1529. #if !defined(NO_CACHING)
  1530. STATIC_FILE_MAX_AGE,
  1531. #endif
  1532. #if defined(__linux__)
  1533. ALLOW_SENDFILE_CALL,
  1534. #endif
  1535. #if defined(_WIN32)
  1536. CASE_SENSITIVE_FILES,
  1537. #endif
  1538. #if defined(USE_LUA)
  1539. LUA_BACKGROUND_SCRIPT,
  1540. #endif
  1541. NUM_OPTIONS
  1542. };
  1543. /* Config option name, config types, default value */
  1544. static struct mg_option config_options[] = {
  1545. {"cgi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1546. {"cgi_environment", CONFIG_TYPE_STRING, NULL},
  1547. {"put_delete_auth_file", CONFIG_TYPE_FILE, NULL},
  1548. {"cgi_interpreter", CONFIG_TYPE_FILE, NULL},
  1549. {"protect_uri", CONFIG_TYPE_STRING, NULL},
  1550. {"authentication_domain", CONFIG_TYPE_STRING, "mydomain.com"},
  1551. {"enable_auth_domain_check", CONFIG_TYPE_BOOLEAN, "yes"},
  1552. {"ssi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1553. {"throttle", CONFIG_TYPE_STRING, NULL},
  1554. {"access_log_file", CONFIG_TYPE_FILE, NULL},
  1555. {"enable_directory_listing", CONFIG_TYPE_BOOLEAN, "yes"},
  1556. {"error_log_file", CONFIG_TYPE_FILE, NULL},
  1557. {"global_auth_file", CONFIG_TYPE_FILE, NULL},
  1558. {"index_files",
  1559. CONFIG_TYPE_STRING,
  1560. #ifdef USE_LUA
  1561. "index.xhtml,index.html,index.htm,index.lp,index.lsp,index.lua,index.cgi,"
  1562. "index.shtml,index.php"},
  1563. #else
  1564. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1565. #endif
  1566. {"enable_keep_alive", CONFIG_TYPE_BOOLEAN, "no"},
  1567. {"access_control_list", CONFIG_TYPE_STRING, NULL},
  1568. {"extra_mime_types", CONFIG_TYPE_STRING, NULL},
  1569. {"listening_ports", CONFIG_TYPE_STRING, "8080"},
  1570. {"document_root", CONFIG_TYPE_DIRECTORY, NULL},
  1571. {"ssl_certificate", CONFIG_TYPE_FILE, NULL},
  1572. {"ssl_certificate_chain", CONFIG_TYPE_FILE, NULL},
  1573. {"num_threads", CONFIG_TYPE_NUMBER, "50"},
  1574. {"run_as_user", CONFIG_TYPE_STRING, NULL},
  1575. {"url_rewrite_patterns", CONFIG_TYPE_STRING, NULL},
  1576. {"hide_files_patterns", CONFIG_TYPE_EXT_PATTERN, NULL},
  1577. {"request_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1578. {"keep_alive_timeout_ms", CONFIG_TYPE_NUMBER, "500"},
  1579. {"linger_timeout_ms", CONFIG_TYPE_NUMBER, NULL},
  1580. {"ssl_verify_peer", CONFIG_TYPE_BOOLEAN, "no"},
  1581. {"ssl_ca_path", CONFIG_TYPE_DIRECTORY, NULL},
  1582. {"ssl_ca_file", CONFIG_TYPE_FILE, NULL},
  1583. {"ssl_verify_depth", CONFIG_TYPE_NUMBER, "9"},
  1584. {"ssl_default_verify_paths", CONFIG_TYPE_BOOLEAN, "yes"},
  1585. {"ssl_cipher_list", CONFIG_TYPE_STRING, NULL},
  1586. {"ssl_protocol_version", CONFIG_TYPE_NUMBER, "0"},
  1587. {"ssl_short_trust", CONFIG_TYPE_BOOLEAN, "no"},
  1588. #if defined(USE_WEBSOCKET)
  1589. {"websocket_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1590. #endif
  1591. {"decode_url", CONFIG_TYPE_BOOLEAN, "yes"},
  1592. #if defined(USE_LUA)
  1593. {"lua_preload_file", CONFIG_TYPE_FILE, NULL},
  1594. {"lua_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1595. {"lua_server_page_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1596. #endif
  1597. #if defined(USE_DUKTAPE)
  1598. /* The support for duktape is still in alpha version state.
  1599. * The name of this config option might change. */
  1600. {"duktape_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1601. #endif
  1602. #if defined(USE_WEBSOCKET)
  1603. {"websocket_root", CONFIG_TYPE_DIRECTORY, NULL},
  1604. #endif
  1605. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1606. {"lua_websocket_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1607. #endif
  1608. {"access_control_allow_origin", CONFIG_TYPE_STRING, "*"},
  1609. {"error_pages", CONFIG_TYPE_DIRECTORY, NULL},
  1610. {"tcp_nodelay", CONFIG_TYPE_NUMBER, "0"},
  1611. #if !defined(NO_CACHING)
  1612. {"static_file_max_age", CONFIG_TYPE_NUMBER, "3600"},
  1613. #endif
  1614. #if defined(__linux__)
  1615. {"allow_sendfile_call", CONFIG_TYPE_BOOLEAN, "yes"},
  1616. #endif
  1617. #if defined(_WIN32)
  1618. {"case_sensitive", CONFIG_TYPE_BOOLEAN, "no"},
  1619. #endif
  1620. #if defined(USE_LUA)
  1621. {"lua_background_script", CONFIG_TYPE_FILE, NULL},
  1622. #endif
  1623. {NULL, CONFIG_TYPE_UNKNOWN, NULL}};
  1624. /* Check if the config_options and the corresponding enum have compatible
  1625. * sizes. */
  1626. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1627. == (NUM_OPTIONS + 1),
  1628. "config_options and enum not sync");
  1629. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1630. struct mg_handler_info {
  1631. /* Name/Pattern of the URI. */
  1632. char *uri;
  1633. size_t uri_len;
  1634. /* handler type */
  1635. int handler_type;
  1636. /* Handler for http/https or authorization requests. */
  1637. mg_request_handler handler;
  1638. /* Handler for ws/wss (websocket) requests. */
  1639. mg_websocket_connect_handler connect_handler;
  1640. mg_websocket_ready_handler ready_handler;
  1641. mg_websocket_data_handler data_handler;
  1642. mg_websocket_close_handler close_handler;
  1643. /* accepted subprotocols for ws/wss requests. */
  1644. struct mg_websocket_subprotocols *subprotocols;
  1645. /* Handler for authorization requests */
  1646. mg_authorization_handler auth_handler;
  1647. /* User supplied argument for the handler function. */
  1648. void *cbdata;
  1649. /* next handler in a linked list */
  1650. struct mg_handler_info *next;
  1651. };
  1652. struct mg_context {
  1653. volatile int stop_flag; /* Should we stop event loop */
  1654. SSL_CTX *ssl_ctx; /* SSL context */
  1655. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1656. struct mg_callbacks callbacks; /* User-defined callback function */
  1657. void *user_data; /* User-defined data */
  1658. int context_type; /* 1 = server context,
  1659. * 2 = ws/wss client context,
  1660. */
  1661. struct socket *listening_sockets;
  1662. struct pollfd *listening_socket_fds;
  1663. unsigned int num_listening_sockets;
  1664. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  1665. #ifdef ALTERNATIVE_QUEUE
  1666. struct socket *client_socks;
  1667. void **client_wait_events;
  1668. #else
  1669. struct socket queue[MGSQLEN]; /* Accepted sockets */
  1670. volatile int sq_head; /* Head of the socket queue */
  1671. volatile int sq_tail; /* Tail of the socket queue */
  1672. pthread_cond_t sq_full; /* Signaled when socket is produced */
  1673. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  1674. #endif
  1675. pthread_t masterthreadid; /* The master thread ID */
  1676. unsigned int
  1677. cfg_worker_threads; /* The number of configured worker threads. */
  1678. pthread_t *worker_threadids; /* The worker thread IDs */
  1679. struct mg_connection *worker_connections; /* The connection struct, pre-
  1680. * allocated for each worker */
  1681. time_t start_time; /* Server start time, used for authentication */
  1682. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1683. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  1684. unsigned long nonce_count; /* Used nonces, used for authentication */
  1685. char *systemName; /* What operating system is running */
  1686. /* linked list of uri handlers */
  1687. struct mg_handler_info *handlers;
  1688. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1689. /* linked list of shared lua websockets */
  1690. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1691. #endif
  1692. #if defined(USE_TIMERS)
  1693. struct ttimers *timers;
  1694. #endif
  1695. #if defined(USE_LUA)
  1696. void *lua_background_state;
  1697. #endif
  1698. };
  1699. struct mg_connection {
  1700. struct mg_request_info request_info;
  1701. struct mg_context *ctx;
  1702. SSL *ssl; /* SSL descriptor */
  1703. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  1704. struct socket client; /* Connected client */
  1705. time_t conn_birth_time; /* Time (wall clock) when connection was
  1706. * established */
  1707. struct timespec req_time; /* Time (since system start) when the request
  1708. * was received */
  1709. int64_t num_bytes_sent; /* Total bytes sent to client */
  1710. int64_t content_len; /* Content-Length header value */
  1711. int64_t consumed_content; /* How many bytes of content have been read */
  1712. int is_chunked; /* Transfer-Encoding is chunked: 0=no, 1=yes:
  1713. * data available, 2: all data read */
  1714. size_t chunk_remainder; /* Unread data from the last chunk */
  1715. char *buf; /* Buffer for received data */
  1716. char *path_info; /* PATH_INFO part of the URL */
  1717. int must_close; /* 1 if connection must be closed */
  1718. int in_error_handler; /* 1 if in handler for user defined error
  1719. * pages */
  1720. int handled_requests; /* Number of requests handled by this connection */
  1721. int buf_size; /* Buffer size */
  1722. int request_len; /* Size of the request + headers in a buffer */
  1723. int data_len; /* Total size of data in a buffer */
  1724. int status_code; /* HTTP reply status code, e.g. 200 */
  1725. int throttle; /* Throttling, bytes/sec. <= 0 means no
  1726. * throttle */
  1727. time_t last_throttle_time; /* Last time throttled data was sent */
  1728. int64_t last_throttle_bytes; /* Bytes sent this second */
  1729. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  1730. * atomic transmissions for websockets */
  1731. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1732. void *lua_websocket_state; /* Lua_State for a websocket connection */
  1733. #endif
  1734. int thread_index; /* Thread index within ctx */
  1735. };
  1736. /* Directory entry */
  1737. struct de {
  1738. struct mg_connection *conn;
  1739. char *file_name;
  1740. struct mg_file_stat file;
  1741. };
  1742. #if defined(USE_WEBSOCKET)
  1743. static int is_websocket_protocol(const struct mg_connection *conn);
  1744. #else
  1745. #define is_websocket_protocol(conn) (0)
  1746. #endif
  1747. #if !defined(NO_THREAD_NAME)
  1748. #if defined(_WIN32) && defined(_MSC_VER)
  1749. /* Set the thread name for debugging purposes in Visual Studio
  1750. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  1751. */
  1752. #pragma pack(push, 8)
  1753. typedef struct tagTHREADNAME_INFO {
  1754. DWORD dwType; /* Must be 0x1000. */
  1755. LPCSTR szName; /* Pointer to name (in user addr space). */
  1756. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  1757. DWORD dwFlags; /* Reserved for future use, must be zero. */
  1758. } THREADNAME_INFO;
  1759. #pragma pack(pop)
  1760. #elif defined(__linux__)
  1761. #include <sys/prctl.h>
  1762. #include <sys/sendfile.h>
  1763. #include <sys/eventfd.h>
  1764. #if defined(ALTERNATIVE_QUEUE)
  1765. static void *
  1766. event_create(void)
  1767. {
  1768. int ret = eventfd(0, EFD_CLOEXEC);
  1769. if (ret == -1) {
  1770. /* Linux uses -1 on error, Windows NULL. */
  1771. /* However, Linux does not return 0 on success either. */
  1772. return 0;
  1773. }
  1774. return (void *)ret;
  1775. }
  1776. static int
  1777. event_wait(void *eventhdl)
  1778. {
  1779. uint64_t u;
  1780. int s = (int)read((int)eventhdl, &u, sizeof(u));
  1781. if (s != sizeof(uint64_t)) {
  1782. /* error */
  1783. return 0;
  1784. }
  1785. (void)u; /* the value is not required */
  1786. return 1;
  1787. }
  1788. static int
  1789. event_signal(void *eventhdl)
  1790. {
  1791. uint64_t u = 1;
  1792. int s = (int)write((int)eventhdl, &u, sizeof(u));
  1793. if (s != sizeof(uint64_t)) {
  1794. /* error */
  1795. return 0;
  1796. }
  1797. return 1;
  1798. }
  1799. static void
  1800. event_destroy(void *eventhdl)
  1801. {
  1802. close((int)eventhdl);
  1803. }
  1804. #endif
  1805. #endif
  1806. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  1807. struct posix_event {
  1808. pthread_mutex_t mutex;
  1809. pthread_cond_t cond;
  1810. };
  1811. static void *
  1812. event_create(void)
  1813. {
  1814. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  1815. if (ret == 0) {
  1816. /* out of memory */
  1817. return 0;
  1818. }
  1819. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  1820. /* pthread mutex not available */
  1821. mg_free(ret);
  1822. return 0;
  1823. }
  1824. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  1825. /* pthread cond not available */
  1826. pthread_mutex_destroy(&(ret->mutex));
  1827. mg_free(ret);
  1828. return 0;
  1829. }
  1830. return (void *)ret;
  1831. }
  1832. static int
  1833. event_wait(void *eventhdl)
  1834. {
  1835. struct posix_event *ev = (struct posix_event *)eventhdl;
  1836. pthread_mutex_lock(&(ev->mutex));
  1837. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  1838. pthread_mutex_unlock(&(ev->mutex));
  1839. return 1;
  1840. }
  1841. static int
  1842. event_signal(void *eventhdl)
  1843. {
  1844. struct posix_event *ev = (struct posix_event *)eventhdl;
  1845. pthread_mutex_lock(&(ev->mutex));
  1846. pthread_cond_signal(&(ev->cond));
  1847. pthread_mutex_unlock(&(ev->mutex));
  1848. return 1;
  1849. }
  1850. static void
  1851. event_destroy(void *eventhdl)
  1852. {
  1853. struct posix_event *ev = (struct posix_event *)eventhdl;
  1854. pthread_cond_destroy(&(ev->cond));
  1855. pthread_mutex_destroy(&(ev->mutex));
  1856. mg_free(ev);
  1857. }
  1858. #endif
  1859. static void
  1860. mg_set_thread_name(const char *name)
  1861. {
  1862. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  1863. mg_snprintf(
  1864. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  1865. #if defined(_WIN32)
  1866. #if defined(_MSC_VER)
  1867. /* Windows and Visual Studio Compiler */
  1868. __try
  1869. {
  1870. THREADNAME_INFO info;
  1871. info.dwType = 0x1000;
  1872. info.szName = threadName;
  1873. info.dwThreadID = ~0U;
  1874. info.dwFlags = 0;
  1875. RaiseException(0x406D1388,
  1876. 0,
  1877. sizeof(info) / sizeof(ULONG_PTR),
  1878. (ULONG_PTR *)&info);
  1879. }
  1880. __except(EXCEPTION_EXECUTE_HANDLER)
  1881. {
  1882. }
  1883. #elif defined(__MINGW32__)
  1884. /* No option known to set thread name for MinGW */
  1885. #endif
  1886. #elif defined(__GLIBC__) \
  1887. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  1888. /* pthread_setname_np first appeared in glibc in version 2.12*/
  1889. (void)pthread_setname_np(pthread_self(), threadName);
  1890. #elif defined(__linux__)
  1891. /* on linux we can use the old prctl function */
  1892. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  1893. #endif
  1894. }
  1895. #else /* !defined(NO_THREAD_NAME) */
  1896. void
  1897. mg_set_thread_name(const char *threadName)
  1898. {
  1899. }
  1900. #endif
  1901. #if defined(MG_LEGACY_INTERFACE)
  1902. const char **
  1903. mg_get_valid_option_names(void)
  1904. {
  1905. /* This function is deprecated. Use mg_get_valid_options instead. */
  1906. static const char *
  1907. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  1908. int i;
  1909. for (i = 0; config_options[i].name != NULL; i++) {
  1910. data[i * 2] = config_options[i].name;
  1911. data[i * 2 + 1] = config_options[i].default_value;
  1912. }
  1913. return data;
  1914. }
  1915. #endif
  1916. const struct mg_option *
  1917. mg_get_valid_options(void)
  1918. {
  1919. return config_options;
  1920. }
  1921. /* Do not open file (used in is_file_in_memory) */
  1922. #define MG_FOPEN_MODE_NONE (0)
  1923. /* Open file for read only access */
  1924. #define MG_FOPEN_MODE_READ (1)
  1925. /* Open file for writing, create and overwrite */
  1926. #define MG_FOPEN_MODE_WRITE (2)
  1927. /* Open file for writing, create and append */
  1928. #define MG_FOPEN_MODE_APPEND (4)
  1929. /* If a file is in memory, set all "stat" members and the membuf pointer of
  1930. * output filep and return 1, otherwise return 0 and don't modify anything. */
  1931. static int
  1932. open_file_in_memory(const struct mg_connection *conn,
  1933. const char *path,
  1934. struct mg_file *filep,
  1935. int mode)
  1936. {
  1937. #if defined(MG_USE_OPEN_FILE)
  1938. size_t size = 0;
  1939. const char *buf = NULL;
  1940. if (!conn) {
  1941. return 0;
  1942. }
  1943. if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
  1944. return 0;
  1945. }
  1946. if (conn->ctx->callbacks.open_file) {
  1947. buf = conn->ctx->callbacks.open_file(conn, path, &size);
  1948. if (buf != NULL) {
  1949. if (filep == NULL) {
  1950. /* This is a file in memory, but we cannot store the properties
  1951. * now.
  1952. * Called from "is_file_in_memory" function. */
  1953. return 1;
  1954. }
  1955. /* NOTE: override filep->size only on success. Otherwise, it might
  1956. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  1957. filep->access.membuf = buf;
  1958. filep->access.fp = NULL;
  1959. /* Size was set by the callback */
  1960. filep->stat.size = size;
  1961. /* Assume the data may change during runtime by setting
  1962. * last_modified = now */
  1963. filep->stat.last_modified = time(NULL);
  1964. filep->stat.is_directory = 0;
  1965. filep->stat.is_gzipped = 0;
  1966. }
  1967. }
  1968. return (buf != NULL);
  1969. #else
  1970. (void)conn;
  1971. (void)path;
  1972. (void)filep;
  1973. (void)mode;
  1974. return 0;
  1975. #endif
  1976. }
  1977. static int
  1978. is_file_in_memory(const struct mg_connection *conn, const char *path)
  1979. {
  1980. return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
  1981. }
  1982. static int
  1983. is_file_opened(const struct mg_file_access *fileacc)
  1984. {
  1985. if (!fileacc) {
  1986. return 0;
  1987. }
  1988. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  1989. }
  1990. static int mg_stat(const struct mg_connection *conn,
  1991. const char *path,
  1992. struct mg_file_stat *filep);
  1993. /* mg_fopen will open a file either in memory or on the disk.
  1994. * The input parameter path is a string in UTF-8 encoding.
  1995. * The input parameter mode is MG_FOPEN_MODE_*
  1996. * On success, either fp or membuf will be set in the output
  1997. * struct file. All status members will also be set.
  1998. * The function returns 1 on success, 0 on error. */
  1999. static int
  2000. mg_fopen(const struct mg_connection *conn,
  2001. const char *path,
  2002. int mode,
  2003. struct mg_file *filep)
  2004. {
  2005. int found;
  2006. if (!filep) {
  2007. return 0;
  2008. }
  2009. filep->access.fp = NULL;
  2010. filep->access.membuf = NULL;
  2011. if (!is_file_in_memory(conn, path)) {
  2012. /* filep is initialized in mg_stat: all fields with memset to,
  2013. * some fields like size and modification date with values */
  2014. found = mg_stat(conn, path, &(filep->stat));
  2015. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2016. /* file does not exist and will not be created */
  2017. return 0;
  2018. }
  2019. #ifdef _WIN32
  2020. {
  2021. wchar_t wbuf[PATH_MAX];
  2022. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2023. switch (mode) {
  2024. case MG_FOPEN_MODE_READ:
  2025. filep->access.fp = _wfopen(wbuf, L"rb");
  2026. break;
  2027. case MG_FOPEN_MODE_WRITE:
  2028. filep->access.fp = _wfopen(wbuf, L"wb");
  2029. break;
  2030. case MG_FOPEN_MODE_APPEND:
  2031. filep->access.fp = _wfopen(wbuf, L"ab");
  2032. break;
  2033. }
  2034. }
  2035. #else
  2036. /* Linux et al already use unicode. No need to convert. */
  2037. switch (mode) {
  2038. case MG_FOPEN_MODE_READ:
  2039. filep->access.fp = fopen(path, "r");
  2040. break;
  2041. case MG_FOPEN_MODE_WRITE:
  2042. filep->access.fp = fopen(path, "w");
  2043. break;
  2044. case MG_FOPEN_MODE_APPEND:
  2045. filep->access.fp = fopen(path, "a");
  2046. break;
  2047. }
  2048. #endif
  2049. if (!found) {
  2050. /* File did not exist before fopen was called.
  2051. * Maybe it has been created now. Get stat info
  2052. * like creation time now. */
  2053. found = mg_stat(conn, path, &(filep->stat));
  2054. (void)found;
  2055. }
  2056. /* file is on disk */
  2057. return (filep->access.fp != NULL);
  2058. } else {
  2059. /* is_file_in_memory returned true */
  2060. if (open_file_in_memory(conn, path, filep, mode)) {
  2061. /* file is in memory */
  2062. return (filep->access.membuf != NULL);
  2063. }
  2064. }
  2065. /* Open failed */
  2066. return 0;
  2067. }
  2068. /* return 0 on success, just like fclose */
  2069. static int
  2070. mg_fclose(struct mg_file_access *fileacc)
  2071. {
  2072. int ret = -1;
  2073. if (fileacc != NULL) {
  2074. if (fileacc->fp != NULL) {
  2075. ret = fclose(fileacc->fp);
  2076. } else if (fileacc->membuf != NULL) {
  2077. ret = 0;
  2078. }
  2079. /* reset all members of fileacc */
  2080. memset(fileacc, 0, sizeof(*fileacc));
  2081. }
  2082. return ret;
  2083. }
  2084. static void
  2085. mg_strlcpy(register char *dst, register const char *src, size_t n)
  2086. {
  2087. for (; *src != '\0' && n > 1; n--) {
  2088. *dst++ = *src++;
  2089. }
  2090. *dst = '\0';
  2091. }
  2092. static int
  2093. lowercase(const char *s)
  2094. {
  2095. return tolower(*(const unsigned char *)s);
  2096. }
  2097. int
  2098. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2099. {
  2100. int diff = 0;
  2101. if (len > 0) {
  2102. do {
  2103. diff = lowercase(s1++) - lowercase(s2++);
  2104. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2105. }
  2106. return diff;
  2107. }
  2108. int
  2109. mg_strcasecmp(const char *s1, const char *s2)
  2110. {
  2111. int diff;
  2112. do {
  2113. diff = lowercase(s1++) - lowercase(s2++);
  2114. } while (diff == 0 && s1[-1] != '\0');
  2115. return diff;
  2116. }
  2117. static char *
  2118. mg_strndup(const char *ptr, size_t len)
  2119. {
  2120. char *p;
  2121. if ((p = (char *)mg_malloc(len + 1)) != NULL) {
  2122. mg_strlcpy(p, ptr, len + 1);
  2123. }
  2124. return p;
  2125. }
  2126. static char *
  2127. mg_strdup(const char *str)
  2128. {
  2129. return mg_strndup(str, strlen(str));
  2130. }
  2131. static const char *
  2132. mg_strcasestr(const char *big_str, const char *small_str)
  2133. {
  2134. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2135. if (big_len >= small_len) {
  2136. for (i = 0; i <= (big_len - small_len); i++) {
  2137. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2138. return big_str + i;
  2139. }
  2140. }
  2141. }
  2142. return NULL;
  2143. }
  2144. /* Return null terminated string of given maximum length.
  2145. * Report errors if length is exceeded. */
  2146. static void
  2147. mg_vsnprintf(const struct mg_connection *conn,
  2148. int *truncated,
  2149. char *buf,
  2150. size_t buflen,
  2151. const char *fmt,
  2152. va_list ap)
  2153. {
  2154. int n, ok;
  2155. if (buflen == 0) {
  2156. return;
  2157. }
  2158. #ifdef __clang__
  2159. #pragma clang diagnostic push
  2160. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2161. /* Using fmt as a non-literal is intended here, since it is mostly called
  2162. * indirectly by mg_snprintf */
  2163. #endif
  2164. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2165. ok = (n >= 0) && ((size_t)n < buflen);
  2166. #ifdef __clang__
  2167. #pragma clang diagnostic pop
  2168. #endif
  2169. if (ok) {
  2170. if (truncated) {
  2171. *truncated = 0;
  2172. }
  2173. } else {
  2174. if (truncated) {
  2175. *truncated = 1;
  2176. }
  2177. mg_cry(conn,
  2178. "truncating vsnprintf buffer: [%.*s]",
  2179. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2180. buf);
  2181. n = (int)buflen - 1;
  2182. }
  2183. buf[n] = '\0';
  2184. }
  2185. static void
  2186. mg_snprintf(const struct mg_connection *conn,
  2187. int *truncated,
  2188. char *buf,
  2189. size_t buflen,
  2190. const char *fmt,
  2191. ...)
  2192. {
  2193. va_list ap;
  2194. va_start(ap, fmt);
  2195. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2196. va_end(ap);
  2197. }
  2198. static int
  2199. get_option_index(const char *name)
  2200. {
  2201. int i;
  2202. for (i = 0; config_options[i].name != NULL; i++) {
  2203. if (strcmp(config_options[i].name, name) == 0) {
  2204. return i;
  2205. }
  2206. }
  2207. return -1;
  2208. }
  2209. const char *
  2210. mg_get_option(const struct mg_context *ctx, const char *name)
  2211. {
  2212. int i;
  2213. if ((i = get_option_index(name)) == -1) {
  2214. return NULL;
  2215. } else if (!ctx || ctx->config[i] == NULL) {
  2216. return "";
  2217. } else {
  2218. return ctx->config[i];
  2219. }
  2220. }
  2221. struct mg_context *
  2222. mg_get_context(const struct mg_connection *conn)
  2223. {
  2224. return (conn == NULL) ? (struct mg_context *)NULL : (conn->ctx);
  2225. }
  2226. void *
  2227. mg_get_user_data(const struct mg_context *ctx)
  2228. {
  2229. return (ctx == NULL) ? NULL : ctx->user_data;
  2230. }
  2231. void
  2232. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  2233. {
  2234. if (conn != NULL) {
  2235. conn->request_info.conn_data = data;
  2236. }
  2237. }
  2238. void *
  2239. mg_get_user_connection_data(const struct mg_connection *conn)
  2240. {
  2241. if (conn != NULL) {
  2242. return conn->request_info.conn_data;
  2243. }
  2244. return NULL;
  2245. }
  2246. #if defined(MG_LEGACY_INTERFACE)
  2247. /* Deprecated: Use mg_get_server_ports instead. */
  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. #endif
  2268. int
  2269. mg_get_server_ports(const struct mg_context *ctx,
  2270. int size,
  2271. struct mg_server_ports *ports)
  2272. {
  2273. int i, cnt = 0;
  2274. if (size <= 0) {
  2275. return -1;
  2276. }
  2277. memset(ports, 0, sizeof(*ports) * (size_t)size);
  2278. if (!ctx) {
  2279. return -1;
  2280. }
  2281. if (!ctx->listening_sockets) {
  2282. return -1;
  2283. }
  2284. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  2285. ports[cnt].port =
  2286. #if defined(USE_IPV6)
  2287. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2288. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2289. :
  2290. #endif
  2291. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2292. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  2293. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  2294. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  2295. /* IPv4 */
  2296. ports[cnt].protocol = 1;
  2297. cnt++;
  2298. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  2299. /* IPv6 */
  2300. ports[cnt].protocol = 3;
  2301. cnt++;
  2302. }
  2303. }
  2304. return cnt;
  2305. }
  2306. static void
  2307. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  2308. {
  2309. buf[0] = '\0';
  2310. if (!usa) {
  2311. return;
  2312. }
  2313. if (usa->sa.sa_family == AF_INET) {
  2314. getnameinfo(&usa->sa,
  2315. sizeof(usa->sin),
  2316. buf,
  2317. (unsigned)len,
  2318. NULL,
  2319. 0,
  2320. NI_NUMERICHOST);
  2321. }
  2322. #if defined(USE_IPV6)
  2323. else if (usa->sa.sa_family == AF_INET6) {
  2324. getnameinfo(&usa->sa,
  2325. sizeof(usa->sin6),
  2326. buf,
  2327. (unsigned)len,
  2328. NULL,
  2329. 0,
  2330. NI_NUMERICHOST);
  2331. }
  2332. #endif
  2333. }
  2334. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  2335. * included in all responses other than 100, 101, 5xx. */
  2336. static void
  2337. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  2338. {
  2339. struct tm *tm;
  2340. tm = ((t != NULL) ? gmtime(t) : NULL);
  2341. if (tm != NULL) {
  2342. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  2343. } else {
  2344. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  2345. buf[buf_len - 1] = '\0';
  2346. }
  2347. }
  2348. /* difftime for struct timespec. Return value is in seconds. */
  2349. static double
  2350. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  2351. {
  2352. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  2353. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  2354. }
  2355. /* Print error message to the opened error log stream. */
  2356. void
  2357. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  2358. {
  2359. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  2360. va_list ap;
  2361. struct mg_file fi;
  2362. time_t timestamp;
  2363. va_start(ap, fmt);
  2364. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  2365. va_end(ap);
  2366. buf[sizeof(buf) - 1] = 0;
  2367. if (!conn) {
  2368. puts(buf);
  2369. return;
  2370. }
  2371. /* Do not lock when getting the callback value, here and below.
  2372. * I suppose this is fine, since function cannot disappear in the
  2373. * same way string option can. */
  2374. if ((conn->ctx->callbacks.log_message == NULL)
  2375. || (conn->ctx->callbacks.log_message(conn, buf) == 0)) {
  2376. if (conn->ctx->config[ERROR_LOG_FILE] != NULL) {
  2377. if (mg_fopen(conn,
  2378. conn->ctx->config[ERROR_LOG_FILE],
  2379. MG_FOPEN_MODE_APPEND,
  2380. &fi) == 0) {
  2381. fi.access.fp = NULL;
  2382. }
  2383. } else {
  2384. fi.access.fp = NULL;
  2385. }
  2386. if (fi.access.fp != NULL) {
  2387. flockfile(fi.access.fp);
  2388. timestamp = time(NULL);
  2389. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  2390. fprintf(fi.access.fp,
  2391. "[%010lu] [error] [client %s] ",
  2392. (unsigned long)timestamp,
  2393. src_addr);
  2394. if (conn->request_info.request_method != NULL) {
  2395. fprintf(fi.access.fp,
  2396. "%s %s: ",
  2397. conn->request_info.request_method,
  2398. conn->request_info.request_uri);
  2399. }
  2400. fprintf(fi.access.fp, "%s", buf);
  2401. fputc('\n', fi.access.fp);
  2402. fflush(fi.access.fp);
  2403. funlockfile(fi.access.fp);
  2404. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  2405. * mg_cry here anyway ;-) */
  2406. }
  2407. }
  2408. }
  2409. /* Return fake connection structure. Used for logging, if connection
  2410. * is not applicable at the moment of logging. */
  2411. static struct mg_connection *
  2412. fc(struct mg_context *ctx)
  2413. {
  2414. static struct mg_connection fake_connection;
  2415. fake_connection.ctx = ctx;
  2416. return &fake_connection;
  2417. }
  2418. const char *
  2419. mg_version(void)
  2420. {
  2421. return CIVETWEB_VERSION;
  2422. }
  2423. const struct mg_request_info *
  2424. mg_get_request_info(const struct mg_connection *conn)
  2425. {
  2426. if (!conn) {
  2427. return NULL;
  2428. }
  2429. return &conn->request_info;
  2430. }
  2431. int
  2432. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  2433. {
  2434. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  2435. return -1;
  2436. } else {
  2437. int truncated = 0;
  2438. const struct mg_request_info *ri = &conn->request_info;
  2439. #ifdef __clang__
  2440. #pragma clang diagnostic push
  2441. #pragma clang diagnostic ignored "-Wunreachable-code"
  2442. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  2443. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  2444. * unreachable, but splitting into four different #ifdef clauses here is more
  2445. * complicated.
  2446. */
  2447. #endif
  2448. const char *proto =
  2449. (is_websocket_protocol(conn) ? (ri->is_ssl ? "wss" : "ws")
  2450. : (ri->is_ssl ? "https" : "http"));
  2451. #ifdef __clang__
  2452. #pragma clang diagnostic pop
  2453. #endif
  2454. if (ri->local_uri == NULL) {
  2455. return -1;
  2456. }
  2457. if ((ri->request_uri != NULL)
  2458. && strcmp(ri->local_uri, ri->request_uri)) {
  2459. mg_snprintf(conn,
  2460. &truncated,
  2461. buf,
  2462. buflen,
  2463. "%s://%s",
  2464. proto,
  2465. ri->request_uri);
  2466. if (truncated) {
  2467. return -1;
  2468. }
  2469. return 0;
  2470. } else {
  2471. #if defined(USE_IPV6)
  2472. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  2473. int port = is_ipv6 ? htons(conn->client.lsa.sin6.sin6_port)
  2474. : htons(conn->client.lsa.sin.sin_port);
  2475. #else
  2476. int port = htons(conn->client.lsa.sin.sin_port);
  2477. #endif
  2478. int def_port = ri->is_ssl ? 443 : 80;
  2479. int auth_domain_check_enabled =
  2480. conn->ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  2481. && (!strcmp(conn->ctx->config[ENABLE_AUTH_DOMAIN_CHECK],
  2482. "yes"));
  2483. const char *server_domain =
  2484. conn->ctx->config[AUTHENTICATION_DOMAIN];
  2485. char portstr[16];
  2486. char server_ip[48];
  2487. if (port != def_port) {
  2488. sprintf(portstr, ":%u", (unsigned)port);
  2489. } else {
  2490. portstr[0] = 0;
  2491. }
  2492. if (!auth_domain_check_enabled || !server_domain) {
  2493. sockaddr_to_string(server_ip,
  2494. sizeof(server_ip),
  2495. &conn->client.lsa);
  2496. server_domain = server_ip;
  2497. }
  2498. mg_snprintf(conn,
  2499. &truncated,
  2500. buf,
  2501. buflen,
  2502. "%s://%s%s%s",
  2503. proto,
  2504. server_domain,
  2505. portstr,
  2506. ri->local_uri);
  2507. if (truncated) {
  2508. return -1;
  2509. }
  2510. return 0;
  2511. }
  2512. }
  2513. }
  2514. /* Skip the characters until one of the delimiters characters found.
  2515. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  2516. * Advance pointer to buffer to the next word. Return found 0-terminated word.
  2517. * Delimiters can be quoted with quotechar. */
  2518. static char *
  2519. skip_quoted(char **buf,
  2520. const char *delimiters,
  2521. const char *whitespace,
  2522. char quotechar)
  2523. {
  2524. char *p, *begin_word, *end_word, *end_whitespace;
  2525. begin_word = *buf;
  2526. end_word = begin_word + strcspn(begin_word, delimiters);
  2527. /* Check for quotechar */
  2528. if (end_word > begin_word) {
  2529. p = end_word - 1;
  2530. while (*p == quotechar) {
  2531. /* While the delimiter is quoted, look for the next delimiter. */
  2532. /* This happens, e.g., in calls from parse_auth_header,
  2533. * if the user name contains a " character. */
  2534. /* If there is anything beyond end_word, copy it. */
  2535. if (*end_word != '\0') {
  2536. size_t end_off = strcspn(end_word + 1, delimiters);
  2537. memmove(p, end_word, end_off + 1);
  2538. p += end_off; /* p must correspond to end_word - 1 */
  2539. end_word += end_off + 1;
  2540. } else {
  2541. *p = '\0';
  2542. break;
  2543. }
  2544. }
  2545. for (p++; p < end_word; p++) {
  2546. *p = '\0';
  2547. }
  2548. }
  2549. if (*end_word == '\0') {
  2550. *buf = end_word;
  2551. } else {
  2552. #if defined(__GNUC__) || defined(__MINGW32__)
  2553. /* Disable spurious conversion warning for GCC */
  2554. #pragma GCC diagnostic push
  2555. #pragma GCC diagnostic ignored "-Wsign-conversion"
  2556. #endif
  2557. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  2558. #if defined(__GNUC__) || defined(__MINGW32__)
  2559. #pragma GCC diagnostic pop
  2560. #endif
  2561. for (p = end_word; p < end_whitespace; p++) {
  2562. *p = '\0';
  2563. }
  2564. *buf = end_whitespace;
  2565. }
  2566. return begin_word;
  2567. }
  2568. /* Simplified version of skip_quoted without quote char
  2569. * and whitespace == delimiters */
  2570. static char *
  2571. skip(char **buf, const char *delimiters)
  2572. {
  2573. return skip_quoted(buf, delimiters, delimiters, 0);
  2574. }
  2575. /* Return HTTP header value, or NULL if not found. */
  2576. static const char *
  2577. get_header(const struct mg_request_info *ri, const char *name)
  2578. {
  2579. int i;
  2580. if (ri) {
  2581. for (i = 0; i < ri->num_headers; i++) {
  2582. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  2583. return ri->http_headers[i].value;
  2584. }
  2585. }
  2586. }
  2587. return NULL;
  2588. }
  2589. const char *
  2590. mg_get_header(const struct mg_connection *conn, const char *name)
  2591. {
  2592. if (!conn) {
  2593. return NULL;
  2594. }
  2595. return get_header(&conn->request_info, name);
  2596. }
  2597. /* A helper function for traversing a comma separated list of values.
  2598. * It returns a list pointer shifted to the next value, or NULL if the end
  2599. * of the list found.
  2600. * Value is stored in val vector. If value has form "x=y", then eq_val
  2601. * vector is initialized to point to the "y" part, and val vector length
  2602. * is adjusted to point only to "x". */
  2603. static const char *
  2604. next_option(const char *list, struct vec *val, struct vec *eq_val)
  2605. {
  2606. int end;
  2607. reparse:
  2608. if (val == NULL || list == NULL || *list == '\0') {
  2609. /* End of the list */
  2610. list = NULL;
  2611. } else {
  2612. /* Skip over leading LWS */
  2613. while (*list == ' ' || *list == '\t')
  2614. list++;
  2615. val->ptr = list;
  2616. if ((list = strchr(val->ptr, ',')) != NULL) {
  2617. /* Comma found. Store length and shift the list ptr */
  2618. val->len = ((size_t)(list - val->ptr));
  2619. list++;
  2620. } else {
  2621. /* This value is the last one */
  2622. list = val->ptr + strlen(val->ptr);
  2623. val->len = ((size_t)(list - val->ptr));
  2624. }
  2625. /* Adjust length for trailing LWS */
  2626. end = (int)val->len - 1;
  2627. while (end >= 0 && (val->ptr[end] == ' ' || val->ptr[end] == '\t'))
  2628. end--;
  2629. val->len = (size_t)(end + 1);
  2630. if (val->len == 0) {
  2631. /* Ignore any empty entries. */
  2632. goto reparse;
  2633. }
  2634. if (eq_val != NULL) {
  2635. /* Value has form "x=y", adjust pointers and lengths
  2636. * so that val points to "x", and eq_val points to "y". */
  2637. eq_val->len = 0;
  2638. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  2639. if (eq_val->ptr != NULL) {
  2640. eq_val->ptr++; /* Skip over '=' character */
  2641. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  2642. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  2643. }
  2644. }
  2645. }
  2646. return list;
  2647. }
  2648. /* A helper function for checking if a comma separated list of values contains
  2649. * the given option (case insensitvely).
  2650. * 'header' can be NULL, in which case false is returned. */
  2651. static int
  2652. header_has_option(const char *header, const char *option)
  2653. {
  2654. struct vec opt_vec;
  2655. struct vec eq_vec;
  2656. assert(option != NULL);
  2657. assert(option[0] != '\0');
  2658. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  2659. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  2660. return 1;
  2661. }
  2662. return 0;
  2663. }
  2664. /* Perform case-insensitive match of string against pattern */
  2665. static int
  2666. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  2667. {
  2668. const char *or_str;
  2669. size_t i;
  2670. int j, len, res;
  2671. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  2672. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  2673. return (res > 0) ? res : match_prefix(or_str + 1,
  2674. (size_t)((pattern + pattern_len)
  2675. - (or_str + 1)),
  2676. str);
  2677. }
  2678. for (i = 0, j = 0; i < pattern_len; i++, j++) {
  2679. if (pattern[i] == '?' && str[j] != '\0') {
  2680. continue;
  2681. } else if (pattern[i] == '$') {
  2682. return (str[j] == '\0') ? j : -1;
  2683. } else if (pattern[i] == '*') {
  2684. i++;
  2685. if (pattern[i] == '*') {
  2686. i++;
  2687. len = (int)strlen(str + j);
  2688. } else {
  2689. len = (int)strcspn(str + j, "/");
  2690. }
  2691. if (i == pattern_len) {
  2692. return j + len;
  2693. }
  2694. do {
  2695. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  2696. } while (res == -1 && len-- > 0);
  2697. return (res == -1) ? -1 : j + res + len;
  2698. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  2699. return -1;
  2700. }
  2701. }
  2702. return j;
  2703. }
  2704. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  2705. * This function must tolerate situations when connection info is not
  2706. * set up, for example if request parsing failed. */
  2707. static int
  2708. should_keep_alive(const struct mg_connection *conn)
  2709. {
  2710. if (conn != NULL) {
  2711. const char *http_version = conn->request_info.http_version;
  2712. const char *header = mg_get_header(conn, "Connection");
  2713. if (conn->must_close || conn->status_code == 401
  2714. || mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0
  2715. || (header != NULL && !header_has_option(header, "keep-alive"))
  2716. || (header == NULL && http_version
  2717. && 0 != strcmp(http_version, "1.1"))) {
  2718. return 0;
  2719. }
  2720. return 1;
  2721. }
  2722. return 0;
  2723. }
  2724. static int
  2725. should_decode_url(const struct mg_connection *conn)
  2726. {
  2727. if (!conn || !conn->ctx) {
  2728. return 0;
  2729. }
  2730. return (mg_strcasecmp(conn->ctx->config[DECODE_URL], "yes") == 0);
  2731. }
  2732. static const char *
  2733. suggest_connection_header(const struct mg_connection *conn)
  2734. {
  2735. return should_keep_alive(conn) ? "keep-alive" : "close";
  2736. }
  2737. static int
  2738. send_no_cache_header(struct mg_connection *conn)
  2739. {
  2740. /* Send all current and obsolete cache opt-out directives. */
  2741. return mg_printf(conn,
  2742. "Cache-Control: no-cache, no-store, "
  2743. "must-revalidate, private, max-age=0\r\n"
  2744. "Pragma: no-cache\r\n"
  2745. "Expires: 0\r\n");
  2746. }
  2747. static int
  2748. send_static_cache_header(struct mg_connection *conn)
  2749. {
  2750. #if !defined(NO_CACHING)
  2751. /* Read the server config to check how long a file may be cached.
  2752. * The configuration is in seconds. */
  2753. int max_age = atoi(conn->ctx->config[STATIC_FILE_MAX_AGE]);
  2754. if (max_age <= 0) {
  2755. /* 0 means "do not cache". All values <0 are reserved
  2756. * and may be used differently in the future. */
  2757. /* If a file should not be cached, do not only send
  2758. * max-age=0, but also pragmas and Expires headers. */
  2759. return send_no_cache_header(conn);
  2760. }
  2761. /* Use "Cache-Control: max-age" instead of "Expires" header.
  2762. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  2763. /* See also https://www.mnot.net/cache_docs/ */
  2764. /* According to RFC 2616, Section 14.21, caching times should not exceed
  2765. * one year. A year with 365 days corresponds to 31536000 seconds, a leap
  2766. * year to 31622400 seconds. For the moment, we just send whatever has
  2767. * been configured, still the behavior for >1 year should be considered
  2768. * as undefined. */
  2769. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  2770. #else /* NO_CACHING */
  2771. return send_no_cache_header(conn);
  2772. #endif /* !NO_CACHING */
  2773. }
  2774. static int
  2775. send_additional_header(struct mg_connection *conn)
  2776. {
  2777. int i = 0;
  2778. #if 0
  2779. i += mg_printf(conn, "Strict-Transport-Security: max-age=%u\r\n", 3600);
  2780. #endif
  2781. i += mg_printf(conn, "X-Some-Test-Header: %u\r\n", 42);
  2782. return i;
  2783. }
  2784. static void handle_file_based_request(struct mg_connection *conn,
  2785. const char *path,
  2786. struct mg_file *filep);
  2787. const char *
  2788. mg_get_response_code_text(struct mg_connection *conn, int response_code)
  2789. {
  2790. /* See IANA HTTP status code assignment:
  2791. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  2792. */
  2793. switch (response_code) {
  2794. /* RFC2616 Section 10.1 - Informational 1xx */
  2795. case 100:
  2796. return "Continue"; /* RFC2616 Section 10.1.1 */
  2797. case 101:
  2798. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  2799. case 102:
  2800. return "Processing"; /* RFC2518 Section 10.1 */
  2801. /* RFC2616 Section 10.2 - Successful 2xx */
  2802. case 200:
  2803. return "OK"; /* RFC2616 Section 10.2.1 */
  2804. case 201:
  2805. return "Created"; /* RFC2616 Section 10.2.2 */
  2806. case 202:
  2807. return "Accepted"; /* RFC2616 Section 10.2.3 */
  2808. case 203:
  2809. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  2810. case 204:
  2811. return "No Content"; /* RFC2616 Section 10.2.5 */
  2812. case 205:
  2813. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  2814. case 206:
  2815. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  2816. case 207:
  2817. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1 */
  2818. case 208:
  2819. return "Already Reported"; /* RFC5842 Section 7.1 */
  2820. case 226:
  2821. return "IM used"; /* RFC3229 Section 10.4.1 */
  2822. /* RFC2616 Section 10.3 - Redirection 3xx */
  2823. case 300:
  2824. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  2825. case 301:
  2826. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  2827. case 302:
  2828. return "Found"; /* RFC2616 Section 10.3.3 */
  2829. case 303:
  2830. return "See Other"; /* RFC2616 Section 10.3.4 */
  2831. case 304:
  2832. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  2833. case 305:
  2834. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  2835. case 307:
  2836. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  2837. case 308:
  2838. return "Permanent Redirect"; /* RFC7238 Section 3 */
  2839. /* RFC2616 Section 10.4 - Client Error 4xx */
  2840. case 400:
  2841. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  2842. case 401:
  2843. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  2844. case 402:
  2845. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  2846. case 403:
  2847. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  2848. case 404:
  2849. return "Not Found"; /* RFC2616 Section 10.4.5 */
  2850. case 405:
  2851. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  2852. case 406:
  2853. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  2854. case 407:
  2855. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  2856. case 408:
  2857. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  2858. case 409:
  2859. return "Conflict"; /* RFC2616 Section 10.4.10 */
  2860. case 410:
  2861. return "Gone"; /* RFC2616 Section 10.4.11 */
  2862. case 411:
  2863. return "Length Required"; /* RFC2616 Section 10.4.12 */
  2864. case 412:
  2865. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  2866. case 413:
  2867. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  2868. case 414:
  2869. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  2870. case 415:
  2871. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  2872. case 416:
  2873. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17 */
  2874. case 417:
  2875. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  2876. case 421:
  2877. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  2878. case 422:
  2879. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  2880. * Section 11.2 */
  2881. case 423:
  2882. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  2883. case 424:
  2884. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  2885. * Section 11.4 */
  2886. case 426:
  2887. return "Upgrade Required"; /* RFC 2817 Section 4 */
  2888. case 428:
  2889. return "Precondition Required"; /* RFC 6585, Section 3 */
  2890. case 429:
  2891. return "Too Many Requests"; /* RFC 6585, Section 4 */
  2892. case 431:
  2893. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  2894. case 451:
  2895. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  2896. * Section 3 */
  2897. /* RFC2616 Section 10.5 - Server Error 5xx */
  2898. case 500:
  2899. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  2900. case 501:
  2901. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  2902. case 502:
  2903. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  2904. case 503:
  2905. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  2906. case 504:
  2907. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  2908. case 505:
  2909. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  2910. case 506:
  2911. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  2912. case 507:
  2913. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  2914. * Section 11.5 */
  2915. case 508:
  2916. return "Loop Detected"; /* RFC5842 Section 7.1 */
  2917. case 510:
  2918. return "Not Extended"; /* RFC 2774, Section 7 */
  2919. case 511:
  2920. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  2921. /* Other status codes, not shown in the IANA HTTP status code assignment.
  2922. * E.g., "de facto" standards due to common use, ... */
  2923. case 418:
  2924. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  2925. case 419:
  2926. return "Authentication Timeout"; /* common use */
  2927. case 420:
  2928. return "Enhance Your Calm"; /* common use */
  2929. case 440:
  2930. return "Login Timeout"; /* common use */
  2931. case 509:
  2932. return "Bandwidth Limit Exceeded"; /* common use */
  2933. default:
  2934. /* This error code is unknown. This should not happen. */
  2935. if (conn) {
  2936. mg_cry(conn, "Unknown HTTP response code: %u", response_code);
  2937. }
  2938. /* Return at least a category according to RFC 2616 Section 10. */
  2939. if (response_code >= 100 && response_code < 200) {
  2940. /* Unknown informational status code */
  2941. return "Information";
  2942. }
  2943. if (response_code >= 200 && response_code < 300) {
  2944. /* Unknown success code */
  2945. return "Success";
  2946. }
  2947. if (response_code >= 300 && response_code < 400) {
  2948. /* Unknown redirection code */
  2949. return "Redirection";
  2950. }
  2951. if (response_code >= 400 && response_code < 500) {
  2952. /* Unknown request error code */
  2953. return "Client Error";
  2954. }
  2955. if (response_code >= 500 && response_code < 600) {
  2956. /* Unknown server error code */
  2957. return "Server Error";
  2958. }
  2959. /* Response code not even within reasonable range */
  2960. return "";
  2961. }
  2962. }
  2963. void
  2964. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  2965. {
  2966. char buf[MG_BUF_LEN];
  2967. va_list ap;
  2968. int len, i, page_handler_found, scope, truncated, has_body;
  2969. char date[64];
  2970. time_t curtime = time(NULL);
  2971. const char *error_handler = NULL;
  2972. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  2973. const char *error_page_file_ext, *tstr;
  2974. const char *status_text = mg_get_response_code_text(conn, status);
  2975. if (conn == NULL) {
  2976. return;
  2977. }
  2978. conn->status_code = status;
  2979. if (conn->in_error_handler || conn->ctx->callbacks.http_error == NULL
  2980. || conn->ctx->callbacks.http_error(conn, status)) {
  2981. if (!conn->in_error_handler) {
  2982. /* Send user defined error pages, if defined */
  2983. error_handler = conn->ctx->config[ERROR_PAGES];
  2984. error_page_file_ext = conn->ctx->config[INDEX_FILES];
  2985. page_handler_found = 0;
  2986. if (error_handler != NULL) {
  2987. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  2988. switch (scope) {
  2989. case 1: /* Handler for specific error, e.g. 404 error */
  2990. mg_snprintf(conn,
  2991. &truncated,
  2992. buf,
  2993. sizeof(buf) - 32,
  2994. "%serror%03u.",
  2995. error_handler,
  2996. status);
  2997. break;
  2998. case 2: /* Handler for error group, e.g., 5xx error handler
  2999. * for all server errors (500-599) */
  3000. mg_snprintf(conn,
  3001. &truncated,
  3002. buf,
  3003. sizeof(buf) - 32,
  3004. "%serror%01uxx.",
  3005. error_handler,
  3006. status / 100);
  3007. break;
  3008. default: /* Handler for all errors */
  3009. mg_snprintf(conn,
  3010. &truncated,
  3011. buf,
  3012. sizeof(buf) - 32,
  3013. "%serror.",
  3014. error_handler);
  3015. break;
  3016. }
  3017. /* String truncation in buf may only occur if error_handler
  3018. * is too long. This string is from the config, not from a
  3019. * client. */
  3020. (void)truncated;
  3021. len = (int)strlen(buf);
  3022. tstr = strchr(error_page_file_ext, '.');
  3023. while (tstr) {
  3024. for (i = 1; i < 32 && tstr[i] != 0 && tstr[i] != ',';
  3025. i++)
  3026. buf[len + i - 1] = tstr[i];
  3027. buf[len + i - 1] = 0;
  3028. if (mg_stat(conn, buf, &error_page_file.stat)) {
  3029. page_handler_found = 1;
  3030. break;
  3031. }
  3032. tstr = strchr(tstr + i, '.');
  3033. }
  3034. }
  3035. }
  3036. if (page_handler_found) {
  3037. conn->in_error_handler = 1;
  3038. handle_file_based_request(conn, buf, &error_page_file);
  3039. conn->in_error_handler = 0;
  3040. return;
  3041. }
  3042. }
  3043. /* No custom error page. Send default error page. */
  3044. gmt_time_string(date, sizeof(date), &curtime);
  3045. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3046. has_body = (status > 199 && status != 204 && status != 304);
  3047. conn->must_close = 1;
  3048. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  3049. send_no_cache_header(conn);
  3050. send_additional_header(conn);
  3051. if (has_body) {
  3052. mg_printf(conn,
  3053. "%s",
  3054. "Content-Type: text/plain; charset=utf-8\r\n");
  3055. }
  3056. mg_printf(conn,
  3057. "Date: %s\r\n"
  3058. "Connection: close\r\n\r\n",
  3059. date);
  3060. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3061. if (has_body) {
  3062. mg_printf(conn, "Error %d: %s\n", status, status_text);
  3063. if (fmt != NULL) {
  3064. va_start(ap, fmt);
  3065. mg_vsnprintf(conn, NULL, buf, sizeof(buf), fmt, ap);
  3066. va_end(ap);
  3067. mg_write(conn, buf, strlen(buf));
  3068. DEBUG_TRACE("Error %i - [%s]", status, buf);
  3069. }
  3070. } else {
  3071. /* No body allowed. Close the connection. */
  3072. DEBUG_TRACE("Error %i", status);
  3073. }
  3074. }
  3075. }
  3076. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  3077. /* Create substitutes for POSIX functions in Win32. */
  3078. #if defined(__MINGW32__)
  3079. /* Show no warning in case system functions are not used. */
  3080. #pragma GCC diagnostic push
  3081. #pragma GCC diagnostic ignored "-Wunused-function"
  3082. #endif
  3083. static int
  3084. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  3085. {
  3086. (void)unused;
  3087. *mutex = CreateMutex(NULL, FALSE, NULL);
  3088. return (*mutex == NULL) ? -1 : 0;
  3089. }
  3090. static int
  3091. pthread_mutex_destroy(pthread_mutex_t *mutex)
  3092. {
  3093. return (CloseHandle(*mutex) == 0) ? -1 : 0;
  3094. }
  3095. static int
  3096. pthread_mutex_lock(pthread_mutex_t *mutex)
  3097. {
  3098. return (WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0) ? 0 : -1;
  3099. }
  3100. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  3101. static int
  3102. pthread_mutex_trylock(pthread_mutex_t *mutex)
  3103. {
  3104. switch (WaitForSingleObject(*mutex, 0)) {
  3105. case WAIT_OBJECT_0:
  3106. return 0;
  3107. case WAIT_TIMEOUT:
  3108. return -2; /* EBUSY */
  3109. }
  3110. return -1;
  3111. }
  3112. #endif
  3113. static int
  3114. pthread_mutex_unlock(pthread_mutex_t *mutex)
  3115. {
  3116. return (ReleaseMutex(*mutex) == 0) ? -1 : 0;
  3117. }
  3118. static int
  3119. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  3120. {
  3121. (void)unused;
  3122. InitializeCriticalSection(&cv->threadIdSec);
  3123. cv->waiting_thread = NULL;
  3124. return 0;
  3125. }
  3126. static int
  3127. pthread_cond_timedwait(pthread_cond_t *cv,
  3128. pthread_mutex_t *mutex,
  3129. const struct timespec *abstime)
  3130. {
  3131. struct mg_workerTLS **ptls,
  3132. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3133. int ok;
  3134. int64_t nsnow, nswaitabs, nswaitrel;
  3135. DWORD mswaitrel;
  3136. EnterCriticalSection(&cv->threadIdSec);
  3137. /* Add this thread to cv's waiting list */
  3138. ptls = &cv->waiting_thread;
  3139. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  3140. ;
  3141. tls->next_waiting_thread = NULL;
  3142. *ptls = tls;
  3143. LeaveCriticalSection(&cv->threadIdSec);
  3144. if (abstime) {
  3145. nsnow = mg_get_current_time_ns();
  3146. nswaitabs =
  3147. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  3148. nswaitrel = nswaitabs - nsnow;
  3149. if (nswaitrel < 0) {
  3150. nswaitrel = 0;
  3151. }
  3152. mswaitrel = (DWORD)(nswaitrel / 1000000);
  3153. } else {
  3154. mswaitrel = INFINITE;
  3155. }
  3156. pthread_mutex_unlock(mutex);
  3157. ok = (WAIT_OBJECT_0
  3158. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  3159. if (!ok) {
  3160. ok = 1;
  3161. EnterCriticalSection(&cv->threadIdSec);
  3162. ptls = &cv->waiting_thread;
  3163. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  3164. if (*ptls == tls) {
  3165. *ptls = tls->next_waiting_thread;
  3166. ok = 0;
  3167. break;
  3168. }
  3169. }
  3170. LeaveCriticalSection(&cv->threadIdSec);
  3171. if (ok) {
  3172. WaitForSingleObject(tls->pthread_cond_helper_mutex, INFINITE);
  3173. }
  3174. }
  3175. /* This thread has been removed from cv's waiting list */
  3176. pthread_mutex_lock(mutex);
  3177. return ok ? 0 : -1;
  3178. }
  3179. static int
  3180. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  3181. {
  3182. return pthread_cond_timedwait(cv, mutex, NULL);
  3183. }
  3184. static int
  3185. pthread_cond_signal(pthread_cond_t *cv)
  3186. {
  3187. HANDLE wkup = NULL;
  3188. BOOL ok = FALSE;
  3189. EnterCriticalSection(&cv->threadIdSec);
  3190. if (cv->waiting_thread) {
  3191. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  3192. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  3193. ok = SetEvent(wkup);
  3194. assert(ok);
  3195. }
  3196. LeaveCriticalSection(&cv->threadIdSec);
  3197. return ok ? 0 : 1;
  3198. }
  3199. static int
  3200. pthread_cond_broadcast(pthread_cond_t *cv)
  3201. {
  3202. EnterCriticalSection(&cv->threadIdSec);
  3203. while (cv->waiting_thread) {
  3204. pthread_cond_signal(cv);
  3205. }
  3206. LeaveCriticalSection(&cv->threadIdSec);
  3207. return 0;
  3208. }
  3209. static int
  3210. pthread_cond_destroy(pthread_cond_t *cv)
  3211. {
  3212. EnterCriticalSection(&cv->threadIdSec);
  3213. assert(cv->waiting_thread == NULL);
  3214. LeaveCriticalSection(&cv->threadIdSec);
  3215. DeleteCriticalSection(&cv->threadIdSec);
  3216. return 0;
  3217. }
  3218. #ifdef ALTERNATIVE_QUEUE
  3219. static void *
  3220. event_create(void)
  3221. {
  3222. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  3223. }
  3224. static int
  3225. event_wait(void *eventhdl)
  3226. {
  3227. int res = WaitForSingleObject((HANDLE)eventhdl, INFINITE);
  3228. return (res == WAIT_OBJECT_0);
  3229. }
  3230. static int
  3231. event_signal(void *eventhdl)
  3232. {
  3233. return (int)SetEvent((HANDLE)eventhdl);
  3234. }
  3235. static void
  3236. event_destroy(void *eventhdl)
  3237. {
  3238. CloseHandle((HANDLE)eventhdl);
  3239. }
  3240. #endif
  3241. #if defined(__MINGW32__)
  3242. /* Enable unused function warning again */
  3243. #pragma GCC diagnostic pop
  3244. #endif
  3245. /* For Windows, change all slashes to backslashes in path names. */
  3246. static void
  3247. change_slashes_to_backslashes(char *path)
  3248. {
  3249. int i;
  3250. for (i = 0; path[i] != '\0'; i++) {
  3251. if (path[i] == '/') {
  3252. path[i] = '\\';
  3253. }
  3254. /* remove double backslash (check i > 0 to preserve UNC paths,
  3255. * like \\server\file.txt) */
  3256. if ((path[i] == '\\') && (i > 0)) {
  3257. while (path[i + 1] == '\\' || path[i + 1] == '/') {
  3258. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  3259. }
  3260. }
  3261. }
  3262. }
  3263. static int
  3264. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  3265. {
  3266. int diff;
  3267. do {
  3268. diff = tolower(*s1) - tolower(*s2);
  3269. s1++;
  3270. s2++;
  3271. } while (diff == 0 && s1[-1] != '\0');
  3272. return diff;
  3273. }
  3274. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  3275. * wbuf and wbuf_len is a target buffer and its length. */
  3276. static void
  3277. path_to_unicode(const struct mg_connection *conn,
  3278. const char *path,
  3279. wchar_t *wbuf,
  3280. size_t wbuf_len)
  3281. {
  3282. char buf[PATH_MAX], buf2[PATH_MAX];
  3283. wchar_t wbuf2[MAX_PATH + 1];
  3284. DWORD long_len, err;
  3285. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  3286. mg_strlcpy(buf, path, sizeof(buf));
  3287. change_slashes_to_backslashes(buf);
  3288. /* Convert to Unicode and back. If doubly-converted string does not
  3289. * match the original, something is fishy, reject. */
  3290. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  3291. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  3292. WideCharToMultiByte(
  3293. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  3294. if (strcmp(buf, buf2) != 0) {
  3295. wbuf[0] = L'\0';
  3296. }
  3297. /* Windows file systems are not case sensitive, but you can still use
  3298. * uppercase and lowercase letters (on all modern file systems).
  3299. * The server can check if the URI uses the same upper/lowercase
  3300. * letters an the file system, effectively making Windows servers
  3301. * case sensitive (like Linux servers are). It is still not possible
  3302. * to use two files with the same name in different cases on Windows
  3303. * (like /a and /A) - this would be possible in Linux.
  3304. * As a default, Windows is not case sensitive, but the case sensitive
  3305. * file name check can be activated by an additional configuration. */
  3306. if (conn) {
  3307. if (conn->ctx->config[CASE_SENSITIVE_FILES]
  3308. && !mg_strcasecmp(conn->ctx->config[CASE_SENSITIVE_FILES], "yes")) {
  3309. /* Use case sensitive compare function */
  3310. fcompare = wcscmp;
  3311. }
  3312. }
  3313. (void)conn; /* conn is currently unused */
  3314. #if !defined(_WIN32_WCE)
  3315. /* Only accept a full file path, not a Windows short (8.3) path. */
  3316. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  3317. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  3318. if (long_len == 0) {
  3319. err = GetLastError();
  3320. if (err == ERROR_FILE_NOT_FOUND) {
  3321. /* File does not exist. This is not always a problem here. */
  3322. return;
  3323. }
  3324. }
  3325. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  3326. /* Short name is used. */
  3327. wbuf[0] = L'\0';
  3328. }
  3329. #else
  3330. (void)long_len;
  3331. (void)wbuf2;
  3332. (void)err;
  3333. if (strchr(path, '~')) {
  3334. wbuf[0] = L'\0';
  3335. }
  3336. #endif
  3337. }
  3338. /* Windows happily opens files with some garbage at the end of file name.
  3339. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  3340. * "a.cgi", despite one would expect an error back.
  3341. * This function returns non-0 if path ends with some garbage. */
  3342. static int
  3343. path_cannot_disclose_cgi(const char *path)
  3344. {
  3345. static const char *allowed_last_characters = "_-";
  3346. int last = path[strlen(path) - 1];
  3347. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  3348. }
  3349. static int
  3350. mg_stat(const struct mg_connection *conn,
  3351. const char *path,
  3352. struct mg_file_stat *filep)
  3353. {
  3354. wchar_t wbuf[PATH_MAX];
  3355. WIN32_FILE_ATTRIBUTE_DATA info;
  3356. time_t creation_time;
  3357. if (!filep) {
  3358. return 0;
  3359. }
  3360. memset(filep, 0, sizeof(*filep));
  3361. if (conn && is_file_in_memory(conn, path)) {
  3362. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  3363. * memset */
  3364. /* Quick fix (for 1.9.x): */
  3365. /* mg_stat must fill all fields, also for files in memory */
  3366. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  3367. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  3368. filep->size = tmp_file.stat.size;
  3369. filep->location = 2;
  3370. /* TODO: for 1.10: restructure how files in memory are handled */
  3371. filep->last_modified = time(NULL); /* xxxxxxxx */
  3372. /* last_modified = now ... assumes the file may change during runtime,
  3373. * so every mg_fopen call may return different data */
  3374. /* last_modified = conn->ctx.start_time;
  3375. * May be used it the data does not change during runtime. This allows
  3376. * browser caching. Since we do not know, we have to assume the file
  3377. * in memory may change. */
  3378. return 1;
  3379. }
  3380. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3381. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  3382. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  3383. filep->last_modified =
  3384. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  3385. info.ftLastWriteTime.dwHighDateTime);
  3386. /* On Windows, the file creation time can be higher than the
  3387. * modification time, e.g. when a file is copied.
  3388. * Since the Last-Modified timestamp is used for caching
  3389. * it should be based on the most recent timestamp. */
  3390. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  3391. info.ftCreationTime.dwHighDateTime);
  3392. if (creation_time > filep->last_modified) {
  3393. filep->last_modified = creation_time;
  3394. }
  3395. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  3396. /* If file name is fishy, reset the file structure and return
  3397. * error.
  3398. * Note it is important to reset, not just return the error, cause
  3399. * functions like is_file_opened() check the struct. */
  3400. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  3401. memset(filep, 0, sizeof(*filep));
  3402. return 0;
  3403. }
  3404. return 1;
  3405. }
  3406. return 0;
  3407. }
  3408. static int
  3409. mg_remove(const struct mg_connection *conn, const char *path)
  3410. {
  3411. wchar_t wbuf[PATH_MAX];
  3412. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3413. return DeleteFileW(wbuf) ? 0 : -1;
  3414. }
  3415. static int
  3416. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  3417. {
  3418. wchar_t wbuf[PATH_MAX];
  3419. (void)mode;
  3420. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3421. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  3422. }
  3423. /* Create substitutes for POSIX functions in Win32. */
  3424. #if defined(__MINGW32__)
  3425. /* Show no warning in case system functions are not used. */
  3426. #pragma GCC diagnostic push
  3427. #pragma GCC diagnostic ignored "-Wunused-function"
  3428. #endif
  3429. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  3430. static DIR *
  3431. mg_opendir(const struct mg_connection *conn, const char *name)
  3432. {
  3433. DIR *dir = NULL;
  3434. wchar_t wpath[PATH_MAX];
  3435. DWORD attrs;
  3436. if (name == NULL) {
  3437. SetLastError(ERROR_BAD_ARGUMENTS);
  3438. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  3439. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  3440. } else {
  3441. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  3442. attrs = GetFileAttributesW(wpath);
  3443. if (attrs != 0xFFFFFFFF && ((attrs & FILE_ATTRIBUTE_DIRECTORY)
  3444. == FILE_ATTRIBUTE_DIRECTORY)) {
  3445. (void)wcscat(wpath, L"\\*");
  3446. dir->handle = FindFirstFileW(wpath, &dir->info);
  3447. dir->result.d_name[0] = '\0';
  3448. } else {
  3449. mg_free(dir);
  3450. dir = NULL;
  3451. }
  3452. }
  3453. return dir;
  3454. }
  3455. static int
  3456. mg_closedir(DIR *dir)
  3457. {
  3458. int result = 0;
  3459. if (dir != NULL) {
  3460. if (dir->handle != INVALID_HANDLE_VALUE)
  3461. result = FindClose(dir->handle) ? 0 : -1;
  3462. mg_free(dir);
  3463. } else {
  3464. result = -1;
  3465. SetLastError(ERROR_BAD_ARGUMENTS);
  3466. }
  3467. return result;
  3468. }
  3469. static struct dirent *
  3470. mg_readdir(DIR *dir)
  3471. {
  3472. struct dirent *result = 0;
  3473. if (dir) {
  3474. if (dir->handle != INVALID_HANDLE_VALUE) {
  3475. result = &dir->result;
  3476. (void)WideCharToMultiByte(CP_UTF8,
  3477. 0,
  3478. dir->info.cFileName,
  3479. -1,
  3480. result->d_name,
  3481. sizeof(result->d_name),
  3482. NULL,
  3483. NULL);
  3484. if (!FindNextFileW(dir->handle, &dir->info)) {
  3485. (void)FindClose(dir->handle);
  3486. dir->handle = INVALID_HANDLE_VALUE;
  3487. }
  3488. } else {
  3489. SetLastError(ERROR_FILE_NOT_FOUND);
  3490. }
  3491. } else {
  3492. SetLastError(ERROR_BAD_ARGUMENTS);
  3493. }
  3494. return result;
  3495. }
  3496. #ifndef HAVE_POLL
  3497. static int
  3498. poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  3499. {
  3500. struct timeval tv;
  3501. fd_set set;
  3502. unsigned int i;
  3503. int result;
  3504. SOCKET maxfd = 0;
  3505. memset(&tv, 0, sizeof(tv));
  3506. tv.tv_sec = milliseconds / 1000;
  3507. tv.tv_usec = (milliseconds % 1000) * 1000;
  3508. FD_ZERO(&set);
  3509. for (i = 0; i < n; i++) {
  3510. FD_SET((SOCKET)pfd[i].fd, &set);
  3511. pfd[i].revents = 0;
  3512. if (pfd[i].fd > maxfd) {
  3513. maxfd = pfd[i].fd;
  3514. }
  3515. }
  3516. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  3517. for (i = 0; i < n; i++) {
  3518. if (FD_ISSET(pfd[i].fd, &set)) {
  3519. pfd[i].revents = POLLIN;
  3520. }
  3521. }
  3522. }
  3523. /* We should subtract the time used in select from remaining
  3524. * "milliseconds", in particular if called from mg_poll with a
  3525. * timeout quantum.
  3526. * Unfortunately, the remaining time is not stored in "tv" in all
  3527. * implementations, so the result in "tv" must be considered undefined.
  3528. * See http://man7.org/linux/man-pages/man2/select.2.html */
  3529. return result;
  3530. }
  3531. #endif /* HAVE_POLL */
  3532. #if defined(__MINGW32__)
  3533. /* Enable unused function warning again */
  3534. #pragma GCC diagnostic pop
  3535. #endif
  3536. static void
  3537. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  3538. {
  3539. (void)conn; /* Unused. */
  3540. #if defined(_WIN32_WCE)
  3541. (void)sock;
  3542. #else
  3543. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  3544. #endif
  3545. }
  3546. int
  3547. mg_start_thread(mg_thread_func_t f, void *p)
  3548. {
  3549. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3550. /* Compile-time option to control stack size, e.g. -DUSE_STACK_SIZE=16384
  3551. */
  3552. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  3553. == ((uintptr_t)(-1L)))
  3554. ? -1
  3555. : 0);
  3556. #else
  3557. return (
  3558. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  3559. ? -1
  3560. : 0);
  3561. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3562. }
  3563. /* Start a thread storing the thread context. */
  3564. static int
  3565. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  3566. void *p,
  3567. pthread_t *threadidptr)
  3568. {
  3569. uintptr_t uip;
  3570. HANDLE threadhandle;
  3571. int result = -1;
  3572. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  3573. threadhandle = (HANDLE)uip;
  3574. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  3575. *threadidptr = threadhandle;
  3576. result = 0;
  3577. }
  3578. return result;
  3579. }
  3580. /* Wait for a thread to finish. */
  3581. static int
  3582. mg_join_thread(pthread_t threadid)
  3583. {
  3584. int result;
  3585. DWORD dwevent;
  3586. result = -1;
  3587. dwevent = WaitForSingleObject(threadid, INFINITE);
  3588. if (dwevent == WAIT_FAILED) {
  3589. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  3590. } else {
  3591. if (dwevent == WAIT_OBJECT_0) {
  3592. CloseHandle(threadid);
  3593. result = 0;
  3594. }
  3595. }
  3596. return result;
  3597. }
  3598. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  3599. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  3600. /* Create substitutes for POSIX functions in Win32. */
  3601. #if defined(__MINGW32__)
  3602. /* Show no warning in case system functions are not used. */
  3603. #pragma GCC diagnostic push
  3604. #pragma GCC diagnostic ignored "-Wunused-function"
  3605. #endif
  3606. static HANDLE
  3607. dlopen(const char *dll_name, int flags)
  3608. {
  3609. wchar_t wbuf[PATH_MAX];
  3610. (void)flags;
  3611. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  3612. return LoadLibraryW(wbuf);
  3613. }
  3614. static int
  3615. dlclose(void *handle)
  3616. {
  3617. int result;
  3618. if (FreeLibrary((HMODULE)handle) != 0) {
  3619. result = 0;
  3620. } else {
  3621. result = -1;
  3622. }
  3623. return result;
  3624. }
  3625. #if defined(__MINGW32__)
  3626. /* Enable unused function warning again */
  3627. #pragma GCC diagnostic pop
  3628. #endif
  3629. #endif
  3630. #if !defined(NO_CGI)
  3631. #define SIGKILL (0)
  3632. static int
  3633. kill(pid_t pid, int sig_num)
  3634. {
  3635. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  3636. (void)CloseHandle((HANDLE)pid);
  3637. return 0;
  3638. }
  3639. static void
  3640. trim_trailing_whitespaces(char *s)
  3641. {
  3642. char *e = s + strlen(s) - 1;
  3643. while (e > s && isspace(*(unsigned char *)e)) {
  3644. *e-- = '\0';
  3645. }
  3646. }
  3647. static pid_t
  3648. spawn_process(struct mg_connection *conn,
  3649. const char *prog,
  3650. char *envblk,
  3651. char *envp[],
  3652. int fdin[2],
  3653. int fdout[2],
  3654. int fderr[2],
  3655. const char *dir)
  3656. {
  3657. HANDLE me;
  3658. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  3659. cmdline[PATH_MAX], buf[PATH_MAX];
  3660. int truncated;
  3661. struct mg_file file = STRUCT_FILE_INITIALIZER;
  3662. STARTUPINFOA si;
  3663. PROCESS_INFORMATION pi = {0};
  3664. (void)envp;
  3665. memset(&si, 0, sizeof(si));
  3666. si.cb = sizeof(si);
  3667. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  3668. si.wShowWindow = SW_HIDE;
  3669. me = GetCurrentProcess();
  3670. DuplicateHandle(me,
  3671. (HANDLE)_get_osfhandle(fdin[0]),
  3672. me,
  3673. &si.hStdInput,
  3674. 0,
  3675. TRUE,
  3676. DUPLICATE_SAME_ACCESS);
  3677. DuplicateHandle(me,
  3678. (HANDLE)_get_osfhandle(fdout[1]),
  3679. me,
  3680. &si.hStdOutput,
  3681. 0,
  3682. TRUE,
  3683. DUPLICATE_SAME_ACCESS);
  3684. DuplicateHandle(me,
  3685. (HANDLE)_get_osfhandle(fderr[1]),
  3686. me,
  3687. &si.hStdError,
  3688. 0,
  3689. TRUE,
  3690. DUPLICATE_SAME_ACCESS);
  3691. /* Mark handles that should not be inherited. See
  3692. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  3693. */
  3694. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  3695. HANDLE_FLAG_INHERIT,
  3696. 0);
  3697. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  3698. HANDLE_FLAG_INHERIT,
  3699. 0);
  3700. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  3701. HANDLE_FLAG_INHERIT,
  3702. 0);
  3703. /* If CGI file is a script, try to read the interpreter line */
  3704. interp = conn->ctx->config[CGI_INTERPRETER];
  3705. if (interp == NULL) {
  3706. buf[0] = buf[1] = '\0';
  3707. /* Read the first line of the script into the buffer */
  3708. mg_snprintf(
  3709. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  3710. if (truncated) {
  3711. pi.hProcess = (pid_t)-1;
  3712. goto spawn_cleanup;
  3713. }
  3714. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  3715. p = (char *)file.access.membuf;
  3716. mg_fgets(buf, sizeof(buf), &file, &p);
  3717. (void)mg_fclose(&file.access); /* ignore error on read only file */
  3718. buf[sizeof(buf) - 1] = '\0';
  3719. }
  3720. if (buf[0] == '#' && buf[1] == '!') {
  3721. trim_trailing_whitespaces(buf + 2);
  3722. } else {
  3723. buf[2] = '\0';
  3724. }
  3725. interp = buf + 2;
  3726. }
  3727. if (interp[0] != '\0') {
  3728. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  3729. interp = full_interp;
  3730. }
  3731. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  3732. if (interp[0] != '\0') {
  3733. mg_snprintf(conn,
  3734. &truncated,
  3735. cmdline,
  3736. sizeof(cmdline),
  3737. "\"%s\" \"%s\\%s\"",
  3738. interp,
  3739. full_dir,
  3740. prog);
  3741. } else {
  3742. mg_snprintf(conn,
  3743. &truncated,
  3744. cmdline,
  3745. sizeof(cmdline),
  3746. "\"%s\\%s\"",
  3747. full_dir,
  3748. prog);
  3749. }
  3750. if (truncated) {
  3751. pi.hProcess = (pid_t)-1;
  3752. goto spawn_cleanup;
  3753. }
  3754. DEBUG_TRACE("Running [%s]", cmdline);
  3755. if (CreateProcessA(NULL,
  3756. cmdline,
  3757. NULL,
  3758. NULL,
  3759. TRUE,
  3760. CREATE_NEW_PROCESS_GROUP,
  3761. envblk,
  3762. NULL,
  3763. &si,
  3764. &pi) == 0) {
  3765. mg_cry(
  3766. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  3767. pi.hProcess = (pid_t)-1;
  3768. /* goto spawn_cleanup; */
  3769. }
  3770. spawn_cleanup:
  3771. (void)CloseHandle(si.hStdOutput);
  3772. (void)CloseHandle(si.hStdError);
  3773. (void)CloseHandle(si.hStdInput);
  3774. if (pi.hThread != NULL) {
  3775. (void)CloseHandle(pi.hThread);
  3776. }
  3777. return (pid_t)pi.hProcess;
  3778. }
  3779. #endif /* !NO_CGI */
  3780. static int
  3781. set_blocking_mode(SOCKET sock, int blocking)
  3782. {
  3783. unsigned long non_blocking = !blocking;
  3784. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  3785. }
  3786. #else
  3787. static int
  3788. mg_stat(const struct mg_connection *conn,
  3789. const char *path,
  3790. struct mg_file_stat *filep)
  3791. {
  3792. struct stat st;
  3793. if (!filep) {
  3794. return 0;
  3795. }
  3796. memset(filep, 0, sizeof(*filep));
  3797. if (conn && is_file_in_memory(conn, path)) {
  3798. /* Quick fix (for 1.9.x): */
  3799. /* mg_stat must fill all fields, also for files in memory */
  3800. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  3801. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  3802. filep->size = tmp_file.stat.size;
  3803. filep->last_modified = time(NULL);
  3804. filep->location = 2;
  3805. /* TODO: for 1.10: restructure how files in memory are handled */
  3806. return 1;
  3807. }
  3808. if (0 == stat(path, &st)) {
  3809. filep->size = (uint64_t)(st.st_size);
  3810. filep->last_modified = st.st_mtime;
  3811. filep->is_directory = S_ISDIR(st.st_mode);
  3812. return 1;
  3813. }
  3814. return 0;
  3815. }
  3816. static void
  3817. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  3818. {
  3819. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  3820. if (conn) {
  3821. mg_cry(conn,
  3822. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  3823. __func__,
  3824. strerror(ERRNO));
  3825. }
  3826. }
  3827. }
  3828. int
  3829. mg_start_thread(mg_thread_func_t func, void *param)
  3830. {
  3831. pthread_t thread_id;
  3832. pthread_attr_t attr;
  3833. int result;
  3834. (void)pthread_attr_init(&attr);
  3835. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  3836. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3837. /* Compile-time option to control stack size,
  3838. * e.g. -DUSE_STACK_SIZE=16384 */
  3839. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3840. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3841. result = pthread_create(&thread_id, &attr, func, param);
  3842. pthread_attr_destroy(&attr);
  3843. return result;
  3844. }
  3845. /* Start a thread storing the thread context. */
  3846. static int
  3847. mg_start_thread_with_id(mg_thread_func_t func,
  3848. void *param,
  3849. pthread_t *threadidptr)
  3850. {
  3851. pthread_t thread_id;
  3852. pthread_attr_t attr;
  3853. int result;
  3854. (void)pthread_attr_init(&attr);
  3855. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3856. /* Compile-time option to control stack size,
  3857. * e.g. -DUSE_STACK_SIZE=16384 */
  3858. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3859. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  3860. result = pthread_create(&thread_id, &attr, func, param);
  3861. pthread_attr_destroy(&attr);
  3862. if ((result == 0) && (threadidptr != NULL)) {
  3863. *threadidptr = thread_id;
  3864. }
  3865. return result;
  3866. }
  3867. /* Wait for a thread to finish. */
  3868. static int
  3869. mg_join_thread(pthread_t threadid)
  3870. {
  3871. int result;
  3872. result = pthread_join(threadid, NULL);
  3873. return result;
  3874. }
  3875. #ifndef NO_CGI
  3876. static pid_t
  3877. spawn_process(struct mg_connection *conn,
  3878. const char *prog,
  3879. char *envblk,
  3880. char *envp[],
  3881. int fdin[2],
  3882. int fdout[2],
  3883. int fderr[2],
  3884. const char *dir)
  3885. {
  3886. pid_t pid;
  3887. const char *interp;
  3888. (void)envblk;
  3889. if (conn == NULL) {
  3890. return 0;
  3891. }
  3892. if ((pid = fork()) == -1) {
  3893. /* Parent */
  3894. mg_send_http_error(conn,
  3895. 500,
  3896. "Error: Creating CGI process\nfork(): %s",
  3897. strerror(ERRNO));
  3898. } else if (pid == 0) {
  3899. /* Child */
  3900. if (chdir(dir) != 0) {
  3901. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  3902. } else if (dup2(fdin[0], 0) == -1) {
  3903. mg_cry(conn,
  3904. "%s: dup2(%d, 0): %s",
  3905. __func__,
  3906. fdin[0],
  3907. strerror(ERRNO));
  3908. } else if (dup2(fdout[1], 1) == -1) {
  3909. mg_cry(conn,
  3910. "%s: dup2(%d, 1): %s",
  3911. __func__,
  3912. fdout[1],
  3913. strerror(ERRNO));
  3914. } else if (dup2(fderr[1], 2) == -1) {
  3915. mg_cry(conn,
  3916. "%s: dup2(%d, 2): %s",
  3917. __func__,
  3918. fderr[1],
  3919. strerror(ERRNO));
  3920. } else {
  3921. /* Keep stderr and stdout in two different pipes.
  3922. * Stdout will be sent back to the client,
  3923. * stderr should go into a server error log. */
  3924. (void)close(fdin[0]);
  3925. (void)close(fdout[1]);
  3926. (void)close(fderr[1]);
  3927. /* Close write end fdin and read end fdout and fderr */
  3928. (void)close(fdin[1]);
  3929. (void)close(fdout[0]);
  3930. (void)close(fderr[0]);
  3931. /* After exec, all signal handlers are restored to their default
  3932. * values, with one exception of SIGCHLD. According to
  3933. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler will
  3934. * leave unchanged after exec if it was set to be ignored. Restore
  3935. * it to default action. */
  3936. signal(SIGCHLD, SIG_DFL);
  3937. interp = conn->ctx->config[CGI_INTERPRETER];
  3938. if (interp == NULL) {
  3939. (void)execle(prog, prog, NULL, envp);
  3940. mg_cry(conn,
  3941. "%s: execle(%s): %s",
  3942. __func__,
  3943. prog,
  3944. strerror(ERRNO));
  3945. } else {
  3946. (void)execle(interp, interp, prog, NULL, envp);
  3947. mg_cry(conn,
  3948. "%s: execle(%s %s): %s",
  3949. __func__,
  3950. interp,
  3951. prog,
  3952. strerror(ERRNO));
  3953. }
  3954. }
  3955. exit(EXIT_FAILURE);
  3956. }
  3957. return pid;
  3958. }
  3959. #endif /* !NO_CGI */
  3960. static int
  3961. set_blocking_mode(SOCKET sock, int blocking)
  3962. {
  3963. int flags;
  3964. flags = fcntl(sock, F_GETFL, 0);
  3965. if (blocking) {
  3966. (void)fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  3967. } else {
  3968. (void)fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK)));
  3969. }
  3970. return 0;
  3971. }
  3972. #endif /* _WIN32 */
  3973. /* End of initial operating system specific define block. */
  3974. /* Get a random number (independent of C rand function) */
  3975. static uint64_t
  3976. get_random(void)
  3977. {
  3978. static uint64_t lfsr = 0; /* Linear feedback shift register */
  3979. static uint64_t lcg = 0; /* Linear congruential generator */
  3980. uint64_t now = mg_get_current_time_ns();
  3981. if (lfsr == 0) {
  3982. /* lfsr will be only 0 if has not been initialized,
  3983. * so this code is called only once. */
  3984. lfsr = mg_get_current_time_ns();
  3985. lcg = mg_get_current_time_ns();
  3986. } else {
  3987. /* Get the next step of both random number generators. */
  3988. lfsr = (lfsr >> 1)
  3989. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  3990. << 63);
  3991. lcg = lcg * 6364136223846793005 + 1442695040888963407;
  3992. }
  3993. /* Combining two pseudo-random number generators and a high resolution part
  3994. * of the current server time will make it hard (impossible?) to guess the
  3995. * next number. */
  3996. return (lfsr ^ lcg ^ now);
  3997. }
  3998. static int
  3999. mg_poll(struct pollfd *pfd,
  4000. unsigned int n,
  4001. int milliseconds,
  4002. volatile int *stop_server)
  4003. {
  4004. int ms_now, result;
  4005. /* Call poll, but only for a maximum time of a few seconds.
  4006. * This will allow to stop the server after some seconds, instead
  4007. * of having to wait for a long socket timeout. */
  4008. ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  4009. do {
  4010. if (*stop_server) {
  4011. /* Shut down signal */
  4012. return -2;
  4013. }
  4014. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  4015. ms_now = milliseconds;
  4016. }
  4017. result = poll(pfd, n, ms_now);
  4018. if (result != 0) {
  4019. /* Poll returned either success (1) or error (-1).
  4020. * Forward both to the caller. */
  4021. return result;
  4022. }
  4023. /* Poll returned timeout (0). */
  4024. if (milliseconds > 0) {
  4025. milliseconds -= ms_now;
  4026. }
  4027. } while (milliseconds != 0);
  4028. return result;
  4029. }
  4030. /* Write data to the IO channel - opened file descriptor, socket or SSL
  4031. * descriptor. Return number of bytes written. */
  4032. static int
  4033. push(struct mg_context *ctx,
  4034. FILE *fp,
  4035. SOCKET sock,
  4036. SSL *ssl,
  4037. const char *buf,
  4038. int len,
  4039. double timeout)
  4040. {
  4041. uint64_t start = 0, now = 0, timeout_ns = 0;
  4042. int n, err;
  4043. #ifdef _WIN32
  4044. typedef int len_t;
  4045. #else
  4046. typedef size_t len_t;
  4047. #endif
  4048. if (timeout > 0) {
  4049. start = mg_get_current_time_ns();
  4050. timeout_ns = (uint64_t)(timeout * 1.0E9);
  4051. }
  4052. if (ctx == NULL) {
  4053. return -1;
  4054. }
  4055. #ifdef NO_SSL
  4056. if (ssl) {
  4057. return -1;
  4058. }
  4059. #endif
  4060. do {
  4061. #ifndef NO_SSL
  4062. if (ssl != NULL) {
  4063. n = SSL_write(ssl, buf, len);
  4064. if (n <= 0) {
  4065. err = SSL_get_error(ssl, n);
  4066. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  4067. err = ERRNO;
  4068. } else if ((err == SSL_ERROR_WANT_READ)
  4069. || (err == SSL_ERROR_WANT_WRITE)) {
  4070. n = 0;
  4071. } else {
  4072. DEBUG_TRACE("SSL_write() failed, error %d", err);
  4073. return -1;
  4074. }
  4075. } else {
  4076. err = 0;
  4077. }
  4078. } else
  4079. #endif
  4080. if (fp != NULL) {
  4081. n = (int)fwrite(buf, 1, (size_t)len, fp);
  4082. if (ferror(fp)) {
  4083. n = -1;
  4084. err = ERRNO;
  4085. } else {
  4086. err = 0;
  4087. }
  4088. } else {
  4089. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  4090. err = (n < 0) ? ERRNO : 0;
  4091. #ifdef _WIN32
  4092. if (err == WSAEWOULDBLOCK) {
  4093. err = 0;
  4094. n = 0;
  4095. }
  4096. #else
  4097. if (err == EWOULDBLOCK) {
  4098. err = 0;
  4099. n = 0;
  4100. }
  4101. #endif
  4102. if (n < 0) {
  4103. /* shutdown of the socket at client side */
  4104. return -1;
  4105. }
  4106. }
  4107. if (ctx->stop_flag) {
  4108. return -1;
  4109. }
  4110. if ((n > 0) || (n == 0 && len == 0)) {
  4111. /* some data has been read, or no data was requested */
  4112. return n;
  4113. }
  4114. if (n < 0) {
  4115. /* socket error - check errno */
  4116. DEBUG_TRACE("send() failed, error %d", err);
  4117. /* TODO (mid): error handling depending on the error code.
  4118. * These codes are different between Windows and Linux.
  4119. * Currently there is no problem with failing send calls,
  4120. * if there is a reproducible situation, it should be
  4121. * investigated in detail.
  4122. */
  4123. return -1;
  4124. }
  4125. /* Only in case n=0 (timeout), repeat calling the write function */
  4126. if (timeout >= 0) {
  4127. now = mg_get_current_time_ns();
  4128. }
  4129. } while ((timeout <= 0) || ((start - now) <= timeout_ns));
  4130. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  4131. used */
  4132. return -1;
  4133. }
  4134. static int64_t
  4135. push_all(struct mg_context *ctx,
  4136. FILE *fp,
  4137. SOCKET sock,
  4138. SSL *ssl,
  4139. const char *buf,
  4140. int64_t len)
  4141. {
  4142. double timeout = -1.0;
  4143. int64_t n, nwritten = 0;
  4144. if (ctx == NULL) {
  4145. return -1;
  4146. }
  4147. if (ctx->config[REQUEST_TIMEOUT]) {
  4148. timeout = atoi(ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  4149. }
  4150. while (len > 0 && ctx->stop_flag == 0) {
  4151. n = push(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  4152. if (n < 0) {
  4153. if (nwritten == 0) {
  4154. nwritten = n; /* Propagate the error */
  4155. }
  4156. break;
  4157. } else if (n == 0) {
  4158. break; /* No more data to write */
  4159. } else {
  4160. nwritten += n;
  4161. len -= n;
  4162. }
  4163. }
  4164. return nwritten;
  4165. }
  4166. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  4167. * Return value:
  4168. * >=0 .. number of bytes successfully read
  4169. * -1 .. timeout
  4170. * -2 .. error
  4171. */
  4172. static int
  4173. pull_inner(FILE *fp,
  4174. struct mg_connection *conn,
  4175. char *buf,
  4176. int len,
  4177. double timeout)
  4178. {
  4179. int nread, err = 0;
  4180. #ifdef _WIN32
  4181. typedef int len_t;
  4182. #else
  4183. typedef size_t len_t;
  4184. #endif
  4185. #ifndef NO_SSL
  4186. int ssl_pending;
  4187. #endif
  4188. /* We need an additional wait loop around this, because in some cases
  4189. * with TLSwe may get data from the socket but not from SSL_read.
  4190. * In this case we need to repeat at least once.
  4191. */
  4192. if (fp != NULL) {
  4193. #if !defined(_WIN32_WCE)
  4194. /* Use read() instead of fread(), because if we're reading from the
  4195. * CGI pipe, fread() may block until IO buffer is filled up. We
  4196. * cannot afford to block and must pass all read bytes immediately
  4197. * to the client. */
  4198. nread = (int)read(fileno(fp), buf, (size_t)len);
  4199. #else
  4200. /* WinCE does not support CGI pipes */
  4201. nread = (int)fread(buf, 1, (size_t)len, fp);
  4202. #endif
  4203. err = (nread < 0) ? ERRNO : 0;
  4204. #ifndef NO_SSL
  4205. } else if ((conn->ssl != NULL)
  4206. && ((ssl_pending = SSL_pending(conn->ssl)) > 0)) {
  4207. /* We already know there is no more data buffered in conn->buf
  4208. * but there is more available in the SSL layer. So don't poll
  4209. * conn->client.sock yet. */
  4210. if (ssl_pending > len) {
  4211. ssl_pending = len;
  4212. }
  4213. nread = SSL_read(conn->ssl, buf, ssl_pending);
  4214. if (nread <= 0) {
  4215. err = SSL_get_error(conn->ssl, nread);
  4216. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  4217. err = ERRNO;
  4218. } else if ((err == SSL_ERROR_WANT_READ)
  4219. || (err == SSL_ERROR_WANT_WRITE)) {
  4220. nread = 0;
  4221. } else {
  4222. DEBUG_TRACE("SSL_read() failed, error %d", err);
  4223. return -1;
  4224. }
  4225. } else {
  4226. err = 0;
  4227. }
  4228. } else if (conn->ssl != NULL) {
  4229. struct pollfd pfd[1];
  4230. int pollres;
  4231. pfd[0].fd = conn->client.sock;
  4232. pfd[0].events = POLLIN;
  4233. pollres =
  4234. mg_poll(pfd, 1, (int)(timeout * 1000.0), &(conn->ctx->stop_flag));
  4235. if (conn->ctx->stop_flag) {
  4236. return -2;
  4237. }
  4238. if (pollres > 0) {
  4239. nread = SSL_read(conn->ssl, buf, len);
  4240. if (nread <= 0) {
  4241. err = SSL_get_error(conn->ssl, nread);
  4242. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  4243. err = ERRNO;
  4244. } else if ((err == SSL_ERROR_WANT_READ)
  4245. || (err == SSL_ERROR_WANT_WRITE)) {
  4246. nread = 0;
  4247. } else {
  4248. DEBUG_TRACE("SSL_read() failed, error %d", err);
  4249. return -2;
  4250. }
  4251. } else {
  4252. err = 0;
  4253. }
  4254. } else if (pollres < 0) {
  4255. /* Error */
  4256. return -2;
  4257. } else {
  4258. /* pollres = 0 means timeout */
  4259. nread = 0;
  4260. }
  4261. #endif
  4262. } else {
  4263. struct pollfd pfd[1];
  4264. int pollres;
  4265. pfd[0].fd = conn->client.sock;
  4266. pfd[0].events = POLLIN;
  4267. pollres =
  4268. mg_poll(pfd, 1, (int)(timeout * 1000.0), &(conn->ctx->stop_flag));
  4269. if (conn->ctx->stop_flag) {
  4270. return -2;
  4271. }
  4272. if (pollres > 0) {
  4273. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  4274. err = (nread < 0) ? ERRNO : 0;
  4275. if (nread <= 0) {
  4276. /* shutdown of the socket at client side */
  4277. return -2;
  4278. }
  4279. } else if (pollres < 0) {
  4280. /* error callint poll */
  4281. return -2;
  4282. } else {
  4283. /* pollres = 0 means timeout */
  4284. nread = 0;
  4285. }
  4286. }
  4287. if (conn->ctx->stop_flag) {
  4288. return -2;
  4289. }
  4290. if ((nread > 0) || (nread == 0 && len == 0)) {
  4291. /* some data has been read, or no data was requested */
  4292. return nread;
  4293. }
  4294. if (nread < 0) {
  4295. /* socket error - check errno */
  4296. #ifdef _WIN32
  4297. if (err == WSAEWOULDBLOCK) {
  4298. /* TODO (low): check if this is still required */
  4299. /* standard case if called from close_socket_gracefully */
  4300. return -2;
  4301. } else if (err == WSAETIMEDOUT) {
  4302. /* TODO (low): check if this is still required */
  4303. /* timeout is handled by the while loop */
  4304. return 0;
  4305. } else if (err == WSAECONNABORTED) {
  4306. /* See https://www.chilkatsoft.com/p/p_299.asp */
  4307. return -2;
  4308. } else {
  4309. DEBUG_TRACE("recv() failed, error %d", err);
  4310. return -2;
  4311. }
  4312. #else
  4313. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  4314. * if the timeout is reached and if the socket was set to non-
  4315. * blocking in close_socket_gracefully, so we can not distinguish
  4316. * here. We have to wait for the timeout in both cases for now.
  4317. */
  4318. if (err == EAGAIN || err == EWOULDBLOCK || err == EINTR) {
  4319. /* TODO (low): check if this is still required */
  4320. /* EAGAIN/EWOULDBLOCK:
  4321. * standard case if called from close_socket_gracefully
  4322. * => should return -1 */
  4323. /* or timeout occured
  4324. * => the code must stay in the while loop */
  4325. /* EINTR can be generated on a socket with a timeout set even
  4326. * when SA_RESTART is effective for all relevant signals
  4327. * (see signal(7)).
  4328. * => stay in the while loop */
  4329. } else {
  4330. DEBUG_TRACE("recv() failed, error %d", err);
  4331. return -2;
  4332. }
  4333. #endif
  4334. }
  4335. /* Timeout occured, but no data available. */
  4336. return -1;
  4337. }
  4338. static int
  4339. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  4340. {
  4341. int n, nread = 0;
  4342. double timeout = -1.0;
  4343. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  4344. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  4345. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  4346. }
  4347. if (timeout >= 0.0) {
  4348. start_time = mg_get_current_time_ns();
  4349. timeout_ns = (uint64_t)(timeout * 1.0E9);
  4350. }
  4351. while (len > 0 && conn->ctx->stop_flag == 0) {
  4352. n = pull_inner(fp, conn, buf + nread, len, timeout);
  4353. if (n == -2) {
  4354. if (nread == 0) {
  4355. nread = -1; /* Propagate the error */
  4356. }
  4357. break;
  4358. } else if (n == -1) {
  4359. /* timeout */
  4360. if (timeout >= 0.0) {
  4361. now = mg_get_current_time_ns();
  4362. if ((now - start_time) <= timeout_ns) {
  4363. continue;
  4364. }
  4365. }
  4366. break;
  4367. } else if (n == 0) {
  4368. break; /* No more data to read */
  4369. } else {
  4370. conn->consumed_content += n;
  4371. nread += n;
  4372. len -= n;
  4373. }
  4374. }
  4375. return nread;
  4376. }
  4377. static void
  4378. discard_unread_request_data(struct mg_connection *conn)
  4379. {
  4380. char buf[MG_BUF_LEN];
  4381. size_t to_read;
  4382. int nread;
  4383. if (conn == NULL) {
  4384. return;
  4385. }
  4386. to_read = sizeof(buf);
  4387. if (conn->is_chunked) {
  4388. /* Chunked encoding: 1=chunk not read completely, 2=chunk read
  4389. * completely */
  4390. while (conn->is_chunked == 1) {
  4391. nread = mg_read(conn, buf, to_read);
  4392. if (nread <= 0) {
  4393. break;
  4394. }
  4395. }
  4396. } else {
  4397. /* Not chunked: content length is known */
  4398. while (conn->consumed_content < conn->content_len) {
  4399. if (to_read
  4400. > (size_t)(conn->content_len - conn->consumed_content)) {
  4401. to_read = (size_t)(conn->content_len - conn->consumed_content);
  4402. }
  4403. nread = mg_read(conn, buf, to_read);
  4404. if (nread <= 0) {
  4405. break;
  4406. }
  4407. }
  4408. }
  4409. }
  4410. static int
  4411. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  4412. {
  4413. int64_t n, buffered_len, nread;
  4414. int64_t len64 =
  4415. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  4416. * int, we may not read more
  4417. * bytes */
  4418. const char *body;
  4419. if (conn == NULL) {
  4420. return 0;
  4421. }
  4422. /* If Content-Length is not set for a PUT or POST request, read until
  4423. * socket is closed */
  4424. if (conn->consumed_content == 0 && conn->content_len == -1) {
  4425. conn->content_len = INT64_MAX;
  4426. conn->must_close = 1;
  4427. }
  4428. nread = 0;
  4429. if (conn->consumed_content < conn->content_len) {
  4430. /* Adjust number of bytes to read. */
  4431. int64_t left_to_read = conn->content_len - conn->consumed_content;
  4432. if (left_to_read < len64) {
  4433. /* Do not read more than the total content length of the request.
  4434. */
  4435. len64 = left_to_read;
  4436. }
  4437. /* Return buffered data */
  4438. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  4439. - conn->consumed_content;
  4440. if (buffered_len > 0) {
  4441. if (len64 < buffered_len) {
  4442. buffered_len = len64;
  4443. }
  4444. body = conn->buf + conn->request_len + conn->consumed_content;
  4445. memcpy(buf, body, (size_t)buffered_len);
  4446. len64 -= buffered_len;
  4447. conn->consumed_content += buffered_len;
  4448. nread += buffered_len;
  4449. buf = (char *)buf + buffered_len;
  4450. }
  4451. /* We have returned all buffered data. Read new data from the remote
  4452. * socket.
  4453. */
  4454. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  4455. nread += n;
  4456. } else {
  4457. nread = ((nread > 0) ? nread : n);
  4458. }
  4459. }
  4460. return (int)nread;
  4461. }
  4462. static char
  4463. mg_getc(struct mg_connection *conn)
  4464. {
  4465. char c;
  4466. if (conn == NULL) {
  4467. return 0;
  4468. }
  4469. conn->content_len++;
  4470. if (mg_read_inner(conn, &c, 1) <= 0) {
  4471. return (char)0;
  4472. }
  4473. return c;
  4474. }
  4475. int
  4476. mg_read(struct mg_connection *conn, void *buf, size_t len)
  4477. {
  4478. if (len > INT_MAX) {
  4479. len = INT_MAX;
  4480. }
  4481. if (conn == NULL) {
  4482. return 0;
  4483. }
  4484. if (conn->is_chunked) {
  4485. size_t all_read = 0;
  4486. while (len > 0) {
  4487. if (conn->is_chunked == 2) {
  4488. /* No more data left to read */
  4489. return 0;
  4490. }
  4491. if (conn->chunk_remainder) {
  4492. /* copy from the remainder of the last received chunk */
  4493. long read_ret;
  4494. size_t read_now =
  4495. ((conn->chunk_remainder > len) ? (len)
  4496. : (conn->chunk_remainder));
  4497. conn->content_len += (int)read_now;
  4498. read_ret =
  4499. mg_read_inner(conn, (char *)buf + all_read, read_now);
  4500. if (read_ret < 1) {
  4501. /* read error */
  4502. return -1;
  4503. }
  4504. all_read += (size_t)read_ret;
  4505. conn->chunk_remainder -= (size_t)read_ret;
  4506. len -= (size_t)read_ret;
  4507. if (conn->chunk_remainder == 0) {
  4508. /* Add data bytes in the current chunk have been read,
  4509. * so we are expecting \r\n now. */
  4510. char x1 = mg_getc(conn);
  4511. char x2 = mg_getc(conn);
  4512. if ((x1 != '\r') || (x2 != '\n')) {
  4513. /* Protocol violation */
  4514. return -1;
  4515. }
  4516. }
  4517. } else {
  4518. /* fetch a new chunk */
  4519. int i = 0;
  4520. char lenbuf[64];
  4521. char *end = 0;
  4522. unsigned long chunkSize = 0;
  4523. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  4524. lenbuf[i] = mg_getc(conn);
  4525. if (i > 0 && lenbuf[i] == '\r' && lenbuf[i - 1] != '\r') {
  4526. continue;
  4527. }
  4528. if (i > 1 && lenbuf[i] == '\n' && lenbuf[i - 1] == '\r') {
  4529. lenbuf[i + 1] = 0;
  4530. chunkSize = strtoul(lenbuf, &end, 16);
  4531. if (chunkSize == 0) {
  4532. /* regular end of content */
  4533. conn->is_chunked = 2;
  4534. }
  4535. break;
  4536. }
  4537. if (!isxdigit(lenbuf[i])) {
  4538. /* illegal character for chunk length */
  4539. return -1;
  4540. }
  4541. }
  4542. if ((end == NULL) || (*end != '\r')) {
  4543. /* chunksize not set correctly */
  4544. return -1;
  4545. }
  4546. if (chunkSize == 0) {
  4547. break;
  4548. }
  4549. conn->chunk_remainder = chunkSize;
  4550. }
  4551. }
  4552. return (int)all_read;
  4553. }
  4554. return mg_read_inner(conn, buf, len);
  4555. }
  4556. int
  4557. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  4558. {
  4559. time_t now;
  4560. int64_t n, total, allowed;
  4561. if (conn == NULL) {
  4562. return 0;
  4563. }
  4564. if (conn->throttle > 0) {
  4565. if ((now = time(NULL)) != conn->last_throttle_time) {
  4566. conn->last_throttle_time = now;
  4567. conn->last_throttle_bytes = 0;
  4568. }
  4569. allowed = conn->throttle - conn->last_throttle_bytes;
  4570. if (allowed > (int64_t)len) {
  4571. allowed = (int64_t)len;
  4572. }
  4573. if ((total = push_all(conn->ctx,
  4574. NULL,
  4575. conn->client.sock,
  4576. conn->ssl,
  4577. (const char *)buf,
  4578. (int64_t)allowed)) == allowed) {
  4579. buf = (const char *)buf + total;
  4580. conn->last_throttle_bytes += total;
  4581. while (total < (int64_t)len && conn->ctx->stop_flag == 0) {
  4582. allowed = (conn->throttle > ((int64_t)len - total))
  4583. ? (int64_t)len - total
  4584. : conn->throttle;
  4585. if ((n = push_all(conn->ctx,
  4586. NULL,
  4587. conn->client.sock,
  4588. conn->ssl,
  4589. (const char *)buf,
  4590. (int64_t)allowed)) != allowed) {
  4591. break;
  4592. }
  4593. sleep(1);
  4594. conn->last_throttle_bytes = allowed;
  4595. conn->last_throttle_time = time(NULL);
  4596. buf = (const char *)buf + n;
  4597. total += n;
  4598. }
  4599. }
  4600. } else {
  4601. total = push_all(conn->ctx,
  4602. NULL,
  4603. conn->client.sock,
  4604. conn->ssl,
  4605. (const char *)buf,
  4606. (int64_t)len);
  4607. }
  4608. return (int)total;
  4609. }
  4610. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  4611. int
  4612. mg_send_chunk(struct mg_connection *conn,
  4613. const char *chunk,
  4614. unsigned int chunk_len)
  4615. {
  4616. char lenbuf[16];
  4617. size_t lenbuf_len;
  4618. int ret;
  4619. int t;
  4620. /* First store the length information in a text buffer. */
  4621. sprintf(lenbuf, "%x\r\n", chunk_len);
  4622. lenbuf_len = strlen(lenbuf);
  4623. /* Then send length information, chunk and terminating \r\n. */
  4624. ret = mg_write(conn, lenbuf, lenbuf_len);
  4625. if (ret != (int)lenbuf_len) {
  4626. return -1;
  4627. }
  4628. t = ret;
  4629. ret = mg_write(conn, chunk, chunk_len);
  4630. if (ret != (int)chunk_len) {
  4631. return -1;
  4632. }
  4633. t += ret;
  4634. ret = mg_write(conn, "\r\n", 2);
  4635. if (ret != 2) {
  4636. return -1;
  4637. }
  4638. t += ret;
  4639. return t;
  4640. }
  4641. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  4642. static int
  4643. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  4644. {
  4645. va_list ap_copy;
  4646. size_t size = MG_BUF_LEN / 4;
  4647. int len = -1;
  4648. *buf = NULL;
  4649. while (len < 0) {
  4650. if (*buf) {
  4651. mg_free(*buf);
  4652. }
  4653. size *= 4;
  4654. *buf = (char *)mg_malloc(size);
  4655. if (!*buf) {
  4656. break;
  4657. }
  4658. va_copy(ap_copy, ap);
  4659. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  4660. va_end(ap_copy);
  4661. (*buf)[size - 1] = 0;
  4662. }
  4663. return len;
  4664. }
  4665. /* Print message to buffer. If buffer is large enough to hold the message,
  4666. * return buffer. If buffer is to small, allocate large enough buffer on heap,
  4667. * and return allocated buffer. */
  4668. static int
  4669. alloc_vprintf(char **out_buf,
  4670. char *prealloc_buf,
  4671. size_t prealloc_size,
  4672. const char *fmt,
  4673. va_list ap)
  4674. {
  4675. va_list ap_copy;
  4676. int len;
  4677. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  4678. * buffer is too small. Also, older versions of msvcrt.dll do not have
  4679. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  4680. * Therefore, we make two passes: on first pass, get required message
  4681. * length.
  4682. * On second pass, actually print the message. */
  4683. va_copy(ap_copy, ap);
  4684. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  4685. va_end(ap_copy);
  4686. if (len < 0) {
  4687. /* C runtime is not standard compliant, vsnprintf() returned -1.
  4688. * Switch to alternative code path that uses incremental allocations.
  4689. */
  4690. va_copy(ap_copy, ap);
  4691. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  4692. va_end(ap_copy);
  4693. } else if ((size_t)(len) >= prealloc_size) {
  4694. /* The pre-allocated buffer not large enough. */
  4695. /* Allocate a new buffer. */
  4696. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  4697. if (!*out_buf) {
  4698. /* Allocation failed. Return -1 as "out of memory" error. */
  4699. return -1;
  4700. }
  4701. /* Buffer allocation successful. Store the string there. */
  4702. va_copy(ap_copy, ap);
  4703. IGNORE_UNUSED_RESULT(
  4704. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  4705. va_end(ap_copy);
  4706. } else {
  4707. /* The pre-allocated buffer is large enough.
  4708. * Use it to store the string and return the address. */
  4709. va_copy(ap_copy, ap);
  4710. IGNORE_UNUSED_RESULT(
  4711. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  4712. va_end(ap_copy);
  4713. *out_buf = prealloc_buf;
  4714. }
  4715. return len;
  4716. }
  4717. static int
  4718. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  4719. {
  4720. char mem[MG_BUF_LEN];
  4721. char *buf = NULL;
  4722. int len;
  4723. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  4724. len = mg_write(conn, buf, (size_t)len);
  4725. }
  4726. if (buf != mem && buf != NULL) {
  4727. mg_free(buf);
  4728. }
  4729. return len;
  4730. }
  4731. int
  4732. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  4733. {
  4734. va_list ap;
  4735. int result;
  4736. va_start(ap, fmt);
  4737. result = mg_vprintf(conn, fmt, ap);
  4738. va_end(ap);
  4739. return result;
  4740. }
  4741. int
  4742. mg_url_decode(const char *src,
  4743. int src_len,
  4744. char *dst,
  4745. int dst_len,
  4746. int is_form_url_encoded)
  4747. {
  4748. int i, j, a, b;
  4749. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  4750. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  4751. if (i < src_len - 2 && src[i] == '%'
  4752. && isxdigit(*(const unsigned char *)(src + i + 1))
  4753. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  4754. a = tolower(*(const unsigned char *)(src + i + 1));
  4755. b = tolower(*(const unsigned char *)(src + i + 2));
  4756. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  4757. i += 2;
  4758. } else if (is_form_url_encoded && src[i] == '+') {
  4759. dst[j] = ' ';
  4760. } else {
  4761. dst[j] = src[i];
  4762. }
  4763. }
  4764. dst[j] = '\0'; /* Null-terminate the destination */
  4765. return (i >= src_len) ? j : -1;
  4766. }
  4767. int
  4768. mg_get_var(const char *data,
  4769. size_t data_len,
  4770. const char *name,
  4771. char *dst,
  4772. size_t dst_len)
  4773. {
  4774. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  4775. }
  4776. int
  4777. mg_get_var2(const char *data,
  4778. size_t data_len,
  4779. const char *name,
  4780. char *dst,
  4781. size_t dst_len,
  4782. size_t occurrence)
  4783. {
  4784. const char *p, *e, *s;
  4785. size_t name_len;
  4786. int len;
  4787. if (dst == NULL || dst_len == 0) {
  4788. len = -2;
  4789. } else if (data == NULL || name == NULL || data_len == 0) {
  4790. len = -1;
  4791. dst[0] = '\0';
  4792. } else {
  4793. name_len = strlen(name);
  4794. e = data + data_len;
  4795. len = -1;
  4796. dst[0] = '\0';
  4797. /* data is "var1=val1&var2=val2...". Find variable first */
  4798. for (p = data; p + name_len < e; p++) {
  4799. if ((p == data || p[-1] == '&') && p[name_len] == '='
  4800. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  4801. /* Point p to variable value */
  4802. p += name_len + 1;
  4803. /* Point s to the end of the value */
  4804. s = (const char *)memchr(p, '&', (size_t)(e - p));
  4805. if (s == NULL) {
  4806. s = e;
  4807. }
  4808. /* assert(s >= p); */
  4809. if (s < p) {
  4810. return -3;
  4811. }
  4812. /* Decode variable into destination buffer */
  4813. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  4814. /* Redirect error code from -1 to -2 (destination buffer too
  4815. * small). */
  4816. if (len == -1) {
  4817. len = -2;
  4818. }
  4819. break;
  4820. }
  4821. }
  4822. }
  4823. return len;
  4824. }
  4825. /* HCP24: some changes to compare hole var_name */
  4826. int
  4827. mg_get_cookie(const char *cookie_header,
  4828. const char *var_name,
  4829. char *dst,
  4830. size_t dst_size)
  4831. {
  4832. const char *s, *p, *end;
  4833. int name_len, len = -1;
  4834. if (dst == NULL || dst_size == 0) {
  4835. return -2;
  4836. }
  4837. dst[0] = '\0';
  4838. if (var_name == NULL || (s = cookie_header) == NULL) {
  4839. return -1;
  4840. }
  4841. name_len = (int)strlen(var_name);
  4842. end = s + strlen(s);
  4843. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  4844. if (s[name_len] == '=') {
  4845. /* HCP24: now check is it a substring or a full cookie name */
  4846. if ((s == cookie_header) || (s[-1] == ' ')) {
  4847. s += name_len + 1;
  4848. if ((p = strchr(s, ' ')) == NULL) {
  4849. p = end;
  4850. }
  4851. if (p[-1] == ';') {
  4852. p--;
  4853. }
  4854. if (*s == '"' && p[-1] == '"' && p > s + 1) {
  4855. s++;
  4856. p--;
  4857. }
  4858. if ((size_t)(p - s) < dst_size) {
  4859. len = (int)(p - s);
  4860. mg_strlcpy(dst, s, (size_t)len + 1);
  4861. } else {
  4862. len = -3;
  4863. }
  4864. break;
  4865. }
  4866. }
  4867. }
  4868. return len;
  4869. }
  4870. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  4871. static void
  4872. base64_encode(const unsigned char *src, int src_len, char *dst)
  4873. {
  4874. static const char *b64 =
  4875. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  4876. int i, j, a, b, c;
  4877. for (i = j = 0; i < src_len; i += 3) {
  4878. a = src[i];
  4879. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  4880. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  4881. dst[j++] = b64[a >> 2];
  4882. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  4883. if (i + 1 < src_len) {
  4884. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  4885. }
  4886. if (i + 2 < src_len) {
  4887. dst[j++] = b64[c & 63];
  4888. }
  4889. }
  4890. while (j % 4 != 0) {
  4891. dst[j++] = '=';
  4892. }
  4893. dst[j++] = '\0';
  4894. }
  4895. #endif
  4896. #if defined(USE_LUA)
  4897. static unsigned char
  4898. b64reverse(char letter)
  4899. {
  4900. if (letter >= 'A' && letter <= 'Z') {
  4901. return letter - 'A';
  4902. }
  4903. if (letter >= 'a' && letter <= 'z') {
  4904. return letter - 'a' + 26;
  4905. }
  4906. if (letter >= '0' && letter <= '9') {
  4907. return letter - '0' + 52;
  4908. }
  4909. if (letter == '+') {
  4910. return 62;
  4911. }
  4912. if (letter == '/') {
  4913. return 63;
  4914. }
  4915. if (letter == '=') {
  4916. return 255; /* normal end */
  4917. }
  4918. return 254; /* error */
  4919. }
  4920. static int
  4921. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  4922. {
  4923. int i;
  4924. unsigned char a, b, c, d;
  4925. *dst_len = 0;
  4926. for (i = 0; i < src_len; i += 4) {
  4927. a = b64reverse(src[i]);
  4928. if (a >= 254) {
  4929. return i;
  4930. }
  4931. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  4932. if (b >= 254) {
  4933. return i + 1;
  4934. }
  4935. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  4936. if (c == 254) {
  4937. return i + 2;
  4938. }
  4939. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  4940. if (d == 254) {
  4941. return i + 3;
  4942. }
  4943. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  4944. if (c != 255) {
  4945. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  4946. if (d != 255) {
  4947. dst[(*dst_len)++] = (c << 6) + d;
  4948. }
  4949. }
  4950. }
  4951. return -1;
  4952. }
  4953. #endif
  4954. static int
  4955. is_put_or_delete_method(const struct mg_connection *conn)
  4956. {
  4957. if (conn) {
  4958. const char *s = conn->request_info.request_method;
  4959. return s != NULL && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  4960. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  4961. }
  4962. return 0;
  4963. }
  4964. #if !defined(NO_FILES)
  4965. static int
  4966. extention_matches_script(
  4967. struct mg_connection *conn, /* in: request (must be valid) */
  4968. const char *filename /* in: filename (must be valid) */
  4969. )
  4970. {
  4971. #if !defined(NO_CGI)
  4972. if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  4973. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4974. filename) > 0) {
  4975. return 1;
  4976. }
  4977. #endif
  4978. #if defined(USE_LUA)
  4979. if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  4980. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  4981. filename) > 0) {
  4982. return 1;
  4983. }
  4984. #endif
  4985. #if defined(USE_DUKTAPE)
  4986. if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  4987. strlen(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  4988. filename) > 0) {
  4989. return 1;
  4990. }
  4991. #endif
  4992. /* filename and conn could be unused, if all preocessor conditions
  4993. * are false (no script language supported). */
  4994. (void)filename;
  4995. (void)conn;
  4996. return 0;
  4997. }
  4998. /* For given directory path, substitute it to valid index file.
  4999. * Return 1 if index file has been found, 0 if not found.
  5000. * If the file is found, it's stats is returned in stp. */
  5001. static int
  5002. substitute_index_file(struct mg_connection *conn,
  5003. char *path,
  5004. size_t path_len,
  5005. struct mg_file_stat *filestat)
  5006. {
  5007. const char *list = conn->ctx->config[INDEX_FILES];
  5008. struct vec filename_vec;
  5009. size_t n = strlen(path);
  5010. int found = 0;
  5011. /* The 'path' given to us points to the directory. Remove all trailing
  5012. * directory separator characters from the end of the path, and
  5013. * then append single directory separator character. */
  5014. while (n > 0 && path[n - 1] == '/') {
  5015. n--;
  5016. }
  5017. path[n] = '/';
  5018. /* Traverse index files list. For each entry, append it to the given
  5019. * path and see if the file exists. If it exists, break the loop */
  5020. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  5021. /* Ignore too long entries that may overflow path buffer */
  5022. if (filename_vec.len > path_len - (n + 2)) {
  5023. continue;
  5024. }
  5025. /* Prepare full path to the index file */
  5026. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  5027. /* Does it exist? */
  5028. if (mg_stat(conn, path, filestat)) {
  5029. /* Yes it does, break the loop */
  5030. found = 1;
  5031. break;
  5032. }
  5033. }
  5034. /* If no index file exists, restore directory path */
  5035. if (!found) {
  5036. path[n] = '\0';
  5037. }
  5038. return found;
  5039. }
  5040. #endif
  5041. static void
  5042. interpret_uri(struct mg_connection *conn, /* in: request (must be valid) */
  5043. char *filename, /* out: filename */
  5044. size_t filename_buf_len, /* in: size of filename buffer */
  5045. struct mg_file_stat *filestat, /* out: file status structure */
  5046. int *is_found, /* out: file found (directly) */
  5047. int *is_script_resource, /* out: handled by a script? */
  5048. int *is_websocket_request, /* out: websocket connetion? */
  5049. int *is_put_or_delete_request /* out: put/delete a file? */
  5050. )
  5051. {
  5052. #if !defined(NO_FILES)
  5053. const char *uri = conn->request_info.local_uri;
  5054. const char *root = conn->ctx->config[DOCUMENT_ROOT];
  5055. const char *rewrite;
  5056. struct vec a, b;
  5057. int match_len;
  5058. char gz_path[PATH_MAX];
  5059. char const *accept_encoding;
  5060. int truncated;
  5061. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  5062. char *tmp_str;
  5063. size_t tmp_str_len, sep_pos;
  5064. #endif
  5065. #else
  5066. (void)filename_buf_len; /* unused if NO_FILES is defined */
  5067. #endif
  5068. /* Step 1: Set all initially unknown outputs to zero */
  5069. memset(filestat, 0, sizeof(*filestat));
  5070. *filename = 0;
  5071. *is_found = 0;
  5072. *is_script_resource = 0;
  5073. /* Step 2: Check if the request attempts to modify the file system */
  5074. *is_put_or_delete_request = is_put_or_delete_method(conn);
  5075. /* Step 3: Check if it is a websocket request, and modify the document
  5076. * root if required */
  5077. #if defined(USE_WEBSOCKET)
  5078. *is_websocket_request = is_websocket_protocol(conn);
  5079. #if !defined(NO_FILES)
  5080. if (*is_websocket_request && conn->ctx->config[WEBSOCKET_ROOT]) {
  5081. root = conn->ctx->config[WEBSOCKET_ROOT];
  5082. }
  5083. #endif /* !NO_FILES */
  5084. #else /* USE_WEBSOCKET */
  5085. *is_websocket_request = 0;
  5086. #endif /* USE_WEBSOCKET */
  5087. #if !defined(NO_FILES)
  5088. /* Step 4: If there is no root directory, don't look for files. */
  5089. /* Note that root == NULL is a regular use case here. This occurs,
  5090. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  5091. * config is not required. */
  5092. if (root == NULL) {
  5093. /* all file related outputs have already been set to 0, just return
  5094. */
  5095. return;
  5096. }
  5097. /* Step 5: Determine the local file path from the root path and the
  5098. * request uri. */
  5099. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  5100. * part of the path one byte on the right. */
  5101. mg_snprintf(
  5102. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  5103. if (truncated) {
  5104. goto interpret_cleanup;
  5105. }
  5106. /* Step 6: URI rewriting */
  5107. rewrite = conn->ctx->config[REWRITE];
  5108. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  5109. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  5110. mg_snprintf(conn,
  5111. &truncated,
  5112. filename,
  5113. filename_buf_len - 1,
  5114. "%.*s%s",
  5115. (int)b.len,
  5116. b.ptr,
  5117. uri + match_len);
  5118. break;
  5119. }
  5120. }
  5121. if (truncated) {
  5122. goto interpret_cleanup;
  5123. }
  5124. /* Step 7: Check if the file exists at the server */
  5125. /* Local file path and name, corresponding to requested URI
  5126. * is now stored in "filename" variable. */
  5127. if (mg_stat(conn, filename, filestat)) {
  5128. /* 7.1: File exists. */
  5129. *is_found = 1;
  5130. /* 7.2: Check if it is a script type. */
  5131. if (extention_matches_script(conn, filename)) {
  5132. /* The request addresses a CGI resource, Lua script or
  5133. * server-side javascript.
  5134. * The URI corresponds to the script itself (like
  5135. * /path/script.cgi), and there is no additional resource
  5136. * path (like /path/script.cgi/something).
  5137. * Requests that modify (replace or delete) a resource, like
  5138. * PUT and DELETE requests, should replace/delete the script
  5139. * file.
  5140. * Requests that read or write from/to a resource, like GET and
  5141. * POST requests, should call the script and return the
  5142. * generated response. */
  5143. *is_script_resource = (!*is_put_or_delete_request);
  5144. }
  5145. /* 7.3: If the request target is a directory, there could be
  5146. * a substitute file (index.html, index.cgi, ...). */
  5147. if (filestat->is_directory) {
  5148. /* Use a local copy here, since substitute_index_file will
  5149. * change the content of the file status */
  5150. struct mg_file_stat tmp_filestat;
  5151. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  5152. if (substitute_index_file(
  5153. conn, filename, filename_buf_len, &tmp_filestat)) {
  5154. /* Substitute file found. Copy stat to the output, then
  5155. * check if the file is a script file */
  5156. *filestat = tmp_filestat;
  5157. if (extention_matches_script(conn, filename)) {
  5158. /* Substitute file is a script file */
  5159. *is_script_resource = 1;
  5160. } else {
  5161. /* Substitute file is a regular file */
  5162. *is_script_resource = 0;
  5163. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  5164. }
  5165. }
  5166. /* If there is no substitute file, the server could return
  5167. * a directory listing in a later step */
  5168. }
  5169. return;
  5170. }
  5171. /* Step 8: Check for zipped files: */
  5172. /* If we can't find the actual file, look for the file
  5173. * with the same name but a .gz extension. If we find it,
  5174. * use that and set the gzipped flag in the file struct
  5175. * to indicate that the response need to have the content-
  5176. * encoding: gzip header.
  5177. * We can only do this if the browser declares support. */
  5178. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  5179. if (strstr(accept_encoding, "gzip") != NULL) {
  5180. mg_snprintf(
  5181. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  5182. if (truncated) {
  5183. goto interpret_cleanup;
  5184. }
  5185. if (mg_stat(conn, gz_path, filestat)) {
  5186. if (filestat) {
  5187. filestat->is_gzipped = 1;
  5188. *is_found = 1;
  5189. }
  5190. /* Currently gz files can not be scripts. */
  5191. return;
  5192. }
  5193. }
  5194. }
  5195. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  5196. /* Step 9: Script resources may handle sub-resources */
  5197. /* Support PATH_INFO for CGI scripts. */
  5198. tmp_str_len = strlen(filename);
  5199. tmp_str = mg_malloc(tmp_str_len + PATH_MAX + 1);
  5200. if (!tmp_str) {
  5201. /* Out of memory */
  5202. goto interpret_cleanup;
  5203. }
  5204. memcpy(tmp_str, filename, tmp_str_len + 1);
  5205. sep_pos = tmp_str_len;
  5206. while (sep_pos > 0) {
  5207. sep_pos--;
  5208. if (tmp_str[sep_pos] == '/') {
  5209. int is_script = 0, does_exist = 0;
  5210. tmp_str[sep_pos] = 0;
  5211. if (tmp_str[0]) {
  5212. is_script = extention_matches_script(conn, tmp_str);
  5213. does_exist = mg_stat(conn, tmp_str, filestat);
  5214. }
  5215. if (does_exist && is_script) {
  5216. filename[sep_pos] = 0;
  5217. memmove(filename + sep_pos + 2,
  5218. filename + sep_pos + 1,
  5219. strlen(filename + sep_pos + 1) + 1);
  5220. conn->path_info = filename + sep_pos + 1;
  5221. filename[sep_pos + 1] = '/';
  5222. *is_script_resource = 1;
  5223. *is_found = 1;
  5224. break;
  5225. }
  5226. if (substitute_index_file(
  5227. conn, tmp_str, tmp_str_len + PATH_MAX, filestat)) {
  5228. /* some intermediate directory has an index file */
  5229. if (extention_matches_script(conn, tmp_str)) {
  5230. /* this index file is a script */
  5231. char *tmp_str2 = mg_strdup(filename + sep_pos + 1);
  5232. mg_snprintf(conn,
  5233. &truncated,
  5234. filename,
  5235. filename_buf_len,
  5236. "%s//%s",
  5237. tmp_str,
  5238. tmp_str2);
  5239. mg_free(tmp_str2);
  5240. if (truncated) {
  5241. mg_free(tmp_str);
  5242. tmp_str = NULL;
  5243. goto interpret_cleanup;
  5244. }
  5245. sep_pos = strlen(tmp_str);
  5246. filename[sep_pos] = 0;
  5247. conn->path_info = filename + sep_pos + 1;
  5248. *is_script_resource = 1;
  5249. *is_found = 1;
  5250. break;
  5251. } else {
  5252. /* non-script files will not have sub-resources */
  5253. filename[sep_pos] = 0;
  5254. conn->path_info = 0;
  5255. *is_script_resource = 0;
  5256. *is_found = 0;
  5257. break;
  5258. }
  5259. }
  5260. tmp_str[sep_pos] = '/';
  5261. }
  5262. }
  5263. mg_free(tmp_str);
  5264. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  5265. #endif /* !defined(NO_FILES) */
  5266. return;
  5267. #if !defined(NO_FILES)
  5268. /* Reset all outputs */
  5269. interpret_cleanup:
  5270. memset(filestat, 0, sizeof(*filestat));
  5271. *filename = 0;
  5272. *is_found = 0;
  5273. *is_script_resource = 0;
  5274. *is_websocket_request = 0;
  5275. *is_put_or_delete_request = 0;
  5276. #endif /* !defined(NO_FILES) */
  5277. }
  5278. /* Check whether full request is buffered. Return:
  5279. * -1 if request is malformed
  5280. * 0 if request is not yet fully buffered
  5281. * >0 actual request length, including last \r\n\r\n */
  5282. static int
  5283. get_request_len(const char *buf, int buflen)
  5284. {
  5285. const char *s, *e;
  5286. int len = 0;
  5287. for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
  5288. /* Control characters are not allowed but >=128 is. */
  5289. if (!isprint(*(const unsigned char *)s) && *s != '\r' && *s != '\n'
  5290. && *(const unsigned char *)s < 128) {
  5291. len = -1;
  5292. break; /* [i_a] abort scan as soon as one malformed character is
  5293. * found; */
  5294. /* don't let subsequent \r\n\r\n win us over anyhow */
  5295. } else if (s[0] == '\n' && s[1] == '\n') {
  5296. len = (int)(s - buf) + 2;
  5297. } else if (s[0] == '\n' && &s[1] < e && s[1] == '\r' && s[2] == '\n') {
  5298. len = (int)(s - buf) + 3;
  5299. }
  5300. return len;
  5301. }
  5302. #if !defined(NO_CACHING)
  5303. /* Convert month to the month number. Return -1 on error, or month number */
  5304. static int
  5305. get_month_index(const char *s)
  5306. {
  5307. size_t i;
  5308. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  5309. if (!strcmp(s, month_names[i])) {
  5310. return (int)i;
  5311. }
  5312. }
  5313. return -1;
  5314. }
  5315. /* Parse UTC date-time string, and return the corresponding time_t value. */
  5316. static time_t
  5317. parse_date_string(const char *datetime)
  5318. {
  5319. char month_str[32] = {0};
  5320. int second, minute, hour, day, month, year;
  5321. time_t result = (time_t)0;
  5322. struct tm tm;
  5323. if ((sscanf(datetime,
  5324. "%d/%3s/%d %d:%d:%d",
  5325. &day,
  5326. month_str,
  5327. &year,
  5328. &hour,
  5329. &minute,
  5330. &second) == 6) || (sscanf(datetime,
  5331. "%d %3s %d %d:%d:%d",
  5332. &day,
  5333. month_str,
  5334. &year,
  5335. &hour,
  5336. &minute,
  5337. &second) == 6)
  5338. || (sscanf(datetime,
  5339. "%*3s, %d %3s %d %d:%d:%d",
  5340. &day,
  5341. month_str,
  5342. &year,
  5343. &hour,
  5344. &minute,
  5345. &second) == 6) || (sscanf(datetime,
  5346. "%d-%3s-%d %d:%d:%d",
  5347. &day,
  5348. month_str,
  5349. &year,
  5350. &hour,
  5351. &minute,
  5352. &second) == 6)) {
  5353. month = get_month_index(month_str);
  5354. if ((month >= 0) && (year >= 1970)) {
  5355. memset(&tm, 0, sizeof(tm));
  5356. tm.tm_year = year - 1900;
  5357. tm.tm_mon = month;
  5358. tm.tm_mday = day;
  5359. tm.tm_hour = hour;
  5360. tm.tm_min = minute;
  5361. tm.tm_sec = second;
  5362. result = timegm(&tm);
  5363. }
  5364. }
  5365. return result;
  5366. }
  5367. #endif /* !NO_CACHING */
  5368. /* Protect against directory disclosure attack by removing '..',
  5369. * excessive '/' and '\' characters */
  5370. static void
  5371. remove_double_dots_and_double_slashes(char *s)
  5372. {
  5373. char *p = s;
  5374. while ((s[0] == '.') && (s[1] == '.')) {
  5375. s++;
  5376. }
  5377. while (*s != '\0') {
  5378. *p++ = *s++;
  5379. if (s[-1] == '/' || s[-1] == '\\') {
  5380. /* Skip all following slashes, backslashes and double-dots */
  5381. while (s[0] != '\0') {
  5382. if (s[0] == '/' || s[0] == '\\') {
  5383. s++;
  5384. } else if (s[0] == '.' && s[1] == '.') {
  5385. s += 2;
  5386. } else {
  5387. break;
  5388. }
  5389. }
  5390. }
  5391. }
  5392. *p = '\0';
  5393. }
  5394. static const struct {
  5395. const char *extension;
  5396. size_t ext_len;
  5397. const char *mime_type;
  5398. } builtin_mime_types[] = {
  5399. /* IANA registered MIME types (http://www.iana.org/assignments/media-types)
  5400. * application types */
  5401. {".doc", 4, "application/msword"},
  5402. {".eps", 4, "application/postscript"},
  5403. {".exe", 4, "application/octet-stream"},
  5404. {".js", 3, "application/javascript"},
  5405. {".json", 5, "application/json"},
  5406. {".pdf", 4, "application/pdf"},
  5407. {".ps", 3, "application/postscript"},
  5408. {".rtf", 4, "application/rtf"},
  5409. {".xhtml", 6, "application/xhtml+xml"},
  5410. {".xsl", 4, "application/xml"},
  5411. {".xslt", 5, "application/xml"},
  5412. /* fonts */
  5413. {".ttf", 4, "application/font-sfnt"},
  5414. {".cff", 4, "application/font-sfnt"},
  5415. {".otf", 4, "application/font-sfnt"},
  5416. {".aat", 4, "application/font-sfnt"},
  5417. {".sil", 4, "application/font-sfnt"},
  5418. {".pfr", 4, "application/font-tdpfr"},
  5419. {".woff", 5, "application/font-woff"},
  5420. /* audio */
  5421. {".mp3", 4, "audio/mpeg"},
  5422. {".oga", 4, "audio/ogg"},
  5423. {".ogg", 4, "audio/ogg"},
  5424. /* image */
  5425. {".gif", 4, "image/gif"},
  5426. {".ief", 4, "image/ief"},
  5427. {".jpeg", 5, "image/jpeg"},
  5428. {".jpg", 4, "image/jpeg"},
  5429. {".jpm", 4, "image/jpm"},
  5430. {".jpx", 4, "image/jpx"},
  5431. {".png", 4, "image/png"},
  5432. {".svg", 4, "image/svg+xml"},
  5433. {".tif", 4, "image/tiff"},
  5434. {".tiff", 5, "image/tiff"},
  5435. /* model */
  5436. {".wrl", 4, "model/vrml"},
  5437. /* text */
  5438. {".css", 4, "text/css"},
  5439. {".csv", 4, "text/csv"},
  5440. {".htm", 4, "text/html"},
  5441. {".html", 5, "text/html"},
  5442. {".sgm", 4, "text/sgml"},
  5443. {".shtm", 5, "text/html"},
  5444. {".shtml", 6, "text/html"},
  5445. {".txt", 4, "text/plain"},
  5446. {".xml", 4, "text/xml"},
  5447. /* video */
  5448. {".mov", 4, "video/quicktime"},
  5449. {".mp4", 4, "video/mp4"},
  5450. {".mpeg", 5, "video/mpeg"},
  5451. {".mpg", 4, "video/mpeg"},
  5452. {".ogv", 4, "video/ogg"},
  5453. {".qt", 3, "video/quicktime"},
  5454. /* not registered types
  5455. * (http://reference.sitepoint.com/html/mime-types-full,
  5456. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  5457. {".arj", 4, "application/x-arj-compressed"},
  5458. {".gz", 3, "application/x-gunzip"},
  5459. {".rar", 4, "application/x-arj-compressed"},
  5460. {".swf", 4, "application/x-shockwave-flash"},
  5461. {".tar", 4, "application/x-tar"},
  5462. {".tgz", 4, "application/x-tar-gz"},
  5463. {".torrent", 8, "application/x-bittorrent"},
  5464. {".ppt", 4, "application/x-mspowerpoint"},
  5465. {".xls", 4, "application/x-msexcel"},
  5466. {".zip", 4, "application/x-zip-compressed"},
  5467. {".aac",
  5468. 4,
  5469. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  5470. {".aif", 4, "audio/x-aif"},
  5471. {".m3u", 4, "audio/x-mpegurl"},
  5472. {".mid", 4, "audio/x-midi"},
  5473. {".ra", 3, "audio/x-pn-realaudio"},
  5474. {".ram", 4, "audio/x-pn-realaudio"},
  5475. {".wav", 4, "audio/x-wav"},
  5476. {".bmp", 4, "image/bmp"},
  5477. {".ico", 4, "image/x-icon"},
  5478. {".pct", 4, "image/x-pct"},
  5479. {".pict", 5, "image/pict"},
  5480. {".rgb", 4, "image/x-rgb"},
  5481. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  5482. {".asf", 4, "video/x-ms-asf"},
  5483. {".avi", 4, "video/x-msvideo"},
  5484. {".m4v", 4, "video/x-m4v"},
  5485. {NULL, 0, NULL}};
  5486. const char *
  5487. mg_get_builtin_mime_type(const char *path)
  5488. {
  5489. const char *ext;
  5490. size_t i, path_len;
  5491. path_len = strlen(path);
  5492. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  5493. ext = path + (path_len - builtin_mime_types[i].ext_len);
  5494. if (path_len > builtin_mime_types[i].ext_len
  5495. && mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {
  5496. return builtin_mime_types[i].mime_type;
  5497. }
  5498. }
  5499. return "text/plain";
  5500. }
  5501. /* Look at the "path" extension and figure what mime type it has.
  5502. * Store mime type in the vector. */
  5503. static void
  5504. get_mime_type(struct mg_context *ctx, const char *path, struct vec *vec)
  5505. {
  5506. struct vec ext_vec, mime_vec;
  5507. const char *list, *ext;
  5508. size_t path_len;
  5509. path_len = strlen(path);
  5510. if (ctx == NULL || vec == NULL) {
  5511. return;
  5512. }
  5513. /* Scan user-defined mime types first, in case user wants to
  5514. * override default mime types. */
  5515. list = ctx->config[EXTRA_MIME_TYPES];
  5516. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  5517. /* ext now points to the path suffix */
  5518. ext = path + path_len - ext_vec.len;
  5519. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  5520. *vec = mime_vec;
  5521. return;
  5522. }
  5523. }
  5524. vec->ptr = mg_get_builtin_mime_type(path);
  5525. vec->len = strlen(vec->ptr);
  5526. }
  5527. /* Stringify binary data. Output buffer must be twice as big as input,
  5528. * because each byte takes 2 bytes in string representation */
  5529. static void
  5530. bin2str(char *to, const unsigned char *p, size_t len)
  5531. {
  5532. static const char *hex = "0123456789abcdef";
  5533. for (; len--; p++) {
  5534. *to++ = hex[p[0] >> 4];
  5535. *to++ = hex[p[0] & 0x0f];
  5536. }
  5537. *to = '\0';
  5538. }
  5539. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes. */
  5540. char *
  5541. mg_md5(char buf[33], ...)
  5542. {
  5543. md5_byte_t hash[16];
  5544. const char *p;
  5545. va_list ap;
  5546. md5_state_t ctx;
  5547. md5_init(&ctx);
  5548. va_start(ap, buf);
  5549. while ((p = va_arg(ap, const char *)) != NULL) {
  5550. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  5551. }
  5552. va_end(ap);
  5553. md5_finish(&ctx, hash);
  5554. bin2str(buf, hash, sizeof(hash));
  5555. return buf;
  5556. }
  5557. /* Check the user's password, return 1 if OK */
  5558. static int
  5559. check_password(const char *method,
  5560. const char *ha1,
  5561. const char *uri,
  5562. const char *nonce,
  5563. const char *nc,
  5564. const char *cnonce,
  5565. const char *qop,
  5566. const char *response)
  5567. {
  5568. char ha2[32 + 1], expected_response[32 + 1];
  5569. /* Some of the parameters may be NULL */
  5570. if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL
  5571. || qop == NULL
  5572. || response == NULL) {
  5573. return 0;
  5574. }
  5575. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  5576. if (strlen(response) != 32) {
  5577. return 0;
  5578. }
  5579. mg_md5(ha2, method, ":", uri, NULL);
  5580. mg_md5(expected_response,
  5581. ha1,
  5582. ":",
  5583. nonce,
  5584. ":",
  5585. nc,
  5586. ":",
  5587. cnonce,
  5588. ":",
  5589. qop,
  5590. ":",
  5591. ha2,
  5592. NULL);
  5593. return mg_strcasecmp(response, expected_response) == 0;
  5594. }
  5595. /* Use the global passwords file, if specified by auth_gpass option,
  5596. * or search for .htpasswd in the requested directory. */
  5597. static void
  5598. open_auth_file(struct mg_connection *conn,
  5599. const char *path,
  5600. struct mg_file *filep)
  5601. {
  5602. if (conn != NULL && conn->ctx != NULL) {
  5603. char name[PATH_MAX];
  5604. const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
  5605. int truncated;
  5606. if (gpass != NULL) {
  5607. /* Use global passwords file */
  5608. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  5609. #ifdef DEBUG
  5610. /* Use mg_cry here, since gpass has been configured. */
  5611. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  5612. #endif
  5613. }
  5614. /* Important: using local struct mg_file to test path for
  5615. * is_directory flag. If filep is used, mg_stat() makes it
  5616. * appear as if auth file was opened.
  5617. * TODO(mid): Check if this is still required after rewriting
  5618. * mg_stat */
  5619. } else if (mg_stat(conn, path, &filep->stat)
  5620. && filep->stat.is_directory) {
  5621. mg_snprintf(conn,
  5622. &truncated,
  5623. name,
  5624. sizeof(name),
  5625. "%s/%s",
  5626. path,
  5627. PASSWORDS_FILE_NAME);
  5628. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  5629. #ifdef DEBUG
  5630. /* Don't use mg_cry here, but only a trace, since this is
  5631. * a typical case. It will occur for every directory
  5632. * without a password file. */
  5633. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  5634. #endif
  5635. }
  5636. } else {
  5637. /* Try to find .htpasswd in requested directory. */
  5638. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  5639. if (e[0] == '/') {
  5640. break;
  5641. }
  5642. }
  5643. mg_snprintf(conn,
  5644. &truncated,
  5645. name,
  5646. sizeof(name),
  5647. "%.*s/%s",
  5648. (int)(e - p),
  5649. p,
  5650. PASSWORDS_FILE_NAME);
  5651. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  5652. #ifdef DEBUG
  5653. /* Don't use mg_cry here, but only a trace, since this is
  5654. * a typical case. It will occur for every directory
  5655. * without a password file. */
  5656. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  5657. #endif
  5658. }
  5659. }
  5660. }
  5661. }
  5662. /* Parsed Authorization header */
  5663. struct ah {
  5664. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  5665. };
  5666. /* Return 1 on success. Always initializes the ah structure. */
  5667. static int
  5668. parse_auth_header(struct mg_connection *conn,
  5669. char *buf,
  5670. size_t buf_size,
  5671. struct ah *ah)
  5672. {
  5673. char *name, *value, *s;
  5674. const char *auth_header;
  5675. uint64_t nonce;
  5676. if (!ah || !conn) {
  5677. return 0;
  5678. }
  5679. (void)memset(ah, 0, sizeof(*ah));
  5680. if ((auth_header = mg_get_header(conn, "Authorization")) == NULL
  5681. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  5682. return 0;
  5683. }
  5684. /* Make modifiable copy of the auth header */
  5685. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  5686. s = buf;
  5687. /* Parse authorization header */
  5688. for (;;) {
  5689. /* Gobble initial spaces */
  5690. while (isspace(*(unsigned char *)s)) {
  5691. s++;
  5692. }
  5693. name = skip_quoted(&s, "=", " ", 0);
  5694. /* Value is either quote-delimited, or ends at first comma or space. */
  5695. if (s[0] == '\"') {
  5696. s++;
  5697. value = skip_quoted(&s, "\"", " ", '\\');
  5698. if (s[0] == ',') {
  5699. s++;
  5700. }
  5701. } else {
  5702. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  5703. * spaces */
  5704. }
  5705. if (*name == '\0') {
  5706. break;
  5707. }
  5708. if (!strcmp(name, "username")) {
  5709. ah->user = value;
  5710. } else if (!strcmp(name, "cnonce")) {
  5711. ah->cnonce = value;
  5712. } else if (!strcmp(name, "response")) {
  5713. ah->response = value;
  5714. } else if (!strcmp(name, "uri")) {
  5715. ah->uri = value;
  5716. } else if (!strcmp(name, "qop")) {
  5717. ah->qop = value;
  5718. } else if (!strcmp(name, "nc")) {
  5719. ah->nc = value;
  5720. } else if (!strcmp(name, "nonce")) {
  5721. ah->nonce = value;
  5722. }
  5723. }
  5724. #ifndef NO_NONCE_CHECK
  5725. /* Read the nonce from the response. */
  5726. if (ah->nonce == NULL) {
  5727. return 0;
  5728. }
  5729. s = NULL;
  5730. nonce = strtoull(ah->nonce, &s, 10);
  5731. if ((s == NULL) || (*s != 0)) {
  5732. return 0;
  5733. }
  5734. /* Convert the nonce from the client to a number. */
  5735. nonce ^= conn->ctx->auth_nonce_mask;
  5736. /* The converted number corresponds to the time the nounce has been
  5737. * created. This should not be earlier than the server start. */
  5738. /* Server side nonce check is valuable in all situations but one:
  5739. * if the server restarts frequently, but the client should not see
  5740. * that, so the server should accept nonces from previous starts. */
  5741. /* However, the reasonable default is to not accept a nonce from a
  5742. * previous start, so if anyone changed the access rights between
  5743. * two restarts, a new login is required. */
  5744. if (nonce < (uint64_t)conn->ctx->start_time) {
  5745. /* nonce is from a previous start of the server and no longer valid
  5746. * (replay attack?) */
  5747. return 0;
  5748. }
  5749. /* Check if the nonce is too high, so it has not (yet) been used by the
  5750. * server. */
  5751. if (nonce >= ((uint64_t)conn->ctx->start_time + conn->ctx->nonce_count)) {
  5752. return 0;
  5753. }
  5754. #else
  5755. (void)nonce;
  5756. #endif
  5757. /* CGI needs it as REMOTE_USER */
  5758. if (ah->user != NULL) {
  5759. conn->request_info.remote_user = mg_strdup(ah->user);
  5760. } else {
  5761. return 0;
  5762. }
  5763. return 1;
  5764. }
  5765. static const char *
  5766. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  5767. {
  5768. const char *eof;
  5769. size_t len;
  5770. const char *memend;
  5771. if (!filep) {
  5772. return NULL;
  5773. }
  5774. if (filep->access.membuf != NULL && *p != NULL) {
  5775. memend = (const char *)&filep->access.membuf[filep->stat.size];
  5776. /* Search for \n from p till the end of stream */
  5777. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  5778. if (eof != NULL) {
  5779. eof += 1; /* Include \n */
  5780. } else {
  5781. eof = memend; /* Copy remaining data */
  5782. }
  5783. len =
  5784. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  5785. memcpy(buf, *p, len);
  5786. buf[len] = '\0';
  5787. *p += len;
  5788. return len ? eof : NULL;
  5789. } else if (filep->access.fp != NULL) {
  5790. return fgets(buf, (int)size, filep->access.fp);
  5791. } else {
  5792. return NULL;
  5793. }
  5794. }
  5795. /* Define the initial recursion depth for procesesing htpasswd files that
  5796. * include other htpasswd
  5797. * (or even the same) files. It is not difficult to provide a file or files
  5798. * s.t. they force civetweb
  5799. * to infinitely recurse and then crash.
  5800. */
  5801. #define INITIAL_DEPTH 9
  5802. #if INITIAL_DEPTH <= 0
  5803. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  5804. #endif
  5805. struct read_auth_file_struct {
  5806. struct mg_connection *conn;
  5807. struct ah ah;
  5808. char *domain;
  5809. char buf[256 + 256 + 40];
  5810. char *f_user;
  5811. char *f_domain;
  5812. char *f_ha1;
  5813. };
  5814. static int
  5815. read_auth_file(struct mg_file *filep,
  5816. struct read_auth_file_struct *workdata,
  5817. int depth)
  5818. {
  5819. char *p;
  5820. int is_authorized = 0;
  5821. struct mg_file fp;
  5822. size_t l;
  5823. if (!filep || !workdata || 0 == depth) {
  5824. return 0;
  5825. }
  5826. /* Loop over passwords file */
  5827. p = (char *)filep->access.membuf;
  5828. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  5829. l = strlen(workdata->buf);
  5830. while (l > 0) {
  5831. if (isspace(workdata->buf[l - 1])
  5832. || iscntrl(workdata->buf[l - 1])) {
  5833. l--;
  5834. workdata->buf[l] = 0;
  5835. } else
  5836. break;
  5837. }
  5838. if (l < 1) {
  5839. continue;
  5840. }
  5841. workdata->f_user = workdata->buf;
  5842. if (workdata->f_user[0] == ':') {
  5843. /* user names may not contain a ':' and may not be empty,
  5844. * so lines starting with ':' may be used for a special purpose */
  5845. if (workdata->f_user[1] == '#') {
  5846. /* :# is a comment */
  5847. continue;
  5848. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  5849. if (mg_fopen(workdata->conn,
  5850. workdata->f_user + 9,
  5851. MG_FOPEN_MODE_READ,
  5852. &fp)) {
  5853. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  5854. (void)mg_fclose(
  5855. &fp.access); /* ignore error on read only file */
  5856. /* No need to continue processing files once we have a
  5857. * match, since nothing will reset it back
  5858. * to 0.
  5859. */
  5860. if (is_authorized) {
  5861. return is_authorized;
  5862. }
  5863. } else {
  5864. mg_cry(workdata->conn,
  5865. "%s: cannot open authorization file: %s",
  5866. __func__,
  5867. workdata->buf);
  5868. }
  5869. continue;
  5870. }
  5871. /* everything is invalid for the moment (might change in the
  5872. * future) */
  5873. mg_cry(workdata->conn,
  5874. "%s: syntax error in authorization file: %s",
  5875. __func__,
  5876. workdata->buf);
  5877. continue;
  5878. }
  5879. workdata->f_domain = strchr(workdata->f_user, ':');
  5880. if (workdata->f_domain == NULL) {
  5881. mg_cry(workdata->conn,
  5882. "%s: syntax error in authorization file: %s",
  5883. __func__,
  5884. workdata->buf);
  5885. continue;
  5886. }
  5887. *(workdata->f_domain) = 0;
  5888. (workdata->f_domain)++;
  5889. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  5890. if (workdata->f_ha1 == NULL) {
  5891. mg_cry(workdata->conn,
  5892. "%s: syntax error in authorization file: %s",
  5893. __func__,
  5894. workdata->buf);
  5895. continue;
  5896. }
  5897. *(workdata->f_ha1) = 0;
  5898. (workdata->f_ha1)++;
  5899. if (!strcmp(workdata->ah.user, workdata->f_user)
  5900. && !strcmp(workdata->domain, workdata->f_domain)) {
  5901. return check_password(workdata->conn->request_info.request_method,
  5902. workdata->f_ha1,
  5903. workdata->ah.uri,
  5904. workdata->ah.nonce,
  5905. workdata->ah.nc,
  5906. workdata->ah.cnonce,
  5907. workdata->ah.qop,
  5908. workdata->ah.response);
  5909. }
  5910. }
  5911. return is_authorized;
  5912. }
  5913. /* Authorize against the opened passwords file. Return 1 if authorized. */
  5914. static int
  5915. authorize(struct mg_connection *conn, struct mg_file *filep)
  5916. {
  5917. struct read_auth_file_struct workdata;
  5918. char buf[MG_BUF_LEN];
  5919. if (!conn || !conn->ctx) {
  5920. return 0;
  5921. }
  5922. memset(&workdata, 0, sizeof(workdata));
  5923. workdata.conn = conn;
  5924. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  5925. return 0;
  5926. }
  5927. workdata.domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  5928. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  5929. }
  5930. /* Return 1 if request is authorised, 0 otherwise. */
  5931. static int
  5932. check_authorization(struct mg_connection *conn, const char *path)
  5933. {
  5934. char fname[PATH_MAX];
  5935. struct vec uri_vec, filename_vec;
  5936. const char *list;
  5937. struct mg_file file = STRUCT_FILE_INITIALIZER;
  5938. int authorized = 1, truncated;
  5939. if (!conn || !conn->ctx) {
  5940. return 0;
  5941. }
  5942. list = conn->ctx->config[PROTECT_URI];
  5943. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  5944. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  5945. mg_snprintf(conn,
  5946. &truncated,
  5947. fname,
  5948. sizeof(fname),
  5949. "%.*s",
  5950. (int)filename_vec.len,
  5951. filename_vec.ptr);
  5952. if (truncated
  5953. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  5954. mg_cry(conn,
  5955. "%s: cannot open %s: %s",
  5956. __func__,
  5957. fname,
  5958. strerror(errno));
  5959. }
  5960. break;
  5961. }
  5962. }
  5963. if (!is_file_opened(&file.access)) {
  5964. open_auth_file(conn, path, &file);
  5965. }
  5966. if (is_file_opened(&file.access)) {
  5967. authorized = authorize(conn, &file);
  5968. (void)mg_fclose(&file.access); /* ignore error on read only file */
  5969. }
  5970. return authorized;
  5971. }
  5972. static void
  5973. send_authorization_request(struct mg_connection *conn)
  5974. {
  5975. char date[64];
  5976. time_t curtime = time(NULL);
  5977. if (conn && conn->ctx) {
  5978. uint64_t nonce = (uint64_t)(conn->ctx->start_time);
  5979. (void)pthread_mutex_lock(&conn->ctx->nonce_mutex);
  5980. nonce += conn->ctx->nonce_count;
  5981. ++conn->ctx->nonce_count;
  5982. (void)pthread_mutex_unlock(&conn->ctx->nonce_mutex);
  5983. nonce ^= conn->ctx->auth_nonce_mask;
  5984. conn->status_code = 401;
  5985. conn->must_close = 1;
  5986. gmt_time_string(date, sizeof(date), &curtime);
  5987. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  5988. send_no_cache_header(conn);
  5989. send_additional_header(conn);
  5990. mg_printf(conn,
  5991. "Date: %s\r\n"
  5992. "Connection: %s\r\n"
  5993. "Content-Length: 0\r\n"
  5994. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  5995. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  5996. date,
  5997. suggest_connection_header(conn),
  5998. conn->ctx->config[AUTHENTICATION_DOMAIN],
  5999. nonce);
  6000. }
  6001. }
  6002. #if !defined(NO_FILES)
  6003. static int
  6004. is_authorized_for_put(struct mg_connection *conn)
  6005. {
  6006. if (conn) {
  6007. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6008. const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
  6009. int ret = 0;
  6010. if (passfile != NULL
  6011. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  6012. ret = authorize(conn, &file);
  6013. (void)mg_fclose(&file.access); /* ignore error on read only file */
  6014. }
  6015. return ret;
  6016. }
  6017. return 0;
  6018. }
  6019. #endif
  6020. int
  6021. mg_modify_passwords_file(const char *fname,
  6022. const char *domain,
  6023. const char *user,
  6024. const char *pass)
  6025. {
  6026. int found, i;
  6027. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  6028. FILE *fp, *fp2;
  6029. found = 0;
  6030. fp = fp2 = NULL;
  6031. /* Regard empty password as no password - remove user record. */
  6032. if (pass != NULL && pass[0] == '\0') {
  6033. pass = NULL;
  6034. }
  6035. /* Other arguments must not be empty */
  6036. if (fname == NULL || domain == NULL || user == NULL) {
  6037. return 0;
  6038. }
  6039. /* Using the given file format, user name and domain must not contain ':'
  6040. */
  6041. if (strchr(user, ':') != NULL) {
  6042. return 0;
  6043. }
  6044. if (strchr(domain, ':') != NULL) {
  6045. return 0;
  6046. }
  6047. /* Do not allow control characters like newline in user name and domain.
  6048. * Do not allow excessively long names either. */
  6049. for (i = 0; i < 255 && user[i] != 0; i++) {
  6050. if (iscntrl(user[i])) {
  6051. return 0;
  6052. }
  6053. }
  6054. if (user[i]) {
  6055. return 0;
  6056. }
  6057. for (i = 0; i < 255 && domain[i] != 0; i++) {
  6058. if (iscntrl(domain[i])) {
  6059. return 0;
  6060. }
  6061. }
  6062. if (domain[i]) {
  6063. return 0;
  6064. }
  6065. /* The maximum length of the path to the password file is limited */
  6066. if ((strlen(fname) + 4) >= PATH_MAX) {
  6067. return 0;
  6068. }
  6069. /* Create a temporary file name. Length has been checked before. */
  6070. strcpy(tmp, fname);
  6071. strcat(tmp, ".tmp");
  6072. /* Create the file if does not exist */
  6073. /* Use of fopen here is OK, since fname is only ASCII */
  6074. if ((fp = fopen(fname, "a+")) != NULL) {
  6075. (void)fclose(fp);
  6076. }
  6077. /* Open the given file and temporary file */
  6078. if ((fp = fopen(fname, "r")) == NULL) {
  6079. return 0;
  6080. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  6081. fclose(fp);
  6082. return 0;
  6083. }
  6084. /* Copy the stuff to temporary file */
  6085. while (fgets(line, sizeof(line), fp) != NULL) {
  6086. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  6087. continue;
  6088. }
  6089. u[255] = 0;
  6090. d[255] = 0;
  6091. if (!strcmp(u, user) && !strcmp(d, domain)) {
  6092. found++;
  6093. if (pass != NULL) {
  6094. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  6095. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  6096. }
  6097. } else {
  6098. fprintf(fp2, "%s", line);
  6099. }
  6100. }
  6101. /* If new user, just add it */
  6102. if (!found && pass != NULL) {
  6103. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  6104. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  6105. }
  6106. /* Close files */
  6107. fclose(fp);
  6108. fclose(fp2);
  6109. /* Put the temp file in place of real file */
  6110. IGNORE_UNUSED_RESULT(remove(fname));
  6111. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  6112. return 1;
  6113. }
  6114. static int
  6115. is_valid_port(unsigned long port)
  6116. {
  6117. return (port <= 0xffff);
  6118. }
  6119. static int
  6120. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  6121. {
  6122. struct addrinfo hints, *res, *ressave;
  6123. int func_ret = 0;
  6124. int gai_ret;
  6125. memset(&hints, 0, sizeof(struct addrinfo));
  6126. hints.ai_family = af;
  6127. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  6128. if (gai_ret != 0) {
  6129. /* gai_strerror could be used to convert gai_ret to a string */
  6130. /* POSIX return values: see
  6131. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  6132. */
  6133. /* Windows return values: see
  6134. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  6135. */
  6136. return 0;
  6137. }
  6138. ressave = res;
  6139. while (res) {
  6140. if (dstlen >= res->ai_addrlen) {
  6141. memcpy(dst, res->ai_addr, res->ai_addrlen);
  6142. func_ret = 1;
  6143. }
  6144. res = res->ai_next;
  6145. }
  6146. freeaddrinfo(ressave);
  6147. return func_ret;
  6148. }
  6149. static int
  6150. connect_socket(struct mg_context *ctx /* may be NULL */,
  6151. const char *host,
  6152. int port,
  6153. int use_ssl,
  6154. char *ebuf,
  6155. size_t ebuf_len,
  6156. SOCKET *sock /* output: socket, must not be NULL */,
  6157. union usa *sa /* output: socket address, must not be NULL */
  6158. )
  6159. {
  6160. int ip_ver = 0;
  6161. *sock = INVALID_SOCKET;
  6162. memset(sa, 0, sizeof(*sa));
  6163. if (ebuf_len > 0) {
  6164. *ebuf = 0;
  6165. }
  6166. if (host == NULL) {
  6167. mg_snprintf(NULL,
  6168. NULL, /* No truncation check for ebuf */
  6169. ebuf,
  6170. ebuf_len,
  6171. "%s",
  6172. "NULL host");
  6173. return 0;
  6174. }
  6175. if (port <= 0 || !is_valid_port((unsigned)port)) {
  6176. mg_snprintf(NULL,
  6177. NULL, /* No truncation check for ebuf */
  6178. ebuf,
  6179. ebuf_len,
  6180. "%s",
  6181. "invalid port");
  6182. return 0;
  6183. }
  6184. #if !defined(NO_SSL)
  6185. #if !defined(NO_SSL_DL)
  6186. #ifdef OPENSSL_API_1_1
  6187. if (use_ssl && (TLS_client_method == NULL)) {
  6188. mg_snprintf(NULL,
  6189. NULL, /* No truncation check for ebuf */
  6190. ebuf,
  6191. ebuf_len,
  6192. "%s",
  6193. "SSL is not initialized");
  6194. return 0;
  6195. }
  6196. #else
  6197. if (use_ssl && (SSLv23_client_method == NULL)) {
  6198. mg_snprintf(NULL,
  6199. NULL, /* No truncation check for ebuf */
  6200. ebuf,
  6201. ebuf_len,
  6202. "%s",
  6203. "SSL is not initialized");
  6204. return 0;
  6205. }
  6206. #endif /* OPENSSL_API_1_1 */
  6207. #else
  6208. (void)use_ssl;
  6209. #endif /* NO_SSL_DL */
  6210. #else
  6211. (void)use_ssl;
  6212. #endif /* !defined(NO_SSL) */
  6213. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  6214. sa->sin.sin_port = htons((uint16_t)port);
  6215. ip_ver = 4;
  6216. #ifdef USE_IPV6
  6217. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  6218. sa->sin6.sin6_port = htons((uint16_t)port);
  6219. ip_ver = 6;
  6220. } else if (host[0] == '[') {
  6221. /* While getaddrinfo on Windows will work with [::1],
  6222. * getaddrinfo on Linux only works with ::1 (without []). */
  6223. size_t l = strlen(host + 1);
  6224. char *h = (l > 1) ? mg_strdup(host + 1) : NULL;
  6225. if (h) {
  6226. h[l - 1] = 0;
  6227. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  6228. sa->sin6.sin6_port = htons((uint16_t)port);
  6229. ip_ver = 6;
  6230. }
  6231. mg_free(h);
  6232. }
  6233. #endif
  6234. }
  6235. if (ip_ver == 0) {
  6236. mg_snprintf(NULL,
  6237. NULL, /* No truncation check for ebuf */
  6238. ebuf,
  6239. ebuf_len,
  6240. "%s",
  6241. "host not found");
  6242. return 0;
  6243. }
  6244. if (ip_ver == 4) {
  6245. *sock = socket(PF_INET, SOCK_STREAM, 0);
  6246. }
  6247. #ifdef USE_IPV6
  6248. else if (ip_ver == 6) {
  6249. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  6250. }
  6251. #endif
  6252. if (*sock == INVALID_SOCKET) {
  6253. mg_snprintf(NULL,
  6254. NULL, /* No truncation check for ebuf */
  6255. ebuf,
  6256. ebuf_len,
  6257. "socket(): %s",
  6258. strerror(ERRNO));
  6259. return 0;
  6260. }
  6261. set_close_on_exec(*sock, fc(ctx));
  6262. if ((ip_ver == 4)
  6263. && (connect(*sock, (struct sockaddr *)&sa->sin, sizeof(sa->sin))
  6264. == 0)) {
  6265. /* connected with IPv4 */
  6266. set_blocking_mode(*sock, 0);
  6267. return 1;
  6268. }
  6269. #ifdef USE_IPV6
  6270. if ((ip_ver == 6)
  6271. && (connect(*sock, (struct sockaddr *)&sa->sin6, sizeof(sa->sin6))
  6272. == 0)) {
  6273. /* connected with IPv6 */
  6274. set_blocking_mode(*sock, 0);
  6275. return 1;
  6276. }
  6277. #endif
  6278. /* Not connected */
  6279. mg_snprintf(NULL,
  6280. NULL, /* No truncation check for ebuf */
  6281. ebuf,
  6282. ebuf_len,
  6283. "connect(%s:%d): %s",
  6284. host,
  6285. port,
  6286. strerror(ERRNO));
  6287. closesocket(*sock);
  6288. *sock = INVALID_SOCKET;
  6289. return 0;
  6290. }
  6291. int
  6292. mg_url_encode(const char *src, char *dst, size_t dst_len)
  6293. {
  6294. static const char *dont_escape = "._-$,;~()";
  6295. static const char *hex = "0123456789abcdef";
  6296. char *pos = dst;
  6297. const char *end = dst + dst_len - 1;
  6298. for (; *src != '\0' && pos < end; src++, pos++) {
  6299. if (isalnum(*(const unsigned char *)src)
  6300. || strchr(dont_escape, *(const unsigned char *)src) != NULL) {
  6301. *pos = *src;
  6302. } else if (pos + 2 < end) {
  6303. pos[0] = '%';
  6304. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  6305. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  6306. pos += 2;
  6307. } else {
  6308. break;
  6309. }
  6310. }
  6311. *pos = '\0';
  6312. return (*src == '\0') ? (int)(pos - dst) : -1;
  6313. }
  6314. static void
  6315. print_dir_entry(struct de *de)
  6316. {
  6317. char size[64], mod[64], href[PATH_MAX * 3 /* worst case */];
  6318. struct tm *tm;
  6319. if (de->file.is_directory) {
  6320. mg_snprintf(de->conn,
  6321. NULL, /* Buffer is big enough */
  6322. size,
  6323. sizeof(size),
  6324. "%s",
  6325. "[DIRECTORY]");
  6326. } else {
  6327. /* We use (signed) cast below because MSVC 6 compiler cannot
  6328. * convert unsigned __int64 to double. Sigh. */
  6329. if (de->file.size < 1024) {
  6330. mg_snprintf(de->conn,
  6331. NULL, /* Buffer is big enough */
  6332. size,
  6333. sizeof(size),
  6334. "%d",
  6335. (int)de->file.size);
  6336. } else if (de->file.size < 0x100000) {
  6337. mg_snprintf(de->conn,
  6338. NULL, /* Buffer is big enough */
  6339. size,
  6340. sizeof(size),
  6341. "%.1fk",
  6342. (double)de->file.size / 1024.0);
  6343. } else if (de->file.size < 0x40000000) {
  6344. mg_snprintf(de->conn,
  6345. NULL, /* Buffer is big enough */
  6346. size,
  6347. sizeof(size),
  6348. "%.1fM",
  6349. (double)de->file.size / 1048576);
  6350. } else {
  6351. mg_snprintf(de->conn,
  6352. NULL, /* Buffer is big enough */
  6353. size,
  6354. sizeof(size),
  6355. "%.1fG",
  6356. (double)de->file.size / 1073741824);
  6357. }
  6358. }
  6359. /* Note: mg_snprintf will not cause a buffer overflow above.
  6360. * So, string truncation checks are not required here. */
  6361. tm = localtime(&de->file.last_modified);
  6362. if (tm != NULL) {
  6363. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  6364. } else {
  6365. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  6366. mod[sizeof(mod) - 1] = '\0';
  6367. }
  6368. mg_url_encode(de->file_name, href, sizeof(href));
  6369. de->conn->num_bytes_sent +=
  6370. mg_printf(de->conn,
  6371. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  6372. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  6373. de->conn->request_info.local_uri,
  6374. href,
  6375. de->file.is_directory ? "/" : "",
  6376. de->file_name,
  6377. de->file.is_directory ? "/" : "",
  6378. mod,
  6379. size);
  6380. }
  6381. /* This function is called from send_directory() and used for
  6382. * sorting directory entries by size, or name, or modification time.
  6383. * On windows, __cdecl specification is needed in case if project is built
  6384. * with __stdcall convention. qsort always requires __cdels callback. */
  6385. static int WINCDECL
  6386. compare_dir_entries(const void *p1, const void *p2)
  6387. {
  6388. if (p1 && p2) {
  6389. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  6390. const char *query_string = a->conn->request_info.query_string;
  6391. int cmp_result = 0;
  6392. if (query_string == NULL) {
  6393. query_string = "na";
  6394. }
  6395. if (a->file.is_directory && !b->file.is_directory) {
  6396. return -1; /* Always put directories on top */
  6397. } else if (!a->file.is_directory && b->file.is_directory) {
  6398. return 1; /* Always put directories on top */
  6399. } else if (*query_string == 'n') {
  6400. cmp_result = strcmp(a->file_name, b->file_name);
  6401. } else if (*query_string == 's') {
  6402. cmp_result = (a->file.size == b->file.size)
  6403. ? 0
  6404. : ((a->file.size > b->file.size) ? 1 : -1);
  6405. } else if (*query_string == 'd') {
  6406. cmp_result =
  6407. (a->file.last_modified == b->file.last_modified)
  6408. ? 0
  6409. : ((a->file.last_modified > b->file.last_modified) ? 1
  6410. : -1);
  6411. }
  6412. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  6413. }
  6414. return 0;
  6415. }
  6416. static int
  6417. must_hide_file(struct mg_connection *conn, const char *path)
  6418. {
  6419. if (conn && conn->ctx) {
  6420. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  6421. const char *pattern = conn->ctx->config[HIDE_FILES];
  6422. return match_prefix(pw_pattern, strlen(pw_pattern), path) > 0
  6423. || (pattern != NULL
  6424. && match_prefix(pattern, strlen(pattern), path) > 0);
  6425. }
  6426. return 0;
  6427. }
  6428. static int
  6429. scan_directory(struct mg_connection *conn,
  6430. const char *dir,
  6431. void *data,
  6432. void (*cb)(struct de *, void *))
  6433. {
  6434. char path[PATH_MAX];
  6435. struct dirent *dp;
  6436. DIR *dirp;
  6437. struct de de;
  6438. int truncated;
  6439. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  6440. return 0;
  6441. } else {
  6442. de.conn = conn;
  6443. while ((dp = mg_readdir(dirp)) != NULL) {
  6444. /* Do not show current dir and hidden files */
  6445. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  6446. || must_hide_file(conn, dp->d_name)) {
  6447. continue;
  6448. }
  6449. mg_snprintf(
  6450. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  6451. /* If we don't memset stat structure to zero, mtime will have
  6452. * garbage and strftime() will segfault later on in
  6453. * print_dir_entry(). memset is required only if mg_stat()
  6454. * fails. For more details, see
  6455. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  6456. memset(&de.file, 0, sizeof(de.file));
  6457. if (truncated) {
  6458. /* If the path is not complete, skip processing. */
  6459. continue;
  6460. }
  6461. if (!mg_stat(conn, path, &de.file)) {
  6462. mg_cry(conn,
  6463. "%s: mg_stat(%s) failed: %s",
  6464. __func__,
  6465. path,
  6466. strerror(ERRNO));
  6467. }
  6468. de.file_name = dp->d_name;
  6469. cb(&de, data);
  6470. }
  6471. (void)mg_closedir(dirp);
  6472. }
  6473. return 1;
  6474. }
  6475. #if !defined(NO_FILES)
  6476. static int
  6477. remove_directory(struct mg_connection *conn, const char *dir)
  6478. {
  6479. char path[PATH_MAX];
  6480. struct dirent *dp;
  6481. DIR *dirp;
  6482. struct de de;
  6483. int truncated;
  6484. int ok = 1;
  6485. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  6486. return 0;
  6487. } else {
  6488. de.conn = conn;
  6489. while ((dp = mg_readdir(dirp)) != NULL) {
  6490. /* Do not show current dir (but show hidden files as they will
  6491. * also be removed) */
  6492. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  6493. continue;
  6494. }
  6495. mg_snprintf(
  6496. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  6497. /* If we don't memset stat structure to zero, mtime will have
  6498. * garbage and strftime() will segfault later on in
  6499. * print_dir_entry(). memset is required only if mg_stat()
  6500. * fails. For more details, see
  6501. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  6502. memset(&de.file, 0, sizeof(de.file));
  6503. if (truncated) {
  6504. /* Do not delete anything shorter */
  6505. ok = 0;
  6506. continue;
  6507. }
  6508. if (!mg_stat(conn, path, &de.file)) {
  6509. mg_cry(conn,
  6510. "%s: mg_stat(%s) failed: %s",
  6511. __func__,
  6512. path,
  6513. strerror(ERRNO));
  6514. ok = 0;
  6515. }
  6516. if (de.file.is_directory) {
  6517. if (remove_directory(conn, path) == 0) {
  6518. ok = 0;
  6519. }
  6520. } else {
  6521. /* This will fail file is the file is in memory */
  6522. if (mg_remove(conn, path) == 0) {
  6523. ok = 0;
  6524. }
  6525. }
  6526. }
  6527. (void)mg_closedir(dirp);
  6528. IGNORE_UNUSED_RESULT(rmdir(dir));
  6529. }
  6530. return ok;
  6531. }
  6532. #endif
  6533. struct dir_scan_data {
  6534. struct de *entries;
  6535. unsigned int num_entries;
  6536. unsigned int arr_size;
  6537. };
  6538. /* Behaves like realloc(), but frees original pointer on failure */
  6539. static void *
  6540. realloc2(void *ptr, size_t size)
  6541. {
  6542. void *new_ptr = mg_realloc(ptr, size);
  6543. if (new_ptr == NULL) {
  6544. mg_free(ptr);
  6545. }
  6546. return new_ptr;
  6547. }
  6548. static void
  6549. dir_scan_callback(struct de *de, void *data)
  6550. {
  6551. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  6552. if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {
  6553. dsd->arr_size *= 2;
  6554. dsd->entries =
  6555. (struct de *)realloc2(dsd->entries,
  6556. dsd->arr_size * sizeof(dsd->entries[0]));
  6557. }
  6558. if (dsd->entries == NULL) {
  6559. /* TODO(lsm, low): propagate an error to the caller */
  6560. dsd->num_entries = 0;
  6561. } else {
  6562. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  6563. dsd->entries[dsd->num_entries].file = de->file;
  6564. dsd->entries[dsd->num_entries].conn = de->conn;
  6565. dsd->num_entries++;
  6566. }
  6567. }
  6568. static void
  6569. handle_directory_request(struct mg_connection *conn, const char *dir)
  6570. {
  6571. unsigned int i;
  6572. int sort_direction;
  6573. struct dir_scan_data data = {NULL, 0, 128};
  6574. char date[64];
  6575. time_t curtime = time(NULL);
  6576. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  6577. mg_send_http_error(conn,
  6578. 500,
  6579. "Error: Cannot open directory\nopendir(%s): %s",
  6580. dir,
  6581. strerror(ERRNO));
  6582. return;
  6583. }
  6584. gmt_time_string(date, sizeof(date), &curtime);
  6585. if (!conn) {
  6586. return;
  6587. }
  6588. sort_direction = ((conn->request_info.query_string != NULL)
  6589. && (conn->request_info.query_string[1] == 'd'))
  6590. ? 'a'
  6591. : 'd';
  6592. conn->must_close = 1;
  6593. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  6594. send_static_cache_header(conn);
  6595. send_additional_header(conn);
  6596. mg_printf(conn,
  6597. "Date: %s\r\n"
  6598. "Connection: close\r\n"
  6599. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  6600. date);
  6601. conn->num_bytes_sent +=
  6602. mg_printf(conn,
  6603. "<html><head><title>Index of %s</title>"
  6604. "<style>th {text-align: left;}</style></head>"
  6605. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  6606. "<tr><th><a href=\"?n%c\">Name</a></th>"
  6607. "<th><a href=\"?d%c\">Modified</a></th>"
  6608. "<th><a href=\"?s%c\">Size</a></th></tr>"
  6609. "<tr><td colspan=\"3\"><hr></td></tr>",
  6610. conn->request_info.local_uri,
  6611. conn->request_info.local_uri,
  6612. sort_direction,
  6613. sort_direction,
  6614. sort_direction);
  6615. /* Print first entry - link to a parent directory */
  6616. conn->num_bytes_sent +=
  6617. mg_printf(conn,
  6618. "<tr><td><a href=\"%s%s\">%s</a></td>"
  6619. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  6620. conn->request_info.local_uri,
  6621. "..",
  6622. "Parent directory",
  6623. "-",
  6624. "-");
  6625. /* Sort and print directory entries */
  6626. if (data.entries != NULL) {
  6627. qsort(data.entries,
  6628. (size_t)data.num_entries,
  6629. sizeof(data.entries[0]),
  6630. compare_dir_entries);
  6631. for (i = 0; i < data.num_entries; i++) {
  6632. print_dir_entry(&data.entries[i]);
  6633. mg_free(data.entries[i].file_name);
  6634. }
  6635. mg_free(data.entries);
  6636. }
  6637. conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");
  6638. conn->status_code = 200;
  6639. }
  6640. /* Send len bytes from the opened file to the client. */
  6641. static void
  6642. send_file_data(struct mg_connection *conn,
  6643. struct mg_file *filep,
  6644. int64_t offset,
  6645. int64_t len)
  6646. {
  6647. char buf[MG_BUF_LEN];
  6648. int to_read, num_read, num_written;
  6649. int64_t size;
  6650. if (!filep || !conn) {
  6651. return;
  6652. }
  6653. /* Sanity check the offset */
  6654. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  6655. : (int64_t)(filep->stat.size);
  6656. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  6657. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  6658. /* file stored in memory */
  6659. if (len > size - offset) {
  6660. len = size - offset;
  6661. }
  6662. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  6663. } else if (len > 0 && filep->access.fp != NULL) {
  6664. /* file stored on disk */
  6665. #if defined(__linux__)
  6666. /* sendfile is only available for Linux */
  6667. if ((conn->ssl == 0) && (conn->throttle == 0)
  6668. && (!mg_strcasecmp(conn->ctx->config[ALLOW_SENDFILE_CALL],
  6669. "yes"))) {
  6670. off_t sf_offs = (off_t)offset;
  6671. ssize_t sf_sent;
  6672. int sf_file = fileno(filep->access.fp);
  6673. int loop_cnt = 0;
  6674. do {
  6675. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  6676. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  6677. size_t sf_tosend =
  6678. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  6679. sf_sent =
  6680. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  6681. if (sf_sent > 0) {
  6682. conn->num_bytes_sent += sf_sent;
  6683. len -= sf_sent;
  6684. offset += sf_sent;
  6685. } else if (loop_cnt == 0) {
  6686. /* This file can not be sent using sendfile.
  6687. * This might be the case for pseudo-files in the
  6688. * /sys/ and /proc/ file system.
  6689. * Use the regular user mode copy code instead. */
  6690. break;
  6691. } else if (sf_sent == 0) {
  6692. /* No error, but 0 bytes sent. May be EOF? */
  6693. return;
  6694. }
  6695. loop_cnt++;
  6696. } while ((len > 0) && (sf_sent >= 0));
  6697. if (sf_sent > 0) {
  6698. return; /* OK */
  6699. }
  6700. /* sf_sent<0 means error, thus fall back to the classic way */
  6701. /* This is always the case, if sf_file is not a "normal" file,
  6702. * e.g., for sending data from the output of a CGI process. */
  6703. offset = (int64_t)sf_offs;
  6704. }
  6705. #endif
  6706. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  6707. mg_cry(conn, "%s: fseeko() failed: %s", __func__, strerror(ERRNO));
  6708. mg_send_http_error(
  6709. conn,
  6710. 500,
  6711. "%s",
  6712. "Error: Unable to access file at requested position.");
  6713. } else {
  6714. while (len > 0) {
  6715. /* Calculate how much to read from the file in the buffer */
  6716. to_read = sizeof(buf);
  6717. if ((int64_t)to_read > len) {
  6718. to_read = (int)len;
  6719. }
  6720. /* Read from file, exit the loop on error */
  6721. if ((num_read =
  6722. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  6723. <= 0) {
  6724. break;
  6725. }
  6726. /* Send read bytes to the client, exit the loop on error */
  6727. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  6728. != num_read) {
  6729. break;
  6730. }
  6731. /* Both read and were successful, adjust counters */
  6732. conn->num_bytes_sent += num_written;
  6733. len -= num_written;
  6734. }
  6735. }
  6736. }
  6737. }
  6738. static int
  6739. parse_range_header(const char *header, int64_t *a, int64_t *b)
  6740. {
  6741. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  6742. }
  6743. static void
  6744. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  6745. {
  6746. if (filestat != NULL && buf != NULL) {
  6747. mg_snprintf(NULL,
  6748. NULL, /* All calls to construct_etag use 64 byte buffer */
  6749. buf,
  6750. buf_len,
  6751. "\"%lx.%" INT64_FMT "\"",
  6752. (unsigned long)filestat->last_modified,
  6753. filestat->size);
  6754. }
  6755. }
  6756. static void
  6757. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  6758. {
  6759. if (filep != NULL && filep->fp != NULL) {
  6760. #ifdef _WIN32
  6761. (void)conn; /* Unused. */
  6762. #else
  6763. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  6764. mg_cry(conn,
  6765. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  6766. __func__,
  6767. strerror(ERRNO));
  6768. }
  6769. #endif
  6770. }
  6771. }
  6772. static void
  6773. handle_static_file_request(struct mg_connection *conn,
  6774. const char *path,
  6775. struct mg_file *filep,
  6776. const char *mime_type,
  6777. const char *additional_headers)
  6778. {
  6779. char date[64], lm[64], etag[64];
  6780. char range[128]; /* large enough, so there will be no overflow */
  6781. const char *msg = "OK", *hdr;
  6782. time_t curtime = time(NULL);
  6783. int64_t cl, r1, r2;
  6784. struct vec mime_vec;
  6785. int n, truncated;
  6786. char gz_path[PATH_MAX];
  6787. const char *encoding = "";
  6788. const char *cors1, *cors2, *cors3;
  6789. if (conn == NULL || conn->ctx == NULL || filep == NULL) {
  6790. return;
  6791. }
  6792. if (mime_type == NULL) {
  6793. get_mime_type(conn->ctx, path, &mime_vec);
  6794. } else {
  6795. mime_vec.ptr = mime_type;
  6796. mime_vec.len = strlen(mime_type);
  6797. }
  6798. if (filep->stat.size > INT64_MAX) {
  6799. mg_send_http_error(conn,
  6800. 500,
  6801. "Error: File size is too large to send\n%" INT64_FMT,
  6802. filep->stat.size);
  6803. }
  6804. cl = (int64_t)filep->stat.size;
  6805. conn->status_code = 200;
  6806. range[0] = '\0';
  6807. /* if this file is in fact a pre-gzipped file, rewrite its filename
  6808. * it's important to rewrite the filename after resolving
  6809. * the mime type from it, to preserve the actual file's type */
  6810. if (filep->stat.is_gzipped) {
  6811. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  6812. if (truncated) {
  6813. mg_send_http_error(conn,
  6814. 500,
  6815. "Error: Path of zipped file too long (%s)",
  6816. path);
  6817. return;
  6818. }
  6819. path = gz_path;
  6820. encoding = "Content-Encoding: gzip\r\n";
  6821. }
  6822. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  6823. mg_send_http_error(conn,
  6824. 500,
  6825. "Error: Cannot open file\nfopen(%s): %s",
  6826. path,
  6827. strerror(ERRNO));
  6828. return;
  6829. }
  6830. fclose_on_exec(&filep->access, conn);
  6831. /* If Range: header specified, act accordingly */
  6832. r1 = r2 = 0;
  6833. hdr = mg_get_header(conn, "Range");
  6834. if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 && r1 >= 0
  6835. && r2 >= 0) {
  6836. /* actually, range requests don't play well with a pre-gzipped
  6837. * file (since the range is specified in the uncompressed space) */
  6838. if (filep->stat.is_gzipped) {
  6839. mg_send_http_error(
  6840. conn,
  6841. 416, /* 416 = Range Not Satisfiable */
  6842. "%s",
  6843. "Error: Range requests in gzipped files are not supported");
  6844. (void)mg_fclose(
  6845. &filep->access); /* ignore error on read only file */
  6846. return;
  6847. }
  6848. conn->status_code = 206;
  6849. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  6850. mg_snprintf(conn,
  6851. NULL, /* range buffer is big enough */
  6852. range,
  6853. sizeof(range),
  6854. "Content-Range: bytes "
  6855. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  6856. r1,
  6857. r1 + cl - 1,
  6858. filep->stat.size);
  6859. msg = "Partial Content";
  6860. }
  6861. hdr = mg_get_header(conn, "Origin");
  6862. if (hdr) {
  6863. /* Cross-origin resource sharing (CORS), see
  6864. * http://www.html5rocks.com/en/tutorials/cors/,
  6865. * http://www.html5rocks.com/static/images/cors_server_flowchart.png -
  6866. * preflight is not supported for files. */
  6867. cors1 = "Access-Control-Allow-Origin: ";
  6868. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  6869. cors3 = "\r\n";
  6870. } else {
  6871. cors1 = cors2 = cors3 = "";
  6872. }
  6873. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
  6874. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  6875. gmt_time_string(date, sizeof(date), &curtime);
  6876. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  6877. construct_etag(etag, sizeof(etag), &filep->stat);
  6878. (void)mg_printf(conn,
  6879. "HTTP/1.1 %d %s\r\n"
  6880. "%s%s%s"
  6881. "Date: %s\r\n",
  6882. conn->status_code,
  6883. msg,
  6884. cors1,
  6885. cors2,
  6886. cors3,
  6887. date);
  6888. send_static_cache_header(conn);
  6889. send_additional_header(conn);
  6890. (void)mg_printf(conn,
  6891. "Last-Modified: %s\r\n"
  6892. "Etag: %s\r\n"
  6893. "Content-Type: %.*s\r\n"
  6894. "Content-Length: %" INT64_FMT "\r\n"
  6895. "Connection: %s\r\n"
  6896. "Accept-Ranges: bytes\r\n"
  6897. "%s%s",
  6898. lm,
  6899. etag,
  6900. (int)mime_vec.len,
  6901. mime_vec.ptr,
  6902. cl,
  6903. suggest_connection_header(conn),
  6904. range,
  6905. encoding);
  6906. /* The previous code must not add any header starting with X- to make
  6907. * sure no one of the additional_headers is included twice */
  6908. if (additional_headers != NULL) {
  6909. (void)mg_printf(conn,
  6910. "%.*s\r\n\r\n",
  6911. (int)strlen(additional_headers),
  6912. additional_headers);
  6913. } else {
  6914. (void)mg_printf(conn, "\r\n");
  6915. }
  6916. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  6917. send_file_data(conn, filep, r1, cl);
  6918. }
  6919. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  6920. }
  6921. #if !defined(NO_CACHING)
  6922. static void
  6923. handle_not_modified_static_file_request(struct mg_connection *conn,
  6924. struct mg_file *filep)
  6925. {
  6926. char date[64], lm[64], etag[64];
  6927. time_t curtime = time(NULL);
  6928. if (conn == NULL || filep == NULL) {
  6929. return;
  6930. }
  6931. conn->status_code = 304;
  6932. gmt_time_string(date, sizeof(date), &curtime);
  6933. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  6934. construct_etag(etag, sizeof(etag), &filep->stat);
  6935. (void)mg_printf(conn,
  6936. "HTTP/1.1 %d %s\r\n"
  6937. "Date: %s\r\n",
  6938. conn->status_code,
  6939. mg_get_response_code_text(conn, conn->status_code),
  6940. date);
  6941. send_static_cache_header(conn);
  6942. send_additional_header(conn);
  6943. (void)mg_printf(conn,
  6944. "Last-Modified: %s\r\n"
  6945. "Etag: %s\r\n"
  6946. "Connection: %s\r\n"
  6947. "\r\n",
  6948. lm,
  6949. etag,
  6950. suggest_connection_header(conn));
  6951. }
  6952. #endif
  6953. void
  6954. mg_send_file(struct mg_connection *conn, const char *path)
  6955. {
  6956. mg_send_mime_file(conn, path, NULL);
  6957. }
  6958. void
  6959. mg_send_mime_file(struct mg_connection *conn,
  6960. const char *path,
  6961. const char *mime_type)
  6962. {
  6963. mg_send_mime_file2(conn, path, mime_type, NULL);
  6964. }
  6965. void
  6966. mg_send_mime_file2(struct mg_connection *conn,
  6967. const char *path,
  6968. const char *mime_type,
  6969. const char *additional_headers)
  6970. {
  6971. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6972. if (mg_stat(conn, path, &file.stat)) {
  6973. if (file.stat.is_directory) {
  6974. if (!conn) {
  6975. return;
  6976. }
  6977. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  6978. "yes")) {
  6979. handle_directory_request(conn, path);
  6980. } else {
  6981. mg_send_http_error(conn,
  6982. 403,
  6983. "%s",
  6984. "Error: Directory listing denied");
  6985. }
  6986. } else {
  6987. handle_static_file_request(
  6988. conn, path, &file, mime_type, additional_headers);
  6989. }
  6990. } else {
  6991. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  6992. }
  6993. }
  6994. /* For a given PUT path, create all intermediate subdirectories.
  6995. * Return 0 if the path itself is a directory.
  6996. * Return 1 if the path leads to a file.
  6997. * Return -1 for if the path is too long.
  6998. * Return -2 if path can not be created.
  6999. */
  7000. static int
  7001. put_dir(struct mg_connection *conn, const char *path)
  7002. {
  7003. char buf[PATH_MAX];
  7004. const char *s, *p;
  7005. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7006. size_t len;
  7007. int res = 1;
  7008. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  7009. len = (size_t)(p - path);
  7010. if (len >= sizeof(buf)) {
  7011. /* path too long */
  7012. res = -1;
  7013. break;
  7014. }
  7015. memcpy(buf, path, len);
  7016. buf[len] = '\0';
  7017. /* Try to create intermediate directory */
  7018. DEBUG_TRACE("mkdir(%s)", buf);
  7019. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  7020. /* path does not exixt and can not be created */
  7021. res = -2;
  7022. break;
  7023. }
  7024. /* Is path itself a directory? */
  7025. if (p[1] == '\0') {
  7026. res = 0;
  7027. }
  7028. }
  7029. return res;
  7030. }
  7031. static void
  7032. remove_bad_file(const struct mg_connection *conn, const char *path)
  7033. {
  7034. int r = mg_remove(conn, path);
  7035. if (r != 0) {
  7036. mg_cry(conn, "%s: Cannot remove invalid file %s", __func__, path);
  7037. }
  7038. }
  7039. long long
  7040. mg_store_body(struct mg_connection *conn, const char *path)
  7041. {
  7042. char buf[MG_BUF_LEN];
  7043. long long len = 0;
  7044. int ret, n;
  7045. struct mg_file fi;
  7046. if (conn->consumed_content != 0) {
  7047. mg_cry(conn, "%s: Contents already consumed", __func__);
  7048. return -11;
  7049. }
  7050. ret = put_dir(conn, path);
  7051. if (ret < 0) {
  7052. /* -1 for path too long,
  7053. * -2 for path can not be created. */
  7054. return ret;
  7055. }
  7056. if (ret != 1) {
  7057. /* Return 0 means, path itself is a directory. */
  7058. return 0;
  7059. }
  7060. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  7061. return -12;
  7062. }
  7063. ret = mg_read(conn, buf, sizeof(buf));
  7064. while (ret > 0) {
  7065. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  7066. if (n != ret) {
  7067. (void)mg_fclose(
  7068. &fi.access); /* File is bad and will be removed anyway. */
  7069. remove_bad_file(conn, path);
  7070. return -13;
  7071. }
  7072. len += ret;
  7073. ret = mg_read(conn, buf, sizeof(buf));
  7074. }
  7075. /* File is open for writing. If fclose fails, there was probably an
  7076. * error flushing the buffer to disk, so the file on disk might be
  7077. * broken. Delete it and return an error to the caller. */
  7078. if (mg_fclose(&fi.access) != 0) {
  7079. remove_bad_file(conn, path);
  7080. return -14;
  7081. }
  7082. return len;
  7083. }
  7084. /* Parse HTTP headers from the given buffer, advance buf pointer
  7085. * to the point where parsing stopped.
  7086. * All parameters must be valid pointers (not NULL).
  7087. * Return <0 on error. */
  7088. static int
  7089. parse_http_headers(char **buf, struct mg_request_info *ri)
  7090. {
  7091. int i;
  7092. ri->num_headers = 0;
  7093. for (i = 0; i < (int)ARRAY_SIZE(ri->http_headers); i++) {
  7094. char *dp = *buf;
  7095. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  7096. dp++;
  7097. }
  7098. if (dp == *buf) {
  7099. /* End of headers reached. */
  7100. break;
  7101. }
  7102. if (*dp != ':') {
  7103. /* This is not a valid field. */
  7104. return -1;
  7105. }
  7106. /* End of header key (*dp == ':') */
  7107. /* Truncate here and set the key name */
  7108. *dp = 0;
  7109. ri->http_headers[i].name = *buf;
  7110. do {
  7111. dp++;
  7112. } while (*dp == ' ');
  7113. /* The rest of the line is the value */
  7114. ri->http_headers[i].value = dp;
  7115. *buf = dp + strcspn(dp, "\r\n");
  7116. if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) {
  7117. *buf = NULL;
  7118. }
  7119. ri->num_headers = i + 1;
  7120. if (*buf) {
  7121. (*buf)[0] = 0;
  7122. (*buf)[1] = 0;
  7123. *buf += 2;
  7124. } else {
  7125. *buf = dp;
  7126. break;
  7127. }
  7128. if ((*buf)[0] == '\r') {
  7129. /* This is the end of the header */
  7130. break;
  7131. }
  7132. }
  7133. return ri->num_headers;
  7134. }
  7135. static int
  7136. is_valid_http_method(const char *method)
  7137. {
  7138. /* Check if the method is known to the server. The list of all known
  7139. * HTTP methods can be found here at
  7140. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  7141. */
  7142. return !strcmp(method, "GET") /* HTTP (RFC 2616) */
  7143. || !strcmp(method, "POST") /* HTTP (RFC 2616) */
  7144. || !strcmp(method, "HEAD") /* HTTP (RFC 2616) */
  7145. || !strcmp(method, "PUT") /* HTTP (RFC 2616) */
  7146. || !strcmp(method, "DELETE") /* HTTP (RFC 2616) */
  7147. || !strcmp(method, "OPTIONS") /* HTTP (RFC 2616) */
  7148. /* TRACE method (RFC 2616) is not supported for security reasons */
  7149. || !strcmp(method, "CONNECT") /* HTTP (RFC 2616) */
  7150. || !strcmp(method, "PROPFIND") /* WEBDAV (RFC 2518) */
  7151. || !strcmp(method, "MKCOL") /* WEBDAV (RFC 2518) */
  7152. /* Unsupported WEBDAV Methods: */
  7153. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  7154. /* + 11 methods from RFC 3253 */
  7155. /* ORDERPATCH (RFC 3648) */
  7156. /* ACL (RFC 3744) */
  7157. /* SEARCH (RFC 5323) */
  7158. /* + MicroSoft extensions
  7159. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  7160. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  7161. || !strcmp(method, "PATCH") /* PATCH method (RFC 5789) */
  7162. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  7163. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  7164. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  7165. * to be useful for REST in case a "GET request with body" is
  7166. * required. */
  7167. || !strcmp(method, "REPORT") /* REPORT method (RFC 3253) */
  7168. ;
  7169. }
  7170. /* Parse HTTP request, fill in mg_request_info structure.
  7171. * This function modifies the buffer by NUL-terminating
  7172. * HTTP request components, header names and header values.
  7173. * Parameters:
  7174. * buf (in/out): pointer to the HTTP header to parse and split
  7175. * len (in): length of HTTP header buffer
  7176. * re (out): parsed header as mg_request_info
  7177. * buf and ri must be valid pointers (not NULL), len>0.
  7178. * Returns <0 on error. */
  7179. static int
  7180. parse_http_message(char *buf, int len, struct mg_request_info *ri)
  7181. {
  7182. int is_request, request_length;
  7183. char *start_line;
  7184. request_length = get_request_len(buf, len);
  7185. if (request_length > 0) {
  7186. /* Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_addr,
  7187. * remote_port */
  7188. ri->remote_user = ri->request_method = ri->request_uri =
  7189. ri->http_version = NULL;
  7190. ri->num_headers = 0;
  7191. buf[request_length - 1] = '\0';
  7192. /* RFC says that all initial whitespaces should be ingored */
  7193. while (*buf != '\0' && isspace(*(unsigned char *)buf)) {
  7194. buf++;
  7195. }
  7196. start_line = skip(&buf, "\r\n");
  7197. ri->request_method = skip(&start_line, " ");
  7198. ri->request_uri = skip(&start_line, " ");
  7199. ri->http_version = start_line;
  7200. /* HTTP message could be either HTTP request:
  7201. * "GET / HTTP/1.0 ..."
  7202. * or a HTTP response:
  7203. * "HTTP/1.0 200 OK ..."
  7204. * otherwise it is invalid.
  7205. */
  7206. is_request = is_valid_http_method(ri->request_method);
  7207. if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0)
  7208. || (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
  7209. /* Not a valid request or response: invalid */
  7210. return -1;
  7211. }
  7212. if (is_request) {
  7213. ri->http_version += 5;
  7214. }
  7215. if (parse_http_headers(&buf, ri) < 0) {
  7216. /* Error while parsing headers */
  7217. return -1;
  7218. }
  7219. }
  7220. return request_length;
  7221. }
  7222. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  7223. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  7224. * buffer (which marks the end of HTTP request). Buffer buf may already
  7225. * have some data. The length of the data is stored in nread.
  7226. * Upon every read operation, increase nread by the number of bytes read. */
  7227. static int
  7228. read_request(FILE *fp,
  7229. struct mg_connection *conn,
  7230. char *buf,
  7231. int bufsiz,
  7232. int *nread)
  7233. {
  7234. int request_len, n = 0;
  7235. struct timespec last_action_time;
  7236. double request_timeout;
  7237. if (!conn) {
  7238. return 0;
  7239. }
  7240. memset(&last_action_time, 0, sizeof(last_action_time));
  7241. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  7242. /* value of request_timeout is in seconds, config in milliseconds */
  7243. request_timeout = atof(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  7244. } else {
  7245. request_timeout = -1.0;
  7246. }
  7247. if (conn->handled_requests > 0) {
  7248. if (conn->ctx->config[KEEP_ALIVE_TIMEOUT]) {
  7249. request_timeout =
  7250. atof(conn->ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  7251. }
  7252. }
  7253. request_len = get_request_len(buf, *nread);
  7254. /* first time reading from this connection */
  7255. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  7256. while (request_len == 0) {
  7257. /* Full request not yet received */
  7258. if (conn->ctx->stop_flag != 0) {
  7259. /* Server is to be stopped. */
  7260. return -1;
  7261. }
  7262. if (*nread >= bufsiz) {
  7263. /* Request too long */
  7264. return -2;
  7265. }
  7266. n = pull_inner(
  7267. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  7268. if (n == -2) {
  7269. /* Receive error */
  7270. return -1;
  7271. }
  7272. if (n > 0) {
  7273. *nread += n;
  7274. request_len = get_request_len(buf, *nread);
  7275. } else {
  7276. request_len = 0;
  7277. }
  7278. if ((request_len == 0) && (request_timeout >= 0)) {
  7279. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  7280. > request_timeout) {
  7281. /* Timeout */
  7282. return -1;
  7283. }
  7284. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  7285. }
  7286. }
  7287. return request_len;
  7288. }
  7289. #if !defined(NO_CACHING)
  7290. /* Return True if we should reply 304 Not Modified. */
  7291. static int
  7292. is_not_modified(const struct mg_connection *conn,
  7293. const struct mg_file_stat *filestat)
  7294. {
  7295. char etag[64];
  7296. const char *ims = mg_get_header(conn, "If-Modified-Since");
  7297. const char *inm = mg_get_header(conn, "If-None-Match");
  7298. construct_etag(etag, sizeof(etag), filestat);
  7299. return (inm != NULL && !mg_strcasecmp(etag, inm))
  7300. || ((ims != NULL)
  7301. && (filestat->last_modified <= parse_date_string(ims)));
  7302. }
  7303. #endif /* !NO_CACHING */
  7304. #if !defined(NO_CGI) || !defined(NO_FILES)
  7305. static int
  7306. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  7307. {
  7308. const char *expect, *body;
  7309. char buf[MG_BUF_LEN];
  7310. int to_read, nread, success = 0;
  7311. int64_t buffered_len;
  7312. double timeout = -1.0;
  7313. if (!conn) {
  7314. return 0;
  7315. }
  7316. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  7317. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  7318. }
  7319. expect = mg_get_header(conn, "Expect");
  7320. /* assert(fp != NULL); */
  7321. if (!fp) {
  7322. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  7323. return 0;
  7324. }
  7325. if (conn->content_len == -1 && !conn->is_chunked) {
  7326. /* Content length is not specified by the client. */
  7327. mg_send_http_error(conn,
  7328. 411,
  7329. "%s",
  7330. "Error: Client did not specify content length");
  7331. } else if ((expect != NULL)
  7332. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  7333. /* Client sent an "Expect: xyz" header and xyz is not 100-continue. */
  7334. mg_send_http_error(conn,
  7335. 417,
  7336. "Error: Can not fulfill expectation %s",
  7337. expect);
  7338. } else {
  7339. if (expect != NULL) {
  7340. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  7341. conn->status_code = 100;
  7342. } else {
  7343. conn->status_code = 200;
  7344. }
  7345. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  7346. - conn->consumed_content;
  7347. /* assert(buffered_len >= 0); */
  7348. /* assert(conn->consumed_content == 0); */
  7349. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  7350. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  7351. return 0;
  7352. }
  7353. if (buffered_len > 0) {
  7354. if ((int64_t)buffered_len > conn->content_len) {
  7355. buffered_len = (int)conn->content_len;
  7356. }
  7357. body = conn->buf + conn->request_len + conn->consumed_content;
  7358. push_all(conn->ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  7359. conn->consumed_content += buffered_len;
  7360. }
  7361. nread = 0;
  7362. while (conn->consumed_content < conn->content_len) {
  7363. to_read = sizeof(buf);
  7364. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  7365. to_read = (int)(conn->content_len - conn->consumed_content);
  7366. }
  7367. nread = pull_inner(NULL, conn, buf, to_read, timeout);
  7368. if (nread == -2) {
  7369. /* error */
  7370. break;
  7371. }
  7372. if (nread > 0) {
  7373. if (push_all(conn->ctx, fp, sock, ssl, buf, nread) != nread) {
  7374. break;
  7375. }
  7376. }
  7377. conn->consumed_content += nread;
  7378. }
  7379. if (conn->consumed_content == conn->content_len) {
  7380. success = (nread >= 0);
  7381. }
  7382. /* Each error code path in this function must send an error */
  7383. if (!success) {
  7384. /* NOTE: Maybe some data has already been sent. */
  7385. /* TODO (low): If some data has been sent, a correct error
  7386. * reply can no longer be sent, so just close the connection */
  7387. mg_send_http_error(conn, 500, "%s", "");
  7388. }
  7389. }
  7390. return success;
  7391. }
  7392. #endif
  7393. #if !defined(NO_CGI)
  7394. /* This structure helps to create an environment for the spawned CGI program.
  7395. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  7396. * last element must be NULL.
  7397. * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  7398. * strings must reside in a contiguous buffer. The end of the buffer is
  7399. * marked by two '\0' characters.
  7400. * We satisfy both worlds: we create an envp array (which is vars), all
  7401. * entries are actually pointers inside buf. */
  7402. struct cgi_environment {
  7403. struct mg_connection *conn;
  7404. /* Data block */
  7405. char *buf; /* Environment buffer */
  7406. size_t buflen; /* Space available in buf */
  7407. size_t bufused; /* Space taken in buf */
  7408. /* Index block */
  7409. char **var; /* char **envp */
  7410. size_t varlen; /* Number of variables available in var */
  7411. size_t varused; /* Number of variables stored in var */
  7412. };
  7413. static void addenv(struct cgi_environment *env,
  7414. PRINTF_FORMAT_STRING(const char *fmt),
  7415. ...) PRINTF_ARGS(2, 3);
  7416. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  7417. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  7418. static void
  7419. addenv(struct cgi_environment *env, const char *fmt, ...)
  7420. {
  7421. size_t n, space;
  7422. int truncated = 0;
  7423. char *added;
  7424. va_list ap;
  7425. /* Calculate how much space is left in the buffer */
  7426. space = (env->buflen - env->bufused);
  7427. /* Calculate an estimate for the required space */
  7428. n = strlen(fmt) + 2 + 128;
  7429. do {
  7430. if (space <= n) {
  7431. /* Allocate new buffer */
  7432. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  7433. added = (char *)mg_realloc(env->buf, n);
  7434. if (!added) {
  7435. /* Out of memory */
  7436. mg_cry(env->conn,
  7437. "%s: Cannot allocate memory for CGI variable [%s]",
  7438. __func__,
  7439. fmt);
  7440. return;
  7441. }
  7442. env->buf = added;
  7443. env->buflen = n;
  7444. space = (env->buflen - env->bufused);
  7445. }
  7446. /* Make a pointer to the free space int the buffer */
  7447. added = env->buf + env->bufused;
  7448. /* Copy VARIABLE=VALUE\0 string into the free space */
  7449. va_start(ap, fmt);
  7450. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  7451. va_end(ap);
  7452. /* Do not add truncated strings to the environment */
  7453. if (truncated) {
  7454. /* Reallocate the buffer */
  7455. space = 0;
  7456. n = 1;
  7457. }
  7458. } while (truncated);
  7459. /* Calculate number of bytes added to the environment */
  7460. n = strlen(added) + 1;
  7461. env->bufused += n;
  7462. /* Now update the variable index */
  7463. space = (env->varlen - env->varused);
  7464. if (space < 2) {
  7465. mg_cry(env->conn,
  7466. "%s: Cannot register CGI variable [%s]",
  7467. __func__,
  7468. fmt);
  7469. return;
  7470. }
  7471. /* Append a pointer to the added string into the envp array */
  7472. env->var[env->varused] = added;
  7473. env->varused++;
  7474. }
  7475. static void
  7476. prepare_cgi_environment(struct mg_connection *conn,
  7477. const char *prog,
  7478. struct cgi_environment *env)
  7479. {
  7480. const char *s;
  7481. struct vec var_vec;
  7482. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  7483. int i, truncated, uri_len;
  7484. if (conn == NULL || prog == NULL || env == NULL) {
  7485. return;
  7486. }
  7487. env->conn = conn;
  7488. env->buflen = CGI_ENVIRONMENT_SIZE;
  7489. env->bufused = 0;
  7490. env->buf = (char *)mg_malloc(env->buflen);
  7491. env->varlen = MAX_CGI_ENVIR_VARS;
  7492. env->varused = 0;
  7493. env->var = (char **)mg_malloc(env->buflen * sizeof(char *));
  7494. addenv(env, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  7495. addenv(env, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  7496. addenv(env, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  7497. addenv(env, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  7498. /* Prepare the environment block */
  7499. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  7500. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  7501. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  7502. #if defined(USE_IPV6)
  7503. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  7504. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  7505. } else
  7506. #endif
  7507. {
  7508. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  7509. }
  7510. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  7511. addenv(env, "REMOTE_ADDR=%s", src_addr);
  7512. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  7513. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  7514. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  7515. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  7516. /* SCRIPT_NAME */
  7517. uri_len = (int)strlen(conn->request_info.local_uri);
  7518. if (conn->path_info == NULL) {
  7519. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  7520. /* URI: /path_to_script/script.cgi */
  7521. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  7522. } else {
  7523. /* URI: /path_to_script/ ... using index.cgi */
  7524. const char *index_file = strrchr(prog, '/');
  7525. if (index_file) {
  7526. addenv(env,
  7527. "SCRIPT_NAME=%s%s",
  7528. conn->request_info.local_uri,
  7529. index_file + 1);
  7530. }
  7531. }
  7532. } else {
  7533. /* URI: /path_to_script/script.cgi/path_info */
  7534. addenv(env,
  7535. "SCRIPT_NAME=%.*s",
  7536. uri_len - (int)strlen(conn->path_info),
  7537. conn->request_info.local_uri);
  7538. }
  7539. addenv(env, "SCRIPT_FILENAME=%s", prog);
  7540. if (conn->path_info == NULL) {
  7541. addenv(env, "PATH_TRANSLATED=%s", conn->ctx->config[DOCUMENT_ROOT]);
  7542. } else {
  7543. addenv(env,
  7544. "PATH_TRANSLATED=%s%s",
  7545. conn->ctx->config[DOCUMENT_ROOT],
  7546. conn->path_info);
  7547. }
  7548. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  7549. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  7550. addenv(env, "CONTENT_TYPE=%s", s);
  7551. }
  7552. if (conn->request_info.query_string != NULL) {
  7553. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  7554. }
  7555. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  7556. addenv(env, "CONTENT_LENGTH=%s", s);
  7557. }
  7558. if ((s = getenv("PATH")) != NULL) {
  7559. addenv(env, "PATH=%s", s);
  7560. }
  7561. if (conn->path_info != NULL) {
  7562. addenv(env, "PATH_INFO=%s", conn->path_info);
  7563. }
  7564. if (conn->status_code > 0) {
  7565. /* CGI error handler should show the status code */
  7566. addenv(env, "STATUS=%d", conn->status_code);
  7567. }
  7568. #if defined(_WIN32)
  7569. if ((s = getenv("COMSPEC")) != NULL) {
  7570. addenv(env, "COMSPEC=%s", s);
  7571. }
  7572. if ((s = getenv("SYSTEMROOT")) != NULL) {
  7573. addenv(env, "SYSTEMROOT=%s", s);
  7574. }
  7575. if ((s = getenv("SystemDrive")) != NULL) {
  7576. addenv(env, "SystemDrive=%s", s);
  7577. }
  7578. if ((s = getenv("ProgramFiles")) != NULL) {
  7579. addenv(env, "ProgramFiles=%s", s);
  7580. }
  7581. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  7582. addenv(env, "ProgramFiles(x86)=%s", s);
  7583. }
  7584. #else
  7585. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  7586. addenv(env, "LD_LIBRARY_PATH=%s", s);
  7587. }
  7588. #endif /* _WIN32 */
  7589. if ((s = getenv("PERLLIB")) != NULL) {
  7590. addenv(env, "PERLLIB=%s", s);
  7591. }
  7592. if (conn->request_info.remote_user != NULL) {
  7593. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  7594. addenv(env, "%s", "AUTH_TYPE=Digest");
  7595. }
  7596. /* Add all headers as HTTP_* variables */
  7597. for (i = 0; i < conn->request_info.num_headers; i++) {
  7598. (void)mg_snprintf(conn,
  7599. &truncated,
  7600. http_var_name,
  7601. sizeof(http_var_name),
  7602. "HTTP_%s",
  7603. conn->request_info.http_headers[i].name);
  7604. if (truncated) {
  7605. mg_cry(conn,
  7606. "%s: HTTP header variable too long [%s]",
  7607. __func__,
  7608. conn->request_info.http_headers[i].name);
  7609. continue;
  7610. }
  7611. /* Convert variable name into uppercase, and change - to _ */
  7612. for (p = http_var_name; *p != '\0'; p++) {
  7613. if (*p == '-') {
  7614. *p = '_';
  7615. }
  7616. *p = (char)toupper(*(unsigned char *)p);
  7617. }
  7618. addenv(env,
  7619. "%s=%s",
  7620. http_var_name,
  7621. conn->request_info.http_headers[i].value);
  7622. }
  7623. /* Add user-specified variables */
  7624. s = conn->ctx->config[CGI_ENVIRONMENT];
  7625. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  7626. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  7627. }
  7628. env->var[env->varused] = NULL;
  7629. env->buf[env->bufused] = '\0';
  7630. }
  7631. static void
  7632. handle_cgi_request(struct mg_connection *conn, const char *prog)
  7633. {
  7634. char *buf;
  7635. size_t buflen;
  7636. int headers_len, data_len, i, truncated;
  7637. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  7638. const char *status, *status_text, *connection_state;
  7639. char *pbuf, dir[PATH_MAX], *p;
  7640. struct mg_request_info ri;
  7641. struct cgi_environment blk;
  7642. FILE *in = NULL, *out = NULL, *err = NULL;
  7643. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  7644. pid_t pid = (pid_t)-1;
  7645. if (conn == NULL) {
  7646. return;
  7647. }
  7648. buf = NULL;
  7649. buflen = 16384;
  7650. prepare_cgi_environment(conn, prog, &blk);
  7651. /* CGI must be executed in its own directory. 'dir' must point to the
  7652. * directory containing executable program, 'p' must point to the
  7653. * executable program name relative to 'dir'. */
  7654. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  7655. if (truncated) {
  7656. mg_cry(conn, "Error: CGI program \"%s\": Path too long", prog);
  7657. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  7658. goto done;
  7659. }
  7660. if ((p = strrchr(dir, '/')) != NULL) {
  7661. *p++ = '\0';
  7662. } else {
  7663. dir[0] = '.', dir[1] = '\0';
  7664. p = (char *)prog;
  7665. }
  7666. if (pipe(fdin) != 0 || pipe(fdout) != 0 || pipe(fderr) != 0) {
  7667. status = strerror(ERRNO);
  7668. mg_cry(conn,
  7669. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  7670. prog,
  7671. status);
  7672. mg_send_http_error(conn,
  7673. 500,
  7674. "Error: Cannot create CGI pipe: %s",
  7675. 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. mg_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. mg_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. mg_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. mg_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. mg_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. mg_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. mg_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 mg_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. mg_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. mg_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. mg_send_http_error(
  7941. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7942. } else if (errno == EACCES) {
  7943. mg_send_http_error(
  7944. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7945. } else if (errno == ENOENT) {
  7946. mg_send_http_error(
  7947. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7948. } else {
  7949. mg_send_http_error(
  7950. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  7951. }
  7952. }
  7953. }
  7954. static void
  7955. put_file(struct mg_connection *conn, const char *path)
  7956. {
  7957. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7958. const char *range;
  7959. int64_t r1, r2;
  7960. int rc;
  7961. char date[64];
  7962. time_t curtime = time(NULL);
  7963. if (conn == NULL) {
  7964. return;
  7965. }
  7966. if (mg_stat(conn, path, &file.stat)) {
  7967. /* File already exists */
  7968. conn->status_code = 200;
  7969. if (file.stat.is_directory) {
  7970. /* This is an already existing directory,
  7971. * so there is nothing to do for the server. */
  7972. rc = 0;
  7973. } else {
  7974. /* File exists and is not a directory. */
  7975. /* Can it be replaced? */
  7976. if (file.access.membuf != NULL) {
  7977. /* This is an "in-memory" file, that can not be replaced */
  7978. mg_send_http_error(
  7979. conn,
  7980. 405,
  7981. "Error: Put not possible\nReplacing %s is not supported",
  7982. path);
  7983. return;
  7984. }
  7985. /* Check if the server may write this file */
  7986. if (access(path, W_OK) == 0) {
  7987. /* Access granted */
  7988. conn->status_code = 200;
  7989. rc = 1;
  7990. } else {
  7991. mg_send_http_error(
  7992. conn,
  7993. 403,
  7994. "Error: Put not possible\nReplacing %s is not allowed",
  7995. path);
  7996. return;
  7997. }
  7998. }
  7999. } else {
  8000. /* File should be created */
  8001. conn->status_code = 201;
  8002. rc = put_dir(conn, path);
  8003. }
  8004. if (rc == 0) {
  8005. /* put_dir returns 0 if path is a directory */
  8006. gmt_time_string(date, sizeof(date), &curtime);
  8007. mg_printf(conn,
  8008. "HTTP/1.1 %d %s\r\n",
  8009. conn->status_code,
  8010. mg_get_response_code_text(NULL, conn->status_code));
  8011. send_no_cache_header(conn);
  8012. send_additional_header(conn);
  8013. mg_printf(conn,
  8014. "Date: %s\r\n"
  8015. "Content-Length: 0\r\n"
  8016. "Connection: %s\r\n\r\n",
  8017. date,
  8018. suggest_connection_header(conn));
  8019. /* Request to create a directory has been fulfilled successfully.
  8020. * No need to put a file. */
  8021. return;
  8022. }
  8023. if (rc == -1) {
  8024. /* put_dir returns -1 if the path is too long */
  8025. mg_send_http_error(conn,
  8026. 414,
  8027. "Error: Path too long\nput_dir(%s): %s",
  8028. path,
  8029. strerror(ERRNO));
  8030. return;
  8031. }
  8032. if (rc == -2) {
  8033. /* put_dir returns -2 if the directory can not be created */
  8034. mg_send_http_error(conn,
  8035. 500,
  8036. "Error: Can not create directory\nput_dir(%s): %s",
  8037. path,
  8038. strerror(ERRNO));
  8039. return;
  8040. }
  8041. /* A file should be created or overwritten. */
  8042. /* Currently CivetWeb does not nead read+write access. */
  8043. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  8044. || file.access.fp == NULL) {
  8045. (void)mg_fclose(&file.access);
  8046. mg_send_http_error(conn,
  8047. 500,
  8048. "Error: Can not create file\nfopen(%s): %s",
  8049. path,
  8050. strerror(ERRNO));
  8051. return;
  8052. }
  8053. fclose_on_exec(&file.access, conn);
  8054. range = mg_get_header(conn, "Content-Range");
  8055. r1 = r2 = 0;
  8056. if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
  8057. conn->status_code = 206; /* Partial content */
  8058. fseeko(file.access.fp, r1, SEEK_SET);
  8059. }
  8060. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  8061. /* forward_body_data failed.
  8062. * The error code has already been sent to the client,
  8063. * and conn->status_code is already set. */
  8064. (void)mg_fclose(&file.access);
  8065. return;
  8066. }
  8067. if (mg_fclose(&file.access) != 0) {
  8068. /* fclose failed. This might have different reasons, but a likely
  8069. * one is "no space on disk", http 507. */
  8070. conn->status_code = 507;
  8071. }
  8072. gmt_time_string(date, sizeof(date), &curtime);
  8073. mg_printf(conn,
  8074. "HTTP/1.1 %d %s\r\n",
  8075. conn->status_code,
  8076. mg_get_response_code_text(NULL, conn->status_code));
  8077. send_no_cache_header(conn);
  8078. send_additional_header(conn);
  8079. mg_printf(conn,
  8080. "Date: %s\r\n"
  8081. "Content-Length: 0\r\n"
  8082. "Connection: %s\r\n\r\n",
  8083. date,
  8084. suggest_connection_header(conn));
  8085. }
  8086. static void
  8087. delete_file(struct mg_connection *conn, const char *path)
  8088. {
  8089. struct de de;
  8090. memset(&de.file, 0, sizeof(de.file));
  8091. if (!mg_stat(conn, path, &de.file)) {
  8092. /* mg_stat returns 0 if the file does not exist */
  8093. mg_send_http_error(conn,
  8094. 404,
  8095. "Error: Cannot delete file\nFile %s not found",
  8096. path);
  8097. return;
  8098. }
  8099. #if 0 /* Ignore if a file in memory is inside a folder */
  8100. if (de.access.membuf != NULL) {
  8101. /* the file is cached in memory */
  8102. mg_send_http_error(
  8103. conn,
  8104. 405,
  8105. "Error: Delete not possible\nDeleting %s is not supported",
  8106. path);
  8107. return;
  8108. }
  8109. #endif
  8110. if (de.file.is_directory) {
  8111. if (remove_directory(conn, path)) {
  8112. /* Delete is successful: Return 204 without content. */
  8113. mg_send_http_error(conn, 204, "%s", "");
  8114. } else {
  8115. /* Delete is not successful: Return 500 (Server error). */
  8116. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  8117. }
  8118. return;
  8119. }
  8120. /* This is an existing file (not a directory).
  8121. * Check if write permission is granted. */
  8122. if (access(path, W_OK) != 0) {
  8123. /* File is read only */
  8124. mg_send_http_error(
  8125. conn,
  8126. 403,
  8127. "Error: Delete not possible\nDeleting %s is not allowed",
  8128. path);
  8129. return;
  8130. }
  8131. /* Try to delete it. */
  8132. if (mg_remove(conn, path) == 0) {
  8133. /* Delete was successful: Return 204 without content. */
  8134. mg_send_http_error(conn, 204, "%s", "");
  8135. } else {
  8136. /* Delete not successful (file locked). */
  8137. mg_send_http_error(conn,
  8138. 423,
  8139. "Error: Cannot delete file\nremove(%s): %s",
  8140. path,
  8141. strerror(ERRNO));
  8142. }
  8143. }
  8144. #endif /* !NO_FILES */
  8145. static void
  8146. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  8147. static void
  8148. do_ssi_include(struct mg_connection *conn,
  8149. const char *ssi,
  8150. char *tag,
  8151. int include_level)
  8152. {
  8153. char file_name[MG_BUF_LEN], path[512], *p;
  8154. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8155. size_t len;
  8156. int truncated = 0;
  8157. if (conn == NULL) {
  8158. return;
  8159. }
  8160. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  8161. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  8162. * always < MG_BUF_LEN. */
  8163. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  8164. /* File name is relative to the webserver root */
  8165. file_name[511] = 0;
  8166. (void)mg_snprintf(conn,
  8167. &truncated,
  8168. path,
  8169. sizeof(path),
  8170. "%s/%s",
  8171. conn->ctx->config[DOCUMENT_ROOT],
  8172. file_name);
  8173. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  8174. /* File name is relative to the webserver working directory
  8175. * or it is absolute system path */
  8176. file_name[511] = 0;
  8177. (void)
  8178. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  8179. } else if (sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1
  8180. || sscanf(tag, " \"%511[^\"]\"", file_name) == 1) {
  8181. /* File name is relative to the currect document */
  8182. file_name[511] = 0;
  8183. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  8184. if (!truncated) {
  8185. if ((p = strrchr(path, '/')) != NULL) {
  8186. p[1] = '\0';
  8187. }
  8188. len = strlen(path);
  8189. (void)mg_snprintf(conn,
  8190. &truncated,
  8191. path + len,
  8192. sizeof(path) - len,
  8193. "%s",
  8194. file_name);
  8195. }
  8196. } else {
  8197. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  8198. return;
  8199. }
  8200. if (truncated) {
  8201. mg_cry(conn, "SSI #include path length overflow: [%s]", tag);
  8202. return;
  8203. }
  8204. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  8205. mg_cry(conn,
  8206. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  8207. tag,
  8208. path,
  8209. strerror(ERRNO));
  8210. } else {
  8211. fclose_on_exec(&file.access, conn);
  8212. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  8213. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  8214. path) > 0) {
  8215. send_ssi_file(conn, path, &file, include_level + 1);
  8216. } else {
  8217. send_file_data(conn, &file, 0, INT64_MAX);
  8218. }
  8219. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  8220. }
  8221. }
  8222. #if !defined(NO_POPEN)
  8223. static void
  8224. do_ssi_exec(struct mg_connection *conn, char *tag)
  8225. {
  8226. char cmd[1024] = "";
  8227. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8228. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  8229. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  8230. } else {
  8231. cmd[1023] = 0;
  8232. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  8233. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  8234. } else {
  8235. send_file_data(conn, &file, 0, INT64_MAX);
  8236. pclose(file.access.fp);
  8237. }
  8238. }
  8239. }
  8240. #endif /* !NO_POPEN */
  8241. static int
  8242. mg_fgetc(struct mg_file *filep, int offset)
  8243. {
  8244. if (filep == NULL) {
  8245. return EOF;
  8246. }
  8247. if (filep->access.membuf != NULL && offset >= 0
  8248. && ((unsigned int)(offset)) < filep->stat.size) {
  8249. return ((const unsigned char *)filep->access.membuf)[offset];
  8250. } else if (filep->access.fp != NULL) {
  8251. return fgetc(filep->access.fp);
  8252. } else {
  8253. return EOF;
  8254. }
  8255. }
  8256. static void
  8257. send_ssi_file(struct mg_connection *conn,
  8258. const char *path,
  8259. struct mg_file *filep,
  8260. int include_level)
  8261. {
  8262. char buf[MG_BUF_LEN];
  8263. int ch, offset, len, in_ssi_tag;
  8264. if (include_level > 10) {
  8265. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  8266. return;
  8267. }
  8268. in_ssi_tag = len = offset = 0;
  8269. while ((ch = mg_fgetc(filep, offset)) != EOF) {
  8270. if (in_ssi_tag && ch == '>') {
  8271. in_ssi_tag = 0;
  8272. buf[len++] = (char)ch;
  8273. buf[len] = '\0';
  8274. /* assert(len <= (int) sizeof(buf)); */
  8275. if (len > (int)sizeof(buf)) {
  8276. break;
  8277. }
  8278. if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
  8279. /* Not an SSI tag, pass it */
  8280. (void)mg_write(conn, buf, (size_t)len);
  8281. } else {
  8282. if (!memcmp(buf + 5, "include", 7)) {
  8283. do_ssi_include(conn, path, buf + 12, include_level);
  8284. #if !defined(NO_POPEN)
  8285. } else if (!memcmp(buf + 5, "exec", 4)) {
  8286. do_ssi_exec(conn, buf + 9);
  8287. #endif /* !NO_POPEN */
  8288. } else {
  8289. mg_cry(conn,
  8290. "%s: unknown SSI "
  8291. "command: \"%s\"",
  8292. path,
  8293. buf);
  8294. }
  8295. }
  8296. len = 0;
  8297. } else if (in_ssi_tag) {
  8298. if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
  8299. /* Not an SSI tag */
  8300. in_ssi_tag = 0;
  8301. } else if (len == (int)sizeof(buf) - 2) {
  8302. mg_cry(conn, "%s: SSI tag is too large", path);
  8303. len = 0;
  8304. }
  8305. buf[len++] = (char)(ch & 0xff);
  8306. } else if (ch == '<') {
  8307. in_ssi_tag = 1;
  8308. if (len > 0) {
  8309. mg_write(conn, buf, (size_t)len);
  8310. }
  8311. len = 0;
  8312. buf[len++] = (char)(ch & 0xff);
  8313. } else {
  8314. buf[len++] = (char)(ch & 0xff);
  8315. if (len == (int)sizeof(buf)) {
  8316. mg_write(conn, buf, (size_t)len);
  8317. len = 0;
  8318. }
  8319. }
  8320. }
  8321. /* Send the rest of buffered data */
  8322. if (len > 0) {
  8323. mg_write(conn, buf, (size_t)len);
  8324. }
  8325. }
  8326. static void
  8327. handle_ssi_file_request(struct mg_connection *conn,
  8328. const char *path,
  8329. struct mg_file *filep)
  8330. {
  8331. char date[64];
  8332. time_t curtime = time(NULL);
  8333. const char *cors1, *cors2, *cors3;
  8334. if (conn == NULL || path == NULL || filep == NULL) {
  8335. return;
  8336. }
  8337. if (mg_get_header(conn, "Origin")) {
  8338. /* Cross-origin resource sharing (CORS). */
  8339. cors1 = "Access-Control-Allow-Origin: ";
  8340. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  8341. cors3 = "\r\n";
  8342. } else {
  8343. cors1 = cors2 = cors3 = "";
  8344. }
  8345. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8346. /* File exists (precondition for calling this function),
  8347. * but can not be opened by the server. */
  8348. mg_send_http_error(conn,
  8349. 500,
  8350. "Error: Cannot read file\nfopen(%s): %s",
  8351. path,
  8352. strerror(ERRNO));
  8353. } else {
  8354. conn->must_close = 1;
  8355. gmt_time_string(date, sizeof(date), &curtime);
  8356. fclose_on_exec(&filep->access, conn);
  8357. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  8358. send_no_cache_header(conn);
  8359. send_additional_header(conn);
  8360. mg_printf(conn,
  8361. "%s%s%s"
  8362. "Date: %s\r\n"
  8363. "Content-Type: text/html\r\n"
  8364. "Connection: %s\r\n\r\n",
  8365. cors1,
  8366. cors2,
  8367. cors3,
  8368. date,
  8369. suggest_connection_header(conn));
  8370. send_ssi_file(conn, path, filep, 0);
  8371. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  8372. }
  8373. }
  8374. #if !defined(NO_FILES)
  8375. static void
  8376. send_options(struct mg_connection *conn)
  8377. {
  8378. char date[64];
  8379. time_t curtime = time(NULL);
  8380. if (!conn) {
  8381. return;
  8382. }
  8383. conn->status_code = 200;
  8384. conn->must_close = 1;
  8385. gmt_time_string(date, sizeof(date), &curtime);
  8386. /* We do not set a "Cache-Control" header here, but leave the default.
  8387. * Since browsers do not send an OPTIONS request, we can not test the
  8388. * effect anyway. */
  8389. mg_printf(conn,
  8390. "HTTP/1.1 200 OK\r\n"
  8391. "Date: %s\r\n"
  8392. "Connection: %s\r\n"
  8393. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  8394. "PROPFIND, MKCOL\r\n"
  8395. "DAV: 1\r\n",
  8396. date,
  8397. suggest_connection_header(conn));
  8398. send_additional_header(conn);
  8399. mg_printf(conn, "\r\n");
  8400. }
  8401. /* Writes PROPFIND properties for a collection element */
  8402. static void
  8403. print_props(struct mg_connection *conn,
  8404. const char *uri,
  8405. struct mg_file_stat *filep)
  8406. {
  8407. char mtime[64];
  8408. if (conn == NULL || uri == NULL || filep == NULL) {
  8409. return;
  8410. }
  8411. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  8412. conn->num_bytes_sent +=
  8413. mg_printf(conn,
  8414. "<d:response>"
  8415. "<d:href>%s</d:href>"
  8416. "<d:propstat>"
  8417. "<d:prop>"
  8418. "<d:resourcetype>%s</d:resourcetype>"
  8419. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  8420. "<d:getlastmodified>%s</d:getlastmodified>"
  8421. "</d:prop>"
  8422. "<d:status>HTTP/1.1 200 OK</d:status>"
  8423. "</d:propstat>"
  8424. "</d:response>\n",
  8425. uri,
  8426. filep->is_directory ? "<d:collection/>" : "",
  8427. filep->size,
  8428. mtime);
  8429. }
  8430. static void
  8431. print_dav_dir_entry(struct de *de, void *data)
  8432. {
  8433. char href[PATH_MAX];
  8434. char href_encoded[PATH_MAX * 3 /* worst case */];
  8435. int truncated;
  8436. struct mg_connection *conn = (struct mg_connection *)data;
  8437. if (!de || !conn) {
  8438. return;
  8439. }
  8440. mg_snprintf(conn,
  8441. &truncated,
  8442. href,
  8443. sizeof(href),
  8444. "%s%s",
  8445. conn->request_info.local_uri,
  8446. de->file_name);
  8447. if (!truncated) {
  8448. mg_url_encode(href, href_encoded, PATH_MAX * 3);
  8449. print_props(conn, href_encoded, &de->file);
  8450. }
  8451. }
  8452. static void
  8453. handle_propfind(struct mg_connection *conn,
  8454. const char *path,
  8455. struct mg_file_stat *filep)
  8456. {
  8457. const char *depth = mg_get_header(conn, "Depth");
  8458. char date[64];
  8459. time_t curtime = time(NULL);
  8460. gmt_time_string(date, sizeof(date), &curtime);
  8461. if (!conn || !path || !filep || !conn->ctx) {
  8462. return;
  8463. }
  8464. conn->must_close = 1;
  8465. conn->status_code = 207;
  8466. mg_printf(conn,
  8467. "HTTP/1.1 207 Multi-Status\r\n"
  8468. "Date: %s\r\n",
  8469. date);
  8470. send_static_cache_header(conn);
  8471. send_additional_header(conn);
  8472. mg_printf(conn,
  8473. "Connection: %s\r\n"
  8474. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  8475. suggest_connection_header(conn));
  8476. conn->num_bytes_sent +=
  8477. mg_printf(conn,
  8478. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  8479. "<d:multistatus xmlns:d='DAV:'>\n");
  8480. /* Print properties for the requested resource itself */
  8481. print_props(conn, conn->request_info.local_uri, filep);
  8482. /* If it is a directory, print directory entries too if Depth is not 0 */
  8483. if (filep && filep->is_directory
  8484. && !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")
  8485. && (depth == NULL || strcmp(depth, "0") != 0)) {
  8486. scan_directory(conn, path, conn, &print_dav_dir_entry);
  8487. }
  8488. conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");
  8489. }
  8490. #endif
  8491. void
  8492. mg_lock_connection(struct mg_connection *conn)
  8493. {
  8494. if (conn) {
  8495. (void)pthread_mutex_lock(&conn->mutex);
  8496. }
  8497. }
  8498. void
  8499. mg_unlock_connection(struct mg_connection *conn)
  8500. {
  8501. if (conn) {
  8502. (void)pthread_mutex_unlock(&conn->mutex);
  8503. }
  8504. }
  8505. void
  8506. mg_lock_context(struct mg_context *ctx)
  8507. {
  8508. if (ctx) {
  8509. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  8510. }
  8511. }
  8512. void
  8513. mg_unlock_context(struct mg_context *ctx)
  8514. {
  8515. if (ctx) {
  8516. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  8517. }
  8518. }
  8519. #if defined(USE_TIMERS)
  8520. #define TIMER_API static
  8521. #include "timer.inl"
  8522. #endif /* USE_TIMERS */
  8523. #ifdef USE_LUA
  8524. #include "mod_lua.inl"
  8525. #endif /* USE_LUA */
  8526. #ifdef USE_DUKTAPE
  8527. #include "mod_duktape.inl"
  8528. #endif /* USE_DUKTAPE */
  8529. #if defined(USE_WEBSOCKET)
  8530. #if !defined(NO_SSL_DL)
  8531. #define SHA_API static
  8532. #include "sha1.inl"
  8533. #endif
  8534. static int
  8535. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  8536. {
  8537. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  8538. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  8539. SHA_CTX sha_ctx;
  8540. int truncated;
  8541. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  8542. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  8543. if (truncated) {
  8544. conn->must_close = 1;
  8545. return 0;
  8546. }
  8547. SHA1_Init(&sha_ctx);
  8548. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  8549. SHA1_Final((unsigned char *)sha, &sha_ctx);
  8550. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  8551. mg_printf(conn,
  8552. "HTTP/1.1 101 Switching Protocols\r\n"
  8553. "Upgrade: websocket\r\n"
  8554. "Connection: Upgrade\r\n"
  8555. "Sec-WebSocket-Accept: %s\r\n",
  8556. b64_sha);
  8557. if (conn->request_info.acceptedWebSocketSubprotocol) {
  8558. mg_printf(conn,
  8559. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  8560. conn->request_info.acceptedWebSocketSubprotocol);
  8561. } else {
  8562. mg_printf(conn, "%s", "\r\n");
  8563. }
  8564. return 1;
  8565. }
  8566. static void
  8567. read_websocket(struct mg_connection *conn,
  8568. mg_websocket_data_handler ws_data_handler,
  8569. void *callback_data)
  8570. {
  8571. /* Pointer to the beginning of the portion of the incoming websocket
  8572. * message queue.
  8573. * The original websocket upgrade request is never removed, so the queue
  8574. * begins after it. */
  8575. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  8576. int n, error, exit_by_callback;
  8577. /* body_len is the length of the entire queue in bytes
  8578. * len is the length of the current message
  8579. * data_len is the length of the current message's data payload
  8580. * header_len is the length of the current message's header */
  8581. size_t i, len, mask_len = 0, data_len = 0, header_len, body_len;
  8582. /* "The masking key is a 32-bit value chosen at random by the client."
  8583. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  8584. */
  8585. unsigned char mask[4];
  8586. /* data points to the place where the message is stored when passed to
  8587. * the
  8588. * websocket_data callback. This is either mem on the stack, or a
  8589. * dynamically allocated buffer if it is too large. */
  8590. unsigned char mem[4096];
  8591. unsigned char *data = mem;
  8592. unsigned char mop; /* mask flag and opcode */
  8593. double timeout = -1.0;
  8594. if (conn->ctx->config[WEBSOCKET_TIMEOUT]) {
  8595. timeout = atoi(conn->ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  8596. }
  8597. if ((timeout <= 0.0) && (conn->ctx->config[REQUEST_TIMEOUT])) {
  8598. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  8599. }
  8600. mg_set_thread_name("wsock");
  8601. /* Loop continuously, reading messages from the socket, invoking the
  8602. * callback, and waiting repeatedly until an error occurs. */
  8603. while (!conn->ctx->stop_flag) {
  8604. header_len = 0;
  8605. assert(conn->data_len >= conn->request_len);
  8606. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  8607. len = buf[1] & 127;
  8608. mask_len = (buf[1] & 128) ? 4 : 0;
  8609. if ((len < 126) && (body_len >= mask_len)) {
  8610. /* inline 7-bit length field */
  8611. data_len = len;
  8612. header_len = 2 + mask_len;
  8613. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  8614. /* 16-bit length field */
  8615. header_len = 4 + mask_len;
  8616. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  8617. } else if (body_len >= (10 + mask_len)) {
  8618. /* 64-bit length field */
  8619. uint32_t l1, l2;
  8620. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  8621. memcpy(&l2, &buf[6], 4);
  8622. header_len = 10 + mask_len;
  8623. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  8624. }
  8625. }
  8626. if (header_len > 0 && body_len >= header_len) {
  8627. /* Allocate space to hold websocket payload */
  8628. data = mem;
  8629. if (data_len > sizeof(mem)) {
  8630. data = (unsigned char *)mg_malloc(data_len);
  8631. if (data == NULL) {
  8632. /* Allocation failed, exit the loop and then close the
  8633. * connection */
  8634. mg_cry(conn, "websocket out of memory; closing connection");
  8635. break;
  8636. }
  8637. }
  8638. /* Copy the mask before we shift the queue and destroy it */
  8639. if (mask_len > 0) {
  8640. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  8641. } else {
  8642. memset(mask, 0, sizeof(mask));
  8643. }
  8644. /* Read frame payload from the first message in the queue into
  8645. * data and advance the queue by moving the memory in place. */
  8646. assert(body_len >= header_len);
  8647. if (data_len + header_len > body_len) {
  8648. mop = buf[0]; /* current mask and opcode */
  8649. /* Overflow case */
  8650. len = body_len - header_len;
  8651. memcpy(data, buf + header_len, len);
  8652. error = 0;
  8653. while (len < data_len) {
  8654. n = pull_inner(NULL,
  8655. conn,
  8656. (char *)(data + len),
  8657. (int)(data_len - len),
  8658. timeout);
  8659. if (n <= -2) {
  8660. error = 1;
  8661. break;
  8662. } else if (n > 0) {
  8663. len += (size_t)n;
  8664. } else {
  8665. /* Timeout: should retry */
  8666. /* TODO: retry condition */
  8667. }
  8668. }
  8669. if (error) {
  8670. mg_cry(conn, "Websocket pull failed; closing connection");
  8671. break;
  8672. }
  8673. conn->data_len = conn->request_len;
  8674. } else {
  8675. mop = buf[0]; /* current mask and opcode, overwritten by
  8676. * memmove() */
  8677. /* Length of the message being read at the front of the
  8678. * queue */
  8679. len = data_len + header_len;
  8680. /* Copy the data payload into the data pointer for the
  8681. * callback */
  8682. memcpy(data, buf + header_len, data_len);
  8683. /* Move the queue forward len bytes */
  8684. memmove(buf, buf + len, body_len - len);
  8685. /* Mark the queue as advanced */
  8686. conn->data_len -= (int)len;
  8687. }
  8688. /* Apply mask if necessary */
  8689. if (mask_len > 0) {
  8690. for (i = 0; i < data_len; ++i) {
  8691. data[i] ^= mask[i & 3];
  8692. }
  8693. }
  8694. /* Exit the loop if callback signals to exit (server side),
  8695. * or "connection close" opcode received (client side). */
  8696. exit_by_callback = 0;
  8697. if ((ws_data_handler != NULL)
  8698. && !ws_data_handler(
  8699. conn, mop, (char *)data, data_len, callback_data)) {
  8700. exit_by_callback = 1;
  8701. }
  8702. if (data != mem) {
  8703. mg_free(data);
  8704. }
  8705. if (exit_by_callback
  8706. || ((mop & 0xf) == WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  8707. /* Opcode == 8, connection close */
  8708. break;
  8709. }
  8710. /* Not breaking the loop, process next websocket frame. */
  8711. } else {
  8712. /* Read from the socket into the next available location in the
  8713. * message queue. */
  8714. n = pull_inner(NULL,
  8715. conn,
  8716. conn->buf + conn->data_len,
  8717. conn->buf_size - conn->data_len,
  8718. timeout);
  8719. if (n <= -2) {
  8720. /* Error, no bytes read */
  8721. break;
  8722. }
  8723. if (n > 0) {
  8724. conn->data_len += n;
  8725. } else {
  8726. /* Timeout: should retry */
  8727. /* TODO: get timeout def */
  8728. }
  8729. }
  8730. }
  8731. mg_set_thread_name("worker");
  8732. }
  8733. static int
  8734. mg_websocket_write_exec(struct mg_connection *conn,
  8735. int opcode,
  8736. const char *data,
  8737. size_t dataLen,
  8738. uint32_t masking_key)
  8739. {
  8740. unsigned char header[14];
  8741. size_t headerLen = 1;
  8742. int retval = -1;
  8743. #if defined(__GNUC__) || defined(__MINGW32__)
  8744. /* Disable spurious conversion warning for GCC */
  8745. #pragma GCC diagnostic push
  8746. #pragma GCC diagnostic ignored "-Wconversion"
  8747. #endif
  8748. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  8749. #if defined(__GNUC__) || defined(__MINGW32__)
  8750. #pragma GCC diagnostic pop
  8751. #endif
  8752. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  8753. if (dataLen < 126) {
  8754. /* inline 7-bit length field */
  8755. header[1] = (unsigned char)dataLen;
  8756. headerLen = 2;
  8757. } else if (dataLen <= 0xFFFF) {
  8758. /* 16-bit length field */
  8759. uint16_t len = htons((uint16_t)dataLen);
  8760. header[1] = 126;
  8761. memcpy(header + 2, &len, 2);
  8762. headerLen = 4;
  8763. } else {
  8764. /* 64-bit length field */
  8765. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  8766. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  8767. header[1] = 127;
  8768. memcpy(header + 2, &len1, 4);
  8769. memcpy(header + 6, &len2, 4);
  8770. headerLen = 10;
  8771. }
  8772. if (masking_key) {
  8773. /* add mask */
  8774. header[1] |= 0x80;
  8775. memcpy(header + headerLen, &masking_key, 4);
  8776. headerLen += 4;
  8777. }
  8778. /* Note that POSIX/Winsock's send() is threadsafe
  8779. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  8780. * but mongoose's mg_printf/mg_write is not (because of the loop in
  8781. * push(), although that is only a problem if the packet is large or
  8782. * outgoing buffer is full). */
  8783. (void)mg_lock_connection(conn);
  8784. retval = mg_write(conn, header, headerLen);
  8785. if (dataLen > 0) {
  8786. retval = mg_write(conn, data, dataLen);
  8787. }
  8788. mg_unlock_connection(conn);
  8789. return retval;
  8790. }
  8791. int
  8792. mg_websocket_write(struct mg_connection *conn,
  8793. int opcode,
  8794. const char *data,
  8795. size_t dataLen)
  8796. {
  8797. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  8798. }
  8799. static void
  8800. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  8801. {
  8802. size_t i = 0;
  8803. i = 0;
  8804. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  8805. /* Convert in 32 bit words, if data is 4 byte aligned */
  8806. while (i < (in_len - 3)) {
  8807. *(uint32_t *)(void *)(out + i) =
  8808. *(uint32_t *)(void *)(in + i) ^ masking_key;
  8809. i += 4;
  8810. }
  8811. }
  8812. if (i != in_len) {
  8813. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  8814. while (i < in_len) {
  8815. *(uint8_t *)(void *)(out + i) =
  8816. *(uint8_t *)(void *)(in + i)
  8817. ^ *(((uint8_t *)&masking_key) + (i % 4));
  8818. i++;
  8819. }
  8820. }
  8821. }
  8822. int
  8823. mg_websocket_client_write(struct mg_connection *conn,
  8824. int opcode,
  8825. const char *data,
  8826. size_t dataLen)
  8827. {
  8828. int retval = -1;
  8829. char *masked_data = (char *)mg_malloc(((dataLen + 7) / 4) * 4);
  8830. uint32_t masking_key = (uint32_t)get_random();
  8831. if (masked_data == NULL) {
  8832. /* Return -1 in an error case */
  8833. mg_cry(conn,
  8834. "Cannot allocate buffer for masked websocket response: "
  8835. "Out of memory");
  8836. return -1;
  8837. }
  8838. mask_data(data, dataLen, masking_key, masked_data);
  8839. retval = mg_websocket_write_exec(
  8840. conn, opcode, masked_data, dataLen, masking_key);
  8841. mg_free(masked_data);
  8842. return retval;
  8843. }
  8844. static void
  8845. handle_websocket_request(struct mg_connection *conn,
  8846. const char *path,
  8847. int is_callback_resource,
  8848. struct mg_websocket_subprotocols *subprotocols,
  8849. mg_websocket_connect_handler ws_connect_handler,
  8850. mg_websocket_ready_handler ws_ready_handler,
  8851. mg_websocket_data_handler ws_data_handler,
  8852. mg_websocket_close_handler ws_close_handler,
  8853. void *cbData)
  8854. {
  8855. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  8856. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  8857. int lua_websock = 0;
  8858. #if !defined(USE_LUA)
  8859. (void)path;
  8860. #endif
  8861. /* Step 1: Check websocket protocol version. */
  8862. /* Step 1.1: Check Sec-WebSocket-Key. */
  8863. if (!websock_key) {
  8864. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  8865. * requires a Sec-WebSocket-Key header.
  8866. */
  8867. /* It could be the hixie draft version
  8868. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  8869. */
  8870. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  8871. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  8872. char key3[8];
  8873. if ((key1 != NULL) && (key2 != NULL)) {
  8874. /* This version uses 8 byte body data in a GET request */
  8875. conn->content_len = 8;
  8876. if (8 == mg_read(conn, key3, 8)) {
  8877. /* This is the hixie version */
  8878. mg_send_http_error(conn,
  8879. 426,
  8880. "%s",
  8881. "Protocol upgrade to RFC 6455 required");
  8882. return;
  8883. }
  8884. }
  8885. /* This is an unknown version */
  8886. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  8887. return;
  8888. }
  8889. /* Step 1.2: Check websocket protocol version. */
  8890. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  8891. if (version == NULL || strcmp(version, "13") != 0) {
  8892. /* Reject wrong versions */
  8893. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  8894. return;
  8895. }
  8896. /* Step 1.3: Could check for "Host", but we do not really nead this
  8897. * value for anything, so just ignore it. */
  8898. /* Step 2: If a callback is responsible, call it. */
  8899. if (is_callback_resource) {
  8900. /* Step 2.1 check and select subprotocol */
  8901. const char *protocol = mg_get_header(conn, "Sec-WebSocket-Protocol");
  8902. if (protocol && subprotocols) {
  8903. int idx;
  8904. unsigned long len;
  8905. const char *sep, *curSubProtocol,
  8906. *acceptedWebSocketSubprotocol = NULL;
  8907. /* look for matching subprotocol */
  8908. do {
  8909. sep = strchr(protocol, ',');
  8910. curSubProtocol = protocol;
  8911. len = sep ? (unsigned long)(sep - protocol)
  8912. : (unsigned long)strlen(protocol);
  8913. while (sep && isspace(*++sep)) {
  8914. ; /* ignore leading whitespaces */
  8915. }
  8916. protocol = sep;
  8917. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  8918. if ((strlen(subprotocols->subprotocols[idx]) == len)
  8919. && (strncmp(curSubProtocol,
  8920. subprotocols->subprotocols[idx],
  8921. len) == 0)) {
  8922. acceptedWebSocketSubprotocol =
  8923. subprotocols->subprotocols[idx];
  8924. break;
  8925. }
  8926. }
  8927. } while (sep && !acceptedWebSocketSubprotocol);
  8928. conn->request_info.acceptedWebSocketSubprotocol =
  8929. acceptedWebSocketSubprotocol;
  8930. } else if (protocol) {
  8931. /* keep legacy behavior */
  8932. /* The protocol is a comma seperated list of names. */
  8933. /* The server must only return one value from this list. */
  8934. /* First check if it is a list or just a single value. */
  8935. const char *sep = strrchr(protocol, ',');
  8936. if (sep == NULL) {
  8937. /* Just a single protocol -> accept it. */
  8938. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  8939. } else {
  8940. /* Multiple protocols -> accept the last one. */
  8941. /* This is just a quick fix if the client offers multiple
  8942. * protocols. The handler should have a list of accepted
  8943. * protocols on his own
  8944. * and use it to select one protocol among those the client has
  8945. * offered.
  8946. */
  8947. while (isspace(*++sep)) {
  8948. ; /* ignore leading whitespaces */
  8949. }
  8950. conn->request_info.acceptedWebSocketSubprotocol = sep;
  8951. }
  8952. }
  8953. if (ws_connect_handler != NULL
  8954. && ws_connect_handler(conn, cbData) != 0) {
  8955. /* C callback has returned non-zero, do not proceed with
  8956. * handshake.
  8957. */
  8958. /* Note that C callbacks are no longer called when Lua is
  8959. * responsible, so C can no longer filter callbacks for Lua. */
  8960. return;
  8961. }
  8962. }
  8963. #if defined(USE_LUA)
  8964. /* Step 3: No callback. Check if Lua is responsible. */
  8965. else {
  8966. /* Step 3.1: Check if Lua is responsible. */
  8967. if (conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  8968. lua_websock =
  8969. match_prefix(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  8970. strlen(
  8971. conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  8972. path);
  8973. }
  8974. if (lua_websock) {
  8975. /* Step 3.2: Lua is responsible: call it. */
  8976. conn->lua_websocket_state = lua_websocket_new(path, conn);
  8977. if (!conn->lua_websocket_state) {
  8978. /* Lua rejected the new client */
  8979. return;
  8980. }
  8981. }
  8982. }
  8983. #endif
  8984. /* Step 4: Check if there is a responsible websocket handler. */
  8985. if (!is_callback_resource && !lua_websock) {
  8986. /* There is no callback, and Lua is not responsible either. */
  8987. /* Reply with a 404 Not Found. We are still at a standard
  8988. * HTTP request here, before the websocket handshake, so
  8989. * we can still send standard HTTP error replies. */
  8990. mg_send_http_error(conn, 404, "%s", "Not found");
  8991. return;
  8992. }
  8993. /* Step 5: The websocket connection has been accepted */
  8994. if (!send_websocket_handshake(conn, websock_key)) {
  8995. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  8996. return;
  8997. }
  8998. /* Step 6: Call the ready handler */
  8999. if (is_callback_resource) {
  9000. if (ws_ready_handler != NULL) {
  9001. ws_ready_handler(conn, cbData);
  9002. }
  9003. #if defined(USE_LUA)
  9004. } else if (lua_websock) {
  9005. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  9006. /* the ready handler returned false */
  9007. return;
  9008. }
  9009. #endif
  9010. }
  9011. /* Step 7: Enter the read loop */
  9012. if (is_callback_resource) {
  9013. read_websocket(conn, ws_data_handler, cbData);
  9014. #if defined(USE_LUA)
  9015. } else if (lua_websock) {
  9016. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  9017. #endif
  9018. }
  9019. /* Step 8: Call the close handler */
  9020. if (ws_close_handler) {
  9021. ws_close_handler(conn, cbData);
  9022. }
  9023. }
  9024. static int
  9025. is_websocket_protocol(const struct mg_connection *conn)
  9026. {
  9027. const char *upgrade, *connection;
  9028. /* A websocket protocoll has the following HTTP headers:
  9029. *
  9030. * Connection: Upgrade
  9031. * Upgrade: Websocket
  9032. */
  9033. upgrade = mg_get_header(conn, "Upgrade");
  9034. if (upgrade == NULL) {
  9035. return 0; /* fail early, don't waste time checking other header
  9036. * fields
  9037. */
  9038. }
  9039. if (!mg_strcasestr(upgrade, "websocket")) {
  9040. return 0;
  9041. }
  9042. connection = mg_get_header(conn, "Connection");
  9043. if (connection == NULL) {
  9044. return 0;
  9045. }
  9046. if (!mg_strcasestr(connection, "upgrade")) {
  9047. return 0;
  9048. }
  9049. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  9050. * "Sec-WebSocket-Version" are also required.
  9051. * Don't check them here, since even an unsupported websocket protocol
  9052. * request still IS a websocket request (in contrast to a standard HTTP
  9053. * request). It will fail later in handle_websocket_request.
  9054. */
  9055. return 1;
  9056. }
  9057. #endif /* !USE_WEBSOCKET */
  9058. static int
  9059. isbyte(int n)
  9060. {
  9061. return n >= 0 && n <= 255;
  9062. }
  9063. static int
  9064. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  9065. {
  9066. int n, a, b, c, d, slash = 32, len = 0;
  9067. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5
  9068. || sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) && isbyte(a)
  9069. && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0
  9070. && slash < 33) {
  9071. len = n;
  9072. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  9073. | (uint32_t)d;
  9074. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  9075. }
  9076. return len;
  9077. }
  9078. static int
  9079. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  9080. {
  9081. int throttle = 0;
  9082. struct vec vec, val;
  9083. uint32_t net, mask;
  9084. char mult;
  9085. double v;
  9086. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  9087. mult = ',';
  9088. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  9089. || (v < 0) || ((lowercase(&mult) != 'k')
  9090. && (lowercase(&mult) != 'm') && (mult != ','))) {
  9091. continue;
  9092. }
  9093. v *= (lowercase(&mult) == 'k')
  9094. ? 1024
  9095. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  9096. if (vec.len == 1 && vec.ptr[0] == '*') {
  9097. throttle = (int)v;
  9098. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  9099. if ((remote_ip & mask) == net) {
  9100. throttle = (int)v;
  9101. }
  9102. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  9103. throttle = (int)v;
  9104. }
  9105. }
  9106. return throttle;
  9107. }
  9108. static uint32_t
  9109. get_remote_ip(const struct mg_connection *conn)
  9110. {
  9111. if (!conn) {
  9112. return 0;
  9113. }
  9114. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  9115. }
  9116. /* The mg_upload function is superseeded by mg_handle_form_request. */
  9117. #include "handle_form.inl"
  9118. #if defined(MG_LEGACY_INTERFACE)
  9119. /* Implement the deprecated mg_upload function by calling the new
  9120. * mg_handle_form_request function. While mg_upload could only handle
  9121. * HTML forms sent as POST request in multipart/form-data format
  9122. * containing only file input elements, mg_handle_form_request can
  9123. * handle all form input elements and all standard request methods. */
  9124. struct mg_upload_user_data {
  9125. struct mg_connection *conn;
  9126. const char *destination_dir;
  9127. int num_uploaded_files;
  9128. };
  9129. /* Helper function for deprecated mg_upload. */
  9130. static int
  9131. mg_upload_field_found(const char *key,
  9132. const char *filename,
  9133. char *path,
  9134. size_t pathlen,
  9135. void *user_data)
  9136. {
  9137. int truncated = 0;
  9138. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  9139. (void)key;
  9140. if (!filename) {
  9141. mg_cry(fud->conn, "%s: No filename set", __func__);
  9142. return FORM_FIELD_STORAGE_ABORT;
  9143. }
  9144. mg_snprintf(fud->conn,
  9145. &truncated,
  9146. path,
  9147. pathlen - 1,
  9148. "%s/%s",
  9149. fud->destination_dir,
  9150. filename);
  9151. if (!truncated) {
  9152. mg_cry(fud->conn, "%s: File path too long", __func__);
  9153. return FORM_FIELD_STORAGE_ABORT;
  9154. }
  9155. return FORM_FIELD_STORAGE_STORE;
  9156. }
  9157. /* Helper function for deprecated mg_upload. */
  9158. static int
  9159. mg_upload_field_get(const char *key,
  9160. const char *value,
  9161. size_t value_size,
  9162. void *user_data)
  9163. {
  9164. /* Function should never be called */
  9165. (void)key;
  9166. (void)value;
  9167. (void)value_size;
  9168. (void)user_data;
  9169. return 0;
  9170. }
  9171. /* Helper function for deprecated mg_upload. */
  9172. static int
  9173. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  9174. {
  9175. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  9176. (void)file_size;
  9177. fud->num_uploaded_files++;
  9178. fud->conn->ctx->callbacks.upload(fud->conn, path);
  9179. return 0;
  9180. }
  9181. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  9182. int
  9183. mg_upload(struct mg_connection *conn, const char *destination_dir)
  9184. {
  9185. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  9186. struct mg_form_data_handler fdh = {mg_upload_field_found,
  9187. mg_upload_field_get,
  9188. mg_upload_field_stored,
  9189. 0};
  9190. int ret;
  9191. fdh.user_data = (void *)&fud;
  9192. ret = mg_handle_form_request(conn, &fdh);
  9193. if (ret < 0) {
  9194. mg_cry(conn, "%s: Error while parsing the request", __func__);
  9195. }
  9196. return fud.num_uploaded_files;
  9197. }
  9198. #endif
  9199. static int
  9200. get_first_ssl_listener_index(const struct mg_context *ctx)
  9201. {
  9202. unsigned int i;
  9203. int idx = -1;
  9204. if (ctx) {
  9205. for (i = 0; idx == -1 && i < ctx->num_listening_sockets; i++) {
  9206. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  9207. }
  9208. }
  9209. return idx;
  9210. }
  9211. static void
  9212. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  9213. {
  9214. char host[1025];
  9215. const char *host_header;
  9216. size_t hostlen;
  9217. host_header = mg_get_header(conn, "Host");
  9218. hostlen = sizeof(host);
  9219. if (host_header != NULL) {
  9220. char *pos;
  9221. mg_strlcpy(host, host_header, hostlen);
  9222. host[hostlen - 1] = '\0';
  9223. pos = strchr(host, ':');
  9224. if (pos != NULL) {
  9225. *pos = '\0';
  9226. }
  9227. } else {
  9228. /* Cannot get host from the Host: header.
  9229. * Fallback to our IP address. */
  9230. if (conn) {
  9231. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  9232. }
  9233. }
  9234. /* Send host, port, uri and (if it exists) ?query_string */
  9235. if (conn) {
  9236. mg_printf(conn,
  9237. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  9238. host,
  9239. #if defined(USE_IPV6)
  9240. (conn->ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  9241. == AF_INET6)
  9242. ? (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  9243. .lsa.sin6.sin6_port)
  9244. :
  9245. #endif
  9246. (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  9247. .lsa.sin.sin_port),
  9248. conn->request_info.local_uri,
  9249. (conn->request_info.query_string == NULL) ? "" : "?",
  9250. (conn->request_info.query_string == NULL)
  9251. ? ""
  9252. : conn->request_info.query_string);
  9253. }
  9254. }
  9255. static void
  9256. mg_set_handler_type(struct mg_context *ctx,
  9257. const char *uri,
  9258. int handler_type,
  9259. int is_delete_request,
  9260. mg_request_handler handler,
  9261. struct mg_websocket_subprotocols *subprotocols,
  9262. mg_websocket_connect_handler connect_handler,
  9263. mg_websocket_ready_handler ready_handler,
  9264. mg_websocket_data_handler data_handler,
  9265. mg_websocket_close_handler close_handler,
  9266. mg_authorization_handler auth_handler,
  9267. void *cbdata)
  9268. {
  9269. struct mg_handler_info *tmp_rh, **lastref;
  9270. size_t urilen = strlen(uri);
  9271. if (handler_type == WEBSOCKET_HANDLER) {
  9272. /* assert(handler == NULL); */
  9273. /* assert(is_delete_request || connect_handler!=NULL ||
  9274. * ready_handler!=NULL || data_handler!=NULL ||
  9275. * close_handler!=NULL);
  9276. */
  9277. /* assert(auth_handler == NULL); */
  9278. if (handler != NULL) {
  9279. return;
  9280. }
  9281. if (!is_delete_request && connect_handler == NULL
  9282. && ready_handler == NULL
  9283. && data_handler == NULL
  9284. && close_handler == NULL) {
  9285. return;
  9286. }
  9287. if (auth_handler != NULL) {
  9288. return;
  9289. }
  9290. } else if (handler_type == REQUEST_HANDLER) {
  9291. /* assert(connect_handler==NULL && ready_handler==NULL &&
  9292. * data_handler==NULL && close_handler==NULL); */
  9293. /* assert(is_delete_request || (handler!=NULL));
  9294. */
  9295. /* assert(auth_handler == NULL); */
  9296. if (connect_handler != NULL || ready_handler != NULL
  9297. || data_handler != NULL
  9298. || close_handler != NULL) {
  9299. return;
  9300. }
  9301. if (!is_delete_request && (handler == NULL)) {
  9302. return;
  9303. }
  9304. if (auth_handler != NULL) {
  9305. return;
  9306. }
  9307. } else { /* AUTH_HANDLER */
  9308. /* assert(handler == NULL); */
  9309. /* assert(connect_handler==NULL && ready_handler==NULL &&
  9310. * data_handler==NULL && close_handler==NULL); */
  9311. /* assert(auth_handler != NULL); */
  9312. if (handler != NULL) {
  9313. return;
  9314. }
  9315. if (connect_handler != NULL || ready_handler != NULL
  9316. || data_handler != NULL
  9317. || close_handler != NULL) {
  9318. return;
  9319. }
  9320. if (!is_delete_request && (auth_handler == NULL)) {
  9321. return;
  9322. }
  9323. }
  9324. if (!ctx) {
  9325. return;
  9326. }
  9327. mg_lock_context(ctx);
  9328. /* first try to find an existing handler */
  9329. lastref = &(ctx->handlers);
  9330. for (tmp_rh = ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  9331. if (tmp_rh->handler_type == handler_type) {
  9332. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  9333. if (!is_delete_request) {
  9334. /* update existing handler */
  9335. if (handler_type == REQUEST_HANDLER) {
  9336. tmp_rh->handler = handler;
  9337. } else if (handler_type == WEBSOCKET_HANDLER) {
  9338. tmp_rh->subprotocols = subprotocols;
  9339. tmp_rh->connect_handler = connect_handler;
  9340. tmp_rh->ready_handler = ready_handler;
  9341. tmp_rh->data_handler = data_handler;
  9342. tmp_rh->close_handler = close_handler;
  9343. } else { /* AUTH_HANDLER */
  9344. tmp_rh->auth_handler = auth_handler;
  9345. }
  9346. tmp_rh->cbdata = cbdata;
  9347. } else {
  9348. /* remove existing handler */
  9349. *lastref = tmp_rh->next;
  9350. mg_free(tmp_rh->uri);
  9351. mg_free(tmp_rh);
  9352. }
  9353. mg_unlock_context(ctx);
  9354. return;
  9355. }
  9356. }
  9357. lastref = &(tmp_rh->next);
  9358. }
  9359. if (is_delete_request) {
  9360. /* no handler to set, this was a remove request to a non-existing
  9361. * handler */
  9362. mg_unlock_context(ctx);
  9363. return;
  9364. }
  9365. tmp_rh =
  9366. (struct mg_handler_info *)mg_calloc(sizeof(struct mg_handler_info), 1);
  9367. if (tmp_rh == NULL) {
  9368. mg_unlock_context(ctx);
  9369. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  9370. return;
  9371. }
  9372. tmp_rh->uri = mg_strdup(uri);
  9373. if (!tmp_rh->uri) {
  9374. mg_unlock_context(ctx);
  9375. mg_free(tmp_rh);
  9376. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  9377. return;
  9378. }
  9379. tmp_rh->uri_len = urilen;
  9380. if (handler_type == REQUEST_HANDLER) {
  9381. tmp_rh->handler = handler;
  9382. } else if (handler_type == WEBSOCKET_HANDLER) {
  9383. tmp_rh->subprotocols = subprotocols;
  9384. tmp_rh->connect_handler = connect_handler;
  9385. tmp_rh->ready_handler = ready_handler;
  9386. tmp_rh->data_handler = data_handler;
  9387. tmp_rh->close_handler = close_handler;
  9388. } else { /* AUTH_HANDLER */
  9389. tmp_rh->auth_handler = auth_handler;
  9390. }
  9391. tmp_rh->cbdata = cbdata;
  9392. tmp_rh->handler_type = handler_type;
  9393. tmp_rh->next = NULL;
  9394. *lastref = tmp_rh;
  9395. mg_unlock_context(ctx);
  9396. }
  9397. void
  9398. mg_set_request_handler(struct mg_context *ctx,
  9399. const char *uri,
  9400. mg_request_handler handler,
  9401. void *cbdata)
  9402. {
  9403. mg_set_handler_type(ctx,
  9404. uri,
  9405. REQUEST_HANDLER,
  9406. handler == NULL,
  9407. handler,
  9408. NULL,
  9409. NULL,
  9410. NULL,
  9411. NULL,
  9412. NULL,
  9413. NULL,
  9414. cbdata);
  9415. }
  9416. void
  9417. mg_set_websocket_handler(struct mg_context *ctx,
  9418. const char *uri,
  9419. mg_websocket_connect_handler connect_handler,
  9420. mg_websocket_ready_handler ready_handler,
  9421. mg_websocket_data_handler data_handler,
  9422. mg_websocket_close_handler close_handler,
  9423. void *cbdata)
  9424. {
  9425. mg_set_websocket_handler_with_subprotocols(ctx,
  9426. uri,
  9427. NULL,
  9428. connect_handler,
  9429. ready_handler,
  9430. data_handler,
  9431. close_handler,
  9432. cbdata);
  9433. }
  9434. void
  9435. mg_set_websocket_handler_with_subprotocols(
  9436. struct mg_context *ctx,
  9437. const char *uri,
  9438. struct mg_websocket_subprotocols *subprotocols,
  9439. mg_websocket_connect_handler connect_handler,
  9440. mg_websocket_ready_handler ready_handler,
  9441. mg_websocket_data_handler data_handler,
  9442. mg_websocket_close_handler close_handler,
  9443. void *cbdata)
  9444. {
  9445. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  9446. && (data_handler == NULL)
  9447. && (close_handler == NULL);
  9448. mg_set_handler_type(ctx,
  9449. uri,
  9450. WEBSOCKET_HANDLER,
  9451. is_delete_request,
  9452. NULL,
  9453. subprotocols,
  9454. connect_handler,
  9455. ready_handler,
  9456. data_handler,
  9457. close_handler,
  9458. NULL,
  9459. cbdata);
  9460. }
  9461. void
  9462. mg_set_auth_handler(struct mg_context *ctx,
  9463. const char *uri,
  9464. mg_request_handler handler,
  9465. void *cbdata)
  9466. {
  9467. mg_set_handler_type(ctx,
  9468. uri,
  9469. AUTH_HANDLER,
  9470. handler == NULL,
  9471. NULL,
  9472. NULL,
  9473. NULL,
  9474. NULL,
  9475. NULL,
  9476. NULL,
  9477. handler,
  9478. cbdata);
  9479. }
  9480. static int
  9481. get_request_handler(struct mg_connection *conn,
  9482. int handler_type,
  9483. mg_request_handler *handler,
  9484. struct mg_websocket_subprotocols **subprotocols,
  9485. mg_websocket_connect_handler *connect_handler,
  9486. mg_websocket_ready_handler *ready_handler,
  9487. mg_websocket_data_handler *data_handler,
  9488. mg_websocket_close_handler *close_handler,
  9489. mg_authorization_handler *auth_handler,
  9490. void **cbdata)
  9491. {
  9492. const struct mg_request_info *request_info = mg_get_request_info(conn);
  9493. if (request_info) {
  9494. const char *uri = request_info->local_uri;
  9495. size_t urilen = strlen(uri);
  9496. struct mg_handler_info *tmp_rh;
  9497. if (!conn || !conn->ctx) {
  9498. return 0;
  9499. }
  9500. mg_lock_context(conn->ctx);
  9501. /* first try for an exact match */
  9502. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  9503. tmp_rh = tmp_rh->next) {
  9504. if (tmp_rh->handler_type == handler_type) {
  9505. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  9506. if (handler_type == WEBSOCKET_HANDLER) {
  9507. *subprotocols = tmp_rh->subprotocols;
  9508. *connect_handler = tmp_rh->connect_handler;
  9509. *ready_handler = tmp_rh->ready_handler;
  9510. *data_handler = tmp_rh->data_handler;
  9511. *close_handler = tmp_rh->close_handler;
  9512. } else if (handler_type == REQUEST_HANDLER) {
  9513. *handler = tmp_rh->handler;
  9514. } else { /* AUTH_HANDLER */
  9515. *auth_handler = tmp_rh->auth_handler;
  9516. }
  9517. *cbdata = tmp_rh->cbdata;
  9518. mg_unlock_context(conn->ctx);
  9519. return 1;
  9520. }
  9521. }
  9522. }
  9523. /* next try for a partial match, we will accept uri/something */
  9524. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  9525. tmp_rh = tmp_rh->next) {
  9526. if (tmp_rh->handler_type == handler_type) {
  9527. if (tmp_rh->uri_len < urilen && uri[tmp_rh->uri_len] == '/'
  9528. && memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0) {
  9529. if (handler_type == WEBSOCKET_HANDLER) {
  9530. *subprotocols = tmp_rh->subprotocols;
  9531. *connect_handler = tmp_rh->connect_handler;
  9532. *ready_handler = tmp_rh->ready_handler;
  9533. *data_handler = tmp_rh->data_handler;
  9534. *close_handler = tmp_rh->close_handler;
  9535. } else if (handler_type == REQUEST_HANDLER) {
  9536. *handler = tmp_rh->handler;
  9537. } else { /* AUTH_HANDLER */
  9538. *auth_handler = tmp_rh->auth_handler;
  9539. }
  9540. *cbdata = tmp_rh->cbdata;
  9541. mg_unlock_context(conn->ctx);
  9542. return 1;
  9543. }
  9544. }
  9545. }
  9546. /* finally try for pattern match */
  9547. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  9548. tmp_rh = tmp_rh->next) {
  9549. if (tmp_rh->handler_type == handler_type) {
  9550. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  9551. if (handler_type == WEBSOCKET_HANDLER) {
  9552. *subprotocols = tmp_rh->subprotocols;
  9553. *connect_handler = tmp_rh->connect_handler;
  9554. *ready_handler = tmp_rh->ready_handler;
  9555. *data_handler = tmp_rh->data_handler;
  9556. *close_handler = tmp_rh->close_handler;
  9557. } else if (handler_type == REQUEST_HANDLER) {
  9558. *handler = tmp_rh->handler;
  9559. } else { /* AUTH_HANDLER */
  9560. *auth_handler = tmp_rh->auth_handler;
  9561. }
  9562. *cbdata = tmp_rh->cbdata;
  9563. mg_unlock_context(conn->ctx);
  9564. return 1;
  9565. }
  9566. }
  9567. }
  9568. mg_unlock_context(conn->ctx);
  9569. }
  9570. return 0; /* none found */
  9571. }
  9572. /* Check if the script file is in a path, allowed for script files.
  9573. * This can be used if uploading files is possible not only for the server
  9574. * admin, and the upload mechanism does not check the file extension.
  9575. */
  9576. static int
  9577. is_in_script_path(const struct mg_connection *conn, const char *path)
  9578. {
  9579. /* TODO: Add config value for allowed script path.
  9580. * Default: All allowed. */
  9581. (void)conn;
  9582. (void)path;
  9583. return 1;
  9584. }
  9585. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  9586. static int
  9587. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  9588. void *cbdata)
  9589. {
  9590. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9591. if (pcallbacks->websocket_connect) {
  9592. return pcallbacks->websocket_connect(conn);
  9593. }
  9594. /* No handler set - assume "OK" */
  9595. return 0;
  9596. }
  9597. static void
  9598. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  9599. {
  9600. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9601. if (pcallbacks->websocket_ready) {
  9602. pcallbacks->websocket_ready(conn);
  9603. }
  9604. }
  9605. static int
  9606. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  9607. int bits,
  9608. char *data,
  9609. size_t len,
  9610. void *cbdata)
  9611. {
  9612. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9613. if (pcallbacks->websocket_data) {
  9614. return pcallbacks->websocket_data(conn, bits, data, len);
  9615. }
  9616. /* No handler set - assume "OK" */
  9617. return 1;
  9618. }
  9619. #endif
  9620. /* This is the heart of the Civetweb's logic.
  9621. * This function is called when the request is read, parsed and validated,
  9622. * and Civetweb must decide what action to take: serve a file, or
  9623. * a directory, or call embedded function, etcetera. */
  9624. static void
  9625. handle_request(struct mg_connection *conn)
  9626. {
  9627. struct mg_request_info *ri = &conn->request_info;
  9628. char path[PATH_MAX];
  9629. int uri_len, ssl_index;
  9630. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  9631. is_put_or_delete_request = 0, is_callback_resource = 0;
  9632. int i;
  9633. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9634. mg_request_handler callback_handler = NULL;
  9635. struct mg_websocket_subprotocols *subprotocols;
  9636. mg_websocket_connect_handler ws_connect_handler = NULL;
  9637. mg_websocket_ready_handler ws_ready_handler = NULL;
  9638. mg_websocket_data_handler ws_data_handler = NULL;
  9639. mg_websocket_close_handler ws_close_handler = NULL;
  9640. void *callback_data = NULL;
  9641. mg_authorization_handler auth_handler = NULL;
  9642. void *auth_callback_data = NULL;
  9643. #if !defined(NO_FILES)
  9644. time_t curtime = time(NULL);
  9645. char date[64];
  9646. #endif
  9647. path[0] = 0;
  9648. /* 1. get the request url */
  9649. /* 1.1. split into url and query string */
  9650. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  9651. != NULL) {
  9652. *((char *)conn->request_info.query_string++) = '\0';
  9653. }
  9654. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  9655. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  9656. ssl_index = get_first_ssl_listener_index(conn->ctx);
  9657. if (ssl_index >= 0) {
  9658. redirect_to_https_port(conn, ssl_index);
  9659. } else {
  9660. /* A http to https forward port has been specified,
  9661. * but no https port to forward to. */
  9662. mg_send_http_error(conn,
  9663. 503,
  9664. "%s",
  9665. "Error: SSL forward not configured properly");
  9666. mg_cry(conn, "Can not redirect to SSL, no SSL port available");
  9667. }
  9668. return;
  9669. }
  9670. uri_len = (int)strlen(ri->local_uri);
  9671. /* 1.3. decode url (if config says so) */
  9672. if (should_decode_url(conn)) {
  9673. mg_url_decode(
  9674. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  9675. }
  9676. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  9677. * not possible */
  9678. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  9679. /* step 1. completed, the url is known now */
  9680. uri_len = (int)strlen(ri->local_uri);
  9681. DEBUG_TRACE("URL: %s", ri->local_uri);
  9682. /* 3. if this ip has limited speed, set it for this connection */
  9683. conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
  9684. get_remote_ip(conn),
  9685. ri->local_uri);
  9686. /* 4. call a "handle everything" callback, if registered */
  9687. if (conn->ctx->callbacks.begin_request != NULL) {
  9688. /* Note that since V1.7 the "begin_request" function is called
  9689. * before an authorization check. If an authorization check is
  9690. * required, use a request_handler instead. */
  9691. i = conn->ctx->callbacks.begin_request(conn);
  9692. if (i > 0) {
  9693. /* callback already processed the request. Store the
  9694. return value as a status code for the access log. */
  9695. conn->status_code = i;
  9696. discard_unread_request_data(conn);
  9697. return;
  9698. } else if (i == 0) {
  9699. /* civetweb should process the request */
  9700. } else {
  9701. /* unspecified - may change with the next version */
  9702. return;
  9703. }
  9704. }
  9705. /* request not yet handled by a handler or redirect, so the request
  9706. * is processed here */
  9707. /* 5. interpret the url to find out how the request must be handled
  9708. */
  9709. /* 5.1. first test, if the request targets the regular http(s)://
  9710. * protocol namespace or the websocket ws(s):// protocol namespace.
  9711. */
  9712. is_websocket_request = is_websocket_protocol(conn);
  9713. /* 5.2. check if the request will be handled by a callback */
  9714. if (get_request_handler(conn,
  9715. is_websocket_request ? WEBSOCKET_HANDLER
  9716. : REQUEST_HANDLER,
  9717. &callback_handler,
  9718. &subprotocols,
  9719. &ws_connect_handler,
  9720. &ws_ready_handler,
  9721. &ws_data_handler,
  9722. &ws_close_handler,
  9723. NULL,
  9724. &callback_data)) {
  9725. /* 5.2.1. A callback will handle this request. All requests
  9726. * handled
  9727. * by a callback have to be considered as requests to a script
  9728. * resource. */
  9729. is_callback_resource = 1;
  9730. is_script_resource = 1;
  9731. is_put_or_delete_request = is_put_or_delete_method(conn);
  9732. } else {
  9733. no_callback_resource:
  9734. /* 5.2.2. No callback is responsible for this request. The URI
  9735. * addresses a file based resource (static content or Lua/cgi
  9736. * scripts in the file system). */
  9737. is_callback_resource = 0;
  9738. interpret_uri(conn,
  9739. path,
  9740. sizeof(path),
  9741. &file.stat,
  9742. &is_found,
  9743. &is_script_resource,
  9744. &is_websocket_request,
  9745. &is_put_or_delete_request);
  9746. }
  9747. /* 6. authorization check */
  9748. /* 6.1. a custom authorization handler is installed */
  9749. if (get_request_handler(conn,
  9750. AUTH_HANDLER,
  9751. NULL,
  9752. NULL,
  9753. NULL,
  9754. NULL,
  9755. NULL,
  9756. NULL,
  9757. &auth_handler,
  9758. &auth_callback_data)) {
  9759. if (!auth_handler(conn, auth_callback_data)) {
  9760. return;
  9761. }
  9762. } else if (is_put_or_delete_request && !is_script_resource
  9763. && !is_callback_resource) {
  9764. /* 6.2. this request is a PUT/DELETE to a real file */
  9765. /* 6.2.1. thus, the server must have real files */
  9766. #if defined(NO_FILES)
  9767. if (1) {
  9768. #else
  9769. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  9770. #endif
  9771. /* This server does not have any real files, thus the
  9772. * PUT/DELETE methods are not valid. */
  9773. mg_send_http_error(conn,
  9774. 405,
  9775. "%s method not allowed",
  9776. conn->request_info.request_method);
  9777. return;
  9778. }
  9779. #if !defined(NO_FILES)
  9780. /* 6.2.2. Check if put authorization for static files is
  9781. * available.
  9782. */
  9783. if (!is_authorized_for_put(conn)) {
  9784. send_authorization_request(conn);
  9785. return;
  9786. }
  9787. #endif
  9788. } else {
  9789. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  9790. * or it is a PUT or DELETE request to a resource that does not
  9791. * correspond to a file. Check authorization. */
  9792. if (!check_authorization(conn, path)) {
  9793. send_authorization_request(conn);
  9794. return;
  9795. }
  9796. }
  9797. /* request is authorized or does not need authorization */
  9798. /* 7. check if there are request handlers for this uri */
  9799. if (is_callback_resource) {
  9800. if (!is_websocket_request) {
  9801. i = callback_handler(conn, callback_data);
  9802. if (i > 0) {
  9803. /* Do nothing, callback has served the request. Store
  9804. * then return value as status code for the log and discard
  9805. * all data from the client not used by the callback. */
  9806. conn->status_code = i;
  9807. discard_unread_request_data(conn);
  9808. } else {
  9809. /* The handler did NOT handle the request. */
  9810. /* Some proper reactions would be:
  9811. * a) close the connections without sending anything
  9812. * b) send a 404 not found
  9813. * c) try if there is a file matching the URI
  9814. * It would be possible to do a, b or c in the callback
  9815. * implementation, and return 1 - we cannot do anything
  9816. * here, that is not possible in the callback.
  9817. *
  9818. * TODO: What would be the best reaction here?
  9819. * (Note: The reaction may change, if there is a better idea.)
  9820. */
  9821. /* For the moment, use option c: We look for a proper file,
  9822. * but since a file request is not always a script resource,
  9823. * the authorization check might be different. */
  9824. interpret_uri(conn,
  9825. path,
  9826. sizeof(path),
  9827. &file.stat,
  9828. &is_found,
  9829. &is_script_resource,
  9830. &is_websocket_request,
  9831. &is_put_or_delete_request);
  9832. callback_handler = NULL;
  9833. /* Here we are at a dead end:
  9834. * According to URI matching, a callback should be
  9835. * responsible for handling the request,
  9836. * we called it, but the callback declared itself
  9837. * not responsible.
  9838. * We use a goto here, to get out of this dead end,
  9839. * and continue with the default handling.
  9840. * A goto here is simpler and better to understand
  9841. * than some curious loop. */
  9842. goto no_callback_resource;
  9843. }
  9844. } else {
  9845. #if defined(USE_WEBSOCKET)
  9846. handle_websocket_request(conn,
  9847. path,
  9848. is_callback_resource,
  9849. subprotocols,
  9850. ws_connect_handler,
  9851. ws_ready_handler,
  9852. ws_data_handler,
  9853. ws_close_handler,
  9854. callback_data);
  9855. #endif
  9856. }
  9857. return;
  9858. }
  9859. /* 8. handle websocket requests */
  9860. #if defined(USE_WEBSOCKET)
  9861. if (is_websocket_request) {
  9862. if (is_script_resource) {
  9863. if (is_in_script_path(conn, path)) {
  9864. /* Websocket Lua script */
  9865. handle_websocket_request(conn,
  9866. path,
  9867. 0 /* Lua Script */,
  9868. NULL,
  9869. NULL,
  9870. NULL,
  9871. NULL,
  9872. NULL,
  9873. &conn->ctx->callbacks);
  9874. } else {
  9875. /* Script was in an illegal path */
  9876. mg_send_http_error(conn, 403, "%s", "Forbidden");
  9877. }
  9878. } else {
  9879. #if defined(MG_LEGACY_INTERFACE)
  9880. handle_websocket_request(
  9881. conn,
  9882. path,
  9883. !is_script_resource /* could be deprecated global callback */,
  9884. NULL,
  9885. deprecated_websocket_connect_wrapper,
  9886. deprecated_websocket_ready_wrapper,
  9887. deprecated_websocket_data_wrapper,
  9888. NULL,
  9889. &conn->ctx->callbacks);
  9890. #else
  9891. mg_send_http_error(conn, 404, "%s", "Not found");
  9892. #endif
  9893. }
  9894. return;
  9895. } else
  9896. #endif
  9897. #if defined(NO_FILES)
  9898. /* 9a. In case the server uses only callbacks, this uri is
  9899. * unknown.
  9900. * Then, all request handling ends here. */
  9901. mg_send_http_error(conn, 404, "%s", "Not Found");
  9902. #else
  9903. /* 9b. This request is either for a static file or resource handled
  9904. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  9905. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  9906. mg_send_http_error(conn, 404, "%s", "Not Found");
  9907. return;
  9908. }
  9909. /* 10. Request is handled by a script */
  9910. if (is_script_resource) {
  9911. handle_file_based_request(conn, path, &file);
  9912. return;
  9913. }
  9914. /* 11. Handle put/delete/mkcol requests */
  9915. if (is_put_or_delete_request) {
  9916. /* 11.1. PUT method */
  9917. if (!strcmp(ri->request_method, "PUT")) {
  9918. put_file(conn, path);
  9919. return;
  9920. }
  9921. /* 11.2. DELETE method */
  9922. if (!strcmp(ri->request_method, "DELETE")) {
  9923. delete_file(conn, path);
  9924. return;
  9925. }
  9926. /* 11.3. MKCOL method */
  9927. if (!strcmp(ri->request_method, "MKCOL")) {
  9928. mkcol(conn, path);
  9929. return;
  9930. }
  9931. /* 11.4. PATCH method
  9932. * This method is not supported for static resources,
  9933. * only for scripts (Lua, CGI) and callbacks. */
  9934. mg_send_http_error(conn,
  9935. 405,
  9936. "%s method not allowed",
  9937. conn->request_info.request_method);
  9938. return;
  9939. }
  9940. /* 11. File does not exist, or it was configured that it should be
  9941. * hidden */
  9942. if (!is_found || (must_hide_file(conn, path))) {
  9943. mg_send_http_error(conn, 404, "%s", "Not found");
  9944. return;
  9945. }
  9946. /* 12. Directory uris should end with a slash */
  9947. if (file.stat.is_directory && (uri_len > 0)
  9948. && (ri->local_uri[uri_len - 1] != '/')) {
  9949. gmt_time_string(date, sizeof(date), &curtime);
  9950. mg_printf(conn,
  9951. "HTTP/1.1 301 Moved Permanently\r\n"
  9952. "Location: %s/\r\n"
  9953. "Date: %s\r\n"
  9954. /* "Cache-Control: private\r\n" (= default) */
  9955. "Content-Length: 0\r\n"
  9956. "Connection: %s\r\n",
  9957. ri->request_uri,
  9958. date,
  9959. suggest_connection_header(conn));
  9960. send_additional_header(conn);
  9961. mg_printf(conn, "\r\n");
  9962. return;
  9963. }
  9964. /* 13. Handle other methods than GET/HEAD */
  9965. /* 13.1. Handle PROPFIND */
  9966. if (!strcmp(ri->request_method, "PROPFIND")) {
  9967. handle_propfind(conn, path, &file.stat);
  9968. return;
  9969. }
  9970. /* 13.2. Handle OPTIONS for files */
  9971. if (!strcmp(ri->request_method, "OPTIONS")) {
  9972. /* This standard handler is only used for real files.
  9973. * Scripts should support the OPTIONS method themselves, to allow a
  9974. * maximum flexibility.
  9975. * Lua and CGI scripts may fully support CORS this way (including
  9976. * preflights). */
  9977. send_options(conn);
  9978. return;
  9979. }
  9980. /* 13.3. everything but GET and HEAD (e.g. POST) */
  9981. if (0 != strcmp(ri->request_method, "GET")
  9982. && 0 != strcmp(ri->request_method, "HEAD")) {
  9983. mg_send_http_error(conn,
  9984. 405,
  9985. "%s method not allowed",
  9986. conn->request_info.request_method);
  9987. return;
  9988. }
  9989. /* 14. directories */
  9990. if (file.stat.is_directory) {
  9991. /* Substitute files have already been handled above. */
  9992. /* Here we can either generate and send a directory listing,
  9993. * or send an "access denied" error. */
  9994. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  9995. "yes")) {
  9996. handle_directory_request(conn, path);
  9997. } else {
  9998. mg_send_http_error(conn,
  9999. 403,
  10000. "%s",
  10001. "Error: Directory listing denied");
  10002. }
  10003. return;
  10004. }
  10005. handle_file_based_request(conn, path, &file);
  10006. #endif /* !defined(NO_FILES) */
  10007. #if 0
  10008. /* Perform redirect and auth checks before calling begin_request()
  10009. * handler.
  10010. * Otherwise, begin_request() would need to perform auth checks and
  10011. * redirects. */
  10012. #endif
  10013. }
  10014. static void
  10015. handle_file_based_request(struct mg_connection *conn,
  10016. const char *path,
  10017. struct mg_file *file)
  10018. {
  10019. if (!conn || !conn->ctx) {
  10020. return;
  10021. }
  10022. if (0) {
  10023. #ifdef USE_LUA
  10024. } else if (match_prefix(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  10025. strlen(
  10026. conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  10027. path) > 0) {
  10028. if (is_in_script_path(conn, path)) {
  10029. /* Lua server page: an SSI like page containing mostly plain html
  10030. * code
  10031. * plus some tags with server generated contents. */
  10032. handle_lsp_request(conn, path, file, NULL);
  10033. } else {
  10034. /* Script was in an illegal path */
  10035. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10036. }
  10037. } else if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  10038. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  10039. path) > 0) {
  10040. if (is_in_script_path(conn, path)) {
  10041. /* Lua in-server module script: a CGI like script used to generate
  10042. * the
  10043. * entire reply. */
  10044. mg_exec_lua_script(conn, path, NULL);
  10045. } else {
  10046. /* Script was in an illegal path */
  10047. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10048. }
  10049. #endif
  10050. #if defined(USE_DUKTAPE)
  10051. } else if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  10052. strlen(
  10053. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  10054. path) > 0) {
  10055. if (is_in_script_path(conn, path)) {
  10056. /* Call duktape to generate the page */
  10057. mg_exec_duktape_script(conn, path);
  10058. } else {
  10059. /* Script was in an illegal path */
  10060. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10061. }
  10062. #endif
  10063. #if !defined(NO_CGI)
  10064. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  10065. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  10066. path) > 0) {
  10067. if (is_in_script_path(conn, path)) {
  10068. /* CGI scripts may support all HTTP methods */
  10069. handle_cgi_request(conn, path);
  10070. } else {
  10071. /* Script was in an illegal path */
  10072. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10073. }
  10074. #endif /* !NO_CGI */
  10075. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  10076. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  10077. path) > 0) {
  10078. if (is_in_script_path(conn, path)) {
  10079. handle_ssi_file_request(conn, path, file);
  10080. } else {
  10081. /* Script was in an illegal path */
  10082. mg_send_http_error(conn, 403, "%s", "Forbidden");
  10083. }
  10084. #if !defined(NO_CACHING)
  10085. } else if ((!conn->in_error_handler)
  10086. && is_not_modified(conn, &file->stat)) {
  10087. /* Send 304 "Not Modified" - this must not send any body data */
  10088. handle_not_modified_static_file_request(conn, file);
  10089. #endif /* !NO_CACHING */
  10090. } else {
  10091. handle_static_file_request(conn, path, file, NULL, NULL);
  10092. }
  10093. }
  10094. static void
  10095. close_all_listening_sockets(struct mg_context *ctx)
  10096. {
  10097. unsigned int i;
  10098. if (!ctx) {
  10099. return;
  10100. }
  10101. for (i = 0; i < ctx->num_listening_sockets; i++) {
  10102. closesocket(ctx->listening_sockets[i].sock);
  10103. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  10104. }
  10105. mg_free(ctx->listening_sockets);
  10106. ctx->listening_sockets = NULL;
  10107. mg_free(ctx->listening_socket_fds);
  10108. ctx->listening_socket_fds = NULL;
  10109. }
  10110. /* Valid listening port specification is: [ip_address:]port[s]
  10111. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  10112. * Examples for IPv6: [::]:80, [::1]:80,
  10113. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  10114. * see https://tools.ietf.org/html/rfc3513#section-2.2
  10115. * In order to bind to both, IPv4 and IPv6, you can either add
  10116. * both ports using 8080,[::]:8080, or the short form +8080.
  10117. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  10118. * one only accepting IPv4 the other only IPv6. +8080 creates
  10119. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  10120. * environment, they might work differently, or might not work
  10121. * at all - it must be tested what options work best in the
  10122. * relevant network environment.
  10123. */
  10124. static int
  10125. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  10126. {
  10127. unsigned int a, b, c, d, port;
  10128. int ch, len;
  10129. #if defined(USE_IPV6)
  10130. char buf[100] = {0};
  10131. #endif
  10132. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  10133. * Also, all-zeroes in the socket address means binding to all addresses
  10134. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  10135. memset(so, 0, sizeof(*so));
  10136. so->lsa.sin.sin_family = AF_INET;
  10137. *ip_version = 0;
  10138. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  10139. == 5) {
  10140. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  10141. so->lsa.sin.sin_addr.s_addr =
  10142. htonl((a << 24) | (b << 16) | (c << 8) | d);
  10143. so->lsa.sin.sin_port = htons((uint16_t)port);
  10144. *ip_version = 4;
  10145. #if defined(USE_IPV6)
  10146. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  10147. && mg_inet_pton(
  10148. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  10149. /* IPv6 address, examples: see above */
  10150. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  10151. */
  10152. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  10153. *ip_version = 6;
  10154. #endif
  10155. } else if ((vec->ptr[0] == '+')
  10156. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  10157. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  10158. /* Add 1 to len for the + character we skipped before */
  10159. len++;
  10160. #if defined(USE_IPV6)
  10161. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  10162. so->lsa.sin6.sin6_family = AF_INET6;
  10163. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  10164. *ip_version = 4 + 6;
  10165. #else
  10166. /* Bind to IPv4 only, since IPv6 is not built in. */
  10167. so->lsa.sin.sin_port = htons((uint16_t)port);
  10168. *ip_version = 4;
  10169. #endif
  10170. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  10171. /* If only port is specified, bind to IPv4, INADDR_ANY */
  10172. so->lsa.sin.sin_port = htons((uint16_t)port);
  10173. *ip_version = 4;
  10174. } else {
  10175. /* Parsing failure. Make port invalid. */
  10176. port = 0;
  10177. len = 0;
  10178. }
  10179. /* sscanf and the option splitting code ensure the following condition
  10180. */
  10181. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  10182. *ip_version = 0;
  10183. return 0;
  10184. }
  10185. ch = vec->ptr[len]; /* Next character after the port number */
  10186. so->is_ssl = (ch == 's');
  10187. so->ssl_redir = (ch == 'r');
  10188. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  10189. if (is_valid_port(port)
  10190. && (ch == '\0' || ch == 's' || ch == 'r' || ch == ',')) {
  10191. return 1;
  10192. }
  10193. /* Reset ip_version to 0 of there is an error */
  10194. *ip_version = 0;
  10195. return 0;
  10196. }
  10197. static int
  10198. set_ports_option(struct mg_context *ctx)
  10199. {
  10200. const char *list;
  10201. int on = 1;
  10202. #if defined(USE_IPV6)
  10203. int off = 0;
  10204. #endif
  10205. struct vec vec;
  10206. struct socket so, *ptr;
  10207. struct pollfd *pfd;
  10208. union usa usa;
  10209. socklen_t len;
  10210. int ip_version;
  10211. int portsTotal = 0;
  10212. int portsOk = 0;
  10213. if (!ctx) {
  10214. return 0;
  10215. }
  10216. memset(&so, 0, sizeof(so));
  10217. memset(&usa, 0, sizeof(usa));
  10218. len = sizeof(usa);
  10219. list = ctx->config[LISTENING_PORTS];
  10220. while ((list = next_option(list, &vec, NULL)) != NULL) {
  10221. portsTotal++;
  10222. if (!parse_port_string(&vec, &so, &ip_version)) {
  10223. mg_cry(fc(ctx),
  10224. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  10225. (int)vec.len,
  10226. vec.ptr,
  10227. portsTotal,
  10228. "[IP_ADDRESS:]PORT[s|r]");
  10229. continue;
  10230. }
  10231. #if !defined(NO_SSL)
  10232. if (so.is_ssl && ctx->ssl_ctx == NULL) {
  10233. mg_cry(fc(ctx),
  10234. "Cannot add SSL socket (entry %i). Is -ssl_certificate "
  10235. "option set?",
  10236. portsTotal);
  10237. continue;
  10238. }
  10239. #endif
  10240. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  10241. == INVALID_SOCKET) {
  10242. mg_cry(fc(ctx), "cannot create socket (entry %i)", portsTotal);
  10243. continue;
  10244. }
  10245. #ifdef _WIN32
  10246. /* Windows SO_REUSEADDR lets many procs binds to a
  10247. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  10248. * if someone already has the socket -- DTL */
  10249. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  10250. * Windows might need a few seconds before
  10251. * the same port can be used again in the
  10252. * same process, so a short Sleep may be
  10253. * required between mg_stop and mg_start.
  10254. */
  10255. if (setsockopt(so.sock,
  10256. SOL_SOCKET,
  10257. SO_EXCLUSIVEADDRUSE,
  10258. (SOCK_OPT_TYPE)&on,
  10259. sizeof(on)) != 0) {
  10260. /* Set reuse option, but don't abort on errors. */
  10261. mg_cry(fc(ctx),
  10262. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  10263. portsTotal);
  10264. }
  10265. #else
  10266. if (setsockopt(so.sock,
  10267. SOL_SOCKET,
  10268. SO_REUSEADDR,
  10269. (SOCK_OPT_TYPE)&on,
  10270. sizeof(on)) != 0) {
  10271. /* Set reuse option, but don't abort on errors. */
  10272. mg_cry(fc(ctx),
  10273. "cannot set socket option SO_REUSEADDR (entry %i)",
  10274. portsTotal);
  10275. }
  10276. #endif
  10277. if (ip_version > 4) {
  10278. #if defined(USE_IPV6)
  10279. if (ip_version == 6) {
  10280. if (so.lsa.sa.sa_family == AF_INET6
  10281. && setsockopt(so.sock,
  10282. IPPROTO_IPV6,
  10283. IPV6_V6ONLY,
  10284. (void *)&off,
  10285. sizeof(off)) != 0) {
  10286. /* Set IPv6 only option, but don't abort on errors. */
  10287. mg_cry(fc(ctx),
  10288. "cannot set socket option IPV6_V6ONLY (entry %i)",
  10289. portsTotal);
  10290. }
  10291. }
  10292. #else
  10293. mg_cry(fc(ctx), "IPv6 not available");
  10294. closesocket(so.sock);
  10295. so.sock = INVALID_SOCKET;
  10296. continue;
  10297. #endif
  10298. }
  10299. if (so.lsa.sa.sa_family == AF_INET) {
  10300. len = sizeof(so.lsa.sin);
  10301. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  10302. mg_cry(fc(ctx),
  10303. "cannot bind to %.*s: %d (%s)",
  10304. (int)vec.len,
  10305. vec.ptr,
  10306. (int)ERRNO,
  10307. strerror(errno));
  10308. closesocket(so.sock);
  10309. so.sock = INVALID_SOCKET;
  10310. continue;
  10311. }
  10312. }
  10313. #if defined(USE_IPV6)
  10314. else if (so.lsa.sa.sa_family == AF_INET6) {
  10315. len = sizeof(so.lsa.sin6);
  10316. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  10317. mg_cry(fc(ctx),
  10318. "cannot bind to IPv6 %.*s: %d (%s)",
  10319. (int)vec.len,
  10320. vec.ptr,
  10321. (int)ERRNO,
  10322. strerror(errno));
  10323. closesocket(so.sock);
  10324. so.sock = INVALID_SOCKET;
  10325. continue;
  10326. }
  10327. }
  10328. #endif
  10329. else {
  10330. mg_cry(fc(ctx),
  10331. "cannot bind: address family not supported (entry %i)",
  10332. portsTotal);
  10333. continue;
  10334. }
  10335. if (listen(so.sock, SOMAXCONN) != 0) {
  10336. mg_cry(fc(ctx),
  10337. "cannot listen to %.*s: %d (%s)",
  10338. (int)vec.len,
  10339. vec.ptr,
  10340. (int)ERRNO,
  10341. strerror(errno));
  10342. closesocket(so.sock);
  10343. so.sock = INVALID_SOCKET;
  10344. continue;
  10345. }
  10346. if (getsockname(so.sock, &(usa.sa), &len) != 0
  10347. || usa.sa.sa_family != so.lsa.sa.sa_family) {
  10348. int err = (int)ERRNO;
  10349. mg_cry(fc(ctx),
  10350. "call to getsockname failed %.*s: %d (%s)",
  10351. (int)vec.len,
  10352. vec.ptr,
  10353. err,
  10354. strerror(errno));
  10355. closesocket(so.sock);
  10356. so.sock = INVALID_SOCKET;
  10357. continue;
  10358. }
  10359. /* Update lsa port in case of random free ports */
  10360. #if defined(USE_IPV6)
  10361. if (so.lsa.sa.sa_family == AF_INET6) {
  10362. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  10363. } else
  10364. #endif
  10365. {
  10366. so.lsa.sin.sin_port = usa.sin.sin_port;
  10367. }
  10368. if ((ptr = (struct socket *)
  10369. mg_realloc(ctx->listening_sockets,
  10370. (ctx->num_listening_sockets + 1)
  10371. * sizeof(ctx->listening_sockets[0]))) == NULL) {
  10372. mg_cry(fc(ctx), "%s", "Out of memory");
  10373. closesocket(so.sock);
  10374. so.sock = INVALID_SOCKET;
  10375. continue;
  10376. }
  10377. if ((pfd = (struct pollfd *)mg_realloc(
  10378. ctx->listening_socket_fds,
  10379. (ctx->num_listening_sockets + 1)
  10380. * sizeof(ctx->listening_socket_fds[0]))) == NULL) {
  10381. mg_cry(fc(ctx), "%s", "Out of memory");
  10382. closesocket(so.sock);
  10383. so.sock = INVALID_SOCKET;
  10384. mg_free(ptr);
  10385. continue;
  10386. }
  10387. set_close_on_exec(so.sock, fc(ctx));
  10388. ctx->listening_sockets = ptr;
  10389. ctx->listening_sockets[ctx->num_listening_sockets] = so;
  10390. ctx->listening_socket_fds = pfd;
  10391. ctx->num_listening_sockets++;
  10392. portsOk++;
  10393. }
  10394. if (portsOk != portsTotal) {
  10395. close_all_listening_sockets(ctx);
  10396. portsOk = 0;
  10397. }
  10398. return portsOk;
  10399. }
  10400. static const char *
  10401. header_val(const struct mg_connection *conn, const char *header)
  10402. {
  10403. const char *header_value;
  10404. if ((header_value = mg_get_header(conn, header)) == NULL) {
  10405. return "-";
  10406. } else {
  10407. return header_value;
  10408. }
  10409. }
  10410. static void
  10411. log_access(const struct mg_connection *conn)
  10412. {
  10413. const struct mg_request_info *ri;
  10414. struct mg_file fi;
  10415. char date[64], src_addr[IP_ADDR_STR_LEN];
  10416. struct tm *tm;
  10417. const char *referer;
  10418. const char *user_agent;
  10419. char buf[4096];
  10420. if (!conn || !conn->ctx) {
  10421. return;
  10422. }
  10423. if (conn->ctx->config[ACCESS_LOG_FILE] != NULL) {
  10424. if (mg_fopen(conn,
  10425. conn->ctx->config[ACCESS_LOG_FILE],
  10426. MG_FOPEN_MODE_APPEND,
  10427. &fi) == 0) {
  10428. fi.access.fp = NULL;
  10429. }
  10430. } else {
  10431. fi.access.fp = NULL;
  10432. }
  10433. /* Log is written to a file and/or a callback. If both are not set,
  10434. * executing the rest of the function is pointless. */
  10435. if ((fi.access.fp == NULL) && (conn->ctx->callbacks.log_access == NULL)) {
  10436. return;
  10437. }
  10438. tm = localtime(&conn->conn_birth_time);
  10439. if (tm != NULL) {
  10440. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  10441. } else {
  10442. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  10443. date[sizeof(date) - 1] = '\0';
  10444. }
  10445. ri = &conn->request_info;
  10446. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  10447. referer = header_val(conn, "Referer");
  10448. user_agent = header_val(conn, "User-Agent");
  10449. mg_snprintf(conn,
  10450. NULL, /* Ignore truncation in access log */
  10451. buf,
  10452. sizeof(buf),
  10453. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  10454. src_addr,
  10455. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  10456. date,
  10457. ri->request_method ? ri->request_method : "-",
  10458. ri->request_uri ? ri->request_uri : "-",
  10459. ri->query_string ? "?" : "",
  10460. ri->query_string ? ri->query_string : "",
  10461. ri->http_version,
  10462. conn->status_code,
  10463. conn->num_bytes_sent,
  10464. referer,
  10465. user_agent);
  10466. if (conn->ctx->callbacks.log_access) {
  10467. conn->ctx->callbacks.log_access(conn, buf);
  10468. }
  10469. if (fi.access.fp) {
  10470. int ok = 1;
  10471. flockfile(fi.access.fp);
  10472. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  10473. ok = 0;
  10474. }
  10475. if (fflush(fi.access.fp) != 0) {
  10476. ok = 0;
  10477. }
  10478. funlockfile(fi.access.fp);
  10479. if (mg_fclose(&fi.access) != 0) {
  10480. ok = 0;
  10481. }
  10482. if (!ok) {
  10483. mg_cry(conn,
  10484. "Error writing log file %s",
  10485. conn->ctx->config[ACCESS_LOG_FILE]);
  10486. }
  10487. }
  10488. }
  10489. /* Verify given socket address against the ACL.
  10490. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  10491. */
  10492. static int
  10493. check_acl(struct mg_context *ctx, uint32_t remote_ip)
  10494. {
  10495. int allowed, flag;
  10496. uint32_t net, mask;
  10497. struct vec vec;
  10498. if (ctx) {
  10499. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  10500. /* If any ACL is set, deny by default */
  10501. allowed = (list == NULL) ? '+' : '-';
  10502. while ((list = next_option(list, &vec, NULL)) != NULL) {
  10503. flag = vec.ptr[0];
  10504. if ((flag != '+' && flag != '-')
  10505. || parse_net(&vec.ptr[1], &net, &mask) == 0) {
  10506. mg_cry(fc(ctx),
  10507. "%s: subnet must be [+|-]x.x.x.x[/x]",
  10508. __func__);
  10509. return -1;
  10510. }
  10511. if (net == (remote_ip & mask)) {
  10512. allowed = flag;
  10513. }
  10514. }
  10515. return allowed == '+';
  10516. }
  10517. return -1;
  10518. }
  10519. #if !defined(_WIN32)
  10520. static int
  10521. set_uid_option(struct mg_context *ctx)
  10522. {
  10523. struct passwd *pw;
  10524. if (ctx) {
  10525. const char *uid = ctx->config[RUN_AS_USER];
  10526. int success = 0;
  10527. if (uid == NULL) {
  10528. success = 1;
  10529. } else {
  10530. if ((pw = getpwnam(uid)) == NULL) {
  10531. mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  10532. } else if (setgid(pw->pw_gid) == -1) {
  10533. mg_cry(fc(ctx),
  10534. "%s: setgid(%s): %s",
  10535. __func__,
  10536. uid,
  10537. strerror(errno));
  10538. } else if (setgroups(0, NULL)) {
  10539. mg_cry(fc(ctx),
  10540. "%s: setgroups(): %s",
  10541. __func__,
  10542. strerror(errno));
  10543. } else if (setuid(pw->pw_uid) == -1) {
  10544. mg_cry(fc(ctx),
  10545. "%s: setuid(%s): %s",
  10546. __func__,
  10547. uid,
  10548. strerror(errno));
  10549. } else {
  10550. success = 1;
  10551. }
  10552. }
  10553. return success;
  10554. }
  10555. return 0;
  10556. }
  10557. #endif /* !_WIN32 */
  10558. static void
  10559. tls_dtor(void *key)
  10560. {
  10561. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  10562. /* key == pthread_getspecific(sTlsKey); */
  10563. if (tls) {
  10564. if (tls->is_master == 2) {
  10565. tls->is_master = -3; /* Mark memory as dead */
  10566. mg_free(tls);
  10567. }
  10568. }
  10569. pthread_setspecific(sTlsKey, NULL);
  10570. }
  10571. #if !defined(NO_SSL)
  10572. static int
  10573. ssl_use_pem_file(struct mg_context *ctx, const char *pem, const char *chain);
  10574. static const char *ssl_error(void);
  10575. static int
  10576. refresh_trust(struct mg_connection *conn)
  10577. {
  10578. static int reload_lock = 0;
  10579. static long int data_check = 0;
  10580. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  10581. struct stat cert_buf;
  10582. long int t;
  10583. const char *pem;
  10584. const char *chain;
  10585. int should_verify_peer;
  10586. if ((pem = conn->ctx->config[SSL_CERTIFICATE]) == NULL) {
  10587. /* If peem is NULL and conn->ctx->callbacks.init_ssl is not,
  10588. * refresh_trust still can not work. */
  10589. return 0;
  10590. }
  10591. chain = conn->ctx->config[SSL_CERTIFICATE_CHAIN];
  10592. if (chain == NULL) {
  10593. chain = pem;
  10594. }
  10595. if (*chain == 0) {
  10596. chain = NULL;
  10597. }
  10598. t = data_check;
  10599. if (stat(pem, &cert_buf) != -1) {
  10600. t = (long int)cert_buf.st_mtime;
  10601. }
  10602. if (data_check != t) {
  10603. data_check = t;
  10604. should_verify_peer =
  10605. (conn->ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  10606. && (mg_strcasecmp(conn->ctx->config[SSL_DO_VERIFY_PEER], "yes")
  10607. == 0);
  10608. if (should_verify_peer) {
  10609. char *ca_path = conn->ctx->config[SSL_CA_PATH];
  10610. char *ca_file = conn->ctx->config[SSL_CA_FILE];
  10611. if (SSL_CTX_load_verify_locations(conn->ctx->ssl_ctx,
  10612. ca_file,
  10613. ca_path) != 1) {
  10614. mg_cry(fc(conn->ctx),
  10615. "SSL_CTX_load_verify_locations error: %s "
  10616. "ssl_verify_peer requires setting "
  10617. "either ssl_ca_path or ssl_ca_file. Is any of them "
  10618. "present in "
  10619. "the .conf file?",
  10620. ssl_error());
  10621. return 0;
  10622. }
  10623. }
  10624. if (1 == mg_atomic_inc(p_reload_lock)) {
  10625. if (ssl_use_pem_file(conn->ctx, pem, chain) == 0) {
  10626. return 0;
  10627. }
  10628. *p_reload_lock = 0;
  10629. }
  10630. }
  10631. /* lock while cert is reloading */
  10632. while (*p_reload_lock) {
  10633. sleep(1);
  10634. }
  10635. return 1;
  10636. }
  10637. #ifdef OPENSSL_API_1_1
  10638. #else
  10639. static pthread_mutex_t *ssl_mutexes;
  10640. #endif /* OPENSSL_API_1_1 */
  10641. static int
  10642. sslize(struct mg_connection *conn,
  10643. SSL_CTX *s,
  10644. int (*func)(SSL *),
  10645. volatile int *stop_server)
  10646. {
  10647. int ret, err;
  10648. int short_trust;
  10649. unsigned i;
  10650. if (!conn) {
  10651. return 0;
  10652. }
  10653. short_trust =
  10654. (conn->ctx->config[SSL_SHORT_TRUST] != NULL)
  10655. && (mg_strcasecmp(conn->ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  10656. if (short_trust) {
  10657. int trust_ret = refresh_trust(conn);
  10658. if (!trust_ret) {
  10659. return trust_ret;
  10660. }
  10661. }
  10662. conn->ssl = SSL_new(s);
  10663. if (conn->ssl == NULL) {
  10664. return 0;
  10665. }
  10666. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  10667. if (ret != 1) {
  10668. err = SSL_get_error(conn->ssl, ret);
  10669. (void)err; /* TODO: set some error message */
  10670. SSL_free(conn->ssl);
  10671. conn->ssl = NULL;
  10672. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  10673. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  10674. #ifndef OPENSSL_API_1_1
  10675. ERR_remove_state(0);
  10676. #endif
  10677. return 0;
  10678. }
  10679. /* SSL functions may fail and require to be called again:
  10680. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  10681. * Here "func" could be SSL_connect or SSL_accept. */
  10682. for (i = 16; i <= 1024; i *= 2) {
  10683. ret = func(conn->ssl);
  10684. if (ret != 1) {
  10685. err = SSL_get_error(conn->ssl, ret);
  10686. if ((err == SSL_ERROR_WANT_CONNECT)
  10687. || (err == SSL_ERROR_WANT_ACCEPT)
  10688. || (err == SSL_ERROR_WANT_READ)
  10689. || (err == SSL_ERROR_WANT_WRITE)) {
  10690. /* Need to retry the function call "later".
  10691. * See https://linux.die.net/man/3/ssl_get_error
  10692. * This is typical for non-blocking sockets. */
  10693. if (*stop_server) {
  10694. /* Don't wait if the server is going to be stopped. */
  10695. break;
  10696. }
  10697. mg_sleep(i);
  10698. } else if (err == SSL_ERROR_SYSCALL) {
  10699. /* This is an IO error. Look at errno. */
  10700. err = errno;
  10701. /* TODO: set some error message */
  10702. break;
  10703. } else {
  10704. /* This is an SSL specific error */
  10705. /* TODO: set some error message */
  10706. break;
  10707. }
  10708. } else {
  10709. /* success */
  10710. break;
  10711. }
  10712. }
  10713. if (ret != 1) {
  10714. SSL_free(conn->ssl);
  10715. conn->ssl = NULL;
  10716. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  10717. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  10718. #ifndef OPENSSL_API_1_1
  10719. ERR_remove_state(0);
  10720. #endif
  10721. return 0;
  10722. }
  10723. return 1;
  10724. }
  10725. /* Return OpenSSL error message (from CRYPTO lib) */
  10726. static const char *
  10727. ssl_error(void)
  10728. {
  10729. unsigned long err;
  10730. err = ERR_get_error();
  10731. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  10732. }
  10733. static int
  10734. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  10735. {
  10736. int i;
  10737. const char hexdigit[] = "0123456789abcdef";
  10738. if (memlen <= 0 || buflen <= 0) {
  10739. return 0;
  10740. }
  10741. if (buflen < (3 * memlen)) {
  10742. return 0;
  10743. }
  10744. for (i = 0; i < memlen; i++) {
  10745. if (i > 0) {
  10746. buf[3 * i - 1] = ' ';
  10747. }
  10748. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  10749. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  10750. }
  10751. buf[3 * memlen - 1] = 0;
  10752. return 1;
  10753. }
  10754. static void
  10755. ssl_get_client_cert_info(struct mg_connection *conn)
  10756. {
  10757. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  10758. if (cert) {
  10759. char str_subject[1024];
  10760. char str_issuer[1024];
  10761. char str_finger[1024];
  10762. unsigned char buf[256];
  10763. char *str_serial = NULL;
  10764. unsigned int ulen;
  10765. int ilen;
  10766. unsigned char *tmp_buf;
  10767. unsigned char *tmp_p;
  10768. /* Handle to algorithm used for fingerprint */
  10769. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  10770. /* Get Subject and issuer */
  10771. X509_NAME *subj = X509_get_subject_name(cert);
  10772. X509_NAME *iss = X509_get_issuer_name(cert);
  10773. /* Get serial number */
  10774. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  10775. /* Translate serial number to a hex string */
  10776. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  10777. str_serial = BN_bn2hex(serial_bn);
  10778. BN_free(serial_bn);
  10779. /* Translate subject and issuer to a string */
  10780. (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
  10781. (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
  10782. /* Calculate SHA1 fingerprint and store as a hex string */
  10783. ulen = 0;
  10784. /* ASN1_digest is deprecated. Do the calculation manually,
  10785. * using EVP_Digest. */
  10786. ilen = i2d_X509((void *)cert, NULL);
  10787. tmp_buf =
  10788. (ilen > 0) ? (unsigned char *)mg_malloc((unsigned)ilen + 1) : NULL;
  10789. if (tmp_buf) {
  10790. tmp_p = tmp_buf;
  10791. (void)i2d_X509((void *)cert, &tmp_p);
  10792. if (!EVP_Digest(
  10793. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  10794. ulen = 0;
  10795. }
  10796. mg_free(tmp_buf);
  10797. }
  10798. if (!hexdump2string(
  10799. buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
  10800. *str_finger = 0;
  10801. }
  10802. conn->request_info.client_cert =
  10803. (struct client_cert *)mg_malloc(sizeof(struct client_cert));
  10804. if (conn->request_info.client_cert) {
  10805. conn->request_info.client_cert->subject = mg_strdup(str_subject);
  10806. conn->request_info.client_cert->issuer = mg_strdup(str_issuer);
  10807. conn->request_info.client_cert->serial = mg_strdup(str_serial);
  10808. conn->request_info.client_cert->finger = mg_strdup(str_finger);
  10809. } else {
  10810. /* TODO: write some OOM message */
  10811. }
  10812. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  10813. * see https://linux.die.net/man/3/bn_bn2hex */
  10814. OPENSSL_free(str_serial);
  10815. /* Free certificate memory */
  10816. X509_free(cert);
  10817. }
  10818. }
  10819. #ifdef OPENSSL_API_1_1
  10820. #else
  10821. static void
  10822. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  10823. {
  10824. (void)line;
  10825. (void)file;
  10826. if (mode & 1) {
  10827. /* 1 is CRYPTO_LOCK */
  10828. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  10829. } else {
  10830. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  10831. }
  10832. }
  10833. #endif /* OPENSSL_API_1_1 */
  10834. #if !defined(NO_SSL_DL)
  10835. static void *
  10836. load_dll(char *ebuf, size_t ebuf_len, const char *dll_name, struct ssl_func *sw)
  10837. {
  10838. union {
  10839. void *p;
  10840. void (*fp)(void);
  10841. } u;
  10842. void *dll_handle;
  10843. struct ssl_func *fp;
  10844. int ok;
  10845. int truncated = 0;
  10846. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  10847. mg_snprintf(NULL,
  10848. NULL, /* No truncation check for ebuf */
  10849. ebuf,
  10850. ebuf_len,
  10851. "%s: cannot load %s",
  10852. __func__,
  10853. dll_name);
  10854. return NULL;
  10855. }
  10856. ok = 1;
  10857. for (fp = sw; fp->name != NULL; fp++) {
  10858. #ifdef _WIN32
  10859. /* GetProcAddress() returns pointer to function */
  10860. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  10861. #else
  10862. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  10863. * pointers to function pointers. We need to use a union to make a
  10864. * cast. */
  10865. u.p = dlsym(dll_handle, fp->name);
  10866. #endif /* _WIN32 */
  10867. if (u.fp == NULL) {
  10868. if (ok) {
  10869. mg_snprintf(NULL,
  10870. &truncated,
  10871. ebuf,
  10872. ebuf_len,
  10873. "%s: %s: cannot find %s",
  10874. __func__,
  10875. dll_name,
  10876. fp->name);
  10877. ok = 0;
  10878. } else {
  10879. size_t cur_len = strlen(ebuf);
  10880. if (!truncated) {
  10881. mg_snprintf(NULL,
  10882. &truncated,
  10883. ebuf + cur_len,
  10884. ebuf_len - cur_len - 3,
  10885. ", %s",
  10886. fp->name);
  10887. if (truncated) {
  10888. /* If truncated, add "..." */
  10889. strcat(ebuf, "...");
  10890. }
  10891. }
  10892. }
  10893. /* Debug:
  10894. * printf("Missing function: %s\n", fp->name); */
  10895. } else {
  10896. fp->ptr = u.fp;
  10897. }
  10898. }
  10899. if (!ok) {
  10900. (void)dlclose(dll_handle);
  10901. return NULL;
  10902. }
  10903. return dll_handle;
  10904. }
  10905. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  10906. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  10907. #endif /* NO_SSL_DL */
  10908. #if defined(SSL_ALREADY_INITIALIZED)
  10909. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  10910. #else
  10911. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  10912. #endif
  10913. static int
  10914. initialize_ssl(char *ebuf, size_t ebuf_len)
  10915. {
  10916. #ifdef OPENSSL_API_1_1
  10917. if (ebuf_len > 0) {
  10918. ebuf[0] = 0;
  10919. }
  10920. #if !defined(NO_SSL_DL)
  10921. if (!cryptolib_dll_handle) {
  10922. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  10923. if (!cryptolib_dll_handle) {
  10924. return 0;
  10925. }
  10926. }
  10927. #endif /* NO_SSL_DL */
  10928. if (mg_atomic_inc(&cryptolib_users) > 1) {
  10929. return 1;
  10930. }
  10931. #else /* not OPENSSL_API_1_1 */
  10932. int i;
  10933. size_t size;
  10934. if (ebuf_len > 0) {
  10935. ebuf[0] = 0;
  10936. }
  10937. #if !defined(NO_SSL_DL)
  10938. if (!cryptolib_dll_handle) {
  10939. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  10940. if (!cryptolib_dll_handle) {
  10941. return 0;
  10942. }
  10943. }
  10944. #endif /* NO_SSL_DL */
  10945. if (mg_atomic_inc(&cryptolib_users) > 1) {
  10946. return 1;
  10947. }
  10948. /* Initialize locking callbacks, needed for thread safety.
  10949. * http://www.openssl.org/support/faq.html#PROG1
  10950. */
  10951. i = CRYPTO_num_locks();
  10952. if (i < 0) {
  10953. i = 0;
  10954. }
  10955. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  10956. if (size == 0) {
  10957. ssl_mutexes = NULL;
  10958. } else if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  10959. mg_snprintf(NULL,
  10960. NULL, /* No truncation check for ebuf */
  10961. ebuf,
  10962. ebuf_len,
  10963. "%s: cannot allocate mutexes: %s",
  10964. __func__,
  10965. ssl_error());
  10966. return 0;
  10967. }
  10968. for (i = 0; i < CRYPTO_num_locks(); i++) {
  10969. pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr);
  10970. }
  10971. CRYPTO_set_locking_callback(&ssl_locking_callback);
  10972. CRYPTO_set_id_callback(&mg_current_thread_id);
  10973. #endif /* OPENSSL_API_1_1 */
  10974. return 1;
  10975. }
  10976. static int
  10977. ssl_use_pem_file(struct mg_context *ctx, const char *pem, const char *chain)
  10978. {
  10979. if (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0) {
  10980. mg_cry(fc(ctx),
  10981. "%s: cannot open certificate file %s: %s",
  10982. __func__,
  10983. pem,
  10984. ssl_error());
  10985. return 0;
  10986. }
  10987. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  10988. if (SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0) {
  10989. mg_cry(fc(ctx),
  10990. "%s: cannot open private key file %s: %s",
  10991. __func__,
  10992. pem,
  10993. ssl_error());
  10994. return 0;
  10995. }
  10996. if (SSL_CTX_check_private_key(ctx->ssl_ctx) == 0) {
  10997. mg_cry(fc(ctx),
  10998. "%s: certificate and private key do not match: %s",
  10999. __func__,
  11000. pem);
  11001. return 0;
  11002. }
  11003. /* In contrast to OpenSSL, wolfSSL does not support certificate
  11004. * chain files that contain private keys and certificates in
  11005. * SSL_CTX_use_certificate_chain_file.
  11006. * The CivetWeb-Server used pem-Files that contained both information.
  11007. * In order to make wolfSSL work, it is split in two files.
  11008. * One file that contains key and certificate used by the server and
  11009. * an optional chain file for the ssl stack.
  11010. */
  11011. if (chain) {
  11012. if (SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, chain) == 0) {
  11013. mg_cry(fc(ctx),
  11014. "%s: cannot use certificate chain file %s: %s",
  11015. __func__,
  11016. pem,
  11017. ssl_error());
  11018. return 0;
  11019. }
  11020. }
  11021. return 1;
  11022. }
  11023. #ifdef OPENSSL_API_1_1
  11024. static unsigned long
  11025. ssl_get_protocol(int version_id)
  11026. {
  11027. long unsigned ret = SSL_OP_ALL;
  11028. if (version_id > 0)
  11029. ret |= SSL_OP_NO_SSLv2;
  11030. if (version_id > 1)
  11031. ret |= SSL_OP_NO_SSLv3;
  11032. if (version_id > 2)
  11033. ret |= SSL_OP_NO_TLSv1;
  11034. if (version_id > 3)
  11035. ret |= SSL_OP_NO_TLSv1_1;
  11036. return ret;
  11037. }
  11038. #else
  11039. static long
  11040. ssl_get_protocol(int version_id)
  11041. {
  11042. long ret = SSL_OP_ALL;
  11043. if (version_id > 0)
  11044. ret |= SSL_OP_NO_SSLv2;
  11045. if (version_id > 1)
  11046. ret |= SSL_OP_NO_SSLv3;
  11047. if (version_id > 2)
  11048. ret |= SSL_OP_NO_TLSv1;
  11049. if (version_id > 3)
  11050. ret |= SSL_OP_NO_TLSv1_1;
  11051. return ret;
  11052. }
  11053. #endif /* OPENSSL_API_1_1 */
  11054. /* Dynamically load SSL library. Set up ctx->ssl_ctx pointer. */
  11055. static int
  11056. set_ssl_option(struct mg_context *ctx)
  11057. {
  11058. const char *pem;
  11059. const char *chain;
  11060. int callback_ret;
  11061. int should_verify_peer;
  11062. const char *ca_path;
  11063. const char *ca_file;
  11064. int use_default_verify_paths;
  11065. int verify_depth;
  11066. time_t now_rt = time(NULL);
  11067. struct timespec now_mt;
  11068. md5_byte_t ssl_context_id[16];
  11069. md5_state_t md5state;
  11070. int protocol_ver;
  11071. char ebuf[128];
  11072. /* If PEM file is not specified and the init_ssl callback
  11073. * is not specified, skip SSL initialization. */
  11074. if (!ctx) {
  11075. return 0;
  11076. }
  11077. if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL
  11078. && ctx->callbacks.init_ssl == NULL) {
  11079. return 1;
  11080. }
  11081. chain = ctx->config[SSL_CERTIFICATE_CHAIN];
  11082. if (chain == NULL) {
  11083. chain = pem;
  11084. }
  11085. if (*chain == 0) {
  11086. chain = NULL;
  11087. }
  11088. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  11089. mg_cry(fc(ctx), "%s", ebuf);
  11090. return 0;
  11091. }
  11092. #if !defined(NO_SSL_DL)
  11093. if (!ssllib_dll_handle) {
  11094. ssllib_dll_handle = load_dll(ebuf, sizeof(ebuf), SSL_LIB, ssl_sw);
  11095. if (!ssllib_dll_handle) {
  11096. mg_cry(fc(ctx), "%s", ebuf);
  11097. return 0;
  11098. }
  11099. }
  11100. #endif /* NO_SSL_DL */
  11101. #ifdef OPENSSL_API_1_1
  11102. /* Initialize SSL library */
  11103. OPENSSL_init_ssl(0, NULL);
  11104. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  11105. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  11106. NULL);
  11107. if ((ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  11108. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  11109. return 0;
  11110. }
  11111. #else
  11112. /* Initialize SSL library */
  11113. SSL_library_init();
  11114. SSL_load_error_strings();
  11115. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  11116. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  11117. return 0;
  11118. }
  11119. #endif /* OPENSSL_API_1_1 */
  11120. SSL_CTX_clear_options(ctx->ssl_ctx,
  11121. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  11122. | SSL_OP_NO_TLSv1_1);
  11123. protocol_ver = atoi(ctx->config[SSL_PROTOCOL_VERSION]);
  11124. SSL_CTX_set_options(ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  11125. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  11126. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  11127. #if !defined(NO_SSL_DL)
  11128. SSL_CTX_set_ecdh_auto(ctx->ssl_ctx, 1);
  11129. #endif /* NO_SSL_DL */
  11130. /* If a callback has been specified, call it. */
  11131. callback_ret =
  11132. (ctx->callbacks.init_ssl == NULL)
  11133. ? 0
  11134. : (ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data));
  11135. /* If callback returns 0, civetweb sets up the SSL certificate.
  11136. * If it returns 1, civetweb assumes the calback already did this.
  11137. * If it returns -1, initializing ssl fails. */
  11138. if (callback_ret < 0) {
  11139. mg_cry(fc(ctx), "SSL callback returned error: %i", callback_ret);
  11140. return 0;
  11141. }
  11142. if (callback_ret > 0) {
  11143. if (pem != NULL) {
  11144. (void)SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
  11145. }
  11146. return 1;
  11147. }
  11148. /* Use some UID as session context ID. */
  11149. md5_init(&md5state);
  11150. md5_append(&md5state, (const md5_byte_t *)&now_rt, sizeof(now_rt));
  11151. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  11152. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  11153. md5_append(&md5state,
  11154. (const md5_byte_t *)ctx->config[LISTENING_PORTS],
  11155. strlen(ctx->config[LISTENING_PORTS]));
  11156. md5_append(&md5state, (const md5_byte_t *)ctx, sizeof(*ctx));
  11157. md5_finish(&md5state, ssl_context_id);
  11158. SSL_CTX_set_session_id_context(ctx->ssl_ctx,
  11159. (const unsigned char *)&ssl_context_id,
  11160. sizeof(ssl_context_id));
  11161. if (pem != NULL) {
  11162. if (!ssl_use_pem_file(ctx, pem, chain)) {
  11163. return 0;
  11164. }
  11165. }
  11166. should_verify_peer =
  11167. (ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  11168. && (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0);
  11169. use_default_verify_paths =
  11170. (ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  11171. && (mg_strcasecmp(ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes") == 0);
  11172. if (should_verify_peer) {
  11173. ca_path = ctx->config[SSL_CA_PATH];
  11174. ca_file = ctx->config[SSL_CA_FILE];
  11175. if (SSL_CTX_load_verify_locations(ctx->ssl_ctx, ca_file, ca_path)
  11176. != 1) {
  11177. mg_cry(fc(ctx),
  11178. "SSL_CTX_load_verify_locations error: %s "
  11179. "ssl_verify_peer requires setting "
  11180. "either ssl_ca_path or ssl_ca_file. Is any of them "
  11181. "present in "
  11182. "the .conf file?",
  11183. ssl_error());
  11184. return 0;
  11185. }
  11186. SSL_CTX_set_verify(ctx->ssl_ctx,
  11187. SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  11188. NULL);
  11189. if (use_default_verify_paths
  11190. && SSL_CTX_set_default_verify_paths(ctx->ssl_ctx) != 1) {
  11191. mg_cry(fc(ctx),
  11192. "SSL_CTX_set_default_verify_paths error: %s",
  11193. ssl_error());
  11194. return 0;
  11195. }
  11196. if (ctx->config[SSL_VERIFY_DEPTH]) {
  11197. verify_depth = atoi(ctx->config[SSL_VERIFY_DEPTH]);
  11198. SSL_CTX_set_verify_depth(ctx->ssl_ctx, verify_depth);
  11199. }
  11200. }
  11201. if (ctx->config[SSL_CIPHER_LIST] != NULL) {
  11202. if (SSL_CTX_set_cipher_list(ctx->ssl_ctx, ctx->config[SSL_CIPHER_LIST])
  11203. != 1) {
  11204. mg_cry(fc(ctx), "SSL_CTX_set_cipher_list error: %s", ssl_error());
  11205. }
  11206. }
  11207. return 1;
  11208. }
  11209. static void
  11210. uninitialize_ssl(void)
  11211. {
  11212. #ifdef OPENSSL_API_1_1
  11213. if (mg_atomic_dec(&cryptolib_users) == 0) {
  11214. /* Shutdown according to
  11215. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  11216. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  11217. */
  11218. CONF_modules_unload(1);
  11219. #else
  11220. int i;
  11221. if (mg_atomic_dec(&cryptolib_users) == 0) {
  11222. /* Shutdown according to
  11223. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  11224. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  11225. */
  11226. CRYPTO_set_locking_callback(NULL);
  11227. CRYPTO_set_id_callback(NULL);
  11228. ENGINE_cleanup();
  11229. CONF_modules_unload(1);
  11230. ERR_free_strings();
  11231. EVP_cleanup();
  11232. CRYPTO_cleanup_all_ex_data();
  11233. ERR_remove_state(0);
  11234. for (i = 0; i < CRYPTO_num_locks(); i++) {
  11235. pthread_mutex_destroy(&ssl_mutexes[i]);
  11236. }
  11237. mg_free(ssl_mutexes);
  11238. ssl_mutexes = NULL;
  11239. #endif /* OPENSSL_API_1_1 */
  11240. }
  11241. }
  11242. #endif /* !NO_SSL */
  11243. static int
  11244. set_gpass_option(struct mg_context *ctx)
  11245. {
  11246. if (ctx) {
  11247. struct mg_file file = STRUCT_FILE_INITIALIZER;
  11248. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  11249. if (path != NULL && !mg_stat(fc(ctx), path, &file.stat)) {
  11250. mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  11251. return 0;
  11252. }
  11253. return 1;
  11254. }
  11255. return 0;
  11256. }
  11257. static int
  11258. set_acl_option(struct mg_context *ctx)
  11259. {
  11260. return check_acl(ctx, (uint32_t)0x7f000001UL) != -1;
  11261. }
  11262. static void
  11263. reset_per_request_attributes(struct mg_connection *conn)
  11264. {
  11265. if (!conn) {
  11266. return;
  11267. }
  11268. conn->path_info = NULL;
  11269. conn->num_bytes_sent = conn->consumed_content = 0;
  11270. conn->status_code = -1;
  11271. conn->is_chunked = 0;
  11272. conn->must_close = conn->request_len = conn->throttle = 0;
  11273. conn->request_info.content_length = -1;
  11274. conn->request_info.remote_user = NULL;
  11275. conn->request_info.request_method = NULL;
  11276. conn->request_info.request_uri = NULL;
  11277. conn->request_info.local_uri = NULL;
  11278. #if defined(MG_LEGACY_INTERFACE)
  11279. conn->request_info.uri = NULL; /* TODO: cleanup uri,
  11280. * local_uri and request_uri */
  11281. #endif
  11282. conn->request_info.http_version = NULL;
  11283. conn->request_info.num_headers = 0;
  11284. conn->data_len = 0;
  11285. conn->chunk_remainder = 0;
  11286. }
  11287. #if 0
  11288. /* Note: set_sock_timeout is not required for non-blocking sockets.
  11289. * Leave this function here (commented out) for reference until
  11290. * CivetWeb 1.9 is tested, and the tests confirme this function is
  11291. * no longer required.
  11292. */
  11293. static int
  11294. set_sock_timeout(SOCKET sock, int milliseconds)
  11295. {
  11296. int r0 = 0, r1, r2;
  11297. #ifdef _WIN32
  11298. /* Windows specific */
  11299. DWORD tv = (DWORD)milliseconds;
  11300. #else
  11301. /* Linux, ... (not Windows) */
  11302. struct timeval tv;
  11303. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  11304. * max. time waiting for the acknowledged of TCP data before the connection
  11305. * will be forcefully closed and ETIMEDOUT is returned to the application.
  11306. * If this option is not set, the default timeout of 20-30 minutes is used.
  11307. */
  11308. /* #define TCP_USER_TIMEOUT (18) */
  11309. #if defined(TCP_USER_TIMEOUT)
  11310. unsigned int uto = (unsigned int)milliseconds;
  11311. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  11312. #endif
  11313. memset(&tv, 0, sizeof(tv));
  11314. tv.tv_sec = milliseconds / 1000;
  11315. tv.tv_usec = (milliseconds * 1000) % 1000000;
  11316. #endif /* _WIN32 */
  11317. r1 = setsockopt(
  11318. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  11319. r2 = setsockopt(
  11320. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  11321. return r0 || r1 || r2;
  11322. }
  11323. #endif
  11324. static int
  11325. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  11326. {
  11327. if (setsockopt(sock,
  11328. IPPROTO_TCP,
  11329. TCP_NODELAY,
  11330. (SOCK_OPT_TYPE)&nodelay_on,
  11331. sizeof(nodelay_on)) != 0) {
  11332. /* Error */
  11333. return 1;
  11334. }
  11335. /* OK */
  11336. return 0;
  11337. }
  11338. static void
  11339. close_socket_gracefully(struct mg_connection *conn)
  11340. {
  11341. #if defined(_WIN32)
  11342. char buf[MG_BUF_LEN];
  11343. int n;
  11344. #endif
  11345. struct linger linger;
  11346. int error_code = 0;
  11347. int linger_timeout = -2;
  11348. socklen_t opt_len = sizeof(error_code);
  11349. if (!conn) {
  11350. return;
  11351. }
  11352. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  11353. * "Note that enabling a nonzero timeout on a nonblocking socket
  11354. * is not recommended.", so set it to blocking now */
  11355. set_blocking_mode(conn->client.sock, 1);
  11356. /* Send FIN to the client */
  11357. shutdown(conn->client.sock, SHUTDOWN_WR);
  11358. #if defined(_WIN32)
  11359. /* Read and discard pending incoming data. If we do not do that and
  11360. * close
  11361. * the socket, the data in the send buffer may be discarded. This
  11362. * behaviour is seen on Windows, when client keeps sending data
  11363. * when server decides to close the connection; then when client
  11364. * does recv() it gets no data back. */
  11365. do {
  11366. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  11367. } while (n > 0);
  11368. #endif
  11369. if (conn->ctx->config[LINGER_TIMEOUT]) {
  11370. linger_timeout = atoi(conn->ctx->config[LINGER_TIMEOUT]);
  11371. }
  11372. /* Set linger option according to configuration */
  11373. if (linger_timeout >= 0) {
  11374. /* Set linger option to avoid socket hanging out after close. This
  11375. * prevent ephemeral port exhaust problem under high QPS. */
  11376. linger.l_onoff = 1;
  11377. #if defined(_MSC_VER)
  11378. #pragma warning(push)
  11379. #pragma warning(disable : 4244)
  11380. #endif
  11381. linger.l_linger = (linger_timeout + 999) / 1000;
  11382. #if defined(_MSC_VER)
  11383. #pragma warning(pop)
  11384. #endif
  11385. } else {
  11386. linger.l_onoff = 0;
  11387. linger.l_linger = 0;
  11388. }
  11389. if (linger_timeout < -1) {
  11390. /* Default: don't configure any linger */
  11391. } else if (getsockopt(conn->client.sock,
  11392. SOL_SOCKET,
  11393. SO_ERROR,
  11394. (char *)&error_code,
  11395. &opt_len) != 0) {
  11396. /* Cannot determine if socket is already closed. This should
  11397. * not occur and never did in a test. Log an error message
  11398. * and continue. */
  11399. mg_cry(conn,
  11400. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  11401. __func__,
  11402. strerror(ERRNO));
  11403. } else if (error_code == ECONNRESET) {
  11404. /* Socket already closed by client/peer, close socket without linger */
  11405. } else {
  11406. /* Set linger timeout */
  11407. if (setsockopt(conn->client.sock,
  11408. SOL_SOCKET,
  11409. SO_LINGER,
  11410. (char *)&linger,
  11411. sizeof(linger)) != 0) {
  11412. mg_cry(conn,
  11413. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  11414. __func__,
  11415. linger.l_onoff,
  11416. linger.l_linger,
  11417. strerror(ERRNO));
  11418. }
  11419. }
  11420. /* Now we know that our FIN is ACK-ed, safe to close */
  11421. closesocket(conn->client.sock);
  11422. conn->client.sock = INVALID_SOCKET;
  11423. }
  11424. static void
  11425. close_connection(struct mg_connection *conn)
  11426. {
  11427. if (!conn || !conn->ctx) {
  11428. return;
  11429. }
  11430. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  11431. if (conn->lua_websocket_state) {
  11432. lua_websocket_close(conn, conn->lua_websocket_state);
  11433. conn->lua_websocket_state = NULL;
  11434. }
  11435. #endif
  11436. /* call the connection_close callback if assigned */
  11437. if ((conn->ctx->callbacks.connection_close != NULL)
  11438. && (conn->ctx->context_type == 1)) {
  11439. conn->ctx->callbacks.connection_close(conn);
  11440. }
  11441. mg_lock_connection(conn);
  11442. conn->must_close = 1;
  11443. #ifndef NO_SSL
  11444. if (conn->ssl != NULL) {
  11445. /* Run SSL_shutdown twice to ensure completly close SSL connection
  11446. */
  11447. SSL_shutdown(conn->ssl);
  11448. SSL_free(conn->ssl);
  11449. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  11450. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  11451. #ifndef OPENSSL_API_1_1
  11452. ERR_remove_state(0);
  11453. #endif
  11454. conn->ssl = NULL;
  11455. }
  11456. #endif
  11457. if (conn->client.sock != INVALID_SOCKET) {
  11458. close_socket_gracefully(conn);
  11459. conn->client.sock = INVALID_SOCKET;
  11460. }
  11461. mg_unlock_connection(conn);
  11462. }
  11463. void
  11464. mg_close_connection(struct mg_connection *conn)
  11465. {
  11466. struct mg_context *client_ctx = NULL;
  11467. if (conn == NULL) {
  11468. return;
  11469. }
  11470. #if defined(USE_WEBSOCKET)
  11471. if (conn->ctx->context_type == 2) {
  11472. unsigned int i;
  11473. /* ws/wss client */
  11474. client_ctx = conn->ctx;
  11475. /* client context: loops must end */
  11476. conn->ctx->stop_flag = 1;
  11477. /* We need to get the client thread out of the select/recv call here. */
  11478. /* Since we use a sleep quantum of some seconds to check for recv
  11479. * timeouts, we will just wait a few seconds in mg_join_thread. */
  11480. /* join worker thread */
  11481. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  11482. if (client_ctx->worker_threadids[i] != 0) {
  11483. mg_join_thread(client_ctx->worker_threadids[i]);
  11484. }
  11485. }
  11486. }
  11487. #else
  11488. (void)client_ctx;
  11489. #endif
  11490. close_connection(conn);
  11491. #ifndef NO_SSL
  11492. if (conn->client_ssl_ctx != NULL) {
  11493. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  11494. }
  11495. #endif
  11496. if (client_ctx != NULL) {
  11497. /* free context */
  11498. mg_free(client_ctx->worker_threadids);
  11499. mg_free(client_ctx);
  11500. (void)pthread_mutex_destroy(&conn->mutex);
  11501. mg_free(conn);
  11502. }
  11503. }
  11504. static struct mg_connection *
  11505. mg_connect_client_impl(const struct mg_client_options *client_options,
  11506. int use_ssl,
  11507. char *ebuf,
  11508. size_t ebuf_len)
  11509. {
  11510. static struct mg_context fake_ctx;
  11511. struct mg_connection *conn = NULL;
  11512. SOCKET sock;
  11513. union usa sa;
  11514. if (!connect_socket(&fake_ctx,
  11515. client_options->host,
  11516. client_options->port,
  11517. use_ssl,
  11518. ebuf,
  11519. ebuf_len,
  11520. &sock,
  11521. &sa)) {
  11522. ;
  11523. } else if ((conn = (struct mg_connection *)
  11524. mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) {
  11525. mg_snprintf(NULL,
  11526. NULL, /* No truncation check for ebuf */
  11527. ebuf,
  11528. ebuf_len,
  11529. "calloc(): %s",
  11530. strerror(ERRNO));
  11531. closesocket(sock);
  11532. #ifndef NO_SSL
  11533. #ifdef OPENSSL_API_1_1
  11534. } else if (use_ssl
  11535. && (conn->client_ssl_ctx = SSL_CTX_new(TLS_client_method()))
  11536. == NULL) {
  11537. mg_snprintf(NULL,
  11538. NULL, /* No truncation check for ebuf */
  11539. ebuf,
  11540. ebuf_len,
  11541. "SSL_CTX_new error");
  11542. closesocket(sock);
  11543. mg_free(conn);
  11544. conn = NULL;
  11545. #else
  11546. } else if (use_ssl
  11547. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  11548. == NULL) {
  11549. mg_snprintf(NULL,
  11550. NULL, /* No truncation check for ebuf */
  11551. ebuf,
  11552. ebuf_len,
  11553. "SSL_CTX_new error");
  11554. closesocket(sock);
  11555. mg_free(conn);
  11556. conn = NULL;
  11557. #endif /* OPENSSL_API_1_1 */
  11558. #endif /* NO_SSL */
  11559. } else {
  11560. #ifdef USE_IPV6
  11561. socklen_t len = (sa.sa.sa_family == AF_INET)
  11562. ? sizeof(conn->client.rsa.sin)
  11563. : sizeof(conn->client.rsa.sin6);
  11564. struct sockaddr *psa =
  11565. (sa.sa.sa_family == AF_INET)
  11566. ? (struct sockaddr *)&(conn->client.rsa.sin)
  11567. : (struct sockaddr *)&(conn->client.rsa.sin6);
  11568. #else
  11569. socklen_t len = sizeof(conn->client.rsa.sin);
  11570. struct sockaddr *psa = (struct sockaddr *)&(conn->client.rsa.sin);
  11571. #endif
  11572. conn->buf_size = MAX_REQUEST_SIZE;
  11573. conn->buf = (char *)(conn + 1);
  11574. conn->ctx = &fake_ctx;
  11575. conn->client.sock = sock;
  11576. conn->client.lsa = sa;
  11577. if (getsockname(sock, psa, &len) != 0) {
  11578. mg_cry(conn,
  11579. "%s: getsockname() failed: %s",
  11580. __func__,
  11581. strerror(ERRNO));
  11582. }
  11583. conn->client.is_ssl = use_ssl ? 1 : 0;
  11584. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  11585. #ifndef NO_SSL
  11586. if (use_ssl) {
  11587. fake_ctx.ssl_ctx = conn->client_ssl_ctx;
  11588. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  11589. * SSL_CTX_set_verify call is needed to switch off server
  11590. * certificate checking, which is off by default in OpenSSL and
  11591. * on in yaSSL. */
  11592. /* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  11593. * SSL_VERIFY_PEER, verify_ssl_server); */
  11594. if (client_options->client_cert) {
  11595. if (!ssl_use_pem_file(&fake_ctx,
  11596. client_options->client_cert,
  11597. NULL)) {
  11598. mg_snprintf(NULL,
  11599. NULL, /* No truncation check for ebuf */
  11600. ebuf,
  11601. ebuf_len,
  11602. "Can not use SSL client certificate");
  11603. SSL_CTX_free(conn->client_ssl_ctx);
  11604. closesocket(sock);
  11605. mg_free(conn);
  11606. conn = NULL;
  11607. }
  11608. }
  11609. if (client_options->server_cert) {
  11610. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  11611. client_options->server_cert,
  11612. NULL);
  11613. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  11614. } else {
  11615. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  11616. }
  11617. if (!sslize(conn,
  11618. conn->client_ssl_ctx,
  11619. SSL_connect,
  11620. &(conn->ctx->stop_flag))) {
  11621. mg_snprintf(NULL,
  11622. NULL, /* No truncation check for ebuf */
  11623. ebuf,
  11624. ebuf_len,
  11625. "SSL connection error");
  11626. SSL_CTX_free(conn->client_ssl_ctx);
  11627. closesocket(sock);
  11628. mg_free(conn);
  11629. conn = NULL;
  11630. }
  11631. }
  11632. #endif
  11633. }
  11634. if (conn) {
  11635. set_blocking_mode(sock, 0);
  11636. }
  11637. return conn;
  11638. }
  11639. CIVETWEB_API struct mg_connection *
  11640. mg_connect_client_secure(const struct mg_client_options *client_options,
  11641. char *error_buffer,
  11642. size_t error_buffer_size)
  11643. {
  11644. return mg_connect_client_impl(client_options,
  11645. 1,
  11646. error_buffer,
  11647. error_buffer_size);
  11648. }
  11649. struct mg_connection *
  11650. mg_connect_client(const char *host,
  11651. int port,
  11652. int use_ssl,
  11653. char *error_buffer,
  11654. size_t error_buffer_size)
  11655. {
  11656. struct mg_client_options opts;
  11657. memset(&opts, 0, sizeof(opts));
  11658. opts.host = host;
  11659. opts.port = port;
  11660. return mg_connect_client_impl(&opts,
  11661. use_ssl,
  11662. error_buffer,
  11663. error_buffer_size);
  11664. }
  11665. static const struct {
  11666. const char *proto;
  11667. size_t proto_len;
  11668. unsigned default_port;
  11669. } abs_uri_protocols[] = {{"http://", 7, 80},
  11670. {"https://", 8, 443},
  11671. {"ws://", 5, 80},
  11672. {"wss://", 6, 443},
  11673. {NULL, 0, 0}};
  11674. /* Check if the uri is valid.
  11675. * return 0 for invalid uri,
  11676. * return 1 for *,
  11677. * return 2 for relative uri,
  11678. * return 3 for absolute uri without port,
  11679. * return 4 for absolute uri with port */
  11680. static int
  11681. get_uri_type(const char *uri)
  11682. {
  11683. int i;
  11684. const char *hostend, *portbegin;
  11685. char *portend;
  11686. unsigned long port;
  11687. /* According to the HTTP standard
  11688. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  11689. * URI can be an asterisk (*) or should start with slash (relative uri),
  11690. * or it should start with the protocol (absolute uri). */
  11691. if (uri[0] == '*' && uri[1] == '\0') {
  11692. /* asterisk */
  11693. return 1;
  11694. }
  11695. /* Valid URIs according to RFC 3986
  11696. * (https://www.ietf.org/rfc/rfc3986.txt)
  11697. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  11698. * and unreserved characters A-Z a-z 0-9 and -._~
  11699. * and % encoded symbols.
  11700. */
  11701. for (i = 0; uri[i] != 0; i++) {
  11702. if (uri[i] < 33) {
  11703. /* control characters and spaces are invalid */
  11704. return 0;
  11705. }
  11706. if (uri[i] > 126) {
  11707. /* non-ascii characters must be % encoded */
  11708. return 0;
  11709. } else {
  11710. switch (uri[i]) {
  11711. case '"': /* 34 */
  11712. case '<': /* 60 */
  11713. case '>': /* 62 */
  11714. case '\\': /* 92 */
  11715. case '^': /* 94 */
  11716. case '`': /* 96 */
  11717. case '{': /* 123 */
  11718. case '|': /* 124 */
  11719. case '}': /* 125 */
  11720. return 0;
  11721. default:
  11722. /* character is ok */
  11723. break;
  11724. }
  11725. }
  11726. }
  11727. /* A relative uri starts with a / character */
  11728. if (uri[0] == '/') {
  11729. /* relative uri */
  11730. return 2;
  11731. }
  11732. /* It could be an absolute uri: */
  11733. /* This function only checks if the uri is valid, not if it is
  11734. * addressing the current server. So civetweb can also be used
  11735. * as a proxy server. */
  11736. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  11737. if (mg_strncasecmp(uri,
  11738. abs_uri_protocols[i].proto,
  11739. abs_uri_protocols[i].proto_len) == 0) {
  11740. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  11741. if (!hostend) {
  11742. return 0;
  11743. }
  11744. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  11745. if (!portbegin) {
  11746. return 3;
  11747. }
  11748. port = strtoul(portbegin + 1, &portend, 10);
  11749. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  11750. return 0;
  11751. }
  11752. return 4;
  11753. }
  11754. }
  11755. return 0;
  11756. }
  11757. /* Return NULL or the relative uri at the current server */
  11758. static const char *
  11759. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  11760. {
  11761. const char *server_domain;
  11762. size_t server_domain_len;
  11763. size_t request_domain_len = 0;
  11764. unsigned long port = 0;
  11765. int i, auth_domain_check_enabled;
  11766. const char *hostbegin = NULL;
  11767. const char *hostend = NULL;
  11768. const char *portbegin;
  11769. char *portend;
  11770. auth_domain_check_enabled =
  11771. !strcmp(conn->ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  11772. if (!auth_domain_check_enabled) {
  11773. return 0;
  11774. }
  11775. server_domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  11776. if (!server_domain) {
  11777. return 0;
  11778. }
  11779. server_domain_len = strlen(server_domain);
  11780. if (!server_domain_len) {
  11781. return 0;
  11782. }
  11783. /* DNS is case insensitive, so use case insensitive string compare here
  11784. */
  11785. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  11786. if (mg_strncasecmp(uri,
  11787. abs_uri_protocols[i].proto,
  11788. abs_uri_protocols[i].proto_len) == 0) {
  11789. hostbegin = uri + abs_uri_protocols[i].proto_len;
  11790. hostend = strchr(hostbegin, '/');
  11791. if (!hostend) {
  11792. return 0;
  11793. }
  11794. portbegin = strchr(hostbegin, ':');
  11795. if ((!portbegin) || (portbegin > hostend)) {
  11796. port = abs_uri_protocols[i].default_port;
  11797. request_domain_len = (size_t)(hostend - hostbegin);
  11798. } else {
  11799. port = strtoul(portbegin + 1, &portend, 10);
  11800. if ((portend != hostend) || (port <= 0)
  11801. || !is_valid_port(port)) {
  11802. return 0;
  11803. }
  11804. request_domain_len = (size_t)(portbegin - hostbegin);
  11805. }
  11806. /* protocol found, port set */
  11807. break;
  11808. }
  11809. }
  11810. if (!port) {
  11811. /* port remains 0 if the protocol is not found */
  11812. return 0;
  11813. }
  11814. /* Check if the request is directed to a different server. */
  11815. /* First check if the port is the same (IPv4 and IPv6). */
  11816. #if defined(USE_IPV6)
  11817. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  11818. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  11819. /* Request is directed to a different port */
  11820. return 0;
  11821. }
  11822. } else
  11823. #endif
  11824. {
  11825. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  11826. /* Request is directed to a different port */
  11827. return 0;
  11828. }
  11829. }
  11830. /* Finally check if the server corresponds to the authentication
  11831. * domain of the server (the server domain).
  11832. * Allow full matches (like http://mydomain.com/path/file.ext), and
  11833. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  11834. * but do not allow substrings (like http://notmydomain.com/path/file.ext
  11835. * or http://mydomain.com.fake/path/file.ext).
  11836. */
  11837. if (auth_domain_check_enabled) {
  11838. if ((request_domain_len == server_domain_len)
  11839. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  11840. /* Request is directed to this server - full name match. */
  11841. } else {
  11842. if (request_domain_len < (server_domain_len + 2)) {
  11843. /* Request is directed to another server: The server name is
  11844. * longer
  11845. * than
  11846. * the request name. Drop this case here to avoid overflows in
  11847. * the
  11848. * following checks. */
  11849. return 0;
  11850. }
  11851. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  11852. /* Request is directed to another server: It could be a
  11853. * substring
  11854. * like notmyserver.com */
  11855. return 0;
  11856. }
  11857. if (0 != memcmp(server_domain,
  11858. hostbegin + request_domain_len - server_domain_len,
  11859. server_domain_len)) {
  11860. /* Request is directed to another server:
  11861. * The server name is different. */
  11862. return 0;
  11863. }
  11864. }
  11865. }
  11866. return hostend;
  11867. }
  11868. static int
  11869. getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  11870. {
  11871. const char *cl;
  11872. if (ebuf_len > 0) {
  11873. ebuf[0] = '\0';
  11874. }
  11875. *err = 0;
  11876. reset_per_request_attributes(conn);
  11877. if (!conn) {
  11878. mg_snprintf(conn,
  11879. NULL, /* No truncation check for ebuf */
  11880. ebuf,
  11881. ebuf_len,
  11882. "%s",
  11883. "Internal error");
  11884. *err = 500;
  11885. return 0;
  11886. }
  11887. /* Set the time the request was received. This value should be used for
  11888. * timeouts. */
  11889. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  11890. conn->request_len =
  11891. read_request(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  11892. /* assert(conn->request_len < 0 || conn->data_len >= conn->request_len);
  11893. */
  11894. if (conn->request_len >= 0 && conn->data_len < conn->request_len) {
  11895. mg_snprintf(conn,
  11896. NULL, /* No truncation check for ebuf */
  11897. ebuf,
  11898. ebuf_len,
  11899. "%s",
  11900. "Invalid request size");
  11901. *err = 500;
  11902. return 0;
  11903. }
  11904. if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
  11905. mg_snprintf(conn,
  11906. NULL, /* No truncation check for ebuf */
  11907. ebuf,
  11908. ebuf_len,
  11909. "%s",
  11910. "Request Too Large");
  11911. *err = 413;
  11912. return 0;
  11913. } else if (conn->request_len <= 0) {
  11914. if (conn->data_len > 0) {
  11915. mg_snprintf(conn,
  11916. NULL, /* No truncation check for ebuf */
  11917. ebuf,
  11918. ebuf_len,
  11919. "%s",
  11920. "Client sent malformed request");
  11921. *err = 400;
  11922. } else {
  11923. /* Server did not recv anything -> just close the connection */
  11924. conn->must_close = 1;
  11925. mg_snprintf(conn,
  11926. NULL, /* No truncation check for ebuf */
  11927. ebuf,
  11928. ebuf_len,
  11929. "%s",
  11930. "Client did not send a request");
  11931. *err = 0;
  11932. }
  11933. return 0;
  11934. } else if (parse_http_message(conn->buf,
  11935. conn->buf_size,
  11936. &conn->request_info) <= 0) {
  11937. mg_snprintf(conn,
  11938. NULL, /* No truncation check for ebuf */
  11939. ebuf,
  11940. ebuf_len,
  11941. "%s",
  11942. "Bad Request");
  11943. *err = 400;
  11944. return 0;
  11945. } else {
  11946. /* Message is a valid request or response */
  11947. if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) {
  11948. /* Request/response has content length set */
  11949. char *endptr = NULL;
  11950. conn->content_len = strtoll(cl, &endptr, 10);
  11951. if (endptr == cl) {
  11952. mg_snprintf(conn,
  11953. NULL, /* No truncation check for ebuf */
  11954. ebuf,
  11955. ebuf_len,
  11956. "%s",
  11957. "Bad Request");
  11958. *err = 411;
  11959. return 0;
  11960. }
  11961. /* Publish the content length back to the request info. */
  11962. conn->request_info.content_length = conn->content_len;
  11963. } else if ((cl = get_header(&conn->request_info, "Transfer-Encoding"))
  11964. != NULL
  11965. && !mg_strcasecmp(cl, "chunked")) {
  11966. conn->is_chunked = 1;
  11967. } else if (!mg_strcasecmp(conn->request_info.request_method, "POST")
  11968. || !mg_strcasecmp(conn->request_info.request_method,
  11969. "PUT")) {
  11970. /* POST or PUT request without content length set */
  11971. conn->content_len = -1;
  11972. } else if (!mg_strncasecmp(conn->request_info.request_method,
  11973. "HTTP/",
  11974. 5)) {
  11975. /* Response without content length set */
  11976. conn->content_len = -1;
  11977. } else {
  11978. /* Other request */
  11979. conn->content_len = 0;
  11980. }
  11981. }
  11982. return 1;
  11983. }
  11984. int
  11985. mg_get_response(struct mg_connection *conn,
  11986. char *ebuf,
  11987. size_t ebuf_len,
  11988. int timeout)
  11989. {
  11990. if (conn) {
  11991. /* Implementation of API function for HTTP clients */
  11992. int err, ret;
  11993. struct mg_context *octx = conn->ctx;
  11994. struct mg_context rctx = *(conn->ctx);
  11995. char txt[32]; /* will not overflow */
  11996. if (timeout >= 0) {
  11997. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  11998. rctx.config[REQUEST_TIMEOUT] = txt;
  11999. /* Not required for non-blocking sockets.
  12000. set_sock_timeout(conn->client.sock, timeout);
  12001. */
  12002. } else {
  12003. rctx.config[REQUEST_TIMEOUT] = NULL;
  12004. }
  12005. conn->ctx = &rctx;
  12006. ret = getreq(conn, ebuf, ebuf_len, &err);
  12007. conn->ctx = octx;
  12008. #if defined(MG_LEGACY_INTERFACE)
  12009. /* TODO: 1) uri is deprecated;
  12010. * 2) here, ri.uri is the http response code */
  12011. conn->request_info.uri = conn->request_info.request_uri;
  12012. #endif
  12013. conn->request_info.local_uri = conn->request_info.request_uri;
  12014. /* TODO (mid): Define proper return values - maybe return length?
  12015. * For the first test use <0 for error and >0 for OK */
  12016. return (ret == 0) ? -1 : +1;
  12017. }
  12018. return -1;
  12019. }
  12020. struct mg_connection *
  12021. mg_download(const char *host,
  12022. int port,
  12023. int use_ssl,
  12024. char *ebuf,
  12025. size_t ebuf_len,
  12026. const char *fmt,
  12027. ...)
  12028. {
  12029. struct mg_connection *conn;
  12030. va_list ap;
  12031. int i;
  12032. int reqerr;
  12033. va_start(ap, fmt);
  12034. ebuf[0] = '\0';
  12035. /* open a connection */
  12036. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  12037. if (conn != NULL) {
  12038. i = mg_vprintf(conn, fmt, ap);
  12039. if (i <= 0) {
  12040. mg_snprintf(conn,
  12041. NULL, /* No truncation check for ebuf */
  12042. ebuf,
  12043. ebuf_len,
  12044. "%s",
  12045. "Error sending request");
  12046. } else {
  12047. getreq(conn, ebuf, ebuf_len, &reqerr);
  12048. #if defined(MG_LEGACY_INTERFACE)
  12049. /* TODO: 1) uri is deprecated;
  12050. * 2) here, ri.uri is the http response code */
  12051. conn->request_info.uri = conn->request_info.request_uri;
  12052. #endif
  12053. conn->request_info.local_uri = conn->request_info.request_uri;
  12054. }
  12055. }
  12056. /* if an error occured, close the connection */
  12057. if (ebuf[0] != '\0' && conn != NULL) {
  12058. mg_close_connection(conn);
  12059. conn = NULL;
  12060. }
  12061. va_end(ap);
  12062. return conn;
  12063. }
  12064. struct websocket_client_thread_data {
  12065. struct mg_connection *conn;
  12066. mg_websocket_data_handler data_handler;
  12067. mg_websocket_close_handler close_handler;
  12068. void *callback_data;
  12069. };
  12070. #if defined(USE_WEBSOCKET)
  12071. #ifdef _WIN32
  12072. static unsigned __stdcall websocket_client_thread(void *data)
  12073. #else
  12074. static void *
  12075. websocket_client_thread(void *data)
  12076. #endif
  12077. {
  12078. struct websocket_client_thread_data *cdata =
  12079. (struct websocket_client_thread_data *)data;
  12080. mg_set_thread_name("ws-clnt");
  12081. if (cdata->conn->ctx) {
  12082. if (cdata->conn->ctx->callbacks.init_thread) {
  12083. /* 3 indicates a websocket client thread */
  12084. /* TODO: check if conn->ctx can be set */
  12085. cdata->conn->ctx->callbacks.init_thread(cdata->conn->ctx, 3);
  12086. }
  12087. }
  12088. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  12089. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  12090. if (cdata->close_handler != NULL) {
  12091. cdata->close_handler(cdata->conn, cdata->callback_data);
  12092. }
  12093. /* The websocket_client context has only this thread. If it runs out,
  12094. set the stop_flag to 2 (= "stopped"). */
  12095. cdata->conn->ctx->stop_flag = 2;
  12096. mg_free((void *)cdata);
  12097. #ifdef _WIN32
  12098. return 0;
  12099. #else
  12100. return NULL;
  12101. #endif
  12102. }
  12103. #endif
  12104. struct mg_connection *
  12105. mg_connect_websocket_client(const char *host,
  12106. int port,
  12107. int use_ssl,
  12108. char *error_buffer,
  12109. size_t error_buffer_size,
  12110. const char *path,
  12111. const char *origin,
  12112. mg_websocket_data_handler data_func,
  12113. mg_websocket_close_handler close_func,
  12114. void *user_data)
  12115. {
  12116. struct mg_connection *conn = NULL;
  12117. #if defined(USE_WEBSOCKET)
  12118. struct mg_context *newctx = NULL;
  12119. struct websocket_client_thread_data *thread_data;
  12120. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  12121. static const char *handshake_req;
  12122. if (origin != NULL) {
  12123. handshake_req = "GET %s HTTP/1.1\r\n"
  12124. "Host: %s\r\n"
  12125. "Upgrade: websocket\r\n"
  12126. "Connection: Upgrade\r\n"
  12127. "Sec-WebSocket-Key: %s\r\n"
  12128. "Sec-WebSocket-Version: 13\r\n"
  12129. "Origin: %s\r\n"
  12130. "\r\n";
  12131. } else {
  12132. handshake_req = "GET %s HTTP/1.1\r\n"
  12133. "Host: %s\r\n"
  12134. "Upgrade: websocket\r\n"
  12135. "Connection: Upgrade\r\n"
  12136. "Sec-WebSocket-Key: %s\r\n"
  12137. "Sec-WebSocket-Version: 13\r\n"
  12138. "\r\n";
  12139. }
  12140. /* Establish the client connection and request upgrade */
  12141. conn = mg_download(host,
  12142. port,
  12143. use_ssl,
  12144. error_buffer,
  12145. error_buffer_size,
  12146. handshake_req,
  12147. path,
  12148. host,
  12149. magic,
  12150. origin);
  12151. /* Connection object will be null if something goes wrong */
  12152. if (conn == NULL || (strcmp(conn->request_info.request_uri, "101") != 0)) {
  12153. if (!*error_buffer) {
  12154. /* if there is a connection, but it did not return 101,
  12155. * error_buffer is not yet set */
  12156. mg_snprintf(conn,
  12157. NULL, /* No truncation check for ebuf */
  12158. error_buffer,
  12159. error_buffer_size,
  12160. "Unexpected server reply");
  12161. }
  12162. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  12163. if (conn != NULL) {
  12164. mg_free(conn);
  12165. conn = NULL;
  12166. }
  12167. return conn;
  12168. }
  12169. /* For client connections, mg_context is fake. Since we need to set a
  12170. * callback function, we need to create a copy and modify it. */
  12171. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  12172. memcpy(newctx, conn->ctx, sizeof(struct mg_context));
  12173. newctx->user_data = user_data;
  12174. newctx->context_type = 2; /* ws/wss client context type */
  12175. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  12176. newctx->worker_threadids =
  12177. (pthread_t *)mg_calloc(newctx->cfg_worker_threads, sizeof(pthread_t));
  12178. conn->ctx = newctx;
  12179. thread_data = (struct websocket_client_thread_data *)
  12180. mg_calloc(sizeof(struct websocket_client_thread_data), 1);
  12181. thread_data->conn = conn;
  12182. thread_data->data_handler = data_func;
  12183. thread_data->close_handler = close_func;
  12184. thread_data->callback_data = user_data;
  12185. /* Start a thread to read the websocket client connection
  12186. * This thread will automatically stop when mg_disconnect is
  12187. * called on the client connection */
  12188. if (mg_start_thread_with_id(websocket_client_thread,
  12189. (void *)thread_data,
  12190. newctx->worker_threadids) != 0) {
  12191. mg_free((void *)thread_data);
  12192. mg_free((void *)newctx->worker_threadids);
  12193. mg_free((void *)newctx);
  12194. mg_free((void *)conn);
  12195. conn = NULL;
  12196. DEBUG_TRACE("%s",
  12197. "Websocket client connect thread could not be started\r\n");
  12198. }
  12199. #else
  12200. /* Appease "unused parameter" warnings */
  12201. (void)host;
  12202. (void)port;
  12203. (void)use_ssl;
  12204. (void)error_buffer;
  12205. (void)error_buffer_size;
  12206. (void)path;
  12207. (void)origin;
  12208. (void)user_data;
  12209. (void)data_func;
  12210. (void)close_func;
  12211. #endif
  12212. return conn;
  12213. }
  12214. static void
  12215. process_new_connection(struct mg_connection *conn)
  12216. {
  12217. if (conn && conn->ctx) {
  12218. struct mg_request_info *ri = &conn->request_info;
  12219. int keep_alive_enabled, keep_alive, discard_len;
  12220. char ebuf[100];
  12221. const char *hostend;
  12222. int reqerr, uri_type;
  12223. keep_alive_enabled =
  12224. !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  12225. /* Important: on new connection, reset the receiving buffer. Credit
  12226. * goes to crule42. */
  12227. conn->data_len = 0;
  12228. conn->handled_requests = 0;
  12229. do {
  12230. DEBUG_TRACE("calling getreq (%i times for this connection)",
  12231. conn->handled_requests + 1);
  12232. if (!getreq(conn, ebuf, sizeof(ebuf), &reqerr)) {
  12233. /* The request sent by the client could not be understood by
  12234. * the server, or it was incomplete or a timeout. Send an
  12235. * error message and close the connection. */
  12236. if (reqerr > 0) {
  12237. /*assert(ebuf[0] != '\0');*/
  12238. mg_send_http_error(conn, reqerr, "%s", ebuf);
  12239. }
  12240. } else if (strcmp(ri->http_version, "1.0")
  12241. && strcmp(ri->http_version, "1.1")) {
  12242. mg_snprintf(conn,
  12243. NULL, /* No truncation check for ebuf */
  12244. ebuf,
  12245. sizeof(ebuf),
  12246. "Bad HTTP version: [%s]",
  12247. ri->http_version);
  12248. mg_send_http_error(conn, 505, "%s", ebuf);
  12249. }
  12250. if (ebuf[0] == '\0') {
  12251. uri_type = get_uri_type(conn->request_info.request_uri);
  12252. switch (uri_type) {
  12253. case 1:
  12254. /* Asterisk */
  12255. conn->request_info.local_uri = NULL;
  12256. break;
  12257. case 2:
  12258. /* relative uri */
  12259. conn->request_info.local_uri =
  12260. conn->request_info.request_uri;
  12261. break;
  12262. case 3:
  12263. case 4:
  12264. /* absolute uri (with/without port) */
  12265. hostend = get_rel_url_at_current_server(
  12266. conn->request_info.request_uri, conn);
  12267. if (hostend) {
  12268. conn->request_info.local_uri = hostend;
  12269. } else {
  12270. conn->request_info.local_uri = NULL;
  12271. }
  12272. break;
  12273. default:
  12274. mg_snprintf(conn,
  12275. NULL, /* No truncation check for ebuf */
  12276. ebuf,
  12277. sizeof(ebuf),
  12278. "Invalid URI");
  12279. mg_send_http_error(conn, 400, "%s", ebuf);
  12280. conn->request_info.local_uri = NULL;
  12281. break;
  12282. }
  12283. #if defined(MG_LEGACY_INTERFACE)
  12284. /* TODO: cleanup uri, local_uri and request_uri */
  12285. conn->request_info.uri = conn->request_info.local_uri;
  12286. #endif
  12287. }
  12288. DEBUG_TRACE("http: %s, error: %s",
  12289. (ri->http_version ? ri->http_version : "none"),
  12290. (ebuf[0] ? ebuf : "none"));
  12291. if (ebuf[0] == '\0') {
  12292. if (conn->request_info.local_uri) {
  12293. /* handle request to local server */
  12294. handle_request(conn);
  12295. DEBUG_TRACE("%s", "handle_request done");
  12296. if (conn->ctx->callbacks.end_request != NULL) {
  12297. conn->ctx->callbacks.end_request(conn,
  12298. conn->status_code);
  12299. DEBUG_TRACE("%s", "end_request callback done");
  12300. }
  12301. log_access(conn);
  12302. } else {
  12303. /* TODO: handle non-local request (PROXY) */
  12304. conn->must_close = 1;
  12305. }
  12306. } else {
  12307. conn->must_close = 1;
  12308. }
  12309. if (ri->remote_user != NULL) {
  12310. mg_free((void *)ri->remote_user);
  12311. /* Important! When having connections with and without auth
  12312. * would cause double free and then crash */
  12313. ri->remote_user = NULL;
  12314. }
  12315. /* NOTE(lsm): order is important here. should_keep_alive() call
  12316. * is
  12317. * using parsed request, which will be invalid after memmove's
  12318. * below.
  12319. * Therefore, memorize should_keep_alive() result now for later
  12320. * use
  12321. * in loop exit condition. */
  12322. keep_alive = (conn->ctx->stop_flag == 0) && keep_alive_enabled
  12323. && (conn->content_len >= 0) && should_keep_alive(conn);
  12324. /* Discard all buffered data for this request */
  12325. discard_len = ((conn->content_len >= 0) && (conn->request_len > 0)
  12326. && ((conn->request_len + conn->content_len)
  12327. < (int64_t)conn->data_len))
  12328. ? (int)(conn->request_len + conn->content_len)
  12329. : conn->data_len;
  12330. /*assert(discard_len >= 0);*/
  12331. if (discard_len < 0) {
  12332. DEBUG_TRACE("internal error: discard_len = %li",
  12333. (long int)discard_len);
  12334. break;
  12335. }
  12336. conn->data_len -= discard_len;
  12337. if (conn->data_len > 0) {
  12338. DEBUG_TRACE("discard_len = %lu", (long unsigned)discard_len);
  12339. memmove(conn->buf,
  12340. conn->buf + discard_len,
  12341. (size_t)conn->data_len);
  12342. }
  12343. /* assert(conn->data_len >= 0); */
  12344. /* assert(conn->data_len <= conn->buf_size); */
  12345. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  12346. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  12347. (long int)conn->data_len,
  12348. (long int)conn->buf_size);
  12349. break;
  12350. }
  12351. conn->handled_requests++;
  12352. } while (keep_alive);
  12353. }
  12354. }
  12355. #if defined(ALTERNATIVE_QUEUE)
  12356. static void
  12357. produce_socket(struct mg_context *ctx, const struct socket *sp)
  12358. {
  12359. unsigned int i;
  12360. for (;;) {
  12361. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  12362. /* find a free worker slot and signal it */
  12363. if (ctx->client_socks[i].in_use == 0) {
  12364. ctx->client_socks[i] = *sp;
  12365. ctx->client_socks[i].in_use = 1;
  12366. event_signal(ctx->client_wait_events[i]);
  12367. return;
  12368. }
  12369. }
  12370. /* queue is full */
  12371. mg_sleep(1);
  12372. }
  12373. }
  12374. static int
  12375. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  12376. {
  12377. DEBUG_TRACE("%s", "going idle");
  12378. ctx->client_socks[thread_index].in_use = 0;
  12379. event_wait(ctx->client_wait_events[thread_index]);
  12380. *sp = ctx->client_socks[thread_index];
  12381. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  12382. return !ctx->stop_flag;
  12383. }
  12384. #else /* ALTERNATIVE_QUEUE */
  12385. /* Worker threads take accepted socket from the queue */
  12386. static int
  12387. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  12388. {
  12389. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  12390. (void)thread_index;
  12391. (void)pthread_mutex_lock(&ctx->thread_mutex);
  12392. DEBUG_TRACE("%s", "going idle");
  12393. /* If the queue is empty, wait. We're idle at this point. */
  12394. while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
  12395. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  12396. }
  12397. /* If we're stopping, sq_head may be equal to sq_tail. */
  12398. if (ctx->sq_head > ctx->sq_tail) {
  12399. /* Copy socket from the queue and increment tail */
  12400. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  12401. ctx->sq_tail++;
  12402. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  12403. /* Wrap pointers if needed */
  12404. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  12405. ctx->sq_tail -= QUEUE_SIZE(ctx);
  12406. ctx->sq_head -= QUEUE_SIZE(ctx);
  12407. }
  12408. }
  12409. (void)pthread_cond_signal(&ctx->sq_empty);
  12410. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  12411. return !ctx->stop_flag;
  12412. #undef QUEUE_SIZE
  12413. }
  12414. /* Master thread adds accepted socket to a queue */
  12415. static void
  12416. produce_socket(struct mg_context *ctx, const struct socket *sp)
  12417. {
  12418. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  12419. if (!ctx) {
  12420. return;
  12421. }
  12422. (void)pthread_mutex_lock(&ctx->thread_mutex);
  12423. /* If the queue is full, wait */
  12424. while (ctx->stop_flag == 0
  12425. && ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx)) {
  12426. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  12427. }
  12428. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  12429. /* Copy socket to the queue and increment head */
  12430. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  12431. ctx->sq_head++;
  12432. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  12433. }
  12434. (void)pthread_cond_signal(&ctx->sq_full);
  12435. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  12436. #undef QUEUE_SIZE
  12437. }
  12438. #endif /* ALTERNATIVE_QUEUE */
  12439. struct worker_thread_args {
  12440. struct mg_context *ctx;
  12441. int index;
  12442. };
  12443. static void *
  12444. worker_thread_run(struct worker_thread_args *thread_args)
  12445. {
  12446. struct mg_context *ctx = thread_args->ctx;
  12447. struct mg_connection *conn;
  12448. struct mg_workerTLS tls;
  12449. #if defined(MG_LEGACY_INTERFACE)
  12450. uint32_t addr;
  12451. #endif
  12452. mg_set_thread_name("worker");
  12453. tls.is_master = 0;
  12454. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  12455. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12456. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  12457. #endif
  12458. /* Initialize thread local storage before calling any callback */
  12459. pthread_setspecific(sTlsKey, &tls);
  12460. if (ctx->callbacks.init_thread) {
  12461. /* call init_thread for a worker thread (type 1) */
  12462. ctx->callbacks.init_thread(ctx, 1);
  12463. }
  12464. /* Connection structure has been pre-allocated */
  12465. if (((int)thread_args->index < 0)
  12466. || ((unsigned)thread_args->index
  12467. >= (unsigned)ctx->cfg_worker_threads)) {
  12468. mg_cry(fc(ctx),
  12469. "Internal error: Invalid worker index %i",
  12470. (int)thread_args->index);
  12471. return NULL;
  12472. }
  12473. conn = ctx->worker_connections + thread_args->index;
  12474. /* Request buffers are not pre-allocated. They are private to the
  12475. * request and do not contain any state information that might be
  12476. * of interest to anyone observing a server status. */
  12477. conn->buf = (char *)mg_malloc(MAX_REQUEST_SIZE);
  12478. if (conn->buf == NULL) {
  12479. mg_cry(fc(ctx),
  12480. "Out of memory: Cannot allocate buffer for worker %i",
  12481. (int)thread_args->index);
  12482. return NULL;
  12483. }
  12484. conn->buf_size = MAX_REQUEST_SIZE;
  12485. conn->ctx = ctx;
  12486. conn->thread_index = thread_args->index;
  12487. conn->request_info.user_data = ctx->user_data;
  12488. /* Allocate a mutex for this connection to allow communication both
  12489. * within the request handler and from elsewhere in the application
  12490. */
  12491. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  12492. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  12493. * signal sq_empty condvar to wake up the master waiting in
  12494. * produce_socket() */
  12495. while (consume_socket(ctx, &conn->client, conn->thread_index)) {
  12496. conn->conn_birth_time = time(NULL);
  12497. /* Fill in IP, port info early so even if SSL setup below fails,
  12498. * error handler would have the corresponding info.
  12499. * Thanks to Johannes Winkelmann for the patch.
  12500. */
  12501. #if defined(USE_IPV6)
  12502. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  12503. conn->request_info.remote_port =
  12504. ntohs(conn->client.rsa.sin6.sin6_port);
  12505. } else
  12506. #endif
  12507. {
  12508. conn->request_info.remote_port =
  12509. ntohs(conn->client.rsa.sin.sin_port);
  12510. }
  12511. sockaddr_to_string(conn->request_info.remote_addr,
  12512. sizeof(conn->request_info.remote_addr),
  12513. &conn->client.rsa);
  12514. DEBUG_TRACE("Start processing connection from %s",
  12515. conn->request_info.remote_addr);
  12516. #if defined(MG_LEGACY_INTERFACE)
  12517. /* This legacy interface only works for the IPv4 case */
  12518. addr = ntohl(conn->client.rsa.sin.sin_addr.s_addr);
  12519. memcpy(&conn->request_info.remote_ip, &addr, 4);
  12520. #endif
  12521. conn->request_info.is_ssl = conn->client.is_ssl;
  12522. if (conn->client.is_ssl) {
  12523. #ifndef NO_SSL
  12524. /* HTTPS connection */
  12525. if (sslize(conn,
  12526. conn->ctx->ssl_ctx,
  12527. SSL_accept,
  12528. &(conn->ctx->stop_flag))) {
  12529. /* Get SSL client certificate information (if set) */
  12530. ssl_get_client_cert_info(conn);
  12531. /* process HTTPS connection */
  12532. process_new_connection(conn);
  12533. /* Free client certificate info */
  12534. if (conn->request_info.client_cert) {
  12535. mg_free((void *)(conn->request_info.client_cert->subject));
  12536. mg_free((void *)(conn->request_info.client_cert->issuer));
  12537. mg_free((void *)(conn->request_info.client_cert->serial));
  12538. mg_free((void *)(conn->request_info.client_cert->finger));
  12539. conn->request_info.client_cert->subject = 0;
  12540. conn->request_info.client_cert->issuer = 0;
  12541. conn->request_info.client_cert->serial = 0;
  12542. conn->request_info.client_cert->finger = 0;
  12543. mg_free(conn->request_info.client_cert);
  12544. conn->request_info.client_cert = 0;
  12545. }
  12546. }
  12547. #endif
  12548. } else {
  12549. /* process HTTP connection */
  12550. process_new_connection(conn);
  12551. }
  12552. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  12553. conn->request_info.remote_addr,
  12554. difftime(time(NULL), conn->conn_birth_time));
  12555. close_connection(conn);
  12556. DEBUG_TRACE("%s", "Connection closed");
  12557. }
  12558. pthread_setspecific(sTlsKey, NULL);
  12559. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12560. CloseHandle(tls.pthread_cond_helper_mutex);
  12561. #endif
  12562. pthread_mutex_destroy(&conn->mutex);
  12563. /* Free the request buffer. */
  12564. conn->buf_size = 0;
  12565. mg_free(conn->buf);
  12566. conn->buf = NULL;
  12567. DEBUG_TRACE("%s", "exiting");
  12568. return NULL;
  12569. }
  12570. /* Threads have different return types on Windows and Unix. */
  12571. #ifdef _WIN32
  12572. static unsigned __stdcall worker_thread(void *thread_func_param)
  12573. {
  12574. struct worker_thread_args *pwta =
  12575. (struct worker_thread_args *)thread_func_param;
  12576. worker_thread_run(pwta);
  12577. mg_free(thread_func_param);
  12578. return 0;
  12579. }
  12580. #else
  12581. static void *
  12582. worker_thread(void *thread_func_param)
  12583. {
  12584. struct worker_thread_args *pwta =
  12585. (struct worker_thread_args *)thread_func_param;
  12586. worker_thread_run(pwta);
  12587. mg_free(thread_func_param);
  12588. return NULL;
  12589. }
  12590. #endif /* _WIN32 */
  12591. static void
  12592. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  12593. {
  12594. struct socket so;
  12595. char src_addr[IP_ADDR_STR_LEN];
  12596. socklen_t len = sizeof(so.rsa);
  12597. int on = 1;
  12598. if (!listener) {
  12599. return;
  12600. }
  12601. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  12602. == INVALID_SOCKET) {
  12603. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  12604. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  12605. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  12606. closesocket(so.sock);
  12607. so.sock = INVALID_SOCKET;
  12608. } else {
  12609. /* Put so socket structure into the queue */
  12610. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  12611. set_close_on_exec(so.sock, fc(ctx));
  12612. so.is_ssl = listener->is_ssl;
  12613. so.ssl_redir = listener->ssl_redir;
  12614. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  12615. mg_cry(fc(ctx),
  12616. "%s: getsockname() failed: %s",
  12617. __func__,
  12618. strerror(ERRNO));
  12619. }
  12620. /* Set TCP keep-alive. This is needed because if HTTP-level
  12621. * keep-alive
  12622. * is enabled, and client resets the connection, server won't get
  12623. * TCP FIN or RST and will keep the connection open forever. With
  12624. * TCP keep-alive, next keep-alive handshake will figure out that
  12625. * the client is down and will close the server end.
  12626. * Thanks to Igor Klopov who suggested the patch. */
  12627. if (setsockopt(so.sock,
  12628. SOL_SOCKET,
  12629. SO_KEEPALIVE,
  12630. (SOCK_OPT_TYPE)&on,
  12631. sizeof(on)) != 0) {
  12632. mg_cry(fc(ctx),
  12633. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  12634. __func__,
  12635. strerror(ERRNO));
  12636. }
  12637. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  12638. * to effectively fill up the underlying IP packet payload and
  12639. * reduce the overhead of sending lots of small buffers. However
  12640. * this hurts the server's throughput (ie. operations per second)
  12641. * when HTTP 1.1 persistent connections are used and the responses
  12642. * are relatively small (eg. less than 1400 bytes).
  12643. */
  12644. if ((ctx != NULL) && (ctx->config[CONFIG_TCP_NODELAY] != NULL)
  12645. && (!strcmp(ctx->config[CONFIG_TCP_NODELAY], "1"))) {
  12646. if (set_tcp_nodelay(so.sock, 1) != 0) {
  12647. mg_cry(fc(ctx),
  12648. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  12649. __func__,
  12650. strerror(ERRNO));
  12651. }
  12652. }
  12653. /* We are using non-blocking sockets. Thus, the
  12654. * set_sock_timeout(so.sock, timeout);
  12655. * call is no longer required. */
  12656. set_blocking_mode(so.sock, 0);
  12657. produce_socket(ctx, &so);
  12658. }
  12659. }
  12660. static void
  12661. master_thread_run(void *thread_func_param)
  12662. {
  12663. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  12664. struct mg_workerTLS tls;
  12665. struct pollfd *pfd;
  12666. unsigned int i;
  12667. unsigned int workerthreadcount;
  12668. if (!ctx) {
  12669. return;
  12670. }
  12671. mg_set_thread_name("master");
  12672. /* Increase priority of the master thread */
  12673. #if defined(_WIN32)
  12674. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  12675. #elif defined(USE_MASTER_THREAD_PRIORITY)
  12676. int min_prio = sched_get_priority_min(SCHED_RR);
  12677. int max_prio = sched_get_priority_max(SCHED_RR);
  12678. if ((min_prio >= 0) && (max_prio >= 0)
  12679. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  12680. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  12681. struct sched_param sched_param = {0};
  12682. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  12683. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  12684. }
  12685. #endif
  12686. /* Initialize thread local storage */
  12687. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12688. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  12689. #endif
  12690. tls.is_master = 1;
  12691. pthread_setspecific(sTlsKey, &tls);
  12692. if (ctx->callbacks.init_thread) {
  12693. /* Callback for the master thread (type 0) */
  12694. ctx->callbacks.init_thread(ctx, 0);
  12695. }
  12696. /* Server starts *now* */
  12697. ctx->start_time = time(NULL);
  12698. /* Start the server */
  12699. pfd = ctx->listening_socket_fds;
  12700. while (ctx->stop_flag == 0) {
  12701. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12702. pfd[i].fd = ctx->listening_sockets[i].sock;
  12703. pfd[i].events = POLLIN;
  12704. }
  12705. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  12706. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12707. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  12708. * successful poll, and POLLIN is defined as
  12709. * (POLLRDNORM | POLLRDBAND)
  12710. * Therefore, we're checking pfd[i].revents & POLLIN, not
  12711. * pfd[i].revents == POLLIN. */
  12712. if (ctx->stop_flag == 0 && (pfd[i].revents & POLLIN)) {
  12713. accept_new_connection(&ctx->listening_sockets[i], ctx);
  12714. }
  12715. }
  12716. }
  12717. }
  12718. /* Here stop_flag is 1 - Initiate shutdown. */
  12719. DEBUG_TRACE("%s", "stopping workers");
  12720. /* Stop signal received: somebody called mg_stop. Quit. */
  12721. close_all_listening_sockets(ctx);
  12722. /* Wakeup workers that are waiting for connections to handle. */
  12723. (void)pthread_mutex_lock(&ctx->thread_mutex);
  12724. #if defined(ALTERNATIVE_QUEUE)
  12725. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  12726. event_signal(ctx->client_wait_events[i]);
  12727. /* Since we know all sockets, we can shutdown the connections. */
  12728. if (ctx->client_socks[i].in_use) {
  12729. shutdown(ctx->client_socks[i].sock, SHUTDOWN_BOTH);
  12730. }
  12731. }
  12732. #else
  12733. pthread_cond_broadcast(&ctx->sq_full);
  12734. #endif
  12735. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  12736. /* Join all worker threads to avoid leaking threads. */
  12737. workerthreadcount = ctx->cfg_worker_threads;
  12738. for (i = 0; i < workerthreadcount; i++) {
  12739. if (ctx->worker_threadids[i] != 0) {
  12740. mg_join_thread(ctx->worker_threadids[i]);
  12741. }
  12742. }
  12743. #if defined(USE_LUA)
  12744. /* Free Lua state of lua background task */
  12745. if (ctx->lua_background_state) {
  12746. lua_close((lua_State *)ctx->lua_background_state);
  12747. ctx->lua_background_state = 0;
  12748. }
  12749. #endif
  12750. #if !defined(NO_SSL)
  12751. if (ctx->ssl_ctx != NULL) {
  12752. uninitialize_ssl();
  12753. }
  12754. #endif
  12755. DEBUG_TRACE("%s", "exiting");
  12756. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12757. CloseHandle(tls.pthread_cond_helper_mutex);
  12758. #endif
  12759. pthread_setspecific(sTlsKey, NULL);
  12760. /* Signal mg_stop() that we're done.
  12761. * WARNING: This must be the very last thing this
  12762. * thread does, as ctx becomes invalid after this line. */
  12763. ctx->stop_flag = 2;
  12764. }
  12765. /* Threads have different return types on Windows and Unix. */
  12766. #ifdef _WIN32
  12767. static unsigned __stdcall master_thread(void *thread_func_param)
  12768. {
  12769. master_thread_run(thread_func_param);
  12770. return 0;
  12771. }
  12772. #else
  12773. static void *
  12774. master_thread(void *thread_func_param)
  12775. {
  12776. master_thread_run(thread_func_param);
  12777. return NULL;
  12778. }
  12779. #endif /* _WIN32 */
  12780. static void
  12781. free_context(struct mg_context *ctx)
  12782. {
  12783. int i;
  12784. struct mg_handler_info *tmp_rh;
  12785. if (ctx == NULL) {
  12786. return;
  12787. }
  12788. if (ctx->callbacks.exit_context) {
  12789. ctx->callbacks.exit_context(ctx);
  12790. }
  12791. /* All threads exited, no sync is needed. Destroy thread mutex and
  12792. * condvars
  12793. */
  12794. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  12795. #if defined(ALTERNATIVE_QUEUE)
  12796. mg_free(ctx->client_socks);
  12797. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  12798. event_destroy(ctx->client_wait_events[i]);
  12799. }
  12800. mg_free(ctx->client_wait_events);
  12801. #else
  12802. (void)pthread_cond_destroy(&ctx->sq_empty);
  12803. (void)pthread_cond_destroy(&ctx->sq_full);
  12804. #endif
  12805. /* Destroy other context global data structures mutex */
  12806. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  12807. #if defined(USE_TIMERS)
  12808. timers_exit(ctx);
  12809. #endif
  12810. /* Deallocate config parameters */
  12811. for (i = 0; i < NUM_OPTIONS; i++) {
  12812. if (ctx->config[i] != NULL) {
  12813. #if defined(_MSC_VER)
  12814. #pragma warning(suppress : 6001)
  12815. #endif
  12816. mg_free(ctx->config[i]);
  12817. }
  12818. }
  12819. /* Deallocate request handlers */
  12820. while (ctx->handlers) {
  12821. tmp_rh = ctx->handlers;
  12822. ctx->handlers = tmp_rh->next;
  12823. mg_free(tmp_rh->uri);
  12824. mg_free(tmp_rh);
  12825. }
  12826. #ifndef NO_SSL
  12827. /* Deallocate SSL context */
  12828. if (ctx->ssl_ctx != NULL) {
  12829. SSL_CTX_free(ctx->ssl_ctx);
  12830. }
  12831. #endif /* !NO_SSL */
  12832. /* Deallocate worker thread ID array */
  12833. if (ctx->worker_threadids != NULL) {
  12834. mg_free(ctx->worker_threadids);
  12835. }
  12836. /* Deallocate worker thread ID array */
  12837. if (ctx->worker_connections != NULL) {
  12838. mg_free(ctx->worker_connections);
  12839. }
  12840. /* Deallocate the tls variable */
  12841. if (mg_atomic_dec(&sTlsInit) == 0) {
  12842. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12843. DeleteCriticalSection(&global_log_file_lock);
  12844. #endif /* _WIN32 && !__SYMBIAN32__ */
  12845. #if !defined(_WIN32)
  12846. pthread_mutexattr_destroy(&pthread_mutex_attr);
  12847. #endif
  12848. pthread_key_delete(sTlsKey);
  12849. #if defined(USE_LUA)
  12850. lua_exit_optional_libraries();
  12851. #endif
  12852. }
  12853. /* deallocate system name string */
  12854. mg_free(ctx->systemName);
  12855. /* Deallocate context itself */
  12856. mg_free(ctx);
  12857. }
  12858. void
  12859. mg_stop(struct mg_context *ctx)
  12860. {
  12861. pthread_t mt;
  12862. if (!ctx) {
  12863. return;
  12864. }
  12865. /* We don't use a lock here. Calling mg_stop with the same ctx from
  12866. * two threads is not allowed. */
  12867. mt = ctx->masterthreadid;
  12868. if (mt == 0) {
  12869. return;
  12870. }
  12871. ctx->masterthreadid = 0;
  12872. /* Set stop flag, so all threads know they have to exit. */
  12873. ctx->stop_flag = 1;
  12874. /* Wait until everything has stopped. */
  12875. while (ctx->stop_flag != 2) {
  12876. (void)mg_sleep(10);
  12877. }
  12878. mg_join_thread(mt);
  12879. free_context(ctx);
  12880. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12881. (void)WSACleanup();
  12882. #endif /* _WIN32 && !__SYMBIAN32__ */
  12883. }
  12884. static void
  12885. get_system_name(char **sysName)
  12886. {
  12887. #if defined(_WIN32)
  12888. #if !defined(__SYMBIAN32__)
  12889. #if defined(_WIN32_WCE)
  12890. *sysName = mg_strdup("WinCE");
  12891. #else
  12892. char name[128];
  12893. DWORD dwVersion = 0;
  12894. DWORD dwMajorVersion = 0;
  12895. DWORD dwMinorVersion = 0;
  12896. DWORD dwBuild = 0;
  12897. BOOL wowRet, isWoW = FALSE;
  12898. #ifdef _MSC_VER
  12899. #pragma warning(push)
  12900. /* GetVersion was declared deprecated */
  12901. #pragma warning(disable : 4996)
  12902. #endif
  12903. dwVersion = GetVersion();
  12904. #ifdef _MSC_VER
  12905. #pragma warning(pop)
  12906. #endif
  12907. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  12908. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  12909. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  12910. (void)dwBuild;
  12911. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  12912. sprintf(name,
  12913. "Windows %u.%u%s",
  12914. (unsigned)dwMajorVersion,
  12915. (unsigned)dwMinorVersion,
  12916. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  12917. *sysName = mg_strdup(name);
  12918. #endif
  12919. #else
  12920. *sysName = mg_strdup("Symbian");
  12921. #endif
  12922. #else
  12923. struct utsname name;
  12924. memset(&name, 0, sizeof(name));
  12925. uname(&name);
  12926. *sysName = mg_strdup(name.sysname);
  12927. #endif
  12928. }
  12929. struct mg_context *
  12930. mg_start(const struct mg_callbacks *callbacks,
  12931. void *user_data,
  12932. const char **options)
  12933. {
  12934. struct mg_context *ctx;
  12935. const char *name, *value, *default_value;
  12936. int idx, ok, workerthreadcount;
  12937. unsigned int i;
  12938. void (*exit_callback)(const struct mg_context *ctx) = 0;
  12939. struct mg_workerTLS tls;
  12940. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12941. WSADATA data;
  12942. WSAStartup(MAKEWORD(2, 2), &data);
  12943. #endif /* _WIN32 && !__SYMBIAN32__ */
  12944. /* Allocate context and initialize reasonable general case defaults. */
  12945. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  12946. return NULL;
  12947. }
  12948. /* Random number generator will initialize at the first call */
  12949. ctx->auth_nonce_mask =
  12950. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  12951. if (mg_atomic_inc(&sTlsInit) == 1) {
  12952. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12953. InitializeCriticalSection(&global_log_file_lock);
  12954. #endif /* _WIN32 && !__SYMBIAN32__ */
  12955. #if !defined(_WIN32)
  12956. pthread_mutexattr_init(&pthread_mutex_attr);
  12957. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  12958. #endif
  12959. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  12960. /* Fatal error - abort start. However, this situation should
  12961. * never occur in practice. */
  12962. mg_atomic_dec(&sTlsInit);
  12963. mg_cry(fc(ctx), "Cannot initialize thread local storage");
  12964. mg_free(ctx);
  12965. return NULL;
  12966. }
  12967. #if defined(USE_LUA)
  12968. lua_init_optional_libraries();
  12969. #endif
  12970. } else {
  12971. /* TODO (low): instead of sleeping, check if sTlsKey is already
  12972. * initialized. */
  12973. mg_sleep(1);
  12974. }
  12975. tls.is_master = -1;
  12976. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  12977. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12978. tls.pthread_cond_helper_mutex = NULL;
  12979. #endif
  12980. pthread_setspecific(sTlsKey, &tls);
  12981. /* Dummy use this function - in some #ifdef combinations it's used,
  12982. * while it's not used in others, but GCC seems to stupid to understand
  12983. * #pragma GCC diagnostic ignored "-Wunused-function"
  12984. * in cases the function is unused, and it also complains on
  12985. * __attribute((unused))__ in cases it is used.
  12986. * So dummy use it, to have our peace. */
  12987. (void)mg_current_thread_id();
  12988. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr);
  12989. #if !defined(ALTERNATIVE_QUEUE)
  12990. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  12991. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  12992. #endif
  12993. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr);
  12994. if (!ok) {
  12995. /* Fatal error - abort start. However, this situation should never
  12996. * occur in practice. */
  12997. mg_cry(fc(ctx), "Cannot initialize thread synchronization objects");
  12998. mg_free(ctx);
  12999. pthread_setspecific(sTlsKey, NULL);
  13000. return NULL;
  13001. }
  13002. if (callbacks) {
  13003. ctx->callbacks = *callbacks;
  13004. exit_callback = callbacks->exit_context;
  13005. ctx->callbacks.exit_context = 0;
  13006. }
  13007. ctx->user_data = user_data;
  13008. ctx->handlers = NULL;
  13009. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  13010. ctx->shared_lua_websockets = 0;
  13011. #endif
  13012. while (options && (name = *options++) != NULL) {
  13013. if ((idx = get_option_index(name)) == -1) {
  13014. mg_cry(fc(ctx), "Invalid option: %s", name);
  13015. free_context(ctx);
  13016. pthread_setspecific(sTlsKey, NULL);
  13017. return NULL;
  13018. } else if ((value = *options++) == NULL) {
  13019. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  13020. free_context(ctx);
  13021. pthread_setspecific(sTlsKey, NULL);
  13022. return NULL;
  13023. }
  13024. if (ctx->config[idx] != NULL) {
  13025. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  13026. mg_free(ctx->config[idx]);
  13027. }
  13028. ctx->config[idx] = mg_strdup(value);
  13029. DEBUG_TRACE("[%s] -> [%s]", name, value);
  13030. }
  13031. /* Set default value if needed */
  13032. for (i = 0; config_options[i].name != NULL; i++) {
  13033. default_value = config_options[i].default_value;
  13034. if (ctx->config[i] == NULL && default_value != NULL) {
  13035. ctx->config[i] = mg_strdup(default_value);
  13036. }
  13037. }
  13038. workerthreadcount = atoi(ctx->config[NUM_THREADS]);
  13039. if (workerthreadcount > MAX_WORKER_THREADS) {
  13040. mg_cry(fc(ctx), "Too many worker threads");
  13041. free_context(ctx);
  13042. pthread_setspecific(sTlsKey, NULL);
  13043. return NULL;
  13044. }
  13045. if (workerthreadcount <= 0) {
  13046. mg_cry(fc(ctx), "Invalid number of worker threads");
  13047. free_context(ctx);
  13048. pthread_setspecific(sTlsKey, NULL);
  13049. return NULL;
  13050. }
  13051. #if defined(NO_FILES)
  13052. if (ctx->config[DOCUMENT_ROOT] != NULL) {
  13053. mg_cry(fc(ctx), "%s", "Document root must not be set");
  13054. free_context(ctx);
  13055. pthread_setspecific(sTlsKey, NULL);
  13056. return NULL;
  13057. }
  13058. #endif
  13059. get_system_name(&ctx->systemName);
  13060. #if defined(USE_LUA)
  13061. /* If a Lua background script has been configured, start it. */
  13062. if (ctx->config[LUA_BACKGROUND_SCRIPT] != NULL) {
  13063. char ebuf[256];
  13064. void *state = (void *)mg_prepare_lua_context_script(
  13065. ctx->config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  13066. if (!state) {
  13067. mg_cry(fc(ctx), "lua_background_script error: %s", ebuf);
  13068. free_context(ctx);
  13069. pthread_setspecific(sTlsKey, NULL);
  13070. return NULL;
  13071. }
  13072. ctx->lua_background_state = state;
  13073. } else {
  13074. ctx->lua_background_state = 0;
  13075. }
  13076. #endif
  13077. /* NOTE(lsm): order is important here. SSL certificates must
  13078. * be initialized before listening ports. UID must be set last. */
  13079. if (!set_gpass_option(ctx) ||
  13080. #if !defined(NO_SSL)
  13081. !set_ssl_option(ctx) ||
  13082. #endif
  13083. !set_ports_option(ctx) ||
  13084. #if !defined(_WIN32)
  13085. !set_uid_option(ctx) ||
  13086. #endif
  13087. !set_acl_option(ctx)) {
  13088. free_context(ctx);
  13089. pthread_setspecific(sTlsKey, NULL);
  13090. return NULL;
  13091. }
  13092. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  13093. /* Ignore SIGPIPE signal, so if browser cancels the request, it
  13094. * won't kill the whole process. */
  13095. (void)signal(SIGPIPE, SIG_IGN);
  13096. #endif /* !_WIN32 && !__SYMBIAN32__ */
  13097. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  13098. ctx->worker_threadids =
  13099. (pthread_t *)mg_calloc(ctx->cfg_worker_threads, sizeof(pthread_t));
  13100. if (ctx->worker_threadids == NULL) {
  13101. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  13102. free_context(ctx);
  13103. pthread_setspecific(sTlsKey, NULL);
  13104. return NULL;
  13105. }
  13106. ctx->worker_connections =
  13107. (struct mg_connection *)mg_calloc(ctx->cfg_worker_threads,
  13108. sizeof(struct mg_connection));
  13109. if (ctx->worker_connections == NULL) {
  13110. mg_cry(fc(ctx), "Not enough memory for worker thread connection array");
  13111. free_context(ctx);
  13112. pthread_setspecific(sTlsKey, NULL);
  13113. return NULL;
  13114. }
  13115. #if defined(ALTERNATIVE_QUEUE)
  13116. ctx->client_wait_events =
  13117. mg_calloc(sizeof(ctx->client_wait_events[0]), ctx->cfg_worker_threads);
  13118. if (ctx->client_wait_events == NULL) {
  13119. mg_cry(fc(ctx), "Not enough memory for worker event array");
  13120. mg_free(ctx->worker_threadids);
  13121. free_context(ctx);
  13122. pthread_setspecific(sTlsKey, NULL);
  13123. return NULL;
  13124. }
  13125. ctx->client_socks =
  13126. mg_calloc(sizeof(ctx->client_socks[0]), ctx->cfg_worker_threads);
  13127. if (ctx->client_wait_events == NULL) {
  13128. mg_cry(fc(ctx), "Not enough memory for worker socket array");
  13129. mg_free(ctx->client_socks);
  13130. mg_free(ctx->worker_threadids);
  13131. free_context(ctx);
  13132. pthread_setspecific(sTlsKey, NULL);
  13133. return NULL;
  13134. }
  13135. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  13136. ctx->client_wait_events[i] = event_create();
  13137. if (ctx->client_wait_events[i] == 0) {
  13138. mg_cry(fc(ctx), "Error creating worker event %i", i);
  13139. while (i > 0) {
  13140. i--;
  13141. event_destroy(ctx->client_wait_events[i]);
  13142. }
  13143. mg_free(ctx->client_socks);
  13144. mg_free(ctx->worker_threadids);
  13145. free_context(ctx);
  13146. pthread_setspecific(sTlsKey, NULL);
  13147. return NULL;
  13148. }
  13149. }
  13150. #endif
  13151. #if defined(USE_TIMERS)
  13152. if (timers_init(ctx) != 0) {
  13153. mg_cry(fc(ctx), "Error creating timers");
  13154. free_context(ctx);
  13155. pthread_setspecific(sTlsKey, NULL);
  13156. return NULL;
  13157. }
  13158. #endif
  13159. /* Context has been created - init user libraries */
  13160. if (ctx->callbacks.init_context) {
  13161. ctx->callbacks.init_context(ctx);
  13162. }
  13163. ctx->callbacks.exit_context = exit_callback;
  13164. ctx->context_type = 1; /* server context */
  13165. /* Start master (listening) thread */
  13166. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  13167. /* Start worker threads */
  13168. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  13169. struct worker_thread_args *wta = (struct worker_thread_args *)mg_malloc(
  13170. sizeof(struct worker_thread_args));
  13171. if (wta) {
  13172. wta->ctx = ctx;
  13173. wta->index = (int)i;
  13174. }
  13175. if ((wta == NULL)
  13176. || (mg_start_thread_with_id(worker_thread,
  13177. wta,
  13178. &ctx->worker_threadids[i]) != 0)) {
  13179. /* thread was not created */
  13180. if (wta != NULL) {
  13181. mg_free(wta);
  13182. }
  13183. if (i > 0) {
  13184. mg_cry(fc(ctx),
  13185. "Cannot start worker thread %i: error %ld",
  13186. i + 1,
  13187. (long)ERRNO);
  13188. } else {
  13189. mg_cry(fc(ctx),
  13190. "Cannot create threads: error %ld",
  13191. (long)ERRNO);
  13192. free_context(ctx);
  13193. pthread_setspecific(sTlsKey, NULL);
  13194. return NULL;
  13195. }
  13196. break;
  13197. }
  13198. }
  13199. pthread_setspecific(sTlsKey, NULL);
  13200. return ctx;
  13201. }
  13202. /* Feature check API function */
  13203. unsigned
  13204. mg_check_feature(unsigned feature)
  13205. {
  13206. static const unsigned feature_set = 0
  13207. /* Set bits for available features according to API documentation.
  13208. * This bit mask is created at compile time, according to the active
  13209. * preprocessor defines. It is a single const value at runtime. */
  13210. #if !defined(NO_FILES)
  13211. | 0x0001u
  13212. #endif
  13213. #if !defined(NO_SSL)
  13214. | 0x0002u
  13215. #endif
  13216. #if !defined(NO_CGI)
  13217. | 0x0004u
  13218. #endif
  13219. #if defined(USE_IPV6)
  13220. | 0x0008u
  13221. #endif
  13222. #if defined(USE_WEBSOCKET)
  13223. | 0x0010u
  13224. #endif
  13225. #if defined(USE_LUA)
  13226. | 0x0020u
  13227. #endif
  13228. #if defined(USE_DUKTAPE)
  13229. | 0x0040u
  13230. #endif
  13231. #if !defined(NO_CACHING)
  13232. | 0x0080u
  13233. #endif
  13234. /* Set some extra bits not defined in the API documentation.
  13235. * These bits may change without further notice. */
  13236. #if defined(MG_LEGACY_INTERFACE)
  13237. | 0x8000u
  13238. #endif
  13239. #if defined(MEMORY_DEBUGGING)
  13240. | 0x0100u
  13241. #endif
  13242. #if defined(USE_TIMERS)
  13243. | 0x0200u
  13244. #endif
  13245. #if !defined(NO_NONCE_CHECK)
  13246. | 0x0400u
  13247. #endif
  13248. #if !defined(NO_POPEN)
  13249. | 0x0800u
  13250. #endif
  13251. ;
  13252. return (feature & feature_set);
  13253. }
  13254. /* Get system information. It can be printed or stored by the caller.
  13255. * Return the size of available information. */
  13256. static int
  13257. mg_get_system_info_impl(char *buffer, int buflen)
  13258. {
  13259. char block[256];
  13260. int system_info_length = 0;
  13261. #if defined(_WIN32)
  13262. const char *eol = "\r\n";
  13263. #else
  13264. const char *eol = "\n";
  13265. #endif
  13266. /* Server version */
  13267. {
  13268. const char *version = mg_version();
  13269. mg_snprintf(NULL,
  13270. NULL,
  13271. block,
  13272. sizeof(block),
  13273. "Server Version: %s%s",
  13274. version,
  13275. eol);
  13276. system_info_length += (int)strlen(block);
  13277. if (system_info_length < buflen) {
  13278. strcat(buffer, block);
  13279. }
  13280. }
  13281. /* System info */
  13282. {
  13283. #if defined(_WIN32)
  13284. #if !defined(__SYMBIAN32__)
  13285. DWORD dwVersion = 0;
  13286. DWORD dwMajorVersion = 0;
  13287. DWORD dwMinorVersion = 0;
  13288. SYSTEM_INFO si;
  13289. GetSystemInfo(&si);
  13290. #ifdef _MSC_VER
  13291. #pragma warning(push)
  13292. /* GetVersion was declared deprecated */
  13293. #pragma warning(disable : 4996)
  13294. #endif
  13295. dwVersion = GetVersion();
  13296. #ifdef _MSC_VER
  13297. #pragma warning(pop)
  13298. #endif
  13299. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  13300. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  13301. mg_snprintf(NULL,
  13302. NULL,
  13303. block,
  13304. sizeof(block),
  13305. "Windows %u.%u%s",
  13306. (unsigned)dwMajorVersion,
  13307. (unsigned)dwMinorVersion,
  13308. eol);
  13309. system_info_length += (int)strlen(block);
  13310. if (system_info_length < buflen) {
  13311. strcat(buffer, block);
  13312. }
  13313. mg_snprintf(NULL,
  13314. NULL,
  13315. block,
  13316. sizeof(block),
  13317. "CPU: type %u, cores %u, mask %x%s",
  13318. (unsigned)si.wProcessorArchitecture,
  13319. (unsigned)si.dwNumberOfProcessors,
  13320. (unsigned)si.dwActiveProcessorMask,
  13321. eol);
  13322. system_info_length += (int)strlen(block);
  13323. if (system_info_length < buflen) {
  13324. strcat(buffer, block);
  13325. }
  13326. #else
  13327. mg_snprintf(NULL, NULL, block, sizeof(block), "%s - Symbian%s", eol);
  13328. system_info_length += (int)strlen(block);
  13329. if (system_info_length < buflen) {
  13330. strcat(buffer, block);
  13331. }
  13332. #endif
  13333. #else
  13334. struct utsname name;
  13335. memset(&name, 0, sizeof(name));
  13336. uname(&name);
  13337. mg_snprintf(NULL,
  13338. NULL,
  13339. block,
  13340. sizeof(block),
  13341. "%s %s (%s) - %s%s",
  13342. name.sysname,
  13343. name.version,
  13344. name.release,
  13345. name.machine,
  13346. eol);
  13347. system_info_length += (int)strlen(block);
  13348. if (system_info_length < buflen) {
  13349. strcat(buffer, block);
  13350. }
  13351. #endif
  13352. }
  13353. /* Features */
  13354. {
  13355. mg_snprintf(NULL,
  13356. NULL,
  13357. block,
  13358. sizeof(block),
  13359. "Features: %X%s%s%s%s%s%s%s%s%s%s",
  13360. mg_check_feature(0xFFFFFFFFu),
  13361. eol,
  13362. mg_check_feature(1) ? " Files" : "",
  13363. mg_check_feature(2) ? " HTTPS" : "",
  13364. mg_check_feature(4) ? " CGI" : "",
  13365. mg_check_feature(8) ? " IPv6" : "",
  13366. mg_check_feature(16) ? " WebSockets" : "",
  13367. mg_check_feature(32) ? " Lua" : "",
  13368. mg_check_feature(64) ? " JavaScript" : "",
  13369. mg_check_feature(128) ? " Cache" : "",
  13370. eol);
  13371. system_info_length += (int)strlen(block);
  13372. if (system_info_length < buflen) {
  13373. strcat(buffer, block);
  13374. }
  13375. #ifdef USE_LUA
  13376. mg_snprintf(NULL,
  13377. NULL,
  13378. block,
  13379. sizeof(block),
  13380. "Lua Version: %u (%s)%s",
  13381. (unsigned)LUA_VERSION_NUM,
  13382. LUA_RELEASE,
  13383. eol);
  13384. system_info_length += (int)strlen(block);
  13385. if (system_info_length < buflen) {
  13386. strcat(buffer, block);
  13387. }
  13388. #endif
  13389. #if defined(USE_DUKTAPE)
  13390. mg_snprintf(NULL,
  13391. NULL,
  13392. block,
  13393. sizeof(block),
  13394. "JavaScript: Duktape %u.%u.%u%s",
  13395. (unsigned)DUK_VERSION / 10000,
  13396. ((unsigned)DUK_VERSION / 100) % 100,
  13397. (unsigned)DUK_VERSION % 100,
  13398. eol);
  13399. system_info_length += (int)strlen(block);
  13400. if (system_info_length < buflen) {
  13401. strcat(buffer, block);
  13402. }
  13403. #endif
  13404. }
  13405. /* Build date */
  13406. {
  13407. mg_snprintf(
  13408. NULL, NULL, block, sizeof(block), "Build: %s%s", __DATE__, eol);
  13409. system_info_length += (int)strlen(block);
  13410. if (system_info_length < buflen) {
  13411. strcat(buffer, block);
  13412. }
  13413. }
  13414. /* Compiler information */
  13415. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  13416. {
  13417. #if defined(_MSC_VER)
  13418. mg_snprintf(NULL,
  13419. NULL,
  13420. block,
  13421. sizeof(block),
  13422. "MSC: %u (%u)%s",
  13423. (unsigned)_MSC_VER,
  13424. (unsigned)_MSC_FULL_VER,
  13425. eol);
  13426. system_info_length += (int)strlen(block);
  13427. if (system_info_length < buflen) {
  13428. strcat(buffer, block);
  13429. }
  13430. #elif defined(__MINGW64__)
  13431. mg_snprintf(NULL,
  13432. NULL,
  13433. block,
  13434. sizeof(block),
  13435. "MinGW64: %u.%u%s",
  13436. (unsigned)__MINGW64_VERSION_MAJOR,
  13437. (unsigned)__MINGW64_VERSION_MINOR,
  13438. eol);
  13439. system_info_length += (int)strlen(block);
  13440. if (system_info_length < buflen) {
  13441. strcat(buffer, block);
  13442. }
  13443. mg_snprintf(NULL,
  13444. NULL,
  13445. block,
  13446. sizeof(block),
  13447. "MinGW32: %u.%u%s",
  13448. (unsigned)__MINGW32_MAJOR_VERSION,
  13449. (unsigned)__MINGW32_MINOR_VERSION,
  13450. eol);
  13451. system_info_length += (int)strlen(block);
  13452. if (system_info_length < buflen) {
  13453. strcat(buffer, block);
  13454. }
  13455. #elif defined(__MINGW32__)
  13456. mg_snprintf(NULL,
  13457. NULL,
  13458. block,
  13459. sizeof(block),
  13460. "MinGW32: %u.%u%s",
  13461. (unsigned)__MINGW32_MAJOR_VERSION,
  13462. (unsigned)__MINGW32_MINOR_VERSION,
  13463. eol);
  13464. system_info_length += (int)strlen(block);
  13465. if (system_info_length < buflen) {
  13466. strcat(buffer, block);
  13467. }
  13468. #elif defined(__clang__)
  13469. mg_snprintf(NULL,
  13470. NULL,
  13471. block,
  13472. sizeof(block),
  13473. "clang: %u.%u.%u (%s)%s",
  13474. __clang_major__,
  13475. __clang_minor__,
  13476. __clang_patchlevel__,
  13477. __clang_version__,
  13478. eol);
  13479. system_info_length += (int)strlen(block);
  13480. if (system_info_length < buflen) {
  13481. strcat(buffer, block);
  13482. }
  13483. #elif defined(__GNUC__)
  13484. mg_snprintf(NULL,
  13485. NULL,
  13486. block,
  13487. sizeof(block),
  13488. "gcc: %u.%u.%u%s",
  13489. (unsigned)__GNUC__,
  13490. (unsigned)__GNUC_MINOR__,
  13491. (unsigned)__GNUC_PATCHLEVEL__,
  13492. eol);
  13493. system_info_length += (int)strlen(block);
  13494. if (system_info_length < buflen) {
  13495. strcat(buffer, block);
  13496. }
  13497. #elif defined(__INTEL_COMPILER)
  13498. mg_snprintf(NULL,
  13499. NULL,
  13500. block,
  13501. sizeof(block),
  13502. "Intel C/C++: %u%s",
  13503. (unsigned)__INTEL_COMPILER,
  13504. eol);
  13505. system_info_length += (int)strlen(block);
  13506. if (system_info_length < buflen) {
  13507. strcat(buffer, block);
  13508. }
  13509. #elif defined(__BORLANDC__)
  13510. mg_snprintf(NULL,
  13511. NULL,
  13512. block,
  13513. sizeof(block),
  13514. "Borland C: 0x%x%s",
  13515. (unsigned)__BORLANDC__,
  13516. eol);
  13517. system_info_length += (int)strlen(block);
  13518. if (system_info_length < buflen) {
  13519. strcat(buffer, block);
  13520. }
  13521. #elif defined(__SUNPRO_C)
  13522. mg_snprintf(NULL,
  13523. NULL,
  13524. block,
  13525. sizeof(block),
  13526. "Solaris: 0x%x%s",
  13527. (unsigned)__SUNPRO_C,
  13528. eol);
  13529. system_info_length += (int)strlen(block);
  13530. if (system_info_length < buflen) {
  13531. strcat(buffer, block);
  13532. }
  13533. #else
  13534. mg_snprintf(NULL, NULL, block, sizeof(block), "Other compiler%s", eol);
  13535. system_info_length += (int)strlen(block);
  13536. if (system_info_length < buflen) {
  13537. strcat(buffer, block);
  13538. }
  13539. #endif
  13540. }
  13541. /* Determine 32/64 bit data mode.
  13542. * see https://en.wikipedia.org/wiki/64-bit_computing */
  13543. {
  13544. mg_snprintf(NULL,
  13545. NULL,
  13546. block,
  13547. sizeof(block),
  13548. "Data model: int:%u/%u/%u/%u, float:%u/%u/%u, char:%u/%u, "
  13549. "ptr:%u, size:%u, time:%u%s",
  13550. (unsigned)sizeof(short),
  13551. (unsigned)sizeof(int),
  13552. (unsigned)sizeof(long),
  13553. (unsigned)sizeof(long long),
  13554. (unsigned)sizeof(float),
  13555. (unsigned)sizeof(double),
  13556. (unsigned)sizeof(long double),
  13557. (unsigned)sizeof(char),
  13558. (unsigned)sizeof(wchar_t),
  13559. (unsigned)sizeof(void *),
  13560. (unsigned)sizeof(size_t),
  13561. (unsigned)sizeof(time_t),
  13562. eol);
  13563. system_info_length += (int)strlen(block);
  13564. if (system_info_length < buflen) {
  13565. strcat(buffer, block);
  13566. }
  13567. }
  13568. return system_info_length;
  13569. }
  13570. /* Get system information. It can be printed or stored by the caller.
  13571. * Return the size of available information. */
  13572. int
  13573. mg_get_system_info(char *buffer, int buflen)
  13574. {
  13575. if ((buffer == NULL) || (buflen < 1)) {
  13576. return mg_get_system_info_impl(NULL, 0);
  13577. } else {
  13578. /* Reset buffer, so we can always use strcat. */
  13579. buffer[0] = 0;
  13580. return mg_get_system_info_impl(buffer, buflen);
  13581. }
  13582. }
  13583. /* mg_init_library counter */
  13584. static int mg_init_library_called = 0;
  13585. #if !defined(NO_SSL)
  13586. static int mg_ssl_initialized = 0;
  13587. #endif
  13588. /* Initialize this library. This function does not need to be thread safe. */
  13589. unsigned
  13590. mg_init_library(unsigned features)
  13591. {
  13592. #if !defined(NO_SSL)
  13593. char ebuf[128];
  13594. #endif
  13595. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  13596. unsigned features_inited = features_to_init;
  13597. #if !defined(NO_SSL)
  13598. if (features_to_init & 2) {
  13599. if (!mg_ssl_initialized) {
  13600. if (initialize_ssl(ebuf, sizeof(ebuf))) {
  13601. mg_ssl_initialized = 1;
  13602. } else {
  13603. (void)ebuf;
  13604. /* TODO: print error */
  13605. features_inited &= ~(2u);
  13606. }
  13607. } else {
  13608. /* ssl already initialized */
  13609. }
  13610. }
  13611. #endif
  13612. /* Start Windows. */
  13613. if (mg_init_library_called <= 0) {
  13614. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13615. WSADATA data;
  13616. WSAStartup(MAKEWORD(2, 2), &data);
  13617. #endif /* _WIN32 && !__SYMBIAN32__ */
  13618. mg_init_library_called = 1;
  13619. } else {
  13620. mg_init_library_called++;
  13621. }
  13622. return features_inited;
  13623. }
  13624. /* Un-initialize this library. */
  13625. unsigned
  13626. mg_exit_library(void)
  13627. {
  13628. if (mg_init_library_called <= 0) {
  13629. return 0;
  13630. }
  13631. mg_init_library_called--;
  13632. if (mg_init_library_called == 0) {
  13633. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13634. (void)WSACleanup();
  13635. #endif /* _WIN32 && !__SYMBIAN32__ */
  13636. #if !defined(NO_SSL)
  13637. if (mg_ssl_initialized) {
  13638. uninitialize_ssl();
  13639. mg_ssl_initialized = 0;
  13640. }
  13641. #endif
  13642. }
  13643. return 1;
  13644. }
  13645. /* End of civetweb.c */