civetweb.c 405 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348
  1. /* Copyright (c) 2013-2017 the Civetweb developers
  2. * Copyright (c) 2004-2013 Sergey Lyubka
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. * THE SOFTWARE.
  21. */
  22. #if defined(_WIN32)
  23. #if !defined(_CRT_SECURE_NO_WARNINGS)
  24. #define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */
  25. #endif
  26. #ifndef _WIN32_WINNT /* defined for tdm-gcc so we can use getnameinfo */
  27. #define _WIN32_WINNT 0x0501
  28. #endif
  29. #else
  30. #if defined(__GNUC__) && !defined(_GNU_SOURCE)
  31. #define _GNU_SOURCE /* for setgroups() */
  32. #endif
  33. #if defined(__linux__) && !defined(_XOPEN_SOURCE)
  34. #define _XOPEN_SOURCE 600 /* For flockfile() on Linux */
  35. #endif
  36. #ifndef _LARGEFILE_SOURCE
  37. #define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
  38. #endif
  39. #ifndef _FILE_OFFSET_BITS
  40. #define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
  41. #endif
  42. #ifndef __STDC_FORMAT_MACROS
  43. #define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
  44. #endif
  45. #ifndef __STDC_LIMIT_MACROS
  46. #define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
  47. #endif
  48. #ifdef __sun
  49. #define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */
  50. #define __inline inline /* not recognized on older compiler versions */
  51. #endif
  52. #endif
  53. #if defined(USE_LUA)
  54. #define USE_TIMERS
  55. #endif
  56. #if defined(_MSC_VER)
  57. /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
  58. #pragma warning(disable : 4306)
  59. /* conditional expression is constant: introduced by FD_SET(..) */
  60. #pragma warning(disable : 4127)
  61. /* non-constant aggregate initializer: issued due to missing C99 support */
  62. #pragma warning(disable : 4204)
  63. /* padding added after data member */
  64. #pragma warning(disable : 4820)
  65. /* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
  66. #pragma warning(disable : 4668)
  67. /* no function prototype given: converting '()' to '(void)' */
  68. #pragma warning(disable : 4255)
  69. /* function has been selected for automatic inline expansion */
  70. #pragma warning(disable : 4711)
  71. #endif
  72. /* This code uses static_assert to check some conditions.
  73. * Unfortunately some compilers still do not support it, so we have a
  74. * replacement function here. */
  75. #if defined(_MSC_VER) && (_MSC_VER >= 1600)
  76. #define mg_static_assert static_assert
  77. #elif defined(__cplusplus) && (__cplusplus >= 201103L)
  78. #define mg_static_assert static_assert
  79. #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)
  80. #define mg_static_assert _Static_assert
  81. #else
  82. char static_assert_replacement[1];
  83. #define mg_static_assert(cond, txt) \
  84. extern char static_assert_replacement[(cond) ? 1 : -1]
  85. #endif
  86. mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
  87. "int data type size check");
  88. mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
  89. "pointer data type size check");
  90. mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
  91. /* DTL -- including winsock2.h works better if lean and mean */
  92. #ifndef WIN32_LEAN_AND_MEAN
  93. #define WIN32_LEAN_AND_MEAN
  94. #endif
  95. #if defined(__SYMBIAN32__)
  96. #define NO_SSL /* SSL is not supported */
  97. #define NO_CGI /* CGI is not supported */
  98. #define PATH_MAX FILENAME_MAX
  99. #endif /* __SYMBIAN32__ */
  100. #ifndef CIVETWEB_HEADER_INCLUDED
  101. /* Include the header file here, so the CivetWeb interface is defined for the
  102. * entire implementation, including the following forward definitions. */
  103. #include "civetweb.h"
  104. #endif
  105. #ifndef IGNORE_UNUSED_RESULT
  106. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  107. #endif
  108. #ifndef _WIN32_WCE /* Some ANSI #includes are not available on Windows CE */
  109. #include <sys/types.h>
  110. #include <sys/stat.h>
  111. #include <errno.h>
  112. #include <signal.h>
  113. #include <fcntl.h>
  114. #endif /* !_WIN32_WCE */
  115. #ifdef __clang__
  116. /* When using -Weverything, clang does not accept it's own headers
  117. * in a release build configuration. Disable what is too much in
  118. * -Weverything. */
  119. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  120. #endif
  121. #ifdef __MACH__ /* Apple OSX section */
  122. #ifdef __clang__
  123. /* Avoid warnings for Xopen 7.00 and higher */
  124. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  125. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  126. #endif
  127. #define CLOCK_MONOTONIC (1)
  128. #define CLOCK_REALTIME (2)
  129. #include <sys/errno.h>
  130. #include <sys/time.h>
  131. #include <mach/clock.h>
  132. #include <mach/mach.h>
  133. #include <mach/mach_time.h>
  134. #include <assert.h>
  135. /* clock_gettime is not implemented on OSX prior to 10.12 */
  136. static int
  137. _civet_clock_gettime(int clk_id, struct timespec *t)
  138. {
  139. memset(t, 0, sizeof(*t));
  140. if (clk_id == CLOCK_REALTIME) {
  141. struct timeval now;
  142. int rv = gettimeofday(&now, NULL);
  143. if (rv) {
  144. return rv;
  145. }
  146. t->tv_sec = now.tv_sec;
  147. t->tv_nsec = now.tv_usec * 1000;
  148. return 0;
  149. } else if (clk_id == CLOCK_MONOTONIC) {
  150. static uint64_t clock_start_time = 0;
  151. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  152. uint64_t now = mach_absolute_time();
  153. if (clock_start_time == 0) {
  154. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  155. #if defined(DEBUG)
  156. assert(mach_status == KERN_SUCCESS);
  157. #else
  158. /* appease "unused variable" warning for release builds */
  159. (void)mach_status;
  160. #endif
  161. clock_start_time = now;
  162. }
  163. now = (uint64_t)((double)(now - clock_start_time)
  164. * (double)timebase_ifo.numer
  165. / (double)timebase_ifo.denom);
  166. t->tv_sec = now / 1000000000;
  167. t->tv_nsec = now % 1000000000;
  168. return 0;
  169. }
  170. return -1; /* EINVAL - Clock ID is unknown */
  171. }
  172. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  173. #ifdef __CLOCK_AVAILABILITY
  174. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  175. * declared but it may be NULL at runtime. So we need to check before using
  176. * it. */
  177. static int
  178. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  179. {
  180. if (clock_gettime) {
  181. return clock_gettime(clk_id, t);
  182. }
  183. return _civet_clock_gettime(clk_id, t);
  184. }
  185. #define clock_gettime _civet_safe_clock_gettime
  186. #else
  187. #define clock_gettime _civet_clock_gettime
  188. #endif
  189. #endif
  190. #include <time.h>
  191. #include <stdlib.h>
  192. #include <stdarg.h>
  193. #include <assert.h>
  194. #include <string.h>
  195. #include <ctype.h>
  196. #include <limits.h>
  197. #include <stddef.h>
  198. #include <stdio.h>
  199. #include <stdint.h>
  200. #ifndef INT64_MAX
  201. #define INT64_MAX (9223372036854775807)
  202. #endif
  203. #ifndef MAX_WORKER_THREADS
  204. #define MAX_WORKER_THREADS (1024 * 64)
  205. #endif
  206. #ifndef SOCKET_TIMEOUT_QUANTUM /* in ms */
  207. #define SOCKET_TIMEOUT_QUANTUM (2000)
  208. #endif
  209. #define SHUTDOWN_RD (0)
  210. #define SHUTDOWN_WR (1)
  211. #define SHUTDOWN_BOTH (2)
  212. mg_static_assert(MAX_WORKER_THREADS >= 1,
  213. "worker threads must be a positive number");
  214. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  215. "size_t data type size check");
  216. #if defined(_WIN32) \
  217. && !defined(__SYMBIAN32__) /* WINDOWS / UNIX include block */
  218. #include <windows.h>
  219. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  220. #include <ws2tcpip.h>
  221. typedef const char *SOCK_OPT_TYPE;
  222. #if !defined(PATH_MAX)
  223. #define PATH_MAX (MAX_PATH)
  224. #endif
  225. #if !defined(PATH_MAX)
  226. #define PATH_MAX (4096)
  227. #endif
  228. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  229. #ifndef _IN_PORT_T
  230. #ifndef in_port_t
  231. #define in_port_t u_short
  232. #endif
  233. #endif
  234. #ifndef _WIN32_WCE
  235. #include <process.h>
  236. #include <direct.h>
  237. #include <io.h>
  238. #else /* _WIN32_WCE */
  239. #define NO_CGI /* WinCE has no pipes */
  240. #define NO_POPEN /* WinCE has no popen */
  241. typedef long off_t;
  242. #define errno ((int)(GetLastError()))
  243. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  244. #endif /* _WIN32_WCE */
  245. #define MAKEUQUAD(lo, hi) \
  246. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  247. #define RATE_DIFF (10000000) /* 100 nsecs */
  248. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  249. #define SYS2UNIX_TIME(lo, hi) \
  250. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  251. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  252. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  253. * Also use _strtoui64 on modern M$ compilers */
  254. #if defined(_MSC_VER)
  255. #if (_MSC_VER < 1300)
  256. #define STRX(x) #x
  257. #define STR(x) STRX(x)
  258. #define __func__ __FILE__ ":" STR(__LINE__)
  259. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  260. #define strtoll(x, y, z) (_atoi64(x))
  261. #else
  262. #define __func__ __FUNCTION__
  263. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  264. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  265. #endif
  266. #endif /* _MSC_VER */
  267. #define ERRNO ((int)(GetLastError()))
  268. #define NO_SOCKLEN_T
  269. #if defined(_WIN64) || defined(__MINGW64__)
  270. #define SSL_LIB "ssleay64.dll"
  271. #define CRYPTO_LIB "libeay64.dll"
  272. #else
  273. #define SSL_LIB "ssleay32.dll"
  274. #define CRYPTO_LIB "libeay32.dll"
  275. #endif
  276. #define O_NONBLOCK (0)
  277. #ifndef W_OK
  278. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  279. #endif
  280. #if !defined(EWOULDBLOCK)
  281. #define EWOULDBLOCK WSAEWOULDBLOCK
  282. #endif /* !EWOULDBLOCK */
  283. #define _POSIX_
  284. #define INT64_FMT "I64d"
  285. #define UINT64_FMT "I64u"
  286. #define WINCDECL __cdecl
  287. #define vsnprintf_impl _vsnprintf
  288. #define access _access
  289. #define mg_sleep(x) (Sleep(x))
  290. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  291. #ifndef popen
  292. #define popen(x, y) (_popen(x, y))
  293. #endif
  294. #ifndef pclose
  295. #define pclose(x) (_pclose(x))
  296. #endif
  297. #define close(x) (_close(x))
  298. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  299. #define RTLD_LAZY (0)
  300. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  301. #define fdopen(x, y) (_fdopen((x), (y)))
  302. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  303. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  304. #define flockfile(x) (EnterCriticalSection(&global_log_file_lock))
  305. #define funlockfile(x) (LeaveCriticalSection(&global_log_file_lock))
  306. #define sleep(x) (Sleep((x)*1000))
  307. #define rmdir(x) (_rmdir(x))
  308. #define timegm(x) (_mkgmtime(x))
  309. #if !defined(fileno)
  310. #define fileno(x) (_fileno(x))
  311. #endif /* !fileno MINGW #defines fileno */
  312. typedef HANDLE pthread_mutex_t;
  313. typedef DWORD pthread_key_t;
  314. typedef HANDLE pthread_t;
  315. typedef struct {
  316. CRITICAL_SECTION threadIdSec;
  317. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  318. } pthread_cond_t;
  319. #ifndef __clockid_t_defined
  320. typedef DWORD clockid_t;
  321. #endif
  322. #ifndef CLOCK_MONOTONIC
  323. #define CLOCK_MONOTONIC (1)
  324. #endif
  325. #ifndef CLOCK_REALTIME
  326. #define CLOCK_REALTIME (2)
  327. #endif
  328. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  329. #define _TIMESPEC_DEFINED
  330. #endif
  331. #ifndef _TIMESPEC_DEFINED
  332. struct timespec {
  333. time_t tv_sec; /* seconds */
  334. long tv_nsec; /* nanoseconds */
  335. };
  336. #endif
  337. #if !defined(WIN_PTHREADS_TIME_H)
  338. #define MUST_IMPLEMENT_CLOCK_GETTIME
  339. #endif
  340. #ifdef MUST_IMPLEMENT_CLOCK_GETTIME
  341. #define clock_gettime mg_clock_gettime
  342. static int
  343. clock_gettime(clockid_t clk_id, struct timespec *tp)
  344. {
  345. FILETIME ft;
  346. ULARGE_INTEGER li;
  347. BOOL ok = FALSE;
  348. double d;
  349. static double perfcnt_per_sec = 0.0;
  350. if (tp) {
  351. memset(tp, 0, sizeof(*tp));
  352. if (clk_id == CLOCK_REALTIME) {
  353. GetSystemTimeAsFileTime(&ft);
  354. li.LowPart = ft.dwLowDateTime;
  355. li.HighPart = ft.dwHighDateTime;
  356. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  357. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  358. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  359. ok = TRUE;
  360. } else if (clk_id == CLOCK_MONOTONIC) {
  361. if (perfcnt_per_sec == 0.0) {
  362. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  363. perfcnt_per_sec = 1.0 / li.QuadPart;
  364. }
  365. if (perfcnt_per_sec != 0.0) {
  366. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  367. d = li.QuadPart * perfcnt_per_sec;
  368. tp->tv_sec = (time_t)d;
  369. d -= tp->tv_sec;
  370. tp->tv_nsec = (long)(d * 1.0E9);
  371. ok = TRUE;
  372. }
  373. }
  374. }
  375. return ok ? 0 : -1;
  376. }
  377. #endif
  378. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  379. static int pthread_mutex_lock(pthread_mutex_t *);
  380. static int pthread_mutex_unlock(pthread_mutex_t *);
  381. static void path_to_unicode(const struct mg_connection *conn,
  382. const char *path,
  383. wchar_t *wbuf,
  384. size_t wbuf_len);
  385. /* All file operations need to be rewritten to solve #246. */
  386. #include "file_ops.inl"
  387. struct mg_file;
  388. static const char *
  389. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p);
  390. /* POSIX dirent interface */
  391. struct dirent {
  392. char d_name[PATH_MAX];
  393. };
  394. typedef struct DIR {
  395. HANDLE handle;
  396. WIN32_FIND_DATAW info;
  397. struct dirent result;
  398. } DIR;
  399. #if defined(_WIN32) && !defined(POLLIN)
  400. #ifndef HAVE_POLL
  401. struct pollfd {
  402. SOCKET fd;
  403. short events;
  404. short revents;
  405. };
  406. #define POLLIN (0x0300)
  407. #endif
  408. #endif
  409. /* Mark required libraries */
  410. #if defined(_MSC_VER)
  411. #pragma comment(lib, "Ws2_32.lib")
  412. #endif
  413. #else /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  414. WINDOWS / UNIX include block */
  415. #include <sys/wait.h>
  416. #include <sys/socket.h>
  417. #include <sys/poll.h>
  418. #include <netinet/in.h>
  419. #include <arpa/inet.h>
  420. #include <sys/time.h>
  421. #include <sys/utsname.h>
  422. #include <stdint.h>
  423. #include <inttypes.h>
  424. #include <netdb.h>
  425. #include <netinet/tcp.h>
  426. typedef const void *SOCK_OPT_TYPE;
  427. #if defined(ANDROID)
  428. typedef unsigned short int in_port_t;
  429. #endif
  430. #include <pwd.h>
  431. #include <unistd.h>
  432. #include <grp.h>
  433. #include <dirent.h>
  434. #define vsnprintf_impl vsnprintf
  435. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  436. #include <dlfcn.h>
  437. #endif
  438. #include <pthread.h>
  439. #if defined(__MACH__)
  440. #define SSL_LIB "libssl.dylib"
  441. #define CRYPTO_LIB "libcrypto.dylib"
  442. #else
  443. #if !defined(SSL_LIB)
  444. #define SSL_LIB "libssl.so"
  445. #endif
  446. #if !defined(CRYPTO_LIB)
  447. #define CRYPTO_LIB "libcrypto.so"
  448. #endif
  449. #endif
  450. #ifndef O_BINARY
  451. #define O_BINARY (0)
  452. #endif /* O_BINARY */
  453. #define closesocket(a) (close(a))
  454. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  455. #define mg_remove(conn, x) (remove(x))
  456. #define mg_sleep(x) (usleep((x)*1000))
  457. #define mg_opendir(conn, x) (opendir(x))
  458. #define mg_closedir(x) (closedir(x))
  459. #define mg_readdir(x) (readdir(x))
  460. #define ERRNO (errno)
  461. #define INVALID_SOCKET (-1)
  462. #define INT64_FMT PRId64
  463. #define UINT64_FMT PRIu64
  464. typedef int SOCKET;
  465. #define WINCDECL
  466. #if defined(__hpux)
  467. /* HPUX 11 does not have monotonic, fall back to realtime */
  468. #ifndef CLOCK_MONOTONIC
  469. #define CLOCK_MONOTONIC CLOCK_REALTIME
  470. #endif
  471. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  472. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  473. * the prototypes use int* rather than socklen_t* which matches the
  474. * actual library expectation. When called with the wrong size arg
  475. * accept() returns a zero client inet addr and check_acl() always
  476. * fails. Since socklen_t is widely used below, just force replace
  477. * their typedef with int. - DTL
  478. */
  479. #define socklen_t int
  480. #endif /* hpux */
  481. #endif /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  482. WINDOWS / UNIX include block */
  483. /* va_copy should always be a macro, C99 and C++11 - DTL */
  484. #ifndef va_copy
  485. #define va_copy(x, y) ((x) = (y))
  486. #endif
  487. #ifdef _WIN32
  488. /* Create substitutes for POSIX functions in Win32. */
  489. #if defined(__MINGW32__)
  490. /* Show no warning in case system functions are not used. */
  491. #pragma GCC diagnostic push
  492. #pragma GCC diagnostic ignored "-Wunused-function"
  493. #endif
  494. static CRITICAL_SECTION global_log_file_lock;
  495. static DWORD
  496. pthread_self(void)
  497. {
  498. return GetCurrentThreadId();
  499. }
  500. static int
  501. pthread_key_create(
  502. pthread_key_t *key,
  503. void (*_ignored)(void *) /* destructor not supported for Windows */
  504. )
  505. {
  506. (void)_ignored;
  507. if ((key != 0)) {
  508. *key = TlsAlloc();
  509. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  510. }
  511. return -2;
  512. }
  513. static int
  514. pthread_key_delete(pthread_key_t key)
  515. {
  516. return TlsFree(key) ? 0 : 1;
  517. }
  518. static int
  519. pthread_setspecific(pthread_key_t key, void *value)
  520. {
  521. return TlsSetValue(key, value) ? 0 : 1;
  522. }
  523. static void *
  524. pthread_getspecific(pthread_key_t key)
  525. {
  526. return TlsGetValue(key);
  527. }
  528. #if defined(__MINGW32__)
  529. /* Enable unused function warning again */
  530. #pragma GCC diagnostic pop
  531. #endif
  532. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  533. #else
  534. static pthread_mutexattr_t pthread_mutex_attr;
  535. #endif /* _WIN32 */
  536. #define PASSWORDS_FILE_NAME ".htpasswd"
  537. #define CGI_ENVIRONMENT_SIZE (4096)
  538. #define MAX_CGI_ENVIR_VARS (256)
  539. #define MG_BUF_LEN (8192)
  540. #ifndef MAX_REQUEST_SIZE
  541. #define MAX_REQUEST_SIZE (16384)
  542. #endif
  543. mg_static_assert(MAX_REQUEST_SIZE >= 256,
  544. "request size length must be a positive number");
  545. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  546. #if defined(_WIN32_WCE)
  547. /* Create substitutes for POSIX functions in Win32. */
  548. #if defined(__MINGW32__)
  549. /* Show no warning in case system functions are not used. */
  550. #pragma GCC diagnostic push
  551. #pragma GCC diagnostic ignored "-Wunused-function"
  552. #endif
  553. static time_t
  554. time(time_t *ptime)
  555. {
  556. time_t t;
  557. SYSTEMTIME st;
  558. FILETIME ft;
  559. GetSystemTime(&st);
  560. SystemTimeToFileTime(&st, &ft);
  561. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  562. if (ptime != NULL) {
  563. *ptime = t;
  564. }
  565. return t;
  566. }
  567. static struct tm *
  568. localtime_s(const time_t *ptime, struct tm *ptm)
  569. {
  570. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  571. FILETIME ft, lft;
  572. SYSTEMTIME st;
  573. TIME_ZONE_INFORMATION tzinfo;
  574. if (ptm == NULL) {
  575. return NULL;
  576. }
  577. *(int64_t *)&ft = t;
  578. FileTimeToLocalFileTime(&ft, &lft);
  579. FileTimeToSystemTime(&lft, &st);
  580. ptm->tm_year = st.wYear - 1900;
  581. ptm->tm_mon = st.wMonth - 1;
  582. ptm->tm_wday = st.wDayOfWeek;
  583. ptm->tm_mday = st.wDay;
  584. ptm->tm_hour = st.wHour;
  585. ptm->tm_min = st.wMinute;
  586. ptm->tm_sec = st.wSecond;
  587. ptm->tm_yday = 0; /* hope nobody uses this */
  588. ptm->tm_isdst =
  589. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  590. return ptm;
  591. }
  592. static struct tm *
  593. gmtime_s(const time_t *ptime, struct tm *ptm)
  594. {
  595. /* FIXME(lsm): fix this. */
  596. return localtime_s(ptime, ptm);
  597. }
  598. static int mg_atomic_inc(volatile int *addr);
  599. static struct tm tm_array[MAX_WORKER_THREADS];
  600. static int tm_index = 0;
  601. static struct tm *
  602. localtime(const time_t *ptime)
  603. {
  604. int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0]));
  605. return localtime_s(ptime, tm_array + i);
  606. }
  607. static struct tm *
  608. gmtime(const time_t *ptime)
  609. {
  610. int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  611. return gmtime_s(ptime, tm_array + i);
  612. }
  613. static size_t
  614. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  615. {
  616. /* TODO: (void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  617. * for WinCE"); */
  618. return 0;
  619. }
  620. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  621. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  622. #define remove(f) mg_remove(NULL, f)
  623. static int
  624. rename(const char *a, const char *b)
  625. {
  626. wchar_t wa[PATH_MAX];
  627. wchar_t wb[PATH_MAX];
  628. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  629. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  630. return MoveFileW(wa, wb) ? 0 : -1;
  631. }
  632. struct stat {
  633. int64_t st_size;
  634. time_t st_mtime;
  635. };
  636. static int
  637. stat(const char *name, struct stat *st)
  638. {
  639. wchar_t wbuf[PATH_MAX];
  640. WIN32_FILE_ATTRIBUTE_DATA attr;
  641. time_t creation_time, write_time;
  642. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  643. memset(&attr, 0, sizeof(attr));
  644. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  645. st->st_size =
  646. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  647. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  648. attr.ftLastWriteTime.dwHighDateTime);
  649. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  650. attr.ftCreationTime.dwHighDateTime);
  651. if (creation_time > write_time) {
  652. st->st_mtime = creation_time;
  653. } else {
  654. st->st_mtime = write_time;
  655. }
  656. return 0;
  657. }
  658. #define access(x, a) 1 /* not required anyway */
  659. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  660. /* Values from errno.h in Windows SDK (Visual Studio). */
  661. #define EEXIST 17
  662. #define EACCES 13
  663. #define ENOENT 2
  664. #if defined(__MINGW32__)
  665. /* Enable unused function warning again */
  666. #pragma GCC diagnostic pop
  667. #endif
  668. #endif /* defined(_WIN32_WCE) */
  669. static int
  670. mg_atomic_inc(volatile int *addr)
  671. {
  672. int ret;
  673. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  674. /* Depending on the SDK, this function uses either
  675. * (volatile unsigned int *) or (volatile LONG *),
  676. * so whatever you use, the other SDK is likely to raise a warning. */
  677. ret = InterlockedIncrement((volatile long *)addr);
  678. #elif defined(__GNUC__) \
  679. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  680. ret = __sync_add_and_fetch(addr, 1);
  681. #else
  682. ret = (++(*addr));
  683. #endif
  684. return ret;
  685. }
  686. static int
  687. mg_atomic_dec(volatile int *addr)
  688. {
  689. int ret;
  690. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  691. /* Depending on the SDK, this function uses either
  692. * (volatile unsigned int *) or (volatile LONG *),
  693. * so whatever you use, the other SDK is likely to raise a warning. */
  694. ret = InterlockedDecrement((volatile long *)addr);
  695. #elif defined(__GNUC__) \
  696. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  697. ret = __sync_sub_and_fetch(addr, 1);
  698. #else
  699. ret = (--(*addr));
  700. #endif
  701. return ret;
  702. }
  703. #if defined(MEMORY_DEBUGGING)
  704. static unsigned long mg_memory_debug_blockCount = 0;
  705. static unsigned long mg_memory_debug_totalMemUsed = 0;
  706. static void *
  707. mg_malloc_ex(size_t size, const char *file, unsigned line)
  708. {
  709. void *data = malloc(size + sizeof(size_t));
  710. void *memory = 0;
  711. char mallocStr[256];
  712. if (data) {
  713. *(size_t *)data = size;
  714. mg_memory_debug_totalMemUsed += size;
  715. mg_memory_debug_blockCount++;
  716. memory = (void *)(((char *)data) + sizeof(size_t));
  717. }
  718. sprintf(mallocStr,
  719. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  720. memory,
  721. (unsigned long)size,
  722. mg_memory_debug_totalMemUsed,
  723. mg_memory_debug_blockCount,
  724. file,
  725. line);
  726. #if defined(_WIN32)
  727. OutputDebugStringA(mallocStr);
  728. #else
  729. DEBUG_TRACE("%s", mallocStr);
  730. #endif
  731. return memory;
  732. }
  733. static void *
  734. mg_calloc_ex(size_t count, size_t size, const char *file, unsigned line)
  735. {
  736. void *data = mg_malloc_ex(size * count, file, line);
  737. if (data) {
  738. memset(data, 0, size * count);
  739. }
  740. return data;
  741. }
  742. static void
  743. mg_free_ex(void *memory, const char *file, unsigned line)
  744. {
  745. char mallocStr[256];
  746. void *data = (void *)(((char *)memory) - sizeof(size_t));
  747. size_t size;
  748. if (memory) {
  749. size = *(size_t *)data;
  750. mg_memory_debug_totalMemUsed -= size;
  751. mg_memory_debug_blockCount--;
  752. sprintf(mallocStr,
  753. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  754. memory,
  755. (unsigned long)size,
  756. mg_memory_debug_totalMemUsed,
  757. mg_memory_debug_blockCount,
  758. file,
  759. line);
  760. #if defined(_WIN32)
  761. OutputDebugStringA(mallocStr);
  762. #else
  763. DEBUG_TRACE("%s", mallocStr);
  764. #endif
  765. free(data);
  766. }
  767. }
  768. static void *
  769. mg_realloc_ex(void *memory, size_t newsize, const char *file, unsigned line)
  770. {
  771. char mallocStr[256];
  772. void *data;
  773. void *_realloc;
  774. size_t oldsize;
  775. if (newsize) {
  776. if (memory) {
  777. data = (void *)(((char *)memory) - sizeof(size_t));
  778. oldsize = *(size_t *)data;
  779. _realloc = realloc(data, newsize + sizeof(size_t));
  780. if (_realloc) {
  781. data = _realloc;
  782. mg_memory_debug_totalMemUsed -= oldsize;
  783. sprintf(mallocStr,
  784. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  785. memory,
  786. (unsigned long)oldsize,
  787. mg_memory_debug_totalMemUsed,
  788. mg_memory_debug_blockCount,
  789. file,
  790. line);
  791. #if defined(_WIN32)
  792. OutputDebugStringA(mallocStr);
  793. #else
  794. DEBUG_TRACE("%s", mallocStr);
  795. #endif
  796. mg_memory_debug_totalMemUsed += newsize;
  797. sprintf(mallocStr,
  798. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  799. memory,
  800. (unsigned long)newsize,
  801. mg_memory_debug_totalMemUsed,
  802. mg_memory_debug_blockCount,
  803. file,
  804. line);
  805. #if defined(_WIN32)
  806. OutputDebugStringA(mallocStr);
  807. #else
  808. DEBUG_TRACE("%s", mallocStr);
  809. #endif
  810. *(size_t *)data = newsize;
  811. data = (void *)(((char *)data) + sizeof(size_t));
  812. } else {
  813. #if defined(_WIN32)
  814. OutputDebugStringA("MEM: realloc failed\n");
  815. #else
  816. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  817. #endif
  818. return _realloc;
  819. }
  820. } else {
  821. data = mg_malloc_ex(newsize, file, line);
  822. }
  823. } else {
  824. data = 0;
  825. mg_free_ex(memory, file, line);
  826. }
  827. return data;
  828. }
  829. #define mg_malloc(a) mg_malloc_ex(a, __FILE__, __LINE__)
  830. #define mg_calloc(a, b) mg_calloc_ex(a, b, __FILE__, __LINE__)
  831. #define mg_realloc(a, b) mg_realloc_ex(a, b, __FILE__, __LINE__)
  832. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  833. #else
  834. static __inline void *
  835. mg_malloc(size_t a)
  836. {
  837. return malloc(a);
  838. }
  839. static __inline void *
  840. mg_calloc(size_t a, size_t b)
  841. {
  842. return calloc(a, b);
  843. }
  844. static __inline void *
  845. mg_realloc(void *a, size_t b)
  846. {
  847. return realloc(a, b);
  848. }
  849. static __inline void
  850. mg_free(void *a)
  851. {
  852. free(a);
  853. }
  854. #endif
  855. static void mg_vsnprintf(const struct mg_connection *conn,
  856. int *truncated,
  857. char *buf,
  858. size_t buflen,
  859. const char *fmt,
  860. va_list ap);
  861. static void mg_snprintf(const struct mg_connection *conn,
  862. int *truncated,
  863. char *buf,
  864. size_t buflen,
  865. PRINTF_FORMAT_STRING(const char *fmt),
  866. ...) PRINTF_ARGS(5, 6);
  867. /* This following lines are just meant as a reminder to use the mg-functions
  868. * for memory management */
  869. #ifdef malloc
  870. #undef malloc
  871. #endif
  872. #ifdef calloc
  873. #undef calloc
  874. #endif
  875. #ifdef realloc
  876. #undef realloc
  877. #endif
  878. #ifdef free
  879. #undef free
  880. #endif
  881. #ifdef snprintf
  882. #undef snprintf
  883. #endif
  884. #ifdef vsnprintf
  885. #undef vsnprintf
  886. #endif
  887. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  888. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  889. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  890. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  891. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  892. #ifdef _WIN32 /* vsnprintf must not be used in any system, * \ \ \ \
  893. * but this define only works well for Windows. */
  894. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  895. #endif
  896. static pthread_key_t sTlsKey; /* Thread local storage index */
  897. static int sTlsInit = 0;
  898. static int thread_idx_max = 0;
  899. struct mg_workerTLS {
  900. int is_master;
  901. unsigned long thread_idx;
  902. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  903. HANDLE pthread_cond_helper_mutex;
  904. struct mg_workerTLS *next_waiting_thread;
  905. #endif
  906. };
  907. #if defined(__GNUC__) || defined(__MINGW32__)
  908. /* Show no warning in case system functions are not used. */
  909. #pragma GCC diagnostic push
  910. #pragma GCC diagnostic ignored "-Wunused-function"
  911. #endif
  912. #if defined(__clang__)
  913. /* Show no warning in case system functions are not used. */
  914. #pragma clang diagnostic push
  915. #pragma clang diagnostic ignored "-Wunused-function"
  916. #endif
  917. /* Get a unique thread ID as unsigned long, independent from the data type
  918. * of thread IDs defined by the operating system API.
  919. * If two calls to mg_current_thread_id return the same value, they calls
  920. * are done from the same thread. If they return different values, they are
  921. * done from different threads. (Provided this function is used in the same
  922. * process context and threads are not repeatedly created and deleted, but
  923. * CivetWeb does not do that).
  924. * This function must match the signature required for SSL id callbacks:
  925. * CRYPTO_set_id_callback
  926. */
  927. static unsigned long
  928. mg_current_thread_id(void)
  929. {
  930. #ifdef _WIN32
  931. return GetCurrentThreadId();
  932. #else
  933. #ifdef __clang__
  934. #pragma clang diagnostic push
  935. #pragma clang diagnostic ignored "-Wunreachable-code"
  936. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  937. * or not, so one of the two conditions will be unreachable by construction.
  938. * Unfortunately the C standard does not define a way to check this at
  939. * compile time, since the #if preprocessor conditions can not use the sizeof
  940. * operator as an argument. */
  941. #endif
  942. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  943. /* This is the problematic case for CRYPTO_set_id_callback:
  944. * The OS pthread_t can not be cast to unsigned long. */
  945. struct mg_workerTLS *tls =
  946. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  947. if (tls == NULL) {
  948. /* SSL called from an unknown thread: Create some thread index.
  949. */
  950. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  951. tls->is_master = -2; /* -2 means "3rd party thread" */
  952. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  953. pthread_setspecific(sTlsKey, tls);
  954. }
  955. return tls->thread_idx;
  956. } else {
  957. /* pthread_t may be any data type, so a simple cast to unsigned long
  958. * can rise a warning/error, depending on the platform.
  959. * Here memcpy is used as an anything-to-anything cast. */
  960. unsigned long ret = 0;
  961. pthread_t t = pthread_self();
  962. memcpy(&ret, &t, sizeof(pthread_t));
  963. return ret;
  964. }
  965. #ifdef __clang__
  966. #pragma clang diagnostic pop
  967. #endif
  968. #endif
  969. }
  970. static uint64_t
  971. mg_get_current_time_ns()
  972. {
  973. struct timespec tsnow;
  974. clock_gettime(CLOCK_REALTIME, &tsnow);
  975. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  976. }
  977. #if defined(__GNUC__)
  978. /* Show no warning in case system functions are not used. */
  979. #pragma GCC diagnostic pop
  980. #endif
  981. #if defined(__clang__)
  982. /* Show no warning in case system functions are not used. */
  983. #pragma clang diagnostic pop
  984. #endif
  985. #if !defined(DEBUG_TRACE)
  986. #if defined(DEBUG)
  987. static void DEBUG_TRACE_FUNC(const char *func,
  988. unsigned line,
  989. PRINTF_FORMAT_STRING(const char *fmt),
  990. ...) PRINTF_ARGS(3, 4);
  991. static void
  992. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  993. {
  994. va_list args;
  995. uint64_t nsnow;
  996. static uint64_t nslast;
  997. struct timespec tsnow;
  998. /* Get some operating system independent thread id */
  999. unsigned long thread_id = mg_current_thread_id();
  1000. clock_gettime(CLOCK_REALTIME, &tsnow);
  1001. nsnow = ((uint64_t)tsnow.tv_sec) * ((uint64_t)1000000000)
  1002. + ((uint64_t)tsnow.tv_nsec);
  1003. if (!nslast) {
  1004. nslast = nsnow;
  1005. }
  1006. flockfile(stdout);
  1007. printf("*** %lu.%09lu %12" INT64_FMT " %lu %s:%u: ",
  1008. (unsigned long)tsnow.tv_sec,
  1009. (unsigned long)tsnow.tv_nsec,
  1010. nsnow - nslast,
  1011. thread_id,
  1012. func,
  1013. line);
  1014. va_start(args, fmt);
  1015. vprintf(fmt, args);
  1016. va_end(args);
  1017. putchar('\n');
  1018. fflush(stdout);
  1019. funlockfile(stdout);
  1020. nslast = nsnow;
  1021. }
  1022. #define DEBUG_TRACE(fmt, ...) \
  1023. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  1024. #else
  1025. #define DEBUG_TRACE(fmt, ...) \
  1026. do { \
  1027. } while (0)
  1028. #endif /* DEBUG */
  1029. #endif /* DEBUG_TRACE */
  1030. #define MD5_STATIC static
  1031. #include "md5.inl"
  1032. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1033. #ifdef NO_SOCKLEN_T
  1034. typedef int socklen_t;
  1035. #endif /* NO_SOCKLEN_T */
  1036. #define _DARWIN_UNLIMITED_SELECT
  1037. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1038. #if !defined(MSG_NOSIGNAL)
  1039. #define MSG_NOSIGNAL (0)
  1040. #endif
  1041. #if !defined(SOMAXCONN)
  1042. #define SOMAXCONN (100)
  1043. #endif
  1044. /* Size of the accepted socket queue */
  1045. #if !defined(MGSQLEN)
  1046. #define MGSQLEN (20)
  1047. #endif
  1048. #if defined(NO_SSL)
  1049. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1050. typedef struct SSL_CTX SSL_CTX;
  1051. #else
  1052. #if defined(NO_SSL_DL)
  1053. #include <openssl/ssl.h>
  1054. #include <openssl/err.h>
  1055. #include <openssl/crypto.h>
  1056. #include <openssl/x509.h>
  1057. #include <openssl/pem.h>
  1058. #include <openssl/engine.h>
  1059. #include <openssl/conf.h>
  1060. #include <openssl/dh.h>
  1061. #include <openssl/bn.h>
  1062. #include <openssl/opensslv.h>
  1063. #else
  1064. /* SSL loaded dynamically from DLL.
  1065. * I put the prototypes here to be independent from OpenSSL source
  1066. * installation. */
  1067. typedef struct ssl_st SSL;
  1068. typedef struct ssl_method_st SSL_METHOD;
  1069. typedef struct ssl_ctx_st SSL_CTX;
  1070. typedef struct x509_store_ctx_st X509_STORE_CTX;
  1071. typedef struct x509_name X509_NAME;
  1072. typedef struct asn1_integer ASN1_INTEGER;
  1073. typedef struct bignum BIGNUM;
  1074. typedef struct ossl_init_settings_st OPENSSL_INIT_SETTINGS;
  1075. typedef struct evp_md EVP_MD;
  1076. typedef struct x509 X509;
  1077. #define SSL_CTRL_OPTIONS (32)
  1078. #define SSL_CTRL_CLEAR_OPTIONS (77)
  1079. #define SSL_CTRL_SET_ECDH_AUTO (94)
  1080. #define OPENSSL_INIT_NO_LOAD_SSL_STRINGS 0x00100000L
  1081. #define OPENSSL_INIT_LOAD_SSL_STRINGS 0x00200000L
  1082. #define OPENSSL_INIT_LOAD_CRYPTO_STRINGS 0x00000002L
  1083. #define SSL_VERIFY_NONE (0)
  1084. #define SSL_VERIFY_PEER (1)
  1085. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  1086. #define SSL_VERIFY_CLIENT_ONCE (4)
  1087. #define SSL_OP_ALL ((long)(0x80000BFFUL))
  1088. #define SSL_OP_NO_SSLv2 (0x01000000L)
  1089. #define SSL_OP_NO_SSLv3 (0x02000000L)
  1090. #define SSL_OP_NO_TLSv1 (0x04000000L)
  1091. #define SSL_OP_NO_TLSv1_2 (0x08000000L)
  1092. #define SSL_OP_NO_TLSv1_1 (0x10000000L)
  1093. #define SSL_OP_SINGLE_DH_USE (0x00100000L)
  1094. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000L)
  1095. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000L)
  1096. #define SSL_ERROR_NONE (0)
  1097. #define SSL_ERROR_SSL (1)
  1098. #define SSL_ERROR_WANT_READ (2)
  1099. #define SSL_ERROR_WANT_WRITE (3)
  1100. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  1101. #define SSL_ERROR_SYSCALL (5) /* see errno */
  1102. #define SSL_ERROR_ZERO_RETURN (6)
  1103. #define SSL_ERROR_WANT_CONNECT (7)
  1104. #define SSL_ERROR_WANT_ACCEPT (8)
  1105. struct ssl_func {
  1106. const char *name; /* SSL function name */
  1107. void (*ptr)(void); /* Function pointer */
  1108. };
  1109. #ifdef OPENSSL_API_1_1
  1110. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1111. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1112. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1113. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1114. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1115. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1116. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1117. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  1118. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  1119. #define TLS_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  1120. #define OPENSSL_init_ssl \
  1121. (*(int (*)(uint64_t opts, \
  1122. const OPENSSL_INIT_SETTINGS *settings))ssl_sw[10].ptr)
  1123. #define SSL_CTX_use_PrivateKey_file \
  1124. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1125. #define SSL_CTX_use_certificate_file \
  1126. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1127. #define SSL_CTX_set_default_passwd_cb \
  1128. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1129. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1130. #define SSL_CTX_use_certificate_chain_file \
  1131. (*(int (*)(SSL_CTX *, const char *))ssl_sw[15].ptr)
  1132. #define TLS_client_method (*(SSL_METHOD * (*)(void))ssl_sw[16].ptr)
  1133. #define SSL_pending (*(int (*)(SSL *))ssl_sw[17].ptr)
  1134. #define SSL_CTX_set_verify \
  1135. (*(void (*)(SSL_CTX *, \
  1136. int, \
  1137. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[18].ptr)
  1138. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[19].ptr)
  1139. #define SSL_CTX_load_verify_locations \
  1140. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[20].ptr)
  1141. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[21].ptr)
  1142. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[22].ptr)
  1143. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[23].ptr)
  1144. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[24].ptr)
  1145. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[25].ptr)
  1146. #define SSL_CIPHER_get_name \
  1147. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[26].ptr)
  1148. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[27].ptr)
  1149. #define SSL_CTX_set_session_id_context \
  1150. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[28].ptr)
  1151. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[29].ptr)
  1152. #define SSL_CTX_set_cipher_list \
  1153. (*(int (*)(SSL_CTX *, const char *))ssl_sw[30].ptr)
  1154. #define SSL_CTX_set_options \
  1155. (*(unsigned long (*)(SSL_CTX *, unsigned long))ssl_sw[31].ptr)
  1156. #define SSL_CTX_clear_options(ctx, op) \
  1157. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1158. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1159. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1160. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1161. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1162. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[0].ptr)
  1163. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[1].ptr)
  1164. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[2].ptr)
  1165. #define CONF_modules_unload (*(void (*)(int))crypto_sw[3].ptr)
  1166. #define X509_free (*(void (*)(X509 *))crypto_sw[4].ptr)
  1167. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[5].ptr)
  1168. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[6].ptr)
  1169. #define X509_NAME_oneline \
  1170. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[7].ptr)
  1171. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[8].ptr)
  1172. #define EVP_get_digestbyname \
  1173. (*(const EVP_MD *(*)(const char *))crypto_sw[9].ptr)
  1174. #define ASN1_digest \
  1175. (*(int (*)(int (*)(), \
  1176. const EVP_MD *, \
  1177. char *, \
  1178. unsigned char *, \
  1179. unsigned int *))crypto_sw[10].ptr)
  1180. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[11].ptr)
  1181. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[12].ptr)
  1182. #define ASN1_INTEGER_to_BN \
  1183. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn))crypto_sw[13].ptr)
  1184. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[14].ptr)
  1185. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[15].ptr)
  1186. #define OPENSSL_free(a) CRYPTO_free(a)
  1187. /* set_ssl_option() function updates this array.
  1188. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1189. * of respective functions. The macros above (like SSL_connect()) are really
  1190. * just calling these functions indirectly via the pointer. */
  1191. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1192. {"SSL_accept", NULL},
  1193. {"SSL_connect", NULL},
  1194. {"SSL_read", NULL},
  1195. {"SSL_write", NULL},
  1196. {"SSL_get_error", NULL},
  1197. {"SSL_set_fd", NULL},
  1198. {"SSL_new", NULL},
  1199. {"SSL_CTX_new", NULL},
  1200. {"TLS_server_method", NULL},
  1201. {"OPENSSL_init_ssl", NULL},
  1202. {"SSL_CTX_use_PrivateKey_file", NULL},
  1203. {"SSL_CTX_use_certificate_file", NULL},
  1204. {"SSL_CTX_set_default_passwd_cb", NULL},
  1205. {"SSL_CTX_free", NULL},
  1206. {"SSL_CTX_use_certificate_chain_file", NULL},
  1207. {"TLS_client_method", NULL},
  1208. {"SSL_pending", NULL},
  1209. {"SSL_CTX_set_verify", NULL},
  1210. {"SSL_shutdown", NULL},
  1211. {"SSL_CTX_load_verify_locations", NULL},
  1212. {"SSL_CTX_set_default_verify_paths", NULL},
  1213. {"SSL_CTX_set_verify_depth", NULL},
  1214. {"SSL_get_peer_certificate", NULL},
  1215. {"SSL_get_version", NULL},
  1216. {"SSL_get_current_cipher", NULL},
  1217. {"SSL_CIPHER_get_name", NULL},
  1218. {"SSL_CTX_check_private_key", NULL},
  1219. {"SSL_CTX_set_session_id_context", NULL},
  1220. {"SSL_CTX_ctrl", NULL},
  1221. {"SSL_CTX_set_cipher_list", NULL},
  1222. {"SSL_CTX_set_options", NULL},
  1223. {NULL, NULL}};
  1224. /* Similar array as ssl_sw. These functions could be located in different
  1225. * lib. */
  1226. static struct ssl_func crypto_sw[] = {{"ERR_get_error", NULL},
  1227. {"ERR_error_string", NULL},
  1228. {"ERR_remove_state", NULL},
  1229. {"CONF_modules_unload", NULL},
  1230. {"X509_free", NULL},
  1231. {"X509_get_subject_name", NULL},
  1232. {"X509_get_issuer_name", NULL},
  1233. {"X509_NAME_oneline", NULL},
  1234. {"X509_get_serialNumber", NULL},
  1235. {"EVP_get_digestbyname", NULL},
  1236. {"ASN1_digest", NULL},
  1237. {"i2d_X509", NULL},
  1238. {"BN_bn2hex", NULL},
  1239. {"ASN1_INTEGER_to_BN", NULL},
  1240. {"BN_free", NULL},
  1241. {"CRYPTO_free", NULL},
  1242. {NULL, NULL}};
  1243. #else
  1244. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1245. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1246. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1247. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1248. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1249. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1250. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1251. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  1252. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  1253. #define SSLv23_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  1254. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  1255. #define SSL_CTX_use_PrivateKey_file \
  1256. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1257. #define SSL_CTX_use_certificate_file \
  1258. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1259. #define SSL_CTX_set_default_passwd_cb \
  1260. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1261. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1262. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  1263. #define SSL_CTX_use_certificate_chain_file \
  1264. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  1265. #define SSLv23_client_method (*(SSL_METHOD * (*)(void))ssl_sw[17].ptr)
  1266. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  1267. #define SSL_CTX_set_verify \
  1268. (*(void (*)(SSL_CTX *, \
  1269. int, \
  1270. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19].ptr)
  1271. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  1272. #define SSL_CTX_load_verify_locations \
  1273. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  1274. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  1275. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  1276. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[24].ptr)
  1277. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  1278. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[26].ptr)
  1279. #define SSL_CIPHER_get_name \
  1280. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  1281. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  1282. #define SSL_CTX_set_session_id_context \
  1283. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  1284. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  1285. #define SSL_CTX_set_cipher_list \
  1286. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  1287. #define SSL_CTX_set_options(ctx, op) \
  1288. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  1289. #define SSL_CTX_clear_options(ctx, op) \
  1290. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1291. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1292. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1293. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1294. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1295. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  1296. #define CRYPTO_set_locking_callback \
  1297. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  1298. #define CRYPTO_set_id_callback \
  1299. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  1300. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  1301. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  1302. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  1303. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  1304. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  1305. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  1306. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  1307. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  1308. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  1309. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[12].ptr)
  1310. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[13].ptr)
  1311. #define X509_NAME_oneline \
  1312. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  1313. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[15].ptr)
  1314. #define i2c_ASN1_INTEGER \
  1315. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  1316. #define EVP_get_digestbyname \
  1317. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1318. #define ASN1_digest \
  1319. (*(int (*)(int (*)(), \
  1320. const EVP_MD *, \
  1321. char *, \
  1322. unsigned char *, \
  1323. unsigned int *))crypto_sw[18].ptr)
  1324. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1325. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[20].ptr)
  1326. #define ASN1_INTEGER_to_BN \
  1327. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn))crypto_sw[21].ptr)
  1328. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[22].ptr)
  1329. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[23].ptr)
  1330. #define OPENSSL_free(a) CRYPTO_free(a)
  1331. /* set_ssl_option() function updates this array.
  1332. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1333. * of respective functions. The macros above (like SSL_connect()) are really
  1334. * just calling these functions indirectly via the pointer. */
  1335. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1336. {"SSL_accept", NULL},
  1337. {"SSL_connect", NULL},
  1338. {"SSL_read", NULL},
  1339. {"SSL_write", NULL},
  1340. {"SSL_get_error", NULL},
  1341. {"SSL_set_fd", NULL},
  1342. {"SSL_new", NULL},
  1343. {"SSL_CTX_new", NULL},
  1344. {"SSLv23_server_method", NULL},
  1345. {"SSL_library_init", NULL},
  1346. {"SSL_CTX_use_PrivateKey_file", NULL},
  1347. {"SSL_CTX_use_certificate_file", NULL},
  1348. {"SSL_CTX_set_default_passwd_cb", NULL},
  1349. {"SSL_CTX_free", NULL},
  1350. {"SSL_load_error_strings", NULL},
  1351. {"SSL_CTX_use_certificate_chain_file", NULL},
  1352. {"SSLv23_client_method", NULL},
  1353. {"SSL_pending", NULL},
  1354. {"SSL_CTX_set_verify", NULL},
  1355. {"SSL_shutdown", NULL},
  1356. {"SSL_CTX_load_verify_locations", NULL},
  1357. {"SSL_CTX_set_default_verify_paths", NULL},
  1358. {"SSL_CTX_set_verify_depth", NULL},
  1359. {"SSL_get_peer_certificate", NULL},
  1360. {"SSL_get_version", NULL},
  1361. {"SSL_get_current_cipher", NULL},
  1362. {"SSL_CIPHER_get_name", NULL},
  1363. {"SSL_CTX_check_private_key", NULL},
  1364. {"SSL_CTX_set_session_id_context", NULL},
  1365. {"SSL_CTX_ctrl", NULL},
  1366. {"SSL_CTX_set_cipher_list", NULL},
  1367. {NULL, NULL}};
  1368. /* Similar array as ssl_sw. These functions could be located in different
  1369. * lib. */
  1370. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  1371. {"CRYPTO_set_locking_callback", NULL},
  1372. {"CRYPTO_set_id_callback", NULL},
  1373. {"ERR_get_error", NULL},
  1374. {"ERR_error_string", NULL},
  1375. {"ERR_remove_state", NULL},
  1376. {"ERR_free_strings", NULL},
  1377. {"ENGINE_cleanup", NULL},
  1378. {"CONF_modules_unload", NULL},
  1379. {"CRYPTO_cleanup_all_ex_data", NULL},
  1380. {"EVP_cleanup", NULL},
  1381. {"X509_free", NULL},
  1382. {"X509_get_subject_name", NULL},
  1383. {"X509_get_issuer_name", NULL},
  1384. {"X509_NAME_oneline", NULL},
  1385. {"X509_get_serialNumber", NULL},
  1386. {"i2c_ASN1_INTEGER", NULL},
  1387. {"EVP_get_digestbyname", NULL},
  1388. {"ASN1_digest", NULL},
  1389. {"i2d_X509", NULL},
  1390. {"BN_bn2hex", NULL},
  1391. {"ASN1_INTEGER_to_BN", NULL},
  1392. {"BN_free", NULL},
  1393. {"CRYPTO_free", NULL},
  1394. {NULL, NULL}};
  1395. #endif /* OPENSSL_API_1_1 */
  1396. #endif /* NO_SSL_DL */
  1397. #endif /* NO_SSL */
  1398. #if !defined(NO_CACHING)
  1399. static const char *month_names[] = {"Jan",
  1400. "Feb",
  1401. "Mar",
  1402. "Apr",
  1403. "May",
  1404. "Jun",
  1405. "Jul",
  1406. "Aug",
  1407. "Sep",
  1408. "Oct",
  1409. "Nov",
  1410. "Dec"};
  1411. #endif /* !NO_CACHING */
  1412. /* Unified socket address. For IPv6 support, add IPv6 address structure in the
  1413. * union u. */
  1414. union usa {
  1415. struct sockaddr sa;
  1416. struct sockaddr_in sin;
  1417. #if defined(USE_IPV6)
  1418. struct sockaddr_in6 sin6;
  1419. #endif
  1420. };
  1421. /* Describes a string (chunk of memory). */
  1422. struct vec {
  1423. const char *ptr;
  1424. size_t len;
  1425. };
  1426. struct mg_file_stat {
  1427. /* File properties filled by mg_stat: */
  1428. uint64_t size;
  1429. time_t last_modified;
  1430. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1431. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1432. * case we need a "Content-Eencoding: gzip" header */
  1433. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1434. };
  1435. struct mg_file_in_memory {
  1436. char *p;
  1437. uint32_t pos;
  1438. char mode;
  1439. };
  1440. struct mg_file_access {
  1441. /* File properties filled by mg_fopen: */
  1442. FILE *fp;
  1443. /* TODO (low): Replace "membuf" implementation by a "file in memory"
  1444. * support library. Use some struct mg_file_in_memory *mf; instead of
  1445. * membuf char pointer. */
  1446. const char *membuf;
  1447. };
  1448. struct mg_file {
  1449. struct mg_file_stat stat;
  1450. struct mg_file_access access;
  1451. };
  1452. #define STRUCT_FILE_INITIALIZER \
  1453. { \
  1454. { \
  1455. (uint64_t)0, (time_t)0, 0, 0, 0 \
  1456. } \
  1457. , \
  1458. { \
  1459. (FILE *) NULL, (const char *)NULL \
  1460. } \
  1461. }
  1462. /* Describes listening socket, or socket which was accept()-ed by the master
  1463. * thread and queued for future handling by the worker thread. */
  1464. struct socket {
  1465. SOCKET sock; /* Listening socket */
  1466. union usa lsa; /* Local socket address */
  1467. union usa rsa; /* Remote socket address */
  1468. unsigned char is_ssl; /* Is port SSL-ed */
  1469. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1470. * port */
  1471. unsigned char in_use; /* Is valid */
  1472. };
  1473. /* NOTE(lsm): this enum shoulds be in sync with the config_options below. */
  1474. enum {
  1475. CGI_EXTENSIONS,
  1476. CGI_ENVIRONMENT,
  1477. PUT_DELETE_PASSWORDS_FILE,
  1478. CGI_INTERPRETER,
  1479. PROTECT_URI,
  1480. AUTHENTICATION_DOMAIN,
  1481. ENABLE_AUTH_DOMAIN_CHECK,
  1482. SSI_EXTENSIONS,
  1483. THROTTLE,
  1484. ACCESS_LOG_FILE,
  1485. ENABLE_DIRECTORY_LISTING,
  1486. ERROR_LOG_FILE,
  1487. GLOBAL_PASSWORDS_FILE,
  1488. INDEX_FILES,
  1489. ENABLE_KEEP_ALIVE,
  1490. ACCESS_CONTROL_LIST,
  1491. EXTRA_MIME_TYPES,
  1492. LISTENING_PORTS,
  1493. DOCUMENT_ROOT,
  1494. SSL_CERTIFICATE,
  1495. NUM_THREADS,
  1496. RUN_AS_USER,
  1497. REWRITE,
  1498. HIDE_FILES,
  1499. REQUEST_TIMEOUT,
  1500. KEEP_ALIVE_TIMEOUT,
  1501. LINGER_TIMEOUT,
  1502. SSL_DO_VERIFY_PEER,
  1503. SSL_CA_PATH,
  1504. SSL_CA_FILE,
  1505. SSL_VERIFY_DEPTH,
  1506. SSL_DEFAULT_VERIFY_PATHS,
  1507. SSL_CIPHER_LIST,
  1508. SSL_PROTOCOL_VERSION,
  1509. SSL_SHORT_TRUST,
  1510. #if defined(USE_WEBSOCKET)
  1511. WEBSOCKET_TIMEOUT,
  1512. #endif
  1513. DECODE_URL,
  1514. #if defined(USE_LUA)
  1515. LUA_PRELOAD_FILE,
  1516. LUA_SCRIPT_EXTENSIONS,
  1517. LUA_SERVER_PAGE_EXTENSIONS,
  1518. #endif
  1519. #if defined(USE_DUKTAPE)
  1520. DUKTAPE_SCRIPT_EXTENSIONS,
  1521. #endif
  1522. #if defined(USE_WEBSOCKET)
  1523. WEBSOCKET_ROOT,
  1524. #endif
  1525. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1526. LUA_WEBSOCKET_EXTENSIONS,
  1527. #endif
  1528. ACCESS_CONTROL_ALLOW_ORIGIN,
  1529. ERROR_PAGES,
  1530. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1531. * socket option typedef TCP_NODELAY. */
  1532. #if !defined(NO_CACHING)
  1533. STATIC_FILE_MAX_AGE,
  1534. #endif
  1535. #if defined(__linux__)
  1536. ALLOW_SENDFILE_CALL,
  1537. #endif
  1538. #if defined(_WIN32)
  1539. CASE_SENSITIVE_FILES,
  1540. #endif
  1541. #if defined(USE_LUA)
  1542. LUA_BACKGROUND_SCRIPT,
  1543. #endif
  1544. NUM_OPTIONS
  1545. };
  1546. /* Config option name, config types, default value */
  1547. static struct mg_option config_options[] = {
  1548. {"cgi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1549. {"cgi_environment", CONFIG_TYPE_STRING, NULL},
  1550. {"put_delete_auth_file", CONFIG_TYPE_FILE, NULL},
  1551. {"cgi_interpreter", CONFIG_TYPE_FILE, NULL},
  1552. {"protect_uri", CONFIG_TYPE_STRING, NULL},
  1553. {"authentication_domain", CONFIG_TYPE_STRING, "mydomain.com"},
  1554. {"enable_auth_domain_check", CONFIG_TYPE_BOOLEAN, "yes"},
  1555. {"ssi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1556. {"throttle", CONFIG_TYPE_STRING, NULL},
  1557. {"access_log_file", CONFIG_TYPE_FILE, NULL},
  1558. {"enable_directory_listing", CONFIG_TYPE_BOOLEAN, "yes"},
  1559. {"error_log_file", CONFIG_TYPE_FILE, NULL},
  1560. {"global_auth_file", CONFIG_TYPE_FILE, NULL},
  1561. {"index_files",
  1562. CONFIG_TYPE_STRING,
  1563. #ifdef USE_LUA
  1564. "index.xhtml,index.html,index.htm,index.lp,index.lsp,index.lua,index.cgi,"
  1565. "index.shtml,index.php"},
  1566. #else
  1567. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1568. #endif
  1569. {"enable_keep_alive", CONFIG_TYPE_BOOLEAN, "no"},
  1570. {"access_control_list", CONFIG_TYPE_STRING, NULL},
  1571. {"extra_mime_types", CONFIG_TYPE_STRING, NULL},
  1572. {"listening_ports", CONFIG_TYPE_STRING, "8080"},
  1573. {"document_root", CONFIG_TYPE_DIRECTORY, NULL},
  1574. {"ssl_certificate", CONFIG_TYPE_FILE, NULL},
  1575. {"num_threads", CONFIG_TYPE_NUMBER, "50"},
  1576. {"run_as_user", CONFIG_TYPE_STRING, NULL},
  1577. {"url_rewrite_patterns", CONFIG_TYPE_STRING, NULL},
  1578. {"hide_files_patterns", CONFIG_TYPE_EXT_PATTERN, NULL},
  1579. {"request_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1580. {"keep_alive_timeout_ms", CONFIG_TYPE_NUMBER, "500"},
  1581. {"linger_timeout_ms", CONFIG_TYPE_NUMBER, NULL},
  1582. {"ssl_verify_peer", CONFIG_TYPE_BOOLEAN, "no"},
  1583. {"ssl_ca_path", CONFIG_TYPE_DIRECTORY, NULL},
  1584. {"ssl_ca_file", CONFIG_TYPE_FILE, NULL},
  1585. {"ssl_verify_depth", CONFIG_TYPE_NUMBER, "9"},
  1586. {"ssl_default_verify_paths", CONFIG_TYPE_BOOLEAN, "yes"},
  1587. {"ssl_cipher_list", CONFIG_TYPE_STRING, NULL},
  1588. {"ssl_protocol_version", CONFIG_TYPE_NUMBER, "0"},
  1589. {"ssl_short_trust", CONFIG_TYPE_BOOLEAN, "no"},
  1590. #if defined(USE_WEBSOCKET)
  1591. {"websocket_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1592. #endif
  1593. {"decode_url", CONFIG_TYPE_BOOLEAN, "yes"},
  1594. #if defined(USE_LUA)
  1595. {"lua_preload_file", CONFIG_TYPE_FILE, NULL},
  1596. {"lua_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1597. {"lua_server_page_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1598. #endif
  1599. #if defined(USE_DUKTAPE)
  1600. /* The support for duktape is still in alpha version state.
  1601. * The name of this config option might change. */
  1602. {"duktape_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1603. #endif
  1604. #if defined(USE_WEBSOCKET)
  1605. {"websocket_root", CONFIG_TYPE_DIRECTORY, NULL},
  1606. #endif
  1607. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1608. {"lua_websocket_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1609. #endif
  1610. {"access_control_allow_origin", CONFIG_TYPE_STRING, "*"},
  1611. {"error_pages", CONFIG_TYPE_DIRECTORY, NULL},
  1612. {"tcp_nodelay", CONFIG_TYPE_NUMBER, "0"},
  1613. #if !defined(NO_CACHING)
  1614. {"static_file_max_age", CONFIG_TYPE_NUMBER, "3600"},
  1615. #endif
  1616. #if defined(__linux__)
  1617. {"allow_sendfile_call", CONFIG_TYPE_BOOLEAN, "yes"},
  1618. #endif
  1619. #if defined(_WIN32)
  1620. {"case_sensitive", CONFIG_TYPE_BOOLEAN, "no"},
  1621. #endif
  1622. #if defined(USE_LUA)
  1623. {"lua_background_script", CONFIG_TYPE_FILE, NULL},
  1624. #endif
  1625. {NULL, CONFIG_TYPE_UNKNOWN, NULL}};
  1626. /* Check if the config_options and the corresponding enum have compatible
  1627. * sizes. */
  1628. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1629. == (NUM_OPTIONS + 1),
  1630. "config_options and enum not sync");
  1631. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1632. struct mg_handler_info {
  1633. /* Name/Pattern of the URI. */
  1634. char *uri;
  1635. size_t uri_len;
  1636. /* handler type */
  1637. int handler_type;
  1638. /* Handler for http/https or authorization requests. */
  1639. mg_request_handler handler;
  1640. /* Handler for ws/wss (websocket) requests. */
  1641. mg_websocket_connect_handler connect_handler;
  1642. mg_websocket_ready_handler ready_handler;
  1643. mg_websocket_data_handler data_handler;
  1644. mg_websocket_close_handler close_handler;
  1645. /* accepted subprotocols for ws/wss requests. */
  1646. struct mg_websocket_subprotocols *subprotocols;
  1647. /* Handler for authorization requests */
  1648. mg_authorization_handler auth_handler;
  1649. /* User supplied argument for the handler function. */
  1650. void *cbdata;
  1651. /* next handler in a linked list */
  1652. struct mg_handler_info *next;
  1653. };
  1654. struct mg_context {
  1655. volatile int stop_flag; /* Should we stop event loop */
  1656. SSL_CTX *ssl_ctx; /* SSL context */
  1657. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1658. struct mg_callbacks callbacks; /* User-defined callback function */
  1659. void *user_data; /* User-defined data */
  1660. int context_type; /* 1 = server context,
  1661. * 2 = ws/wss client context,
  1662. */
  1663. struct socket *listening_sockets;
  1664. struct pollfd *listening_socket_fds;
  1665. unsigned int num_listening_sockets;
  1666. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  1667. #ifdef ALTERNATIVE_QUEUE
  1668. struct socket *client_socks;
  1669. void **client_wait_events;
  1670. #else
  1671. struct socket queue[MGSQLEN]; /* Accepted sockets */
  1672. volatile int sq_head; /* Head of the socket queue */
  1673. volatile int sq_tail; /* Tail of the socket queue */
  1674. pthread_cond_t sq_full; /* Signaled when socket is produced */
  1675. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  1676. #endif
  1677. pthread_t masterthreadid; /* The master thread ID */
  1678. unsigned int
  1679. cfg_worker_threads; /* The number of configured worker threads. */
  1680. pthread_t *worker_threadids; /* The worker thread IDs */
  1681. struct mg_connection *worker_connections; /* The connection struct, pre-
  1682. * allocated for each worker */
  1683. time_t start_time; /* Server start time, used for authentication */
  1684. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1685. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  1686. unsigned long nonce_count; /* Used nonces, used for authentication */
  1687. char *systemName; /* What operating system is running */
  1688. /* linked list of uri handlers */
  1689. struct mg_handler_info *handlers;
  1690. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1691. /* linked list of shared lua websockets */
  1692. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1693. #endif
  1694. #if defined(USE_TIMERS)
  1695. struct ttimers *timers;
  1696. #endif
  1697. #if defined(USE_LUA)
  1698. void *lua_background_state;
  1699. #endif
  1700. };
  1701. struct mg_connection {
  1702. struct mg_request_info request_info;
  1703. struct mg_context *ctx;
  1704. SSL *ssl; /* SSL descriptor */
  1705. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  1706. struct socket client; /* Connected client */
  1707. time_t conn_birth_time; /* Time (wall clock) when connection was
  1708. * established */
  1709. struct timespec req_time; /* Time (since system start) when the request
  1710. * was received */
  1711. int64_t num_bytes_sent; /* Total bytes sent to client */
  1712. int64_t content_len; /* Content-Length header value */
  1713. int64_t consumed_content; /* How many bytes of content have been read */
  1714. int is_chunked; /* Transfer-Encoding is chunked: 0=no, 1=yes:
  1715. * data available, 2: all data read */
  1716. size_t chunk_remainder; /* Unread data from the last chunk */
  1717. char *buf; /* Buffer for received data */
  1718. char *path_info; /* PATH_INFO part of the URL */
  1719. int must_close; /* 1 if connection must be closed */
  1720. int in_error_handler; /* 1 if in handler for user defined error
  1721. * pages */
  1722. int handled_requests; /* Number of requests handled by this connection */
  1723. int buf_size; /* Buffer size */
  1724. int request_len; /* Size of the request + headers in a buffer */
  1725. int data_len; /* Total size of data in a buffer */
  1726. int status_code; /* HTTP reply status code, e.g. 200 */
  1727. int throttle; /* Throttling, bytes/sec. <= 0 means no
  1728. * throttle */
  1729. time_t last_throttle_time; /* Last time throttled data was sent */
  1730. int64_t last_throttle_bytes; /* Bytes sent this second */
  1731. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  1732. * atomic transmissions for websockets */
  1733. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1734. void *lua_websocket_state; /* Lua_State for a websocket connection */
  1735. #endif
  1736. int thread_index; /* Thread index within ctx */
  1737. };
  1738. /* Directory entry */
  1739. struct de {
  1740. struct mg_connection *conn;
  1741. char *file_name;
  1742. struct mg_file_stat file;
  1743. };
  1744. #if defined(USE_WEBSOCKET)
  1745. static int is_websocket_protocol(const struct mg_connection *conn);
  1746. #else
  1747. #define is_websocket_protocol(conn) (0)
  1748. #endif
  1749. #if !defined(NO_THREAD_NAME)
  1750. #if defined(_WIN32) && defined(_MSC_VER)
  1751. /* Set the thread name for debugging purposes in Visual Studio
  1752. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  1753. */
  1754. #pragma pack(push, 8)
  1755. typedef struct tagTHREADNAME_INFO {
  1756. DWORD dwType; /* Must be 0x1000. */
  1757. LPCSTR szName; /* Pointer to name (in user addr space). */
  1758. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  1759. DWORD dwFlags; /* Reserved for future use, must be zero. */
  1760. } THREADNAME_INFO;
  1761. #pragma pack(pop)
  1762. #elif defined(__linux__)
  1763. #include <sys/prctl.h>
  1764. #include <sys/sendfile.h>
  1765. #include <sys/eventfd.h>
  1766. #if defined(ALTERNATIVE_QUEUE)
  1767. static void *
  1768. event_create(void)
  1769. {
  1770. int ret = eventfd(0, EFD_CLOEXEC);
  1771. if (ret == -1) {
  1772. /* Linux uses -1 on error, Windows NULL. */
  1773. /* However, Linux does not return 0 on success either. */
  1774. return 0;
  1775. }
  1776. return (void *)ret;
  1777. }
  1778. static int
  1779. event_wait(void *eventhdl)
  1780. {
  1781. uint64_t u;
  1782. int s = (int)read((int)eventhdl, &u, sizeof(u));
  1783. if (s != sizeof(uint64_t)) {
  1784. /* error */
  1785. return 0;
  1786. }
  1787. (void)u; /* the value is not required */
  1788. return 1;
  1789. }
  1790. static int
  1791. event_signal(void *eventhdl)
  1792. {
  1793. uint64_t u = 1;
  1794. int s = (int)write((int)eventhdl, &u, sizeof(u));
  1795. if (s != sizeof(uint64_t)) {
  1796. /* error */
  1797. return 0;
  1798. }
  1799. return 1;
  1800. }
  1801. static void
  1802. event_destroy(void *eventhdl)
  1803. {
  1804. close((int)eventhdl);
  1805. }
  1806. #endif
  1807. #endif
  1808. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  1809. struct posix_event {
  1810. pthread_mutex_t mutex;
  1811. pthread_cond_t cond;
  1812. };
  1813. static void *
  1814. event_create(void)
  1815. {
  1816. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  1817. if (ret == 0) {
  1818. /* out of memory */
  1819. return 0;
  1820. }
  1821. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  1822. /* pthread mutex not available */
  1823. mg_free(ret);
  1824. return 0;
  1825. }
  1826. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  1827. /* pthread cond not available */
  1828. pthread_mutex_destroy(&(ret->mutex));
  1829. mg_free(ret);
  1830. return 0;
  1831. }
  1832. return (void *)ret;
  1833. }
  1834. static int
  1835. event_wait(void *eventhdl)
  1836. {
  1837. struct posix_event *ev = (struct posix_event *)eventhdl;
  1838. pthread_mutex_lock(&(ev->mutex));
  1839. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  1840. pthread_mutex_unlock(&(ev->mutex));
  1841. return 1;
  1842. }
  1843. static int
  1844. event_signal(void *eventhdl)
  1845. {
  1846. struct posix_event *ev = (struct posix_event *)eventhdl;
  1847. pthread_mutex_lock(&(ev->mutex));
  1848. pthread_cond_signal(&(ev->cond));
  1849. pthread_mutex_unlock(&(ev->mutex));
  1850. return 1;
  1851. }
  1852. static void
  1853. event_destroy(void *eventhdl)
  1854. {
  1855. struct posix_event *ev = (struct posix_event *)eventhdl;
  1856. pthread_cond_destroy(&(ev->cond));
  1857. pthread_mutex_destroy(&(ev->mutex));
  1858. mg_free(ev);
  1859. }
  1860. #endif
  1861. static void
  1862. mg_set_thread_name(const char *name)
  1863. {
  1864. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  1865. mg_snprintf(
  1866. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  1867. #if defined(_WIN32)
  1868. #if defined(_MSC_VER)
  1869. /* Windows and Visual Studio Compiler */
  1870. __try
  1871. {
  1872. THREADNAME_INFO info;
  1873. info.dwType = 0x1000;
  1874. info.szName = threadName;
  1875. info.dwThreadID = ~0U;
  1876. info.dwFlags = 0;
  1877. RaiseException(0x406D1388,
  1878. 0,
  1879. sizeof(info) / sizeof(ULONG_PTR),
  1880. (ULONG_PTR *)&info);
  1881. }
  1882. __except(EXCEPTION_EXECUTE_HANDLER)
  1883. {
  1884. }
  1885. #elif defined(__MINGW32__)
  1886. /* No option known to set thread name for MinGW */
  1887. #endif
  1888. #elif defined(__GLIBC__) \
  1889. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  1890. /* pthread_setname_np first appeared in glibc in version 2.12*/
  1891. (void)pthread_setname_np(pthread_self(), threadName);
  1892. #elif defined(__linux__)
  1893. /* on linux we can use the old prctl function */
  1894. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  1895. #endif
  1896. }
  1897. #else /* !defined(NO_THREAD_NAME) */
  1898. void
  1899. mg_set_thread_name(const char *threadName)
  1900. {
  1901. }
  1902. #endif
  1903. #if defined(MG_LEGACY_INTERFACE)
  1904. const char **
  1905. mg_get_valid_option_names(void)
  1906. {
  1907. /* This function is deprecated. Use mg_get_valid_options instead. */
  1908. static const char *
  1909. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  1910. int i;
  1911. for (i = 0; config_options[i].name != NULL; i++) {
  1912. data[i * 2] = config_options[i].name;
  1913. data[i * 2 + 1] = config_options[i].default_value;
  1914. }
  1915. return data;
  1916. }
  1917. #endif
  1918. const struct mg_option *
  1919. mg_get_valid_options(void)
  1920. {
  1921. return config_options;
  1922. }
  1923. /* Do not open file (used in is_file_in_memory) */
  1924. #define MG_FOPEN_MODE_NONE (0)
  1925. /* Open file for read only access */
  1926. #define MG_FOPEN_MODE_READ (1)
  1927. /* Open file for writing, create and overwrite */
  1928. #define MG_FOPEN_MODE_WRITE (2)
  1929. /* Open file for writing, create and append */
  1930. #define MG_FOPEN_MODE_APPEND (4)
  1931. /* If a file is in memory, set all "stat" members and the membuf pointer of
  1932. * output filep and return 1, otherwise return 0 and don't modify anything. */
  1933. static int
  1934. open_file_in_memory(const struct mg_connection *conn,
  1935. const char *path,
  1936. struct mg_file *filep,
  1937. int mode)
  1938. {
  1939. #if defined(MG_USE_OPEN_FILE)
  1940. size_t size = 0;
  1941. const char *buf = NULL;
  1942. if (!conn) {
  1943. return 0;
  1944. }
  1945. if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
  1946. return 0;
  1947. }
  1948. if (conn->ctx->callbacks.open_file) {
  1949. buf = conn->ctx->callbacks.open_file(conn, path, &size);
  1950. if (buf != NULL) {
  1951. if (filep == NULL) {
  1952. /* This is a file in memory, but we cannot store the properties
  1953. * now.
  1954. * Called from "is_file_in_memory" function. */
  1955. return 1;
  1956. }
  1957. /* NOTE: override filep->size only on success. Otherwise, it might
  1958. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  1959. filep->access.membuf = buf;
  1960. filep->access.fp = NULL;
  1961. /* Size was set by the callback */
  1962. filep->stat.size = size;
  1963. /* Assume the data may change during runtime by setting
  1964. * last_modified = now */
  1965. filep->stat.last_modified = time(NULL);
  1966. filep->stat.is_directory = 0;
  1967. filep->stat.is_gzipped = 0;
  1968. }
  1969. }
  1970. return (buf != NULL);
  1971. #else
  1972. (void)conn;
  1973. (void)path;
  1974. (void)filep;
  1975. (void)mode;
  1976. return 0;
  1977. #endif
  1978. }
  1979. static int
  1980. is_file_in_memory(const struct mg_connection *conn, const char *path)
  1981. {
  1982. return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
  1983. }
  1984. static int
  1985. is_file_opened(const struct mg_file_access *fileacc)
  1986. {
  1987. if (!fileacc) {
  1988. return 0;
  1989. }
  1990. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  1991. }
  1992. static int mg_stat(const struct mg_connection *conn,
  1993. const char *path,
  1994. struct mg_file_stat *filep);
  1995. /* mg_fopen will open a file either in memory or on the disk.
  1996. * The input parameter path is a string in UTF-8 encoding.
  1997. * The input parameter mode is MG_FOPEN_MODE_*
  1998. * On success, either fp or membuf will be set in the output
  1999. * struct file. All status members will also be set.
  2000. * The function returns 1 on success, 0 on error. */
  2001. static int
  2002. mg_fopen(const struct mg_connection *conn,
  2003. const char *path,
  2004. int mode,
  2005. struct mg_file *filep)
  2006. {
  2007. int found;
  2008. if (!filep) {
  2009. return 0;
  2010. }
  2011. filep->access.fp = NULL;
  2012. filep->access.membuf = NULL;
  2013. if (!is_file_in_memory(conn, path)) {
  2014. /* filep is initialized in mg_stat: all fields with memset to,
  2015. * some fields like size and modification date with values */
  2016. found = mg_stat(conn, path, &(filep->stat));
  2017. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2018. /* file does not exist and will not be created */
  2019. return 0;
  2020. }
  2021. #ifdef _WIN32
  2022. {
  2023. wchar_t wbuf[PATH_MAX];
  2024. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2025. switch (mode) {
  2026. case MG_FOPEN_MODE_READ:
  2027. filep->access.fp = _wfopen(wbuf, L"rb");
  2028. break;
  2029. case MG_FOPEN_MODE_WRITE:
  2030. filep->access.fp = _wfopen(wbuf, L"wb");
  2031. break;
  2032. case MG_FOPEN_MODE_APPEND:
  2033. filep->access.fp = _wfopen(wbuf, L"ab");
  2034. break;
  2035. }
  2036. }
  2037. #else
  2038. /* Linux et al already use unicode. No need to convert. */
  2039. switch (mode) {
  2040. case MG_FOPEN_MODE_READ:
  2041. filep->access.fp = fopen(path, "r");
  2042. break;
  2043. case MG_FOPEN_MODE_WRITE:
  2044. filep->access.fp = fopen(path, "w");
  2045. break;
  2046. case MG_FOPEN_MODE_APPEND:
  2047. filep->access.fp = fopen(path, "a");
  2048. break;
  2049. }
  2050. #endif
  2051. if (!found) {
  2052. /* File did not exist before fopen was called.
  2053. * Maybe it has been created now. Get stat info
  2054. * like creation time now. */
  2055. found = mg_stat(conn, path, &(filep->stat));
  2056. (void)found;
  2057. }
  2058. /* file is on disk */
  2059. return (filep->access.fp != NULL);
  2060. } else {
  2061. /* is_file_in_memory returned true */
  2062. if (open_file_in_memory(conn, path, filep, mode)) {
  2063. /* file is in memory */
  2064. return (filep->access.membuf != NULL);
  2065. }
  2066. }
  2067. /* Open failed */
  2068. return 0;
  2069. }
  2070. /* return 0 on success, just like fclose */
  2071. static int
  2072. mg_fclose(struct mg_file_access *fileacc)
  2073. {
  2074. int ret = -1;
  2075. if (fileacc != NULL) {
  2076. if (fileacc->fp != NULL) {
  2077. ret = fclose(fileacc->fp);
  2078. } else if (fileacc->membuf != NULL) {
  2079. ret = 0;
  2080. }
  2081. /* reset all members of fileacc */
  2082. memset(fileacc, 0, sizeof(*fileacc));
  2083. }
  2084. return ret;
  2085. }
  2086. static void
  2087. mg_strlcpy(register char *dst, register const char *src, size_t n)
  2088. {
  2089. for (; *src != '\0' && n > 1; n--) {
  2090. *dst++ = *src++;
  2091. }
  2092. *dst = '\0';
  2093. }
  2094. static int
  2095. lowercase(const char *s)
  2096. {
  2097. return tolower(*(const unsigned char *)s);
  2098. }
  2099. int
  2100. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2101. {
  2102. int diff = 0;
  2103. if (len > 0) {
  2104. do {
  2105. diff = lowercase(s1++) - lowercase(s2++);
  2106. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2107. }
  2108. return diff;
  2109. }
  2110. int
  2111. mg_strcasecmp(const char *s1, const char *s2)
  2112. {
  2113. int diff;
  2114. do {
  2115. diff = lowercase(s1++) - lowercase(s2++);
  2116. } while (diff == 0 && s1[-1] != '\0');
  2117. return diff;
  2118. }
  2119. static char *
  2120. mg_strndup(const char *ptr, size_t len)
  2121. {
  2122. char *p;
  2123. if ((p = (char *)mg_malloc(len + 1)) != NULL) {
  2124. mg_strlcpy(p, ptr, len + 1);
  2125. }
  2126. return p;
  2127. }
  2128. static char *
  2129. mg_strdup(const char *str)
  2130. {
  2131. return mg_strndup(str, strlen(str));
  2132. }
  2133. static const char *
  2134. mg_strcasestr(const char *big_str, const char *small_str)
  2135. {
  2136. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2137. if (big_len >= small_len) {
  2138. for (i = 0; i <= (big_len - small_len); i++) {
  2139. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2140. return big_str + i;
  2141. }
  2142. }
  2143. }
  2144. return NULL;
  2145. }
  2146. /* Return null terminated string of given maximum length.
  2147. * Report errors if length is exceeded. */
  2148. static void
  2149. mg_vsnprintf(const struct mg_connection *conn,
  2150. int *truncated,
  2151. char *buf,
  2152. size_t buflen,
  2153. const char *fmt,
  2154. va_list ap)
  2155. {
  2156. int n, ok;
  2157. if (buflen == 0) {
  2158. return;
  2159. }
  2160. #ifdef __clang__
  2161. #pragma clang diagnostic push
  2162. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2163. /* Using fmt as a non-literal is intended here, since it is mostly called
  2164. * indirectly by mg_snprintf */
  2165. #endif
  2166. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2167. ok = (n >= 0) && ((size_t)n < buflen);
  2168. #ifdef __clang__
  2169. #pragma clang diagnostic pop
  2170. #endif
  2171. if (ok) {
  2172. if (truncated) {
  2173. *truncated = 0;
  2174. }
  2175. } else {
  2176. if (truncated) {
  2177. *truncated = 1;
  2178. }
  2179. mg_cry(conn,
  2180. "truncating vsnprintf buffer: [%.*s]",
  2181. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2182. buf);
  2183. n = (int)buflen - 1;
  2184. }
  2185. buf[n] = '\0';
  2186. }
  2187. static void
  2188. mg_snprintf(const struct mg_connection *conn,
  2189. int *truncated,
  2190. char *buf,
  2191. size_t buflen,
  2192. const char *fmt,
  2193. ...)
  2194. {
  2195. va_list ap;
  2196. va_start(ap, fmt);
  2197. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2198. va_end(ap);
  2199. }
  2200. static int
  2201. get_option_index(const char *name)
  2202. {
  2203. int i;
  2204. for (i = 0; config_options[i].name != NULL; i++) {
  2205. if (strcmp(config_options[i].name, name) == 0) {
  2206. return i;
  2207. }
  2208. }
  2209. return -1;
  2210. }
  2211. const char *
  2212. mg_get_option(const struct mg_context *ctx, const char *name)
  2213. {
  2214. int i;
  2215. if ((i = get_option_index(name)) == -1) {
  2216. return NULL;
  2217. } else if (!ctx || ctx->config[i] == NULL) {
  2218. return "";
  2219. } else {
  2220. return ctx->config[i];
  2221. }
  2222. }
  2223. struct mg_context *
  2224. mg_get_context(const struct mg_connection *conn)
  2225. {
  2226. return (conn == NULL) ? (struct mg_context *)NULL : (conn->ctx);
  2227. }
  2228. void *
  2229. mg_get_user_data(const struct mg_context *ctx)
  2230. {
  2231. return (ctx == NULL) ? NULL : ctx->user_data;
  2232. }
  2233. void
  2234. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  2235. {
  2236. if (conn != NULL) {
  2237. conn->request_info.conn_data = data;
  2238. }
  2239. }
  2240. void *
  2241. mg_get_user_connection_data(const struct mg_connection *conn)
  2242. {
  2243. if (conn != NULL) {
  2244. return conn->request_info.conn_data;
  2245. }
  2246. return NULL;
  2247. }
  2248. size_t
  2249. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  2250. {
  2251. size_t i;
  2252. if (!ctx) {
  2253. return 0;
  2254. }
  2255. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  2256. ssl[i] = ctx->listening_sockets[i].is_ssl;
  2257. ports[i] =
  2258. #if defined(USE_IPV6)
  2259. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2260. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2261. :
  2262. #endif
  2263. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2264. }
  2265. return i;
  2266. }
  2267. int
  2268. mg_get_server_ports(const struct mg_context *ctx,
  2269. int size,
  2270. struct mg_server_ports *ports)
  2271. {
  2272. int i, cnt = 0;
  2273. if (size <= 0) {
  2274. return -1;
  2275. }
  2276. memset(ports, 0, sizeof(*ports) * (size_t)size);
  2277. if (!ctx) {
  2278. return -1;
  2279. }
  2280. if (!ctx->listening_sockets) {
  2281. return -1;
  2282. }
  2283. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  2284. ports[cnt].port =
  2285. #if defined(USE_IPV6)
  2286. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2287. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2288. :
  2289. #endif
  2290. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2291. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  2292. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  2293. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  2294. /* IPv4 */
  2295. ports[cnt].protocol = 1;
  2296. cnt++;
  2297. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  2298. /* IPv6 */
  2299. ports[cnt].protocol = 3;
  2300. cnt++;
  2301. }
  2302. }
  2303. return cnt;
  2304. }
  2305. static void
  2306. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  2307. {
  2308. buf[0] = '\0';
  2309. if (!usa) {
  2310. return;
  2311. }
  2312. if (usa->sa.sa_family == AF_INET) {
  2313. getnameinfo(&usa->sa,
  2314. sizeof(usa->sin),
  2315. buf,
  2316. (unsigned)len,
  2317. NULL,
  2318. 0,
  2319. NI_NUMERICHOST);
  2320. }
  2321. #if defined(USE_IPV6)
  2322. else if (usa->sa.sa_family == AF_INET6) {
  2323. getnameinfo(&usa->sa,
  2324. sizeof(usa->sin6),
  2325. buf,
  2326. (unsigned)len,
  2327. NULL,
  2328. 0,
  2329. NI_NUMERICHOST);
  2330. }
  2331. #endif
  2332. }
  2333. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  2334. * included in all responses other than 100, 101, 5xx. */
  2335. static void
  2336. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  2337. {
  2338. struct tm *tm;
  2339. tm = ((t != NULL) ? gmtime(t) : NULL);
  2340. if (tm != NULL) {
  2341. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  2342. } else {
  2343. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  2344. buf[buf_len - 1] = '\0';
  2345. }
  2346. }
  2347. /* difftime for struct timespec. Return value is in seconds. */
  2348. static double
  2349. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  2350. {
  2351. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  2352. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  2353. }
  2354. /* Print error message to the opened error log stream. */
  2355. void
  2356. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  2357. {
  2358. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  2359. va_list ap;
  2360. struct mg_file fi;
  2361. time_t timestamp;
  2362. va_start(ap, fmt);
  2363. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  2364. va_end(ap);
  2365. buf[sizeof(buf) - 1] = 0;
  2366. if (!conn) {
  2367. puts(buf);
  2368. return;
  2369. }
  2370. /* Do not lock when getting the callback value, here and below.
  2371. * I suppose this is fine, since function cannot disappear in the
  2372. * same way string option can. */
  2373. if ((conn->ctx->callbacks.log_message == NULL)
  2374. || (conn->ctx->callbacks.log_message(conn, buf) == 0)) {
  2375. if (conn->ctx->config[ERROR_LOG_FILE] != NULL) {
  2376. if (mg_fopen(conn,
  2377. conn->ctx->config[ERROR_LOG_FILE],
  2378. MG_FOPEN_MODE_APPEND,
  2379. &fi) == 0) {
  2380. fi.access.fp = NULL;
  2381. }
  2382. } else {
  2383. fi.access.fp = NULL;
  2384. }
  2385. if (fi.access.fp != NULL) {
  2386. flockfile(fi.access.fp);
  2387. timestamp = time(NULL);
  2388. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  2389. fprintf(fi.access.fp,
  2390. "[%010lu] [error] [client %s] ",
  2391. (unsigned long)timestamp,
  2392. src_addr);
  2393. if (conn->request_info.request_method != NULL) {
  2394. fprintf(fi.access.fp,
  2395. "%s %s: ",
  2396. conn->request_info.request_method,
  2397. conn->request_info.request_uri);
  2398. }
  2399. fprintf(fi.access.fp, "%s", buf);
  2400. fputc('\n', fi.access.fp);
  2401. fflush(fi.access.fp);
  2402. funlockfile(fi.access.fp);
  2403. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  2404. * mg_cry here anyway ;-) */
  2405. }
  2406. }
  2407. }
  2408. /* Return fake connection structure. Used for logging, if connection
  2409. * is not applicable at the moment of logging. */
  2410. static struct mg_connection *
  2411. fc(struct mg_context *ctx)
  2412. {
  2413. static struct mg_connection fake_connection;
  2414. fake_connection.ctx = ctx;
  2415. return &fake_connection;
  2416. }
  2417. const char *
  2418. mg_version(void)
  2419. {
  2420. return CIVETWEB_VERSION;
  2421. }
  2422. const struct mg_request_info *
  2423. mg_get_request_info(const struct mg_connection *conn)
  2424. {
  2425. if (!conn) {
  2426. return NULL;
  2427. }
  2428. return &conn->request_info;
  2429. }
  2430. /* Skip the characters until one of the delimiters characters found.
  2431. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  2432. * Advance pointer to buffer to the next word. Return found 0-terminated word.
  2433. * Delimiters can be quoted with quotechar. */
  2434. static char *
  2435. skip_quoted(char **buf,
  2436. const char *delimiters,
  2437. const char *whitespace,
  2438. char quotechar)
  2439. {
  2440. char *p, *begin_word, *end_word, *end_whitespace;
  2441. begin_word = *buf;
  2442. end_word = begin_word + strcspn(begin_word, delimiters);
  2443. /* Check for quotechar */
  2444. if (end_word > begin_word) {
  2445. p = end_word - 1;
  2446. while (*p == quotechar) {
  2447. /* While the delimiter is quoted, look for the next delimiter. */
  2448. /* This happens, e.g., in calls from parse_auth_header,
  2449. * if the user name contains a " character. */
  2450. /* If there is anything beyond end_word, copy it. */
  2451. if (*end_word != '\0') {
  2452. size_t end_off = strcspn(end_word + 1, delimiters);
  2453. memmove(p, end_word, end_off + 1);
  2454. p += end_off; /* p must correspond to end_word - 1 */
  2455. end_word += end_off + 1;
  2456. } else {
  2457. *p = '\0';
  2458. break;
  2459. }
  2460. }
  2461. for (p++; p < end_word; p++) {
  2462. *p = '\0';
  2463. }
  2464. }
  2465. if (*end_word == '\0') {
  2466. *buf = end_word;
  2467. } else {
  2468. #if defined(__GNUC__) || defined(__MINGW32__)
  2469. /* Disable spurious conversion warning for GCC */
  2470. #pragma GCC diagnostic push
  2471. #pragma GCC diagnostic ignored "-Wsign-conversion"
  2472. #endif
  2473. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  2474. #if defined(__GNUC__) || defined(__MINGW32__)
  2475. #pragma GCC diagnostic pop
  2476. #endif
  2477. for (p = end_word; p < end_whitespace; p++) {
  2478. *p = '\0';
  2479. }
  2480. *buf = end_whitespace;
  2481. }
  2482. return begin_word;
  2483. }
  2484. /* Simplified version of skip_quoted without quote char
  2485. * and whitespace == delimiters */
  2486. static char *
  2487. skip(char **buf, const char *delimiters)
  2488. {
  2489. return skip_quoted(buf, delimiters, delimiters, 0);
  2490. }
  2491. /* Return HTTP header value, or NULL if not found. */
  2492. static const char *
  2493. get_header(const struct mg_request_info *ri, const char *name)
  2494. {
  2495. int i;
  2496. if (ri) {
  2497. for (i = 0; i < ri->num_headers; i++) {
  2498. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  2499. return ri->http_headers[i].value;
  2500. }
  2501. }
  2502. }
  2503. return NULL;
  2504. }
  2505. const char *
  2506. mg_get_header(const struct mg_connection *conn, const char *name)
  2507. {
  2508. if (!conn) {
  2509. return NULL;
  2510. }
  2511. return get_header(&conn->request_info, name);
  2512. }
  2513. /* A helper function for traversing a comma separated list of values.
  2514. * It returns a list pointer shifted to the next value, or NULL if the end
  2515. * of the list found.
  2516. * Value is stored in val vector. If value has form "x=y", then eq_val
  2517. * vector is initialized to point to the "y" part, and val vector length
  2518. * is adjusted to point only to "x". */
  2519. static const char *
  2520. next_option(const char *list, struct vec *val, struct vec *eq_val)
  2521. {
  2522. int end;
  2523. reparse:
  2524. if (val == NULL || list == NULL || *list == '\0') {
  2525. /* End of the list */
  2526. list = NULL;
  2527. } else {
  2528. /* Skip over leading LWS */
  2529. while (*list == ' ' || *list == '\t')
  2530. list++;
  2531. val->ptr = list;
  2532. if ((list = strchr(val->ptr, ',')) != NULL) {
  2533. /* Comma found. Store length and shift the list ptr */
  2534. val->len = ((size_t)(list - val->ptr));
  2535. list++;
  2536. } else {
  2537. /* This value is the last one */
  2538. list = val->ptr + strlen(val->ptr);
  2539. val->len = ((size_t)(list - val->ptr));
  2540. }
  2541. /* Adjust length for trailing LWS */
  2542. end = (int)val->len - 1;
  2543. while (end >= 0 && (val->ptr[end] == ' ' || val->ptr[end] == '\t'))
  2544. end--;
  2545. val->len = (size_t)(end + 1);
  2546. if (val->len == 0) {
  2547. /* Ignore any empty entries. */
  2548. goto reparse;
  2549. }
  2550. if (eq_val != NULL) {
  2551. /* Value has form "x=y", adjust pointers and lengths
  2552. * so that val points to "x", and eq_val points to "y". */
  2553. eq_val->len = 0;
  2554. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  2555. if (eq_val->ptr != NULL) {
  2556. eq_val->ptr++; /* Skip over '=' character */
  2557. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  2558. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  2559. }
  2560. }
  2561. }
  2562. return list;
  2563. }
  2564. /* A helper function for checking if a comma separated list of values contains
  2565. * the given option (case insensitvely).
  2566. * 'header' can be NULL, in which case false is returned. */
  2567. static int
  2568. header_has_option(const char *header, const char *option)
  2569. {
  2570. struct vec opt_vec;
  2571. struct vec eq_vec;
  2572. assert(option != NULL);
  2573. assert(option[0] != '\0');
  2574. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  2575. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  2576. return 1;
  2577. }
  2578. return 0;
  2579. }
  2580. /* Perform case-insensitive match of string against pattern */
  2581. static int
  2582. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  2583. {
  2584. const char *or_str;
  2585. size_t i;
  2586. int j, len, res;
  2587. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  2588. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  2589. return (res > 0) ? res : match_prefix(or_str + 1,
  2590. (size_t)((pattern + pattern_len)
  2591. - (or_str + 1)),
  2592. str);
  2593. }
  2594. for (i = 0, j = 0; i < pattern_len; i++, j++) {
  2595. if (pattern[i] == '?' && str[j] != '\0') {
  2596. continue;
  2597. } else if (pattern[i] == '$') {
  2598. return (str[j] == '\0') ? j : -1;
  2599. } else if (pattern[i] == '*') {
  2600. i++;
  2601. if (pattern[i] == '*') {
  2602. i++;
  2603. len = (int)strlen(str + j);
  2604. } else {
  2605. len = (int)strcspn(str + j, "/");
  2606. }
  2607. if (i == pattern_len) {
  2608. return j + len;
  2609. }
  2610. do {
  2611. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  2612. } while (res == -1 && len-- > 0);
  2613. return (res == -1) ? -1 : j + res + len;
  2614. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  2615. return -1;
  2616. }
  2617. }
  2618. return j;
  2619. }
  2620. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  2621. * This function must tolerate situations when connection info is not
  2622. * set up, for example if request parsing failed. */
  2623. static int
  2624. should_keep_alive(const struct mg_connection *conn)
  2625. {
  2626. if (conn != NULL) {
  2627. const char *http_version = conn->request_info.http_version;
  2628. const char *header = mg_get_header(conn, "Connection");
  2629. if (conn->must_close || conn->status_code == 401
  2630. || mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0
  2631. || (header != NULL && !header_has_option(header, "keep-alive"))
  2632. || (header == NULL && http_version
  2633. && 0 != strcmp(http_version, "1.1"))) {
  2634. return 0;
  2635. }
  2636. return 1;
  2637. }
  2638. return 0;
  2639. }
  2640. static int
  2641. should_decode_url(const struct mg_connection *conn)
  2642. {
  2643. if (!conn || !conn->ctx) {
  2644. return 0;
  2645. }
  2646. return (mg_strcasecmp(conn->ctx->config[DECODE_URL], "yes") == 0);
  2647. }
  2648. static const char *
  2649. suggest_connection_header(const struct mg_connection *conn)
  2650. {
  2651. return should_keep_alive(conn) ? "keep-alive" : "close";
  2652. }
  2653. static int
  2654. send_no_cache_header(struct mg_connection *conn)
  2655. {
  2656. /* Send all current and obsolete cache opt-out directives. */
  2657. return mg_printf(conn,
  2658. "Cache-Control: no-cache, no-store, "
  2659. "must-revalidate, private, max-age=0\r\n"
  2660. "Pragma: no-cache\r\n"
  2661. "Expires: 0\r\n");
  2662. }
  2663. static int
  2664. send_static_cache_header(struct mg_connection *conn)
  2665. {
  2666. #if !defined(NO_CACHING)
  2667. /* Read the server config to check how long a file may be cached.
  2668. * The configuration is in seconds. */
  2669. int max_age = atoi(conn->ctx->config[STATIC_FILE_MAX_AGE]);
  2670. if (max_age <= 0) {
  2671. /* 0 means "do not cache". All values <0 are reserved
  2672. * and may be used differently in the future. */
  2673. /* If a file should not be cached, do not only send
  2674. * max-age=0, but also pragmas and Expires headers. */
  2675. return send_no_cache_header(conn);
  2676. }
  2677. /* Use "Cache-Control: max-age" instead of "Expires" header.
  2678. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  2679. /* See also https://www.mnot.net/cache_docs/ */
  2680. /* According to RFC 2616, Section 14.21, caching times should not exceed
  2681. * one year. A year with 365 days corresponds to 31536000 seconds, a leap
  2682. * year to 31622400 seconds. For the moment, we just send whatever has
  2683. * been configured, still the behavior for >1 year should be considered
  2684. * as undefined. */
  2685. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  2686. #else /* NO_CACHING */
  2687. return send_no_cache_header(conn);
  2688. #endif /* !NO_CACHING */
  2689. }
  2690. static int
  2691. send_additional_header(struct mg_connection *conn)
  2692. {
  2693. int i = 0;
  2694. #if 0
  2695. i += mg_printf(conn, "Strict-Transport-Security: max-age=%u\r\n", 3600);
  2696. #endif
  2697. i += mg_printf(conn, "X-Some-Test-Header: %u\r\n", 42);
  2698. return i;
  2699. }
  2700. static void handle_file_based_request(struct mg_connection *conn,
  2701. const char *path,
  2702. struct mg_file *filep);
  2703. const char *
  2704. mg_get_response_code_text(struct mg_connection *conn, int response_code)
  2705. {
  2706. /* See IANA HTTP status code assignment:
  2707. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  2708. */
  2709. switch (response_code) {
  2710. /* RFC2616 Section 10.1 - Informational 1xx */
  2711. case 100:
  2712. return "Continue"; /* RFC2616 Section 10.1.1 */
  2713. case 101:
  2714. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  2715. case 102:
  2716. return "Processing"; /* RFC2518 Section 10.1 */
  2717. /* RFC2616 Section 10.2 - Successful 2xx */
  2718. case 200:
  2719. return "OK"; /* RFC2616 Section 10.2.1 */
  2720. case 201:
  2721. return "Created"; /* RFC2616 Section 10.2.2 */
  2722. case 202:
  2723. return "Accepted"; /* RFC2616 Section 10.2.3 */
  2724. case 203:
  2725. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  2726. case 204:
  2727. return "No Content"; /* RFC2616 Section 10.2.5 */
  2728. case 205:
  2729. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  2730. case 206:
  2731. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  2732. case 207:
  2733. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1 */
  2734. case 208:
  2735. return "Already Reported"; /* RFC5842 Section 7.1 */
  2736. case 226:
  2737. return "IM used"; /* RFC3229 Section 10.4.1 */
  2738. /* RFC2616 Section 10.3 - Redirection 3xx */
  2739. case 300:
  2740. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  2741. case 301:
  2742. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  2743. case 302:
  2744. return "Found"; /* RFC2616 Section 10.3.3 */
  2745. case 303:
  2746. return "See Other"; /* RFC2616 Section 10.3.4 */
  2747. case 304:
  2748. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  2749. case 305:
  2750. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  2751. case 307:
  2752. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  2753. case 308:
  2754. return "Permanent Redirect"; /* RFC7238 Section 3 */
  2755. /* RFC2616 Section 10.4 - Client Error 4xx */
  2756. case 400:
  2757. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  2758. case 401:
  2759. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  2760. case 402:
  2761. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  2762. case 403:
  2763. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  2764. case 404:
  2765. return "Not Found"; /* RFC2616 Section 10.4.5 */
  2766. case 405:
  2767. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  2768. case 406:
  2769. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  2770. case 407:
  2771. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  2772. case 408:
  2773. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  2774. case 409:
  2775. return "Conflict"; /* RFC2616 Section 10.4.10 */
  2776. case 410:
  2777. return "Gone"; /* RFC2616 Section 10.4.11 */
  2778. case 411:
  2779. return "Length Required"; /* RFC2616 Section 10.4.12 */
  2780. case 412:
  2781. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  2782. case 413:
  2783. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  2784. case 414:
  2785. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  2786. case 415:
  2787. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  2788. case 416:
  2789. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17 */
  2790. case 417:
  2791. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  2792. case 421:
  2793. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  2794. case 422:
  2795. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  2796. * Section 11.2 */
  2797. case 423:
  2798. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  2799. case 424:
  2800. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  2801. * Section 11.4 */
  2802. case 426:
  2803. return "Upgrade Required"; /* RFC 2817 Section 4 */
  2804. case 428:
  2805. return "Precondition Required"; /* RFC 6585, Section 3 */
  2806. case 429:
  2807. return "Too Many Requests"; /* RFC 6585, Section 4 */
  2808. case 431:
  2809. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  2810. case 451:
  2811. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  2812. * Section 3 */
  2813. /* RFC2616 Section 10.5 - Server Error 5xx */
  2814. case 500:
  2815. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  2816. case 501:
  2817. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  2818. case 502:
  2819. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  2820. case 503:
  2821. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  2822. case 504:
  2823. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  2824. case 505:
  2825. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  2826. case 506:
  2827. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  2828. case 507:
  2829. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  2830. * Section 11.5 */
  2831. case 508:
  2832. return "Loop Detected"; /* RFC5842 Section 7.1 */
  2833. case 510:
  2834. return "Not Extended"; /* RFC 2774, Section 7 */
  2835. case 511:
  2836. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  2837. /* Other status codes, not shown in the IANA HTTP status code assignment.
  2838. * E.g., "de facto" standards due to common use, ... */
  2839. case 418:
  2840. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  2841. case 419:
  2842. return "Authentication Timeout"; /* common use */
  2843. case 420:
  2844. return "Enhance Your Calm"; /* common use */
  2845. case 440:
  2846. return "Login Timeout"; /* common use */
  2847. case 509:
  2848. return "Bandwidth Limit Exceeded"; /* common use */
  2849. default:
  2850. /* This error code is unknown. This should not happen. */
  2851. if (conn) {
  2852. mg_cry(conn, "Unknown HTTP response code: %u", response_code);
  2853. }
  2854. /* Return at least a category according to RFC 2616 Section 10. */
  2855. if (response_code >= 100 && response_code < 200) {
  2856. /* Unknown informational status code */
  2857. return "Information";
  2858. }
  2859. if (response_code >= 200 && response_code < 300) {
  2860. /* Unknown success code */
  2861. return "Success";
  2862. }
  2863. if (response_code >= 300 && response_code < 400) {
  2864. /* Unknown redirection code */
  2865. return "Redirection";
  2866. }
  2867. if (response_code >= 400 && response_code < 500) {
  2868. /* Unknown request error code */
  2869. return "Client Error";
  2870. }
  2871. if (response_code >= 500 && response_code < 600) {
  2872. /* Unknown server error code */
  2873. return "Server Error";
  2874. }
  2875. /* Response code not even within reasonable range */
  2876. return "";
  2877. }
  2878. }
  2879. static void send_http_error(struct mg_connection *,
  2880. int,
  2881. PRINTF_FORMAT_STRING(const char *fmt),
  2882. ...) PRINTF_ARGS(3, 4);
  2883. static void
  2884. send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  2885. {
  2886. char buf[MG_BUF_LEN];
  2887. va_list ap;
  2888. int len, i, page_handler_found, scope, truncated, has_body;
  2889. char date[64];
  2890. time_t curtime = time(NULL);
  2891. const char *error_handler = NULL;
  2892. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  2893. const char *error_page_file_ext, *tstr;
  2894. const char *status_text = mg_get_response_code_text(conn, status);
  2895. if (conn == NULL) {
  2896. return;
  2897. }
  2898. conn->status_code = status;
  2899. if (conn->in_error_handler || conn->ctx->callbacks.http_error == NULL
  2900. || conn->ctx->callbacks.http_error(conn, status)) {
  2901. if (!conn->in_error_handler) {
  2902. /* Send user defined error pages, if defined */
  2903. error_handler = conn->ctx->config[ERROR_PAGES];
  2904. error_page_file_ext = conn->ctx->config[INDEX_FILES];
  2905. page_handler_found = 0;
  2906. if (error_handler != NULL) {
  2907. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  2908. switch (scope) {
  2909. case 1: /* Handler for specific error, e.g. 404 error */
  2910. mg_snprintf(conn,
  2911. &truncated,
  2912. buf,
  2913. sizeof(buf) - 32,
  2914. "%serror%03u.",
  2915. error_handler,
  2916. status);
  2917. break;
  2918. case 2: /* Handler for error group, e.g., 5xx error handler
  2919. * for all server errors (500-599) */
  2920. mg_snprintf(conn,
  2921. &truncated,
  2922. buf,
  2923. sizeof(buf) - 32,
  2924. "%serror%01uxx.",
  2925. error_handler,
  2926. status / 100);
  2927. break;
  2928. default: /* Handler for all errors */
  2929. mg_snprintf(conn,
  2930. &truncated,
  2931. buf,
  2932. sizeof(buf) - 32,
  2933. "%serror.",
  2934. error_handler);
  2935. break;
  2936. }
  2937. /* String truncation in buf may only occur if error_handler
  2938. * is too long. This string is from the config, not from a
  2939. * client. */
  2940. (void)truncated;
  2941. len = (int)strlen(buf);
  2942. tstr = strchr(error_page_file_ext, '.');
  2943. while (tstr) {
  2944. for (i = 1; i < 32 && tstr[i] != 0 && tstr[i] != ',';
  2945. i++)
  2946. buf[len + i - 1] = tstr[i];
  2947. buf[len + i - 1] = 0;
  2948. if (mg_stat(conn, buf, &error_page_file.stat)) {
  2949. page_handler_found = 1;
  2950. break;
  2951. }
  2952. tstr = strchr(tstr + i, '.');
  2953. }
  2954. }
  2955. }
  2956. if (page_handler_found) {
  2957. conn->in_error_handler = 1;
  2958. handle_file_based_request(conn, buf, &error_page_file);
  2959. conn->in_error_handler = 0;
  2960. return;
  2961. }
  2962. }
  2963. /* No custom error page. Send default error page. */
  2964. gmt_time_string(date, sizeof(date), &curtime);
  2965. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  2966. has_body = (status > 199 && status != 204 && status != 304);
  2967. conn->must_close = 1;
  2968. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  2969. send_no_cache_header(conn);
  2970. send_additional_header(conn);
  2971. if (has_body) {
  2972. mg_printf(conn,
  2973. "%s",
  2974. "Content-Type: text/plain; charset=utf-8\r\n");
  2975. }
  2976. mg_printf(conn,
  2977. "Date: %s\r\n"
  2978. "Connection: close\r\n\r\n",
  2979. date);
  2980. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  2981. if (has_body) {
  2982. mg_printf(conn, "Error %d: %s\n", status, status_text);
  2983. if (fmt != NULL) {
  2984. va_start(ap, fmt);
  2985. mg_vsnprintf(conn, NULL, buf, sizeof(buf), fmt, ap);
  2986. va_end(ap);
  2987. mg_write(conn, buf, strlen(buf));
  2988. DEBUG_TRACE("Error %i - [%s]", status, buf);
  2989. }
  2990. } else {
  2991. /* No body allowed. Close the connection. */
  2992. DEBUG_TRACE("Error %i", status);
  2993. }
  2994. }
  2995. }
  2996. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  2997. /* Create substitutes for POSIX functions in Win32. */
  2998. #if defined(__MINGW32__)
  2999. /* Show no warning in case system functions are not used. */
  3000. #pragma GCC diagnostic push
  3001. #pragma GCC diagnostic ignored "-Wunused-function"
  3002. #endif
  3003. static int
  3004. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  3005. {
  3006. (void)unused;
  3007. *mutex = CreateMutex(NULL, FALSE, NULL);
  3008. return (*mutex == NULL) ? -1 : 0;
  3009. }
  3010. static int
  3011. pthread_mutex_destroy(pthread_mutex_t *mutex)
  3012. {
  3013. return (CloseHandle(*mutex) == 0) ? -1 : 0;
  3014. }
  3015. static int
  3016. pthread_mutex_lock(pthread_mutex_t *mutex)
  3017. {
  3018. return (WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0) ? 0 : -1;
  3019. }
  3020. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  3021. static int
  3022. pthread_mutex_trylock(pthread_mutex_t *mutex)
  3023. {
  3024. switch (WaitForSingleObject(*mutex, 0)) {
  3025. case WAIT_OBJECT_0:
  3026. return 0;
  3027. case WAIT_TIMEOUT:
  3028. return -2; /* EBUSY */
  3029. }
  3030. return -1;
  3031. }
  3032. #endif
  3033. static int
  3034. pthread_mutex_unlock(pthread_mutex_t *mutex)
  3035. {
  3036. return (ReleaseMutex(*mutex) == 0) ? -1 : 0;
  3037. }
  3038. static int
  3039. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  3040. {
  3041. (void)unused;
  3042. InitializeCriticalSection(&cv->threadIdSec);
  3043. cv->waiting_thread = NULL;
  3044. return 0;
  3045. }
  3046. static int
  3047. pthread_cond_timedwait(pthread_cond_t *cv,
  3048. pthread_mutex_t *mutex,
  3049. const struct timespec *abstime)
  3050. {
  3051. struct mg_workerTLS **ptls,
  3052. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3053. int ok;
  3054. int64_t nsnow, nswaitabs, nswaitrel;
  3055. DWORD mswaitrel;
  3056. EnterCriticalSection(&cv->threadIdSec);
  3057. /* Add this thread to cv's waiting list */
  3058. ptls = &cv->waiting_thread;
  3059. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  3060. ;
  3061. tls->next_waiting_thread = NULL;
  3062. *ptls = tls;
  3063. LeaveCriticalSection(&cv->threadIdSec);
  3064. if (abstime) {
  3065. nsnow = mg_get_current_time_ns();
  3066. nswaitabs =
  3067. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  3068. nswaitrel = nswaitabs - nsnow;
  3069. if (nswaitrel < 0) {
  3070. nswaitrel = 0;
  3071. }
  3072. mswaitrel = (DWORD)(nswaitrel / 1000000);
  3073. } else {
  3074. mswaitrel = INFINITE;
  3075. }
  3076. pthread_mutex_unlock(mutex);
  3077. ok = (WAIT_OBJECT_0
  3078. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  3079. if (!ok) {
  3080. ok = 1;
  3081. EnterCriticalSection(&cv->threadIdSec);
  3082. ptls = &cv->waiting_thread;
  3083. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  3084. if (*ptls == tls) {
  3085. *ptls = tls->next_waiting_thread;
  3086. ok = 0;
  3087. break;
  3088. }
  3089. }
  3090. LeaveCriticalSection(&cv->threadIdSec);
  3091. if (ok) {
  3092. WaitForSingleObject(tls->pthread_cond_helper_mutex, INFINITE);
  3093. }
  3094. }
  3095. /* This thread has been removed from cv's waiting list */
  3096. pthread_mutex_lock(mutex);
  3097. return ok ? 0 : -1;
  3098. }
  3099. static int
  3100. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  3101. {
  3102. return pthread_cond_timedwait(cv, mutex, NULL);
  3103. }
  3104. static int
  3105. pthread_cond_signal(pthread_cond_t *cv)
  3106. {
  3107. HANDLE wkup = NULL;
  3108. BOOL ok = FALSE;
  3109. EnterCriticalSection(&cv->threadIdSec);
  3110. if (cv->waiting_thread) {
  3111. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  3112. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  3113. ok = SetEvent(wkup);
  3114. assert(ok);
  3115. }
  3116. LeaveCriticalSection(&cv->threadIdSec);
  3117. return ok ? 0 : 1;
  3118. }
  3119. static int
  3120. pthread_cond_broadcast(pthread_cond_t *cv)
  3121. {
  3122. EnterCriticalSection(&cv->threadIdSec);
  3123. while (cv->waiting_thread) {
  3124. pthread_cond_signal(cv);
  3125. }
  3126. LeaveCriticalSection(&cv->threadIdSec);
  3127. return 0;
  3128. }
  3129. static int
  3130. pthread_cond_destroy(pthread_cond_t *cv)
  3131. {
  3132. EnterCriticalSection(&cv->threadIdSec);
  3133. assert(cv->waiting_thread == NULL);
  3134. LeaveCriticalSection(&cv->threadIdSec);
  3135. DeleteCriticalSection(&cv->threadIdSec);
  3136. return 0;
  3137. }
  3138. #ifdef ALTERNATIVE_QUEUE
  3139. static void *
  3140. event_create(void)
  3141. {
  3142. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  3143. }
  3144. static int
  3145. event_wait(void *eventhdl)
  3146. {
  3147. int res = WaitForSingleObject((HANDLE)eventhdl, INFINITE);
  3148. return (res == WAIT_OBJECT_0);
  3149. }
  3150. static int
  3151. event_signal(void *eventhdl)
  3152. {
  3153. return (int)SetEvent((HANDLE)eventhdl);
  3154. }
  3155. static void
  3156. event_destroy(void *eventhdl)
  3157. {
  3158. CloseHandle((HANDLE)eventhdl);
  3159. }
  3160. #endif
  3161. #if defined(__MINGW32__)
  3162. /* Enable unused function warning again */
  3163. #pragma GCC diagnostic pop
  3164. #endif
  3165. /* For Windows, change all slashes to backslashes in path names. */
  3166. static void
  3167. change_slashes_to_backslashes(char *path)
  3168. {
  3169. int i;
  3170. for (i = 0; path[i] != '\0'; i++) {
  3171. if (path[i] == '/') {
  3172. path[i] = '\\';
  3173. }
  3174. /* remove double backslash (check i > 0 to preserve UNC paths,
  3175. * like \\server\file.txt) */
  3176. if ((path[i] == '\\') && (i > 0)) {
  3177. while (path[i + 1] == '\\' || path[i + 1] == '/') {
  3178. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  3179. }
  3180. }
  3181. }
  3182. }
  3183. static int
  3184. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  3185. {
  3186. int diff;
  3187. do {
  3188. diff = tolower(*s1) - tolower(*s2);
  3189. s1++;
  3190. s2++;
  3191. } while (diff == 0 && s1[-1] != '\0');
  3192. return diff;
  3193. }
  3194. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  3195. * wbuf and wbuf_len is a target buffer and its length. */
  3196. static void
  3197. path_to_unicode(const struct mg_connection *conn,
  3198. const char *path,
  3199. wchar_t *wbuf,
  3200. size_t wbuf_len)
  3201. {
  3202. char buf[PATH_MAX], buf2[PATH_MAX];
  3203. wchar_t wbuf2[MAX_PATH + 1];
  3204. DWORD long_len, err;
  3205. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  3206. mg_strlcpy(buf, path, sizeof(buf));
  3207. change_slashes_to_backslashes(buf);
  3208. /* Convert to Unicode and back. If doubly-converted string does not
  3209. * match the original, something is fishy, reject. */
  3210. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  3211. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  3212. WideCharToMultiByte(
  3213. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  3214. if (strcmp(buf, buf2) != 0) {
  3215. wbuf[0] = L'\0';
  3216. }
  3217. /* Windows file systems are not case sensitive, but you can still use
  3218. * uppercase and lowercase letters (on all modern file systems).
  3219. * The server can check if the URI uses the same upper/lowercase
  3220. * letters an the file system, effectively making Windows servers
  3221. * case sensitive (like Linux servers are). It is still not possible
  3222. * to use two files with the same name in different cases on Windows
  3223. * (like /a and /A) - this would be possible in Linux.
  3224. * As a default, Windows is not case sensitive, but the case sensitive
  3225. * file name check can be activated by an additional configuration. */
  3226. if (conn) {
  3227. if (conn->ctx->config[CASE_SENSITIVE_FILES]
  3228. && !mg_strcasecmp(conn->ctx->config[CASE_SENSITIVE_FILES], "yes")) {
  3229. /* Use case sensitive compare function */
  3230. fcompare = wcscmp;
  3231. }
  3232. }
  3233. (void)conn; /* conn is currently unused */
  3234. #if !defined(_WIN32_WCE)
  3235. /* Only accept a full file path, not a Windows short (8.3) path. */
  3236. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  3237. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  3238. if (long_len == 0) {
  3239. err = GetLastError();
  3240. if (err == ERROR_FILE_NOT_FOUND) {
  3241. /* File does not exist. This is not always a problem here. */
  3242. return;
  3243. }
  3244. }
  3245. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  3246. /* Short name is used. */
  3247. wbuf[0] = L'\0';
  3248. }
  3249. #else
  3250. (void)long_len;
  3251. (void)wbuf2;
  3252. (void)err;
  3253. if (strchr(path, '~')) {
  3254. wbuf[0] = L'\0';
  3255. }
  3256. #endif
  3257. }
  3258. /* Windows happily opens files with some garbage at the end of file name.
  3259. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  3260. * "a.cgi", despite one would expect an error back.
  3261. * This function returns non-0 if path ends with some garbage. */
  3262. static int
  3263. path_cannot_disclose_cgi(const char *path)
  3264. {
  3265. static const char *allowed_last_characters = "_-";
  3266. int last = path[strlen(path) - 1];
  3267. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  3268. }
  3269. static int
  3270. mg_stat(const struct mg_connection *conn,
  3271. const char *path,
  3272. struct mg_file_stat *filep)
  3273. {
  3274. wchar_t wbuf[PATH_MAX];
  3275. WIN32_FILE_ATTRIBUTE_DATA info;
  3276. time_t creation_time;
  3277. if (!filep) {
  3278. return 0;
  3279. }
  3280. memset(filep, 0, sizeof(*filep));
  3281. if (conn && is_file_in_memory(conn, path)) {
  3282. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  3283. * memset */
  3284. /* Quick fix (for 1.9.x): */
  3285. /* mg_stat must fill all fields, also for files in memory */
  3286. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  3287. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  3288. filep->size = tmp_file.stat.size;
  3289. filep->location = 2;
  3290. /* TODO: for 1.10: restructure how files in memory are handled */
  3291. filep->last_modified = time(NULL); /* xxxxxxxx */
  3292. /* last_modified = now ... assumes the file may change during runtime,
  3293. * so every mg_fopen call may return different data */
  3294. /* last_modified = conn->ctx.start_time;
  3295. * May be used it the data does not change during runtime. This allows
  3296. * browser caching. Since we do not know, we have to assume the file
  3297. * in memory may change. */
  3298. return 1;
  3299. }
  3300. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3301. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  3302. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  3303. filep->last_modified =
  3304. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  3305. info.ftLastWriteTime.dwHighDateTime);
  3306. /* On Windows, the file creation time can be higher than the
  3307. * modification time, e.g. when a file is copied.
  3308. * Since the Last-Modified timestamp is used for caching
  3309. * it should be based on the most recent timestamp. */
  3310. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  3311. info.ftCreationTime.dwHighDateTime);
  3312. if (creation_time > filep->last_modified) {
  3313. filep->last_modified = creation_time;
  3314. }
  3315. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  3316. /* If file name is fishy, reset the file structure and return
  3317. * error.
  3318. * Note it is important to reset, not just return the error, cause
  3319. * functions like is_file_opened() check the struct. */
  3320. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  3321. memset(filep, 0, sizeof(*filep));
  3322. return 0;
  3323. }
  3324. return 1;
  3325. }
  3326. return 0;
  3327. }
  3328. static int
  3329. mg_remove(const struct mg_connection *conn, const char *path)
  3330. {
  3331. wchar_t wbuf[PATH_MAX];
  3332. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3333. return DeleteFileW(wbuf) ? 0 : -1;
  3334. }
  3335. static int
  3336. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  3337. {
  3338. wchar_t wbuf[PATH_MAX];
  3339. (void)mode;
  3340. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3341. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  3342. }
  3343. /* Create substitutes for POSIX functions in Win32. */
  3344. #if defined(__MINGW32__)
  3345. /* Show no warning in case system functions are not used. */
  3346. #pragma GCC diagnostic push
  3347. #pragma GCC diagnostic ignored "-Wunused-function"
  3348. #endif
  3349. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  3350. static DIR *
  3351. mg_opendir(const struct mg_connection *conn, const char *name)
  3352. {
  3353. DIR *dir = NULL;
  3354. wchar_t wpath[PATH_MAX];
  3355. DWORD attrs;
  3356. if (name == NULL) {
  3357. SetLastError(ERROR_BAD_ARGUMENTS);
  3358. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  3359. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  3360. } else {
  3361. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  3362. attrs = GetFileAttributesW(wpath);
  3363. if (attrs != 0xFFFFFFFF && ((attrs & FILE_ATTRIBUTE_DIRECTORY)
  3364. == FILE_ATTRIBUTE_DIRECTORY)) {
  3365. (void)wcscat(wpath, L"\\*");
  3366. dir->handle = FindFirstFileW(wpath, &dir->info);
  3367. dir->result.d_name[0] = '\0';
  3368. } else {
  3369. mg_free(dir);
  3370. dir = NULL;
  3371. }
  3372. }
  3373. return dir;
  3374. }
  3375. static int
  3376. mg_closedir(DIR *dir)
  3377. {
  3378. int result = 0;
  3379. if (dir != NULL) {
  3380. if (dir->handle != INVALID_HANDLE_VALUE)
  3381. result = FindClose(dir->handle) ? 0 : -1;
  3382. mg_free(dir);
  3383. } else {
  3384. result = -1;
  3385. SetLastError(ERROR_BAD_ARGUMENTS);
  3386. }
  3387. return result;
  3388. }
  3389. static struct dirent *
  3390. mg_readdir(DIR *dir)
  3391. {
  3392. struct dirent *result = 0;
  3393. if (dir) {
  3394. if (dir->handle != INVALID_HANDLE_VALUE) {
  3395. result = &dir->result;
  3396. (void)WideCharToMultiByte(CP_UTF8,
  3397. 0,
  3398. dir->info.cFileName,
  3399. -1,
  3400. result->d_name,
  3401. sizeof(result->d_name),
  3402. NULL,
  3403. NULL);
  3404. if (!FindNextFileW(dir->handle, &dir->info)) {
  3405. (void)FindClose(dir->handle);
  3406. dir->handle = INVALID_HANDLE_VALUE;
  3407. }
  3408. } else {
  3409. SetLastError(ERROR_FILE_NOT_FOUND);
  3410. }
  3411. } else {
  3412. SetLastError(ERROR_BAD_ARGUMENTS);
  3413. }
  3414. return result;
  3415. }
  3416. #ifndef HAVE_POLL
  3417. static int
  3418. poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  3419. {
  3420. struct timeval tv;
  3421. fd_set set;
  3422. unsigned int i;
  3423. int result;
  3424. SOCKET maxfd = 0;
  3425. memset(&tv, 0, sizeof(tv));
  3426. tv.tv_sec = milliseconds / 1000;
  3427. tv.tv_usec = (milliseconds % 1000) * 1000;
  3428. FD_ZERO(&set);
  3429. for (i = 0; i < n; i++) {
  3430. FD_SET((SOCKET)pfd[i].fd, &set);
  3431. pfd[i].revents = 0;
  3432. if (pfd[i].fd > maxfd) {
  3433. maxfd = pfd[i].fd;
  3434. }
  3435. }
  3436. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  3437. for (i = 0; i < n; i++) {
  3438. if (FD_ISSET(pfd[i].fd, &set)) {
  3439. pfd[i].revents = POLLIN;
  3440. }
  3441. }
  3442. }
  3443. /* We should subtract the time used in select from remaining
  3444. * "milliseconds", in particular if called from mg_poll with a
  3445. * timeout quantum.
  3446. * Unfortunately, the remaining time is not stored in "tv" in all
  3447. * implementations, so the result in "tv" must be considered undefined.
  3448. * See http://man7.org/linux/man-pages/man2/select.2.html */
  3449. return result;
  3450. }
  3451. #endif /* HAVE_POLL */
  3452. #if defined(__MINGW32__)
  3453. /* Enable unused function warning again */
  3454. #pragma GCC diagnostic pop
  3455. #endif
  3456. static void
  3457. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  3458. {
  3459. (void)conn; /* Unused. */
  3460. #if defined(_WIN32_WCE)
  3461. (void)sock;
  3462. #else
  3463. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  3464. #endif
  3465. }
  3466. int
  3467. mg_start_thread(mg_thread_func_t f, void *p)
  3468. {
  3469. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3470. /* Compile-time option to control stack size, e.g. -DUSE_STACK_SIZE=16384
  3471. */
  3472. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  3473. == ((uintptr_t)(-1L)))
  3474. ? -1
  3475. : 0);
  3476. #else
  3477. return (
  3478. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  3479. ? -1
  3480. : 0);
  3481. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3482. }
  3483. /* Start a thread storing the thread context. */
  3484. static int
  3485. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  3486. void *p,
  3487. pthread_t *threadidptr)
  3488. {
  3489. uintptr_t uip;
  3490. HANDLE threadhandle;
  3491. int result = -1;
  3492. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  3493. threadhandle = (HANDLE)uip;
  3494. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  3495. *threadidptr = threadhandle;
  3496. result = 0;
  3497. }
  3498. return result;
  3499. }
  3500. /* Wait for a thread to finish. */
  3501. static int
  3502. mg_join_thread(pthread_t threadid)
  3503. {
  3504. int result;
  3505. DWORD dwevent;
  3506. result = -1;
  3507. dwevent = WaitForSingleObject(threadid, INFINITE);
  3508. if (dwevent == WAIT_FAILED) {
  3509. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  3510. } else {
  3511. if (dwevent == WAIT_OBJECT_0) {
  3512. CloseHandle(threadid);
  3513. result = 0;
  3514. }
  3515. }
  3516. return result;
  3517. }
  3518. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  3519. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  3520. /* Create substitutes for POSIX functions in Win32. */
  3521. #if defined(__MINGW32__)
  3522. /* Show no warning in case system functions are not used. */
  3523. #pragma GCC diagnostic push
  3524. #pragma GCC diagnostic ignored "-Wunused-function"
  3525. #endif
  3526. static HANDLE
  3527. dlopen(const char *dll_name, int flags)
  3528. {
  3529. wchar_t wbuf[PATH_MAX];
  3530. (void)flags;
  3531. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  3532. return LoadLibraryW(wbuf);
  3533. }
  3534. static int
  3535. dlclose(void *handle)
  3536. {
  3537. int result;
  3538. if (FreeLibrary((HMODULE)handle) != 0) {
  3539. result = 0;
  3540. } else {
  3541. result = -1;
  3542. }
  3543. return result;
  3544. }
  3545. #if defined(__MINGW32__)
  3546. /* Enable unused function warning again */
  3547. #pragma GCC diagnostic pop
  3548. #endif
  3549. #endif
  3550. #if !defined(NO_CGI)
  3551. #define SIGKILL (0)
  3552. static int
  3553. kill(pid_t pid, int sig_num)
  3554. {
  3555. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  3556. (void)CloseHandle((HANDLE)pid);
  3557. return 0;
  3558. }
  3559. static void
  3560. trim_trailing_whitespaces(char *s)
  3561. {
  3562. char *e = s + strlen(s) - 1;
  3563. while (e > s && isspace(*(unsigned char *)e)) {
  3564. *e-- = '\0';
  3565. }
  3566. }
  3567. static pid_t
  3568. spawn_process(struct mg_connection *conn,
  3569. const char *prog,
  3570. char *envblk,
  3571. char *envp[],
  3572. int fdin[2],
  3573. int fdout[2],
  3574. int fderr[2],
  3575. const char *dir)
  3576. {
  3577. HANDLE me;
  3578. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  3579. cmdline[PATH_MAX], buf[PATH_MAX];
  3580. int truncated;
  3581. struct mg_file file = STRUCT_FILE_INITIALIZER;
  3582. STARTUPINFOA si;
  3583. PROCESS_INFORMATION pi = {0};
  3584. (void)envp;
  3585. memset(&si, 0, sizeof(si));
  3586. si.cb = sizeof(si);
  3587. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  3588. si.wShowWindow = SW_HIDE;
  3589. me = GetCurrentProcess();
  3590. DuplicateHandle(me,
  3591. (HANDLE)_get_osfhandle(fdin[0]),
  3592. me,
  3593. &si.hStdInput,
  3594. 0,
  3595. TRUE,
  3596. DUPLICATE_SAME_ACCESS);
  3597. DuplicateHandle(me,
  3598. (HANDLE)_get_osfhandle(fdout[1]),
  3599. me,
  3600. &si.hStdOutput,
  3601. 0,
  3602. TRUE,
  3603. DUPLICATE_SAME_ACCESS);
  3604. DuplicateHandle(me,
  3605. (HANDLE)_get_osfhandle(fderr[1]),
  3606. me,
  3607. &si.hStdError,
  3608. 0,
  3609. TRUE,
  3610. DUPLICATE_SAME_ACCESS);
  3611. /* Mark handles that should not be inherited. See
  3612. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  3613. */
  3614. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  3615. HANDLE_FLAG_INHERIT,
  3616. 0);
  3617. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  3618. HANDLE_FLAG_INHERIT,
  3619. 0);
  3620. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  3621. HANDLE_FLAG_INHERIT,
  3622. 0);
  3623. /* If CGI file is a script, try to read the interpreter line */
  3624. interp = conn->ctx->config[CGI_INTERPRETER];
  3625. if (interp == NULL) {
  3626. buf[0] = buf[1] = '\0';
  3627. /* Read the first line of the script into the buffer */
  3628. mg_snprintf(
  3629. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  3630. if (truncated) {
  3631. pi.hProcess = (pid_t)-1;
  3632. goto spawn_cleanup;
  3633. }
  3634. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  3635. p = (char *)file.access.membuf;
  3636. mg_fgets(buf, sizeof(buf), &file, &p);
  3637. (void)mg_fclose(&file.access); /* ignore error on read only file */
  3638. buf[sizeof(buf) - 1] = '\0';
  3639. }
  3640. if (buf[0] == '#' && buf[1] == '!') {
  3641. trim_trailing_whitespaces(buf + 2);
  3642. } else {
  3643. buf[2] = '\0';
  3644. }
  3645. interp = buf + 2;
  3646. }
  3647. if (interp[0] != '\0') {
  3648. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  3649. interp = full_interp;
  3650. }
  3651. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  3652. if (interp[0] != '\0') {
  3653. mg_snprintf(conn,
  3654. &truncated,
  3655. cmdline,
  3656. sizeof(cmdline),
  3657. "\"%s\" \"%s\\%s\"",
  3658. interp,
  3659. full_dir,
  3660. prog);
  3661. } else {
  3662. mg_snprintf(conn,
  3663. &truncated,
  3664. cmdline,
  3665. sizeof(cmdline),
  3666. "\"%s\\%s\"",
  3667. full_dir,
  3668. prog);
  3669. }
  3670. if (truncated) {
  3671. pi.hProcess = (pid_t)-1;
  3672. goto spawn_cleanup;
  3673. }
  3674. DEBUG_TRACE("Running [%s]", cmdline);
  3675. if (CreateProcessA(NULL,
  3676. cmdline,
  3677. NULL,
  3678. NULL,
  3679. TRUE,
  3680. CREATE_NEW_PROCESS_GROUP,
  3681. envblk,
  3682. NULL,
  3683. &si,
  3684. &pi) == 0) {
  3685. mg_cry(
  3686. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  3687. pi.hProcess = (pid_t)-1;
  3688. /* goto spawn_cleanup; */
  3689. }
  3690. spawn_cleanup:
  3691. (void)CloseHandle(si.hStdOutput);
  3692. (void)CloseHandle(si.hStdError);
  3693. (void)CloseHandle(si.hStdInput);
  3694. if (pi.hThread != NULL) {
  3695. (void)CloseHandle(pi.hThread);
  3696. }
  3697. return (pid_t)pi.hProcess;
  3698. }
  3699. #endif /* !NO_CGI */
  3700. static int
  3701. set_blocking_mode(SOCKET sock, int blocking)
  3702. {
  3703. unsigned long non_blocking = !blocking;
  3704. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  3705. }
  3706. #else
  3707. static int
  3708. mg_stat(const struct mg_connection *conn,
  3709. const char *path,
  3710. struct mg_file_stat *filep)
  3711. {
  3712. struct stat st;
  3713. if (!filep) {
  3714. return 0;
  3715. }
  3716. memset(filep, 0, sizeof(*filep));
  3717. if (conn && is_file_in_memory(conn, path)) {
  3718. /* Quick fix (for 1.9.x): */
  3719. /* mg_stat must fill all fields, also for files in memory */
  3720. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  3721. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  3722. filep->size = tmp_file.stat.size;
  3723. filep->last_modified = time(NULL);
  3724. filep->location = 2;
  3725. /* TODO: for 1.10: restructure how files in memory are handled */
  3726. return 1;
  3727. }
  3728. if (0 == stat(path, &st)) {
  3729. filep->size = (uint64_t)(st.st_size);
  3730. filep->last_modified = st.st_mtime;
  3731. filep->is_directory = S_ISDIR(st.st_mode);
  3732. return 1;
  3733. }
  3734. return 0;
  3735. }
  3736. static void
  3737. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  3738. {
  3739. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  3740. if (conn) {
  3741. mg_cry(conn,
  3742. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  3743. __func__,
  3744. strerror(ERRNO));
  3745. }
  3746. }
  3747. }
  3748. int
  3749. mg_start_thread(mg_thread_func_t func, void *param)
  3750. {
  3751. pthread_t thread_id;
  3752. pthread_attr_t attr;
  3753. int result;
  3754. (void)pthread_attr_init(&attr);
  3755. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  3756. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3757. /* Compile-time option to control stack size,
  3758. * e.g. -DUSE_STACK_SIZE=16384 */
  3759. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3760. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3761. result = pthread_create(&thread_id, &attr, func, param);
  3762. pthread_attr_destroy(&attr);
  3763. return result;
  3764. }
  3765. /* Start a thread storing the thread context. */
  3766. static int
  3767. mg_start_thread_with_id(mg_thread_func_t func,
  3768. void *param,
  3769. pthread_t *threadidptr)
  3770. {
  3771. pthread_t thread_id;
  3772. pthread_attr_t attr;
  3773. int result;
  3774. (void)pthread_attr_init(&attr);
  3775. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3776. /* Compile-time option to control stack size,
  3777. * e.g. -DUSE_STACK_SIZE=16384 */
  3778. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3779. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  3780. result = pthread_create(&thread_id, &attr, func, param);
  3781. pthread_attr_destroy(&attr);
  3782. if ((result == 0) && (threadidptr != NULL)) {
  3783. *threadidptr = thread_id;
  3784. }
  3785. return result;
  3786. }
  3787. /* Wait for a thread to finish. */
  3788. static int
  3789. mg_join_thread(pthread_t threadid)
  3790. {
  3791. int result;
  3792. result = pthread_join(threadid, NULL);
  3793. return result;
  3794. }
  3795. #ifndef NO_CGI
  3796. static pid_t
  3797. spawn_process(struct mg_connection *conn,
  3798. const char *prog,
  3799. char *envblk,
  3800. char *envp[],
  3801. int fdin[2],
  3802. int fdout[2],
  3803. int fderr[2],
  3804. const char *dir)
  3805. {
  3806. pid_t pid;
  3807. const char *interp;
  3808. (void)envblk;
  3809. if (conn == NULL) {
  3810. return 0;
  3811. }
  3812. if ((pid = fork()) == -1) {
  3813. /* Parent */
  3814. send_http_error(conn,
  3815. 500,
  3816. "Error: Creating CGI process\nfork(): %s",
  3817. strerror(ERRNO));
  3818. } else if (pid == 0) {
  3819. /* Child */
  3820. if (chdir(dir) != 0) {
  3821. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  3822. } else if (dup2(fdin[0], 0) == -1) {
  3823. mg_cry(conn,
  3824. "%s: dup2(%d, 0): %s",
  3825. __func__,
  3826. fdin[0],
  3827. strerror(ERRNO));
  3828. } else if (dup2(fdout[1], 1) == -1) {
  3829. mg_cry(conn,
  3830. "%s: dup2(%d, 1): %s",
  3831. __func__,
  3832. fdout[1],
  3833. strerror(ERRNO));
  3834. } else if (dup2(fderr[1], 2) == -1) {
  3835. mg_cry(conn,
  3836. "%s: dup2(%d, 2): %s",
  3837. __func__,
  3838. fderr[1],
  3839. strerror(ERRNO));
  3840. } else {
  3841. /* Keep stderr and stdout in two different pipes.
  3842. * Stdout will be sent back to the client,
  3843. * stderr should go into a server error log. */
  3844. (void)close(fdin[0]);
  3845. (void)close(fdout[1]);
  3846. (void)close(fderr[1]);
  3847. /* Close write end fdin and read end fdout and fderr */
  3848. (void)close(fdin[1]);
  3849. (void)close(fdout[0]);
  3850. (void)close(fderr[0]);
  3851. /* After exec, all signal handlers are restored to their default
  3852. * values, with one exception of SIGCHLD. According to
  3853. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler will
  3854. * leave unchanged after exec if it was set to be ignored. Restore
  3855. * it to default action. */
  3856. signal(SIGCHLD, SIG_DFL);
  3857. interp = conn->ctx->config[CGI_INTERPRETER];
  3858. if (interp == NULL) {
  3859. (void)execle(prog, prog, NULL, envp);
  3860. mg_cry(conn,
  3861. "%s: execle(%s): %s",
  3862. __func__,
  3863. prog,
  3864. strerror(ERRNO));
  3865. } else {
  3866. (void)execle(interp, interp, prog, NULL, envp);
  3867. mg_cry(conn,
  3868. "%s: execle(%s %s): %s",
  3869. __func__,
  3870. interp,
  3871. prog,
  3872. strerror(ERRNO));
  3873. }
  3874. }
  3875. exit(EXIT_FAILURE);
  3876. }
  3877. return pid;
  3878. }
  3879. #endif /* !NO_CGI */
  3880. static int
  3881. set_blocking_mode(SOCKET sock, int blocking)
  3882. {
  3883. int flags;
  3884. flags = fcntl(sock, F_GETFL, 0);
  3885. if (blocking) {
  3886. (void)fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  3887. } else {
  3888. (void)fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK)));
  3889. }
  3890. return 0;
  3891. }
  3892. #endif /* _WIN32 */
  3893. /* End of initial operating system specific define block. */
  3894. /* Get a random number (independent of C rand function) */
  3895. static uint64_t
  3896. get_random(void)
  3897. {
  3898. static uint64_t lfsr = 0; /* Linear feedback shift register */
  3899. static uint64_t lcg = 0; /* Linear congruential generator */
  3900. uint64_t now = mg_get_current_time_ns();
  3901. if (lfsr == 0) {
  3902. /* lfsr will be only 0 if has not been initialized,
  3903. * so this code is called only once. */
  3904. lfsr = mg_get_current_time_ns();
  3905. lcg = mg_get_current_time_ns();
  3906. } else {
  3907. /* Get the next step of both random number generators. */
  3908. lfsr = (lfsr >> 1)
  3909. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  3910. << 63);
  3911. lcg = lcg * 6364136223846793005 + 1442695040888963407;
  3912. }
  3913. /* Combining two pseudo-random number generators and a high resolution part
  3914. * of the current server time will make it hard (impossible?) to guess the
  3915. * next number. */
  3916. return (lfsr ^ lcg ^ now);
  3917. }
  3918. static int
  3919. mg_poll(struct pollfd *pfd,
  3920. unsigned int n,
  3921. int milliseconds,
  3922. volatile int *stop_server)
  3923. {
  3924. int ms_now, result;
  3925. /* Call poll, but only for a maximum time of a few seconds.
  3926. * This will allow to stop the server after some seconds, instead
  3927. * of having to wait for a long socket timeout. */
  3928. ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  3929. do {
  3930. if (*stop_server) {
  3931. /* Shut down signal */
  3932. return -2;
  3933. }
  3934. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  3935. ms_now = milliseconds;
  3936. }
  3937. result = poll(pfd, n, ms_now);
  3938. if (result != 0) {
  3939. /* Poll returned either success (1) or error (-1).
  3940. * Forward both to the caller. */
  3941. return result;
  3942. }
  3943. /* Poll returned timeout (0). */
  3944. if (milliseconds > 0) {
  3945. milliseconds -= ms_now;
  3946. }
  3947. } while (milliseconds != 0);
  3948. return result;
  3949. }
  3950. /* Write data to the IO channel - opened file descriptor, socket or SSL
  3951. * descriptor. Return number of bytes written. */
  3952. static int
  3953. push(struct mg_context *ctx,
  3954. FILE *fp,
  3955. SOCKET sock,
  3956. SSL *ssl,
  3957. const char *buf,
  3958. int len,
  3959. double timeout)
  3960. {
  3961. uint64_t start, now, timeout_ns;
  3962. int n, err;
  3963. #ifdef _WIN32
  3964. typedef int len_t;
  3965. #else
  3966. typedef size_t len_t;
  3967. #endif
  3968. if (timeout > 0) {
  3969. start = mg_get_current_time_ns();
  3970. timeout_ns = (uint64_t)(timeout * 1.0E9);
  3971. } else {
  3972. timeout_ns = 0;
  3973. }
  3974. if (ctx == NULL) {
  3975. return -1;
  3976. }
  3977. #ifdef NO_SSL
  3978. if (ssl) {
  3979. return -1;
  3980. }
  3981. #endif
  3982. do {
  3983. #ifndef NO_SSL
  3984. if (ssl != NULL) {
  3985. n = SSL_write(ssl, buf, len);
  3986. if (n <= 0) {
  3987. err = SSL_get_error(ssl, n);
  3988. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  3989. err = ERRNO;
  3990. } else if ((err == SSL_ERROR_WANT_READ)
  3991. || (err == SSL_ERROR_WANT_WRITE)) {
  3992. n = 0;
  3993. } else {
  3994. DEBUG_TRACE("SSL_write() failed, error %d", err);
  3995. return -1;
  3996. }
  3997. } else {
  3998. err = 0;
  3999. }
  4000. } else
  4001. #endif
  4002. if (fp != NULL) {
  4003. n = (int)fwrite(buf, 1, (size_t)len, fp);
  4004. if (ferror(fp)) {
  4005. n = -1;
  4006. err = ERRNO;
  4007. } else {
  4008. err = 0;
  4009. }
  4010. } else {
  4011. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  4012. err = (n < 0) ? ERRNO : 0;
  4013. #ifdef _WIN32
  4014. if (err == WSAEWOULDBLOCK) {
  4015. err = 0;
  4016. n = 0;
  4017. }
  4018. #else
  4019. if (err == EWOULDBLOCK) {
  4020. err = 0;
  4021. n = 0;
  4022. }
  4023. #endif
  4024. if (n < 0) {
  4025. /* shutdown of the socket at client side */
  4026. return -1;
  4027. }
  4028. }
  4029. if (ctx->stop_flag) {
  4030. return -1;
  4031. }
  4032. if ((n > 0) || (n == 0 && len == 0)) {
  4033. /* some data has been read, or no data was requested */
  4034. return n;
  4035. }
  4036. if (n < 0) {
  4037. /* socket error - check errno */
  4038. DEBUG_TRACE("send() failed, error %d", err);
  4039. /* TODO (mid): error handling depending on the error code.
  4040. * These codes are different between Windows and Linux.
  4041. * Currently there is no problem with failing send calls,
  4042. * if there is a reproducible situation, it should be
  4043. * investigated in detail.
  4044. */
  4045. return -1;
  4046. }
  4047. /* Only in case n=0 (timeout), repeat calling the write function */
  4048. if (timeout >= 0) {
  4049. now = mg_get_current_time_ns();
  4050. }
  4051. } while ((timeout <= 0) || ((start - now) <= timeout_ns));
  4052. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  4053. used */
  4054. return -1;
  4055. }
  4056. static int64_t
  4057. push_all(struct mg_context *ctx,
  4058. FILE *fp,
  4059. SOCKET sock,
  4060. SSL *ssl,
  4061. const char *buf,
  4062. int64_t len)
  4063. {
  4064. double timeout = -1.0;
  4065. int64_t n, nwritten = 0;
  4066. if (ctx == NULL) {
  4067. return -1;
  4068. }
  4069. if (ctx->config[REQUEST_TIMEOUT]) {
  4070. timeout = atoi(ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  4071. }
  4072. while (len > 0 && ctx->stop_flag == 0) {
  4073. n = push(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  4074. if (n < 0) {
  4075. if (nwritten == 0) {
  4076. nwritten = n; /* Propagate the error */
  4077. }
  4078. break;
  4079. } else if (n == 0) {
  4080. break; /* No more data to write */
  4081. } else {
  4082. nwritten += n;
  4083. len -= n;
  4084. }
  4085. }
  4086. return nwritten;
  4087. }
  4088. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  4089. * Return value:
  4090. * >=0 .. number of bytes successfully read
  4091. * -1 .. timeout
  4092. * -2 .. error
  4093. */
  4094. static int
  4095. pull_inner(FILE *fp,
  4096. struct mg_connection *conn,
  4097. char *buf,
  4098. int len,
  4099. double timeout)
  4100. {
  4101. int nread, err = 0;
  4102. #ifdef _WIN32
  4103. typedef int len_t;
  4104. #else
  4105. typedef size_t len_t;
  4106. #endif
  4107. /* We need an additional wait loop around this, because in some cases
  4108. * with TLSwe may get data from the socket but not from SSL_read.
  4109. * In this case we need to repeat at least once.
  4110. */
  4111. if (fp != NULL) {
  4112. #if !defined(_WIN32_WCE)
  4113. /* Use read() instead of fread(), because if we're reading from the
  4114. * CGI pipe, fread() may block until IO buffer is filled up. We
  4115. * cannot afford to block and must pass all read bytes immediately
  4116. * to the client. */
  4117. nread = (int)read(fileno(fp), buf, (size_t)len);
  4118. #else
  4119. /* WinCE does not support CGI pipes */
  4120. nread = (int)fread(buf, 1, (size_t)len, fp);
  4121. #endif
  4122. err = (nread < 0) ? ERRNO : 0;
  4123. #ifndef NO_SSL
  4124. } else if (conn->ssl != NULL) {
  4125. struct pollfd pfd[1];
  4126. int pollres;
  4127. pfd[0].fd = conn->client.sock;
  4128. pfd[0].events = POLLIN;
  4129. pollres =
  4130. mg_poll(pfd, 1, (int)(timeout * 1000.0), &(conn->ctx->stop_flag));
  4131. if (conn->ctx->stop_flag) {
  4132. return -2;
  4133. }
  4134. if (pollres > 0) {
  4135. nread = SSL_read(conn->ssl, buf, len);
  4136. if (nread <= 0) {
  4137. err = SSL_get_error(conn->ssl, nread);
  4138. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  4139. err = ERRNO;
  4140. } else if ((err == SSL_ERROR_WANT_READ)
  4141. || (err == SSL_ERROR_WANT_WRITE)) {
  4142. nread = 0;
  4143. } else {
  4144. DEBUG_TRACE("SSL_read() failed, error %d", err);
  4145. return -2;
  4146. }
  4147. } else {
  4148. err = 0;
  4149. }
  4150. } else if (pollres < 0) {
  4151. /* Error */
  4152. return -2;
  4153. } else {
  4154. /* pollres = 0 means timeout */
  4155. nread = 0;
  4156. }
  4157. #endif
  4158. } else {
  4159. struct pollfd pfd[1];
  4160. int pollres;
  4161. pfd[0].fd = conn->client.sock;
  4162. pfd[0].events = POLLIN;
  4163. pollres =
  4164. mg_poll(pfd, 1, (int)(timeout * 1000.0), &(conn->ctx->stop_flag));
  4165. if (conn->ctx->stop_flag) {
  4166. return -2;
  4167. }
  4168. if (pollres > 0) {
  4169. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  4170. err = (nread < 0) ? ERRNO : 0;
  4171. if (nread <= 0) {
  4172. /* shutdown of the socket at client side */
  4173. return -2;
  4174. }
  4175. } else if (pollres < 0) {
  4176. /* error callint poll */
  4177. return -2;
  4178. } else {
  4179. /* pollres = 0 means timeout */
  4180. nread = 0;
  4181. }
  4182. }
  4183. if (conn->ctx->stop_flag) {
  4184. return -2;
  4185. }
  4186. if ((nread > 0) || (nread == 0 && len == 0)) {
  4187. /* some data has been read, or no data was requested */
  4188. return nread;
  4189. }
  4190. if (nread < 0) {
  4191. /* socket error - check errno */
  4192. #ifdef _WIN32
  4193. if (err == WSAEWOULDBLOCK) {
  4194. /* TODO (low): check if this is still required */
  4195. /* standard case if called from close_socket_gracefully */
  4196. return -2;
  4197. } else if (err == WSAETIMEDOUT) {
  4198. /* TODO (low): check if this is still required */
  4199. /* timeout is handled by the while loop */
  4200. return 0;
  4201. } else if (err == WSAECONNABORTED) {
  4202. /* See https://www.chilkatsoft.com/p/p_299.asp */
  4203. return -2;
  4204. } else {
  4205. DEBUG_TRACE("recv() failed, error %d", err);
  4206. return -2;
  4207. }
  4208. #else
  4209. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  4210. * if the timeout is reached and if the socket was set to non-
  4211. * blocking in close_socket_gracefully, so we can not distinguish
  4212. * here. We have to wait for the timeout in both cases for now.
  4213. */
  4214. if (err == EAGAIN || err == EWOULDBLOCK || err == EINTR) {
  4215. /* TODO (low): check if this is still required */
  4216. /* EAGAIN/EWOULDBLOCK:
  4217. * standard case if called from close_socket_gracefully
  4218. * => should return -1 */
  4219. /* or timeout occured
  4220. * => the code must stay in the while loop */
  4221. /* EINTR can be generated on a socket with a timeout set even
  4222. * when SA_RESTART is effective for all relevant signals
  4223. * (see signal(7)).
  4224. * => stay in the while loop */
  4225. } else {
  4226. DEBUG_TRACE("recv() failed, error %d", err);
  4227. return -2;
  4228. }
  4229. #endif
  4230. }
  4231. /* Timeout occured, but no data available. */
  4232. return -1;
  4233. }
  4234. static int
  4235. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  4236. {
  4237. int n, nread = 0;
  4238. double timeout = -1.0;
  4239. uint64_t start_time, now, timeout_ns;
  4240. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  4241. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  4242. }
  4243. if (timeout >= 0.0) {
  4244. start_time = mg_get_current_time_ns();
  4245. timeout_ns = (uint64_t)(timeout * 1.0E9);
  4246. } else {
  4247. /* The variable is not used, but if it is left uninitialized,
  4248. * we get a spurious warning. */
  4249. start_time = 0;
  4250. }
  4251. while (len > 0 && conn->ctx->stop_flag == 0) {
  4252. n = pull_inner(fp, conn, buf + nread, len, timeout);
  4253. if (n == -2) {
  4254. if (nread == 0) {
  4255. nread = -1; /* Propagate the error */
  4256. }
  4257. break;
  4258. } else if (n == -1) {
  4259. /* timeout */
  4260. if (timeout >= 0.0) {
  4261. now = mg_get_current_time_ns();
  4262. if ((now - start_time) <= timeout_ns) {
  4263. continue;
  4264. }
  4265. }
  4266. break;
  4267. } else if (n == 0) {
  4268. break; /* No more data to read */
  4269. } else {
  4270. conn->consumed_content += n;
  4271. nread += n;
  4272. len -= n;
  4273. }
  4274. }
  4275. return nread;
  4276. }
  4277. static void
  4278. discard_unread_request_data(struct mg_connection *conn)
  4279. {
  4280. char buf[MG_BUF_LEN];
  4281. size_t to_read;
  4282. int nread;
  4283. if (conn == NULL) {
  4284. return;
  4285. }
  4286. to_read = sizeof(buf);
  4287. if (conn->is_chunked) {
  4288. /* Chunked encoding: 1=chunk not read completely, 2=chunk read
  4289. * completely */
  4290. while (conn->is_chunked == 1) {
  4291. nread = mg_read(conn, buf, to_read);
  4292. if (nread <= 0) {
  4293. break;
  4294. }
  4295. }
  4296. } else {
  4297. /* Not chunked: content length is known */
  4298. while (conn->consumed_content < conn->content_len) {
  4299. if (to_read
  4300. > (size_t)(conn->content_len - conn->consumed_content)) {
  4301. to_read = (size_t)(conn->content_len - conn->consumed_content);
  4302. }
  4303. nread = mg_read(conn, buf, to_read);
  4304. if (nread <= 0) {
  4305. break;
  4306. }
  4307. }
  4308. }
  4309. }
  4310. static int
  4311. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  4312. {
  4313. int64_t n, buffered_len, nread;
  4314. int64_t len64 =
  4315. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  4316. * int, we may not read more
  4317. * bytes */
  4318. const char *body;
  4319. if (conn == NULL) {
  4320. return 0;
  4321. }
  4322. /* If Content-Length is not set for a PUT or POST request, read until
  4323. * socket is closed */
  4324. if (conn->consumed_content == 0 && conn->content_len == -1) {
  4325. conn->content_len = INT64_MAX;
  4326. conn->must_close = 1;
  4327. }
  4328. nread = 0;
  4329. if (conn->consumed_content < conn->content_len) {
  4330. /* Adjust number of bytes to read. */
  4331. int64_t left_to_read = conn->content_len - conn->consumed_content;
  4332. if (left_to_read < len64) {
  4333. /* Do not read more than the total content length of the request.
  4334. */
  4335. len64 = left_to_read;
  4336. }
  4337. /* Return buffered data */
  4338. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  4339. - conn->consumed_content;
  4340. if (buffered_len > 0) {
  4341. if (len64 < buffered_len) {
  4342. buffered_len = len64;
  4343. }
  4344. body = conn->buf + conn->request_len + conn->consumed_content;
  4345. memcpy(buf, body, (size_t)buffered_len);
  4346. len64 -= buffered_len;
  4347. conn->consumed_content += buffered_len;
  4348. nread += buffered_len;
  4349. buf = (char *)buf + buffered_len;
  4350. }
  4351. /* We have returned all buffered data. Read new data from the remote
  4352. * socket.
  4353. */
  4354. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  4355. nread += n;
  4356. } else {
  4357. nread = ((nread > 0) ? nread : n);
  4358. }
  4359. }
  4360. return (int)nread;
  4361. }
  4362. static char
  4363. mg_getc(struct mg_connection *conn)
  4364. {
  4365. char c;
  4366. if (conn == NULL) {
  4367. return 0;
  4368. }
  4369. conn->content_len++;
  4370. if (mg_read_inner(conn, &c, 1) <= 0) {
  4371. return (char)0;
  4372. }
  4373. return c;
  4374. }
  4375. int
  4376. mg_read(struct mg_connection *conn, void *buf, size_t len)
  4377. {
  4378. if (len > INT_MAX) {
  4379. len = INT_MAX;
  4380. }
  4381. if (conn == NULL) {
  4382. return 0;
  4383. }
  4384. if (conn->is_chunked) {
  4385. size_t all_read = 0;
  4386. while (len > 0) {
  4387. if (conn->is_chunked == 2) {
  4388. /* No more data left to read */
  4389. return 0;
  4390. }
  4391. if (conn->chunk_remainder) {
  4392. /* copy from the remainder of the last received chunk */
  4393. long read_ret;
  4394. size_t read_now =
  4395. ((conn->chunk_remainder > len) ? (len)
  4396. : (conn->chunk_remainder));
  4397. conn->content_len += (int)read_now;
  4398. read_ret =
  4399. mg_read_inner(conn, (char *)buf + all_read, read_now);
  4400. if (read_ret < 1) {
  4401. /* read error */
  4402. return -1;
  4403. }
  4404. all_read += (size_t)read_ret;
  4405. conn->chunk_remainder -= (size_t)read_ret;
  4406. len -= (size_t)read_ret;
  4407. if (conn->chunk_remainder == 0) {
  4408. /* Add data bytes in the current chunk have been read,
  4409. * so we are expecting \r\n now. */
  4410. char x1 = mg_getc(conn);
  4411. char x2 = mg_getc(conn);
  4412. if ((x1 != '\r') || (x2 != '\n')) {
  4413. /* Protocol violation */
  4414. return -1;
  4415. }
  4416. }
  4417. } else {
  4418. /* fetch a new chunk */
  4419. int i = 0;
  4420. char lenbuf[64];
  4421. char *end = 0;
  4422. unsigned long chunkSize = 0;
  4423. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  4424. lenbuf[i] = mg_getc(conn);
  4425. if (i > 0 && lenbuf[i] == '\r' && lenbuf[i - 1] != '\r') {
  4426. continue;
  4427. }
  4428. if (i > 1 && lenbuf[i] == '\n' && lenbuf[i - 1] == '\r') {
  4429. lenbuf[i + 1] = 0;
  4430. chunkSize = strtoul(lenbuf, &end, 16);
  4431. if (chunkSize == 0) {
  4432. /* regular end of content */
  4433. conn->is_chunked = 2;
  4434. }
  4435. break;
  4436. }
  4437. if (!isxdigit(lenbuf[i])) {
  4438. /* illegal character for chunk length */
  4439. return -1;
  4440. }
  4441. }
  4442. if ((end == NULL) || (*end != '\r')) {
  4443. /* chunksize not set correctly */
  4444. return -1;
  4445. }
  4446. if (chunkSize == 0) {
  4447. break;
  4448. }
  4449. conn->chunk_remainder = chunkSize;
  4450. }
  4451. }
  4452. return (int)all_read;
  4453. }
  4454. return mg_read_inner(conn, buf, len);
  4455. }
  4456. int
  4457. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  4458. {
  4459. time_t now;
  4460. int64_t n, total, allowed;
  4461. if (conn == NULL) {
  4462. return 0;
  4463. }
  4464. if (conn->throttle > 0) {
  4465. if ((now = time(NULL)) != conn->last_throttle_time) {
  4466. conn->last_throttle_time = now;
  4467. conn->last_throttle_bytes = 0;
  4468. }
  4469. allowed = conn->throttle - conn->last_throttle_bytes;
  4470. if (allowed > (int64_t)len) {
  4471. allowed = (int64_t)len;
  4472. }
  4473. if ((total = push_all(conn->ctx,
  4474. NULL,
  4475. conn->client.sock,
  4476. conn->ssl,
  4477. (const char *)buf,
  4478. (int64_t)allowed)) == allowed) {
  4479. buf = (const char *)buf + total;
  4480. conn->last_throttle_bytes += total;
  4481. while (total < (int64_t)len && conn->ctx->stop_flag == 0) {
  4482. allowed = (conn->throttle > ((int64_t)len - total))
  4483. ? (int64_t)len - total
  4484. : conn->throttle;
  4485. if ((n = push_all(conn->ctx,
  4486. NULL,
  4487. conn->client.sock,
  4488. conn->ssl,
  4489. (const char *)buf,
  4490. (int64_t)allowed)) != allowed) {
  4491. break;
  4492. }
  4493. sleep(1);
  4494. conn->last_throttle_bytes = allowed;
  4495. conn->last_throttle_time = time(NULL);
  4496. buf = (const char *)buf + n;
  4497. total += n;
  4498. }
  4499. }
  4500. } else {
  4501. total = push_all(conn->ctx,
  4502. NULL,
  4503. conn->client.sock,
  4504. conn->ssl,
  4505. (const char *)buf,
  4506. (int64_t)len);
  4507. }
  4508. return (int)total;
  4509. }
  4510. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  4511. static int
  4512. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  4513. {
  4514. va_list ap_copy;
  4515. size_t size = MG_BUF_LEN / 4;
  4516. int len = -1;
  4517. *buf = NULL;
  4518. while (len < 0) {
  4519. if (*buf) {
  4520. mg_free(*buf);
  4521. }
  4522. size *= 4;
  4523. *buf = (char *)mg_malloc(size);
  4524. if (!*buf) {
  4525. break;
  4526. }
  4527. va_copy(ap_copy, ap);
  4528. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  4529. va_end(ap_copy);
  4530. (*buf)[size - 1] = 0;
  4531. }
  4532. return len;
  4533. }
  4534. /* Print message to buffer. If buffer is large enough to hold the message,
  4535. * return buffer. If buffer is to small, allocate large enough buffer on heap,
  4536. * and return allocated buffer. */
  4537. static int
  4538. alloc_vprintf(char **out_buf,
  4539. char *prealloc_buf,
  4540. size_t prealloc_size,
  4541. const char *fmt,
  4542. va_list ap)
  4543. {
  4544. va_list ap_copy;
  4545. int len;
  4546. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  4547. * buffer is too small. Also, older versions of msvcrt.dll do not have
  4548. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  4549. * Therefore, we make two passes: on first pass, get required message
  4550. * length.
  4551. * On second pass, actually print the message. */
  4552. va_copy(ap_copy, ap);
  4553. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  4554. va_end(ap_copy);
  4555. if (len < 0) {
  4556. /* C runtime is not standard compliant, vsnprintf() returned -1.
  4557. * Switch to alternative code path that uses incremental allocations.
  4558. */
  4559. va_copy(ap_copy, ap);
  4560. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  4561. va_end(ap_copy);
  4562. } else if ((size_t)(len) >= prealloc_size) {
  4563. /* The pre-allocated buffer not large enough. */
  4564. /* Allocate a new buffer. */
  4565. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  4566. if (!*out_buf) {
  4567. /* Allocation failed. Return -1 as "out of memory" error. */
  4568. return -1;
  4569. }
  4570. /* Buffer allocation successful. Store the string there. */
  4571. va_copy(ap_copy, ap);
  4572. IGNORE_UNUSED_RESULT(
  4573. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  4574. va_end(ap_copy);
  4575. } else {
  4576. /* The pre-allocated buffer is large enough.
  4577. * Use it to store the string and return the address. */
  4578. va_copy(ap_copy, ap);
  4579. IGNORE_UNUSED_RESULT(
  4580. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  4581. va_end(ap_copy);
  4582. *out_buf = prealloc_buf;
  4583. }
  4584. return len;
  4585. }
  4586. static int
  4587. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  4588. {
  4589. char mem[MG_BUF_LEN];
  4590. char *buf = NULL;
  4591. int len;
  4592. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  4593. len = mg_write(conn, buf, (size_t)len);
  4594. }
  4595. if (buf != mem && buf != NULL) {
  4596. mg_free(buf);
  4597. }
  4598. return len;
  4599. }
  4600. int
  4601. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  4602. {
  4603. va_list ap;
  4604. int result;
  4605. va_start(ap, fmt);
  4606. result = mg_vprintf(conn, fmt, ap);
  4607. va_end(ap);
  4608. return result;
  4609. }
  4610. int
  4611. mg_url_decode(const char *src,
  4612. int src_len,
  4613. char *dst,
  4614. int dst_len,
  4615. int is_form_url_encoded)
  4616. {
  4617. int i, j, a, b;
  4618. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  4619. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  4620. if (i < src_len - 2 && src[i] == '%'
  4621. && isxdigit(*(const unsigned char *)(src + i + 1))
  4622. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  4623. a = tolower(*(const unsigned char *)(src + i + 1));
  4624. b = tolower(*(const unsigned char *)(src + i + 2));
  4625. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  4626. i += 2;
  4627. } else if (is_form_url_encoded && src[i] == '+') {
  4628. dst[j] = ' ';
  4629. } else {
  4630. dst[j] = src[i];
  4631. }
  4632. }
  4633. dst[j] = '\0'; /* Null-terminate the destination */
  4634. return (i >= src_len) ? j : -1;
  4635. }
  4636. int
  4637. mg_get_var(const char *data,
  4638. size_t data_len,
  4639. const char *name,
  4640. char *dst,
  4641. size_t dst_len)
  4642. {
  4643. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  4644. }
  4645. int
  4646. mg_get_var2(const char *data,
  4647. size_t data_len,
  4648. const char *name,
  4649. char *dst,
  4650. size_t dst_len,
  4651. size_t occurrence)
  4652. {
  4653. const char *p, *e, *s;
  4654. size_t name_len;
  4655. int len;
  4656. if (dst == NULL || dst_len == 0) {
  4657. len = -2;
  4658. } else if (data == NULL || name == NULL || data_len == 0) {
  4659. len = -1;
  4660. dst[0] = '\0';
  4661. } else {
  4662. name_len = strlen(name);
  4663. e = data + data_len;
  4664. len = -1;
  4665. dst[0] = '\0';
  4666. /* data is "var1=val1&var2=val2...". Find variable first */
  4667. for (p = data; p + name_len < e; p++) {
  4668. if ((p == data || p[-1] == '&') && p[name_len] == '='
  4669. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  4670. /* Point p to variable value */
  4671. p += name_len + 1;
  4672. /* Point s to the end of the value */
  4673. s = (const char *)memchr(p, '&', (size_t)(e - p));
  4674. if (s == NULL) {
  4675. s = e;
  4676. }
  4677. /* assert(s >= p); */
  4678. if (s < p) {
  4679. return -3;
  4680. }
  4681. /* Decode variable into destination buffer */
  4682. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  4683. /* Redirect error code from -1 to -2 (destination buffer too
  4684. * small). */
  4685. if (len == -1) {
  4686. len = -2;
  4687. }
  4688. break;
  4689. }
  4690. }
  4691. }
  4692. return len;
  4693. }
  4694. /* HCP24: some changes to compare hole var_name */
  4695. int
  4696. mg_get_cookie(const char *cookie_header,
  4697. const char *var_name,
  4698. char *dst,
  4699. size_t dst_size)
  4700. {
  4701. const char *s, *p, *end;
  4702. int name_len, len = -1;
  4703. if (dst == NULL || dst_size == 0) {
  4704. return -2;
  4705. }
  4706. dst[0] = '\0';
  4707. if (var_name == NULL || (s = cookie_header) == NULL) {
  4708. return -1;
  4709. }
  4710. name_len = (int)strlen(var_name);
  4711. end = s + strlen(s);
  4712. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  4713. if (s[name_len] == '=') {
  4714. /* HCP24: now check is it a substring or a full cookie name */
  4715. if ((s == cookie_header) || (s[-1] == ' ')) {
  4716. s += name_len + 1;
  4717. if ((p = strchr(s, ' ')) == NULL) {
  4718. p = end;
  4719. }
  4720. if (p[-1] == ';') {
  4721. p--;
  4722. }
  4723. if (*s == '"' && p[-1] == '"' && p > s + 1) {
  4724. s++;
  4725. p--;
  4726. }
  4727. if ((size_t)(p - s) < dst_size) {
  4728. len = (int)(p - s);
  4729. mg_strlcpy(dst, s, (size_t)len + 1);
  4730. } else {
  4731. len = -3;
  4732. }
  4733. break;
  4734. }
  4735. }
  4736. }
  4737. return len;
  4738. }
  4739. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  4740. static void
  4741. base64_encode(const unsigned char *src, int src_len, char *dst)
  4742. {
  4743. static const char *b64 =
  4744. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  4745. int i, j, a, b, c;
  4746. for (i = j = 0; i < src_len; i += 3) {
  4747. a = src[i];
  4748. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  4749. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  4750. dst[j++] = b64[a >> 2];
  4751. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  4752. if (i + 1 < src_len) {
  4753. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  4754. }
  4755. if (i + 2 < src_len) {
  4756. dst[j++] = b64[c & 63];
  4757. }
  4758. }
  4759. while (j % 4 != 0) {
  4760. dst[j++] = '=';
  4761. }
  4762. dst[j++] = '\0';
  4763. }
  4764. #endif
  4765. #if defined(USE_LUA)
  4766. static unsigned char
  4767. b64reverse(char letter)
  4768. {
  4769. if (letter >= 'A' && letter <= 'Z') {
  4770. return letter - 'A';
  4771. }
  4772. if (letter >= 'a' && letter <= 'z') {
  4773. return letter - 'a' + 26;
  4774. }
  4775. if (letter >= '0' && letter <= '9') {
  4776. return letter - '0' + 52;
  4777. }
  4778. if (letter == '+') {
  4779. return 62;
  4780. }
  4781. if (letter == '/') {
  4782. return 63;
  4783. }
  4784. if (letter == '=') {
  4785. return 255; /* normal end */
  4786. }
  4787. return 254; /* error */
  4788. }
  4789. static int
  4790. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  4791. {
  4792. int i;
  4793. unsigned char a, b, c, d;
  4794. *dst_len = 0;
  4795. for (i = 0; i < src_len; i += 4) {
  4796. a = b64reverse(src[i]);
  4797. if (a >= 254) {
  4798. return i;
  4799. }
  4800. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  4801. if (b >= 254) {
  4802. return i + 1;
  4803. }
  4804. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  4805. if (c == 254) {
  4806. return i + 2;
  4807. }
  4808. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  4809. if (d == 254) {
  4810. return i + 3;
  4811. }
  4812. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  4813. if (c != 255) {
  4814. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  4815. if (d != 255) {
  4816. dst[(*dst_len)++] = (c << 6) + d;
  4817. }
  4818. }
  4819. }
  4820. return -1;
  4821. }
  4822. #endif
  4823. static int
  4824. is_put_or_delete_method(const struct mg_connection *conn)
  4825. {
  4826. if (conn) {
  4827. const char *s = conn->request_info.request_method;
  4828. return s != NULL && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  4829. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  4830. }
  4831. return 0;
  4832. }
  4833. static void
  4834. interpret_uri(struct mg_connection *conn, /* in: request (must be valid) */
  4835. char *filename, /* out: filename */
  4836. size_t filename_buf_len, /* in: size of filename buffer */
  4837. struct mg_file_stat *filestat, /* out: file structure */
  4838. int *is_found, /* out: file found (directly) */
  4839. int *is_script_resource, /* out: handled by a script? */
  4840. int *is_websocket_request, /* out: websocket connetion? */
  4841. int *is_put_or_delete_request /* out: put/delete a file? */
  4842. )
  4843. {
  4844. /* TODO (high / maintainability issue): Restructure this function */
  4845. #if !defined(NO_FILES)
  4846. const char *uri = conn->request_info.local_uri;
  4847. const char *root = conn->ctx->config[DOCUMENT_ROOT];
  4848. const char *rewrite;
  4849. struct vec a, b;
  4850. int match_len;
  4851. char gz_path[PATH_MAX];
  4852. char const *accept_encoding;
  4853. int truncated;
  4854. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  4855. char *p;
  4856. #endif
  4857. #else
  4858. (void)filename_buf_len; /* unused if NO_FILES is defined */
  4859. #endif
  4860. memset(filestat, 0, sizeof(*filestat));
  4861. *filename = 0;
  4862. *is_found = 0;
  4863. *is_script_resource = 0;
  4864. *is_put_or_delete_request = is_put_or_delete_method(conn);
  4865. #if defined(USE_WEBSOCKET)
  4866. *is_websocket_request = is_websocket_protocol(conn);
  4867. #if !defined(NO_FILES)
  4868. if (*is_websocket_request && conn->ctx->config[WEBSOCKET_ROOT]) {
  4869. root = conn->ctx->config[WEBSOCKET_ROOT];
  4870. }
  4871. #endif /* !NO_FILES */
  4872. #else /* USE_WEBSOCKET */
  4873. *is_websocket_request = 0;
  4874. #endif /* USE_WEBSOCKET */
  4875. #if !defined(NO_FILES)
  4876. /* Note that root == NULL is a regular use case here. This occurs,
  4877. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  4878. * config is not required. */
  4879. if (root == NULL) {
  4880. /* all file related outputs have already been set to 0, just return
  4881. */
  4882. return;
  4883. }
  4884. /* Using buf_len - 1 because memmove() for PATH_INFO may shift part
  4885. * of the path one byte on the right.
  4886. * If document_root is NULL, leave the file empty. */
  4887. mg_snprintf(
  4888. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  4889. if (truncated) {
  4890. goto interpret_cleanup;
  4891. }
  4892. rewrite = conn->ctx->config[REWRITE];
  4893. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  4894. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  4895. mg_snprintf(conn,
  4896. &truncated,
  4897. filename,
  4898. filename_buf_len - 1,
  4899. "%.*s%s",
  4900. (int)b.len,
  4901. b.ptr,
  4902. uri + match_len);
  4903. break;
  4904. }
  4905. }
  4906. if (truncated) {
  4907. goto interpret_cleanup;
  4908. }
  4909. /* Local file path and name, corresponding to requested URI
  4910. * is now stored in "filename" variable. */
  4911. if (mg_stat(conn, filename, filestat)) {
  4912. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  4913. /* File exists. Check if it is a script type. */
  4914. if (0
  4915. #if !defined(NO_CGI)
  4916. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  4917. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4918. filename) > 0
  4919. #endif
  4920. #if defined(USE_LUA)
  4921. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  4922. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  4923. filename) > 0
  4924. #endif
  4925. #if defined(USE_DUKTAPE)
  4926. || match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  4927. strlen(
  4928. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  4929. filename) > 0
  4930. #endif
  4931. ) {
  4932. /* The request addresses a CGI script or a Lua script. The URI
  4933. * corresponds to the script itself (like /path/script.cgi),
  4934. * and there is no additional resource path
  4935. * (like /path/script.cgi/something).
  4936. * Requests that modify (replace or delete) a resource, like
  4937. * PUT and DELETE requests, should replace/delete the script
  4938. * file.
  4939. * Requests that read or write from/to a resource, like GET and
  4940. * POST requests, should call the script and return the
  4941. * generated response. */
  4942. *is_script_resource = (!*is_put_or_delete_request);
  4943. }
  4944. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  4945. *is_found = 1;
  4946. return;
  4947. }
  4948. /* If we can't find the actual file, look for the file
  4949. * with the same name but a .gz extension. If we find it,
  4950. * use that and set the gzipped flag in the file struct
  4951. * to indicate that the response need to have the content-
  4952. * encoding: gzip header.
  4953. * We can only do this if the browser declares support. */
  4954. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  4955. if (strstr(accept_encoding, "gzip") != NULL) {
  4956. mg_snprintf(
  4957. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  4958. if (truncated) {
  4959. goto interpret_cleanup;
  4960. }
  4961. if (mg_stat(conn, gz_path, filestat)) {
  4962. if (filestat) {
  4963. filestat->is_gzipped = 1;
  4964. *is_found = 1;
  4965. }
  4966. /* Currently gz files can not be scripts. */
  4967. return;
  4968. }
  4969. }
  4970. }
  4971. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  4972. /* Support PATH_INFO for CGI scripts. */
  4973. for (p = filename + strlen(filename); p > filename + 1; p--) {
  4974. if (*p == '/') {
  4975. *p = '\0';
  4976. if ((0
  4977. #if !defined(NO_CGI)
  4978. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  4979. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4980. filename) > 0
  4981. #endif
  4982. #if defined(USE_LUA)
  4983. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  4984. strlen(
  4985. conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  4986. filename) > 0
  4987. #endif
  4988. #if defined(USE_DUKTAPE)
  4989. || match_prefix(
  4990. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  4991. strlen(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  4992. filename) > 0
  4993. #endif
  4994. ) && mg_stat(conn, filename, filestat)) {
  4995. /* Shift PATH_INFO block one character right, e.g.
  4996. * "/x.cgi/foo/bar\x00" => "/x.cgi\x00/foo/bar\x00"
  4997. * conn->path_info is pointing to the local variable "path"
  4998. * declared in handle_request(), so PATH_INFO is not valid
  4999. * after handle_request returns. */
  5000. conn->path_info = p + 1;
  5001. memmove(p + 2, p + 1, strlen(p + 1) + 1); /* +1 is for
  5002. * trailing \0 */
  5003. p[1] = '/';
  5004. *is_script_resource = 1;
  5005. break;
  5006. } else {
  5007. *p = '/';
  5008. }
  5009. }
  5010. }
  5011. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  5012. #endif /* !defined(NO_FILES) */
  5013. return;
  5014. #if !defined(NO_FILES)
  5015. /* Reset all outputs */
  5016. interpret_cleanup:
  5017. memset(filestat, 0, sizeof(*filestat));
  5018. *filename = 0;
  5019. *is_found = 0;
  5020. *is_script_resource = 0;
  5021. *is_websocket_request = 0;
  5022. *is_put_or_delete_request = 0;
  5023. #endif /* !defined(NO_FILES) */
  5024. }
  5025. /* Check whether full request is buffered. Return:
  5026. * -1 if request is malformed
  5027. * 0 if request is not yet fully buffered
  5028. * >0 actual request length, including last \r\n\r\n */
  5029. static int
  5030. get_request_len(const char *buf, int buflen)
  5031. {
  5032. const char *s, *e;
  5033. int len = 0;
  5034. for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
  5035. /* Control characters are not allowed but >=128 is. */
  5036. if (!isprint(*(const unsigned char *)s) && *s != '\r' && *s != '\n'
  5037. && *(const unsigned char *)s < 128) {
  5038. len = -1;
  5039. break; /* [i_a] abort scan as soon as one malformed character is
  5040. * found; */
  5041. /* don't let subsequent \r\n\r\n win us over anyhow */
  5042. } else if (s[0] == '\n' && s[1] == '\n') {
  5043. len = (int)(s - buf) + 2;
  5044. } else if (s[0] == '\n' && &s[1] < e && s[1] == '\r' && s[2] == '\n') {
  5045. len = (int)(s - buf) + 3;
  5046. }
  5047. return len;
  5048. }
  5049. #if !defined(NO_CACHING)
  5050. /* Convert month to the month number. Return -1 on error, or month number */
  5051. static int
  5052. get_month_index(const char *s)
  5053. {
  5054. size_t i;
  5055. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  5056. if (!strcmp(s, month_names[i])) {
  5057. return (int)i;
  5058. }
  5059. }
  5060. return -1;
  5061. }
  5062. /* Parse UTC date-time string, and return the corresponding time_t value. */
  5063. static time_t
  5064. parse_date_string(const char *datetime)
  5065. {
  5066. char month_str[32] = {0};
  5067. int second, minute, hour, day, month, year;
  5068. time_t result = (time_t)0;
  5069. struct tm tm;
  5070. if ((sscanf(datetime,
  5071. "%d/%3s/%d %d:%d:%d",
  5072. &day,
  5073. month_str,
  5074. &year,
  5075. &hour,
  5076. &minute,
  5077. &second) == 6) || (sscanf(datetime,
  5078. "%d %3s %d %d:%d:%d",
  5079. &day,
  5080. month_str,
  5081. &year,
  5082. &hour,
  5083. &minute,
  5084. &second) == 6)
  5085. || (sscanf(datetime,
  5086. "%*3s, %d %3s %d %d:%d:%d",
  5087. &day,
  5088. month_str,
  5089. &year,
  5090. &hour,
  5091. &minute,
  5092. &second) == 6) || (sscanf(datetime,
  5093. "%d-%3s-%d %d:%d:%d",
  5094. &day,
  5095. month_str,
  5096. &year,
  5097. &hour,
  5098. &minute,
  5099. &second) == 6)) {
  5100. month = get_month_index(month_str);
  5101. if ((month >= 0) && (year >= 1970)) {
  5102. memset(&tm, 0, sizeof(tm));
  5103. tm.tm_year = year - 1900;
  5104. tm.tm_mon = month;
  5105. tm.tm_mday = day;
  5106. tm.tm_hour = hour;
  5107. tm.tm_min = minute;
  5108. tm.tm_sec = second;
  5109. result = timegm(&tm);
  5110. }
  5111. }
  5112. return result;
  5113. }
  5114. #endif /* !NO_CACHING */
  5115. /* Protect against directory disclosure attack by removing '..',
  5116. * excessive '/' and '\' characters */
  5117. static void
  5118. remove_double_dots_and_double_slashes(char *s)
  5119. {
  5120. char *p = s;
  5121. while ((s[0] == '.') && (s[1] == '.')) {
  5122. s++;
  5123. }
  5124. while (*s != '\0') {
  5125. *p++ = *s++;
  5126. if (s[-1] == '/' || s[-1] == '\\') {
  5127. /* Skip all following slashes, backslashes and double-dots */
  5128. while (s[0] != '\0') {
  5129. if (s[0] == '/' || s[0] == '\\') {
  5130. s++;
  5131. } else if (s[0] == '.' && s[1] == '.') {
  5132. s += 2;
  5133. } else {
  5134. break;
  5135. }
  5136. }
  5137. }
  5138. }
  5139. *p = '\0';
  5140. }
  5141. static const struct {
  5142. const char *extension;
  5143. size_t ext_len;
  5144. const char *mime_type;
  5145. } builtin_mime_types[] = {
  5146. /* IANA registered MIME types (http://www.iana.org/assignments/media-types)
  5147. * application types */
  5148. {".doc", 4, "application/msword"},
  5149. {".eps", 4, "application/postscript"},
  5150. {".exe", 4, "application/octet-stream"},
  5151. {".js", 3, "application/javascript"},
  5152. {".json", 5, "application/json"},
  5153. {".pdf", 4, "application/pdf"},
  5154. {".ps", 3, "application/postscript"},
  5155. {".rtf", 4, "application/rtf"},
  5156. {".xhtml", 6, "application/xhtml+xml"},
  5157. {".xsl", 4, "application/xml"},
  5158. {".xslt", 5, "application/xml"},
  5159. /* fonts */
  5160. {".ttf", 4, "application/font-sfnt"},
  5161. {".cff", 4, "application/font-sfnt"},
  5162. {".otf", 4, "application/font-sfnt"},
  5163. {".aat", 4, "application/font-sfnt"},
  5164. {".sil", 4, "application/font-sfnt"},
  5165. {".pfr", 4, "application/font-tdpfr"},
  5166. {".woff", 5, "application/font-woff"},
  5167. /* audio */
  5168. {".mp3", 4, "audio/mpeg"},
  5169. {".oga", 4, "audio/ogg"},
  5170. {".ogg", 4, "audio/ogg"},
  5171. /* image */
  5172. {".gif", 4, "image/gif"},
  5173. {".ief", 4, "image/ief"},
  5174. {".jpeg", 5, "image/jpeg"},
  5175. {".jpg", 4, "image/jpeg"},
  5176. {".jpm", 4, "image/jpm"},
  5177. {".jpx", 4, "image/jpx"},
  5178. {".png", 4, "image/png"},
  5179. {".svg", 4, "image/svg+xml"},
  5180. {".tif", 4, "image/tiff"},
  5181. {".tiff", 5, "image/tiff"},
  5182. /* model */
  5183. {".wrl", 4, "model/vrml"},
  5184. /* text */
  5185. {".css", 4, "text/css"},
  5186. {".csv", 4, "text/csv"},
  5187. {".htm", 4, "text/html"},
  5188. {".html", 5, "text/html"},
  5189. {".sgm", 4, "text/sgml"},
  5190. {".shtm", 5, "text/html"},
  5191. {".shtml", 6, "text/html"},
  5192. {".txt", 4, "text/plain"},
  5193. {".xml", 4, "text/xml"},
  5194. /* video */
  5195. {".mov", 4, "video/quicktime"},
  5196. {".mp4", 4, "video/mp4"},
  5197. {".mpeg", 5, "video/mpeg"},
  5198. {".mpg", 4, "video/mpeg"},
  5199. {".ogv", 4, "video/ogg"},
  5200. {".qt", 3, "video/quicktime"},
  5201. /* not registered types
  5202. * (http://reference.sitepoint.com/html/mime-types-full,
  5203. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  5204. {".arj", 4, "application/x-arj-compressed"},
  5205. {".gz", 3, "application/x-gunzip"},
  5206. {".rar", 4, "application/x-arj-compressed"},
  5207. {".swf", 4, "application/x-shockwave-flash"},
  5208. {".tar", 4, "application/x-tar"},
  5209. {".tgz", 4, "application/x-tar-gz"},
  5210. {".torrent", 8, "application/x-bittorrent"},
  5211. {".ppt", 4, "application/x-mspowerpoint"},
  5212. {".xls", 4, "application/x-msexcel"},
  5213. {".zip", 4, "application/x-zip-compressed"},
  5214. {".aac",
  5215. 4,
  5216. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  5217. {".aif", 4, "audio/x-aif"},
  5218. {".m3u", 4, "audio/x-mpegurl"},
  5219. {".mid", 4, "audio/x-midi"},
  5220. {".ra", 3, "audio/x-pn-realaudio"},
  5221. {".ram", 4, "audio/x-pn-realaudio"},
  5222. {".wav", 4, "audio/x-wav"},
  5223. {".bmp", 4, "image/bmp"},
  5224. {".ico", 4, "image/x-icon"},
  5225. {".pct", 4, "image/x-pct"},
  5226. {".pict", 5, "image/pict"},
  5227. {".rgb", 4, "image/x-rgb"},
  5228. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  5229. {".asf", 4, "video/x-ms-asf"},
  5230. {".avi", 4, "video/x-msvideo"},
  5231. {".m4v", 4, "video/x-m4v"},
  5232. {NULL, 0, NULL}};
  5233. const char *
  5234. mg_get_builtin_mime_type(const char *path)
  5235. {
  5236. const char *ext;
  5237. size_t i, path_len;
  5238. path_len = strlen(path);
  5239. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  5240. ext = path + (path_len - builtin_mime_types[i].ext_len);
  5241. if (path_len > builtin_mime_types[i].ext_len
  5242. && mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {
  5243. return builtin_mime_types[i].mime_type;
  5244. }
  5245. }
  5246. return "text/plain";
  5247. }
  5248. /* Look at the "path" extension and figure what mime type it has.
  5249. * Store mime type in the vector. */
  5250. static void
  5251. get_mime_type(struct mg_context *ctx, const char *path, struct vec *vec)
  5252. {
  5253. struct vec ext_vec, mime_vec;
  5254. const char *list, *ext;
  5255. size_t path_len;
  5256. path_len = strlen(path);
  5257. if (ctx == NULL || vec == NULL) {
  5258. return;
  5259. }
  5260. /* Scan user-defined mime types first, in case user wants to
  5261. * override default mime types. */
  5262. list = ctx->config[EXTRA_MIME_TYPES];
  5263. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  5264. /* ext now points to the path suffix */
  5265. ext = path + path_len - ext_vec.len;
  5266. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  5267. *vec = mime_vec;
  5268. return;
  5269. }
  5270. }
  5271. vec->ptr = mg_get_builtin_mime_type(path);
  5272. vec->len = strlen(vec->ptr);
  5273. }
  5274. /* Stringify binary data. Output buffer must be twice as big as input,
  5275. * because each byte takes 2 bytes in string representation */
  5276. static void
  5277. bin2str(char *to, const unsigned char *p, size_t len)
  5278. {
  5279. static const char *hex = "0123456789abcdef";
  5280. for (; len--; p++) {
  5281. *to++ = hex[p[0] >> 4];
  5282. *to++ = hex[p[0] & 0x0f];
  5283. }
  5284. *to = '\0';
  5285. }
  5286. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes. */
  5287. char *
  5288. mg_md5(char buf[33], ...)
  5289. {
  5290. md5_byte_t hash[16];
  5291. const char *p;
  5292. va_list ap;
  5293. md5_state_t ctx;
  5294. md5_init(&ctx);
  5295. va_start(ap, buf);
  5296. while ((p = va_arg(ap, const char *)) != NULL) {
  5297. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  5298. }
  5299. va_end(ap);
  5300. md5_finish(&ctx, hash);
  5301. bin2str(buf, hash, sizeof(hash));
  5302. return buf;
  5303. }
  5304. /* Check the user's password, return 1 if OK */
  5305. static int
  5306. check_password(const char *method,
  5307. const char *ha1,
  5308. const char *uri,
  5309. const char *nonce,
  5310. const char *nc,
  5311. const char *cnonce,
  5312. const char *qop,
  5313. const char *response)
  5314. {
  5315. char ha2[32 + 1], expected_response[32 + 1];
  5316. /* Some of the parameters may be NULL */
  5317. if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL
  5318. || qop == NULL
  5319. || response == NULL) {
  5320. return 0;
  5321. }
  5322. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  5323. if (strlen(response) != 32) {
  5324. return 0;
  5325. }
  5326. mg_md5(ha2, method, ":", uri, NULL);
  5327. mg_md5(expected_response,
  5328. ha1,
  5329. ":",
  5330. nonce,
  5331. ":",
  5332. nc,
  5333. ":",
  5334. cnonce,
  5335. ":",
  5336. qop,
  5337. ":",
  5338. ha2,
  5339. NULL);
  5340. return mg_strcasecmp(response, expected_response) == 0;
  5341. }
  5342. /* Use the global passwords file, if specified by auth_gpass option,
  5343. * or search for .htpasswd in the requested directory. */
  5344. static void
  5345. open_auth_file(struct mg_connection *conn,
  5346. const char *path,
  5347. struct mg_file *filep)
  5348. {
  5349. if (conn != NULL && conn->ctx != NULL) {
  5350. char name[PATH_MAX];
  5351. const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
  5352. int truncated;
  5353. if (gpass != NULL) {
  5354. /* Use global passwords file */
  5355. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  5356. #ifdef DEBUG
  5357. /* Use mg_cry here, since gpass has been configured. */
  5358. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  5359. #endif
  5360. }
  5361. /* Important: using local struct mg_file to test path for
  5362. * is_directory flag. If filep is used, mg_stat() makes it
  5363. * appear as if auth file was opened.
  5364. * TODO(mid): Check if this is still required after rewriting
  5365. * mg_stat */
  5366. } else if (mg_stat(conn, path, &filep->stat)
  5367. && filep->stat.is_directory) {
  5368. mg_snprintf(conn,
  5369. &truncated,
  5370. name,
  5371. sizeof(name),
  5372. "%s/%s",
  5373. path,
  5374. PASSWORDS_FILE_NAME);
  5375. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  5376. #ifdef DEBUG
  5377. /* Don't use mg_cry here, but only a trace, since this is
  5378. * a typical case. It will occur for every directory
  5379. * without a password file. */
  5380. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  5381. #endif
  5382. }
  5383. } else {
  5384. /* Try to find .htpasswd in requested directory. */
  5385. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  5386. if (e[0] == '/') {
  5387. break;
  5388. }
  5389. }
  5390. mg_snprintf(conn,
  5391. &truncated,
  5392. name,
  5393. sizeof(name),
  5394. "%.*s/%s",
  5395. (int)(e - p),
  5396. p,
  5397. PASSWORDS_FILE_NAME);
  5398. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  5399. #ifdef DEBUG
  5400. /* Don't use mg_cry here, but only a trace, since this is
  5401. * a typical case. It will occur for every directory
  5402. * without a password file. */
  5403. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  5404. #endif
  5405. }
  5406. }
  5407. }
  5408. }
  5409. /* Parsed Authorization header */
  5410. struct ah {
  5411. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  5412. };
  5413. /* Return 1 on success. Always initializes the ah structure. */
  5414. static int
  5415. parse_auth_header(struct mg_connection *conn,
  5416. char *buf,
  5417. size_t buf_size,
  5418. struct ah *ah)
  5419. {
  5420. char *name, *value, *s;
  5421. const char *auth_header;
  5422. uint64_t nonce;
  5423. if (!ah || !conn) {
  5424. return 0;
  5425. }
  5426. (void)memset(ah, 0, sizeof(*ah));
  5427. if ((auth_header = mg_get_header(conn, "Authorization")) == NULL
  5428. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  5429. return 0;
  5430. }
  5431. /* Make modifiable copy of the auth header */
  5432. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  5433. s = buf;
  5434. /* Parse authorization header */
  5435. for (;;) {
  5436. /* Gobble initial spaces */
  5437. while (isspace(*(unsigned char *)s)) {
  5438. s++;
  5439. }
  5440. name = skip_quoted(&s, "=", " ", 0);
  5441. /* Value is either quote-delimited, or ends at first comma or space. */
  5442. if (s[0] == '\"') {
  5443. s++;
  5444. value = skip_quoted(&s, "\"", " ", '\\');
  5445. if (s[0] == ',') {
  5446. s++;
  5447. }
  5448. } else {
  5449. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  5450. * spaces */
  5451. }
  5452. if (*name == '\0') {
  5453. break;
  5454. }
  5455. if (!strcmp(name, "username")) {
  5456. ah->user = value;
  5457. } else if (!strcmp(name, "cnonce")) {
  5458. ah->cnonce = value;
  5459. } else if (!strcmp(name, "response")) {
  5460. ah->response = value;
  5461. } else if (!strcmp(name, "uri")) {
  5462. ah->uri = value;
  5463. } else if (!strcmp(name, "qop")) {
  5464. ah->qop = value;
  5465. } else if (!strcmp(name, "nc")) {
  5466. ah->nc = value;
  5467. } else if (!strcmp(name, "nonce")) {
  5468. ah->nonce = value;
  5469. }
  5470. }
  5471. #ifndef NO_NONCE_CHECK
  5472. /* Read the nonce from the response. */
  5473. if (ah->nonce == NULL) {
  5474. return 0;
  5475. }
  5476. s = NULL;
  5477. nonce = strtoull(ah->nonce, &s, 10);
  5478. if ((s == NULL) || (*s != 0)) {
  5479. return 0;
  5480. }
  5481. /* Convert the nonce from the client to a number. */
  5482. nonce ^= conn->ctx->auth_nonce_mask;
  5483. /* The converted number corresponds to the time the nounce has been
  5484. * created. This should not be earlier than the server start. */
  5485. /* Server side nonce check is valuable in all situations but one:
  5486. * if the server restarts frequently, but the client should not see
  5487. * that, so the server should accept nonces from previous starts. */
  5488. /* However, the reasonable default is to not accept a nonce from a
  5489. * previous start, so if anyone changed the access rights between
  5490. * two restarts, a new login is required. */
  5491. if (nonce < (uint64_t)conn->ctx->start_time) {
  5492. /* nonce is from a previous start of the server and no longer valid
  5493. * (replay attack?) */
  5494. return 0;
  5495. }
  5496. /* Check if the nonce is too high, so it has not (yet) been used by the
  5497. * server. */
  5498. if (nonce >= ((uint64_t)conn->ctx->start_time + conn->ctx->nonce_count)) {
  5499. return 0;
  5500. }
  5501. #else
  5502. (void)nonce;
  5503. #endif
  5504. /* CGI needs it as REMOTE_USER */
  5505. if (ah->user != NULL) {
  5506. conn->request_info.remote_user = mg_strdup(ah->user);
  5507. } else {
  5508. return 0;
  5509. }
  5510. return 1;
  5511. }
  5512. static const char *
  5513. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  5514. {
  5515. const char *eof;
  5516. size_t len;
  5517. const char *memend;
  5518. if (!filep) {
  5519. return NULL;
  5520. }
  5521. if (filep->access.membuf != NULL && *p != NULL) {
  5522. memend = (const char *)&filep->access.membuf[filep->stat.size];
  5523. /* Search for \n from p till the end of stream */
  5524. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  5525. if (eof != NULL) {
  5526. eof += 1; /* Include \n */
  5527. } else {
  5528. eof = memend; /* Copy remaining data */
  5529. }
  5530. len =
  5531. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  5532. memcpy(buf, *p, len);
  5533. buf[len] = '\0';
  5534. *p += len;
  5535. return len ? eof : NULL;
  5536. } else if (filep->access.fp != NULL) {
  5537. return fgets(buf, (int)size, filep->access.fp);
  5538. } else {
  5539. return NULL;
  5540. }
  5541. }
  5542. /* Define the initial recursion depth for procesesing htpasswd files that
  5543. * include other htpasswd
  5544. * (or even the same) files. It is not difficult to provide a file or files
  5545. * s.t. they force civetweb
  5546. * to infinitely recurse and then crash.
  5547. */
  5548. #define INITIAL_DEPTH 9
  5549. #if INITIAL_DEPTH <= 0
  5550. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  5551. #endif
  5552. struct read_auth_file_struct {
  5553. struct mg_connection *conn;
  5554. struct ah ah;
  5555. char *domain;
  5556. char buf[256 + 256 + 40];
  5557. char *f_user;
  5558. char *f_domain;
  5559. char *f_ha1;
  5560. };
  5561. static int
  5562. read_auth_file(struct mg_file *filep,
  5563. struct read_auth_file_struct *workdata,
  5564. int depth)
  5565. {
  5566. char *p;
  5567. int is_authorized = 0;
  5568. struct mg_file fp;
  5569. size_t l;
  5570. if (!filep || !workdata || 0 == depth) {
  5571. return 0;
  5572. }
  5573. /* Loop over passwords file */
  5574. p = (char *)filep->access.membuf;
  5575. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  5576. l = strlen(workdata->buf);
  5577. while (l > 0) {
  5578. if (isspace(workdata->buf[l - 1])
  5579. || iscntrl(workdata->buf[l - 1])) {
  5580. l--;
  5581. workdata->buf[l] = 0;
  5582. } else
  5583. break;
  5584. }
  5585. if (l < 1) {
  5586. continue;
  5587. }
  5588. workdata->f_user = workdata->buf;
  5589. if (workdata->f_user[0] == ':') {
  5590. /* user names may not contain a ':' and may not be empty,
  5591. * so lines starting with ':' may be used for a special purpose */
  5592. if (workdata->f_user[1] == '#') {
  5593. /* :# is a comment */
  5594. continue;
  5595. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  5596. if (mg_fopen(workdata->conn,
  5597. workdata->f_user + 9,
  5598. MG_FOPEN_MODE_READ,
  5599. &fp)) {
  5600. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  5601. (void)mg_fclose(
  5602. &fp.access); /* ignore error on read only file */
  5603. /* No need to continue processing files once we have a
  5604. * match, since nothing will reset it back
  5605. * to 0.
  5606. */
  5607. if (is_authorized) {
  5608. return is_authorized;
  5609. }
  5610. } else {
  5611. mg_cry(workdata->conn,
  5612. "%s: cannot open authorization file: %s",
  5613. __func__,
  5614. workdata->buf);
  5615. }
  5616. continue;
  5617. }
  5618. /* everything is invalid for the moment (might change in the
  5619. * future) */
  5620. mg_cry(workdata->conn,
  5621. "%s: syntax error in authorization file: %s",
  5622. __func__,
  5623. workdata->buf);
  5624. continue;
  5625. }
  5626. workdata->f_domain = strchr(workdata->f_user, ':');
  5627. if (workdata->f_domain == NULL) {
  5628. mg_cry(workdata->conn,
  5629. "%s: syntax error in authorization file: %s",
  5630. __func__,
  5631. workdata->buf);
  5632. continue;
  5633. }
  5634. *(workdata->f_domain) = 0;
  5635. (workdata->f_domain)++;
  5636. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  5637. if (workdata->f_ha1 == NULL) {
  5638. mg_cry(workdata->conn,
  5639. "%s: syntax error in authorization file: %s",
  5640. __func__,
  5641. workdata->buf);
  5642. continue;
  5643. }
  5644. *(workdata->f_ha1) = 0;
  5645. (workdata->f_ha1)++;
  5646. if (!strcmp(workdata->ah.user, workdata->f_user)
  5647. && !strcmp(workdata->domain, workdata->f_domain)) {
  5648. return check_password(workdata->conn->request_info.request_method,
  5649. workdata->f_ha1,
  5650. workdata->ah.uri,
  5651. workdata->ah.nonce,
  5652. workdata->ah.nc,
  5653. workdata->ah.cnonce,
  5654. workdata->ah.qop,
  5655. workdata->ah.response);
  5656. }
  5657. }
  5658. return is_authorized;
  5659. }
  5660. /* Authorize against the opened passwords file. Return 1 if authorized. */
  5661. static int
  5662. authorize(struct mg_connection *conn, struct mg_file *filep)
  5663. {
  5664. struct read_auth_file_struct workdata;
  5665. char buf[MG_BUF_LEN];
  5666. if (!conn || !conn->ctx) {
  5667. return 0;
  5668. }
  5669. memset(&workdata, 0, sizeof(workdata));
  5670. workdata.conn = conn;
  5671. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  5672. return 0;
  5673. }
  5674. workdata.domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  5675. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  5676. }
  5677. /* Return 1 if request is authorised, 0 otherwise. */
  5678. static int
  5679. check_authorization(struct mg_connection *conn, const char *path)
  5680. {
  5681. char fname[PATH_MAX];
  5682. struct vec uri_vec, filename_vec;
  5683. const char *list;
  5684. struct mg_file file = STRUCT_FILE_INITIALIZER;
  5685. int authorized = 1, truncated;
  5686. if (!conn || !conn->ctx) {
  5687. return 0;
  5688. }
  5689. list = conn->ctx->config[PROTECT_URI];
  5690. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  5691. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  5692. mg_snprintf(conn,
  5693. &truncated,
  5694. fname,
  5695. sizeof(fname),
  5696. "%.*s",
  5697. (int)filename_vec.len,
  5698. filename_vec.ptr);
  5699. if (truncated
  5700. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  5701. mg_cry(conn,
  5702. "%s: cannot open %s: %s",
  5703. __func__,
  5704. fname,
  5705. strerror(errno));
  5706. }
  5707. break;
  5708. }
  5709. }
  5710. if (!is_file_opened(&file.access)) {
  5711. open_auth_file(conn, path, &file);
  5712. }
  5713. if (is_file_opened(&file.access)) {
  5714. authorized = authorize(conn, &file);
  5715. (void)mg_fclose(&file.access); /* ignore error on read only file */
  5716. }
  5717. return authorized;
  5718. }
  5719. static void
  5720. send_authorization_request(struct mg_connection *conn)
  5721. {
  5722. char date[64];
  5723. time_t curtime = time(NULL);
  5724. if (conn && conn->ctx) {
  5725. uint64_t nonce = (uint64_t)(conn->ctx->start_time);
  5726. (void)pthread_mutex_lock(&conn->ctx->nonce_mutex);
  5727. nonce += conn->ctx->nonce_count;
  5728. ++conn->ctx->nonce_count;
  5729. (void)pthread_mutex_unlock(&conn->ctx->nonce_mutex);
  5730. nonce ^= conn->ctx->auth_nonce_mask;
  5731. conn->status_code = 401;
  5732. conn->must_close = 1;
  5733. gmt_time_string(date, sizeof(date), &curtime);
  5734. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  5735. send_no_cache_header(conn);
  5736. send_additional_header(conn);
  5737. mg_printf(conn,
  5738. "Date: %s\r\n"
  5739. "Connection: %s\r\n"
  5740. "Content-Length: 0\r\n"
  5741. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  5742. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  5743. date,
  5744. suggest_connection_header(conn),
  5745. conn->ctx->config[AUTHENTICATION_DOMAIN],
  5746. nonce);
  5747. }
  5748. }
  5749. #if !defined(NO_FILES)
  5750. static int
  5751. is_authorized_for_put(struct mg_connection *conn)
  5752. {
  5753. if (conn) {
  5754. struct mg_file file = STRUCT_FILE_INITIALIZER;
  5755. const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
  5756. int ret = 0;
  5757. if (passfile != NULL
  5758. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  5759. ret = authorize(conn, &file);
  5760. (void)mg_fclose(&file.access); /* ignore error on read only file */
  5761. }
  5762. return ret;
  5763. }
  5764. return 0;
  5765. }
  5766. #endif
  5767. int
  5768. mg_modify_passwords_file(const char *fname,
  5769. const char *domain,
  5770. const char *user,
  5771. const char *pass)
  5772. {
  5773. int found, i;
  5774. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  5775. FILE *fp, *fp2;
  5776. found = 0;
  5777. fp = fp2 = NULL;
  5778. /* Regard empty password as no password - remove user record. */
  5779. if (pass != NULL && pass[0] == '\0') {
  5780. pass = NULL;
  5781. }
  5782. /* Other arguments must not be empty */
  5783. if (fname == NULL || domain == NULL || user == NULL) {
  5784. return 0;
  5785. }
  5786. /* Using the given file format, user name and domain must not contain ':'
  5787. */
  5788. if (strchr(user, ':') != NULL) {
  5789. return 0;
  5790. }
  5791. if (strchr(domain, ':') != NULL) {
  5792. return 0;
  5793. }
  5794. /* Do not allow control characters like newline in user name and domain.
  5795. * Do not allow excessively long names either. */
  5796. for (i = 0; i < 255 && user[i] != 0; i++) {
  5797. if (iscntrl(user[i])) {
  5798. return 0;
  5799. }
  5800. }
  5801. if (user[i]) {
  5802. return 0;
  5803. }
  5804. for (i = 0; i < 255 && domain[i] != 0; i++) {
  5805. if (iscntrl(domain[i])) {
  5806. return 0;
  5807. }
  5808. }
  5809. if (domain[i]) {
  5810. return 0;
  5811. }
  5812. /* The maximum length of the path to the password file is limited */
  5813. if ((strlen(fname) + 4) >= PATH_MAX) {
  5814. return 0;
  5815. }
  5816. /* Create a temporary file name. Length has been checked before. */
  5817. strcpy(tmp, fname);
  5818. strcat(tmp, ".tmp");
  5819. /* Create the file if does not exist */
  5820. /* Use of fopen here is OK, since fname is only ASCII */
  5821. if ((fp = fopen(fname, "a+")) != NULL) {
  5822. (void)fclose(fp);
  5823. }
  5824. /* Open the given file and temporary file */
  5825. if ((fp = fopen(fname, "r")) == NULL) {
  5826. return 0;
  5827. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  5828. fclose(fp);
  5829. return 0;
  5830. }
  5831. /* Copy the stuff to temporary file */
  5832. while (fgets(line, sizeof(line), fp) != NULL) {
  5833. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  5834. continue;
  5835. }
  5836. u[255] = 0;
  5837. d[255] = 0;
  5838. if (!strcmp(u, user) && !strcmp(d, domain)) {
  5839. found++;
  5840. if (pass != NULL) {
  5841. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  5842. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  5843. }
  5844. } else {
  5845. fprintf(fp2, "%s", line);
  5846. }
  5847. }
  5848. /* If new user, just add it */
  5849. if (!found && pass != NULL) {
  5850. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  5851. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  5852. }
  5853. /* Close files */
  5854. fclose(fp);
  5855. fclose(fp2);
  5856. /* Put the temp file in place of real file */
  5857. IGNORE_UNUSED_RESULT(remove(fname));
  5858. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  5859. return 1;
  5860. }
  5861. static int
  5862. is_valid_port(unsigned long port)
  5863. {
  5864. return (port <= 0xffff);
  5865. }
  5866. static int
  5867. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  5868. {
  5869. struct addrinfo hints, *res, *ressave;
  5870. int func_ret = 0;
  5871. int gai_ret;
  5872. memset(&hints, 0, sizeof(struct addrinfo));
  5873. hints.ai_family = af;
  5874. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  5875. if (gai_ret != 0) {
  5876. /* gai_strerror could be used to convert gai_ret to a string */
  5877. /* POSIX return values: see
  5878. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  5879. */
  5880. /* Windows return values: see
  5881. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  5882. */
  5883. return 0;
  5884. }
  5885. ressave = res;
  5886. while (res) {
  5887. if (dstlen >= res->ai_addrlen) {
  5888. memcpy(dst, res->ai_addr, res->ai_addrlen);
  5889. func_ret = 1;
  5890. }
  5891. res = res->ai_next;
  5892. }
  5893. freeaddrinfo(ressave);
  5894. return func_ret;
  5895. }
  5896. static int
  5897. connect_socket(struct mg_context *ctx /* may be NULL */,
  5898. const char *host,
  5899. int port,
  5900. int use_ssl,
  5901. char *ebuf,
  5902. size_t ebuf_len,
  5903. SOCKET *sock /* output: socket, must not be NULL */,
  5904. union usa *sa /* output: socket address, must not be NULL */
  5905. )
  5906. {
  5907. int ip_ver = 0;
  5908. *sock = INVALID_SOCKET;
  5909. memset(sa, 0, sizeof(*sa));
  5910. if (ebuf_len > 0) {
  5911. *ebuf = 0;
  5912. }
  5913. if (host == NULL) {
  5914. mg_snprintf(NULL,
  5915. NULL, /* No truncation check for ebuf */
  5916. ebuf,
  5917. ebuf_len,
  5918. "%s",
  5919. "NULL host");
  5920. return 0;
  5921. }
  5922. if (port <= 0 || !is_valid_port((unsigned)port)) {
  5923. mg_snprintf(NULL,
  5924. NULL, /* No truncation check for ebuf */
  5925. ebuf,
  5926. ebuf_len,
  5927. "%s",
  5928. "invalid port");
  5929. return 0;
  5930. }
  5931. #if !defined(NO_SSL)
  5932. #if !defined(NO_SSL_DL)
  5933. #ifdef OPENSSL_API_1_1
  5934. if (use_ssl && (TLS_client_method == NULL)) {
  5935. mg_snprintf(NULL,
  5936. NULL, /* No truncation check for ebuf */
  5937. ebuf,
  5938. ebuf_len,
  5939. "%s",
  5940. "SSL is not initialized");
  5941. return 0;
  5942. }
  5943. #else
  5944. if (use_ssl && (SSLv23_client_method == NULL)) {
  5945. mg_snprintf(NULL,
  5946. NULL, /* No truncation check for ebuf */
  5947. ebuf,
  5948. ebuf_len,
  5949. "%s",
  5950. "SSL is not initialized");
  5951. return 0;
  5952. }
  5953. #endif /* OPENSSL_API_1_1 */
  5954. #else
  5955. (void)use_ssl;
  5956. #endif /* NO_SSL_DL */
  5957. #else
  5958. (void)use_ssl;
  5959. #endif /* !defined(NO_SSL) */
  5960. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  5961. sa->sin.sin_port = htons((uint16_t)port);
  5962. ip_ver = 4;
  5963. #ifdef USE_IPV6
  5964. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  5965. sa->sin6.sin6_port = htons((uint16_t)port);
  5966. ip_ver = 6;
  5967. } else if (host[0] == '[') {
  5968. /* While getaddrinfo on Windows will work with [::1],
  5969. * getaddrinfo on Linux only works with ::1 (without []). */
  5970. size_t l = strlen(host + 1);
  5971. char *h = (l > 1) ? mg_strdup(host + 1) : NULL;
  5972. if (h) {
  5973. h[l - 1] = 0;
  5974. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  5975. sa->sin6.sin6_port = htons((uint16_t)port);
  5976. ip_ver = 6;
  5977. }
  5978. mg_free(h);
  5979. }
  5980. #endif
  5981. }
  5982. if (ip_ver == 0) {
  5983. mg_snprintf(NULL,
  5984. NULL, /* No truncation check for ebuf */
  5985. ebuf,
  5986. ebuf_len,
  5987. "%s",
  5988. "host not found");
  5989. return 0;
  5990. }
  5991. if (ip_ver == 4) {
  5992. *sock = socket(PF_INET, SOCK_STREAM, 0);
  5993. }
  5994. #ifdef USE_IPV6
  5995. else if (ip_ver == 6) {
  5996. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  5997. }
  5998. #endif
  5999. if (*sock == INVALID_SOCKET) {
  6000. mg_snprintf(NULL,
  6001. NULL, /* No truncation check for ebuf */
  6002. ebuf,
  6003. ebuf_len,
  6004. "socket(): %s",
  6005. strerror(ERRNO));
  6006. return 0;
  6007. }
  6008. set_close_on_exec(*sock, fc(ctx));
  6009. if ((ip_ver == 4)
  6010. && (connect(*sock, (struct sockaddr *)&sa->sin, sizeof(sa->sin))
  6011. == 0)) {
  6012. /* connected with IPv4 */
  6013. set_blocking_mode(*sock, 0);
  6014. return 1;
  6015. }
  6016. #ifdef USE_IPV6
  6017. if ((ip_ver == 6)
  6018. && (connect(*sock, (struct sockaddr *)&sa->sin6, sizeof(sa->sin6))
  6019. == 0)) {
  6020. /* connected with IPv6 */
  6021. set_blocking_mode(*sock, 0);
  6022. return 1;
  6023. }
  6024. #endif
  6025. /* Not connected */
  6026. mg_snprintf(NULL,
  6027. NULL, /* No truncation check for ebuf */
  6028. ebuf,
  6029. ebuf_len,
  6030. "connect(%s:%d): %s",
  6031. host,
  6032. port,
  6033. strerror(ERRNO));
  6034. closesocket(*sock);
  6035. *sock = INVALID_SOCKET;
  6036. return 0;
  6037. }
  6038. int
  6039. mg_url_encode(const char *src, char *dst, size_t dst_len)
  6040. {
  6041. static const char *dont_escape = "._-$,;~()";
  6042. static const char *hex = "0123456789abcdef";
  6043. char *pos = dst;
  6044. const char *end = dst + dst_len - 1;
  6045. for (; *src != '\0' && pos < end; src++, pos++) {
  6046. if (isalnum(*(const unsigned char *)src)
  6047. || strchr(dont_escape, *(const unsigned char *)src) != NULL) {
  6048. *pos = *src;
  6049. } else if (pos + 2 < end) {
  6050. pos[0] = '%';
  6051. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  6052. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  6053. pos += 2;
  6054. } else {
  6055. break;
  6056. }
  6057. }
  6058. *pos = '\0';
  6059. return (*src == '\0') ? (int)(pos - dst) : -1;
  6060. }
  6061. static void
  6062. print_dir_entry(struct de *de)
  6063. {
  6064. char size[64], mod[64], href[PATH_MAX * 3 /* worst case */];
  6065. struct tm *tm;
  6066. if (de->file.is_directory) {
  6067. mg_snprintf(de->conn,
  6068. NULL, /* Buffer is big enough */
  6069. size,
  6070. sizeof(size),
  6071. "%s",
  6072. "[DIRECTORY]");
  6073. } else {
  6074. /* We use (signed) cast below because MSVC 6 compiler cannot
  6075. * convert unsigned __int64 to double. Sigh. */
  6076. if (de->file.size < 1024) {
  6077. mg_snprintf(de->conn,
  6078. NULL, /* Buffer is big enough */
  6079. size,
  6080. sizeof(size),
  6081. "%d",
  6082. (int)de->file.size);
  6083. } else if (de->file.size < 0x100000) {
  6084. mg_snprintf(de->conn,
  6085. NULL, /* Buffer is big enough */
  6086. size,
  6087. sizeof(size),
  6088. "%.1fk",
  6089. (double)de->file.size / 1024.0);
  6090. } else if (de->file.size < 0x40000000) {
  6091. mg_snprintf(de->conn,
  6092. NULL, /* Buffer is big enough */
  6093. size,
  6094. sizeof(size),
  6095. "%.1fM",
  6096. (double)de->file.size / 1048576);
  6097. } else {
  6098. mg_snprintf(de->conn,
  6099. NULL, /* Buffer is big enough */
  6100. size,
  6101. sizeof(size),
  6102. "%.1fG",
  6103. (double)de->file.size / 1073741824);
  6104. }
  6105. }
  6106. /* Note: mg_snprintf will not cause a buffer overflow above.
  6107. * So, string truncation checks are not required here. */
  6108. tm = localtime(&de->file.last_modified);
  6109. if (tm != NULL) {
  6110. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  6111. } else {
  6112. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  6113. mod[sizeof(mod) - 1] = '\0';
  6114. }
  6115. mg_url_encode(de->file_name, href, sizeof(href));
  6116. de->conn->num_bytes_sent +=
  6117. mg_printf(de->conn,
  6118. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  6119. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  6120. de->conn->request_info.local_uri,
  6121. href,
  6122. de->file.is_directory ? "/" : "",
  6123. de->file_name,
  6124. de->file.is_directory ? "/" : "",
  6125. mod,
  6126. size);
  6127. }
  6128. /* This function is called from send_directory() and used for
  6129. * sorting directory entries by size, or name, or modification time.
  6130. * On windows, __cdecl specification is needed in case if project is built
  6131. * with __stdcall convention. qsort always requires __cdels callback. */
  6132. static int WINCDECL
  6133. compare_dir_entries(const void *p1, const void *p2)
  6134. {
  6135. if (p1 && p2) {
  6136. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  6137. const char *query_string = a->conn->request_info.query_string;
  6138. int cmp_result = 0;
  6139. if (query_string == NULL) {
  6140. query_string = "na";
  6141. }
  6142. if (a->file.is_directory && !b->file.is_directory) {
  6143. return -1; /* Always put directories on top */
  6144. } else if (!a->file.is_directory && b->file.is_directory) {
  6145. return 1; /* Always put directories on top */
  6146. } else if (*query_string == 'n') {
  6147. cmp_result = strcmp(a->file_name, b->file_name);
  6148. } else if (*query_string == 's') {
  6149. cmp_result = (a->file.size == b->file.size)
  6150. ? 0
  6151. : ((a->file.size > b->file.size) ? 1 : -1);
  6152. } else if (*query_string == 'd') {
  6153. cmp_result =
  6154. (a->file.last_modified == b->file.last_modified)
  6155. ? 0
  6156. : ((a->file.last_modified > b->file.last_modified) ? 1
  6157. : -1);
  6158. }
  6159. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  6160. }
  6161. return 0;
  6162. }
  6163. static int
  6164. must_hide_file(struct mg_connection *conn, const char *path)
  6165. {
  6166. if (conn && conn->ctx) {
  6167. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  6168. const char *pattern = conn->ctx->config[HIDE_FILES];
  6169. return match_prefix(pw_pattern, strlen(pw_pattern), path) > 0
  6170. || (pattern != NULL
  6171. && match_prefix(pattern, strlen(pattern), path) > 0);
  6172. }
  6173. return 0;
  6174. }
  6175. static int
  6176. scan_directory(struct mg_connection *conn,
  6177. const char *dir,
  6178. void *data,
  6179. void (*cb)(struct de *, void *))
  6180. {
  6181. char path[PATH_MAX];
  6182. struct dirent *dp;
  6183. DIR *dirp;
  6184. struct de de;
  6185. int truncated;
  6186. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  6187. return 0;
  6188. } else {
  6189. de.conn = conn;
  6190. while ((dp = mg_readdir(dirp)) != NULL) {
  6191. /* Do not show current dir and hidden files */
  6192. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  6193. || must_hide_file(conn, dp->d_name)) {
  6194. continue;
  6195. }
  6196. mg_snprintf(
  6197. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  6198. /* If we don't memset stat structure to zero, mtime will have
  6199. * garbage and strftime() will segfault later on in
  6200. * print_dir_entry(). memset is required only if mg_stat()
  6201. * fails. For more details, see
  6202. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  6203. memset(&de.file, 0, sizeof(de.file));
  6204. if (truncated) {
  6205. /* If the path is not complete, skip processing. */
  6206. continue;
  6207. }
  6208. if (!mg_stat(conn, path, &de.file)) {
  6209. mg_cry(conn,
  6210. "%s: mg_stat(%s) failed: %s",
  6211. __func__,
  6212. path,
  6213. strerror(ERRNO));
  6214. }
  6215. de.file_name = dp->d_name;
  6216. cb(&de, data);
  6217. }
  6218. (void)mg_closedir(dirp);
  6219. }
  6220. return 1;
  6221. }
  6222. #if !defined(NO_FILES)
  6223. static int
  6224. remove_directory(struct mg_connection *conn, const char *dir)
  6225. {
  6226. char path[PATH_MAX];
  6227. struct dirent *dp;
  6228. DIR *dirp;
  6229. struct de de;
  6230. int truncated;
  6231. int ok = 1;
  6232. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  6233. return 0;
  6234. } else {
  6235. de.conn = conn;
  6236. while ((dp = mg_readdir(dirp)) != NULL) {
  6237. /* Do not show current dir (but show hidden files as they will
  6238. * also be removed) */
  6239. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  6240. continue;
  6241. }
  6242. mg_snprintf(
  6243. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  6244. /* If we don't memset stat structure to zero, mtime will have
  6245. * garbage and strftime() will segfault later on in
  6246. * print_dir_entry(). memset is required only if mg_stat()
  6247. * fails. For more details, see
  6248. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  6249. memset(&de.file, 0, sizeof(de.file));
  6250. if (truncated) {
  6251. /* Do not delete anything shorter */
  6252. ok = 0;
  6253. continue;
  6254. }
  6255. if (!mg_stat(conn, path, &de.file)) {
  6256. mg_cry(conn,
  6257. "%s: mg_stat(%s) failed: %s",
  6258. __func__,
  6259. path,
  6260. strerror(ERRNO));
  6261. ok = 0;
  6262. }
  6263. if (de.file.is_directory) {
  6264. if (remove_directory(conn, path) == 0) {
  6265. ok = 0;
  6266. }
  6267. } else {
  6268. /* This will fail file is the file is in memory */
  6269. if (mg_remove(conn, path) == 0) {
  6270. ok = 0;
  6271. }
  6272. }
  6273. }
  6274. (void)mg_closedir(dirp);
  6275. IGNORE_UNUSED_RESULT(rmdir(dir));
  6276. }
  6277. return ok;
  6278. }
  6279. #endif
  6280. struct dir_scan_data {
  6281. struct de *entries;
  6282. unsigned int num_entries;
  6283. unsigned int arr_size;
  6284. };
  6285. /* Behaves like realloc(), but frees original pointer on failure */
  6286. static void *
  6287. realloc2(void *ptr, size_t size)
  6288. {
  6289. void *new_ptr = mg_realloc(ptr, size);
  6290. if (new_ptr == NULL) {
  6291. mg_free(ptr);
  6292. }
  6293. return new_ptr;
  6294. }
  6295. static void
  6296. dir_scan_callback(struct de *de, void *data)
  6297. {
  6298. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  6299. if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {
  6300. dsd->arr_size *= 2;
  6301. dsd->entries =
  6302. (struct de *)realloc2(dsd->entries,
  6303. dsd->arr_size * sizeof(dsd->entries[0]));
  6304. }
  6305. if (dsd->entries == NULL) {
  6306. /* TODO(lsm, low): propagate an error to the caller */
  6307. dsd->num_entries = 0;
  6308. } else {
  6309. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  6310. dsd->entries[dsd->num_entries].file = de->file;
  6311. dsd->entries[dsd->num_entries].conn = de->conn;
  6312. dsd->num_entries++;
  6313. }
  6314. }
  6315. static void
  6316. handle_directory_request(struct mg_connection *conn, const char *dir)
  6317. {
  6318. unsigned int i;
  6319. int sort_direction;
  6320. struct dir_scan_data data = {NULL, 0, 128};
  6321. char date[64];
  6322. time_t curtime = time(NULL);
  6323. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  6324. send_http_error(conn,
  6325. 500,
  6326. "Error: Cannot open directory\nopendir(%s): %s",
  6327. dir,
  6328. strerror(ERRNO));
  6329. return;
  6330. }
  6331. gmt_time_string(date, sizeof(date), &curtime);
  6332. if (!conn) {
  6333. return;
  6334. }
  6335. sort_direction = ((conn->request_info.query_string != NULL)
  6336. && (conn->request_info.query_string[1] == 'd'))
  6337. ? 'a'
  6338. : 'd';
  6339. conn->must_close = 1;
  6340. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  6341. send_static_cache_header(conn);
  6342. send_additional_header(conn);
  6343. mg_printf(conn,
  6344. "Date: %s\r\n"
  6345. "Connection: close\r\n"
  6346. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  6347. date);
  6348. conn->num_bytes_sent +=
  6349. mg_printf(conn,
  6350. "<html><head><title>Index of %s</title>"
  6351. "<style>th {text-align: left;}</style></head>"
  6352. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  6353. "<tr><th><a href=\"?n%c\">Name</a></th>"
  6354. "<th><a href=\"?d%c\">Modified</a></th>"
  6355. "<th><a href=\"?s%c\">Size</a></th></tr>"
  6356. "<tr><td colspan=\"3\"><hr></td></tr>",
  6357. conn->request_info.local_uri,
  6358. conn->request_info.local_uri,
  6359. sort_direction,
  6360. sort_direction,
  6361. sort_direction);
  6362. /* Print first entry - link to a parent directory */
  6363. conn->num_bytes_sent +=
  6364. mg_printf(conn,
  6365. "<tr><td><a href=\"%s%s\">%s</a></td>"
  6366. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  6367. conn->request_info.local_uri,
  6368. "..",
  6369. "Parent directory",
  6370. "-",
  6371. "-");
  6372. /* Sort and print directory entries */
  6373. if (data.entries != NULL) {
  6374. qsort(data.entries,
  6375. (size_t)data.num_entries,
  6376. sizeof(data.entries[0]),
  6377. compare_dir_entries);
  6378. for (i = 0; i < data.num_entries; i++) {
  6379. print_dir_entry(&data.entries[i]);
  6380. mg_free(data.entries[i].file_name);
  6381. }
  6382. mg_free(data.entries);
  6383. }
  6384. conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");
  6385. conn->status_code = 200;
  6386. }
  6387. /* Send len bytes from the opened file to the client. */
  6388. static void
  6389. send_file_data(struct mg_connection *conn,
  6390. struct mg_file *filep,
  6391. int64_t offset,
  6392. int64_t len)
  6393. {
  6394. char buf[MG_BUF_LEN];
  6395. int to_read, num_read, num_written;
  6396. int64_t size;
  6397. if (!filep || !conn) {
  6398. return;
  6399. }
  6400. /* Sanity check the offset */
  6401. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  6402. : (int64_t)(filep->stat.size);
  6403. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  6404. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  6405. /* file stored in memory */
  6406. if (len > size - offset) {
  6407. len = size - offset;
  6408. }
  6409. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  6410. } else if (len > 0 && filep->access.fp != NULL) {
  6411. /* file stored on disk */
  6412. #if defined(__linux__)
  6413. /* sendfile is only available for Linux */
  6414. if ((conn->ssl == 0) && (conn->throttle == 0)
  6415. && (!mg_strcasecmp(conn->ctx->config[ALLOW_SENDFILE_CALL],
  6416. "yes"))) {
  6417. off_t sf_offs = (off_t)offset;
  6418. ssize_t sf_sent;
  6419. int sf_file = fileno(filep->access.fp);
  6420. int loop_cnt = 0;
  6421. do {
  6422. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  6423. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  6424. size_t sf_tosend =
  6425. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  6426. sf_sent =
  6427. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  6428. if (sf_sent > 0) {
  6429. conn->num_bytes_sent += sf_sent;
  6430. len -= sf_sent;
  6431. offset += sf_sent;
  6432. } else if (loop_cnt == 0) {
  6433. /* This file can not be sent using sendfile.
  6434. * This might be the case for pseudo-files in the
  6435. * /sys/ and /proc/ file system.
  6436. * Use the regular user mode copy code instead. */
  6437. break;
  6438. } else if (sf_sent == 0) {
  6439. /* No error, but 0 bytes sent. May be EOF? */
  6440. return;
  6441. }
  6442. loop_cnt++;
  6443. } while ((len > 0) && (sf_sent >= 0));
  6444. if (sf_sent > 0) {
  6445. return; /* OK */
  6446. }
  6447. /* sf_sent<0 means error, thus fall back to the classic way */
  6448. /* This is always the case, if sf_file is not a "normal" file,
  6449. * e.g., for sending data from the output of a CGI process. */
  6450. offset = (int64_t)sf_offs;
  6451. }
  6452. #endif
  6453. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  6454. mg_cry(conn, "%s: fseeko() failed: %s", __func__, strerror(ERRNO));
  6455. send_http_error(
  6456. conn,
  6457. 500,
  6458. "%s",
  6459. "Error: Unable to access file at requested position.");
  6460. } else {
  6461. while (len > 0) {
  6462. /* Calculate how much to read from the file in the buffer */
  6463. to_read = sizeof(buf);
  6464. if ((int64_t)to_read > len) {
  6465. to_read = (int)len;
  6466. }
  6467. /* Read from file, exit the loop on error */
  6468. if ((num_read =
  6469. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  6470. <= 0) {
  6471. break;
  6472. }
  6473. /* Send read bytes to the client, exit the loop on error */
  6474. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  6475. != num_read) {
  6476. break;
  6477. }
  6478. /* Both read and were successful, adjust counters */
  6479. conn->num_bytes_sent += num_written;
  6480. len -= num_written;
  6481. }
  6482. }
  6483. }
  6484. }
  6485. static int
  6486. parse_range_header(const char *header, int64_t *a, int64_t *b)
  6487. {
  6488. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  6489. }
  6490. static void
  6491. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  6492. {
  6493. if (filestat != NULL && buf != NULL) {
  6494. mg_snprintf(NULL,
  6495. NULL, /* All calls to construct_etag use 64 byte buffer */
  6496. buf,
  6497. buf_len,
  6498. "\"%lx.%" INT64_FMT "\"",
  6499. (unsigned long)filestat->last_modified,
  6500. filestat->size);
  6501. }
  6502. }
  6503. static void
  6504. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  6505. {
  6506. if (filep != NULL && filep->fp != NULL) {
  6507. #ifdef _WIN32
  6508. (void)conn; /* Unused. */
  6509. #else
  6510. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  6511. mg_cry(conn,
  6512. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  6513. __func__,
  6514. strerror(ERRNO));
  6515. }
  6516. #endif
  6517. }
  6518. }
  6519. static void
  6520. handle_static_file_request(struct mg_connection *conn,
  6521. const char *path,
  6522. struct mg_file *filep,
  6523. const char *mime_type,
  6524. const char *additional_headers)
  6525. {
  6526. char date[64], lm[64], etag[64];
  6527. char range[128]; /* large enough, so there will be no overflow */
  6528. const char *msg = "OK", *hdr;
  6529. time_t curtime = time(NULL);
  6530. int64_t cl, r1, r2;
  6531. struct vec mime_vec;
  6532. int n, truncated;
  6533. char gz_path[PATH_MAX];
  6534. const char *encoding = "";
  6535. const char *cors1, *cors2, *cors3;
  6536. if (conn == NULL || conn->ctx == NULL || filep == NULL) {
  6537. return;
  6538. }
  6539. if (mime_type == NULL) {
  6540. get_mime_type(conn->ctx, path, &mime_vec);
  6541. } else {
  6542. mime_vec.ptr = mime_type;
  6543. mime_vec.len = strlen(mime_type);
  6544. }
  6545. if (filep->stat.size > INT64_MAX) {
  6546. send_http_error(conn,
  6547. 500,
  6548. "Error: File size is too large to send\n%" INT64_FMT,
  6549. filep->stat.size);
  6550. }
  6551. cl = (int64_t)filep->stat.size;
  6552. conn->status_code = 200;
  6553. range[0] = '\0';
  6554. /* if this file is in fact a pre-gzipped file, rewrite its filename
  6555. * it's important to rewrite the filename after resolving
  6556. * the mime type from it, to preserve the actual file's type */
  6557. if (filep->stat.is_gzipped) {
  6558. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  6559. if (truncated) {
  6560. send_http_error(conn,
  6561. 500,
  6562. "Error: Path of zipped file too long (%s)",
  6563. path);
  6564. return;
  6565. }
  6566. path = gz_path;
  6567. encoding = "Content-Encoding: gzip\r\n";
  6568. }
  6569. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  6570. send_http_error(conn,
  6571. 500,
  6572. "Error: Cannot open file\nfopen(%s): %s",
  6573. path,
  6574. strerror(ERRNO));
  6575. return;
  6576. }
  6577. fclose_on_exec(&filep->access, conn);
  6578. /* If Range: header specified, act accordingly */
  6579. r1 = r2 = 0;
  6580. hdr = mg_get_header(conn, "Range");
  6581. if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 && r1 >= 0
  6582. && r2 >= 0) {
  6583. /* actually, range requests don't play well with a pre-gzipped
  6584. * file (since the range is specified in the uncompressed space) */
  6585. if (filep->stat.is_gzipped) {
  6586. send_http_error(
  6587. conn,
  6588. 501,
  6589. "%s",
  6590. "Error: Range requests in gzipped files are not supported");
  6591. (void)mg_fclose(
  6592. &filep->access); /* ignore error on read only file */
  6593. return;
  6594. }
  6595. conn->status_code = 206;
  6596. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  6597. mg_snprintf(conn,
  6598. NULL, /* range buffer is big enough */
  6599. range,
  6600. sizeof(range),
  6601. "Content-Range: bytes "
  6602. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  6603. r1,
  6604. r1 + cl - 1,
  6605. filep->stat.size);
  6606. msg = "Partial Content";
  6607. }
  6608. hdr = mg_get_header(conn, "Origin");
  6609. if (hdr) {
  6610. /* Cross-origin resource sharing (CORS), see
  6611. * http://www.html5rocks.com/en/tutorials/cors/,
  6612. * http://www.html5rocks.com/static/images/cors_server_flowchart.png -
  6613. * preflight is not supported for files. */
  6614. cors1 = "Access-Control-Allow-Origin: ";
  6615. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  6616. cors3 = "\r\n";
  6617. } else {
  6618. cors1 = cors2 = cors3 = "";
  6619. }
  6620. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
  6621. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  6622. gmt_time_string(date, sizeof(date), &curtime);
  6623. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  6624. construct_etag(etag, sizeof(etag), &filep->stat);
  6625. (void)mg_printf(conn,
  6626. "HTTP/1.1 %d %s\r\n"
  6627. "%s%s%s"
  6628. "Date: %s\r\n",
  6629. conn->status_code,
  6630. msg,
  6631. cors1,
  6632. cors2,
  6633. cors3,
  6634. date);
  6635. send_static_cache_header(conn);
  6636. send_additional_header(conn);
  6637. (void)mg_printf(conn,
  6638. "Last-Modified: %s\r\n"
  6639. "Etag: %s\r\n"
  6640. "Content-Type: %.*s\r\n"
  6641. "Content-Length: %" INT64_FMT "\r\n"
  6642. "Connection: %s\r\n"
  6643. "Accept-Ranges: bytes\r\n"
  6644. "%s%s",
  6645. lm,
  6646. etag,
  6647. (int)mime_vec.len,
  6648. mime_vec.ptr,
  6649. cl,
  6650. suggest_connection_header(conn),
  6651. range,
  6652. encoding);
  6653. /* The previous code must not add any header starting with X- to make
  6654. * sure no one of the additional_headers is included twice */
  6655. if (additional_headers != NULL) {
  6656. (void)mg_printf(conn,
  6657. "%.*s\r\n\r\n",
  6658. (int)strlen(additional_headers),
  6659. additional_headers);
  6660. } else {
  6661. (void)mg_printf(conn, "\r\n");
  6662. }
  6663. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  6664. send_file_data(conn, filep, r1, cl);
  6665. }
  6666. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  6667. }
  6668. #if !defined(NO_CACHING)
  6669. static void
  6670. handle_not_modified_static_file_request(struct mg_connection *conn,
  6671. struct mg_file *filep)
  6672. {
  6673. char date[64], lm[64], etag[64];
  6674. time_t curtime = time(NULL);
  6675. if (conn == NULL || filep == NULL) {
  6676. return;
  6677. }
  6678. conn->status_code = 304;
  6679. gmt_time_string(date, sizeof(date), &curtime);
  6680. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  6681. construct_etag(etag, sizeof(etag), &filep->stat);
  6682. (void)mg_printf(conn,
  6683. "HTTP/1.1 %d %s\r\n"
  6684. "Date: %s\r\n",
  6685. conn->status_code,
  6686. mg_get_response_code_text(conn, conn->status_code),
  6687. date);
  6688. send_static_cache_header(conn);
  6689. send_additional_header(conn);
  6690. (void)mg_printf(conn,
  6691. "Last-Modified: %s\r\n"
  6692. "Etag: %s\r\n"
  6693. "Connection: %s\r\n"
  6694. "\r\n",
  6695. lm,
  6696. etag,
  6697. suggest_connection_header(conn));
  6698. }
  6699. #endif
  6700. void
  6701. mg_send_file(struct mg_connection *conn, const char *path)
  6702. {
  6703. mg_send_mime_file(conn, path, NULL);
  6704. }
  6705. void
  6706. mg_send_mime_file(struct mg_connection *conn,
  6707. const char *path,
  6708. const char *mime_type)
  6709. {
  6710. mg_send_mime_file2(conn, path, mime_type, NULL);
  6711. }
  6712. void
  6713. mg_send_mime_file2(struct mg_connection *conn,
  6714. const char *path,
  6715. const char *mime_type,
  6716. const char *additional_headers)
  6717. {
  6718. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6719. if (mg_stat(conn, path, &file.stat)) {
  6720. if (file.stat.is_directory) {
  6721. if (!conn) {
  6722. return;
  6723. }
  6724. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  6725. "yes")) {
  6726. handle_directory_request(conn, path);
  6727. } else {
  6728. send_http_error(conn,
  6729. 403,
  6730. "%s",
  6731. "Error: Directory listing denied");
  6732. }
  6733. } else {
  6734. handle_static_file_request(
  6735. conn, path, &file, mime_type, additional_headers);
  6736. }
  6737. } else {
  6738. send_http_error(conn, 404, "%s", "Error: File not found");
  6739. }
  6740. }
  6741. /* For a given PUT path, create all intermediate subdirectories.
  6742. * Return 0 if the path itself is a directory.
  6743. * Return 1 if the path leads to a file.
  6744. * Return -1 for if the path is too long.
  6745. * Return -2 if path can not be created.
  6746. */
  6747. static int
  6748. put_dir(struct mg_connection *conn, const char *path)
  6749. {
  6750. char buf[PATH_MAX];
  6751. const char *s, *p;
  6752. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6753. size_t len;
  6754. int res = 1;
  6755. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  6756. len = (size_t)(p - path);
  6757. if (len >= sizeof(buf)) {
  6758. /* path too long */
  6759. res = -1;
  6760. break;
  6761. }
  6762. memcpy(buf, path, len);
  6763. buf[len] = '\0';
  6764. /* Try to create intermediate directory */
  6765. DEBUG_TRACE("mkdir(%s)", buf);
  6766. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  6767. /* path does not exixt and can not be created */
  6768. res = -2;
  6769. break;
  6770. }
  6771. /* Is path itself a directory? */
  6772. if (p[1] == '\0') {
  6773. res = 0;
  6774. }
  6775. }
  6776. return res;
  6777. }
  6778. static void
  6779. remove_bad_file(const struct mg_connection *conn, const char *path)
  6780. {
  6781. int r = mg_remove(conn, path);
  6782. if (r != 0) {
  6783. mg_cry(conn, "%s: Cannot remove invalid file %s", __func__, path);
  6784. }
  6785. }
  6786. long long
  6787. mg_store_body(struct mg_connection *conn, const char *path)
  6788. {
  6789. char buf[MG_BUF_LEN];
  6790. long long len = 0;
  6791. int ret, n;
  6792. struct mg_file fi;
  6793. if (conn->consumed_content != 0) {
  6794. mg_cry(conn, "%s: Contents already consumed", __func__);
  6795. return -11;
  6796. }
  6797. ret = put_dir(conn, path);
  6798. if (ret < 0) {
  6799. /* -1 for path too long,
  6800. * -2 for path can not be created. */
  6801. return ret;
  6802. }
  6803. if (ret != 1) {
  6804. /* Return 0 means, path itself is a directory. */
  6805. return 0;
  6806. }
  6807. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  6808. return -12;
  6809. }
  6810. ret = mg_read(conn, buf, sizeof(buf));
  6811. while (ret > 0) {
  6812. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  6813. if (n != ret) {
  6814. (void)mg_fclose(
  6815. &fi.access); /* File is bad and will be removed anyway. */
  6816. remove_bad_file(conn, path);
  6817. return -13;
  6818. }
  6819. ret = mg_read(conn, buf, sizeof(buf));
  6820. }
  6821. /* File is open for writing. If fclose fails, there was probably an
  6822. * error flushing the buffer to disk, so the file on disk might be
  6823. * broken. Delete it and return an error to the caller. */
  6824. if (mg_fclose(&fi.access) != 0) {
  6825. remove_bad_file(conn, path);
  6826. return -14;
  6827. }
  6828. return len;
  6829. }
  6830. /* Parse HTTP headers from the given buffer, advance buf pointer
  6831. * to the point where parsing stopped.
  6832. * All parameters must be valid pointers (not NULL).
  6833. * Return <0 on error. */
  6834. static int
  6835. parse_http_headers(char **buf, struct mg_request_info *ri)
  6836. {
  6837. int i;
  6838. ri->num_headers = 0;
  6839. for (i = 0; i < (int)ARRAY_SIZE(ri->http_headers); i++) {
  6840. char *dp = *buf;
  6841. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  6842. dp++;
  6843. }
  6844. if (dp == *buf) {
  6845. /* End of headers reached. */
  6846. break;
  6847. }
  6848. if (*dp != ':') {
  6849. /* This is not a valid field. */
  6850. return -1;
  6851. }
  6852. /* End of header key (*dp == ':') */
  6853. /* Truncate here and set the key name */
  6854. *dp = 0;
  6855. ri->http_headers[i].name = *buf;
  6856. do {
  6857. dp++;
  6858. } while (*dp == ' ');
  6859. /* The rest of the line is the value */
  6860. ri->http_headers[i].value = dp;
  6861. *buf = dp + strcspn(dp, "\r\n");
  6862. if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) {
  6863. *buf = NULL;
  6864. }
  6865. ri->num_headers = i + 1;
  6866. if (*buf) {
  6867. (*buf)[0] = 0;
  6868. (*buf)[1] = 0;
  6869. *buf += 2;
  6870. } else {
  6871. *buf = dp;
  6872. break;
  6873. }
  6874. if ((*buf)[0] == '\r') {
  6875. /* This is the end of the header */
  6876. break;
  6877. }
  6878. }
  6879. return ri->num_headers;
  6880. }
  6881. static int
  6882. is_valid_http_method(const char *method)
  6883. {
  6884. return !strcmp(method, "GET") /* HTTP (RFC 2616) */
  6885. || !strcmp(method, "POST") /* HTTP (RFC 2616) */
  6886. || !strcmp(method, "HEAD") /* HTTP (RFC 2616) */
  6887. || !strcmp(method, "PUT") /* HTTP (RFC 2616) */
  6888. || !strcmp(method, "DELETE") /* HTTP (RFC 2616) */
  6889. || !strcmp(method, "OPTIONS") /* HTTP (RFC 2616) */
  6890. /* TRACE method (RFC 2616) is not supported for security reasons */
  6891. || !strcmp(method, "CONNECT") /* HTTP (RFC 2616) */
  6892. || !strcmp(method, "PROPFIND") /* WEBDAV (RFC 2518) */
  6893. || !strcmp(method, "MKCOL") /* WEBDAV (RFC 2518) */
  6894. /* Unsupported WEBDAV Methods: */
  6895. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  6896. /* + 11 methods from RFC 3253 */
  6897. /* ORDERPATCH (RFC 3648) */
  6898. /* ACL (RFC 3744) */
  6899. /* SEARCH (RFC 5323) */
  6900. /* + MicroSoft extensions
  6901. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  6902. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  6903. || !strcmp(method, "PATCH"); /* PATCH method (RFC 5789) */
  6904. }
  6905. /* Parse HTTP request, fill in mg_request_info structure.
  6906. * This function modifies the buffer by NUL-terminating
  6907. * HTTP request components, header names and header values.
  6908. * Parameters:
  6909. * buf (in/out): pointer to the HTTP header to parse and split
  6910. * len (in): length of HTTP header buffer
  6911. * re (out): parsed header as mg_request_info
  6912. * buf and ri must be valid pointers (not NULL), len>0.
  6913. * Returns <0 on error. */
  6914. static int
  6915. parse_http_message(char *buf, int len, struct mg_request_info *ri)
  6916. {
  6917. int is_request, request_length;
  6918. char *start_line;
  6919. request_length = get_request_len(buf, len);
  6920. if (request_length > 0) {
  6921. /* Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_addr,
  6922. * remote_port */
  6923. ri->remote_user = ri->request_method = ri->request_uri =
  6924. ri->http_version = NULL;
  6925. ri->num_headers = 0;
  6926. buf[request_length - 1] = '\0';
  6927. /* RFC says that all initial whitespaces should be ingored */
  6928. while (*buf != '\0' && isspace(*(unsigned char *)buf)) {
  6929. buf++;
  6930. }
  6931. start_line = skip(&buf, "\r\n");
  6932. ri->request_method = skip(&start_line, " ");
  6933. ri->request_uri = skip(&start_line, " ");
  6934. ri->http_version = start_line;
  6935. /* HTTP message could be either HTTP request:
  6936. * "GET / HTTP/1.0 ..."
  6937. * or a HTTP response:
  6938. * "HTTP/1.0 200 OK ..."
  6939. * otherwise it is invalid.
  6940. */
  6941. is_request = is_valid_http_method(ri->request_method);
  6942. if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0)
  6943. || (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
  6944. /* Not a valid request or response: invalid */
  6945. return -1;
  6946. }
  6947. if (is_request) {
  6948. ri->http_version += 5;
  6949. }
  6950. if (parse_http_headers(&buf, ri) < 0) {
  6951. /* Error while parsing headers */
  6952. return -1;
  6953. }
  6954. }
  6955. return request_length;
  6956. }
  6957. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  6958. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  6959. * buffer (which marks the end of HTTP request). Buffer buf may already
  6960. * have some data. The length of the data is stored in nread.
  6961. * Upon every read operation, increase nread by the number of bytes read. */
  6962. static int
  6963. read_request(FILE *fp,
  6964. struct mg_connection *conn,
  6965. char *buf,
  6966. int bufsiz,
  6967. int *nread)
  6968. {
  6969. int request_len, n = 0;
  6970. struct timespec last_action_time;
  6971. double request_timeout;
  6972. if (!conn) {
  6973. return 0;
  6974. }
  6975. memset(&last_action_time, 0, sizeof(last_action_time));
  6976. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  6977. /* value of request_timeout is in seconds, config in milliseconds */
  6978. request_timeout = atof(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  6979. } else {
  6980. request_timeout = -1.0;
  6981. }
  6982. if (conn->handled_requests > 0) {
  6983. if (conn->ctx->config[KEEP_ALIVE_TIMEOUT]) {
  6984. request_timeout =
  6985. atof(conn->ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  6986. }
  6987. }
  6988. request_len = get_request_len(buf, *nread);
  6989. /* first time reading from this connection */
  6990. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  6991. while (request_len == 0) {
  6992. /* Full request not yet received */
  6993. if (conn->ctx->stop_flag != 0) {
  6994. /* Server is to be stopped. */
  6995. return -1;
  6996. }
  6997. if (*nread >= bufsiz) {
  6998. /* Request too long */
  6999. return -2;
  7000. }
  7001. n = pull_inner(
  7002. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  7003. if (n == -2) {
  7004. /* Receive error */
  7005. return -1;
  7006. }
  7007. if (n > 0) {
  7008. *nread += n;
  7009. request_len = get_request_len(buf, *nread);
  7010. } else {
  7011. request_len = 0;
  7012. }
  7013. if ((request_len == 0) && (request_timeout >= 0)) {
  7014. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  7015. > request_timeout) {
  7016. /* Timeout */
  7017. return -1;
  7018. }
  7019. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  7020. }
  7021. }
  7022. return request_len;
  7023. }
  7024. #if !defined(NO_FILES)
  7025. /* For given directory path, substitute it to valid index file.
  7026. * Return 1 if index file has been found, 0 if not found.
  7027. * If the file is found, it's stats is returned in stp. */
  7028. static int
  7029. substitute_index_file(struct mg_connection *conn,
  7030. char *path,
  7031. size_t path_len,
  7032. struct mg_file *filep)
  7033. {
  7034. if (conn && conn->ctx) {
  7035. const char *list = conn->ctx->config[INDEX_FILES];
  7036. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7037. struct vec filename_vec;
  7038. size_t n = strlen(path);
  7039. int found = 0;
  7040. /* The 'path' given to us points to the directory. Remove all trailing
  7041. * directory separator characters from the end of the path, and
  7042. * then append single directory separator character. */
  7043. while (n > 0 && path[n - 1] == '/') {
  7044. n--;
  7045. }
  7046. path[n] = '/';
  7047. /* Traverse index files list. For each entry, append it to the given
  7048. * path and see if the file exists. If it exists, break the loop */
  7049. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  7050. /* Ignore too long entries that may overflow path buffer */
  7051. if (filename_vec.len > path_len - (n + 2)) {
  7052. continue;
  7053. }
  7054. /* Prepare full path to the index file */
  7055. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  7056. /* Does it exist? */
  7057. if (mg_stat(conn, path, &file.stat)) {
  7058. /* Yes it does, break the loop */
  7059. *filep = file;
  7060. found = 1;
  7061. break;
  7062. }
  7063. }
  7064. /* If no index file exists, restore directory path */
  7065. if (!found) {
  7066. path[n] = '\0';
  7067. }
  7068. return found;
  7069. }
  7070. return 0;
  7071. }
  7072. #endif
  7073. #if !defined(NO_CACHING)
  7074. /* Return True if we should reply 304 Not Modified. */
  7075. static int
  7076. is_not_modified(const struct mg_connection *conn,
  7077. const struct mg_file_stat *filestat)
  7078. {
  7079. char etag[64];
  7080. const char *ims = mg_get_header(conn, "If-Modified-Since");
  7081. const char *inm = mg_get_header(conn, "If-None-Match");
  7082. construct_etag(etag, sizeof(etag), filestat);
  7083. return (inm != NULL && !mg_strcasecmp(etag, inm))
  7084. || ((ims != NULL)
  7085. && (filestat->last_modified <= parse_date_string(ims)));
  7086. }
  7087. #endif /* !NO_CACHING */
  7088. #if !defined(NO_CGI) || !defined(NO_FILES)
  7089. static int
  7090. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  7091. {
  7092. const char *expect, *body;
  7093. char buf[MG_BUF_LEN];
  7094. int to_read, nread, success = 0;
  7095. int64_t buffered_len;
  7096. double timeout = -1.0;
  7097. if (!conn) {
  7098. return 0;
  7099. }
  7100. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  7101. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  7102. }
  7103. expect = mg_get_header(conn, "Expect");
  7104. /* assert(fp != NULL); */
  7105. if (!fp) {
  7106. send_http_error(conn, 500, "%s", "Error: NULL File");
  7107. return 0;
  7108. }
  7109. if (conn->content_len == -1 && !conn->is_chunked) {
  7110. /* Content length is not specified by the client. */
  7111. send_http_error(conn,
  7112. 411,
  7113. "%s",
  7114. "Error: Client did not specify content length");
  7115. } else if ((expect != NULL)
  7116. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  7117. /* Client sent an "Expect: xyz" header and xyz is not 100-continue. */
  7118. send_http_error(conn,
  7119. 417,
  7120. "Error: Can not fulfill expectation %s",
  7121. expect);
  7122. } else {
  7123. if (expect != NULL) {
  7124. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  7125. conn->status_code = 100;
  7126. } else {
  7127. conn->status_code = 200;
  7128. }
  7129. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  7130. - conn->consumed_content;
  7131. /* assert(buffered_len >= 0); */
  7132. /* assert(conn->consumed_content == 0); */
  7133. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  7134. send_http_error(conn, 500, "%s", "Error: Size mismatch");
  7135. return 0;
  7136. }
  7137. if (buffered_len > 0) {
  7138. if ((int64_t)buffered_len > conn->content_len) {
  7139. buffered_len = (int)conn->content_len;
  7140. }
  7141. body = conn->buf + conn->request_len + conn->consumed_content;
  7142. push_all(conn->ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  7143. conn->consumed_content += buffered_len;
  7144. }
  7145. nread = 0;
  7146. while (conn->consumed_content < conn->content_len) {
  7147. to_read = sizeof(buf);
  7148. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  7149. to_read = (int)(conn->content_len - conn->consumed_content);
  7150. }
  7151. nread = pull_inner(NULL, conn, buf, to_read, timeout);
  7152. if (nread == -2) {
  7153. /* error */
  7154. break;
  7155. }
  7156. if (nread > 0) {
  7157. if (push_all(conn->ctx, fp, sock, ssl, buf, nread) != nread) {
  7158. break;
  7159. }
  7160. }
  7161. conn->consumed_content += nread;
  7162. }
  7163. if (conn->consumed_content == conn->content_len) {
  7164. success = (nread >= 0);
  7165. }
  7166. /* Each error code path in this function must send an error */
  7167. if (!success) {
  7168. /* NOTE: Maybe some data has already been sent. */
  7169. /* TODO (low): If some data has been sent, a correct error
  7170. * reply can no longer be sent, so just close the connection */
  7171. send_http_error(conn, 500, "%s", "");
  7172. }
  7173. }
  7174. return success;
  7175. }
  7176. #endif
  7177. #if !defined(NO_CGI)
  7178. /* This structure helps to create an environment for the spawned CGI program.
  7179. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  7180. * last element must be NULL.
  7181. * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  7182. * strings must reside in a contiguous buffer. The end of the buffer is
  7183. * marked by two '\0' characters.
  7184. * We satisfy both worlds: we create an envp array (which is vars), all
  7185. * entries are actually pointers inside buf. */
  7186. struct cgi_environment {
  7187. struct mg_connection *conn;
  7188. /* Data block */
  7189. char *buf; /* Environment buffer */
  7190. size_t buflen; /* Space available in buf */
  7191. size_t bufused; /* Space taken in buf */
  7192. /* Index block */
  7193. char **var; /* char **envp */
  7194. size_t varlen; /* Number of variables available in var */
  7195. size_t varused; /* Number of variables stored in var */
  7196. };
  7197. static void addenv(struct cgi_environment *env,
  7198. PRINTF_FORMAT_STRING(const char *fmt),
  7199. ...) PRINTF_ARGS(2, 3);
  7200. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  7201. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  7202. static void
  7203. addenv(struct cgi_environment *env, const char *fmt, ...)
  7204. {
  7205. size_t n, space;
  7206. int truncated = 0;
  7207. char *added;
  7208. va_list ap;
  7209. /* Calculate how much space is left in the buffer */
  7210. space = (env->buflen - env->bufused);
  7211. /* Calculate an estimate for the required space */
  7212. n = strlen(fmt) + 2 + 128;
  7213. do {
  7214. if (space <= n) {
  7215. /* Allocate new buffer */
  7216. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  7217. added = (char *)mg_realloc(env->buf, n);
  7218. if (!added) {
  7219. /* Out of memory */
  7220. mg_cry(env->conn,
  7221. "%s: Cannot allocate memory for CGI variable [%s]",
  7222. __func__,
  7223. fmt);
  7224. return;
  7225. }
  7226. env->buf = added;
  7227. env->buflen = n;
  7228. space = (env->buflen - env->bufused);
  7229. }
  7230. /* Make a pointer to the free space int the buffer */
  7231. added = env->buf + env->bufused;
  7232. /* Copy VARIABLE=VALUE\0 string into the free space */
  7233. va_start(ap, fmt);
  7234. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  7235. va_end(ap);
  7236. /* Do not add truncated strings to the environment */
  7237. if (truncated) {
  7238. /* Reallocate the buffer */
  7239. space = 0;
  7240. n = 1;
  7241. }
  7242. } while (truncated);
  7243. /* Calculate number of bytes added to the environment */
  7244. n = strlen(added) + 1;
  7245. env->bufused += n;
  7246. /* Now update the variable index */
  7247. space = (env->varlen - env->varused);
  7248. if (space < 2) {
  7249. mg_cry(env->conn,
  7250. "%s: Cannot register CGI variable [%s]",
  7251. __func__,
  7252. fmt);
  7253. return;
  7254. }
  7255. /* Append a pointer to the added string into the envp array */
  7256. env->var[env->varused] = added;
  7257. env->varused++;
  7258. }
  7259. static void
  7260. prepare_cgi_environment(struct mg_connection *conn,
  7261. const char *prog,
  7262. struct cgi_environment *env)
  7263. {
  7264. const char *s;
  7265. struct vec var_vec;
  7266. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  7267. int i, truncated, uri_len;
  7268. if (conn == NULL || prog == NULL || env == NULL) {
  7269. return;
  7270. }
  7271. env->conn = conn;
  7272. env->buflen = CGI_ENVIRONMENT_SIZE;
  7273. env->bufused = 0;
  7274. env->buf = (char *)mg_malloc(env->buflen);
  7275. env->varlen = MAX_CGI_ENVIR_VARS;
  7276. env->varused = 0;
  7277. env->var = (char **)mg_malloc(env->buflen * sizeof(char *));
  7278. addenv(env, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  7279. addenv(env, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  7280. addenv(env, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  7281. addenv(env, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  7282. /* Prepare the environment block */
  7283. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  7284. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  7285. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  7286. #if defined(USE_IPV6)
  7287. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  7288. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  7289. } else
  7290. #endif
  7291. {
  7292. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  7293. }
  7294. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  7295. addenv(env, "REMOTE_ADDR=%s", src_addr);
  7296. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  7297. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  7298. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  7299. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  7300. /* SCRIPT_NAME */
  7301. uri_len = (int)strlen(conn->request_info.local_uri);
  7302. if (conn->path_info == NULL) {
  7303. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  7304. /* URI: /path_to_script/script.cgi */
  7305. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  7306. } else {
  7307. /* URI: /path_to_script/ ... using index.cgi */
  7308. char *index_file = strrchr(prog, '/');
  7309. if (index_file) {
  7310. addenv(env,
  7311. "SCRIPT_NAME=%s%s",
  7312. conn->request_info.local_uri,
  7313. index_file + 1);
  7314. }
  7315. }
  7316. } else {
  7317. /* URI: /path_to_script/script.cgi/path_info */
  7318. addenv(env,
  7319. "SCRIPT_NAME=%.*s",
  7320. uri_len - (int)strlen(conn->path_info),
  7321. conn->request_info.local_uri);
  7322. }
  7323. addenv(env, "SCRIPT_FILENAME=%s", prog);
  7324. if (conn->path_info == NULL) {
  7325. addenv(env, "PATH_TRANSLATED=%s", conn->ctx->config[DOCUMENT_ROOT]);
  7326. } else {
  7327. addenv(env,
  7328. "PATH_TRANSLATED=%s%s",
  7329. conn->ctx->config[DOCUMENT_ROOT],
  7330. conn->path_info);
  7331. }
  7332. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  7333. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  7334. addenv(env, "CONTENT_TYPE=%s", s);
  7335. }
  7336. if (conn->request_info.query_string != NULL) {
  7337. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  7338. }
  7339. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  7340. addenv(env, "CONTENT_LENGTH=%s", s);
  7341. }
  7342. if ((s = getenv("PATH")) != NULL) {
  7343. addenv(env, "PATH=%s", s);
  7344. }
  7345. if (conn->path_info != NULL) {
  7346. addenv(env, "PATH_INFO=%s", conn->path_info);
  7347. }
  7348. if (conn->status_code > 0) {
  7349. /* CGI error handler should show the status code */
  7350. addenv(env, "STATUS=%d", conn->status_code);
  7351. }
  7352. #if defined(_WIN32)
  7353. if ((s = getenv("COMSPEC")) != NULL) {
  7354. addenv(env, "COMSPEC=%s", s);
  7355. }
  7356. if ((s = getenv("SYSTEMROOT")) != NULL) {
  7357. addenv(env, "SYSTEMROOT=%s", s);
  7358. }
  7359. if ((s = getenv("SystemDrive")) != NULL) {
  7360. addenv(env, "SystemDrive=%s", s);
  7361. }
  7362. if ((s = getenv("ProgramFiles")) != NULL) {
  7363. addenv(env, "ProgramFiles=%s", s);
  7364. }
  7365. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  7366. addenv(env, "ProgramFiles(x86)=%s", s);
  7367. }
  7368. #else
  7369. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  7370. addenv(env, "LD_LIBRARY_PATH=%s", s);
  7371. }
  7372. #endif /* _WIN32 */
  7373. if ((s = getenv("PERLLIB")) != NULL) {
  7374. addenv(env, "PERLLIB=%s", s);
  7375. }
  7376. if (conn->request_info.remote_user != NULL) {
  7377. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  7378. addenv(env, "%s", "AUTH_TYPE=Digest");
  7379. }
  7380. /* Add all headers as HTTP_* variables */
  7381. for (i = 0; i < conn->request_info.num_headers; i++) {
  7382. (void)mg_snprintf(conn,
  7383. &truncated,
  7384. http_var_name,
  7385. sizeof(http_var_name),
  7386. "HTTP_%s",
  7387. conn->request_info.http_headers[i].name);
  7388. if (truncated) {
  7389. mg_cry(conn,
  7390. "%s: HTTP header variable too long [%s]",
  7391. __func__,
  7392. conn->request_info.http_headers[i].name);
  7393. continue;
  7394. }
  7395. /* Convert variable name into uppercase, and change - to _ */
  7396. for (p = http_var_name; *p != '\0'; p++) {
  7397. if (*p == '-') {
  7398. *p = '_';
  7399. }
  7400. *p = (char)toupper(*(unsigned char *)p);
  7401. }
  7402. addenv(env,
  7403. "%s=%s",
  7404. http_var_name,
  7405. conn->request_info.http_headers[i].value);
  7406. }
  7407. /* Add user-specified variables */
  7408. s = conn->ctx->config[CGI_ENVIRONMENT];
  7409. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  7410. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  7411. }
  7412. env->var[env->varused] = NULL;
  7413. env->buf[env->bufused] = '\0';
  7414. }
  7415. static void
  7416. handle_cgi_request(struct mg_connection *conn, const char *prog)
  7417. {
  7418. char *buf;
  7419. size_t buflen;
  7420. int headers_len, data_len, i, truncated;
  7421. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  7422. const char *status, *status_text, *connection_state;
  7423. char *pbuf, dir[PATH_MAX], *p;
  7424. struct mg_request_info ri;
  7425. struct cgi_environment blk;
  7426. FILE *in = NULL, *out = NULL, *err = NULL;
  7427. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  7428. pid_t pid = (pid_t)-1;
  7429. if (conn == NULL) {
  7430. return;
  7431. }
  7432. buf = NULL;
  7433. buflen = 16384;
  7434. prepare_cgi_environment(conn, prog, &blk);
  7435. /* CGI must be executed in its own directory. 'dir' must point to the
  7436. * directory containing executable program, 'p' must point to the
  7437. * executable program name relative to 'dir'. */
  7438. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  7439. if (truncated) {
  7440. mg_cry(conn, "Error: CGI program \"%s\": Path too long", prog);
  7441. send_http_error(conn, 500, "Error: %s", "CGI path too long");
  7442. goto done;
  7443. }
  7444. if ((p = strrchr(dir, '/')) != NULL) {
  7445. *p++ = '\0';
  7446. } else {
  7447. dir[0] = '.', dir[1] = '\0';
  7448. p = (char *)prog;
  7449. }
  7450. if (pipe(fdin) != 0 || pipe(fdout) != 0 || pipe(fderr) != 0) {
  7451. status = strerror(ERRNO);
  7452. mg_cry(conn,
  7453. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  7454. prog,
  7455. status);
  7456. send_http_error(conn, 500, "Error: Cannot create CGI pipe: %s", status);
  7457. goto done;
  7458. }
  7459. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  7460. if (pid == (pid_t)-1) {
  7461. status = strerror(ERRNO);
  7462. mg_cry(conn,
  7463. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  7464. prog,
  7465. status);
  7466. send_http_error(conn,
  7467. 500,
  7468. "Error: Cannot spawn CGI process [%s]: %s",
  7469. prog,
  7470. status);
  7471. goto done;
  7472. }
  7473. /* Make sure child closes all pipe descriptors. It must dup them to 0,1 */
  7474. set_close_on_exec((SOCKET)fdin[0], conn); /* stdin read */
  7475. set_close_on_exec((SOCKET)fdout[1], conn); /* stdout write */
  7476. set_close_on_exec((SOCKET)fderr[1], conn); /* stderr write */
  7477. set_close_on_exec((SOCKET)fdin[1], conn); /* stdin write */
  7478. set_close_on_exec((SOCKET)fdout[0], conn); /* stdout read */
  7479. set_close_on_exec((SOCKET)fderr[0], conn); /* stderr read */
  7480. /* Parent closes only one side of the pipes.
  7481. * If we don't mark them as closed, close() attempt before
  7482. * return from this function throws an exception on Windows.
  7483. * Windows does not like when closed descriptor is closed again. */
  7484. (void)close(fdin[0]);
  7485. (void)close(fdout[1]);
  7486. (void)close(fderr[1]);
  7487. fdin[0] = fdout[1] = fderr[1] = -1;
  7488. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  7489. status = strerror(ERRNO);
  7490. mg_cry(conn,
  7491. "Error: CGI program \"%s\": Can not open stdin: %s",
  7492. prog,
  7493. status);
  7494. send_http_error(conn,
  7495. 500,
  7496. "Error: CGI can not open fdin\nfopen: %s",
  7497. status);
  7498. goto done;
  7499. }
  7500. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  7501. status = strerror(ERRNO);
  7502. mg_cry(conn,
  7503. "Error: CGI program \"%s\": Can not open stdout: %s",
  7504. prog,
  7505. status);
  7506. send_http_error(conn,
  7507. 500,
  7508. "Error: CGI can not open fdout\nfopen: %s",
  7509. status);
  7510. goto done;
  7511. }
  7512. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  7513. status = strerror(ERRNO);
  7514. mg_cry(conn,
  7515. "Error: CGI program \"%s\": Can not open stderr: %s",
  7516. prog,
  7517. status);
  7518. send_http_error(conn,
  7519. 500,
  7520. "Error: CGI can not open fdout\nfopen: %s",
  7521. status);
  7522. goto done;
  7523. }
  7524. setbuf(in, NULL);
  7525. setbuf(out, NULL);
  7526. setbuf(err, NULL);
  7527. fout.access.fp = out;
  7528. if ((conn->request_info.content_length > 0) || conn->is_chunked) {
  7529. /* This is a POST/PUT request, or another request with body data. */
  7530. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  7531. /* Error sending the body data */
  7532. mg_cry(conn,
  7533. "Error: CGI program \"%s\": Forward body data failed",
  7534. prog);
  7535. goto done;
  7536. }
  7537. }
  7538. /* Close so child gets an EOF. */
  7539. fclose(in);
  7540. in = NULL;
  7541. fdin[1] = -1;
  7542. /* Now read CGI reply into a buffer. We need to set correct
  7543. * status code, thus we need to see all HTTP headers first.
  7544. * Do not send anything back to client, until we buffer in all
  7545. * HTTP headers. */
  7546. data_len = 0;
  7547. buf = (char *)mg_malloc(buflen);
  7548. if (buf == NULL) {
  7549. send_http_error(conn,
  7550. 500,
  7551. "Error: Not enough memory for CGI buffer (%u bytes)",
  7552. (unsigned int)buflen);
  7553. mg_cry(conn,
  7554. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  7555. "bytes)",
  7556. prog,
  7557. (unsigned int)buflen);
  7558. goto done;
  7559. }
  7560. headers_len = read_request(out, conn, buf, (int)buflen, &data_len);
  7561. if (headers_len <= 0) {
  7562. /* Could not parse the CGI response. Check if some error message on
  7563. * stderr. */
  7564. i = pull_all(err, conn, buf, (int)buflen);
  7565. if (i > 0) {
  7566. mg_cry(conn,
  7567. "Error: CGI program \"%s\" sent error "
  7568. "message: [%.*s]",
  7569. prog,
  7570. i,
  7571. buf);
  7572. send_http_error(conn,
  7573. 500,
  7574. "Error: CGI program \"%s\" sent error "
  7575. "message: [%.*s]",
  7576. prog,
  7577. i,
  7578. buf);
  7579. } else {
  7580. mg_cry(conn,
  7581. "Error: CGI program sent malformed or too big "
  7582. "(>%u bytes) HTTP headers: [%.*s]",
  7583. (unsigned)buflen,
  7584. data_len,
  7585. buf);
  7586. send_http_error(conn,
  7587. 500,
  7588. "Error: CGI program sent malformed or too big "
  7589. "(>%u bytes) HTTP headers: [%.*s]",
  7590. (unsigned)buflen,
  7591. data_len,
  7592. buf);
  7593. }
  7594. goto done;
  7595. }
  7596. pbuf = buf;
  7597. buf[headers_len - 1] = '\0';
  7598. parse_http_headers(&pbuf, &ri);
  7599. /* Make up and send the status line */
  7600. status_text = "OK";
  7601. if ((status = get_header(&ri, "Status")) != NULL) {
  7602. conn->status_code = atoi(status);
  7603. status_text = status;
  7604. while (isdigit(*(const unsigned char *)status_text)
  7605. || *status_text == ' ') {
  7606. status_text++;
  7607. }
  7608. } else if (get_header(&ri, "Location") != NULL) {
  7609. conn->status_code = 302;
  7610. } else {
  7611. conn->status_code = 200;
  7612. }
  7613. connection_state = get_header(&ri, "Connection");
  7614. if (!header_has_option(connection_state, "keep-alive")) {
  7615. conn->must_close = 1;
  7616. }
  7617. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  7618. /* Send headers */
  7619. for (i = 0; i < ri.num_headers; i++) {
  7620. mg_printf(conn,
  7621. "%s: %s\r\n",
  7622. ri.http_headers[i].name,
  7623. ri.http_headers[i].value);
  7624. }
  7625. mg_write(conn, "\r\n", 2);
  7626. /* Send chunk of data that may have been read after the headers */
  7627. conn->num_bytes_sent +=
  7628. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  7629. /* Read the rest of CGI output and send to the client */
  7630. send_file_data(conn, &fout, 0, INT64_MAX);
  7631. done:
  7632. mg_free(blk.var);
  7633. mg_free(blk.buf);
  7634. if (pid != (pid_t)-1) {
  7635. kill(pid, SIGKILL);
  7636. #if !defined(_WIN32)
  7637. {
  7638. int st;
  7639. while (waitpid(pid, &st, 0) != -1)
  7640. ; /* clean zombies */
  7641. }
  7642. #endif
  7643. }
  7644. if (fdin[0] != -1) {
  7645. close(fdin[0]);
  7646. }
  7647. if (fdout[1] != -1) {
  7648. close(fdout[1]);
  7649. }
  7650. if (in != NULL) {
  7651. fclose(in);
  7652. } else if (fdin[1] != -1) {
  7653. close(fdin[1]);
  7654. }
  7655. if (out != NULL) {
  7656. fclose(out);
  7657. } else if (fdout[0] != -1) {
  7658. close(fdout[0]);
  7659. }
  7660. if (err != NULL) {
  7661. fclose(err);
  7662. } else if (fderr[0] != -1) {
  7663. close(fderr[0]);
  7664. }
  7665. if (buf != NULL) {
  7666. mg_free(buf);
  7667. }
  7668. }
  7669. #endif /* !NO_CGI */
  7670. #if !defined(NO_FILES)
  7671. static void
  7672. mkcol(struct mg_connection *conn, const char *path)
  7673. {
  7674. int rc, body_len;
  7675. struct de de;
  7676. char date[64];
  7677. time_t curtime = time(NULL);
  7678. if (conn == NULL) {
  7679. return;
  7680. }
  7681. /* TODO (mid): Check the send_http_error situations in this function */
  7682. memset(&de.file, 0, sizeof(de.file));
  7683. if (!mg_stat(conn, path, &de.file)) {
  7684. mg_cry(conn,
  7685. "%s: mg_stat(%s) failed: %s",
  7686. __func__,
  7687. path,
  7688. strerror(ERRNO));
  7689. }
  7690. if (de.file.last_modified) {
  7691. /* TODO (mid): This check does not seem to make any sense ! */
  7692. /* TODO (mid): Add a webdav unit test first, before changing
  7693. * anything here. */
  7694. send_http_error(
  7695. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7696. return;
  7697. }
  7698. body_len = conn->data_len - conn->request_len;
  7699. if (body_len > 0) {
  7700. send_http_error(
  7701. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7702. return;
  7703. }
  7704. rc = mg_mkdir(conn, path, 0755);
  7705. if (rc == 0) {
  7706. conn->status_code = 201;
  7707. gmt_time_string(date, sizeof(date), &curtime);
  7708. mg_printf(conn,
  7709. "HTTP/1.1 %d Created\r\n"
  7710. "Date: %s\r\n",
  7711. conn->status_code,
  7712. date);
  7713. send_static_cache_header(conn);
  7714. send_additional_header(conn);
  7715. mg_printf(conn,
  7716. "Content-Length: 0\r\n"
  7717. "Connection: %s\r\n\r\n",
  7718. suggest_connection_header(conn));
  7719. } else if (rc == -1) {
  7720. if (errno == EEXIST) {
  7721. send_http_error(
  7722. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7723. } else if (errno == EACCES) {
  7724. send_http_error(
  7725. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7726. } else if (errno == ENOENT) {
  7727. send_http_error(
  7728. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7729. } else {
  7730. send_http_error(conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  7731. }
  7732. }
  7733. }
  7734. static void
  7735. put_file(struct mg_connection *conn, const char *path)
  7736. {
  7737. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7738. const char *range;
  7739. int64_t r1, r2;
  7740. int rc;
  7741. char date[64];
  7742. time_t curtime = time(NULL);
  7743. if (conn == NULL) {
  7744. return;
  7745. }
  7746. if (mg_stat(conn, path, &file.stat)) {
  7747. /* File already exists */
  7748. conn->status_code = 200;
  7749. if (file.stat.is_directory) {
  7750. /* This is an already existing directory,
  7751. * so there is nothing to do for the server. */
  7752. rc = 0;
  7753. } else {
  7754. /* File exists and is not a directory. */
  7755. /* Can it be replaced? */
  7756. if (file.access.membuf != NULL) {
  7757. /* This is an "in-memory" file, that can not be replaced */
  7758. send_http_error(
  7759. conn,
  7760. 405,
  7761. "Error: Put not possible\nReplacing %s is not supported",
  7762. path);
  7763. return;
  7764. }
  7765. /* Check if the server may write this file */
  7766. if (access(path, W_OK) == 0) {
  7767. /* Access granted */
  7768. conn->status_code = 200;
  7769. rc = 1;
  7770. } else {
  7771. send_http_error(
  7772. conn,
  7773. 403,
  7774. "Error: Put not possible\nReplacing %s is not allowed",
  7775. path);
  7776. return;
  7777. }
  7778. }
  7779. } else {
  7780. /* File should be created */
  7781. conn->status_code = 201;
  7782. rc = put_dir(conn, path);
  7783. }
  7784. if (rc == 0) {
  7785. /* put_dir returns 0 if path is a directory */
  7786. gmt_time_string(date, sizeof(date), &curtime);
  7787. mg_printf(conn,
  7788. "HTTP/1.1 %d %s\r\n",
  7789. conn->status_code,
  7790. mg_get_response_code_text(NULL, conn->status_code));
  7791. send_no_cache_header(conn);
  7792. send_additional_header(conn);
  7793. mg_printf(conn,
  7794. "Date: %s\r\n"
  7795. "Content-Length: 0\r\n"
  7796. "Connection: %s\r\n\r\n",
  7797. date,
  7798. suggest_connection_header(conn));
  7799. /* Request to create a directory has been fulfilled successfully.
  7800. * No need to put a file. */
  7801. return;
  7802. }
  7803. if (rc == -1) {
  7804. /* put_dir returns -1 if the path is too long */
  7805. send_http_error(conn,
  7806. 414,
  7807. "Error: Path too long\nput_dir(%s): %s",
  7808. path,
  7809. strerror(ERRNO));
  7810. return;
  7811. }
  7812. if (rc == -2) {
  7813. /* put_dir returns -2 if the directory can not be created */
  7814. send_http_error(conn,
  7815. 500,
  7816. "Error: Can not create directory\nput_dir(%s): %s",
  7817. path,
  7818. strerror(ERRNO));
  7819. return;
  7820. }
  7821. /* A file should be created or overwritten. */
  7822. /* Currently CivetWeb does not nead read+write access. */
  7823. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  7824. || file.access.fp == NULL) {
  7825. (void)mg_fclose(&file.access);
  7826. send_http_error(conn,
  7827. 500,
  7828. "Error: Can not create file\nfopen(%s): %s",
  7829. path,
  7830. strerror(ERRNO));
  7831. return;
  7832. }
  7833. fclose_on_exec(&file.access, conn);
  7834. range = mg_get_header(conn, "Content-Range");
  7835. r1 = r2 = 0;
  7836. if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
  7837. conn->status_code = 206; /* Partial content */
  7838. fseeko(file.access.fp, r1, SEEK_SET);
  7839. }
  7840. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  7841. /* forward_body_data failed.
  7842. * The error code has already been sent to the client,
  7843. * and conn->status_code is already set. */
  7844. (void)mg_fclose(&file.access);
  7845. return;
  7846. }
  7847. if (mg_fclose(&file.access) != 0) {
  7848. /* fclose failed. This might have different reasons, but a likely
  7849. * one is "no space on disk", http 507. */
  7850. conn->status_code = 507;
  7851. }
  7852. gmt_time_string(date, sizeof(date), &curtime);
  7853. mg_printf(conn,
  7854. "HTTP/1.1 %d %s\r\n",
  7855. conn->status_code,
  7856. mg_get_response_code_text(NULL, conn->status_code));
  7857. send_no_cache_header(conn);
  7858. send_additional_header(conn);
  7859. mg_printf(conn,
  7860. "Date: %s\r\n"
  7861. "Content-Length: 0\r\n"
  7862. "Connection: %s\r\n\r\n",
  7863. date,
  7864. suggest_connection_header(conn));
  7865. }
  7866. static void
  7867. delete_file(struct mg_connection *conn, const char *path)
  7868. {
  7869. struct de de;
  7870. memset(&de.file, 0, sizeof(de.file));
  7871. if (!mg_stat(conn, path, &de.file)) {
  7872. /* mg_stat returns 0 if the file does not exist */
  7873. send_http_error(conn,
  7874. 404,
  7875. "Error: Cannot delete file\nFile %s not found",
  7876. path);
  7877. return;
  7878. }
  7879. #if 0 /* Ignore if a file in memory is inside a folder */
  7880. if (de.access.membuf != NULL) {
  7881. /* the file is cached in memory */
  7882. send_http_error(
  7883. conn,
  7884. 405,
  7885. "Error: Delete not possible\nDeleting %s is not supported",
  7886. path);
  7887. return;
  7888. }
  7889. #endif
  7890. if (de.file.is_directory) {
  7891. if (remove_directory(conn, path)) {
  7892. /* Delete is successful: Return 204 without content. */
  7893. send_http_error(conn, 204, "%s", "");
  7894. } else {
  7895. /* Delete is not successful: Return 500 (Server error). */
  7896. send_http_error(conn, 500, "Error: Could not delete %s", path);
  7897. }
  7898. return;
  7899. }
  7900. /* This is an existing file (not a directory).
  7901. * Check if write permission is granted. */
  7902. if (access(path, W_OK) != 0) {
  7903. /* File is read only */
  7904. send_http_error(
  7905. conn,
  7906. 403,
  7907. "Error: Delete not possible\nDeleting %s is not allowed",
  7908. path);
  7909. return;
  7910. }
  7911. /* Try to delete it. */
  7912. if (mg_remove(conn, path) == 0) {
  7913. /* Delete was successful: Return 204 without content. */
  7914. send_http_error(conn, 204, "%s", "");
  7915. } else {
  7916. /* Delete not successful (file locked). */
  7917. send_http_error(conn,
  7918. 423,
  7919. "Error: Cannot delete file\nremove(%s): %s",
  7920. path,
  7921. strerror(ERRNO));
  7922. }
  7923. }
  7924. #endif /* !NO_FILES */
  7925. static void
  7926. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  7927. static void
  7928. do_ssi_include(struct mg_connection *conn,
  7929. const char *ssi,
  7930. char *tag,
  7931. int include_level)
  7932. {
  7933. char file_name[MG_BUF_LEN], path[512], *p;
  7934. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7935. size_t len;
  7936. int truncated = 0;
  7937. if (conn == NULL) {
  7938. return;
  7939. }
  7940. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  7941. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  7942. * always < MG_BUF_LEN. */
  7943. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  7944. /* File name is relative to the webserver root */
  7945. file_name[511] = 0;
  7946. (void)mg_snprintf(conn,
  7947. &truncated,
  7948. path,
  7949. sizeof(path),
  7950. "%s/%s",
  7951. conn->ctx->config[DOCUMENT_ROOT],
  7952. file_name);
  7953. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  7954. /* File name is relative to the webserver working directory
  7955. * or it is absolute system path */
  7956. file_name[511] = 0;
  7957. (void)
  7958. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  7959. } else if (sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1
  7960. || sscanf(tag, " \"%511[^\"]\"", file_name) == 1) {
  7961. /* File name is relative to the currect document */
  7962. file_name[511] = 0;
  7963. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  7964. if (!truncated) {
  7965. if ((p = strrchr(path, '/')) != NULL) {
  7966. p[1] = '\0';
  7967. }
  7968. len = strlen(path);
  7969. (void)mg_snprintf(conn,
  7970. &truncated,
  7971. path + len,
  7972. sizeof(path) - len,
  7973. "%s",
  7974. file_name);
  7975. }
  7976. } else {
  7977. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  7978. return;
  7979. }
  7980. if (truncated) {
  7981. mg_cry(conn, "SSI #include path length overflow: [%s]", tag);
  7982. return;
  7983. }
  7984. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  7985. mg_cry(conn,
  7986. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  7987. tag,
  7988. path,
  7989. strerror(ERRNO));
  7990. } else {
  7991. fclose_on_exec(&file.access, conn);
  7992. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  7993. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  7994. path) > 0) {
  7995. send_ssi_file(conn, path, &file, include_level + 1);
  7996. } else {
  7997. send_file_data(conn, &file, 0, INT64_MAX);
  7998. }
  7999. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  8000. }
  8001. }
  8002. #if !defined(NO_POPEN)
  8003. static void
  8004. do_ssi_exec(struct mg_connection *conn, char *tag)
  8005. {
  8006. char cmd[1024] = "";
  8007. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8008. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  8009. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  8010. } else {
  8011. cmd[1023] = 0;
  8012. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  8013. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  8014. } else {
  8015. send_file_data(conn, &file, 0, INT64_MAX);
  8016. pclose(file.access.fp);
  8017. }
  8018. }
  8019. }
  8020. #endif /* !NO_POPEN */
  8021. static int
  8022. mg_fgetc(struct mg_file *filep, int offset)
  8023. {
  8024. if (filep == NULL) {
  8025. return EOF;
  8026. }
  8027. if (filep->access.membuf != NULL && offset >= 0
  8028. && ((unsigned int)(offset)) < filep->stat.size) {
  8029. return ((const unsigned char *)filep->access.membuf)[offset];
  8030. } else if (filep->access.fp != NULL) {
  8031. return fgetc(filep->access.fp);
  8032. } else {
  8033. return EOF;
  8034. }
  8035. }
  8036. static void
  8037. send_ssi_file(struct mg_connection *conn,
  8038. const char *path,
  8039. struct mg_file *filep,
  8040. int include_level)
  8041. {
  8042. char buf[MG_BUF_LEN];
  8043. int ch, offset, len, in_ssi_tag;
  8044. if (include_level > 10) {
  8045. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  8046. return;
  8047. }
  8048. in_ssi_tag = len = offset = 0;
  8049. while ((ch = mg_fgetc(filep, offset)) != EOF) {
  8050. if (in_ssi_tag && ch == '>') {
  8051. in_ssi_tag = 0;
  8052. buf[len++] = (char)ch;
  8053. buf[len] = '\0';
  8054. /* assert(len <= (int) sizeof(buf)); */
  8055. if (len > (int)sizeof(buf)) {
  8056. break;
  8057. }
  8058. if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
  8059. /* Not an SSI tag, pass it */
  8060. (void)mg_write(conn, buf, (size_t)len);
  8061. } else {
  8062. if (!memcmp(buf + 5, "include", 7)) {
  8063. do_ssi_include(conn, path, buf + 12, include_level);
  8064. #if !defined(NO_POPEN)
  8065. } else if (!memcmp(buf + 5, "exec", 4)) {
  8066. do_ssi_exec(conn, buf + 9);
  8067. #endif /* !NO_POPEN */
  8068. } else {
  8069. mg_cry(conn,
  8070. "%s: unknown SSI "
  8071. "command: \"%s\"",
  8072. path,
  8073. buf);
  8074. }
  8075. }
  8076. len = 0;
  8077. } else if (in_ssi_tag) {
  8078. if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
  8079. /* Not an SSI tag */
  8080. in_ssi_tag = 0;
  8081. } else if (len == (int)sizeof(buf) - 2) {
  8082. mg_cry(conn, "%s: SSI tag is too large", path);
  8083. len = 0;
  8084. }
  8085. buf[len++] = (char)(ch & 0xff);
  8086. } else if (ch == '<') {
  8087. in_ssi_tag = 1;
  8088. if (len > 0) {
  8089. mg_write(conn, buf, (size_t)len);
  8090. }
  8091. len = 0;
  8092. buf[len++] = (char)(ch & 0xff);
  8093. } else {
  8094. buf[len++] = (char)(ch & 0xff);
  8095. if (len == (int)sizeof(buf)) {
  8096. mg_write(conn, buf, (size_t)len);
  8097. len = 0;
  8098. }
  8099. }
  8100. }
  8101. /* Send the rest of buffered data */
  8102. if (len > 0) {
  8103. mg_write(conn, buf, (size_t)len);
  8104. }
  8105. }
  8106. static void
  8107. handle_ssi_file_request(struct mg_connection *conn,
  8108. const char *path,
  8109. struct mg_file *filep)
  8110. {
  8111. char date[64];
  8112. time_t curtime = time(NULL);
  8113. const char *cors1, *cors2, *cors3;
  8114. if (conn == NULL || path == NULL || filep == NULL) {
  8115. return;
  8116. }
  8117. if (mg_get_header(conn, "Origin")) {
  8118. /* Cross-origin resource sharing (CORS). */
  8119. cors1 = "Access-Control-Allow-Origin: ";
  8120. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  8121. cors3 = "\r\n";
  8122. } else {
  8123. cors1 = cors2 = cors3 = "";
  8124. }
  8125. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8126. /* File exists (precondition for calling this function),
  8127. * but can not be opened by the server. */
  8128. send_http_error(conn,
  8129. 500,
  8130. "Error: Cannot read file\nfopen(%s): %s",
  8131. path,
  8132. strerror(ERRNO));
  8133. } else {
  8134. conn->must_close = 1;
  8135. gmt_time_string(date, sizeof(date), &curtime);
  8136. fclose_on_exec(&filep->access, conn);
  8137. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  8138. send_no_cache_header(conn);
  8139. send_additional_header(conn);
  8140. mg_printf(conn,
  8141. "%s%s%s"
  8142. "Date: %s\r\n"
  8143. "Content-Type: text/html\r\n"
  8144. "Connection: %s\r\n\r\n",
  8145. cors1,
  8146. cors2,
  8147. cors3,
  8148. date,
  8149. suggest_connection_header(conn));
  8150. send_ssi_file(conn, path, filep, 0);
  8151. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  8152. }
  8153. }
  8154. #if !defined(NO_FILES)
  8155. static void
  8156. send_options(struct mg_connection *conn)
  8157. {
  8158. char date[64];
  8159. time_t curtime = time(NULL);
  8160. if (!conn) {
  8161. return;
  8162. }
  8163. conn->status_code = 200;
  8164. conn->must_close = 1;
  8165. gmt_time_string(date, sizeof(date), &curtime);
  8166. /* We do not set a "Cache-Control" header here, but leave the default.
  8167. * Since browsers do not send an OPTIONS request, we can not test the
  8168. * effect anyway. */
  8169. mg_printf(conn,
  8170. "HTTP/1.1 200 OK\r\n"
  8171. "Date: %s\r\n"
  8172. "Connection: %s\r\n"
  8173. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  8174. "PROPFIND, MKCOL\r\n"
  8175. "DAV: 1\r\n",
  8176. date,
  8177. suggest_connection_header(conn));
  8178. send_additional_header(conn);
  8179. mg_printf(conn, "\r\n");
  8180. }
  8181. /* Writes PROPFIND properties for a collection element */
  8182. static void
  8183. print_props(struct mg_connection *conn,
  8184. const char *uri,
  8185. struct mg_file_stat *filep)
  8186. {
  8187. char mtime[64];
  8188. if (conn == NULL || uri == NULL || filep == NULL) {
  8189. return;
  8190. }
  8191. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  8192. conn->num_bytes_sent +=
  8193. mg_printf(conn,
  8194. "<d:response>"
  8195. "<d:href>%s</d:href>"
  8196. "<d:propstat>"
  8197. "<d:prop>"
  8198. "<d:resourcetype>%s</d:resourcetype>"
  8199. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  8200. "<d:getlastmodified>%s</d:getlastmodified>"
  8201. "</d:prop>"
  8202. "<d:status>HTTP/1.1 200 OK</d:status>"
  8203. "</d:propstat>"
  8204. "</d:response>\n",
  8205. uri,
  8206. filep->is_directory ? "<d:collection/>" : "",
  8207. filep->size,
  8208. mtime);
  8209. }
  8210. static void
  8211. print_dav_dir_entry(struct de *de, void *data)
  8212. {
  8213. char href[PATH_MAX];
  8214. char href_encoded[PATH_MAX * 3 /* worst case */];
  8215. int truncated;
  8216. struct mg_connection *conn = (struct mg_connection *)data;
  8217. if (!de || !conn) {
  8218. return;
  8219. }
  8220. mg_snprintf(conn,
  8221. &truncated,
  8222. href,
  8223. sizeof(href),
  8224. "%s%s",
  8225. conn->request_info.local_uri,
  8226. de->file_name);
  8227. if (!truncated) {
  8228. mg_url_encode(href, href_encoded, PATH_MAX * 3);
  8229. print_props(conn, href_encoded, &de->file);
  8230. }
  8231. }
  8232. static void
  8233. handle_propfind(struct mg_connection *conn,
  8234. const char *path,
  8235. struct mg_file_stat *filep)
  8236. {
  8237. const char *depth = mg_get_header(conn, "Depth");
  8238. char date[64];
  8239. time_t curtime = time(NULL);
  8240. gmt_time_string(date, sizeof(date), &curtime);
  8241. if (!conn || !path || !filep || !conn->ctx) {
  8242. return;
  8243. }
  8244. conn->must_close = 1;
  8245. conn->status_code = 207;
  8246. mg_printf(conn,
  8247. "HTTP/1.1 207 Multi-Status\r\n"
  8248. "Date: %s\r\n",
  8249. date);
  8250. send_static_cache_header(conn);
  8251. send_additional_header(conn);
  8252. mg_printf(conn,
  8253. "Connection: %s\r\n"
  8254. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  8255. suggest_connection_header(conn));
  8256. conn->num_bytes_sent +=
  8257. mg_printf(conn,
  8258. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  8259. "<d:multistatus xmlns:d='DAV:'>\n");
  8260. /* Print properties for the requested resource itself */
  8261. print_props(conn, conn->request_info.local_uri, filep);
  8262. /* If it is a directory, print directory entries too if Depth is not 0 */
  8263. if (filep && filep->is_directory
  8264. && !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")
  8265. && (depth == NULL || strcmp(depth, "0") != 0)) {
  8266. scan_directory(conn, path, conn, &print_dav_dir_entry);
  8267. }
  8268. conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");
  8269. }
  8270. #endif
  8271. void
  8272. mg_lock_connection(struct mg_connection *conn)
  8273. {
  8274. if (conn) {
  8275. (void)pthread_mutex_lock(&conn->mutex);
  8276. }
  8277. }
  8278. void
  8279. mg_unlock_connection(struct mg_connection *conn)
  8280. {
  8281. if (conn) {
  8282. (void)pthread_mutex_unlock(&conn->mutex);
  8283. }
  8284. }
  8285. void
  8286. mg_lock_context(struct mg_context *ctx)
  8287. {
  8288. if (ctx) {
  8289. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  8290. }
  8291. }
  8292. void
  8293. mg_unlock_context(struct mg_context *ctx)
  8294. {
  8295. if (ctx) {
  8296. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  8297. }
  8298. }
  8299. #if defined(USE_TIMERS)
  8300. #include "timer.inl"
  8301. #endif /* USE_TIMERS */
  8302. #ifdef USE_LUA
  8303. #include "mod_lua.inl"
  8304. #endif /* USE_LUA */
  8305. #ifdef USE_DUKTAPE
  8306. #include "mod_duktape.inl"
  8307. #endif /* USE_DUKTAPE */
  8308. #if defined(USE_WEBSOCKET)
  8309. #if !defined(NO_SSL_DL)
  8310. #define SHA_API static
  8311. #include "sha1.inl"
  8312. #endif
  8313. static int
  8314. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  8315. {
  8316. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  8317. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  8318. SHA_CTX sha_ctx;
  8319. int truncated;
  8320. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  8321. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  8322. if (truncated) {
  8323. conn->must_close = 1;
  8324. return 0;
  8325. }
  8326. SHA1_Init(&sha_ctx);
  8327. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  8328. SHA1_Final((unsigned char *)sha, &sha_ctx);
  8329. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  8330. mg_printf(conn,
  8331. "HTTP/1.1 101 Switching Protocols\r\n"
  8332. "Upgrade: websocket\r\n"
  8333. "Connection: Upgrade\r\n"
  8334. "Sec-WebSocket-Accept: %s\r\n",
  8335. b64_sha);
  8336. if (conn->request_info.acceptedWebSocketSubprotocol) {
  8337. mg_printf(conn,
  8338. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  8339. conn->request_info.acceptedWebSocketSubprotocol);
  8340. } else {
  8341. mg_printf(conn, "%s", "\r\n");
  8342. }
  8343. return 1;
  8344. }
  8345. static void
  8346. read_websocket(struct mg_connection *conn,
  8347. mg_websocket_data_handler ws_data_handler,
  8348. void *callback_data)
  8349. {
  8350. /* Pointer to the beginning of the portion of the incoming websocket
  8351. * message queue.
  8352. * The original websocket upgrade request is never removed, so the queue
  8353. * begins after it. */
  8354. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  8355. int n, error, exit_by_callback;
  8356. /* body_len is the length of the entire queue in bytes
  8357. * len is the length of the current message
  8358. * data_len is the length of the current message's data payload
  8359. * header_len is the length of the current message's header */
  8360. size_t i, len, mask_len = 0, data_len = 0, header_len, body_len;
  8361. /* "The masking key is a 32-bit value chosen at random by the client."
  8362. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  8363. */
  8364. unsigned char mask[4];
  8365. /* data points to the place where the message is stored when passed to
  8366. * the
  8367. * websocket_data callback. This is either mem on the stack, or a
  8368. * dynamically allocated buffer if it is too large. */
  8369. unsigned char mem[4096];
  8370. unsigned char *data = mem;
  8371. unsigned char mop; /* mask flag and opcode */
  8372. double timeout = -1.0;
  8373. if (conn->ctx->config[WEBSOCKET_TIMEOUT]) {
  8374. timeout = atoi(conn->ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  8375. }
  8376. if ((timeout <= 0.0) && (conn->ctx->config[REQUEST_TIMEOUT])) {
  8377. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  8378. }
  8379. mg_set_thread_name("wsock");
  8380. /* Loop continuously, reading messages from the socket, invoking the
  8381. * callback, and waiting repeatedly until an error occurs. */
  8382. while (!conn->ctx->stop_flag) {
  8383. header_len = 0;
  8384. assert(conn->data_len >= conn->request_len);
  8385. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  8386. len = buf[1] & 127;
  8387. mask_len = (buf[1] & 128) ? 4 : 0;
  8388. if ((len < 126) && (body_len >= mask_len)) {
  8389. data_len = len;
  8390. header_len = 2 + mask_len;
  8391. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  8392. header_len = 4 + mask_len;
  8393. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  8394. } else if (body_len >= (10 + mask_len)) {
  8395. header_len = 10 + mask_len;
  8396. data_len = (((uint64_t)ntohl(*(uint32_t *)(void *)&buf[2]))
  8397. << 32) + ntohl(*(uint32_t *)(void *)&buf[6]);
  8398. }
  8399. }
  8400. if (header_len > 0 && body_len >= header_len) {
  8401. /* Allocate space to hold websocket payload */
  8402. data = mem;
  8403. if (data_len > sizeof(mem)) {
  8404. data = (unsigned char *)mg_malloc(data_len);
  8405. if (data == NULL) {
  8406. /* Allocation failed, exit the loop and then close the
  8407. * connection */
  8408. mg_cry(conn, "websocket out of memory; closing connection");
  8409. break;
  8410. }
  8411. }
  8412. /* Copy the mask before we shift the queue and destroy it */
  8413. if (mask_len > 0) {
  8414. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  8415. } else {
  8416. memset(mask, 0, sizeof(mask));
  8417. }
  8418. /* Read frame payload from the first message in the queue into
  8419. * data and advance the queue by moving the memory in place. */
  8420. assert(body_len >= header_len);
  8421. if (data_len + header_len > body_len) {
  8422. mop = buf[0]; /* current mask and opcode */
  8423. /* Overflow case */
  8424. len = body_len - header_len;
  8425. memcpy(data, buf + header_len, len);
  8426. error = 0;
  8427. while (len < data_len) {
  8428. n = pull_inner(NULL,
  8429. conn,
  8430. (char *)(data + len),
  8431. (int)(data_len - len),
  8432. timeout);
  8433. if (n <= -2) {
  8434. error = 1;
  8435. break;
  8436. } else if (n > 0) {
  8437. len += (size_t)n;
  8438. } else {
  8439. /* Timeout: should retry */
  8440. /* TODO: retry condition */
  8441. }
  8442. }
  8443. if (error) {
  8444. mg_cry(conn, "Websocket pull failed; closing connection");
  8445. break;
  8446. }
  8447. conn->data_len = conn->request_len;
  8448. } else {
  8449. mop = buf[0]; /* current mask and opcode, overwritten by
  8450. * memmove() */
  8451. /* Length of the message being read at the front of the
  8452. * queue */
  8453. len = data_len + header_len;
  8454. /* Copy the data payload into the data pointer for the
  8455. * callback */
  8456. memcpy(data, buf + header_len, data_len);
  8457. /* Move the queue forward len bytes */
  8458. memmove(buf, buf + len, body_len - len);
  8459. /* Mark the queue as advanced */
  8460. conn->data_len -= (int)len;
  8461. }
  8462. /* Apply mask if necessary */
  8463. if (mask_len > 0) {
  8464. for (i = 0; i < data_len; ++i) {
  8465. data[i] ^= mask[i & 3];
  8466. }
  8467. }
  8468. /* Exit the loop if callback signals to exit (server side),
  8469. * or "connection close" opcode received (client side). */
  8470. exit_by_callback = 0;
  8471. if ((ws_data_handler != NULL)
  8472. && !ws_data_handler(
  8473. conn, mop, (char *)data, data_len, callback_data)) {
  8474. exit_by_callback = 1;
  8475. }
  8476. if (data != mem) {
  8477. mg_free(data);
  8478. }
  8479. if (exit_by_callback
  8480. || ((mop & 0xf) == WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  8481. /* Opcode == 8, connection close */
  8482. break;
  8483. }
  8484. /* Not breaking the loop, process next websocket frame. */
  8485. } else {
  8486. /* Read from the socket into the next available location in the
  8487. * message queue. */
  8488. n = pull_inner(NULL,
  8489. conn,
  8490. conn->buf + conn->data_len,
  8491. conn->buf_size - conn->data_len,
  8492. timeout);
  8493. if (n <= -2) {
  8494. /* Error, no bytes read */
  8495. break;
  8496. }
  8497. if (n > 0) {
  8498. conn->data_len += n;
  8499. } else {
  8500. /* Timeout: should retry */
  8501. /* TODO: get timeout def */
  8502. }
  8503. }
  8504. }
  8505. mg_set_thread_name("worker");
  8506. }
  8507. static int
  8508. mg_websocket_write_exec(struct mg_connection *conn,
  8509. int opcode,
  8510. const char *data,
  8511. size_t dataLen,
  8512. uint32_t masking_key)
  8513. {
  8514. unsigned char header[14];
  8515. size_t headerLen = 1;
  8516. int retval = -1;
  8517. #if defined(__GNUC__) || defined(__MINGW32__)
  8518. /* Disable spurious conversion warning for GCC */
  8519. #pragma GCC diagnostic push
  8520. #pragma GCC diagnostic ignored "-Wconversion"
  8521. #endif
  8522. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  8523. #if defined(__GNUC__) || defined(__MINGW32__)
  8524. #pragma GCC diagnostic pop
  8525. #endif
  8526. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  8527. if (dataLen < 126) {
  8528. /* inline 7-bit length field */
  8529. header[1] = (unsigned char)dataLen;
  8530. headerLen = 2;
  8531. } else if (dataLen <= 0xFFFF) {
  8532. /* 16-bit length field */
  8533. uint16_t len = htons((uint16_t)dataLen);
  8534. header[1] = 126;
  8535. memcpy(header + 2, &len, 2);
  8536. headerLen = 4;
  8537. } else {
  8538. /* 64-bit length field */
  8539. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  8540. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  8541. header[1] = 127;
  8542. memcpy(header + 2, &len1, 4);
  8543. memcpy(header + 6, &len2, 4);
  8544. headerLen = 10;
  8545. }
  8546. if (masking_key) {
  8547. /* add mask */
  8548. header[1] |= 0x80;
  8549. memcpy(header + headerLen, &masking_key, 4);
  8550. headerLen += 4;
  8551. }
  8552. /* Note that POSIX/Winsock's send() is threadsafe
  8553. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  8554. * but mongoose's mg_printf/mg_write is not (because of the loop in
  8555. * push(), although that is only a problem if the packet is large or
  8556. * outgoing buffer is full). */
  8557. (void)mg_lock_connection(conn);
  8558. retval = mg_write(conn, header, headerLen);
  8559. if (dataLen > 0) {
  8560. retval = mg_write(conn, data, dataLen);
  8561. }
  8562. mg_unlock_connection(conn);
  8563. return retval;
  8564. }
  8565. int
  8566. mg_websocket_write(struct mg_connection *conn,
  8567. int opcode,
  8568. const char *data,
  8569. size_t dataLen)
  8570. {
  8571. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  8572. }
  8573. static void
  8574. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  8575. {
  8576. size_t i = 0;
  8577. i = 0;
  8578. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  8579. /* Convert in 32 bit words, if data is 4 byte aligned */
  8580. while (i < (in_len - 3)) {
  8581. *(uint32_t *)(void *)(out + i) =
  8582. *(uint32_t *)(void *)(in + i) ^ masking_key;
  8583. i += 4;
  8584. }
  8585. }
  8586. if (i != in_len) {
  8587. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  8588. while (i < in_len) {
  8589. *(uint8_t *)(void *)(out + i) =
  8590. *(uint8_t *)(void *)(in + i)
  8591. ^ *(((uint8_t *)&masking_key) + (i % 4));
  8592. i++;
  8593. }
  8594. }
  8595. }
  8596. int
  8597. mg_websocket_client_write(struct mg_connection *conn,
  8598. int opcode,
  8599. const char *data,
  8600. size_t dataLen)
  8601. {
  8602. int retval = -1;
  8603. char *masked_data = (char *)mg_malloc(((dataLen + 7) / 4) * 4);
  8604. uint32_t masking_key = (uint32_t)get_random();
  8605. if (masked_data == NULL) {
  8606. /* Return -1 in an error case */
  8607. mg_cry(conn,
  8608. "Cannot allocate buffer for masked websocket response: "
  8609. "Out of memory");
  8610. return -1;
  8611. }
  8612. mask_data(data, dataLen, masking_key, masked_data);
  8613. retval = mg_websocket_write_exec(
  8614. conn, opcode, masked_data, dataLen, masking_key);
  8615. mg_free(masked_data);
  8616. return retval;
  8617. }
  8618. static void
  8619. handle_websocket_request(struct mg_connection *conn,
  8620. const char *path,
  8621. int is_callback_resource,
  8622. struct mg_websocket_subprotocols *subprotocols,
  8623. mg_websocket_connect_handler ws_connect_handler,
  8624. mg_websocket_ready_handler ws_ready_handler,
  8625. mg_websocket_data_handler ws_data_handler,
  8626. mg_websocket_close_handler ws_close_handler,
  8627. void *cbData)
  8628. {
  8629. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  8630. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  8631. int lua_websock = 0;
  8632. #if !defined(USE_LUA)
  8633. (void)path;
  8634. #endif
  8635. /* Step 1: Check websocket protocol version. */
  8636. /* Step 1.1: Check Sec-WebSocket-Key. */
  8637. if (!websock_key) {
  8638. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  8639. * requires a Sec-WebSocket-Key header.
  8640. */
  8641. /* It could be the hixie draft version
  8642. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  8643. */
  8644. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  8645. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  8646. char key3[8];
  8647. if ((key1 != NULL) && (key2 != NULL)) {
  8648. /* This version uses 8 byte body data in a GET request */
  8649. conn->content_len = 8;
  8650. if (8 == mg_read(conn, key3, 8)) {
  8651. /* This is the hixie version */
  8652. send_http_error(conn,
  8653. 426,
  8654. "%s",
  8655. "Protocol upgrade to RFC 6455 required");
  8656. return;
  8657. }
  8658. }
  8659. /* This is an unknown version */
  8660. send_http_error(conn, 400, "%s", "Malformed websocket request");
  8661. return;
  8662. }
  8663. /* Step 1.2: Check websocket protocol version. */
  8664. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  8665. if (version == NULL || strcmp(version, "13") != 0) {
  8666. /* Reject wrong versions */
  8667. send_http_error(conn, 426, "%s", "Protocol upgrade required");
  8668. return;
  8669. }
  8670. /* Step 1.3: Could check for "Host", but we do not really nead this
  8671. * value for anything, so just ignore it. */
  8672. /* Step 2: If a callback is responsible, call it. */
  8673. if (is_callback_resource) {
  8674. /* Step 2.1 check and select subprotocol */
  8675. const char *protocol = mg_get_header(conn, "Sec-WebSocket-Protocol");
  8676. if (protocol && subprotocols) {
  8677. int idx;
  8678. unsigned long len;
  8679. const char *sep, *curSubProtocol,
  8680. *acceptedWebSocketSubprotocol = NULL;
  8681. /* look for matching subprotocol */
  8682. do {
  8683. sep = strchr(protocol, ',');
  8684. curSubProtocol = protocol;
  8685. len = sep ? (unsigned long)(sep - protocol)
  8686. : (unsigned long)strlen(protocol);
  8687. while (sep && isspace(*++sep)) {
  8688. ; /* ignore leading whitespaces */
  8689. }
  8690. protocol = sep;
  8691. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  8692. if ((strlen(subprotocols->subprotocols[idx]) == len)
  8693. && (strncmp(curSubProtocol,
  8694. subprotocols->subprotocols[idx],
  8695. len) == 0)) {
  8696. acceptedWebSocketSubprotocol =
  8697. subprotocols->subprotocols[idx];
  8698. break;
  8699. }
  8700. }
  8701. } while (sep && !acceptedWebSocketSubprotocol);
  8702. conn->request_info.acceptedWebSocketSubprotocol =
  8703. acceptedWebSocketSubprotocol;
  8704. } else if (protocol) {
  8705. /* keep legacy behavior */
  8706. /* The protocol is a comma seperated list of names. */
  8707. /* The server must only return one value from this list. */
  8708. /* First check if it is a list or just a single value. */
  8709. const char *sep = strrchr(protocol, ',');
  8710. if (sep == NULL) {
  8711. /* Just a single protocol -> accept it. */
  8712. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  8713. } else {
  8714. /* Multiple protocols -> accept the last one. */
  8715. /* This is just a quick fix if the client offers multiple
  8716. * protocols. The handler should have a list of accepted
  8717. * protocols on his own
  8718. * and use it to select one protocol among those the client has
  8719. * offered.
  8720. */
  8721. while (isspace(*++sep)) {
  8722. ; /* ignore leading whitespaces */
  8723. }
  8724. conn->request_info.acceptedWebSocketSubprotocol = sep;
  8725. }
  8726. }
  8727. if (ws_connect_handler != NULL
  8728. && ws_connect_handler(conn, cbData) != 0) {
  8729. /* C callback has returned non-zero, do not proceed with
  8730. * handshake.
  8731. */
  8732. /* Note that C callbacks are no longer called when Lua is
  8733. * responsible, so C can no longer filter callbacks for Lua. */
  8734. return;
  8735. }
  8736. }
  8737. #if defined(USE_LUA)
  8738. /* Step 3: No callback. Check if Lua is responsible. */
  8739. else {
  8740. /* Step 3.1: Check if Lua is responsible. */
  8741. if (conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  8742. lua_websock =
  8743. match_prefix(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  8744. strlen(
  8745. conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  8746. path);
  8747. }
  8748. if (lua_websock) {
  8749. /* Step 3.2: Lua is responsible: call it. */
  8750. conn->lua_websocket_state = lua_websocket_new(path, conn);
  8751. if (!conn->lua_websocket_state) {
  8752. /* Lua rejected the new client */
  8753. return;
  8754. }
  8755. }
  8756. }
  8757. #endif
  8758. /* Step 4: Check if there is a responsible websocket handler. */
  8759. if (!is_callback_resource && !lua_websock) {
  8760. /* There is no callback, and Lua is not responsible either. */
  8761. /* Reply with a 404 Not Found. We are still at a standard
  8762. * HTTP request here, before the websocket handshake, so
  8763. * we can still send standard HTTP error replies. */
  8764. send_http_error(conn, 404, "%s", "Not found");
  8765. return;
  8766. }
  8767. /* Step 5: The websocket connection has been accepted */
  8768. if (!send_websocket_handshake(conn, websock_key)) {
  8769. send_http_error(conn, 500, "%s", "Websocket handshake failed");
  8770. return;
  8771. }
  8772. /* Step 6: Call the ready handler */
  8773. if (is_callback_resource) {
  8774. if (ws_ready_handler != NULL) {
  8775. ws_ready_handler(conn, cbData);
  8776. }
  8777. #if defined(USE_LUA)
  8778. } else if (lua_websock) {
  8779. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  8780. /* the ready handler returned false */
  8781. return;
  8782. }
  8783. #endif
  8784. }
  8785. /* Step 7: Enter the read loop */
  8786. if (is_callback_resource) {
  8787. read_websocket(conn, ws_data_handler, cbData);
  8788. #if defined(USE_LUA)
  8789. } else if (lua_websock) {
  8790. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  8791. #endif
  8792. }
  8793. /* Step 8: Call the close handler */
  8794. if (ws_close_handler) {
  8795. ws_close_handler(conn, cbData);
  8796. }
  8797. }
  8798. static int
  8799. is_websocket_protocol(const struct mg_connection *conn)
  8800. {
  8801. const char *upgrade, *connection;
  8802. /* A websocket protocoll has the following HTTP headers:
  8803. *
  8804. * Connection: Upgrade
  8805. * Upgrade: Websocket
  8806. */
  8807. upgrade = mg_get_header(conn, "Upgrade");
  8808. if (upgrade == NULL) {
  8809. return 0; /* fail early, don't waste time checking other header
  8810. * fields
  8811. */
  8812. }
  8813. if (!mg_strcasestr(upgrade, "websocket")) {
  8814. return 0;
  8815. }
  8816. connection = mg_get_header(conn, "Connection");
  8817. if (connection == NULL) {
  8818. return 0;
  8819. }
  8820. if (!mg_strcasestr(connection, "upgrade")) {
  8821. return 0;
  8822. }
  8823. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  8824. * "Sec-WebSocket-Version" are also required.
  8825. * Don't check them here, since even an unsupported websocket protocol
  8826. * request still IS a websocket request (in contrast to a standard HTTP
  8827. * request). It will fail later in handle_websocket_request.
  8828. */
  8829. return 1;
  8830. }
  8831. #endif /* !USE_WEBSOCKET */
  8832. static int
  8833. isbyte(int n)
  8834. {
  8835. return n >= 0 && n <= 255;
  8836. }
  8837. static int
  8838. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  8839. {
  8840. int n, a, b, c, d, slash = 32, len = 0;
  8841. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5
  8842. || sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) && isbyte(a)
  8843. && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0
  8844. && slash < 33) {
  8845. len = n;
  8846. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  8847. | (uint32_t)d;
  8848. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  8849. }
  8850. return len;
  8851. }
  8852. static int
  8853. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  8854. {
  8855. int throttle = 0;
  8856. struct vec vec, val;
  8857. uint32_t net, mask;
  8858. char mult;
  8859. double v;
  8860. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  8861. mult = ',';
  8862. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  8863. || (v < 0) || ((lowercase(&mult) != 'k')
  8864. && (lowercase(&mult) != 'm') && (mult != ','))) {
  8865. continue;
  8866. }
  8867. v *= (lowercase(&mult) == 'k')
  8868. ? 1024
  8869. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  8870. if (vec.len == 1 && vec.ptr[0] == '*') {
  8871. throttle = (int)v;
  8872. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  8873. if ((remote_ip & mask) == net) {
  8874. throttle = (int)v;
  8875. }
  8876. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  8877. throttle = (int)v;
  8878. }
  8879. }
  8880. return throttle;
  8881. }
  8882. static uint32_t
  8883. get_remote_ip(const struct mg_connection *conn)
  8884. {
  8885. if (!conn) {
  8886. return 0;
  8887. }
  8888. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  8889. }
  8890. /* The mg_upload function is superseeded by mg_handle_form_request. */
  8891. #include "handle_form.inl"
  8892. #if defined(MG_LEGACY_INTERFACE)
  8893. /* Implement the deprecated mg_upload function by calling the new
  8894. * mg_handle_form_request function. While mg_upload could only handle
  8895. * HTML forms sent as POST request in multipart/form-data format
  8896. * containing only file input elements, mg_handle_form_request can
  8897. * handle all form input elements and all standard request methods. */
  8898. struct mg_upload_user_data {
  8899. struct mg_connection *conn;
  8900. const char *destination_dir;
  8901. int num_uploaded_files;
  8902. };
  8903. /* Helper function for deprecated mg_upload. */
  8904. static int
  8905. mg_upload_field_found(const char *key,
  8906. const char *filename,
  8907. char *path,
  8908. size_t pathlen,
  8909. void *user_data)
  8910. {
  8911. int truncated = 0;
  8912. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  8913. (void)key;
  8914. if (!filename) {
  8915. mg_cry(fud->conn, "%s: No filename set", __func__);
  8916. return FORM_FIELD_STORAGE_ABORT;
  8917. }
  8918. mg_snprintf(fud->conn,
  8919. &truncated,
  8920. path,
  8921. pathlen - 1,
  8922. "%s/%s",
  8923. fud->destination_dir,
  8924. filename);
  8925. if (!truncated) {
  8926. mg_cry(fud->conn, "%s: File path too long", __func__);
  8927. return FORM_FIELD_STORAGE_ABORT;
  8928. }
  8929. return FORM_FIELD_STORAGE_STORE;
  8930. }
  8931. /* Helper function for deprecated mg_upload. */
  8932. static int
  8933. mg_upload_field_get(const char *key,
  8934. const char *value,
  8935. size_t value_size,
  8936. void *user_data)
  8937. {
  8938. /* Function should never be called */
  8939. (void)key;
  8940. (void)value;
  8941. (void)value_size;
  8942. (void)user_data;
  8943. return 0;
  8944. }
  8945. /* Helper function for deprecated mg_upload. */
  8946. static int
  8947. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  8948. {
  8949. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  8950. (void)file_size;
  8951. fud->num_uploaded_files++;
  8952. fud->conn->ctx->callbacks.upload(fud->conn, path);
  8953. return 0;
  8954. }
  8955. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  8956. int
  8957. mg_upload(struct mg_connection *conn, const char *destination_dir)
  8958. {
  8959. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  8960. struct mg_form_data_handler fdh = {mg_upload_field_found,
  8961. mg_upload_field_get,
  8962. mg_upload_field_stored,
  8963. 0};
  8964. int ret;
  8965. fdh.user_data = (void *)&fud;
  8966. ret = mg_handle_form_request(conn, &fdh);
  8967. if (ret < 0) {
  8968. mg_cry(conn, "%s: Error while parsing the request", __func__);
  8969. }
  8970. return fud.num_uploaded_files;
  8971. }
  8972. #endif
  8973. static int
  8974. get_first_ssl_listener_index(const struct mg_context *ctx)
  8975. {
  8976. unsigned int i;
  8977. int idx = -1;
  8978. if (ctx) {
  8979. for (i = 0; idx == -1 && i < ctx->num_listening_sockets; i++) {
  8980. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  8981. }
  8982. }
  8983. return idx;
  8984. }
  8985. static void
  8986. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  8987. {
  8988. char host[1025];
  8989. const char *host_header;
  8990. size_t hostlen;
  8991. host_header = mg_get_header(conn, "Host");
  8992. hostlen = sizeof(host);
  8993. if (host_header != NULL) {
  8994. char *pos;
  8995. mg_strlcpy(host, host_header, hostlen);
  8996. host[hostlen - 1] = '\0';
  8997. pos = strchr(host, ':');
  8998. if (pos != NULL) {
  8999. *pos = '\0';
  9000. }
  9001. } else {
  9002. /* Cannot get host from the Host: header.
  9003. * Fallback to our IP address. */
  9004. if (conn) {
  9005. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  9006. }
  9007. }
  9008. /* Send host, port, uri and (if it exists) ?query_string */
  9009. if (conn) {
  9010. mg_printf(conn,
  9011. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  9012. host,
  9013. #if defined(USE_IPV6)
  9014. (conn->ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  9015. == AF_INET6)
  9016. ? (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  9017. .lsa.sin6.sin6_port)
  9018. :
  9019. #endif
  9020. (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  9021. .lsa.sin.sin_port),
  9022. conn->request_info.local_uri,
  9023. (conn->request_info.query_string == NULL) ? "" : "?",
  9024. (conn->request_info.query_string == NULL)
  9025. ? ""
  9026. : conn->request_info.query_string);
  9027. }
  9028. }
  9029. static void
  9030. mg_set_handler_type(struct mg_context *ctx,
  9031. const char *uri,
  9032. int handler_type,
  9033. int is_delete_request,
  9034. mg_request_handler handler,
  9035. struct mg_websocket_subprotocols *subprotocols,
  9036. mg_websocket_connect_handler connect_handler,
  9037. mg_websocket_ready_handler ready_handler,
  9038. mg_websocket_data_handler data_handler,
  9039. mg_websocket_close_handler close_handler,
  9040. mg_authorization_handler auth_handler,
  9041. void *cbdata)
  9042. {
  9043. struct mg_handler_info *tmp_rh, **lastref;
  9044. size_t urilen = strlen(uri);
  9045. if (handler_type == WEBSOCKET_HANDLER) {
  9046. /* assert(handler == NULL); */
  9047. /* assert(is_delete_request || connect_handler!=NULL ||
  9048. * ready_handler!=NULL || data_handler!=NULL ||
  9049. * close_handler!=NULL);
  9050. */
  9051. /* assert(auth_handler == NULL); */
  9052. if (handler != NULL) {
  9053. return;
  9054. }
  9055. if (!is_delete_request && connect_handler == NULL
  9056. && ready_handler == NULL
  9057. && data_handler == NULL
  9058. && close_handler == NULL) {
  9059. return;
  9060. }
  9061. if (auth_handler != NULL) {
  9062. return;
  9063. }
  9064. } else if (handler_type == REQUEST_HANDLER) {
  9065. /* assert(connect_handler==NULL && ready_handler==NULL &&
  9066. * data_handler==NULL && close_handler==NULL); */
  9067. /* assert(is_delete_request || (handler!=NULL));
  9068. */
  9069. /* assert(auth_handler == NULL); */
  9070. if (connect_handler != NULL || ready_handler != NULL
  9071. || data_handler != NULL
  9072. || close_handler != NULL) {
  9073. return;
  9074. }
  9075. if (!is_delete_request && (handler == NULL)) {
  9076. return;
  9077. }
  9078. if (auth_handler != NULL) {
  9079. return;
  9080. }
  9081. } else { /* AUTH_HANDLER */
  9082. /* assert(handler == NULL); */
  9083. /* assert(connect_handler==NULL && ready_handler==NULL &&
  9084. * data_handler==NULL && close_handler==NULL); */
  9085. /* assert(auth_handler != NULL); */
  9086. if (handler != NULL) {
  9087. return;
  9088. }
  9089. if (connect_handler != NULL || ready_handler != NULL
  9090. || data_handler != NULL
  9091. || close_handler != NULL) {
  9092. return;
  9093. }
  9094. if (!is_delete_request && (auth_handler == NULL)) {
  9095. return;
  9096. }
  9097. }
  9098. if (!ctx) {
  9099. return;
  9100. }
  9101. mg_lock_context(ctx);
  9102. /* first try to find an existing handler */
  9103. lastref = &(ctx->handlers);
  9104. for (tmp_rh = ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  9105. if (tmp_rh->handler_type == handler_type) {
  9106. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  9107. if (!is_delete_request) {
  9108. /* update existing handler */
  9109. if (handler_type == REQUEST_HANDLER) {
  9110. tmp_rh->handler = handler;
  9111. } else if (handler_type == WEBSOCKET_HANDLER) {
  9112. tmp_rh->subprotocols = subprotocols;
  9113. tmp_rh->connect_handler = connect_handler;
  9114. tmp_rh->ready_handler = ready_handler;
  9115. tmp_rh->data_handler = data_handler;
  9116. tmp_rh->close_handler = close_handler;
  9117. } else { /* AUTH_HANDLER */
  9118. tmp_rh->auth_handler = auth_handler;
  9119. }
  9120. tmp_rh->cbdata = cbdata;
  9121. } else {
  9122. /* remove existing handler */
  9123. *lastref = tmp_rh->next;
  9124. mg_free(tmp_rh->uri);
  9125. mg_free(tmp_rh);
  9126. }
  9127. mg_unlock_context(ctx);
  9128. return;
  9129. }
  9130. }
  9131. lastref = &(tmp_rh->next);
  9132. }
  9133. if (is_delete_request) {
  9134. /* no handler to set, this was a remove request to a non-existing
  9135. * handler */
  9136. mg_unlock_context(ctx);
  9137. return;
  9138. }
  9139. tmp_rh =
  9140. (struct mg_handler_info *)mg_calloc(sizeof(struct mg_handler_info), 1);
  9141. if (tmp_rh == NULL) {
  9142. mg_unlock_context(ctx);
  9143. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  9144. return;
  9145. }
  9146. tmp_rh->uri = mg_strdup(uri);
  9147. if (!tmp_rh->uri) {
  9148. mg_unlock_context(ctx);
  9149. mg_free(tmp_rh);
  9150. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  9151. return;
  9152. }
  9153. tmp_rh->uri_len = urilen;
  9154. if (handler_type == REQUEST_HANDLER) {
  9155. tmp_rh->handler = handler;
  9156. } else if (handler_type == WEBSOCKET_HANDLER) {
  9157. tmp_rh->subprotocols = subprotocols;
  9158. tmp_rh->connect_handler = connect_handler;
  9159. tmp_rh->ready_handler = ready_handler;
  9160. tmp_rh->data_handler = data_handler;
  9161. tmp_rh->close_handler = close_handler;
  9162. } else { /* AUTH_HANDLER */
  9163. tmp_rh->auth_handler = auth_handler;
  9164. }
  9165. tmp_rh->cbdata = cbdata;
  9166. tmp_rh->handler_type = handler_type;
  9167. tmp_rh->next = NULL;
  9168. *lastref = tmp_rh;
  9169. mg_unlock_context(ctx);
  9170. }
  9171. void
  9172. mg_set_request_handler(struct mg_context *ctx,
  9173. const char *uri,
  9174. mg_request_handler handler,
  9175. void *cbdata)
  9176. {
  9177. mg_set_handler_type(ctx,
  9178. uri,
  9179. REQUEST_HANDLER,
  9180. handler == NULL,
  9181. handler,
  9182. NULL,
  9183. NULL,
  9184. NULL,
  9185. NULL,
  9186. NULL,
  9187. NULL,
  9188. cbdata);
  9189. }
  9190. void
  9191. mg_set_websocket_handler(struct mg_context *ctx,
  9192. const char *uri,
  9193. mg_websocket_connect_handler connect_handler,
  9194. mg_websocket_ready_handler ready_handler,
  9195. mg_websocket_data_handler data_handler,
  9196. mg_websocket_close_handler close_handler,
  9197. void *cbdata)
  9198. {
  9199. mg_set_websocket_handler_with_subprotocols(ctx,
  9200. uri,
  9201. NULL,
  9202. connect_handler,
  9203. ready_handler,
  9204. data_handler,
  9205. close_handler,
  9206. cbdata);
  9207. }
  9208. void
  9209. mg_set_websocket_handler_with_subprotocols(
  9210. struct mg_context *ctx,
  9211. const char *uri,
  9212. struct mg_websocket_subprotocols *subprotocols,
  9213. mg_websocket_connect_handler connect_handler,
  9214. mg_websocket_ready_handler ready_handler,
  9215. mg_websocket_data_handler data_handler,
  9216. mg_websocket_close_handler close_handler,
  9217. void *cbdata)
  9218. {
  9219. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  9220. && (data_handler == NULL)
  9221. && (close_handler == NULL);
  9222. mg_set_handler_type(ctx,
  9223. uri,
  9224. WEBSOCKET_HANDLER,
  9225. is_delete_request,
  9226. NULL,
  9227. subprotocols,
  9228. connect_handler,
  9229. ready_handler,
  9230. data_handler,
  9231. close_handler,
  9232. NULL,
  9233. cbdata);
  9234. }
  9235. void
  9236. mg_set_auth_handler(struct mg_context *ctx,
  9237. const char *uri,
  9238. mg_request_handler handler,
  9239. void *cbdata)
  9240. {
  9241. mg_set_handler_type(ctx,
  9242. uri,
  9243. AUTH_HANDLER,
  9244. handler == NULL,
  9245. NULL,
  9246. NULL,
  9247. NULL,
  9248. NULL,
  9249. NULL,
  9250. NULL,
  9251. handler,
  9252. cbdata);
  9253. }
  9254. static int
  9255. get_request_handler(struct mg_connection *conn,
  9256. int handler_type,
  9257. mg_request_handler *handler,
  9258. struct mg_websocket_subprotocols **subprotocols,
  9259. mg_websocket_connect_handler *connect_handler,
  9260. mg_websocket_ready_handler *ready_handler,
  9261. mg_websocket_data_handler *data_handler,
  9262. mg_websocket_close_handler *close_handler,
  9263. mg_authorization_handler *auth_handler,
  9264. void **cbdata)
  9265. {
  9266. const struct mg_request_info *request_info = mg_get_request_info(conn);
  9267. if (request_info) {
  9268. const char *uri = request_info->local_uri;
  9269. size_t urilen = strlen(uri);
  9270. struct mg_handler_info *tmp_rh;
  9271. if (!conn || !conn->ctx) {
  9272. return 0;
  9273. }
  9274. mg_lock_context(conn->ctx);
  9275. /* first try for an exact match */
  9276. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  9277. tmp_rh = tmp_rh->next) {
  9278. if (tmp_rh->handler_type == handler_type) {
  9279. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  9280. if (handler_type == WEBSOCKET_HANDLER) {
  9281. *subprotocols = tmp_rh->subprotocols;
  9282. *connect_handler = tmp_rh->connect_handler;
  9283. *ready_handler = tmp_rh->ready_handler;
  9284. *data_handler = tmp_rh->data_handler;
  9285. *close_handler = tmp_rh->close_handler;
  9286. } else if (handler_type == REQUEST_HANDLER) {
  9287. *handler = tmp_rh->handler;
  9288. } else { /* AUTH_HANDLER */
  9289. *auth_handler = tmp_rh->auth_handler;
  9290. }
  9291. *cbdata = tmp_rh->cbdata;
  9292. mg_unlock_context(conn->ctx);
  9293. return 1;
  9294. }
  9295. }
  9296. }
  9297. /* next try for a partial match, we will accept uri/something */
  9298. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  9299. tmp_rh = tmp_rh->next) {
  9300. if (tmp_rh->handler_type == handler_type) {
  9301. if (tmp_rh->uri_len < urilen && uri[tmp_rh->uri_len] == '/'
  9302. && memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0) {
  9303. if (handler_type == WEBSOCKET_HANDLER) {
  9304. *subprotocols = tmp_rh->subprotocols;
  9305. *connect_handler = tmp_rh->connect_handler;
  9306. *ready_handler = tmp_rh->ready_handler;
  9307. *data_handler = tmp_rh->data_handler;
  9308. *close_handler = tmp_rh->close_handler;
  9309. } else if (handler_type == REQUEST_HANDLER) {
  9310. *handler = tmp_rh->handler;
  9311. } else { /* AUTH_HANDLER */
  9312. *auth_handler = tmp_rh->auth_handler;
  9313. }
  9314. *cbdata = tmp_rh->cbdata;
  9315. mg_unlock_context(conn->ctx);
  9316. return 1;
  9317. }
  9318. }
  9319. }
  9320. /* finally try for pattern match */
  9321. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  9322. tmp_rh = tmp_rh->next) {
  9323. if (tmp_rh->handler_type == handler_type) {
  9324. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  9325. if (handler_type == WEBSOCKET_HANDLER) {
  9326. *subprotocols = tmp_rh->subprotocols;
  9327. *connect_handler = tmp_rh->connect_handler;
  9328. *ready_handler = tmp_rh->ready_handler;
  9329. *data_handler = tmp_rh->data_handler;
  9330. *close_handler = tmp_rh->close_handler;
  9331. } else if (handler_type == REQUEST_HANDLER) {
  9332. *handler = tmp_rh->handler;
  9333. } else { /* AUTH_HANDLER */
  9334. *auth_handler = tmp_rh->auth_handler;
  9335. }
  9336. *cbdata = tmp_rh->cbdata;
  9337. mg_unlock_context(conn->ctx);
  9338. return 1;
  9339. }
  9340. }
  9341. }
  9342. mg_unlock_context(conn->ctx);
  9343. }
  9344. return 0; /* none found */
  9345. }
  9346. /* Check if the script file is in a path, allowed for script files.
  9347. * This can be used if uploading files is possible not only for the server
  9348. * admin, and the upload mechanism does not check the file extension.
  9349. */
  9350. static int
  9351. is_in_script_path(const struct mg_connection *conn, const char *path)
  9352. {
  9353. /* TODO: Add config value for allowed script path.
  9354. * Default: All allowed. */
  9355. (void)conn;
  9356. (void)path;
  9357. return 1;
  9358. }
  9359. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  9360. static int
  9361. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  9362. void *cbdata)
  9363. {
  9364. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9365. if (pcallbacks->websocket_connect) {
  9366. return pcallbacks->websocket_connect(conn);
  9367. }
  9368. /* No handler set - assume "OK" */
  9369. return 0;
  9370. }
  9371. static void
  9372. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  9373. {
  9374. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9375. if (pcallbacks->websocket_ready) {
  9376. pcallbacks->websocket_ready(conn);
  9377. }
  9378. }
  9379. static int
  9380. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  9381. int bits,
  9382. char *data,
  9383. size_t len,
  9384. void *cbdata)
  9385. {
  9386. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9387. if (pcallbacks->websocket_data) {
  9388. return pcallbacks->websocket_data(conn, bits, data, len);
  9389. }
  9390. /* No handler set - assume "OK" */
  9391. return 1;
  9392. }
  9393. #endif
  9394. /* This is the heart of the Civetweb's logic.
  9395. * This function is called when the request is read, parsed and validated,
  9396. * and Civetweb must decide what action to take: serve a file, or
  9397. * a directory, or call embedded function, etcetera. */
  9398. static void
  9399. handle_request(struct mg_connection *conn)
  9400. {
  9401. struct mg_request_info *ri = &conn->request_info;
  9402. char path[PATH_MAX];
  9403. int uri_len, ssl_index;
  9404. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  9405. is_put_or_delete_request = 0, is_callback_resource = 0;
  9406. int i;
  9407. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9408. mg_request_handler callback_handler = NULL;
  9409. struct mg_websocket_subprotocols *subprotocols;
  9410. mg_websocket_connect_handler ws_connect_handler = NULL;
  9411. mg_websocket_ready_handler ws_ready_handler = NULL;
  9412. mg_websocket_data_handler ws_data_handler = NULL;
  9413. mg_websocket_close_handler ws_close_handler = NULL;
  9414. void *callback_data = NULL;
  9415. mg_authorization_handler auth_handler = NULL;
  9416. void *auth_callback_data = NULL;
  9417. #if !defined(NO_FILES)
  9418. time_t curtime = time(NULL);
  9419. char date[64];
  9420. #endif
  9421. path[0] = 0;
  9422. if (!ri) {
  9423. return;
  9424. }
  9425. /* 1. get the request url */
  9426. /* 1.1. split into url and query string */
  9427. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  9428. != NULL) {
  9429. *((char *)conn->request_info.query_string++) = '\0';
  9430. }
  9431. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  9432. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  9433. ssl_index = get_first_ssl_listener_index(conn->ctx);
  9434. if (ssl_index >= 0) {
  9435. redirect_to_https_port(conn, ssl_index);
  9436. } else {
  9437. /* A http to https forward port has been specified,
  9438. * but no https port to forward to. */
  9439. send_http_error(conn,
  9440. 503,
  9441. "%s",
  9442. "Error: SSL forward not configured properly");
  9443. mg_cry(conn, "Can not redirect to SSL, no SSL port available");
  9444. }
  9445. return;
  9446. }
  9447. uri_len = (int)strlen(ri->local_uri);
  9448. /* 1.3. decode url (if config says so) */
  9449. if (should_decode_url(conn)) {
  9450. mg_url_decode(
  9451. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  9452. }
  9453. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  9454. * not possible */
  9455. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  9456. /* step 1. completed, the url is known now */
  9457. uri_len = (int)strlen(ri->local_uri);
  9458. DEBUG_TRACE("URL: %s", ri->local_uri);
  9459. /* 3. if this ip has limited speed, set it for this connection */
  9460. conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
  9461. get_remote_ip(conn),
  9462. ri->local_uri);
  9463. /* 4. call a "handle everything" callback, if registered */
  9464. if (conn->ctx->callbacks.begin_request != NULL) {
  9465. /* Note that since V1.7 the "begin_request" function is called
  9466. * before an authorization check. If an authorization check is
  9467. * required, use a request_handler instead. */
  9468. i = conn->ctx->callbacks.begin_request(conn);
  9469. if (i > 0) {
  9470. /* callback already processed the request. Store the
  9471. return value as a status code for the access log. */
  9472. conn->status_code = i;
  9473. discard_unread_request_data(conn);
  9474. return;
  9475. } else if (i == 0) {
  9476. /* civetweb should process the request */
  9477. } else {
  9478. /* unspecified - may change with the next version */
  9479. return;
  9480. }
  9481. }
  9482. /* request not yet handled by a handler or redirect, so the request
  9483. * is processed here */
  9484. /* 5. interpret the url to find out how the request must be handled
  9485. */
  9486. /* 5.1. first test, if the request targets the regular http(s)://
  9487. * protocol namespace or the websocket ws(s):// protocol namespace.
  9488. */
  9489. is_websocket_request = is_websocket_protocol(conn);
  9490. /* 5.2. check if the request will be handled by a callback */
  9491. if (get_request_handler(conn,
  9492. is_websocket_request ? WEBSOCKET_HANDLER
  9493. : REQUEST_HANDLER,
  9494. &callback_handler,
  9495. &subprotocols,
  9496. &ws_connect_handler,
  9497. &ws_ready_handler,
  9498. &ws_data_handler,
  9499. &ws_close_handler,
  9500. NULL,
  9501. &callback_data)) {
  9502. /* 5.2.1. A callback will handle this request. All requests
  9503. * handled
  9504. * by a callback have to be considered as requests to a script
  9505. * resource. */
  9506. is_callback_resource = 1;
  9507. is_script_resource = 1;
  9508. is_put_or_delete_request = is_put_or_delete_method(conn);
  9509. } else {
  9510. no_callback_resource:
  9511. /* 5.2.2. No callback is responsible for this request. The URI
  9512. * addresses a file based resource (static content or Lua/cgi
  9513. * scripts in the file system). */
  9514. is_callback_resource = 0;
  9515. interpret_uri(conn,
  9516. path,
  9517. sizeof(path),
  9518. &file.stat,
  9519. &is_found,
  9520. &is_script_resource,
  9521. &is_websocket_request,
  9522. &is_put_or_delete_request);
  9523. }
  9524. /* 6. authorization check */
  9525. /* 6.1. a custom authorization handler is installed */
  9526. if (get_request_handler(conn,
  9527. AUTH_HANDLER,
  9528. NULL,
  9529. NULL,
  9530. NULL,
  9531. NULL,
  9532. NULL,
  9533. NULL,
  9534. &auth_handler,
  9535. &auth_callback_data)) {
  9536. if (!auth_handler(conn, auth_callback_data)) {
  9537. return;
  9538. }
  9539. } else if (is_put_or_delete_request && !is_script_resource
  9540. && !is_callback_resource) {
  9541. /* 6.2. this request is a PUT/DELETE to a real file */
  9542. /* 6.2.1. thus, the server must have real files */
  9543. #if defined(NO_FILES)
  9544. if (1) {
  9545. #else
  9546. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  9547. #endif
  9548. /* This server does not have any real files, thus the
  9549. * PUT/DELETE methods are not valid. */
  9550. send_http_error(conn,
  9551. 405,
  9552. "%s method not allowed",
  9553. conn->request_info.request_method);
  9554. return;
  9555. }
  9556. #if !defined(NO_FILES)
  9557. /* 6.2.2. Check if put authorization for static files is
  9558. * available.
  9559. */
  9560. if (!is_authorized_for_put(conn)) {
  9561. send_authorization_request(conn);
  9562. return;
  9563. }
  9564. #endif
  9565. } else {
  9566. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  9567. * or it is a PUT or DELETE request to a resource that does not
  9568. * correspond to a file. Check authorization. */
  9569. if (!check_authorization(conn, path)) {
  9570. send_authorization_request(conn);
  9571. return;
  9572. }
  9573. }
  9574. /* request is authorized or does not need authorization */
  9575. /* 7. check if there are request handlers for this uri */
  9576. if (is_callback_resource) {
  9577. if (!is_websocket_request) {
  9578. i = callback_handler(conn, callback_data);
  9579. if (i > 0) {
  9580. /* Do nothing, callback has served the request. Store
  9581. * the
  9582. * return value as status code for the log and discard
  9583. * all
  9584. * data from the client not used by the callback. */
  9585. conn->status_code = i;
  9586. discard_unread_request_data(conn);
  9587. } else {
  9588. /* TODO (high): what if the handler did NOT handle the
  9589. * request */
  9590. /* The last version did handle this as a file request,
  9591. * but
  9592. * since a file request is not always a script resource,
  9593. * the authorization check might be different */
  9594. interpret_uri(conn,
  9595. path,
  9596. sizeof(path),
  9597. &file.stat,
  9598. &is_found,
  9599. &is_script_resource,
  9600. &is_websocket_request,
  9601. &is_put_or_delete_request);
  9602. callback_handler = NULL;
  9603. /* Here we are at a dead end:
  9604. * According to URI matching, a callback should be
  9605. * responsible for handling the request,
  9606. * we called it, but the callback declared itself
  9607. * not responsible.
  9608. * We use a goto here, to get out of this dead end,
  9609. * and continue with the default handling.
  9610. * A goto here is simpler and better to understand
  9611. * than some curious loop. */
  9612. goto no_callback_resource;
  9613. }
  9614. } else {
  9615. #if defined(USE_WEBSOCKET)
  9616. handle_websocket_request(conn,
  9617. path,
  9618. is_callback_resource,
  9619. subprotocols,
  9620. ws_connect_handler,
  9621. ws_ready_handler,
  9622. ws_data_handler,
  9623. ws_close_handler,
  9624. callback_data);
  9625. #endif
  9626. }
  9627. return;
  9628. }
  9629. /* 8. handle websocket requests */
  9630. #if defined(USE_WEBSOCKET)
  9631. if (is_websocket_request) {
  9632. if (is_script_resource) {
  9633. if (is_in_script_path(conn, path)) {
  9634. /* Websocket Lua script */
  9635. handle_websocket_request(conn,
  9636. path,
  9637. 0 /* Lua Script */,
  9638. NULL,
  9639. NULL,
  9640. NULL,
  9641. NULL,
  9642. NULL,
  9643. &conn->ctx->callbacks);
  9644. } else {
  9645. /* Script was in an illegal path */
  9646. send_http_error(conn, 403, "%s", "Forbidden");
  9647. }
  9648. } else {
  9649. #if defined(MG_LEGACY_INTERFACE)
  9650. handle_websocket_request(
  9651. conn,
  9652. path,
  9653. !is_script_resource /* could be deprecated global callback */,
  9654. NULL,
  9655. deprecated_websocket_connect_wrapper,
  9656. deprecated_websocket_ready_wrapper,
  9657. deprecated_websocket_data_wrapper,
  9658. NULL,
  9659. &conn->ctx->callbacks);
  9660. #else
  9661. send_http_error(conn, 404, "%s", "Not found");
  9662. #endif
  9663. }
  9664. return;
  9665. } else
  9666. #endif
  9667. #if defined(NO_FILES)
  9668. /* 9a. In case the server uses only callbacks, this uri is
  9669. * unknown.
  9670. * Then, all request handling ends here. */
  9671. send_http_error(conn, 404, "%s", "Not Found");
  9672. #else
  9673. /* 9b. This request is either for a static file or resource handled
  9674. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  9675. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  9676. send_http_error(conn, 404, "%s", "Not Found");
  9677. return;
  9678. }
  9679. /* 10. File is handled by a script. */
  9680. if (is_script_resource) {
  9681. handle_file_based_request(conn, path, &file);
  9682. return;
  9683. }
  9684. /* 11. Handle put/delete/mkcol requests */
  9685. if (is_put_or_delete_request) {
  9686. /* 11.1. PUT method */
  9687. if (!strcmp(ri->request_method, "PUT")) {
  9688. put_file(conn, path);
  9689. return;
  9690. }
  9691. /* 11.2. DELETE method */
  9692. if (!strcmp(ri->request_method, "DELETE")) {
  9693. delete_file(conn, path);
  9694. return;
  9695. }
  9696. /* 11.3. MKCOL method */
  9697. if (!strcmp(ri->request_method, "MKCOL")) {
  9698. mkcol(conn, path);
  9699. return;
  9700. }
  9701. /* 11.4. PATCH method
  9702. * This method is not supported for static resources,
  9703. * only for scripts (Lua, CGI) and callbacks. */
  9704. send_http_error(conn,
  9705. 405,
  9706. "%s method not allowed",
  9707. conn->request_info.request_method);
  9708. return;
  9709. }
  9710. /* 11. File does not exist, or it was configured that it should be
  9711. * hidden */
  9712. if (!is_found || (must_hide_file(conn, path))) {
  9713. send_http_error(conn, 404, "%s", "Not found");
  9714. return;
  9715. }
  9716. /* 12. Directory uris should end with a slash */
  9717. if (file.stat.is_directory && (uri_len > 0)
  9718. && (ri->local_uri[uri_len - 1] != '/')) {
  9719. gmt_time_string(date, sizeof(date), &curtime);
  9720. mg_printf(conn,
  9721. "HTTP/1.1 301 Moved Permanently\r\n"
  9722. "Location: %s/\r\n"
  9723. "Date: %s\r\n"
  9724. /* "Cache-Control: private\r\n" (= default) */
  9725. "Content-Length: 0\r\n"
  9726. "Connection: %s\r\n",
  9727. ri->request_uri,
  9728. date,
  9729. suggest_connection_header(conn));
  9730. send_additional_header(conn);
  9731. mg_printf(conn, "\r\n");
  9732. return;
  9733. }
  9734. /* 13. Handle other methods than GET/HEAD */
  9735. /* 13.1. Handle PROPFIND */
  9736. if (!strcmp(ri->request_method, "PROPFIND")) {
  9737. handle_propfind(conn, path, &file.stat);
  9738. return;
  9739. }
  9740. /* 13.2. Handle OPTIONS for files */
  9741. if (!strcmp(ri->request_method, "OPTIONS")) {
  9742. /* This standard handler is only used for real files.
  9743. * Scripts should support the OPTIONS method themselves, to allow a
  9744. * maximum flexibility.
  9745. * Lua and CGI scripts may fully support CORS this way (including
  9746. * preflights). */
  9747. send_options(conn);
  9748. return;
  9749. }
  9750. /* 13.3. everything but GET and HEAD (e.g. POST) */
  9751. if (0 != strcmp(ri->request_method, "GET")
  9752. && 0 != strcmp(ri->request_method, "HEAD")) {
  9753. send_http_error(conn,
  9754. 405,
  9755. "%s method not allowed",
  9756. conn->request_info.request_method);
  9757. return;
  9758. }
  9759. /* 14. directories */
  9760. if (file.stat.is_directory) {
  9761. if (substitute_index_file(conn, path, sizeof(path), &file)) {
  9762. /* 14.1. use a substitute file */
  9763. /* TODO (high): substitute index may be a script resource.
  9764. * define what should be possible in this case. */
  9765. } else {
  9766. /* 14.2. no substitute file */
  9767. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  9768. "yes")) {
  9769. handle_directory_request(conn, path);
  9770. } else {
  9771. send_http_error(conn,
  9772. 403,
  9773. "%s",
  9774. "Error: Directory listing denied");
  9775. }
  9776. return;
  9777. }
  9778. }
  9779. handle_file_based_request(conn, path, &file);
  9780. #endif /* !defined(NO_FILES) */
  9781. #if 0
  9782. /* Perform redirect and auth checks before calling begin_request()
  9783. * handler.
  9784. * Otherwise, begin_request() would need to perform auth checks and
  9785. * redirects. */
  9786. #endif
  9787. }
  9788. static void
  9789. handle_file_based_request(struct mg_connection *conn,
  9790. const char *path,
  9791. struct mg_file *file)
  9792. {
  9793. if (!conn || !conn->ctx) {
  9794. return;
  9795. }
  9796. if (0) {
  9797. #ifdef USE_LUA
  9798. } else if (match_prefix(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  9799. strlen(
  9800. conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  9801. path) > 0) {
  9802. if (is_in_script_path(conn, path)) {
  9803. /* Lua server page: an SSI like page containing mostly plain html
  9804. * code
  9805. * plus some tags with server generated contents. */
  9806. handle_lsp_request(conn, path, file, NULL);
  9807. } else {
  9808. /* Script was in an illegal path */
  9809. send_http_error(conn, 403, "%s", "Forbidden");
  9810. }
  9811. } else if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  9812. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  9813. path) > 0) {
  9814. if (is_in_script_path(conn, path)) {
  9815. /* Lua in-server module script: a CGI like script used to generate
  9816. * the
  9817. * entire reply. */
  9818. mg_exec_lua_script(conn, path, NULL);
  9819. } else {
  9820. /* Script was in an illegal path */
  9821. send_http_error(conn, 403, "%s", "Forbidden");
  9822. }
  9823. #endif
  9824. #if defined(USE_DUKTAPE)
  9825. } else if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  9826. strlen(
  9827. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  9828. path) > 0) {
  9829. if (is_in_script_path(conn, path)) {
  9830. /* Call duktape to generate the page */
  9831. mg_exec_duktape_script(conn, path);
  9832. } else {
  9833. /* Script was in an illegal path */
  9834. send_http_error(conn, 403, "%s", "Forbidden");
  9835. }
  9836. #endif
  9837. #if !defined(NO_CGI)
  9838. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  9839. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  9840. path) > 0) {
  9841. if (is_in_script_path(conn, path)) {
  9842. /* CGI scripts may support all HTTP methods */
  9843. handle_cgi_request(conn, path);
  9844. } else {
  9845. /* Script was in an illegal path */
  9846. send_http_error(conn, 403, "%s", "Forbidden");
  9847. }
  9848. #endif /* !NO_CGI */
  9849. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  9850. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  9851. path) > 0) {
  9852. if (is_in_script_path(conn, path)) {
  9853. handle_ssi_file_request(conn, path, file);
  9854. } else {
  9855. /* Script was in an illegal path */
  9856. send_http_error(conn, 403, "%s", "Forbidden");
  9857. }
  9858. #if !defined(NO_CACHING)
  9859. } else if ((!conn->in_error_handler)
  9860. && is_not_modified(conn, &file->stat)) {
  9861. /* Send 304 "Not Modified" - this must not send any body data */
  9862. handle_not_modified_static_file_request(conn, file);
  9863. #endif /* !NO_CACHING */
  9864. } else {
  9865. handle_static_file_request(conn, path, file, NULL, NULL);
  9866. }
  9867. }
  9868. static void
  9869. close_all_listening_sockets(struct mg_context *ctx)
  9870. {
  9871. unsigned int i;
  9872. if (!ctx) {
  9873. return;
  9874. }
  9875. for (i = 0; i < ctx->num_listening_sockets; i++) {
  9876. closesocket(ctx->listening_sockets[i].sock);
  9877. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  9878. }
  9879. mg_free(ctx->listening_sockets);
  9880. ctx->listening_sockets = NULL;
  9881. mg_free(ctx->listening_socket_fds);
  9882. ctx->listening_socket_fds = NULL;
  9883. }
  9884. /* Valid listening port specification is: [ip_address:]port[s]
  9885. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  9886. * Examples for IPv6: [::]:80, [::1]:80,
  9887. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  9888. * see https://tools.ietf.org/html/rfc3513#section-2.2
  9889. * In order to bind to both, IPv4 and IPv6, you can either add
  9890. * both ports using 8080,[::]:8080, or the short form +8080.
  9891. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  9892. * one only accepting IPv4 the other only IPv6. +8080 creates
  9893. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  9894. * environment, they might work differently, or might not work
  9895. * at all - it must be tested what options work best in the
  9896. * relevant network environment.
  9897. */
  9898. static int
  9899. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  9900. {
  9901. unsigned int a, b, c, d, port;
  9902. int ch, len;
  9903. #if defined(USE_IPV6)
  9904. char buf[100] = {0};
  9905. #endif
  9906. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  9907. * Also, all-zeroes in the socket address means binding to all addresses
  9908. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  9909. memset(so, 0, sizeof(*so));
  9910. so->lsa.sin.sin_family = AF_INET;
  9911. *ip_version = 0;
  9912. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  9913. == 5) {
  9914. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  9915. so->lsa.sin.sin_addr.s_addr =
  9916. htonl((a << 24) | (b << 16) | (c << 8) | d);
  9917. so->lsa.sin.sin_port = htons((uint16_t)port);
  9918. *ip_version = 4;
  9919. #if defined(USE_IPV6)
  9920. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  9921. && mg_inet_pton(
  9922. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  9923. /* IPv6 address, examples: see above */
  9924. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  9925. */
  9926. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  9927. *ip_version = 6;
  9928. #endif
  9929. } else if ((vec->ptr[0] == '+')
  9930. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  9931. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  9932. /* Add 1 to len for the + character we skipped before */
  9933. len++;
  9934. #if defined(USE_IPV6)
  9935. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  9936. so->lsa.sin6.sin6_family = AF_INET6;
  9937. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  9938. *ip_version = 4 + 6;
  9939. #else
  9940. /* Bind to IPv4 only, since IPv6 is not built in. */
  9941. so->lsa.sin.sin_port = htons((uint16_t)port);
  9942. *ip_version = 4;
  9943. #endif
  9944. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  9945. /* If only port is specified, bind to IPv4, INADDR_ANY */
  9946. so->lsa.sin.sin_port = htons((uint16_t)port);
  9947. *ip_version = 4;
  9948. } else {
  9949. /* Parsing failure. Make port invalid. */
  9950. port = 0;
  9951. len = 0;
  9952. }
  9953. /* sscanf and the option splitting code ensure the following condition
  9954. */
  9955. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  9956. *ip_version = 0;
  9957. return 0;
  9958. }
  9959. ch = vec->ptr[len]; /* Next character after the port number */
  9960. so->is_ssl = (ch == 's');
  9961. so->ssl_redir = (ch == 'r');
  9962. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  9963. if (is_valid_port(port)
  9964. && (ch == '\0' || ch == 's' || ch == 'r' || ch == ',')) {
  9965. return 1;
  9966. }
  9967. /* Reset ip_version to 0 of there is an error */
  9968. *ip_version = 0;
  9969. return 0;
  9970. }
  9971. static int
  9972. set_ports_option(struct mg_context *ctx)
  9973. {
  9974. const char *list;
  9975. int on = 1;
  9976. #if defined(USE_IPV6)
  9977. int off = 0;
  9978. #endif
  9979. struct vec vec;
  9980. struct socket so, *ptr;
  9981. struct pollfd *pfd;
  9982. union usa usa;
  9983. socklen_t len;
  9984. int ip_version;
  9985. int portsTotal = 0;
  9986. int portsOk = 0;
  9987. if (!ctx) {
  9988. return 0;
  9989. }
  9990. memset(&so, 0, sizeof(so));
  9991. memset(&usa, 0, sizeof(usa));
  9992. len = sizeof(usa);
  9993. list = ctx->config[LISTENING_PORTS];
  9994. while ((list = next_option(list, &vec, NULL)) != NULL) {
  9995. portsTotal++;
  9996. if (!parse_port_string(&vec, &so, &ip_version)) {
  9997. mg_cry(fc(ctx),
  9998. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  9999. (int)vec.len,
  10000. vec.ptr,
  10001. portsTotal,
  10002. "[IP_ADDRESS:]PORT[s|r]");
  10003. continue;
  10004. }
  10005. #if !defined(NO_SSL)
  10006. if (so.is_ssl && ctx->ssl_ctx == NULL) {
  10007. mg_cry(fc(ctx),
  10008. "Cannot add SSL socket (entry %i). Is -ssl_certificate "
  10009. "option set?",
  10010. portsTotal);
  10011. continue;
  10012. }
  10013. #endif
  10014. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  10015. == INVALID_SOCKET) {
  10016. mg_cry(fc(ctx), "cannot create socket (entry %i)", portsTotal);
  10017. continue;
  10018. }
  10019. #ifdef _WIN32
  10020. /* Windows SO_REUSEADDR lets many procs binds to a
  10021. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  10022. * if someone already has the socket -- DTL */
  10023. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  10024. * Windows might need a few seconds before
  10025. * the same port can be used again in the
  10026. * same process, so a short Sleep may be
  10027. * required between mg_stop and mg_start.
  10028. */
  10029. if (setsockopt(so.sock,
  10030. SOL_SOCKET,
  10031. SO_EXCLUSIVEADDRUSE,
  10032. (SOCK_OPT_TYPE)&on,
  10033. sizeof(on)) != 0) {
  10034. /* Set reuse option, but don't abort on errors. */
  10035. mg_cry(fc(ctx),
  10036. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  10037. portsTotal);
  10038. }
  10039. #else
  10040. if (setsockopt(so.sock,
  10041. SOL_SOCKET,
  10042. SO_REUSEADDR,
  10043. (SOCK_OPT_TYPE)&on,
  10044. sizeof(on)) != 0) {
  10045. /* Set reuse option, but don't abort on errors. */
  10046. mg_cry(fc(ctx),
  10047. "cannot set socket option SO_REUSEADDR (entry %i)",
  10048. portsTotal);
  10049. }
  10050. #endif
  10051. if (ip_version > 4) {
  10052. #if defined(USE_IPV6)
  10053. if (ip_version == 6) {
  10054. if (so.lsa.sa.sa_family == AF_INET6
  10055. && setsockopt(so.sock,
  10056. IPPROTO_IPV6,
  10057. IPV6_V6ONLY,
  10058. (void *)&off,
  10059. sizeof(off)) != 0) {
  10060. /* Set IPv6 only option, but don't abort on errors. */
  10061. mg_cry(fc(ctx),
  10062. "cannot set socket option IPV6_V6ONLY (entry %i)",
  10063. portsTotal);
  10064. }
  10065. }
  10066. #else
  10067. mg_cry(fc(ctx), "IPv6 not available");
  10068. closesocket(so.sock);
  10069. so.sock = INVALID_SOCKET;
  10070. continue;
  10071. #endif
  10072. }
  10073. if (so.lsa.sa.sa_family == AF_INET) {
  10074. len = sizeof(so.lsa.sin);
  10075. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  10076. mg_cry(fc(ctx),
  10077. "cannot bind to %.*s: %d (%s)",
  10078. (int)vec.len,
  10079. vec.ptr,
  10080. (int)ERRNO,
  10081. strerror(errno));
  10082. closesocket(so.sock);
  10083. so.sock = INVALID_SOCKET;
  10084. continue;
  10085. }
  10086. }
  10087. #if defined(USE_IPV6)
  10088. else if (so.lsa.sa.sa_family == AF_INET6) {
  10089. len = sizeof(so.lsa.sin6);
  10090. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  10091. mg_cry(fc(ctx),
  10092. "cannot bind to IPv6 %.*s: %d (%s)",
  10093. (int)vec.len,
  10094. vec.ptr,
  10095. (int)ERRNO,
  10096. strerror(errno));
  10097. closesocket(so.sock);
  10098. so.sock = INVALID_SOCKET;
  10099. continue;
  10100. }
  10101. }
  10102. #endif
  10103. else {
  10104. mg_cry(fc(ctx),
  10105. "cannot bind: address family not supported (entry %i)",
  10106. portsTotal);
  10107. continue;
  10108. }
  10109. if (listen(so.sock, SOMAXCONN) != 0) {
  10110. mg_cry(fc(ctx),
  10111. "cannot listen to %.*s: %d (%s)",
  10112. (int)vec.len,
  10113. vec.ptr,
  10114. (int)ERRNO,
  10115. strerror(errno));
  10116. closesocket(so.sock);
  10117. so.sock = INVALID_SOCKET;
  10118. continue;
  10119. }
  10120. if (getsockname(so.sock, &(usa.sa), &len) != 0
  10121. || usa.sa.sa_family != so.lsa.sa.sa_family) {
  10122. int err = (int)ERRNO;
  10123. mg_cry(fc(ctx),
  10124. "call to getsockname failed %.*s: %d (%s)",
  10125. (int)vec.len,
  10126. vec.ptr,
  10127. err,
  10128. strerror(errno));
  10129. closesocket(so.sock);
  10130. so.sock = INVALID_SOCKET;
  10131. continue;
  10132. }
  10133. /* Update lsa port in case of random free ports */
  10134. #if defined(USE_IPV6)
  10135. if (so.lsa.sa.sa_family == AF_INET6) {
  10136. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  10137. } else
  10138. #endif
  10139. {
  10140. so.lsa.sin.sin_port = usa.sin.sin_port;
  10141. }
  10142. if ((ptr = (struct socket *)
  10143. mg_realloc(ctx->listening_sockets,
  10144. (ctx->num_listening_sockets + 1)
  10145. * sizeof(ctx->listening_sockets[0]))) == NULL) {
  10146. mg_cry(fc(ctx), "%s", "Out of memory");
  10147. closesocket(so.sock);
  10148. so.sock = INVALID_SOCKET;
  10149. continue;
  10150. }
  10151. if ((pfd = (struct pollfd *)mg_realloc(
  10152. ctx->listening_socket_fds,
  10153. (ctx->num_listening_sockets + 1)
  10154. * sizeof(ctx->listening_socket_fds[0]))) == NULL) {
  10155. mg_cry(fc(ctx), "%s", "Out of memory");
  10156. closesocket(so.sock);
  10157. so.sock = INVALID_SOCKET;
  10158. mg_free(ptr);
  10159. continue;
  10160. }
  10161. set_close_on_exec(so.sock, fc(ctx));
  10162. ctx->listening_sockets = ptr;
  10163. ctx->listening_sockets[ctx->num_listening_sockets] = so;
  10164. ctx->listening_socket_fds = pfd;
  10165. ctx->num_listening_sockets++;
  10166. portsOk++;
  10167. }
  10168. if (portsOk != portsTotal) {
  10169. close_all_listening_sockets(ctx);
  10170. portsOk = 0;
  10171. }
  10172. return portsOk;
  10173. }
  10174. static const char *
  10175. header_val(const struct mg_connection *conn, const char *header)
  10176. {
  10177. const char *header_value;
  10178. if ((header_value = mg_get_header(conn, header)) == NULL) {
  10179. return "-";
  10180. } else {
  10181. return header_value;
  10182. }
  10183. }
  10184. static void
  10185. log_access(const struct mg_connection *conn)
  10186. {
  10187. const struct mg_request_info *ri;
  10188. struct mg_file fi;
  10189. char date[64], src_addr[IP_ADDR_STR_LEN];
  10190. struct tm *tm;
  10191. const char *referer;
  10192. const char *user_agent;
  10193. char buf[4096];
  10194. if (!conn || !conn->ctx) {
  10195. return;
  10196. }
  10197. if (conn->ctx->config[ACCESS_LOG_FILE] != NULL) {
  10198. if (mg_fopen(conn,
  10199. conn->ctx->config[ACCESS_LOG_FILE],
  10200. MG_FOPEN_MODE_APPEND,
  10201. &fi) == 0) {
  10202. fi.access.fp = NULL;
  10203. }
  10204. } else {
  10205. fi.access.fp = NULL;
  10206. }
  10207. /* Log is written to a file and/or a callback. If both are not set,
  10208. * executing the rest of the function is pointless. */
  10209. if ((fi.access.fp == NULL) && (conn->ctx->callbacks.log_access == NULL)) {
  10210. return;
  10211. }
  10212. tm = localtime(&conn->conn_birth_time);
  10213. if (tm != NULL) {
  10214. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  10215. } else {
  10216. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  10217. date[sizeof(date) - 1] = '\0';
  10218. }
  10219. ri = &conn->request_info;
  10220. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  10221. referer = header_val(conn, "Referer");
  10222. user_agent = header_val(conn, "User-Agent");
  10223. mg_snprintf(conn,
  10224. NULL, /* Ignore truncation in access log */
  10225. buf,
  10226. sizeof(buf),
  10227. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  10228. src_addr,
  10229. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  10230. date,
  10231. ri->request_method ? ri->request_method : "-",
  10232. ri->request_uri ? ri->request_uri : "-",
  10233. ri->query_string ? "?" : "",
  10234. ri->query_string ? ri->query_string : "",
  10235. ri->http_version,
  10236. conn->status_code,
  10237. conn->num_bytes_sent,
  10238. referer,
  10239. user_agent);
  10240. if (conn->ctx->callbacks.log_access) {
  10241. conn->ctx->callbacks.log_access(conn, buf);
  10242. }
  10243. if (fi.access.fp) {
  10244. int ok = 1;
  10245. flockfile(fi.access.fp);
  10246. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  10247. ok = 0;
  10248. }
  10249. if (fflush(fi.access.fp) != 0) {
  10250. ok = 0;
  10251. }
  10252. funlockfile(fi.access.fp);
  10253. if (mg_fclose(&fi.access) != 0) {
  10254. ok = 0;
  10255. }
  10256. if (!ok) {
  10257. mg_cry(conn,
  10258. "Error writing log file %s",
  10259. conn->ctx->config[ACCESS_LOG_FILE]);
  10260. }
  10261. }
  10262. }
  10263. /* Verify given socket address against the ACL.
  10264. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  10265. */
  10266. static int
  10267. check_acl(struct mg_context *ctx, uint32_t remote_ip)
  10268. {
  10269. int allowed, flag;
  10270. uint32_t net, mask;
  10271. struct vec vec;
  10272. if (ctx) {
  10273. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  10274. /* If any ACL is set, deny by default */
  10275. allowed = (list == NULL) ? '+' : '-';
  10276. while ((list = next_option(list, &vec, NULL)) != NULL) {
  10277. flag = vec.ptr[0];
  10278. if ((flag != '+' && flag != '-')
  10279. || parse_net(&vec.ptr[1], &net, &mask) == 0) {
  10280. mg_cry(fc(ctx),
  10281. "%s: subnet must be [+|-]x.x.x.x[/x]",
  10282. __func__);
  10283. return -1;
  10284. }
  10285. if (net == (remote_ip & mask)) {
  10286. allowed = flag;
  10287. }
  10288. }
  10289. return allowed == '+';
  10290. }
  10291. return -1;
  10292. }
  10293. #if !defined(_WIN32)
  10294. static int
  10295. set_uid_option(struct mg_context *ctx)
  10296. {
  10297. struct passwd *pw;
  10298. if (ctx) {
  10299. const char *uid = ctx->config[RUN_AS_USER];
  10300. int success = 0;
  10301. if (uid == NULL) {
  10302. success = 1;
  10303. } else {
  10304. if ((pw = getpwnam(uid)) == NULL) {
  10305. mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  10306. } else if (setgid(pw->pw_gid) == -1) {
  10307. mg_cry(fc(ctx),
  10308. "%s: setgid(%s): %s",
  10309. __func__,
  10310. uid,
  10311. strerror(errno));
  10312. } else if (setgroups(0, NULL)) {
  10313. mg_cry(fc(ctx),
  10314. "%s: setgroups(): %s",
  10315. __func__,
  10316. strerror(errno));
  10317. } else if (setuid(pw->pw_uid) == -1) {
  10318. mg_cry(fc(ctx),
  10319. "%s: setuid(%s): %s",
  10320. __func__,
  10321. uid,
  10322. strerror(errno));
  10323. } else {
  10324. success = 1;
  10325. }
  10326. }
  10327. return success;
  10328. }
  10329. return 0;
  10330. }
  10331. #endif /* !_WIN32 */
  10332. static void
  10333. tls_dtor(void *key)
  10334. {
  10335. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  10336. /* key == pthread_getspecific(sTlsKey); */
  10337. if (tls) {
  10338. if (tls->is_master == 2) {
  10339. tls->is_master = -3; /* Mark memory as dead */
  10340. mg_free(tls);
  10341. }
  10342. }
  10343. pthread_setspecific(sTlsKey, NULL);
  10344. }
  10345. #if !defined(NO_SSL)
  10346. static int ssl_use_pem_file(struct mg_context *ctx, const char *pem);
  10347. static const char *ssl_error(void);
  10348. static int
  10349. refresh_trust(struct mg_connection *conn)
  10350. {
  10351. static int reload_lock = 0;
  10352. static long int data_check = 0;
  10353. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  10354. struct stat cert_buf;
  10355. long int t;
  10356. char *pem;
  10357. int should_verify_peer;
  10358. if ((pem = conn->ctx->config[SSL_CERTIFICATE]) == NULL) {
  10359. /* If peem is NULL and conn->ctx->callbacks.init_ssl is not,
  10360. * refresh_trust still can not work. */
  10361. return 0;
  10362. }
  10363. t = data_check;
  10364. if (stat(pem, &cert_buf) != -1) {
  10365. t = (long int)cert_buf.st_mtime;
  10366. }
  10367. if (data_check != t) {
  10368. data_check = t;
  10369. should_verify_peer =
  10370. (conn->ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  10371. && (mg_strcasecmp(conn->ctx->config[SSL_DO_VERIFY_PEER], "yes")
  10372. == 0);
  10373. if (should_verify_peer) {
  10374. char *ca_path = conn->ctx->config[SSL_CA_PATH];
  10375. char *ca_file = conn->ctx->config[SSL_CA_FILE];
  10376. if (SSL_CTX_load_verify_locations(conn->ctx->ssl_ctx,
  10377. ca_file,
  10378. ca_path) != 1) {
  10379. mg_cry(fc(conn->ctx),
  10380. "SSL_CTX_load_verify_locations error: %s "
  10381. "ssl_verify_peer requires setting "
  10382. "either ssl_ca_path or ssl_ca_file. Is any of them "
  10383. "present in "
  10384. "the .conf file?",
  10385. ssl_error());
  10386. return 0;
  10387. }
  10388. }
  10389. if (1 == mg_atomic_inc(p_reload_lock)) {
  10390. if (ssl_use_pem_file(conn->ctx, pem) == 0) {
  10391. return 0;
  10392. }
  10393. *p_reload_lock = 0;
  10394. }
  10395. }
  10396. /* lock while cert is reloading */
  10397. while (*p_reload_lock) {
  10398. sleep(1);
  10399. }
  10400. return 1;
  10401. }
  10402. #ifdef OPENSSL_API_1_1
  10403. #else
  10404. static pthread_mutex_t *ssl_mutexes;
  10405. #endif /* OPENSSL_API_1_1 */
  10406. static int
  10407. sslize(struct mg_connection *conn,
  10408. SSL_CTX *s,
  10409. int (*func)(SSL *),
  10410. volatile int *stop_server)
  10411. {
  10412. int ret, err;
  10413. int short_trust;
  10414. unsigned i;
  10415. if (!conn) {
  10416. return 0;
  10417. }
  10418. short_trust =
  10419. (conn->ctx->config[SSL_SHORT_TRUST] != NULL)
  10420. && (mg_strcasecmp(conn->ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  10421. if (short_trust) {
  10422. int trust_ret = refresh_trust(conn);
  10423. if (!trust_ret) {
  10424. return trust_ret;
  10425. }
  10426. }
  10427. conn->ssl = SSL_new(s);
  10428. if (conn->ssl == NULL) {
  10429. return 0;
  10430. }
  10431. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  10432. if (ret != 1) {
  10433. err = SSL_get_error(conn->ssl, ret);
  10434. (void)err; /* TODO: set some error message */
  10435. SSL_free(conn->ssl);
  10436. conn->ssl = NULL;
  10437. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  10438. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  10439. #ifndef OPENSSL_API_1_1
  10440. ERR_remove_state(0);
  10441. #endif
  10442. return 0;
  10443. }
  10444. /* SSL functions may fail and require to be called again:
  10445. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  10446. * Here "func" could be SSL_connect or SSL_accept. */
  10447. for (i = 16; i <= 1024; i *= 2) {
  10448. ret = func(conn->ssl);
  10449. if (ret != 1) {
  10450. err = SSL_get_error(conn->ssl, ret);
  10451. if ((err == SSL_ERROR_WANT_CONNECT)
  10452. || (err == SSL_ERROR_WANT_ACCEPT)
  10453. || (err == SSL_ERROR_WANT_READ)
  10454. || (err == SSL_ERROR_WANT_WRITE)) {
  10455. /* Need to retry the function call "later".
  10456. * See https://linux.die.net/man/3/ssl_get_error
  10457. * This is typical for non-blocking sockets. */
  10458. if (*stop_server) {
  10459. /* Don't wait if the server is going to be stopped. */
  10460. break;
  10461. }
  10462. mg_sleep(i);
  10463. } else if (err == SSL_ERROR_SYSCALL) {
  10464. /* This is an IO error. Look at errno. */
  10465. err = errno;
  10466. /* TODO: set some error message */
  10467. break;
  10468. } else {
  10469. /* This is an SSL specific error */
  10470. /* TODO: set some error message */
  10471. break;
  10472. }
  10473. } else {
  10474. /* success */
  10475. break;
  10476. }
  10477. }
  10478. if (ret != 1) {
  10479. SSL_free(conn->ssl);
  10480. conn->ssl = NULL;
  10481. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  10482. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  10483. #ifndef OPENSSL_API_1_1
  10484. ERR_remove_state(0);
  10485. #endif
  10486. return 0;
  10487. }
  10488. return 1;
  10489. }
  10490. /* Return OpenSSL error message (from CRYPTO lib) */
  10491. static const char *
  10492. ssl_error(void)
  10493. {
  10494. unsigned long err;
  10495. err = ERR_get_error();
  10496. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  10497. }
  10498. static int
  10499. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  10500. {
  10501. int i;
  10502. const char hexdigit[] = "0123456789abcdef";
  10503. if (memlen <= 0 || buflen <= 0) {
  10504. return 0;
  10505. }
  10506. if (buflen < (3 * memlen)) {
  10507. return 0;
  10508. }
  10509. for (i = 0; i < memlen; i++) {
  10510. if (i > 0) {
  10511. buf[3 * i - 1] = ' ';
  10512. }
  10513. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  10514. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  10515. }
  10516. buf[3 * memlen - 1] = 0;
  10517. return 1;
  10518. }
  10519. static void
  10520. ssl_get_client_cert_info(struct mg_connection *conn)
  10521. {
  10522. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  10523. if (cert) {
  10524. char str_subject[1024];
  10525. char str_issuer[1024];
  10526. char str_finger[1024];
  10527. unsigned char buf[256];
  10528. char *str_serial = NULL;
  10529. unsigned int ulen;
  10530. /* Handle to algorithm used for fingerprint */
  10531. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  10532. /* Get Subject and issuer */
  10533. X509_NAME *subj = X509_get_subject_name(cert);
  10534. X509_NAME *iss = X509_get_issuer_name(cert);
  10535. /* Get serial number */
  10536. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  10537. /* Translate serial number to a hex string */
  10538. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  10539. str_serial = BN_bn2hex(serial_bn);
  10540. BN_free(serial_bn);
  10541. /* Translate subject and issuer to a string */
  10542. (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
  10543. (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
  10544. /* Calculate SHA1 fingerprint and store as a hex string */
  10545. ulen = 0;
  10546. ASN1_digest((int (*)())i2d_X509, digest, (char *)cert, buf, &ulen);
  10547. if (!hexdump2string(
  10548. buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
  10549. *str_finger = 0;
  10550. }
  10551. conn->request_info.client_cert =
  10552. (struct client_cert *)mg_malloc(sizeof(struct client_cert));
  10553. if (conn->request_info.client_cert) {
  10554. conn->request_info.client_cert->subject = mg_strdup(str_subject);
  10555. conn->request_info.client_cert->issuer = mg_strdup(str_issuer);
  10556. conn->request_info.client_cert->serial = mg_strdup(str_serial);
  10557. conn->request_info.client_cert->finger = mg_strdup(str_finger);
  10558. } else {
  10559. /* TODO: write some OOM message */
  10560. }
  10561. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  10562. * see https://linux.die.net/man/3/bn_bn2hex */
  10563. OPENSSL_free(str_serial);
  10564. /* Free certificate memory */
  10565. X509_free(cert);
  10566. }
  10567. }
  10568. #ifdef OPENSSL_API_1_1
  10569. #else
  10570. static void
  10571. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  10572. {
  10573. (void)line;
  10574. (void)file;
  10575. if (mode & 1) {
  10576. /* 1 is CRYPTO_LOCK */
  10577. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  10578. } else {
  10579. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  10580. }
  10581. }
  10582. #endif /* OPENSSL_API_1_1 */
  10583. #if !defined(NO_SSL_DL)
  10584. static void *
  10585. load_dll(struct mg_context *ctx, const char *dll_name, struct ssl_func *sw)
  10586. {
  10587. union {
  10588. void *p;
  10589. void (*fp)(void);
  10590. } u;
  10591. void *dll_handle;
  10592. struct ssl_func *fp;
  10593. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  10594. mg_cry(fc(ctx), "%s: cannot load %s", __func__, dll_name);
  10595. return NULL;
  10596. }
  10597. for (fp = sw; fp->name != NULL; fp++) {
  10598. #ifdef _WIN32
  10599. /* GetProcAddress() returns pointer to function */
  10600. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  10601. #else
  10602. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  10603. * pointers to function pointers. We need to use a union to make a
  10604. * cast. */
  10605. u.p = dlsym(dll_handle, fp->name);
  10606. #endif /* _WIN32 */
  10607. if (u.fp == NULL) {
  10608. mg_cry(fc(ctx),
  10609. "%s: %s: cannot find %s",
  10610. __func__,
  10611. dll_name,
  10612. fp->name);
  10613. dlclose(dll_handle);
  10614. return NULL;
  10615. } else {
  10616. fp->ptr = u.fp;
  10617. }
  10618. }
  10619. return dll_handle;
  10620. }
  10621. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  10622. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  10623. #endif /* NO_SSL_DL */
  10624. #if defined(SSL_ALREADY_INITIALIZED)
  10625. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  10626. #else
  10627. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  10628. #endif
  10629. static int
  10630. initialize_ssl(struct mg_context *ctx)
  10631. {
  10632. #ifdef OPENSSL_API_1_1
  10633. #if !defined(NO_SSL_DL)
  10634. if (!cryptolib_dll_handle) {
  10635. cryptolib_dll_handle = load_dll(ctx, CRYPTO_LIB, crypto_sw);
  10636. if (!cryptolib_dll_handle) {
  10637. return 0;
  10638. }
  10639. }
  10640. #else
  10641. (void)ctx;
  10642. #endif /* NO_SSL_DL */
  10643. if (mg_atomic_inc(&cryptolib_users) > 1) {
  10644. return 1;
  10645. }
  10646. #else
  10647. int i;
  10648. size_t size;
  10649. #if !defined(NO_SSL_DL)
  10650. if (!cryptolib_dll_handle) {
  10651. cryptolib_dll_handle = load_dll(ctx, CRYPTO_LIB, crypto_sw);
  10652. if (!cryptolib_dll_handle) {
  10653. return 0;
  10654. }
  10655. }
  10656. #else
  10657. (void)ctx;
  10658. #endif /* NO_SSL_DL */
  10659. if (mg_atomic_inc(&cryptolib_users) > 1) {
  10660. return 1;
  10661. }
  10662. /* Initialize locking callbacks, needed for thread safety.
  10663. * http://www.openssl.org/support/faq.html#PROG1
  10664. */
  10665. i = CRYPTO_num_locks();
  10666. if (i < 0) {
  10667. i = 0;
  10668. }
  10669. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  10670. if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  10671. mg_cry(fc(ctx),
  10672. "%s: cannot allocate mutexes: %s",
  10673. __func__,
  10674. ssl_error());
  10675. return 0;
  10676. }
  10677. for (i = 0; i < CRYPTO_num_locks(); i++) {
  10678. pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr);
  10679. }
  10680. CRYPTO_set_locking_callback(&ssl_locking_callback);
  10681. CRYPTO_set_id_callback(&mg_current_thread_id);
  10682. #endif /* OPENSSL_API_1_1 */
  10683. return 1;
  10684. }
  10685. static int
  10686. ssl_use_pem_file(struct mg_context *ctx, const char *pem)
  10687. {
  10688. if (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0) {
  10689. mg_cry(fc(ctx),
  10690. "%s: cannot open certificate file %s: %s",
  10691. __func__,
  10692. pem,
  10693. ssl_error());
  10694. return 0;
  10695. }
  10696. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  10697. if (SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0) {
  10698. mg_cry(fc(ctx),
  10699. "%s: cannot open private key file %s: %s",
  10700. __func__,
  10701. pem,
  10702. ssl_error());
  10703. return 0;
  10704. }
  10705. if (SSL_CTX_check_private_key(ctx->ssl_ctx) == 0) {
  10706. mg_cry(fc(ctx),
  10707. "%s: certificate and private key do not match: %s",
  10708. __func__,
  10709. pem);
  10710. return 0;
  10711. }
  10712. if (SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem) == 0) {
  10713. mg_cry(fc(ctx),
  10714. "%s: cannot use certificate chain file %s: %s",
  10715. __func__,
  10716. pem,
  10717. ssl_error());
  10718. return 0;
  10719. }
  10720. return 1;
  10721. }
  10722. #ifdef OPENSSL_API_1_1
  10723. static unsigned long
  10724. ssl_get_protocol(int version_id)
  10725. {
  10726. long unsigned ret = SSL_OP_ALL;
  10727. if (version_id > 0)
  10728. ret |= SSL_OP_NO_SSLv2;
  10729. if (version_id > 1)
  10730. ret |= SSL_OP_NO_SSLv3;
  10731. if (version_id > 2)
  10732. ret |= SSL_OP_NO_TLSv1;
  10733. if (version_id > 3)
  10734. ret |= SSL_OP_NO_TLSv1_1;
  10735. return ret;
  10736. }
  10737. #else
  10738. static long
  10739. ssl_get_protocol(int version_id)
  10740. {
  10741. long ret = SSL_OP_ALL;
  10742. if (version_id > 0)
  10743. ret |= SSL_OP_NO_SSLv2;
  10744. if (version_id > 1)
  10745. ret |= SSL_OP_NO_SSLv3;
  10746. if (version_id > 2)
  10747. ret |= SSL_OP_NO_TLSv1;
  10748. if (version_id > 3)
  10749. ret |= SSL_OP_NO_TLSv1_1;
  10750. return ret;
  10751. }
  10752. #endif /* OPENSSL_API_1_1 */
  10753. /* Dynamically load SSL library. Set up ctx->ssl_ctx pointer. */
  10754. static int
  10755. set_ssl_option(struct mg_context *ctx)
  10756. {
  10757. const char *pem;
  10758. int callback_ret;
  10759. int should_verify_peer;
  10760. const char *ca_path;
  10761. const char *ca_file;
  10762. int use_default_verify_paths;
  10763. int verify_depth;
  10764. time_t now_rt = time(NULL);
  10765. struct timespec now_mt;
  10766. md5_byte_t ssl_context_id[16];
  10767. md5_state_t md5state;
  10768. int protocol_ver;
  10769. /* If PEM file is not specified and the init_ssl callback
  10770. * is not specified, skip SSL initialization. */
  10771. if (!ctx) {
  10772. return 0;
  10773. }
  10774. if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL
  10775. && ctx->callbacks.init_ssl == NULL) {
  10776. return 1;
  10777. }
  10778. if (!initialize_ssl(ctx)) {
  10779. return 0;
  10780. }
  10781. #if !defined(NO_SSL_DL)
  10782. if (!ssllib_dll_handle) {
  10783. ssllib_dll_handle = load_dll(ctx, SSL_LIB, ssl_sw);
  10784. if (!ssllib_dll_handle) {
  10785. return 0;
  10786. }
  10787. }
  10788. #endif /* NO_SSL_DL */
  10789. #ifdef OPENSSL_API_1_1
  10790. /* Initialize SSL library */
  10791. OPENSSL_init_ssl(0, NULL);
  10792. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  10793. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  10794. NULL);
  10795. if ((ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  10796. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  10797. return 0;
  10798. }
  10799. #else
  10800. /* Initialize SSL library */
  10801. SSL_library_init();
  10802. SSL_load_error_strings();
  10803. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  10804. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  10805. return 0;
  10806. }
  10807. #endif /* OPENSSL_API_1_1 */
  10808. SSL_CTX_clear_options(ctx->ssl_ctx,
  10809. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  10810. | SSL_OP_NO_TLSv1_1);
  10811. protocol_ver = atoi(ctx->config[SSL_PROTOCOL_VERSION]);
  10812. SSL_CTX_set_options(ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  10813. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  10814. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  10815. #if !defined(NO_SSL_DL)
  10816. SSL_CTX_set_ecdh_auto(ctx->ssl_ctx, 1);
  10817. #endif /* NO_SSL_DL */
  10818. /* If a callback has been specified, call it. */
  10819. callback_ret =
  10820. (ctx->callbacks.init_ssl == NULL)
  10821. ? 0
  10822. : (ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data));
  10823. /* If callback returns 0, civetweb sets up the SSL certificate.
  10824. * If it returns 1, civetweb assumes the calback already did this.
  10825. * If it returns -1, initializing ssl fails. */
  10826. if (callback_ret < 0) {
  10827. mg_cry(fc(ctx), "SSL callback returned error: %i", callback_ret);
  10828. return 0;
  10829. }
  10830. if (callback_ret > 0) {
  10831. if (pem != NULL) {
  10832. (void)SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
  10833. }
  10834. return 1;
  10835. }
  10836. /* Use some UID as session context ID. */
  10837. md5_init(&md5state);
  10838. md5_append(&md5state, (const md5_byte_t *)&now_rt, sizeof(now_rt));
  10839. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  10840. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  10841. md5_append(&md5state,
  10842. (const md5_byte_t *)ctx->config[LISTENING_PORTS],
  10843. strlen(ctx->config[LISTENING_PORTS]));
  10844. md5_append(&md5state, (const md5_byte_t *)ctx, sizeof(*ctx));
  10845. md5_finish(&md5state, ssl_context_id);
  10846. SSL_CTX_set_session_id_context(ctx->ssl_ctx,
  10847. (const unsigned char *)&ssl_context_id,
  10848. sizeof(ssl_context_id));
  10849. if (pem != NULL) {
  10850. if (!ssl_use_pem_file(ctx, pem)) {
  10851. return 0;
  10852. }
  10853. }
  10854. should_verify_peer =
  10855. (ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  10856. && (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0);
  10857. use_default_verify_paths =
  10858. (ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  10859. && (mg_strcasecmp(ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes") == 0);
  10860. if (should_verify_peer) {
  10861. ca_path = ctx->config[SSL_CA_PATH];
  10862. ca_file = ctx->config[SSL_CA_FILE];
  10863. if (SSL_CTX_load_verify_locations(ctx->ssl_ctx, ca_file, ca_path)
  10864. != 1) {
  10865. mg_cry(fc(ctx),
  10866. "SSL_CTX_load_verify_locations error: %s "
  10867. "ssl_verify_peer requires setting "
  10868. "either ssl_ca_path or ssl_ca_file. Is any of them "
  10869. "present in "
  10870. "the .conf file?",
  10871. ssl_error());
  10872. return 0;
  10873. }
  10874. SSL_CTX_set_verify(ctx->ssl_ctx,
  10875. SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  10876. NULL);
  10877. if (use_default_verify_paths
  10878. && SSL_CTX_set_default_verify_paths(ctx->ssl_ctx) != 1) {
  10879. mg_cry(fc(ctx),
  10880. "SSL_CTX_set_default_verify_paths error: %s",
  10881. ssl_error());
  10882. return 0;
  10883. }
  10884. if (ctx->config[SSL_VERIFY_DEPTH]) {
  10885. verify_depth = atoi(ctx->config[SSL_VERIFY_DEPTH]);
  10886. SSL_CTX_set_verify_depth(ctx->ssl_ctx, verify_depth);
  10887. }
  10888. }
  10889. if (ctx->config[SSL_CIPHER_LIST] != NULL) {
  10890. if (SSL_CTX_set_cipher_list(ctx->ssl_ctx, ctx->config[SSL_CIPHER_LIST])
  10891. != 1) {
  10892. mg_cry(fc(ctx), "SSL_CTX_set_cipher_list error: %s", ssl_error());
  10893. }
  10894. }
  10895. return 1;
  10896. }
  10897. static void
  10898. uninitialize_ssl(struct mg_context *ctx)
  10899. {
  10900. #ifdef OPENSSL_API_1_1
  10901. (void)ctx;
  10902. if (mg_atomic_dec(&cryptolib_users) == 0) {
  10903. /* Shutdown according to
  10904. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  10905. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  10906. */
  10907. CONF_modules_unload(1);
  10908. #else
  10909. int i;
  10910. (void)ctx;
  10911. if (mg_atomic_dec(&cryptolib_users) == 0) {
  10912. /* Shutdown according to
  10913. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  10914. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  10915. */
  10916. CRYPTO_set_locking_callback(NULL);
  10917. CRYPTO_set_id_callback(NULL);
  10918. ENGINE_cleanup();
  10919. CONF_modules_unload(1);
  10920. ERR_free_strings();
  10921. EVP_cleanup();
  10922. CRYPTO_cleanup_all_ex_data();
  10923. ERR_remove_state(0);
  10924. for (i = 0; i < CRYPTO_num_locks(); i++) {
  10925. pthread_mutex_destroy(&ssl_mutexes[i]);
  10926. }
  10927. mg_free(ssl_mutexes);
  10928. ssl_mutexes = NULL;
  10929. #endif /* OPENSSL_API_1_1 */
  10930. }
  10931. }
  10932. #endif /* !NO_SSL */
  10933. static int
  10934. set_gpass_option(struct mg_context *ctx)
  10935. {
  10936. if (ctx) {
  10937. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10938. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  10939. if (path != NULL && !mg_stat(fc(ctx), path, &file.stat)) {
  10940. mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  10941. return 0;
  10942. }
  10943. return 1;
  10944. }
  10945. return 0;
  10946. }
  10947. static int
  10948. set_acl_option(struct mg_context *ctx)
  10949. {
  10950. return check_acl(ctx, (uint32_t)0x7f000001UL) != -1;
  10951. }
  10952. static void
  10953. reset_per_request_attributes(struct mg_connection *conn)
  10954. {
  10955. if (!conn) {
  10956. return;
  10957. }
  10958. conn->path_info = NULL;
  10959. conn->num_bytes_sent = conn->consumed_content = 0;
  10960. conn->status_code = -1;
  10961. conn->is_chunked = 0;
  10962. conn->must_close = conn->request_len = conn->throttle = 0;
  10963. conn->request_info.content_length = -1;
  10964. conn->request_info.remote_user = NULL;
  10965. conn->request_info.request_method = NULL;
  10966. conn->request_info.request_uri = NULL;
  10967. conn->request_info.local_uri = NULL;
  10968. conn->request_info.uri = NULL; /* TODO: cleanup uri,
  10969. * local_uri and request_uri */
  10970. conn->request_info.http_version = NULL;
  10971. conn->request_info.num_headers = 0;
  10972. conn->data_len = 0;
  10973. conn->chunk_remainder = 0;
  10974. }
  10975. #if 0
  10976. /* Note: set_sock_timeout is not required for non-blocking sockets.
  10977. * Leave this function here (commented out) for reference until
  10978. * CivetWeb 1.9 is tested, and the tests confirme this function is
  10979. * no longer required.
  10980. */
  10981. static int
  10982. set_sock_timeout(SOCKET sock, int milliseconds)
  10983. {
  10984. int r0 = 0, r1, r2;
  10985. #ifdef _WIN32
  10986. /* Windows specific */
  10987. DWORD tv = (DWORD)milliseconds;
  10988. #else
  10989. /* Linux, ... (not Windows) */
  10990. struct timeval tv;
  10991. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  10992. * max. time waiting for the acknowledged of TCP data before the connection
  10993. * will be forcefully closed and ETIMEDOUT is returned to the application.
  10994. * If this option is not set, the default timeout of 20-30 minutes is used.
  10995. */
  10996. /* #define TCP_USER_TIMEOUT (18) */
  10997. #if defined(TCP_USER_TIMEOUT)
  10998. unsigned int uto = (unsigned int)milliseconds;
  10999. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  11000. #endif
  11001. memset(&tv, 0, sizeof(tv));
  11002. tv.tv_sec = milliseconds / 1000;
  11003. tv.tv_usec = (milliseconds * 1000) % 1000000;
  11004. #endif /* _WIN32 */
  11005. r1 = setsockopt(
  11006. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  11007. r2 = setsockopt(
  11008. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  11009. return r0 || r1 || r2;
  11010. }
  11011. #endif
  11012. static int
  11013. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  11014. {
  11015. if (setsockopt(sock,
  11016. IPPROTO_TCP,
  11017. TCP_NODELAY,
  11018. (SOCK_OPT_TYPE)&nodelay_on,
  11019. sizeof(nodelay_on)) != 0) {
  11020. /* Error */
  11021. return 1;
  11022. }
  11023. /* OK */
  11024. return 0;
  11025. }
  11026. static void
  11027. close_socket_gracefully(struct mg_connection *conn)
  11028. {
  11029. #if defined(_WIN32)
  11030. char buf[MG_BUF_LEN];
  11031. int n;
  11032. #endif
  11033. struct linger linger;
  11034. int error_code = 0;
  11035. int linger_timeout = -2;
  11036. socklen_t opt_len = sizeof(error_code);
  11037. if (!conn) {
  11038. return;
  11039. }
  11040. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  11041. * "Note that enabling a nonzero timeout on a nonblocking socket
  11042. * is not recommended.", so set it to blocking now */
  11043. set_blocking_mode(conn->client.sock, 1);
  11044. /* Send FIN to the client */
  11045. shutdown(conn->client.sock, SHUTDOWN_WR);
  11046. #if defined(_WIN32)
  11047. /* Read and discard pending incoming data. If we do not do that and
  11048. * close
  11049. * the socket, the data in the send buffer may be discarded. This
  11050. * behaviour is seen on Windows, when client keeps sending data
  11051. * when server decides to close the connection; then when client
  11052. * does recv() it gets no data back. */
  11053. do {
  11054. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  11055. } while (n > 0);
  11056. #endif
  11057. if (conn->ctx->config[LINGER_TIMEOUT]) {
  11058. linger_timeout = atoi(conn->ctx->config[LINGER_TIMEOUT]);
  11059. }
  11060. /* Set linger option according to configuration */
  11061. if (linger_timeout >= 0) {
  11062. /* Set linger option to avoid socket hanging out after close. This
  11063. * prevent ephemeral port exhaust problem under high QPS. */
  11064. linger.l_onoff = 1;
  11065. #if defined(_MSC_VER)
  11066. #pragma warning(push)
  11067. #pragma warning(disable : 4244)
  11068. #endif
  11069. linger.l_linger = (linger_timeout + 999) / 1000;
  11070. #if defined(_MSC_VER)
  11071. #pragma warning(pop)
  11072. #endif
  11073. } else {
  11074. linger.l_onoff = 0;
  11075. linger.l_linger = 0;
  11076. }
  11077. if (linger_timeout < -1) {
  11078. /* Default: don't configure any linger */
  11079. } else if (getsockopt(conn->client.sock,
  11080. SOL_SOCKET,
  11081. SO_ERROR,
  11082. (char *)&error_code,
  11083. &opt_len) != 0) {
  11084. /* Cannot determine if socket is already closed. This should
  11085. * not occur and never did in a test. Log an error message
  11086. * and continue. */
  11087. mg_cry(conn,
  11088. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  11089. __func__,
  11090. strerror(ERRNO));
  11091. } else if (error_code == ECONNRESET) {
  11092. /* Socket already closed by client/peer, close socket without linger */
  11093. } else {
  11094. /* Set linger timeout */
  11095. if (setsockopt(conn->client.sock,
  11096. SOL_SOCKET,
  11097. SO_LINGER,
  11098. (char *)&linger,
  11099. sizeof(linger)) != 0) {
  11100. mg_cry(conn,
  11101. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  11102. __func__,
  11103. linger.l_onoff,
  11104. linger.l_linger,
  11105. strerror(ERRNO));
  11106. }
  11107. }
  11108. /* Now we know that our FIN is ACK-ed, safe to close */
  11109. closesocket(conn->client.sock);
  11110. conn->client.sock = INVALID_SOCKET;
  11111. }
  11112. static void
  11113. close_connection(struct mg_connection *conn)
  11114. {
  11115. if (!conn || !conn->ctx) {
  11116. return;
  11117. }
  11118. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  11119. if (conn->lua_websocket_state) {
  11120. lua_websocket_close(conn, conn->lua_websocket_state);
  11121. conn->lua_websocket_state = NULL;
  11122. }
  11123. #endif
  11124. /* call the connection_close callback if assigned */
  11125. if ((conn->ctx->callbacks.connection_close != NULL)
  11126. && (conn->ctx->context_type == 1)) {
  11127. conn->ctx->callbacks.connection_close(conn);
  11128. }
  11129. mg_lock_connection(conn);
  11130. conn->must_close = 1;
  11131. #ifndef NO_SSL
  11132. if (conn->ssl != NULL) {
  11133. /* Run SSL_shutdown twice to ensure completly close SSL connection
  11134. */
  11135. SSL_shutdown(conn->ssl);
  11136. SSL_free(conn->ssl);
  11137. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  11138. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  11139. #ifndef OPENSSL_API_1_1
  11140. ERR_remove_state(0);
  11141. #endif
  11142. conn->ssl = NULL;
  11143. }
  11144. #endif
  11145. if (conn->client.sock != INVALID_SOCKET) {
  11146. close_socket_gracefully(conn);
  11147. conn->client.sock = INVALID_SOCKET;
  11148. }
  11149. mg_unlock_connection(conn);
  11150. }
  11151. void
  11152. mg_close_connection(struct mg_connection *conn)
  11153. {
  11154. struct mg_context *client_ctx = NULL;
  11155. if (conn == NULL) {
  11156. return;
  11157. }
  11158. #if defined(USE_WEBSOCKET)
  11159. if (conn->ctx->context_type == 2) {
  11160. unsigned int i;
  11161. /* ws/wss client */
  11162. client_ctx = conn->ctx;
  11163. /* client context: loops must end */
  11164. conn->ctx->stop_flag = 1;
  11165. /* We need to get the client thread out of the select/recv call here. */
  11166. /* Since we use a sleep quantum of some seconds to check for recv
  11167. * timeouts, we will just wait a few seconds in mg_join_thread. */
  11168. /* join worker thread */
  11169. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  11170. if (client_ctx->worker_threadids[i] != 0) {
  11171. mg_join_thread(client_ctx->worker_threadids[i]);
  11172. }
  11173. }
  11174. }
  11175. #else
  11176. (void)client_ctx;
  11177. #endif
  11178. close_connection(conn);
  11179. #ifndef NO_SSL
  11180. if (conn->client_ssl_ctx != NULL) {
  11181. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  11182. }
  11183. #endif
  11184. if (client_ctx != NULL) {
  11185. /* free context */
  11186. mg_free(client_ctx->worker_threadids);
  11187. mg_free(client_ctx);
  11188. (void)pthread_mutex_destroy(&conn->mutex);
  11189. mg_free(conn);
  11190. }
  11191. }
  11192. static struct mg_connection *
  11193. mg_connect_client_impl(const struct mg_client_options *client_options,
  11194. int use_ssl,
  11195. char *ebuf,
  11196. size_t ebuf_len)
  11197. {
  11198. static struct mg_context fake_ctx;
  11199. struct mg_connection *conn = NULL;
  11200. SOCKET sock;
  11201. union usa sa;
  11202. if (!connect_socket(&fake_ctx,
  11203. client_options->host,
  11204. client_options->port,
  11205. use_ssl,
  11206. ebuf,
  11207. ebuf_len,
  11208. &sock,
  11209. &sa)) {
  11210. ;
  11211. } else if ((conn = (struct mg_connection *)
  11212. mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) {
  11213. mg_snprintf(NULL,
  11214. NULL, /* No truncation check for ebuf */
  11215. ebuf,
  11216. ebuf_len,
  11217. "calloc(): %s",
  11218. strerror(ERRNO));
  11219. closesocket(sock);
  11220. #ifndef NO_SSL
  11221. #ifdef OPENSSL_API_1_1
  11222. } else if (use_ssl
  11223. && (conn->client_ssl_ctx = SSL_CTX_new(TLS_client_method()))
  11224. == NULL) {
  11225. mg_snprintf(NULL,
  11226. NULL, /* No truncation check for ebuf */
  11227. ebuf,
  11228. ebuf_len,
  11229. "SSL_CTX_new error");
  11230. closesocket(sock);
  11231. mg_free(conn);
  11232. conn = NULL;
  11233. #else
  11234. } else if (use_ssl
  11235. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  11236. == NULL) {
  11237. mg_snprintf(NULL,
  11238. NULL, /* No truncation check for ebuf */
  11239. ebuf,
  11240. ebuf_len,
  11241. "SSL_CTX_new error");
  11242. closesocket(sock);
  11243. mg_free(conn);
  11244. conn = NULL;
  11245. #endif /* OPENSSL_API_1_1 */
  11246. #endif /* NO_SSL */
  11247. } else {
  11248. #ifdef USE_IPV6
  11249. socklen_t len = (sa.sa.sa_family == AF_INET)
  11250. ? sizeof(conn->client.rsa.sin)
  11251. : sizeof(conn->client.rsa.sin6);
  11252. struct sockaddr *psa =
  11253. (sa.sa.sa_family == AF_INET)
  11254. ? (struct sockaddr *)&(conn->client.rsa.sin)
  11255. : (struct sockaddr *)&(conn->client.rsa.sin6);
  11256. #else
  11257. socklen_t len = sizeof(conn->client.rsa.sin);
  11258. struct sockaddr *psa = (struct sockaddr *)&(conn->client.rsa.sin);
  11259. #endif
  11260. conn->buf_size = MAX_REQUEST_SIZE;
  11261. conn->buf = (char *)(conn + 1);
  11262. conn->ctx = &fake_ctx;
  11263. conn->client.sock = sock;
  11264. conn->client.lsa = sa;
  11265. if (getsockname(sock, psa, &len) != 0) {
  11266. mg_cry(conn,
  11267. "%s: getsockname() failed: %s",
  11268. __func__,
  11269. strerror(ERRNO));
  11270. }
  11271. conn->client.is_ssl = use_ssl ? 1 : 0;
  11272. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  11273. #ifndef NO_SSL
  11274. if (use_ssl) {
  11275. fake_ctx.ssl_ctx = conn->client_ssl_ctx;
  11276. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  11277. * SSL_CTX_set_verify call is needed to switch off server
  11278. * certificate checking, which is off by default in OpenSSL and
  11279. * on in yaSSL. */
  11280. /* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  11281. * SSL_VERIFY_PEER, verify_ssl_server); */
  11282. if (client_options->client_cert) {
  11283. if (!ssl_use_pem_file(&fake_ctx, client_options->client_cert)) {
  11284. mg_snprintf(NULL,
  11285. NULL, /* No truncation check for ebuf */
  11286. ebuf,
  11287. ebuf_len,
  11288. "Can not use SSL client certificate");
  11289. SSL_CTX_free(conn->client_ssl_ctx);
  11290. closesocket(sock);
  11291. mg_free(conn);
  11292. conn = NULL;
  11293. }
  11294. }
  11295. if (client_options->server_cert) {
  11296. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  11297. client_options->server_cert,
  11298. NULL);
  11299. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  11300. } else {
  11301. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  11302. }
  11303. if (!sslize(conn,
  11304. conn->client_ssl_ctx,
  11305. SSL_connect,
  11306. &(conn->ctx->stop_flag))) {
  11307. mg_snprintf(NULL,
  11308. NULL, /* No truncation check for ebuf */
  11309. ebuf,
  11310. ebuf_len,
  11311. "SSL connection error");
  11312. SSL_CTX_free(conn->client_ssl_ctx);
  11313. closesocket(sock);
  11314. mg_free(conn);
  11315. conn = NULL;
  11316. }
  11317. }
  11318. #endif
  11319. }
  11320. if (conn) {
  11321. set_blocking_mode(sock, 0);
  11322. }
  11323. return conn;
  11324. }
  11325. CIVETWEB_API struct mg_connection *
  11326. mg_connect_client_secure(const struct mg_client_options *client_options,
  11327. char *error_buffer,
  11328. size_t error_buffer_size)
  11329. {
  11330. return mg_connect_client_impl(client_options,
  11331. 1,
  11332. error_buffer,
  11333. error_buffer_size);
  11334. }
  11335. struct mg_connection *
  11336. mg_connect_client(const char *host,
  11337. int port,
  11338. int use_ssl,
  11339. char *error_buffer,
  11340. size_t error_buffer_size)
  11341. {
  11342. struct mg_client_options opts;
  11343. memset(&opts, 0, sizeof(opts));
  11344. opts.host = host;
  11345. opts.port = port;
  11346. return mg_connect_client_impl(&opts,
  11347. use_ssl,
  11348. error_buffer,
  11349. error_buffer_size);
  11350. }
  11351. static const struct {
  11352. const char *proto;
  11353. size_t proto_len;
  11354. unsigned default_port;
  11355. } abs_uri_protocols[] = {{"http://", 7, 80},
  11356. {"https://", 8, 443},
  11357. {"ws://", 5, 80},
  11358. {"wss://", 6, 443},
  11359. {NULL, 0, 0}};
  11360. /* Check if the uri is valid.
  11361. * return 0 for invalid uri,
  11362. * return 1 for *,
  11363. * return 2 for relative uri,
  11364. * return 3 for absolute uri without port,
  11365. * return 4 for absolute uri with port */
  11366. static int
  11367. get_uri_type(const char *uri)
  11368. {
  11369. int i;
  11370. char *hostend, *portbegin, *portend;
  11371. unsigned long port;
  11372. /* According to the HTTP standard
  11373. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  11374. * URI can be an asterisk (*) or should start with slash (relative uri),
  11375. * or it should start with the protocol (absolute uri). */
  11376. if (uri[0] == '*' && uri[1] == '\0') {
  11377. /* asterisk */
  11378. return 1;
  11379. }
  11380. /* Valid URIs according to RFC 3986
  11381. * (https://www.ietf.org/rfc/rfc3986.txt)
  11382. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  11383. * and unreserved characters A-Z a-z 0-9 and -._~
  11384. * and % encoded symbols.
  11385. */
  11386. for (i = 0; uri[i] != 0; i++) {
  11387. if (uri[i] < 33) {
  11388. /* control characters and spaces are invalid */
  11389. return 0;
  11390. }
  11391. if (uri[i] > 126) {
  11392. /* non-ascii characters must be % encoded */
  11393. return 0;
  11394. } else {
  11395. switch (uri[i]) {
  11396. case '"': /* 34 */
  11397. case '<': /* 60 */
  11398. case '>': /* 62 */
  11399. case '\\': /* 92 */
  11400. case '^': /* 94 */
  11401. case '`': /* 96 */
  11402. case '{': /* 123 */
  11403. case '|': /* 124 */
  11404. case '}': /* 125 */
  11405. return 0;
  11406. default:
  11407. /* character is ok */
  11408. break;
  11409. }
  11410. }
  11411. }
  11412. /* A relative uri starts with a / character */
  11413. if (uri[0] == '/') {
  11414. /* relative uri */
  11415. return 2;
  11416. }
  11417. /* It could be an absolute uri: */
  11418. /* This function only checks if the uri is valid, not if it is
  11419. * addressing the current server. So civetweb can also be used
  11420. * as a proxy server. */
  11421. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  11422. if (mg_strncasecmp(uri,
  11423. abs_uri_protocols[i].proto,
  11424. abs_uri_protocols[i].proto_len) == 0) {
  11425. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  11426. if (!hostend) {
  11427. return 0;
  11428. }
  11429. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  11430. if (!portbegin) {
  11431. return 3;
  11432. }
  11433. port = strtoul(portbegin + 1, &portend, 10);
  11434. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  11435. return 0;
  11436. }
  11437. return 4;
  11438. }
  11439. }
  11440. return 0;
  11441. }
  11442. /* Return NULL or the relative uri at the current server */
  11443. static const char *
  11444. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  11445. {
  11446. const char *server_domain;
  11447. size_t server_domain_len;
  11448. size_t request_domain_len = 0;
  11449. unsigned long port = 0;
  11450. int i, auth_domain_check_enabled;
  11451. const char *hostbegin = NULL;
  11452. const char *hostend = NULL;
  11453. const char *portbegin;
  11454. char *portend;
  11455. auth_domain_check_enabled =
  11456. !strcmp(conn->ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  11457. /* DNS is case insensitive, so use case insensitive string compare here
  11458. */
  11459. server_domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  11460. if (!server_domain && auth_domain_check_enabled) {
  11461. return 0;
  11462. }
  11463. server_domain_len = strlen(server_domain);
  11464. if (!server_domain_len) {
  11465. return 0;
  11466. }
  11467. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  11468. if (mg_strncasecmp(uri,
  11469. abs_uri_protocols[i].proto,
  11470. abs_uri_protocols[i].proto_len) == 0) {
  11471. hostbegin = uri + abs_uri_protocols[i].proto_len;
  11472. hostend = strchr(hostbegin, '/');
  11473. if (!hostend) {
  11474. return 0;
  11475. }
  11476. portbegin = strchr(hostbegin, ':');
  11477. if ((!portbegin) || (portbegin > hostend)) {
  11478. port = abs_uri_protocols[i].default_port;
  11479. request_domain_len = (size_t)(hostend - hostbegin);
  11480. } else {
  11481. port = strtoul(portbegin + 1, &portend, 10);
  11482. if ((portend != hostend) || (port <= 0)
  11483. || !is_valid_port(port)) {
  11484. return 0;
  11485. }
  11486. request_domain_len = (size_t)(portbegin - hostbegin);
  11487. }
  11488. /* protocol found, port set */
  11489. break;
  11490. }
  11491. }
  11492. if (!port) {
  11493. /* port remains 0 if the protocol is not found */
  11494. return 0;
  11495. }
  11496. /* Check if the request is directed to a different server. */
  11497. /* First check if the port is the same (IPv4 and IPv6). */
  11498. #if defined(USE_IPV6)
  11499. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  11500. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  11501. /* Request is directed to a different port */
  11502. return 0;
  11503. }
  11504. } else
  11505. #endif
  11506. {
  11507. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  11508. /* Request is directed to a different port */
  11509. return 0;
  11510. }
  11511. }
  11512. /* Finally check if the server corresponds to the authentication
  11513. * domain of the server (the server domain).
  11514. * Allow full matches (like http://mydomain.com/path/file.ext), and
  11515. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  11516. * but do not allow substrings (like http://notmydomain.com/path/file.ext
  11517. * or http://mydomain.com.fake/path/file.ext).
  11518. */
  11519. if (auth_domain_check_enabled) {
  11520. if ((request_domain_len == server_domain_len)
  11521. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  11522. /* Request is directed to this server - full name match. */
  11523. } else {
  11524. if (request_domain_len < (server_domain_len + 2)) {
  11525. /* Request is directed to another server: The server name is
  11526. * longer
  11527. * than
  11528. * the request name. Drop this case here to avoid overflows in
  11529. * the
  11530. * following checks. */
  11531. return 0;
  11532. }
  11533. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  11534. /* Request is directed to another server: It could be a
  11535. * substring
  11536. * like notmyserver.com */
  11537. return 0;
  11538. }
  11539. if (0 != memcmp(server_domain,
  11540. hostbegin + request_domain_len - server_domain_len,
  11541. server_domain_len)) {
  11542. /* Request is directed to another server:
  11543. * The server name is different. */
  11544. return 0;
  11545. }
  11546. }
  11547. }
  11548. return hostend;
  11549. }
  11550. static int
  11551. getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  11552. {
  11553. const char *cl;
  11554. if (ebuf_len > 0) {
  11555. ebuf[0] = '\0';
  11556. }
  11557. *err = 0;
  11558. reset_per_request_attributes(conn);
  11559. if (!conn) {
  11560. mg_snprintf(conn,
  11561. NULL, /* No truncation check for ebuf */
  11562. ebuf,
  11563. ebuf_len,
  11564. "%s",
  11565. "Internal error");
  11566. *err = 500;
  11567. return 0;
  11568. }
  11569. /* Set the time the request was received. This value should be used for
  11570. * timeouts. */
  11571. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  11572. conn->request_len =
  11573. read_request(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  11574. /* assert(conn->request_len < 0 || conn->data_len >= conn->request_len);
  11575. */
  11576. if (conn->request_len >= 0 && conn->data_len < conn->request_len) {
  11577. mg_snprintf(conn,
  11578. NULL, /* No truncation check for ebuf */
  11579. ebuf,
  11580. ebuf_len,
  11581. "%s",
  11582. "Invalid request size");
  11583. *err = 500;
  11584. return 0;
  11585. }
  11586. if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
  11587. mg_snprintf(conn,
  11588. NULL, /* No truncation check for ebuf */
  11589. ebuf,
  11590. ebuf_len,
  11591. "%s",
  11592. "Request Too Large");
  11593. *err = 413;
  11594. return 0;
  11595. } else if (conn->request_len <= 0) {
  11596. if (conn->data_len > 0) {
  11597. mg_snprintf(conn,
  11598. NULL, /* No truncation check for ebuf */
  11599. ebuf,
  11600. ebuf_len,
  11601. "%s",
  11602. "Client sent malformed request");
  11603. *err = 400;
  11604. } else {
  11605. /* Server did not recv anything -> just close the connection */
  11606. conn->must_close = 1;
  11607. mg_snprintf(conn,
  11608. NULL, /* No truncation check for ebuf */
  11609. ebuf,
  11610. ebuf_len,
  11611. "%s",
  11612. "Client did not send a request");
  11613. *err = 0;
  11614. }
  11615. return 0;
  11616. } else if (parse_http_message(conn->buf,
  11617. conn->buf_size,
  11618. &conn->request_info) <= 0) {
  11619. mg_snprintf(conn,
  11620. NULL, /* No truncation check for ebuf */
  11621. ebuf,
  11622. ebuf_len,
  11623. "%s",
  11624. "Bad Request");
  11625. *err = 400;
  11626. return 0;
  11627. } else {
  11628. /* Message is a valid request or response */
  11629. if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) {
  11630. /* Request/response has content length set */
  11631. char *endptr = NULL;
  11632. conn->content_len = strtoll(cl, &endptr, 10);
  11633. if (endptr == cl) {
  11634. mg_snprintf(conn,
  11635. NULL, /* No truncation check for ebuf */
  11636. ebuf,
  11637. ebuf_len,
  11638. "%s",
  11639. "Bad Request");
  11640. *err = 411;
  11641. return 0;
  11642. }
  11643. /* Publish the content length back to the request info. */
  11644. conn->request_info.content_length = conn->content_len;
  11645. } else if ((cl = get_header(&conn->request_info, "Transfer-Encoding"))
  11646. != NULL
  11647. && !mg_strcasecmp(cl, "chunked")) {
  11648. conn->is_chunked = 1;
  11649. } else if (!mg_strcasecmp(conn->request_info.request_method, "POST")
  11650. || !mg_strcasecmp(conn->request_info.request_method,
  11651. "PUT")) {
  11652. /* POST or PUT request without content length set */
  11653. conn->content_len = -1;
  11654. } else if (!mg_strncasecmp(conn->request_info.request_method,
  11655. "HTTP/",
  11656. 5)) {
  11657. /* Response without content length set */
  11658. conn->content_len = -1;
  11659. } else {
  11660. /* Other request */
  11661. conn->content_len = 0;
  11662. }
  11663. }
  11664. return 1;
  11665. }
  11666. int
  11667. mg_get_response(struct mg_connection *conn,
  11668. char *ebuf,
  11669. size_t ebuf_len,
  11670. int timeout)
  11671. {
  11672. if (conn) {
  11673. /* Implementation of API function for HTTP clients */
  11674. int err, ret;
  11675. struct mg_context *octx = conn->ctx;
  11676. struct mg_context rctx = *(conn->ctx);
  11677. char txt[32]; /* will not overflow */
  11678. if (timeout >= 0) {
  11679. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  11680. rctx.config[REQUEST_TIMEOUT] = txt;
  11681. /* Not required for non-blocking sockets.
  11682. set_sock_timeout(conn->client.sock, timeout);
  11683. */
  11684. } else {
  11685. rctx.config[REQUEST_TIMEOUT] = NULL;
  11686. }
  11687. conn->ctx = &rctx;
  11688. ret = getreq(conn, ebuf, ebuf_len, &err);
  11689. conn->ctx = octx;
  11690. /* TODO: 1) uri is deprecated;
  11691. * 2) here, ri.uri is the http response code */
  11692. conn->request_info.uri = conn->request_info.request_uri;
  11693. /* TODO (mid): Define proper return values - maybe return length?
  11694. * For the first test use <0 for error and >0 for OK */
  11695. return (ret == 0) ? -1 : +1;
  11696. }
  11697. return -1;
  11698. }
  11699. struct mg_connection *
  11700. mg_download(const char *host,
  11701. int port,
  11702. int use_ssl,
  11703. char *ebuf,
  11704. size_t ebuf_len,
  11705. const char *fmt,
  11706. ...)
  11707. {
  11708. struct mg_connection *conn;
  11709. va_list ap;
  11710. int i;
  11711. int reqerr;
  11712. va_start(ap, fmt);
  11713. ebuf[0] = '\0';
  11714. /* open a connection */
  11715. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  11716. if (conn != NULL) {
  11717. i = mg_vprintf(conn, fmt, ap);
  11718. if (i <= 0) {
  11719. mg_snprintf(conn,
  11720. NULL, /* No truncation check for ebuf */
  11721. ebuf,
  11722. ebuf_len,
  11723. "%s",
  11724. "Error sending request");
  11725. } else {
  11726. getreq(conn, ebuf, ebuf_len, &reqerr);
  11727. /* TODO: 1) uri is deprecated;
  11728. * 2) here, ri.uri is the http response code */
  11729. conn->request_info.uri = conn->request_info.request_uri;
  11730. }
  11731. }
  11732. /* if an error occured, close the connection */
  11733. if (ebuf[0] != '\0' && conn != NULL) {
  11734. mg_close_connection(conn);
  11735. conn = NULL;
  11736. }
  11737. va_end(ap);
  11738. return conn;
  11739. }
  11740. struct websocket_client_thread_data {
  11741. struct mg_connection *conn;
  11742. mg_websocket_data_handler data_handler;
  11743. mg_websocket_close_handler close_handler;
  11744. void *callback_data;
  11745. };
  11746. #if defined(USE_WEBSOCKET)
  11747. #ifdef _WIN32
  11748. static unsigned __stdcall websocket_client_thread(void *data)
  11749. #else
  11750. static void *
  11751. websocket_client_thread(void *data)
  11752. #endif
  11753. {
  11754. struct websocket_client_thread_data *cdata =
  11755. (struct websocket_client_thread_data *)data;
  11756. mg_set_thread_name("ws-clnt");
  11757. if (cdata->conn->ctx) {
  11758. if (cdata->conn->ctx->callbacks.init_thread) {
  11759. /* 3 indicates a websocket client thread */
  11760. /* TODO: check if conn->ctx can be set */
  11761. cdata->conn->ctx->callbacks.init_thread(cdata->conn->ctx, 3);
  11762. }
  11763. }
  11764. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  11765. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  11766. if (cdata->close_handler != NULL) {
  11767. cdata->close_handler(cdata->conn, cdata->callback_data);
  11768. }
  11769. /* The websocket_client context has only this thread. If it runs out,
  11770. set the stop_flag to 2 (= "stopped"). */
  11771. cdata->conn->ctx->stop_flag = 2;
  11772. mg_free((void *)cdata);
  11773. #ifdef _WIN32
  11774. return 0;
  11775. #else
  11776. return NULL;
  11777. #endif
  11778. }
  11779. #endif
  11780. struct mg_connection *
  11781. mg_connect_websocket_client(const char *host,
  11782. int port,
  11783. int use_ssl,
  11784. char *error_buffer,
  11785. size_t error_buffer_size,
  11786. const char *path,
  11787. const char *origin,
  11788. mg_websocket_data_handler data_func,
  11789. mg_websocket_close_handler close_func,
  11790. void *user_data)
  11791. {
  11792. struct mg_connection *conn = NULL;
  11793. #if defined(USE_WEBSOCKET)
  11794. struct mg_context *newctx = NULL;
  11795. struct websocket_client_thread_data *thread_data;
  11796. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  11797. static const char *handshake_req;
  11798. if (origin != NULL) {
  11799. handshake_req = "GET %s HTTP/1.1\r\n"
  11800. "Host: %s\r\n"
  11801. "Upgrade: websocket\r\n"
  11802. "Connection: Upgrade\r\n"
  11803. "Sec-WebSocket-Key: %s\r\n"
  11804. "Sec-WebSocket-Version: 13\r\n"
  11805. "Origin: %s\r\n"
  11806. "\r\n";
  11807. } else {
  11808. handshake_req = "GET %s HTTP/1.1\r\n"
  11809. "Host: %s\r\n"
  11810. "Upgrade: websocket\r\n"
  11811. "Connection: Upgrade\r\n"
  11812. "Sec-WebSocket-Key: %s\r\n"
  11813. "Sec-WebSocket-Version: 13\r\n"
  11814. "\r\n";
  11815. }
  11816. /* Establish the client connection and request upgrade */
  11817. conn = mg_download(host,
  11818. port,
  11819. use_ssl,
  11820. error_buffer,
  11821. error_buffer_size,
  11822. handshake_req,
  11823. path,
  11824. host,
  11825. magic,
  11826. origin);
  11827. /* Connection object will be null if something goes wrong */
  11828. if (conn == NULL || (strcmp(conn->request_info.request_uri, "101") != 0)) {
  11829. if (!*error_buffer) {
  11830. /* if there is a connection, but it did not return 101,
  11831. * error_buffer is not yet set */
  11832. mg_snprintf(conn,
  11833. NULL, /* No truncation check for ebuf */
  11834. error_buffer,
  11835. error_buffer_size,
  11836. "Unexpected server reply");
  11837. }
  11838. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  11839. if (conn != NULL) {
  11840. mg_free(conn);
  11841. conn = NULL;
  11842. }
  11843. return conn;
  11844. }
  11845. /* For client connections, mg_context is fake. Since we need to set a
  11846. * callback function, we need to create a copy and modify it. */
  11847. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  11848. memcpy(newctx, conn->ctx, sizeof(struct mg_context));
  11849. newctx->user_data = user_data;
  11850. newctx->context_type = 2; /* ws/wss client context type */
  11851. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  11852. newctx->worker_threadids =
  11853. (pthread_t *)mg_calloc(newctx->cfg_worker_threads, sizeof(pthread_t));
  11854. conn->ctx = newctx;
  11855. thread_data = (struct websocket_client_thread_data *)
  11856. mg_calloc(sizeof(struct websocket_client_thread_data), 1);
  11857. thread_data->conn = conn;
  11858. thread_data->data_handler = data_func;
  11859. thread_data->close_handler = close_func;
  11860. thread_data->callback_data = user_data;
  11861. /* Start a thread to read the websocket client connection
  11862. * This thread will automatically stop when mg_disconnect is
  11863. * called on the client connection */
  11864. if (mg_start_thread_with_id(websocket_client_thread,
  11865. (void *)thread_data,
  11866. newctx->worker_threadids) != 0) {
  11867. mg_free((void *)thread_data);
  11868. mg_free((void *)newctx->worker_threadids);
  11869. mg_free((void *)newctx);
  11870. mg_free((void *)conn);
  11871. conn = NULL;
  11872. DEBUG_TRACE("%s",
  11873. "Websocket client connect thread could not be started\r\n");
  11874. }
  11875. #else
  11876. /* Appease "unused parameter" warnings */
  11877. (void)host;
  11878. (void)port;
  11879. (void)use_ssl;
  11880. (void)error_buffer;
  11881. (void)error_buffer_size;
  11882. (void)path;
  11883. (void)origin;
  11884. (void)user_data;
  11885. (void)data_func;
  11886. (void)close_func;
  11887. #endif
  11888. return conn;
  11889. }
  11890. static void
  11891. process_new_connection(struct mg_connection *conn)
  11892. {
  11893. if (conn && conn->ctx) {
  11894. struct mg_request_info *ri = &conn->request_info;
  11895. int keep_alive_enabled, keep_alive, discard_len;
  11896. char ebuf[100];
  11897. const char *hostend;
  11898. int reqerr, uri_type;
  11899. keep_alive_enabled =
  11900. !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  11901. /* Important: on new connection, reset the receiving buffer. Credit
  11902. * goes to crule42. */
  11903. conn->data_len = 0;
  11904. conn->handled_requests = 0;
  11905. do {
  11906. DEBUG_TRACE("calling getreq (%i times for this connection)",
  11907. conn->handled_requests + 1);
  11908. if (!getreq(conn, ebuf, sizeof(ebuf), &reqerr)) {
  11909. /* The request sent by the client could not be understood by
  11910. * the server, or it was incomplete or a timeout. Send an
  11911. * error message and close the connection. */
  11912. if (reqerr > 0) {
  11913. /*assert(ebuf[0] != '\0');*/
  11914. send_http_error(conn, reqerr, "%s", ebuf);
  11915. }
  11916. } else if (strcmp(ri->http_version, "1.0")
  11917. && strcmp(ri->http_version, "1.1")) {
  11918. mg_snprintf(conn,
  11919. NULL, /* No truncation check for ebuf */
  11920. ebuf,
  11921. sizeof(ebuf),
  11922. "Bad HTTP version: [%s]",
  11923. ri->http_version);
  11924. send_http_error(conn, 505, "%s", ebuf);
  11925. }
  11926. if (ebuf[0] == '\0') {
  11927. uri_type = get_uri_type(conn->request_info.request_uri);
  11928. switch (uri_type) {
  11929. case 1:
  11930. /* Asterisk */
  11931. conn->request_info.local_uri = NULL;
  11932. break;
  11933. case 2:
  11934. /* relative uri */
  11935. conn->request_info.local_uri =
  11936. conn->request_info.request_uri;
  11937. break;
  11938. case 3:
  11939. case 4:
  11940. /* absolute uri (with/without port) */
  11941. hostend = get_rel_url_at_current_server(
  11942. conn->request_info.request_uri, conn);
  11943. if (hostend) {
  11944. conn->request_info.local_uri = hostend;
  11945. } else {
  11946. conn->request_info.local_uri = NULL;
  11947. }
  11948. break;
  11949. default:
  11950. mg_snprintf(conn,
  11951. NULL, /* No truncation check for ebuf */
  11952. ebuf,
  11953. sizeof(ebuf),
  11954. "Invalid URI");
  11955. send_http_error(conn, 400, "%s", ebuf);
  11956. conn->request_info.local_uri = NULL;
  11957. break;
  11958. }
  11959. /* TODO: cleanup uri, local_uri and request_uri */
  11960. conn->request_info.uri = conn->request_info.local_uri;
  11961. }
  11962. DEBUG_TRACE("http: %s, error: %s",
  11963. (ri->http_version ? ri->http_version : "none"),
  11964. (ebuf[0] ? ebuf : "none"));
  11965. if (ebuf[0] == '\0') {
  11966. if (conn->request_info.local_uri) {
  11967. /* handle request to local server */
  11968. handle_request(conn);
  11969. DEBUG_TRACE("%s", "handle_request done");
  11970. if (conn->ctx->callbacks.end_request != NULL) {
  11971. conn->ctx->callbacks.end_request(conn,
  11972. conn->status_code);
  11973. DEBUG_TRACE("%s", "end_request callback done");
  11974. }
  11975. log_access(conn);
  11976. } else {
  11977. /* TODO: handle non-local request (PROXY) */
  11978. conn->must_close = 1;
  11979. }
  11980. } else {
  11981. conn->must_close = 1;
  11982. }
  11983. if (ri->remote_user != NULL) {
  11984. mg_free((void *)ri->remote_user);
  11985. /* Important! When having connections with and without auth
  11986. * would cause double free and then crash */
  11987. ri->remote_user = NULL;
  11988. }
  11989. /* NOTE(lsm): order is important here. should_keep_alive() call
  11990. * is
  11991. * using parsed request, which will be invalid after memmove's
  11992. * below.
  11993. * Therefore, memorize should_keep_alive() result now for later
  11994. * use
  11995. * in loop exit condition. */
  11996. keep_alive = (conn->ctx->stop_flag == 0) && keep_alive_enabled
  11997. && (conn->content_len >= 0) && should_keep_alive(conn);
  11998. /* Discard all buffered data for this request */
  11999. discard_len = ((conn->content_len >= 0) && (conn->request_len > 0)
  12000. && ((conn->request_len + conn->content_len)
  12001. < (int64_t)conn->data_len))
  12002. ? (int)(conn->request_len + conn->content_len)
  12003. : conn->data_len;
  12004. /*assert(discard_len >= 0);*/
  12005. if (discard_len < 0) {
  12006. DEBUG_TRACE("internal error: discard_len = %li",
  12007. (long int)discard_len);
  12008. break;
  12009. }
  12010. conn->data_len -= discard_len;
  12011. if (conn->data_len > 0) {
  12012. DEBUG_TRACE("discard_len = %lu", (long unsigned)discard_len);
  12013. memmove(conn->buf,
  12014. conn->buf + discard_len,
  12015. (size_t)conn->data_len);
  12016. }
  12017. /* assert(conn->data_len >= 0); */
  12018. /* assert(conn->data_len <= conn->buf_size); */
  12019. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  12020. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  12021. (long int)conn->data_len,
  12022. (long int)conn->buf_size);
  12023. break;
  12024. }
  12025. conn->handled_requests++;
  12026. } while (keep_alive);
  12027. }
  12028. }
  12029. #if defined(ALTERNATIVE_QUEUE)
  12030. static void
  12031. produce_socket(struct mg_context *ctx, const struct socket *sp)
  12032. {
  12033. unsigned int i;
  12034. for (;;) {
  12035. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  12036. /* find a free worker slot and signal it */
  12037. if (ctx->client_socks[i].in_use == 0) {
  12038. ctx->client_socks[i] = *sp;
  12039. ctx->client_socks[i].in_use = 1;
  12040. event_signal(ctx->client_wait_events[i]);
  12041. return;
  12042. }
  12043. }
  12044. /* queue is full */
  12045. mg_sleep(1);
  12046. }
  12047. }
  12048. static int
  12049. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  12050. {
  12051. DEBUG_TRACE("%s", "going idle");
  12052. ctx->client_socks[thread_index].in_use = 0;
  12053. event_wait(ctx->client_wait_events[thread_index]);
  12054. *sp = ctx->client_socks[thread_index];
  12055. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  12056. return !ctx->stop_flag;
  12057. }
  12058. #else /* ALTERNATIVE_QUEUE */
  12059. /* Worker threads take accepted socket from the queue */
  12060. static int
  12061. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  12062. {
  12063. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  12064. (void)thread_index;
  12065. (void)pthread_mutex_lock(&ctx->thread_mutex);
  12066. DEBUG_TRACE("%s", "going idle");
  12067. /* If the queue is empty, wait. We're idle at this point. */
  12068. while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
  12069. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  12070. }
  12071. /* If we're stopping, sq_head may be equal to sq_tail. */
  12072. if (ctx->sq_head > ctx->sq_tail) {
  12073. /* Copy socket from the queue and increment tail */
  12074. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  12075. ctx->sq_tail++;
  12076. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  12077. /* Wrap pointers if needed */
  12078. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  12079. ctx->sq_tail -= QUEUE_SIZE(ctx);
  12080. ctx->sq_head -= QUEUE_SIZE(ctx);
  12081. }
  12082. }
  12083. (void)pthread_cond_signal(&ctx->sq_empty);
  12084. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  12085. return !ctx->stop_flag;
  12086. #undef QUEUE_SIZE
  12087. }
  12088. /* Master thread adds accepted socket to a queue */
  12089. static void
  12090. produce_socket(struct mg_context *ctx, const struct socket *sp)
  12091. {
  12092. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  12093. if (!ctx) {
  12094. return;
  12095. }
  12096. (void)pthread_mutex_lock(&ctx->thread_mutex);
  12097. /* If the queue is full, wait */
  12098. while (ctx->stop_flag == 0
  12099. && ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx)) {
  12100. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  12101. }
  12102. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  12103. /* Copy socket to the queue and increment head */
  12104. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  12105. ctx->sq_head++;
  12106. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  12107. }
  12108. (void)pthread_cond_signal(&ctx->sq_full);
  12109. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  12110. #undef QUEUE_SIZE
  12111. }
  12112. #endif /* ALTERNATIVE_QUEUE */
  12113. struct worker_thread_args {
  12114. struct mg_context *ctx;
  12115. int index;
  12116. };
  12117. static void *
  12118. worker_thread_run(struct worker_thread_args *thread_args)
  12119. {
  12120. struct mg_context *ctx = thread_args->ctx;
  12121. struct mg_connection *conn;
  12122. struct mg_workerTLS tls;
  12123. #if defined(MG_LEGACY_INTERFACE)
  12124. uint32_t addr;
  12125. #endif
  12126. mg_set_thread_name("worker");
  12127. tls.is_master = 0;
  12128. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  12129. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12130. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  12131. #endif
  12132. /* Initialize thread local storage before calling any callback */
  12133. pthread_setspecific(sTlsKey, &tls);
  12134. if (ctx->callbacks.init_thread) {
  12135. /* call init_thread for a worker thread (type 1) */
  12136. ctx->callbacks.init_thread(ctx, 1);
  12137. }
  12138. /* Connection structure has been pre-allocated */
  12139. if (((int)thread_args->index < 0)
  12140. || ((unsigned)thread_args->index
  12141. >= (unsigned)ctx->cfg_worker_threads)) {
  12142. mg_cry(fc(ctx),
  12143. "Internal error: Invalid worker index %i",
  12144. (int)thread_args->index);
  12145. return NULL;
  12146. }
  12147. conn = ctx->worker_connections + thread_args->index;
  12148. /* Request buffers are not pre-allocated. They are private to the
  12149. * request and do not contain any state information that might be
  12150. * of interest to anyone observing a server status. */
  12151. conn->buf = (char *)mg_malloc(MAX_REQUEST_SIZE);
  12152. if (conn->buf == NULL) {
  12153. mg_cry(fc(ctx),
  12154. "Out of memory: Cannot allocate buffer for worker %i",
  12155. (int)thread_args->index);
  12156. return NULL;
  12157. }
  12158. conn->buf_size = MAX_REQUEST_SIZE;
  12159. conn->ctx = ctx;
  12160. conn->thread_index = thread_args->index;
  12161. conn->request_info.user_data = ctx->user_data;
  12162. /* Allocate a mutex for this connection to allow communication both
  12163. * within the request handler and from elsewhere in the application
  12164. */
  12165. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  12166. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  12167. * signal sq_empty condvar to wake up the master waiting in
  12168. * produce_socket() */
  12169. while (consume_socket(ctx, &conn->client, conn->thread_index)) {
  12170. conn->conn_birth_time = time(NULL);
  12171. /* Fill in IP, port info early so even if SSL setup below fails,
  12172. * error handler would have the corresponding info.
  12173. * Thanks to Johannes Winkelmann for the patch.
  12174. */
  12175. #if defined(USE_IPV6)
  12176. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  12177. conn->request_info.remote_port =
  12178. ntohs(conn->client.rsa.sin6.sin6_port);
  12179. } else
  12180. #endif
  12181. {
  12182. conn->request_info.remote_port =
  12183. ntohs(conn->client.rsa.sin.sin_port);
  12184. }
  12185. sockaddr_to_string(conn->request_info.remote_addr,
  12186. sizeof(conn->request_info.remote_addr),
  12187. &conn->client.rsa);
  12188. DEBUG_TRACE("Start processing connection from %s",
  12189. conn->request_info.remote_addr);
  12190. #if defined(MG_LEGACY_INTERFACE)
  12191. /* This legacy interface only works for the IPv4 case */
  12192. addr = ntohl(conn->client.rsa.sin.sin_addr.s_addr);
  12193. memcpy(&conn->request_info.remote_ip, &addr, 4);
  12194. #endif
  12195. conn->request_info.is_ssl = conn->client.is_ssl;
  12196. if (conn->client.is_ssl) {
  12197. #ifndef NO_SSL
  12198. /* HTTPS connection */
  12199. if (sslize(conn,
  12200. conn->ctx->ssl_ctx,
  12201. SSL_accept,
  12202. &(conn->ctx->stop_flag))) {
  12203. /* Get SSL client certificate information (if set) */
  12204. ssl_get_client_cert_info(conn);
  12205. /* process HTTPS connection */
  12206. process_new_connection(conn);
  12207. /* Free client certificate info */
  12208. if (conn->request_info.client_cert) {
  12209. mg_free((void *)(conn->request_info.client_cert->subject));
  12210. mg_free((void *)(conn->request_info.client_cert->issuer));
  12211. mg_free((void *)(conn->request_info.client_cert->serial));
  12212. mg_free((void *)(conn->request_info.client_cert->finger));
  12213. conn->request_info.client_cert->subject = 0;
  12214. conn->request_info.client_cert->issuer = 0;
  12215. conn->request_info.client_cert->serial = 0;
  12216. conn->request_info.client_cert->finger = 0;
  12217. mg_free(conn->request_info.client_cert);
  12218. conn->request_info.client_cert = 0;
  12219. }
  12220. }
  12221. #endif
  12222. } else {
  12223. /* process HTTP connection */
  12224. process_new_connection(conn);
  12225. }
  12226. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  12227. conn->request_info.remote_addr,
  12228. difftime(time(NULL), conn->conn_birth_time));
  12229. close_connection(conn);
  12230. DEBUG_TRACE("%s", "Connection closed");
  12231. }
  12232. pthread_setspecific(sTlsKey, NULL);
  12233. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12234. CloseHandle(tls.pthread_cond_helper_mutex);
  12235. #endif
  12236. pthread_mutex_destroy(&conn->mutex);
  12237. /* Free the request buffer. */
  12238. conn->buf_size = 0;
  12239. mg_free(conn->buf);
  12240. conn->buf = NULL;
  12241. DEBUG_TRACE("%s", "exiting");
  12242. return NULL;
  12243. }
  12244. /* Threads have different return types on Windows and Unix. */
  12245. #ifdef _WIN32
  12246. static unsigned __stdcall worker_thread(void *thread_func_param)
  12247. {
  12248. struct worker_thread_args *pwta =
  12249. (struct worker_thread_args *)thread_func_param;
  12250. worker_thread_run(pwta);
  12251. mg_free(thread_func_param);
  12252. return 0;
  12253. }
  12254. #else
  12255. static void *
  12256. worker_thread(void *thread_func_param)
  12257. {
  12258. struct worker_thread_args *pwta =
  12259. (struct worker_thread_args *)thread_func_param;
  12260. worker_thread_run(pwta);
  12261. mg_free(thread_func_param);
  12262. return NULL;
  12263. }
  12264. #endif /* _WIN32 */
  12265. static void
  12266. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  12267. {
  12268. struct socket so;
  12269. char src_addr[IP_ADDR_STR_LEN];
  12270. socklen_t len = sizeof(so.rsa);
  12271. int on = 1;
  12272. if (!listener) {
  12273. return;
  12274. }
  12275. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  12276. == INVALID_SOCKET) {
  12277. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  12278. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  12279. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  12280. closesocket(so.sock);
  12281. so.sock = INVALID_SOCKET;
  12282. } else {
  12283. /* Put so socket structure into the queue */
  12284. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  12285. set_close_on_exec(so.sock, fc(ctx));
  12286. so.is_ssl = listener->is_ssl;
  12287. so.ssl_redir = listener->ssl_redir;
  12288. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  12289. mg_cry(fc(ctx),
  12290. "%s: getsockname() failed: %s",
  12291. __func__,
  12292. strerror(ERRNO));
  12293. }
  12294. /* Set TCP keep-alive. This is needed because if HTTP-level
  12295. * keep-alive
  12296. * is enabled, and client resets the connection, server won't get
  12297. * TCP FIN or RST and will keep the connection open forever. With
  12298. * TCP keep-alive, next keep-alive handshake will figure out that
  12299. * the client is down and will close the server end.
  12300. * Thanks to Igor Klopov who suggested the patch. */
  12301. if (setsockopt(so.sock,
  12302. SOL_SOCKET,
  12303. SO_KEEPALIVE,
  12304. (SOCK_OPT_TYPE)&on,
  12305. sizeof(on)) != 0) {
  12306. mg_cry(fc(ctx),
  12307. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  12308. __func__,
  12309. strerror(ERRNO));
  12310. }
  12311. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  12312. * to effectively fill up the underlying IP packet payload and
  12313. * reduce the overhead of sending lots of small buffers. However
  12314. * this hurts the server's throughput (ie. operations per second)
  12315. * when HTTP 1.1 persistent connections are used and the responses
  12316. * are relatively small (eg. less than 1400 bytes).
  12317. */
  12318. if ((ctx != NULL) && (ctx->config[CONFIG_TCP_NODELAY] != NULL)
  12319. && (!strcmp(ctx->config[CONFIG_TCP_NODELAY], "1"))) {
  12320. if (set_tcp_nodelay(so.sock, 1) != 0) {
  12321. mg_cry(fc(ctx),
  12322. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  12323. __func__,
  12324. strerror(ERRNO));
  12325. }
  12326. }
  12327. /* We are using non-blocking sockets. Thus, the
  12328. * set_sock_timeout(so.sock, timeout);
  12329. * call is no longer required. */
  12330. set_blocking_mode(so.sock, 0);
  12331. produce_socket(ctx, &so);
  12332. }
  12333. }
  12334. static void
  12335. master_thread_run(void *thread_func_param)
  12336. {
  12337. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  12338. struct mg_workerTLS tls;
  12339. struct pollfd *pfd;
  12340. unsigned int i;
  12341. unsigned int workerthreadcount;
  12342. if (!ctx) {
  12343. return;
  12344. }
  12345. mg_set_thread_name("master");
  12346. /* Increase priority of the master thread */
  12347. #if defined(_WIN32)
  12348. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  12349. #elif defined(USE_MASTER_THREAD_PRIORITY)
  12350. int min_prio = sched_get_priority_min(SCHED_RR);
  12351. int max_prio = sched_get_priority_max(SCHED_RR);
  12352. if ((min_prio >= 0) && (max_prio >= 0)
  12353. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  12354. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  12355. struct sched_param sched_param = {0};
  12356. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  12357. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  12358. }
  12359. #endif
  12360. /* Initialize thread local storage */
  12361. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12362. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  12363. #endif
  12364. tls.is_master = 1;
  12365. pthread_setspecific(sTlsKey, &tls);
  12366. if (ctx->callbacks.init_thread) {
  12367. /* Callback for the master thread (type 0) */
  12368. ctx->callbacks.init_thread(ctx, 0);
  12369. }
  12370. /* Server starts *now* */
  12371. ctx->start_time = time(NULL);
  12372. /* Start the server */
  12373. pfd = ctx->listening_socket_fds;
  12374. while (ctx->stop_flag == 0) {
  12375. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12376. pfd[i].fd = ctx->listening_sockets[i].sock;
  12377. pfd[i].events = POLLIN;
  12378. }
  12379. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  12380. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12381. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  12382. * successful poll, and POLLIN is defined as
  12383. * (POLLRDNORM | POLLRDBAND)
  12384. * Therefore, we're checking pfd[i].revents & POLLIN, not
  12385. * pfd[i].revents == POLLIN. */
  12386. if (ctx->stop_flag == 0 && (pfd[i].revents & POLLIN)) {
  12387. accept_new_connection(&ctx->listening_sockets[i], ctx);
  12388. }
  12389. }
  12390. }
  12391. }
  12392. /* Here stop_flag is 1 - Initiate shutdown. */
  12393. DEBUG_TRACE("%s", "stopping workers");
  12394. /* Stop signal received: somebody called mg_stop. Quit. */
  12395. close_all_listening_sockets(ctx);
  12396. /* Wakeup workers that are waiting for connections to handle. */
  12397. (void)pthread_mutex_lock(&ctx->thread_mutex);
  12398. #if defined(ALTERNATIVE_QUEUE)
  12399. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  12400. event_signal(ctx->client_wait_events[i]);
  12401. /* Since we know all sockets, we can shutdown the connections. */
  12402. if (ctx->client_socks[i].in_use) {
  12403. shutdown(ctx->client_socks[i].sock, SHUTDOWN_BOTH);
  12404. }
  12405. }
  12406. #else
  12407. pthread_cond_broadcast(&ctx->sq_full);
  12408. #endif
  12409. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  12410. /* Join all worker threads to avoid leaking threads. */
  12411. workerthreadcount = ctx->cfg_worker_threads;
  12412. for (i = 0; i < workerthreadcount; i++) {
  12413. if (ctx->worker_threadids[i] != 0) {
  12414. mg_join_thread(ctx->worker_threadids[i]);
  12415. }
  12416. }
  12417. #if defined(USE_LUA)
  12418. /* Free Lua state of lua background task */
  12419. if (ctx->lua_background_state) {
  12420. lua_close((lua_State *)ctx->lua_background_state);
  12421. ctx->lua_background_state = 0;
  12422. }
  12423. #endif
  12424. #if !defined(NO_SSL)
  12425. if (ctx->ssl_ctx != NULL) {
  12426. uninitialize_ssl(ctx);
  12427. }
  12428. #endif
  12429. DEBUG_TRACE("%s", "exiting");
  12430. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12431. CloseHandle(tls.pthread_cond_helper_mutex);
  12432. #endif
  12433. pthread_setspecific(sTlsKey, NULL);
  12434. /* Signal mg_stop() that we're done.
  12435. * WARNING: This must be the very last thing this
  12436. * thread does, as ctx becomes invalid after this line. */
  12437. ctx->stop_flag = 2;
  12438. }
  12439. /* Threads have different return types on Windows and Unix. */
  12440. #ifdef _WIN32
  12441. static unsigned __stdcall master_thread(void *thread_func_param)
  12442. {
  12443. master_thread_run(thread_func_param);
  12444. return 0;
  12445. }
  12446. #else
  12447. static void *
  12448. master_thread(void *thread_func_param)
  12449. {
  12450. master_thread_run(thread_func_param);
  12451. return NULL;
  12452. }
  12453. #endif /* _WIN32 */
  12454. static void
  12455. free_context(struct mg_context *ctx)
  12456. {
  12457. int i;
  12458. struct mg_handler_info *tmp_rh;
  12459. if (ctx == NULL) {
  12460. return;
  12461. }
  12462. if (ctx->callbacks.exit_context) {
  12463. ctx->callbacks.exit_context(ctx);
  12464. }
  12465. /* All threads exited, no sync is needed. Destroy thread mutex and
  12466. * condvars
  12467. */
  12468. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  12469. #if defined(ALTERNATIVE_QUEUE)
  12470. mg_free(ctx->client_socks);
  12471. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  12472. event_destroy(ctx->client_wait_events[i]);
  12473. }
  12474. mg_free(ctx->client_wait_events);
  12475. #else
  12476. (void)pthread_cond_destroy(&ctx->sq_empty);
  12477. (void)pthread_cond_destroy(&ctx->sq_full);
  12478. #endif
  12479. /* Destroy other context global data structures mutex */
  12480. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  12481. #if defined(USE_TIMERS)
  12482. timers_exit(ctx);
  12483. #endif
  12484. /* Deallocate config parameters */
  12485. for (i = 0; i < NUM_OPTIONS; i++) {
  12486. if (ctx->config[i] != NULL) {
  12487. #if defined(_MSC_VER)
  12488. #pragma warning(suppress : 6001)
  12489. #endif
  12490. mg_free(ctx->config[i]);
  12491. }
  12492. }
  12493. /* Deallocate request handlers */
  12494. while (ctx->handlers) {
  12495. tmp_rh = ctx->handlers;
  12496. ctx->handlers = tmp_rh->next;
  12497. mg_free(tmp_rh->uri);
  12498. mg_free(tmp_rh);
  12499. }
  12500. #ifndef NO_SSL
  12501. /* Deallocate SSL context */
  12502. if (ctx->ssl_ctx != NULL) {
  12503. SSL_CTX_free(ctx->ssl_ctx);
  12504. }
  12505. #endif /* !NO_SSL */
  12506. /* Deallocate worker thread ID array */
  12507. if (ctx->worker_threadids != NULL) {
  12508. mg_free(ctx->worker_threadids);
  12509. }
  12510. /* Deallocate worker thread ID array */
  12511. if (ctx->worker_connections != NULL) {
  12512. mg_free(ctx->worker_connections);
  12513. }
  12514. /* Deallocate the tls variable */
  12515. if (mg_atomic_dec(&sTlsInit) == 0) {
  12516. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12517. DeleteCriticalSection(&global_log_file_lock);
  12518. #endif /* _WIN32 && !__SYMBIAN32__ */
  12519. #if !defined(_WIN32)
  12520. pthread_mutexattr_destroy(&pthread_mutex_attr);
  12521. #endif
  12522. pthread_key_delete(sTlsKey);
  12523. #if defined(USE_LUA)
  12524. lua_exit_optional_libraries();
  12525. #endif
  12526. }
  12527. /* deallocate system name string */
  12528. mg_free(ctx->systemName);
  12529. /* Deallocate context itself */
  12530. mg_free(ctx);
  12531. }
  12532. void
  12533. mg_stop(struct mg_context *ctx)
  12534. {
  12535. pthread_t mt;
  12536. if (!ctx) {
  12537. return;
  12538. }
  12539. /* We don't use a lock here. Calling mg_stop with the same ctx from
  12540. * two threads is not allowed. */
  12541. mt = ctx->masterthreadid;
  12542. if (mt == 0) {
  12543. return;
  12544. }
  12545. ctx->masterthreadid = 0;
  12546. /* Set stop flag, so all threads know they have to exit. */
  12547. ctx->stop_flag = 1;
  12548. /* Wait until everything has stopped. */
  12549. while (ctx->stop_flag != 2) {
  12550. (void)mg_sleep(10);
  12551. }
  12552. mg_join_thread(mt);
  12553. free_context(ctx);
  12554. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12555. (void)WSACleanup();
  12556. #endif /* _WIN32 && !__SYMBIAN32__ */
  12557. }
  12558. static void
  12559. get_system_name(char **sysName)
  12560. {
  12561. #if defined(_WIN32)
  12562. #if !defined(__SYMBIAN32__)
  12563. #if defined(_WIN32_WCE)
  12564. *sysName = mg_strdup("WinCE");
  12565. #else
  12566. char name[128];
  12567. DWORD dwVersion = 0;
  12568. DWORD dwMajorVersion = 0;
  12569. DWORD dwMinorVersion = 0;
  12570. DWORD dwBuild = 0;
  12571. #ifdef _MSC_VER
  12572. #pragma warning(push)
  12573. /* GetVersion was declared deprecated */
  12574. #pragma warning(disable : 4996)
  12575. #endif
  12576. dwVersion = GetVersion();
  12577. #ifdef _MSC_VER
  12578. #pragma warning(pop)
  12579. #endif
  12580. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  12581. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  12582. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  12583. (void)dwBuild;
  12584. sprintf(name,
  12585. "Windows %u.%u",
  12586. (unsigned)dwMajorVersion,
  12587. (unsigned)dwMinorVersion);
  12588. *sysName = mg_strdup(name);
  12589. #endif
  12590. #else
  12591. *sysName = mg_strdup("Symbian");
  12592. #endif
  12593. #else
  12594. struct utsname name;
  12595. memset(&name, 0, sizeof(name));
  12596. uname(&name);
  12597. *sysName = mg_strdup(name.sysname);
  12598. #endif
  12599. }
  12600. struct mg_context *
  12601. mg_start(const struct mg_callbacks *callbacks,
  12602. void *user_data,
  12603. const char **options)
  12604. {
  12605. struct mg_context *ctx;
  12606. const char *name, *value, *default_value;
  12607. int idx, ok, workerthreadcount;
  12608. unsigned int i;
  12609. void (*exit_callback)(const struct mg_context *ctx) = 0;
  12610. struct mg_workerTLS tls;
  12611. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12612. WSADATA data;
  12613. WSAStartup(MAKEWORD(2, 2), &data);
  12614. #endif /* _WIN32 && !__SYMBIAN32__ */
  12615. /* Allocate context and initialize reasonable general case defaults. */
  12616. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  12617. return NULL;
  12618. }
  12619. /* Random number generator will initialize at the first call */
  12620. ctx->auth_nonce_mask =
  12621. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  12622. if (mg_atomic_inc(&sTlsInit) == 1) {
  12623. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12624. InitializeCriticalSection(&global_log_file_lock);
  12625. #endif /* _WIN32 && !__SYMBIAN32__ */
  12626. #if !defined(_WIN32)
  12627. pthread_mutexattr_init(&pthread_mutex_attr);
  12628. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  12629. #endif
  12630. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  12631. /* Fatal error - abort start. However, this situation should
  12632. * never
  12633. * occur in practice. */
  12634. mg_atomic_dec(&sTlsInit);
  12635. mg_cry(fc(ctx), "Cannot initialize thread local storage");
  12636. mg_free(ctx);
  12637. return NULL;
  12638. }
  12639. #if defined(USE_LUA)
  12640. lua_init_optional_libraries();
  12641. #endif
  12642. } else {
  12643. /* TODO (low): istead of sleeping, check if sTlsKey is already
  12644. * initialized. */
  12645. mg_sleep(1);
  12646. }
  12647. tls.is_master = -1;
  12648. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  12649. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12650. tls.pthread_cond_helper_mutex = NULL;
  12651. #endif
  12652. pthread_setspecific(sTlsKey, &tls);
  12653. /* Dummy use this function - in some #ifdef combinations it's used,
  12654. * while it's not used in others, but GCC seems to stupid to understand
  12655. * #pragma GCC diagnostic ignored "-Wunused-function"
  12656. * in cases the function is unused, and it also complains on
  12657. * __attribute((unused))__ in cases it is used.
  12658. * So dummy use it, to have our peace. */
  12659. (void)mg_current_thread_id();
  12660. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr);
  12661. #if !defined(ALTERNATIVE_QUEUE)
  12662. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  12663. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  12664. #endif
  12665. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr);
  12666. if (!ok) {
  12667. /* Fatal error - abort start. However, this situation should never
  12668. * occur in practice. */
  12669. mg_cry(fc(ctx), "Cannot initialize thread synchronization objects");
  12670. mg_free(ctx);
  12671. pthread_setspecific(sTlsKey, NULL);
  12672. return NULL;
  12673. }
  12674. if (callbacks) {
  12675. ctx->callbacks = *callbacks;
  12676. exit_callback = callbacks->exit_context;
  12677. ctx->callbacks.exit_context = 0;
  12678. }
  12679. ctx->user_data = user_data;
  12680. ctx->handlers = NULL;
  12681. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  12682. ctx->shared_lua_websockets = 0;
  12683. #endif
  12684. while (options && (name = *options++) != NULL) {
  12685. if ((idx = get_option_index(name)) == -1) {
  12686. mg_cry(fc(ctx), "Invalid option: %s", name);
  12687. free_context(ctx);
  12688. pthread_setspecific(sTlsKey, NULL);
  12689. return NULL;
  12690. } else if ((value = *options++) == NULL) {
  12691. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  12692. free_context(ctx);
  12693. pthread_setspecific(sTlsKey, NULL);
  12694. return NULL;
  12695. }
  12696. if (ctx->config[idx] != NULL) {
  12697. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  12698. mg_free(ctx->config[idx]);
  12699. }
  12700. ctx->config[idx] = mg_strdup(value);
  12701. DEBUG_TRACE("[%s] -> [%s]", name, value);
  12702. }
  12703. /* Set default value if needed */
  12704. for (i = 0; config_options[i].name != NULL; i++) {
  12705. default_value = config_options[i].default_value;
  12706. if (ctx->config[i] == NULL && default_value != NULL) {
  12707. ctx->config[i] = mg_strdup(default_value);
  12708. }
  12709. }
  12710. workerthreadcount = atoi(ctx->config[NUM_THREADS]);
  12711. if (workerthreadcount > MAX_WORKER_THREADS) {
  12712. mg_cry(fc(ctx), "Too many worker threads");
  12713. free_context(ctx);
  12714. pthread_setspecific(sTlsKey, NULL);
  12715. return NULL;
  12716. }
  12717. if (workerthreadcount <= 0) {
  12718. mg_cry(fc(ctx), "Invalid number of worker threads");
  12719. free_context(ctx);
  12720. pthread_setspecific(sTlsKey, NULL);
  12721. return NULL;
  12722. }
  12723. #if defined(NO_FILES)
  12724. if (ctx->config[DOCUMENT_ROOT] != NULL) {
  12725. mg_cry(fc(ctx), "%s", "Document root must not be set");
  12726. free_context(ctx);
  12727. pthread_setspecific(sTlsKey, NULL);
  12728. return NULL;
  12729. }
  12730. #endif
  12731. get_system_name(&ctx->systemName);
  12732. #if defined(USE_LUA)
  12733. /* If a Lua background script has been configured, start it. */
  12734. if (ctx->config[LUA_BACKGROUND_SCRIPT] != NULL) {
  12735. char ebuf[256];
  12736. void *state = (void *)mg_prepare_lua_context_script(
  12737. ctx->config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  12738. if (!state) {
  12739. mg_cry(fc(ctx), "lua_background_script error: %s", ebuf);
  12740. free_context(ctx);
  12741. pthread_setspecific(sTlsKey, NULL);
  12742. return NULL;
  12743. }
  12744. ctx->lua_background_state = state;
  12745. } else {
  12746. ctx->lua_background_state = 0;
  12747. }
  12748. #endif
  12749. /* NOTE(lsm): order is important here. SSL certificates must
  12750. * be initialized before listening ports. UID must be set last. */
  12751. if (!set_gpass_option(ctx) ||
  12752. #if !defined(NO_SSL)
  12753. !set_ssl_option(ctx) ||
  12754. #endif
  12755. !set_ports_option(ctx) ||
  12756. #if !defined(_WIN32)
  12757. !set_uid_option(ctx) ||
  12758. #endif
  12759. !set_acl_option(ctx)) {
  12760. free_context(ctx);
  12761. pthread_setspecific(sTlsKey, NULL);
  12762. return NULL;
  12763. }
  12764. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  12765. /* Ignore SIGPIPE signal, so if browser cancels the request, it
  12766. * won't kill the whole process. */
  12767. (void)signal(SIGPIPE, SIG_IGN);
  12768. #endif /* !_WIN32 && !__SYMBIAN32__ */
  12769. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  12770. ctx->worker_threadids =
  12771. (pthread_t *)mg_calloc(ctx->cfg_worker_threads, sizeof(pthread_t));
  12772. if (ctx->worker_threadids == NULL) {
  12773. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  12774. free_context(ctx);
  12775. pthread_setspecific(sTlsKey, NULL);
  12776. return NULL;
  12777. }
  12778. ctx->worker_connections =
  12779. (struct mg_connection *)mg_calloc(ctx->cfg_worker_threads,
  12780. sizeof(struct mg_connection));
  12781. if (ctx->worker_connections == NULL) {
  12782. mg_cry(fc(ctx), "Not enough memory for worker thread connection array");
  12783. free_context(ctx);
  12784. pthread_setspecific(sTlsKey, NULL);
  12785. return NULL;
  12786. }
  12787. #if defined(ALTERNATIVE_QUEUE)
  12788. ctx->client_wait_events =
  12789. mg_calloc(sizeof(ctx->client_wait_events[0]), ctx->cfg_worker_threads);
  12790. if (ctx->client_wait_events == NULL) {
  12791. mg_cry(fc(ctx), "Not enough memory for worker event array");
  12792. mg_free(ctx->worker_threadids);
  12793. free_context(ctx);
  12794. pthread_setspecific(sTlsKey, NULL);
  12795. return NULL;
  12796. }
  12797. ctx->client_socks =
  12798. mg_calloc(sizeof(ctx->client_socks[0]), ctx->cfg_worker_threads);
  12799. if (ctx->client_wait_events == NULL) {
  12800. mg_cry(fc(ctx), "Not enough memory for worker socket array");
  12801. mg_free(ctx->client_socks);
  12802. mg_free(ctx->worker_threadids);
  12803. free_context(ctx);
  12804. pthread_setspecific(sTlsKey, NULL);
  12805. return NULL;
  12806. }
  12807. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  12808. ctx->client_wait_events[i] = event_create();
  12809. if (ctx->client_wait_events[i] == 0) {
  12810. mg_cry(fc(ctx), "Error creating worker event %i", i);
  12811. while (i > 0) {
  12812. i--;
  12813. event_destroy(ctx->client_wait_events[i]);
  12814. }
  12815. mg_free(ctx->client_socks);
  12816. mg_free(ctx->worker_threadids);
  12817. free_context(ctx);
  12818. pthread_setspecific(sTlsKey, NULL);
  12819. return NULL;
  12820. }
  12821. }
  12822. #endif
  12823. #if defined(USE_TIMERS)
  12824. if (timers_init(ctx) != 0) {
  12825. mg_cry(fc(ctx), "Error creating timers");
  12826. free_context(ctx);
  12827. pthread_setspecific(sTlsKey, NULL);
  12828. return NULL;
  12829. }
  12830. #endif
  12831. /* Context has been created - init user libraries */
  12832. if (ctx->callbacks.init_context) {
  12833. ctx->callbacks.init_context(ctx);
  12834. }
  12835. ctx->callbacks.exit_context = exit_callback;
  12836. ctx->context_type = 1; /* server context */
  12837. /* Start master (listening) thread */
  12838. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  12839. /* Start worker threads */
  12840. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  12841. struct worker_thread_args *wta =
  12842. mg_malloc(sizeof(struct worker_thread_args));
  12843. if (wta) {
  12844. wta->ctx = ctx;
  12845. wta->index = (int)i;
  12846. }
  12847. if ((wta == NULL)
  12848. || (mg_start_thread_with_id(worker_thread,
  12849. wta,
  12850. &ctx->worker_threadids[i]) != 0)) {
  12851. /* thread was not created */
  12852. if (wta != NULL) {
  12853. mg_free(wta);
  12854. }
  12855. if (i > 0) {
  12856. mg_cry(fc(ctx),
  12857. "Cannot start worker thread %i: error %ld",
  12858. i + 1,
  12859. (long)ERRNO);
  12860. } else {
  12861. mg_cry(fc(ctx),
  12862. "Cannot create threads: error %ld",
  12863. (long)ERRNO);
  12864. free_context(ctx);
  12865. pthread_setspecific(sTlsKey, NULL);
  12866. return NULL;
  12867. }
  12868. break;
  12869. }
  12870. }
  12871. pthread_setspecific(sTlsKey, NULL);
  12872. return ctx;
  12873. }
  12874. /* Feature check API function */
  12875. unsigned
  12876. mg_check_feature(unsigned feature)
  12877. {
  12878. static const unsigned feature_set = 0
  12879. /* Set bits for available features according to API documentation.
  12880. * This bit mask is created at compile time, according to the active
  12881. * preprocessor defines. It is a single const value at runtime. */
  12882. #if !defined(NO_FILES)
  12883. | 0x0001u
  12884. #endif
  12885. #if !defined(NO_SSL)
  12886. | 0x0002u
  12887. #endif
  12888. #if !defined(NO_CGI)
  12889. | 0x0004u
  12890. #endif
  12891. #if defined(USE_IPV6)
  12892. | 0x0008u
  12893. #endif
  12894. #if defined(USE_WEBSOCKET)
  12895. | 0x0010u
  12896. #endif
  12897. #if defined(USE_LUA)
  12898. | 0x0020u
  12899. #endif
  12900. #if defined(USE_DUKTAPE)
  12901. | 0x0040u
  12902. #endif
  12903. #if !defined(NO_CACHING)
  12904. | 0x0080u
  12905. #endif
  12906. /* Set some extra bits not defined in the API documentation.
  12907. * These bits may change without further notice. */
  12908. #if defined(MG_LEGACY_INTERFACE)
  12909. | 0x8000u
  12910. #endif
  12911. #if defined(MEMORY_DEBUGGING)
  12912. | 0x0100u
  12913. #endif
  12914. #if defined(USE_TIMERS)
  12915. | 0x0200u
  12916. #endif
  12917. #if !defined(NO_NONCE_CHECK)
  12918. | 0x0400u
  12919. #endif
  12920. #if !defined(NO_POPEN)
  12921. | 0x0800u
  12922. #endif
  12923. ;
  12924. return (feature & feature_set);
  12925. }
  12926. /* Get system information. It can be printed or stored by the caller.
  12927. * Return the size of available information. */
  12928. static int
  12929. mg_get_system_info_impl(char *buffer, int buflen)
  12930. {
  12931. char block[256];
  12932. int system_info_length = 0;
  12933. #if defined(_WIN32)
  12934. const char *eol = "\r\n";
  12935. #else
  12936. const char *eol = "\n";
  12937. #endif
  12938. /* Server version */
  12939. {
  12940. const char *version = mg_version();
  12941. mg_snprintf(NULL,
  12942. NULL,
  12943. block,
  12944. sizeof(block),
  12945. "Server Version: %s%s",
  12946. version,
  12947. eol);
  12948. system_info_length += (int)strlen(block);
  12949. if (system_info_length < buflen) {
  12950. strcat(buffer, block);
  12951. }
  12952. }
  12953. /* System info */
  12954. {
  12955. #if defined(_WIN32)
  12956. #if !defined(__SYMBIAN32__)
  12957. DWORD dwVersion = 0;
  12958. DWORD dwMajorVersion = 0;
  12959. DWORD dwMinorVersion = 0;
  12960. SYSTEM_INFO si;
  12961. GetSystemInfo(&si);
  12962. #ifdef _MSC_VER
  12963. #pragma warning(push)
  12964. /* GetVersion was declared deprecated */
  12965. #pragma warning(disable : 4996)
  12966. #endif
  12967. dwVersion = GetVersion();
  12968. #ifdef _MSC_VER
  12969. #pragma warning(pop)
  12970. #endif
  12971. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  12972. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  12973. mg_snprintf(NULL,
  12974. NULL,
  12975. block,
  12976. sizeof(block),
  12977. "Windows %u.%u%s",
  12978. (unsigned)dwMajorVersion,
  12979. (unsigned)dwMinorVersion,
  12980. eol);
  12981. system_info_length += (int)strlen(block);
  12982. if (system_info_length < buflen) {
  12983. strcat(buffer, block);
  12984. }
  12985. mg_snprintf(NULL,
  12986. NULL,
  12987. block,
  12988. sizeof(block),
  12989. "CPU: type %u, cores %u, mask %x%s",
  12990. (unsigned)si.wProcessorArchitecture,
  12991. (unsigned)si.dwNumberOfProcessors,
  12992. (unsigned)si.dwActiveProcessorMask,
  12993. eol);
  12994. system_info_length += (int)strlen(block);
  12995. if (system_info_length < buflen) {
  12996. strcat(buffer, block);
  12997. }
  12998. #else
  12999. mg_snprintf(NULL, NULL, block, sizeof(block), "%s - Symbian%s", eol);
  13000. system_info_length += (int)strlen(block);
  13001. if (system_info_length < buflen) {
  13002. strcat(buffer, block);
  13003. }
  13004. #endif
  13005. #else
  13006. struct utsname name;
  13007. memset(&name, 0, sizeof(name));
  13008. uname(&name);
  13009. mg_snprintf(NULL,
  13010. NULL,
  13011. block,
  13012. sizeof(block),
  13013. "%s %s (%s) - %s%s",
  13014. name.sysname,
  13015. name.version,
  13016. name.release,
  13017. name.machine,
  13018. eol);
  13019. system_info_length += (int)strlen(block);
  13020. if (system_info_length < buflen) {
  13021. strcat(buffer, block);
  13022. }
  13023. #endif
  13024. }
  13025. /* Features */
  13026. {
  13027. mg_snprintf(NULL,
  13028. NULL,
  13029. block,
  13030. sizeof(block),
  13031. "Features: %X%s%s%s%s%s%s%s%s%s%s",
  13032. mg_check_feature(0xFFFFFFFFu),
  13033. eol,
  13034. mg_check_feature(1) ? " Files" : "",
  13035. mg_check_feature(2) ? " HTTPS" : "",
  13036. mg_check_feature(4) ? " CGI" : "",
  13037. mg_check_feature(8) ? " IPv6" : "",
  13038. mg_check_feature(16) ? " WebSockets" : "",
  13039. mg_check_feature(32) ? " Lua" : "",
  13040. mg_check_feature(64) ? " JavaScript" : "",
  13041. mg_check_feature(128) ? " Cache" : "",
  13042. eol);
  13043. system_info_length += (int)strlen(block);
  13044. if (system_info_length < buflen) {
  13045. strcat(buffer, block);
  13046. }
  13047. #ifdef USE_LUA
  13048. mg_snprintf(NULL,
  13049. NULL,
  13050. block,
  13051. sizeof(block),
  13052. "Lua Version: %u (%s)%s",
  13053. (unsigned)LUA_VERSION_NUM,
  13054. LUA_RELEASE,
  13055. eol);
  13056. system_info_length += (int)strlen(block);
  13057. if (system_info_length < buflen) {
  13058. strcat(buffer, block);
  13059. }
  13060. #endif
  13061. #if defined(USE_DUKTAPE)
  13062. mg_snprintf(NULL,
  13063. NULL,
  13064. block,
  13065. sizeof(block),
  13066. "JavaScript: Duktape %u.%u.%u%s",
  13067. (unsigned)DUK_VERSION / 10000,
  13068. ((unsigned)DUK_VERSION / 100) % 100,
  13069. (unsigned)DUK_VERSION % 100,
  13070. eol);
  13071. system_info_length += (int)strlen(block);
  13072. if (system_info_length < buflen) {
  13073. strcat(buffer, block);
  13074. }
  13075. #endif
  13076. }
  13077. /* Build date */
  13078. {
  13079. mg_snprintf(
  13080. NULL, NULL, block, sizeof(block), "Build: %s%s", __DATE__, eol);
  13081. system_info_length += (int)strlen(block);
  13082. if (system_info_length < buflen) {
  13083. strcat(buffer, block);
  13084. }
  13085. }
  13086. /* Compiler information */
  13087. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  13088. {
  13089. #if defined(_MSC_VER)
  13090. mg_snprintf(NULL,
  13091. NULL,
  13092. block,
  13093. sizeof(block),
  13094. "MSC: %u (%u)%s",
  13095. (unsigned)_MSC_VER,
  13096. (unsigned)_MSC_FULL_VER,
  13097. eol);
  13098. system_info_length += (int)strlen(block);
  13099. if (system_info_length < buflen) {
  13100. strcat(buffer, block);
  13101. }
  13102. #elif defined(__MINGW64__)
  13103. mg_snprintf(NULL,
  13104. NULL,
  13105. block,
  13106. sizeof(block),
  13107. "MinGW64: %u.%u%s",
  13108. (unsigned)__MINGW64_VERSION_MAJOR,
  13109. (unsigned)__MINGW64_VERSION_MINOR,
  13110. eol);
  13111. system_info_length += (int)strlen(block);
  13112. if (system_info_length < buflen) {
  13113. strcat(buffer, block);
  13114. }
  13115. mg_snprintf(NULL,
  13116. NULL,
  13117. block,
  13118. sizeof(block),
  13119. "MinGW32: %u.%u%s",
  13120. (unsigned)__MINGW32_MAJOR_VERSION,
  13121. (unsigned)__MINGW32_MINOR_VERSION,
  13122. eol);
  13123. system_info_length += (int)strlen(block);
  13124. if (system_info_length < buflen) {
  13125. strcat(buffer, block);
  13126. }
  13127. #elif defined(__MINGW32__)
  13128. mg_snprintf(NULL,
  13129. NULL,
  13130. block,
  13131. sizeof(block),
  13132. "MinGW32: %u.%u%s",
  13133. (unsigned)__MINGW32_MAJOR_VERSION,
  13134. (unsigned)__MINGW32_MINOR_VERSION,
  13135. eol);
  13136. system_info_length += (int)strlen(block);
  13137. if (system_info_length < buflen) {
  13138. strcat(buffer, block);
  13139. }
  13140. #elif defined(__clang__)
  13141. mg_snprintf(NULL,
  13142. NULL,
  13143. block,
  13144. sizeof(block),
  13145. "clang: %u.%u.%u (%s)%s",
  13146. __clang_major__,
  13147. __clang_minor__,
  13148. __clang_patchlevel__,
  13149. __clang_version__,
  13150. eol);
  13151. system_info_length += (int)strlen(block);
  13152. if (system_info_length < buflen) {
  13153. strcat(buffer, block);
  13154. }
  13155. #elif defined(__GNUC__)
  13156. mg_snprintf(NULL,
  13157. NULL,
  13158. block,
  13159. sizeof(block),
  13160. "gcc: %u.%u.%u%s",
  13161. (unsigned)__GNUC__,
  13162. (unsigned)__GNUC_MINOR__,
  13163. (unsigned)__GNUC_PATCHLEVEL__,
  13164. eol);
  13165. system_info_length += (int)strlen(block);
  13166. if (system_info_length < buflen) {
  13167. strcat(buffer, block);
  13168. }
  13169. #elif defined(__INTEL_COMPILER)
  13170. mg_snprintf(NULL,
  13171. NULL,
  13172. block,
  13173. sizeof(block),
  13174. "Intel C/C++: %u%s",
  13175. (unsigned)__INTEL_COMPILER,
  13176. eol);
  13177. system_info_length += (int)strlen(block);
  13178. if (system_info_length < buflen) {
  13179. strcat(buffer, block);
  13180. }
  13181. #elif defined(__BORLANDC__)
  13182. mg_snprintf(NULL,
  13183. NULL,
  13184. block,
  13185. sizeof(block),
  13186. "Borland C: 0x%x%s",
  13187. (unsigned)__BORLANDC__,
  13188. eol);
  13189. system_info_length += (int)strlen(block);
  13190. if (system_info_length < buflen) {
  13191. strcat(buffer, block);
  13192. }
  13193. #elif defined(__SUNPRO_C)
  13194. mg_snprintf(NULL,
  13195. NULL,
  13196. block,
  13197. sizeof(block),
  13198. "Solaris: 0x%x%s",
  13199. (unsigned)__SUNPRO_C,
  13200. eol);
  13201. system_info_length += (int)strlen(block);
  13202. if (system_info_length < buflen) {
  13203. strcat(buffer, block);
  13204. }
  13205. #else
  13206. mg_snprintf(NULL, NULL, block, sizeof(block), "Other compiler%s", eol);
  13207. system_info_length += (int)strlen(block);
  13208. if (system_info_length < buflen) {
  13209. strcat(buffer, block);
  13210. }
  13211. #endif
  13212. }
  13213. /* Determine 32/64 bit data mode.
  13214. * see https://en.wikipedia.org/wiki/64-bit_computing */
  13215. {
  13216. mg_snprintf(NULL,
  13217. NULL,
  13218. block,
  13219. sizeof(block),
  13220. "Data model: int:%u/%u/%u/%u, float:%u/%u/%u, char:%u/%u, "
  13221. "ptr:%u, size:%u, time:%u%s",
  13222. (unsigned)sizeof(short),
  13223. (unsigned)sizeof(int),
  13224. (unsigned)sizeof(long),
  13225. (unsigned)sizeof(long long),
  13226. (unsigned)sizeof(float),
  13227. (unsigned)sizeof(double),
  13228. (unsigned)sizeof(long double),
  13229. (unsigned)sizeof(char),
  13230. (unsigned)sizeof(wchar_t),
  13231. (unsigned)sizeof(void *),
  13232. (unsigned)sizeof(size_t),
  13233. (unsigned)sizeof(time_t),
  13234. eol);
  13235. system_info_length += (int)strlen(block);
  13236. if (system_info_length < buflen) {
  13237. strcat(buffer, block);
  13238. }
  13239. }
  13240. return system_info_length;
  13241. }
  13242. /* Get system information. It can be printed or stored by the caller.
  13243. * Return the size of available information. */
  13244. int
  13245. mg_get_system_info(char *buffer, int buflen)
  13246. {
  13247. if ((buffer == NULL) || (buflen < 1)) {
  13248. return mg_get_system_info_impl(NULL, 0);
  13249. } else {
  13250. /* Reset buffer, so we can always use strcat. */
  13251. buffer[0] = 0;
  13252. return mg_get_system_info_impl(buffer, buflen);
  13253. }
  13254. }
  13255. /* mg_init_library counter */
  13256. static int mg_init_library_called = 0;
  13257. /* Initialize this library. This function does not need to be thread safe. */
  13258. unsigned
  13259. mg_init_library(unsigned features)
  13260. {
  13261. /* Currently we do nothing here. This is planned for Version 1.10.
  13262. * For now, we just add this function, so clients can be changed early. */
  13263. if (mg_init_library_called <= 0) {
  13264. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13265. WSADATA data;
  13266. WSAStartup(MAKEWORD(2, 2), &data);
  13267. #endif /* _WIN32 && !__SYMBIAN32__ */
  13268. mg_init_library_called = 1;
  13269. } else {
  13270. mg_init_library_called++;
  13271. }
  13272. return mg_check_feature(features & 0xFFu);
  13273. }
  13274. /* Un-initialize this library. */
  13275. unsigned
  13276. mg_exit_library(void)
  13277. {
  13278. if (mg_init_library_called <= 0) {
  13279. return 0;
  13280. }
  13281. mg_init_library_called--;
  13282. if (mg_init_library_called == 0) {
  13283. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13284. (void)WSACleanup();
  13285. #endif /* _WIN32 && !__SYMBIAN32__ */
  13286. }
  13287. return 1;
  13288. }
  13289. /* End of civetweb.c */