civetweb.c 405 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340
  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. /* Get some operating system independent thread id */
  998. unsigned long thread_id = mg_current_thread_id();
  999. msmow = mg_get_current_time();
  1000. flockfile(stdout);
  1001. printf("*** %lu.%09lu %12" INT64_FMT " %lu %s:%u: ",
  1002. (unsigned long)tsnow.tv_sec,
  1003. (unsigned long)tsnow.tv_nsec,
  1004. nsnow - nslast,
  1005. thread_id,
  1006. func,
  1007. line);
  1008. va_start(args, fmt);
  1009. vprintf(fmt, args);
  1010. va_end(args);
  1011. putchar('\n');
  1012. fflush(stdout);
  1013. funlockfile(stdout);
  1014. nslast = nsnow;
  1015. }
  1016. #define DEBUG_TRACE(fmt, ...) \
  1017. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  1018. #else
  1019. #define DEBUG_TRACE(fmt, ...) \
  1020. do { \
  1021. } while (0)
  1022. #endif /* DEBUG */
  1023. #endif /* DEBUG_TRACE */
  1024. #define MD5_STATIC static
  1025. #include "md5.inl"
  1026. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1027. #ifdef NO_SOCKLEN_T
  1028. typedef int socklen_t;
  1029. #endif /* NO_SOCKLEN_T */
  1030. #define _DARWIN_UNLIMITED_SELECT
  1031. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1032. #if !defined(MSG_NOSIGNAL)
  1033. #define MSG_NOSIGNAL (0)
  1034. #endif
  1035. #if !defined(SOMAXCONN)
  1036. #define SOMAXCONN (100)
  1037. #endif
  1038. /* Size of the accepted socket queue */
  1039. #if !defined(MGSQLEN)
  1040. #define MGSQLEN (20)
  1041. #endif
  1042. #if defined(NO_SSL)
  1043. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1044. typedef struct SSL_CTX SSL_CTX;
  1045. #else
  1046. #if defined(NO_SSL_DL)
  1047. #include <openssl/ssl.h>
  1048. #include <openssl/err.h>
  1049. #include <openssl/crypto.h>
  1050. #include <openssl/x509.h>
  1051. #include <openssl/pem.h>
  1052. #include <openssl/engine.h>
  1053. #include <openssl/conf.h>
  1054. #include <openssl/dh.h>
  1055. #include <openssl/bn.h>
  1056. #include <openssl/opensslv.h>
  1057. #else
  1058. /* SSL loaded dynamically from DLL.
  1059. * I put the prototypes here to be independent from OpenSSL source
  1060. * installation. */
  1061. typedef struct ssl_st SSL;
  1062. typedef struct ssl_method_st SSL_METHOD;
  1063. typedef struct ssl_ctx_st SSL_CTX;
  1064. typedef struct x509_store_ctx_st X509_STORE_CTX;
  1065. typedef struct x509_name X509_NAME;
  1066. typedef struct asn1_integer ASN1_INTEGER;
  1067. typedef struct bignum BIGNUM;
  1068. typedef struct ossl_init_settings_st OPENSSL_INIT_SETTINGS;
  1069. typedef struct evp_md EVP_MD;
  1070. typedef struct x509 X509;
  1071. #define SSL_CTRL_OPTIONS (32)
  1072. #define SSL_CTRL_CLEAR_OPTIONS (77)
  1073. #define SSL_CTRL_SET_ECDH_AUTO (94)
  1074. #define OPENSSL_INIT_NO_LOAD_SSL_STRINGS 0x00100000L
  1075. #define OPENSSL_INIT_LOAD_SSL_STRINGS 0x00200000L
  1076. #define OPENSSL_INIT_LOAD_CRYPTO_STRINGS 0x00000002L
  1077. #define SSL_VERIFY_NONE (0)
  1078. #define SSL_VERIFY_PEER (1)
  1079. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  1080. #define SSL_VERIFY_CLIENT_ONCE (4)
  1081. #define SSL_OP_ALL ((long)(0x80000BFFUL))
  1082. #define SSL_OP_NO_SSLv2 (0x01000000L)
  1083. #define SSL_OP_NO_SSLv3 (0x02000000L)
  1084. #define SSL_OP_NO_TLSv1 (0x04000000L)
  1085. #define SSL_OP_NO_TLSv1_2 (0x08000000L)
  1086. #define SSL_OP_NO_TLSv1_1 (0x10000000L)
  1087. #define SSL_OP_SINGLE_DH_USE (0x00100000L)
  1088. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000L)
  1089. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000L)
  1090. #define SSL_ERROR_NONE (0)
  1091. #define SSL_ERROR_SSL (1)
  1092. #define SSL_ERROR_WANT_READ (2)
  1093. #define SSL_ERROR_WANT_WRITE (3)
  1094. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  1095. #define SSL_ERROR_SYSCALL (5) /* see errno */
  1096. #define SSL_ERROR_ZERO_RETURN (6)
  1097. #define SSL_ERROR_WANT_CONNECT (7)
  1098. #define SSL_ERROR_WANT_ACCEPT (8)
  1099. struct ssl_func {
  1100. const char *name; /* SSL function name */
  1101. void (*ptr)(void); /* Function pointer */
  1102. };
  1103. #ifdef OPENSSL_API_1_1
  1104. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1105. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1106. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1107. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1108. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1109. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1110. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1111. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  1112. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  1113. #define TLS_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  1114. #define OPENSSL_init_ssl \
  1115. (*(int (*)(uint64_t opts, \
  1116. const OPENSSL_INIT_SETTINGS *settings))ssl_sw[10].ptr)
  1117. #define SSL_CTX_use_PrivateKey_file \
  1118. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1119. #define SSL_CTX_use_certificate_file \
  1120. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1121. #define SSL_CTX_set_default_passwd_cb \
  1122. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1123. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1124. #define SSL_CTX_use_certificate_chain_file \
  1125. (*(int (*)(SSL_CTX *, const char *))ssl_sw[15].ptr)
  1126. #define TLS_client_method (*(SSL_METHOD * (*)(void))ssl_sw[16].ptr)
  1127. #define SSL_pending (*(int (*)(SSL *))ssl_sw[17].ptr)
  1128. #define SSL_CTX_set_verify \
  1129. (*(void (*)(SSL_CTX *, \
  1130. int, \
  1131. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[18].ptr)
  1132. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[19].ptr)
  1133. #define SSL_CTX_load_verify_locations \
  1134. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[20].ptr)
  1135. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[21].ptr)
  1136. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[22].ptr)
  1137. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[23].ptr)
  1138. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[24].ptr)
  1139. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[25].ptr)
  1140. #define SSL_CIPHER_get_name \
  1141. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[26].ptr)
  1142. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[27].ptr)
  1143. #define SSL_CTX_set_session_id_context \
  1144. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[28].ptr)
  1145. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[29].ptr)
  1146. #define SSL_CTX_set_cipher_list \
  1147. (*(int (*)(SSL_CTX *, const char *))ssl_sw[30].ptr)
  1148. #define SSL_CTX_set_options \
  1149. (*(unsigned long (*)(SSL_CTX *, unsigned long))ssl_sw[31].ptr)
  1150. #define SSL_CTX_clear_options(ctx, op) \
  1151. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1152. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1153. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1154. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1155. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1156. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[0].ptr)
  1157. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[1].ptr)
  1158. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[2].ptr)
  1159. #define CONF_modules_unload (*(void (*)(int))crypto_sw[3].ptr)
  1160. #define X509_free (*(void (*)(X509 *))crypto_sw[4].ptr)
  1161. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[5].ptr)
  1162. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[6].ptr)
  1163. #define X509_NAME_oneline \
  1164. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[7].ptr)
  1165. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[8].ptr)
  1166. #define EVP_get_digestbyname \
  1167. (*(const EVP_MD *(*)(const char *))crypto_sw[9].ptr)
  1168. #define ASN1_digest \
  1169. (*(int (*)(int (*)(), \
  1170. const EVP_MD *, \
  1171. char *, \
  1172. unsigned char *, \
  1173. unsigned int *))crypto_sw[10].ptr)
  1174. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[11].ptr)
  1175. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[12].ptr)
  1176. #define ASN1_INTEGER_to_BN \
  1177. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn))crypto_sw[13].ptr)
  1178. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[14].ptr)
  1179. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[15].ptr)
  1180. #define OPENSSL_free(a) CRYPTO_free(a)
  1181. /* set_ssl_option() function updates this array.
  1182. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1183. * of respective functions. The macros above (like SSL_connect()) are really
  1184. * just calling these functions indirectly via the pointer. */
  1185. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1186. {"SSL_accept", NULL},
  1187. {"SSL_connect", NULL},
  1188. {"SSL_read", NULL},
  1189. {"SSL_write", NULL},
  1190. {"SSL_get_error", NULL},
  1191. {"SSL_set_fd", NULL},
  1192. {"SSL_new", NULL},
  1193. {"SSL_CTX_new", NULL},
  1194. {"TLS_server_method", NULL},
  1195. {"OPENSSL_init_ssl", NULL},
  1196. {"SSL_CTX_use_PrivateKey_file", NULL},
  1197. {"SSL_CTX_use_certificate_file", NULL},
  1198. {"SSL_CTX_set_default_passwd_cb", NULL},
  1199. {"SSL_CTX_free", NULL},
  1200. {"SSL_CTX_use_certificate_chain_file", NULL},
  1201. {"TLS_client_method", NULL},
  1202. {"SSL_pending", NULL},
  1203. {"SSL_CTX_set_verify", NULL},
  1204. {"SSL_shutdown", NULL},
  1205. {"SSL_CTX_load_verify_locations", NULL},
  1206. {"SSL_CTX_set_default_verify_paths", NULL},
  1207. {"SSL_CTX_set_verify_depth", NULL},
  1208. {"SSL_get_peer_certificate", NULL},
  1209. {"SSL_get_version", NULL},
  1210. {"SSL_get_current_cipher", NULL},
  1211. {"SSL_CIPHER_get_name", NULL},
  1212. {"SSL_CTX_check_private_key", NULL},
  1213. {"SSL_CTX_set_session_id_context", NULL},
  1214. {"SSL_CTX_ctrl", NULL},
  1215. {"SSL_CTX_set_cipher_list", NULL},
  1216. {"SSL_CTX_set_options", NULL},
  1217. {NULL, NULL}};
  1218. /* Similar array as ssl_sw. These functions could be located in different
  1219. * lib. */
  1220. static struct ssl_func crypto_sw[] = {{"ERR_get_error", NULL},
  1221. {"ERR_error_string", NULL},
  1222. {"ERR_remove_state", NULL},
  1223. {"CONF_modules_unload", NULL},
  1224. {"X509_free", NULL},
  1225. {"X509_get_subject_name", NULL},
  1226. {"X509_get_issuer_name", NULL},
  1227. {"X509_NAME_oneline", NULL},
  1228. {"X509_get_serialNumber", NULL},
  1229. {"EVP_get_digestbyname", NULL},
  1230. {"ASN1_digest", NULL},
  1231. {"i2d_X509", NULL},
  1232. {"BN_bn2hex", NULL},
  1233. {"ASN1_INTEGER_to_BN", NULL},
  1234. {"BN_free", NULL},
  1235. {"CRYPTO_free", NULL},
  1236. {NULL, NULL}};
  1237. #else
  1238. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1239. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1240. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1241. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1242. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1243. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1244. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1245. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  1246. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  1247. #define SSLv23_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  1248. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  1249. #define SSL_CTX_use_PrivateKey_file \
  1250. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1251. #define SSL_CTX_use_certificate_file \
  1252. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1253. #define SSL_CTX_set_default_passwd_cb \
  1254. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1255. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1256. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  1257. #define SSL_CTX_use_certificate_chain_file \
  1258. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  1259. #define SSLv23_client_method (*(SSL_METHOD * (*)(void))ssl_sw[17].ptr)
  1260. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  1261. #define SSL_CTX_set_verify \
  1262. (*(void (*)(SSL_CTX *, \
  1263. int, \
  1264. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19].ptr)
  1265. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  1266. #define SSL_CTX_load_verify_locations \
  1267. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  1268. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  1269. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  1270. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[24].ptr)
  1271. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  1272. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[26].ptr)
  1273. #define SSL_CIPHER_get_name \
  1274. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  1275. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  1276. #define SSL_CTX_set_session_id_context \
  1277. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  1278. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  1279. #define SSL_CTX_set_cipher_list \
  1280. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  1281. #define SSL_CTX_set_options(ctx, op) \
  1282. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  1283. #define SSL_CTX_clear_options(ctx, op) \
  1284. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1285. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1286. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1287. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1288. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1289. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  1290. #define CRYPTO_set_locking_callback \
  1291. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  1292. #define CRYPTO_set_id_callback \
  1293. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  1294. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  1295. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  1296. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  1297. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  1298. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  1299. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  1300. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  1301. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  1302. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  1303. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[12].ptr)
  1304. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[13].ptr)
  1305. #define X509_NAME_oneline \
  1306. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  1307. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[15].ptr)
  1308. #define i2c_ASN1_INTEGER \
  1309. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  1310. #define EVP_get_digestbyname \
  1311. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1312. #define ASN1_digest \
  1313. (*(int (*)(int (*)(), \
  1314. const EVP_MD *, \
  1315. char *, \
  1316. unsigned char *, \
  1317. unsigned int *))crypto_sw[18].ptr)
  1318. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1319. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[20].ptr)
  1320. #define ASN1_INTEGER_to_BN \
  1321. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn))crypto_sw[21].ptr)
  1322. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[22].ptr)
  1323. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[23].ptr)
  1324. #define OPENSSL_free(a) CRYPTO_free(a)
  1325. /* set_ssl_option() function updates this array.
  1326. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1327. * of respective functions. The macros above (like SSL_connect()) are really
  1328. * just calling these functions indirectly via the pointer. */
  1329. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1330. {"SSL_accept", NULL},
  1331. {"SSL_connect", NULL},
  1332. {"SSL_read", NULL},
  1333. {"SSL_write", NULL},
  1334. {"SSL_get_error", NULL},
  1335. {"SSL_set_fd", NULL},
  1336. {"SSL_new", NULL},
  1337. {"SSL_CTX_new", NULL},
  1338. {"SSLv23_server_method", NULL},
  1339. {"SSL_library_init", NULL},
  1340. {"SSL_CTX_use_PrivateKey_file", NULL},
  1341. {"SSL_CTX_use_certificate_file", NULL},
  1342. {"SSL_CTX_set_default_passwd_cb", NULL},
  1343. {"SSL_CTX_free", NULL},
  1344. {"SSL_load_error_strings", NULL},
  1345. {"SSL_CTX_use_certificate_chain_file", NULL},
  1346. {"SSLv23_client_method", NULL},
  1347. {"SSL_pending", NULL},
  1348. {"SSL_CTX_set_verify", NULL},
  1349. {"SSL_shutdown", NULL},
  1350. {"SSL_CTX_load_verify_locations", NULL},
  1351. {"SSL_CTX_set_default_verify_paths", NULL},
  1352. {"SSL_CTX_set_verify_depth", NULL},
  1353. {"SSL_get_peer_certificate", NULL},
  1354. {"SSL_get_version", NULL},
  1355. {"SSL_get_current_cipher", NULL},
  1356. {"SSL_CIPHER_get_name", NULL},
  1357. {"SSL_CTX_check_private_key", NULL},
  1358. {"SSL_CTX_set_session_id_context", NULL},
  1359. {"SSL_CTX_ctrl", NULL},
  1360. {"SSL_CTX_set_cipher_list", NULL},
  1361. {NULL, NULL}};
  1362. /* Similar array as ssl_sw. These functions could be located in different
  1363. * lib. */
  1364. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  1365. {"CRYPTO_set_locking_callback", NULL},
  1366. {"CRYPTO_set_id_callback", NULL},
  1367. {"ERR_get_error", NULL},
  1368. {"ERR_error_string", NULL},
  1369. {"ERR_remove_state", NULL},
  1370. {"ERR_free_strings", NULL},
  1371. {"ENGINE_cleanup", NULL},
  1372. {"CONF_modules_unload", NULL},
  1373. {"CRYPTO_cleanup_all_ex_data", NULL},
  1374. {"EVP_cleanup", NULL},
  1375. {"X509_free", NULL},
  1376. {"X509_get_subject_name", NULL},
  1377. {"X509_get_issuer_name", NULL},
  1378. {"X509_NAME_oneline", NULL},
  1379. {"X509_get_serialNumber", NULL},
  1380. {"i2c_ASN1_INTEGER", NULL},
  1381. {"EVP_get_digestbyname", NULL},
  1382. {"ASN1_digest", NULL},
  1383. {"i2d_X509", NULL},
  1384. {"BN_bn2hex", NULL},
  1385. {"ASN1_INTEGER_to_BN", NULL},
  1386. {"BN_free", NULL},
  1387. {"CRYPTO_free", NULL},
  1388. {NULL, NULL}};
  1389. #endif /* OPENSSL_API_1_1 */
  1390. #endif /* NO_SSL_DL */
  1391. #endif /* NO_SSL */
  1392. #if !defined(NO_CACHING)
  1393. static const char *month_names[] = {"Jan",
  1394. "Feb",
  1395. "Mar",
  1396. "Apr",
  1397. "May",
  1398. "Jun",
  1399. "Jul",
  1400. "Aug",
  1401. "Sep",
  1402. "Oct",
  1403. "Nov",
  1404. "Dec"};
  1405. #endif /* !NO_CACHING */
  1406. /* Unified socket address. For IPv6 support, add IPv6 address structure in the
  1407. * union u. */
  1408. union usa {
  1409. struct sockaddr sa;
  1410. struct sockaddr_in sin;
  1411. #if defined(USE_IPV6)
  1412. struct sockaddr_in6 sin6;
  1413. #endif
  1414. };
  1415. /* Describes a string (chunk of memory). */
  1416. struct vec {
  1417. const char *ptr;
  1418. size_t len;
  1419. };
  1420. struct mg_file_stat {
  1421. /* File properties filled by mg_stat: */
  1422. uint64_t size;
  1423. time_t last_modified;
  1424. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1425. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1426. * case we need a "Content-Eencoding: gzip" header */
  1427. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1428. };
  1429. struct mg_file_in_memory {
  1430. char *p;
  1431. uint32_t pos;
  1432. char mode;
  1433. };
  1434. struct mg_file_access {
  1435. /* File properties filled by mg_fopen: */
  1436. FILE *fp;
  1437. /* TODO (low): Replace "membuf" implementation by a "file in memory"
  1438. * support library. Use some struct mg_file_in_memory *mf; instead of
  1439. * membuf char pointer. */
  1440. const char *membuf;
  1441. };
  1442. struct mg_file {
  1443. struct mg_file_stat stat;
  1444. struct mg_file_access access;
  1445. };
  1446. #define STRUCT_FILE_INITIALIZER \
  1447. { \
  1448. { \
  1449. (uint64_t)0, (time_t)0, 0, 0, 0 \
  1450. } \
  1451. , \
  1452. { \
  1453. (FILE *) NULL, (const char *)NULL \
  1454. } \
  1455. }
  1456. /* Describes listening socket, or socket which was accept()-ed by the master
  1457. * thread and queued for future handling by the worker thread. */
  1458. struct socket {
  1459. SOCKET sock; /* Listening socket */
  1460. union usa lsa; /* Local socket address */
  1461. union usa rsa; /* Remote socket address */
  1462. unsigned char is_ssl; /* Is port SSL-ed */
  1463. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1464. * port */
  1465. unsigned char in_use; /* Is valid */
  1466. };
  1467. /* NOTE(lsm): this enum shoulds be in sync with the config_options below. */
  1468. enum {
  1469. CGI_EXTENSIONS,
  1470. CGI_ENVIRONMENT,
  1471. PUT_DELETE_PASSWORDS_FILE,
  1472. CGI_INTERPRETER,
  1473. PROTECT_URI,
  1474. AUTHENTICATION_DOMAIN,
  1475. ENABLE_AUTH_DOMAIN_CHECK,
  1476. SSI_EXTENSIONS,
  1477. THROTTLE,
  1478. ACCESS_LOG_FILE,
  1479. ENABLE_DIRECTORY_LISTING,
  1480. ERROR_LOG_FILE,
  1481. GLOBAL_PASSWORDS_FILE,
  1482. INDEX_FILES,
  1483. ENABLE_KEEP_ALIVE,
  1484. ACCESS_CONTROL_LIST,
  1485. EXTRA_MIME_TYPES,
  1486. LISTENING_PORTS,
  1487. DOCUMENT_ROOT,
  1488. SSL_CERTIFICATE,
  1489. NUM_THREADS,
  1490. RUN_AS_USER,
  1491. REWRITE,
  1492. HIDE_FILES,
  1493. REQUEST_TIMEOUT,
  1494. KEEP_ALIVE_TIMEOUT,
  1495. LINGER_TIMEOUT,
  1496. SSL_DO_VERIFY_PEER,
  1497. SSL_CA_PATH,
  1498. SSL_CA_FILE,
  1499. SSL_VERIFY_DEPTH,
  1500. SSL_DEFAULT_VERIFY_PATHS,
  1501. SSL_CIPHER_LIST,
  1502. SSL_PROTOCOL_VERSION,
  1503. SSL_SHORT_TRUST,
  1504. #if defined(USE_WEBSOCKET)
  1505. WEBSOCKET_TIMEOUT,
  1506. #endif
  1507. DECODE_URL,
  1508. #if defined(USE_LUA)
  1509. LUA_PRELOAD_FILE,
  1510. LUA_SCRIPT_EXTENSIONS,
  1511. LUA_SERVER_PAGE_EXTENSIONS,
  1512. #endif
  1513. #if defined(USE_DUKTAPE)
  1514. DUKTAPE_SCRIPT_EXTENSIONS,
  1515. #endif
  1516. #if defined(USE_WEBSOCKET)
  1517. WEBSOCKET_ROOT,
  1518. #endif
  1519. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1520. LUA_WEBSOCKET_EXTENSIONS,
  1521. #endif
  1522. ACCESS_CONTROL_ALLOW_ORIGIN,
  1523. ERROR_PAGES,
  1524. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1525. * socket option typedef TCP_NODELAY. */
  1526. #if !defined(NO_CACHING)
  1527. STATIC_FILE_MAX_AGE,
  1528. #endif
  1529. #if defined(__linux__)
  1530. ALLOW_SENDFILE_CALL,
  1531. #endif
  1532. #if defined(_WIN32)
  1533. CASE_SENSITIVE_FILES,
  1534. #endif
  1535. #if defined(USE_LUA)
  1536. LUA_BACKGROUND_SCRIPT,
  1537. #endif
  1538. NUM_OPTIONS
  1539. };
  1540. /* Config option name, config types, default value */
  1541. static struct mg_option config_options[] = {
  1542. {"cgi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1543. {"cgi_environment", CONFIG_TYPE_STRING, NULL},
  1544. {"put_delete_auth_file", CONFIG_TYPE_FILE, NULL},
  1545. {"cgi_interpreter", CONFIG_TYPE_FILE, NULL},
  1546. {"protect_uri", CONFIG_TYPE_STRING, NULL},
  1547. {"authentication_domain", CONFIG_TYPE_STRING, "mydomain.com"},
  1548. {"enable_auth_domain_check", CONFIG_TYPE_BOOLEAN, "yes"},
  1549. {"ssi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1550. {"throttle", CONFIG_TYPE_STRING, NULL},
  1551. {"access_log_file", CONFIG_TYPE_FILE, NULL},
  1552. {"enable_directory_listing", CONFIG_TYPE_BOOLEAN, "yes"},
  1553. {"error_log_file", CONFIG_TYPE_FILE, NULL},
  1554. {"global_auth_file", CONFIG_TYPE_FILE, NULL},
  1555. {"index_files",
  1556. CONFIG_TYPE_STRING,
  1557. #ifdef USE_LUA
  1558. "index.xhtml,index.html,index.htm,index.lp,index.lsp,index.lua,index.cgi,"
  1559. "index.shtml,index.php"},
  1560. #else
  1561. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1562. #endif
  1563. {"enable_keep_alive", CONFIG_TYPE_BOOLEAN, "no"},
  1564. {"access_control_list", CONFIG_TYPE_STRING, NULL},
  1565. {"extra_mime_types", CONFIG_TYPE_STRING, NULL},
  1566. {"listening_ports", CONFIG_TYPE_STRING, "8080"},
  1567. {"document_root", CONFIG_TYPE_DIRECTORY, NULL},
  1568. {"ssl_certificate", CONFIG_TYPE_FILE, NULL},
  1569. {"num_threads", CONFIG_TYPE_NUMBER, "50"},
  1570. {"run_as_user", CONFIG_TYPE_STRING, NULL},
  1571. {"url_rewrite_patterns", CONFIG_TYPE_STRING, NULL},
  1572. {"hide_files_patterns", CONFIG_TYPE_EXT_PATTERN, NULL},
  1573. {"request_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1574. {"keep_alive_timeout_ms", CONFIG_TYPE_NUMBER, "500"},
  1575. {"linger_timeout_ms", CONFIG_TYPE_NUMBER, NULL},
  1576. {"ssl_verify_peer", CONFIG_TYPE_BOOLEAN, "no"},
  1577. {"ssl_ca_path", CONFIG_TYPE_DIRECTORY, NULL},
  1578. {"ssl_ca_file", CONFIG_TYPE_FILE, NULL},
  1579. {"ssl_verify_depth", CONFIG_TYPE_NUMBER, "9"},
  1580. {"ssl_default_verify_paths", CONFIG_TYPE_BOOLEAN, "yes"},
  1581. {"ssl_cipher_list", CONFIG_TYPE_STRING, NULL},
  1582. {"ssl_protocol_version", CONFIG_TYPE_NUMBER, "0"},
  1583. {"ssl_short_trust", CONFIG_TYPE_BOOLEAN, "no"},
  1584. #if defined(USE_WEBSOCKET)
  1585. {"websocket_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1586. #endif
  1587. {"decode_url", CONFIG_TYPE_BOOLEAN, "yes"},
  1588. #if defined(USE_LUA)
  1589. {"lua_preload_file", CONFIG_TYPE_FILE, NULL},
  1590. {"lua_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1591. {"lua_server_page_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1592. #endif
  1593. #if defined(USE_DUKTAPE)
  1594. /* The support for duktape is still in alpha version state.
  1595. * The name of this config option might change. */
  1596. {"duktape_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1597. #endif
  1598. #if defined(USE_WEBSOCKET)
  1599. {"websocket_root", CONFIG_TYPE_DIRECTORY, NULL},
  1600. #endif
  1601. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1602. {"lua_websocket_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1603. #endif
  1604. {"access_control_allow_origin", CONFIG_TYPE_STRING, "*"},
  1605. {"error_pages", CONFIG_TYPE_DIRECTORY, NULL},
  1606. {"tcp_nodelay", CONFIG_TYPE_NUMBER, "0"},
  1607. #if !defined(NO_CACHING)
  1608. {"static_file_max_age", CONFIG_TYPE_NUMBER, "3600"},
  1609. #endif
  1610. #if defined(__linux__)
  1611. {"allow_sendfile_call", CONFIG_TYPE_BOOLEAN, "yes"},
  1612. #endif
  1613. #if defined(_WIN32)
  1614. {"case_sensitive", CONFIG_TYPE_BOOLEAN, "no"},
  1615. #endif
  1616. #if defined(USE_LUA)
  1617. {"lua_background_script", CONFIG_TYPE_FILE, NULL},
  1618. #endif
  1619. {NULL, CONFIG_TYPE_UNKNOWN, NULL}};
  1620. /* Check if the config_options and the corresponding enum have compatible
  1621. * sizes. */
  1622. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1623. == (NUM_OPTIONS + 1),
  1624. "config_options and enum not sync");
  1625. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1626. struct mg_handler_info {
  1627. /* Name/Pattern of the URI. */
  1628. char *uri;
  1629. size_t uri_len;
  1630. /* handler type */
  1631. int handler_type;
  1632. /* Handler for http/https or authorization requests. */
  1633. mg_request_handler handler;
  1634. /* Handler for ws/wss (websocket) requests. */
  1635. mg_websocket_connect_handler connect_handler;
  1636. mg_websocket_ready_handler ready_handler;
  1637. mg_websocket_data_handler data_handler;
  1638. mg_websocket_close_handler close_handler;
  1639. /* accepted subprotocols for ws/wss requests. */
  1640. struct mg_websocket_subprotocols *subprotocols;
  1641. /* Handler for authorization requests */
  1642. mg_authorization_handler auth_handler;
  1643. /* User supplied argument for the handler function. */
  1644. void *cbdata;
  1645. /* next handler in a linked list */
  1646. struct mg_handler_info *next;
  1647. };
  1648. struct mg_context {
  1649. volatile int stop_flag; /* Should we stop event loop */
  1650. SSL_CTX *ssl_ctx; /* SSL context */
  1651. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1652. struct mg_callbacks callbacks; /* User-defined callback function */
  1653. void *user_data; /* User-defined data */
  1654. int context_type; /* 1 = server context,
  1655. * 2 = ws/wss client context,
  1656. */
  1657. struct socket *listening_sockets;
  1658. struct pollfd *listening_socket_fds;
  1659. unsigned int num_listening_sockets;
  1660. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  1661. #ifdef ALTERNATIVE_QUEUE
  1662. struct socket *client_socks;
  1663. void **client_wait_events;
  1664. #else
  1665. struct socket queue[MGSQLEN]; /* Accepted sockets */
  1666. volatile int sq_head; /* Head of the socket queue */
  1667. volatile int sq_tail; /* Tail of the socket queue */
  1668. pthread_cond_t sq_full; /* Signaled when socket is produced */
  1669. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  1670. #endif
  1671. pthread_t masterthreadid; /* The master thread ID */
  1672. unsigned int
  1673. cfg_worker_threads; /* The number of configured worker threads. */
  1674. pthread_t *worker_threadids; /* The worker thread IDs */
  1675. struct mg_connection *worker_connections; /* The connection struct, pre-
  1676. * allocated for each worker */
  1677. time_t start_time; /* Server start time, used for authentication */
  1678. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1679. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  1680. unsigned long nonce_count; /* Used nonces, used for authentication */
  1681. char *systemName; /* What operating system is running */
  1682. /* linked list of uri handlers */
  1683. struct mg_handler_info *handlers;
  1684. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1685. /* linked list of shared lua websockets */
  1686. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1687. #endif
  1688. #if defined(USE_TIMERS)
  1689. struct ttimers *timers;
  1690. #endif
  1691. #if defined(USE_LUA)
  1692. void *lua_background_state;
  1693. #endif
  1694. };
  1695. struct mg_connection {
  1696. struct mg_request_info request_info;
  1697. struct mg_context *ctx;
  1698. SSL *ssl; /* SSL descriptor */
  1699. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  1700. struct socket client; /* Connected client */
  1701. time_t conn_birth_time; /* Time (wall clock) when connection was
  1702. * established */
  1703. struct timespec req_time; /* Time (since system start) when the request
  1704. * was received */
  1705. int64_t num_bytes_sent; /* Total bytes sent to client */
  1706. int64_t content_len; /* Content-Length header value */
  1707. int64_t consumed_content; /* How many bytes of content have been read */
  1708. int is_chunked; /* Transfer-Encoding is chunked: 0=no, 1=yes:
  1709. * data available, 2: all data read */
  1710. size_t chunk_remainder; /* Unread data from the last chunk */
  1711. char *buf; /* Buffer for received data */
  1712. char *path_info; /* PATH_INFO part of the URL */
  1713. int must_close; /* 1 if connection must be closed */
  1714. int in_error_handler; /* 1 if in handler for user defined error
  1715. * pages */
  1716. int handled_requests; /* Number of requests handled by this connection */
  1717. int buf_size; /* Buffer size */
  1718. int request_len; /* Size of the request + headers in a buffer */
  1719. int data_len; /* Total size of data in a buffer */
  1720. int status_code; /* HTTP reply status code, e.g. 200 */
  1721. int throttle; /* Throttling, bytes/sec. <= 0 means no
  1722. * throttle */
  1723. time_t last_throttle_time; /* Last time throttled data was sent */
  1724. int64_t last_throttle_bytes; /* Bytes sent this second */
  1725. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  1726. * atomic transmissions for websockets */
  1727. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1728. void *lua_websocket_state; /* Lua_State for a websocket connection */
  1729. #endif
  1730. int thread_index; /* Thread index within ctx */
  1731. };
  1732. /* Directory entry */
  1733. struct de {
  1734. struct mg_connection *conn;
  1735. char *file_name;
  1736. struct mg_file_stat file;
  1737. };
  1738. #if defined(USE_WEBSOCKET)
  1739. static int is_websocket_protocol(const struct mg_connection *conn);
  1740. #else
  1741. #define is_websocket_protocol(conn) (0)
  1742. #endif
  1743. #if !defined(NO_THREAD_NAME)
  1744. #if defined(_WIN32) && defined(_MSC_VER)
  1745. /* Set the thread name for debugging purposes in Visual Studio
  1746. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  1747. */
  1748. #pragma pack(push, 8)
  1749. typedef struct tagTHREADNAME_INFO {
  1750. DWORD dwType; /* Must be 0x1000. */
  1751. LPCSTR szName; /* Pointer to name (in user addr space). */
  1752. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  1753. DWORD dwFlags; /* Reserved for future use, must be zero. */
  1754. } THREADNAME_INFO;
  1755. #pragma pack(pop)
  1756. #elif defined(__linux__)
  1757. #include <sys/prctl.h>
  1758. #include <sys/sendfile.h>
  1759. #include <sys/eventfd.h>
  1760. #if defined(ALTERNATIVE_QUEUE)
  1761. static void *
  1762. event_create(void)
  1763. {
  1764. int ret = eventfd(0, EFD_CLOEXEC);
  1765. if (ret == -1) {
  1766. /* Linux uses -1 on error, Windows NULL. */
  1767. /* However, Linux does not return 0 on success either. */
  1768. return 0;
  1769. }
  1770. return (void *)ret;
  1771. }
  1772. static int
  1773. event_wait(void *eventhdl)
  1774. {
  1775. uint64_t u;
  1776. int s = (int)read((int)eventhdl, &u, sizeof(u));
  1777. if (s != sizeof(uint64_t)) {
  1778. /* error */
  1779. return 0;
  1780. }
  1781. (void)u; /* the value is not required */
  1782. return 1;
  1783. }
  1784. static int
  1785. event_signal(void *eventhdl)
  1786. {
  1787. uint64_t u = 1;
  1788. int s = (int)write((int)eventhdl, &u, sizeof(u));
  1789. if (s != sizeof(uint64_t)) {
  1790. /* error */
  1791. return 0;
  1792. }
  1793. return 1;
  1794. }
  1795. static void
  1796. event_destroy(void *eventhdl)
  1797. {
  1798. close((int)eventhdl);
  1799. }
  1800. #endif
  1801. #endif
  1802. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  1803. struct posix_event {
  1804. pthread_mutex_t mutex;
  1805. pthread_cond_t cond;
  1806. };
  1807. static void *
  1808. event_create(void)
  1809. {
  1810. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  1811. if (ret == 0) {
  1812. /* out of memory */
  1813. return 0;
  1814. }
  1815. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  1816. /* pthread mutex not available */
  1817. mg_free(ret);
  1818. return 0;
  1819. }
  1820. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  1821. /* pthread cond not available */
  1822. pthread_mutex_destroy(&(ret->mutex));
  1823. mg_free(ret);
  1824. return 0;
  1825. }
  1826. return (void *)ret;
  1827. }
  1828. static int
  1829. event_wait(void *eventhdl)
  1830. {
  1831. struct posix_event *ev = (struct posix_event *)eventhdl;
  1832. pthread_mutex_lock(&(ev->mutex));
  1833. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  1834. pthread_mutex_unlock(&(ev->mutex));
  1835. return 1;
  1836. }
  1837. static int
  1838. event_signal(void *eventhdl)
  1839. {
  1840. struct posix_event *ev = (struct posix_event *)eventhdl;
  1841. pthread_mutex_lock(&(ev->mutex));
  1842. pthread_cond_signal(&(ev->cond));
  1843. pthread_mutex_unlock(&(ev->mutex));
  1844. return 1;
  1845. }
  1846. static void
  1847. event_destroy(void *eventhdl)
  1848. {
  1849. struct posix_event *ev = (struct posix_event *)eventhdl;
  1850. pthread_cond_destroy(&(ev->cond));
  1851. pthread_mutex_destroy(&(ev->mutex));
  1852. mg_free(ev);
  1853. }
  1854. #endif
  1855. static void
  1856. mg_set_thread_name(const char *name)
  1857. {
  1858. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  1859. mg_snprintf(
  1860. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  1861. #if defined(_WIN32)
  1862. #if defined(_MSC_VER)
  1863. /* Windows and Visual Studio Compiler */
  1864. __try
  1865. {
  1866. THREADNAME_INFO info;
  1867. info.dwType = 0x1000;
  1868. info.szName = threadName;
  1869. info.dwThreadID = ~0U;
  1870. info.dwFlags = 0;
  1871. RaiseException(0x406D1388,
  1872. 0,
  1873. sizeof(info) / sizeof(ULONG_PTR),
  1874. (ULONG_PTR *)&info);
  1875. }
  1876. __except(EXCEPTION_EXECUTE_HANDLER)
  1877. {
  1878. }
  1879. #elif defined(__MINGW32__)
  1880. /* No option known to set thread name for MinGW */
  1881. #endif
  1882. #elif defined(__GLIBC__) \
  1883. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  1884. /* pthread_setname_np first appeared in glibc in version 2.12*/
  1885. (void)pthread_setname_np(pthread_self(), threadName);
  1886. #elif defined(__linux__)
  1887. /* on linux we can use the old prctl function */
  1888. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  1889. #endif
  1890. }
  1891. #else /* !defined(NO_THREAD_NAME) */
  1892. void
  1893. mg_set_thread_name(const char *threadName)
  1894. {
  1895. }
  1896. #endif
  1897. #if defined(MG_LEGACY_INTERFACE)
  1898. const char **
  1899. mg_get_valid_option_names(void)
  1900. {
  1901. /* This function is deprecated. Use mg_get_valid_options instead. */
  1902. static const char *
  1903. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  1904. int i;
  1905. for (i = 0; config_options[i].name != NULL; i++) {
  1906. data[i * 2] = config_options[i].name;
  1907. data[i * 2 + 1] = config_options[i].default_value;
  1908. }
  1909. return data;
  1910. }
  1911. #endif
  1912. const struct mg_option *
  1913. mg_get_valid_options(void)
  1914. {
  1915. return config_options;
  1916. }
  1917. /* Do not open file (used in is_file_in_memory) */
  1918. #define MG_FOPEN_MODE_NONE (0)
  1919. /* Open file for read only access */
  1920. #define MG_FOPEN_MODE_READ (1)
  1921. /* Open file for writing, create and overwrite */
  1922. #define MG_FOPEN_MODE_WRITE (2)
  1923. /* Open file for writing, create and append */
  1924. #define MG_FOPEN_MODE_APPEND (4)
  1925. /* If a file is in memory, set all "stat" members and the membuf pointer of
  1926. * output filep and return 1, otherwise return 0 and don't modify anything. */
  1927. static int
  1928. open_file_in_memory(const struct mg_connection *conn,
  1929. const char *path,
  1930. struct mg_file *filep,
  1931. int mode)
  1932. {
  1933. #if defined(MG_USE_OPEN_FILE)
  1934. size_t size = 0;
  1935. const char *buf = NULL;
  1936. if (!conn) {
  1937. return 0;
  1938. }
  1939. if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
  1940. return 0;
  1941. }
  1942. if (conn->ctx->callbacks.open_file) {
  1943. buf = conn->ctx->callbacks.open_file(conn, path, &size);
  1944. if (buf != NULL) {
  1945. if (filep == NULL) {
  1946. /* This is a file in memory, but we cannot store the properties
  1947. * now.
  1948. * Called from "is_file_in_memory" function. */
  1949. return 1;
  1950. }
  1951. /* NOTE: override filep->size only on success. Otherwise, it might
  1952. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  1953. filep->access.membuf = buf;
  1954. filep->access.fp = NULL;
  1955. /* Size was set by the callback */
  1956. filep->stat.size = size;
  1957. /* Assume the data may change during runtime by setting
  1958. * last_modified = now */
  1959. filep->stat.last_modified = time(NULL);
  1960. filep->stat.is_directory = 0;
  1961. filep->stat.is_gzipped = 0;
  1962. }
  1963. }
  1964. return (buf != NULL);
  1965. #else
  1966. (void)conn;
  1967. (void)path;
  1968. (void)filep;
  1969. (void)mode;
  1970. return 0;
  1971. #endif
  1972. }
  1973. static int
  1974. is_file_in_memory(const struct mg_connection *conn, const char *path)
  1975. {
  1976. return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
  1977. }
  1978. static int
  1979. is_file_opened(const struct mg_file_access *fileacc)
  1980. {
  1981. if (!fileacc) {
  1982. return 0;
  1983. }
  1984. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  1985. }
  1986. static int mg_stat(const struct mg_connection *conn,
  1987. const char *path,
  1988. struct mg_file_stat *filep);
  1989. /* mg_fopen will open a file either in memory or on the disk.
  1990. * The input parameter path is a string in UTF-8 encoding.
  1991. * The input parameter mode is MG_FOPEN_MODE_*
  1992. * On success, either fp or membuf will be set in the output
  1993. * struct file. All status members will also be set.
  1994. * The function returns 1 on success, 0 on error. */
  1995. static int
  1996. mg_fopen(const struct mg_connection *conn,
  1997. const char *path,
  1998. int mode,
  1999. struct mg_file *filep)
  2000. {
  2001. int found;
  2002. if (!filep) {
  2003. return 0;
  2004. }
  2005. filep->access.fp = NULL;
  2006. filep->access.membuf = NULL;
  2007. if (!is_file_in_memory(conn, path)) {
  2008. /* filep is initialized in mg_stat: all fields with memset to,
  2009. * some fields like size and modification date with values */
  2010. found = mg_stat(conn, path, &(filep->stat));
  2011. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2012. /* file does not exist and will not be created */
  2013. return 0;
  2014. }
  2015. #ifdef _WIN32
  2016. {
  2017. wchar_t wbuf[PATH_MAX];
  2018. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2019. switch (mode) {
  2020. case MG_FOPEN_MODE_READ:
  2021. filep->access.fp = _wfopen(wbuf, L"rb");
  2022. break;
  2023. case MG_FOPEN_MODE_WRITE:
  2024. filep->access.fp = _wfopen(wbuf, L"wb");
  2025. break;
  2026. case MG_FOPEN_MODE_APPEND:
  2027. filep->access.fp = _wfopen(wbuf, L"ab");
  2028. break;
  2029. }
  2030. }
  2031. #else
  2032. /* Linux et al already use unicode. No need to convert. */
  2033. switch (mode) {
  2034. case MG_FOPEN_MODE_READ:
  2035. filep->access.fp = fopen(path, "r");
  2036. break;
  2037. case MG_FOPEN_MODE_WRITE:
  2038. filep->access.fp = fopen(path, "w");
  2039. break;
  2040. case MG_FOPEN_MODE_APPEND:
  2041. filep->access.fp = fopen(path, "a");
  2042. break;
  2043. }
  2044. #endif
  2045. if (!found) {
  2046. /* File did not exist before fopen was called.
  2047. * Maybe it has been created now. Get stat info
  2048. * like creation time now. */
  2049. found = mg_stat(conn, path, &(filep->stat));
  2050. (void)found;
  2051. }
  2052. /* file is on disk */
  2053. return (filep->access.fp != NULL);
  2054. } else {
  2055. /* is_file_in_memory returned true */
  2056. if (open_file_in_memory(conn, path, filep, mode)) {
  2057. /* file is in memory */
  2058. return (filep->access.membuf != NULL);
  2059. }
  2060. }
  2061. /* Open failed */
  2062. return 0;
  2063. }
  2064. /* return 0 on success, just like fclose */
  2065. static int
  2066. mg_fclose(struct mg_file_access *fileacc)
  2067. {
  2068. int ret = -1;
  2069. if (fileacc != NULL) {
  2070. if (fileacc->fp != NULL) {
  2071. ret = fclose(fileacc->fp);
  2072. } else if (fileacc->membuf != NULL) {
  2073. ret = 0;
  2074. }
  2075. /* reset all members of fileacc */
  2076. memset(fileacc, 0, sizeof(*fileacc));
  2077. }
  2078. return ret;
  2079. }
  2080. static void
  2081. mg_strlcpy(register char *dst, register const char *src, size_t n)
  2082. {
  2083. for (; *src != '\0' && n > 1; n--) {
  2084. *dst++ = *src++;
  2085. }
  2086. *dst = '\0';
  2087. }
  2088. static int
  2089. lowercase(const char *s)
  2090. {
  2091. return tolower(*(const unsigned char *)s);
  2092. }
  2093. int
  2094. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2095. {
  2096. int diff = 0;
  2097. if (len > 0) {
  2098. do {
  2099. diff = lowercase(s1++) - lowercase(s2++);
  2100. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2101. }
  2102. return diff;
  2103. }
  2104. int
  2105. mg_strcasecmp(const char *s1, const char *s2)
  2106. {
  2107. int diff;
  2108. do {
  2109. diff = lowercase(s1++) - lowercase(s2++);
  2110. } while (diff == 0 && s1[-1] != '\0');
  2111. return diff;
  2112. }
  2113. static char *
  2114. mg_strndup(const char *ptr, size_t len)
  2115. {
  2116. char *p;
  2117. if ((p = (char *)mg_malloc(len + 1)) != NULL) {
  2118. mg_strlcpy(p, ptr, len + 1);
  2119. }
  2120. return p;
  2121. }
  2122. static char *
  2123. mg_strdup(const char *str)
  2124. {
  2125. return mg_strndup(str, strlen(str));
  2126. }
  2127. static const char *
  2128. mg_strcasestr(const char *big_str, const char *small_str)
  2129. {
  2130. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2131. if (big_len >= small_len) {
  2132. for (i = 0; i <= (big_len - small_len); i++) {
  2133. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2134. return big_str + i;
  2135. }
  2136. }
  2137. }
  2138. return NULL;
  2139. }
  2140. /* Return null terminated string of given maximum length.
  2141. * Report errors if length is exceeded. */
  2142. static void
  2143. mg_vsnprintf(const struct mg_connection *conn,
  2144. int *truncated,
  2145. char *buf,
  2146. size_t buflen,
  2147. const char *fmt,
  2148. va_list ap)
  2149. {
  2150. int n, ok;
  2151. if (buflen == 0) {
  2152. return;
  2153. }
  2154. #ifdef __clang__
  2155. #pragma clang diagnostic push
  2156. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2157. /* Using fmt as a non-literal is intended here, since it is mostly called
  2158. * indirectly by mg_snprintf */
  2159. #endif
  2160. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2161. ok = (n >= 0) && ((size_t)n < buflen);
  2162. #ifdef __clang__
  2163. #pragma clang diagnostic pop
  2164. #endif
  2165. if (ok) {
  2166. if (truncated) {
  2167. *truncated = 0;
  2168. }
  2169. } else {
  2170. if (truncated) {
  2171. *truncated = 1;
  2172. }
  2173. mg_cry(conn,
  2174. "truncating vsnprintf buffer: [%.*s]",
  2175. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2176. buf);
  2177. n = (int)buflen - 1;
  2178. }
  2179. buf[n] = '\0';
  2180. }
  2181. static void
  2182. mg_snprintf(const struct mg_connection *conn,
  2183. int *truncated,
  2184. char *buf,
  2185. size_t buflen,
  2186. const char *fmt,
  2187. ...)
  2188. {
  2189. va_list ap;
  2190. va_start(ap, fmt);
  2191. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2192. va_end(ap);
  2193. }
  2194. static int
  2195. get_option_index(const char *name)
  2196. {
  2197. int i;
  2198. for (i = 0; config_options[i].name != NULL; i++) {
  2199. if (strcmp(config_options[i].name, name) == 0) {
  2200. return i;
  2201. }
  2202. }
  2203. return -1;
  2204. }
  2205. const char *
  2206. mg_get_option(const struct mg_context *ctx, const char *name)
  2207. {
  2208. int i;
  2209. if ((i = get_option_index(name)) == -1) {
  2210. return NULL;
  2211. } else if (!ctx || ctx->config[i] == NULL) {
  2212. return "";
  2213. } else {
  2214. return ctx->config[i];
  2215. }
  2216. }
  2217. struct mg_context *
  2218. mg_get_context(const struct mg_connection *conn)
  2219. {
  2220. return (conn == NULL) ? (struct mg_context *)NULL : (conn->ctx);
  2221. }
  2222. void *
  2223. mg_get_user_data(const struct mg_context *ctx)
  2224. {
  2225. return (ctx == NULL) ? NULL : ctx->user_data;
  2226. }
  2227. void
  2228. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  2229. {
  2230. if (conn != NULL) {
  2231. conn->request_info.conn_data = data;
  2232. }
  2233. }
  2234. void *
  2235. mg_get_user_connection_data(const struct mg_connection *conn)
  2236. {
  2237. if (conn != NULL) {
  2238. return conn->request_info.conn_data;
  2239. }
  2240. return NULL;
  2241. }
  2242. size_t
  2243. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  2244. {
  2245. size_t i;
  2246. if (!ctx) {
  2247. return 0;
  2248. }
  2249. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  2250. ssl[i] = ctx->listening_sockets[i].is_ssl;
  2251. ports[i] =
  2252. #if defined(USE_IPV6)
  2253. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2254. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2255. :
  2256. #endif
  2257. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2258. }
  2259. return i;
  2260. }
  2261. int
  2262. mg_get_server_ports(const struct mg_context *ctx,
  2263. int size,
  2264. struct mg_server_ports *ports)
  2265. {
  2266. int i, cnt = 0;
  2267. if (size <= 0) {
  2268. return -1;
  2269. }
  2270. memset(ports, 0, sizeof(*ports) * (size_t)size);
  2271. if (!ctx) {
  2272. return -1;
  2273. }
  2274. if (!ctx->listening_sockets) {
  2275. return -1;
  2276. }
  2277. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  2278. ports[cnt].port =
  2279. #if defined(USE_IPV6)
  2280. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2281. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2282. :
  2283. #endif
  2284. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2285. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  2286. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  2287. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  2288. /* IPv4 */
  2289. ports[cnt].protocol = 1;
  2290. cnt++;
  2291. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  2292. /* IPv6 */
  2293. ports[cnt].protocol = 3;
  2294. cnt++;
  2295. }
  2296. }
  2297. return cnt;
  2298. }
  2299. static void
  2300. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  2301. {
  2302. buf[0] = '\0';
  2303. if (!usa) {
  2304. return;
  2305. }
  2306. if (usa->sa.sa_family == AF_INET) {
  2307. getnameinfo(&usa->sa,
  2308. sizeof(usa->sin),
  2309. buf,
  2310. (unsigned)len,
  2311. NULL,
  2312. 0,
  2313. NI_NUMERICHOST);
  2314. }
  2315. #if defined(USE_IPV6)
  2316. else if (usa->sa.sa_family == AF_INET6) {
  2317. getnameinfo(&usa->sa,
  2318. sizeof(usa->sin6),
  2319. buf,
  2320. (unsigned)len,
  2321. NULL,
  2322. 0,
  2323. NI_NUMERICHOST);
  2324. }
  2325. #endif
  2326. }
  2327. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  2328. * included in all responses other than 100, 101, 5xx. */
  2329. static void
  2330. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  2331. {
  2332. struct tm *tm;
  2333. tm = ((t != NULL) ? gmtime(t) : NULL);
  2334. if (tm != NULL) {
  2335. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  2336. } else {
  2337. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  2338. buf[buf_len - 1] = '\0';
  2339. }
  2340. }
  2341. /* difftime for struct timespec. Return value is in seconds. */
  2342. static double
  2343. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  2344. {
  2345. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  2346. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  2347. }
  2348. /* Print error message to the opened error log stream. */
  2349. void
  2350. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  2351. {
  2352. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  2353. va_list ap;
  2354. struct mg_file fi;
  2355. time_t timestamp;
  2356. va_start(ap, fmt);
  2357. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  2358. va_end(ap);
  2359. buf[sizeof(buf) - 1] = 0;
  2360. if (!conn) {
  2361. puts(buf);
  2362. return;
  2363. }
  2364. /* Do not lock when getting the callback value, here and below.
  2365. * I suppose this is fine, since function cannot disappear in the
  2366. * same way string option can. */
  2367. if ((conn->ctx->callbacks.log_message == NULL)
  2368. || (conn->ctx->callbacks.log_message(conn, buf) == 0)) {
  2369. if (conn->ctx->config[ERROR_LOG_FILE] != NULL) {
  2370. if (mg_fopen(conn,
  2371. conn->ctx->config[ERROR_LOG_FILE],
  2372. MG_FOPEN_MODE_APPEND,
  2373. &fi) == 0) {
  2374. fi.access.fp = NULL;
  2375. }
  2376. } else {
  2377. fi.access.fp = NULL;
  2378. }
  2379. if (fi.access.fp != NULL) {
  2380. flockfile(fi.access.fp);
  2381. timestamp = time(NULL);
  2382. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  2383. fprintf(fi.access.fp,
  2384. "[%010lu] [error] [client %s] ",
  2385. (unsigned long)timestamp,
  2386. src_addr);
  2387. if (conn->request_info.request_method != NULL) {
  2388. fprintf(fi.access.fp,
  2389. "%s %s: ",
  2390. conn->request_info.request_method,
  2391. conn->request_info.request_uri);
  2392. }
  2393. fprintf(fi.access.fp, "%s", buf);
  2394. fputc('\n', fi.access.fp);
  2395. fflush(fi.access.fp);
  2396. funlockfile(fi.access.fp);
  2397. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  2398. * mg_cry here anyway ;-) */
  2399. }
  2400. }
  2401. }
  2402. /* Return fake connection structure. Used for logging, if connection
  2403. * is not applicable at the moment of logging. */
  2404. static struct mg_connection *
  2405. fc(struct mg_context *ctx)
  2406. {
  2407. static struct mg_connection fake_connection;
  2408. fake_connection.ctx = ctx;
  2409. return &fake_connection;
  2410. }
  2411. const char *
  2412. mg_version(void)
  2413. {
  2414. return CIVETWEB_VERSION;
  2415. }
  2416. const struct mg_request_info *
  2417. mg_get_request_info(const struct mg_connection *conn)
  2418. {
  2419. if (!conn) {
  2420. return NULL;
  2421. }
  2422. return &conn->request_info;
  2423. }
  2424. /* Skip the characters until one of the delimiters characters found.
  2425. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  2426. * Advance pointer to buffer to the next word. Return found 0-terminated word.
  2427. * Delimiters can be quoted with quotechar. */
  2428. static char *
  2429. skip_quoted(char **buf,
  2430. const char *delimiters,
  2431. const char *whitespace,
  2432. char quotechar)
  2433. {
  2434. char *p, *begin_word, *end_word, *end_whitespace;
  2435. begin_word = *buf;
  2436. end_word = begin_word + strcspn(begin_word, delimiters);
  2437. /* Check for quotechar */
  2438. if (end_word > begin_word) {
  2439. p = end_word - 1;
  2440. while (*p == quotechar) {
  2441. /* While the delimiter is quoted, look for the next delimiter. */
  2442. /* This happens, e.g., in calls from parse_auth_header,
  2443. * if the user name contains a " character. */
  2444. /* If there is anything beyond end_word, copy it. */
  2445. if (*end_word != '\0') {
  2446. size_t end_off = strcspn(end_word + 1, delimiters);
  2447. memmove(p, end_word, end_off + 1);
  2448. p += end_off; /* p must correspond to end_word - 1 */
  2449. end_word += end_off + 1;
  2450. } else {
  2451. *p = '\0';
  2452. break;
  2453. }
  2454. }
  2455. for (p++; p < end_word; p++) {
  2456. *p = '\0';
  2457. }
  2458. }
  2459. if (*end_word == '\0') {
  2460. *buf = end_word;
  2461. } else {
  2462. #if defined(__GNUC__) || defined(__MINGW32__)
  2463. /* Disable spurious conversion warning for GCC */
  2464. #pragma GCC diagnostic push
  2465. #pragma GCC diagnostic ignored "-Wsign-conversion"
  2466. #endif
  2467. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  2468. #if defined(__GNUC__) || defined(__MINGW32__)
  2469. #pragma GCC diagnostic pop
  2470. #endif
  2471. for (p = end_word; p < end_whitespace; p++) {
  2472. *p = '\0';
  2473. }
  2474. *buf = end_whitespace;
  2475. }
  2476. return begin_word;
  2477. }
  2478. /* Simplified version of skip_quoted without quote char
  2479. * and whitespace == delimiters */
  2480. static char *
  2481. skip(char **buf, const char *delimiters)
  2482. {
  2483. return skip_quoted(buf, delimiters, delimiters, 0);
  2484. }
  2485. /* Return HTTP header value, or NULL if not found. */
  2486. static const char *
  2487. get_header(const struct mg_request_info *ri, const char *name)
  2488. {
  2489. int i;
  2490. if (ri) {
  2491. for (i = 0; i < ri->num_headers; i++) {
  2492. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  2493. return ri->http_headers[i].value;
  2494. }
  2495. }
  2496. }
  2497. return NULL;
  2498. }
  2499. const char *
  2500. mg_get_header(const struct mg_connection *conn, const char *name)
  2501. {
  2502. if (!conn) {
  2503. return NULL;
  2504. }
  2505. return get_header(&conn->request_info, name);
  2506. }
  2507. /* A helper function for traversing a comma separated list of values.
  2508. * It returns a list pointer shifted to the next value, or NULL if the end
  2509. * of the list found.
  2510. * Value is stored in val vector. If value has form "x=y", then eq_val
  2511. * vector is initialized to point to the "y" part, and val vector length
  2512. * is adjusted to point only to "x". */
  2513. static const char *
  2514. next_option(const char *list, struct vec *val, struct vec *eq_val)
  2515. {
  2516. int end;
  2517. reparse:
  2518. if (val == NULL || list == NULL || *list == '\0') {
  2519. /* End of the list */
  2520. list = NULL;
  2521. } else {
  2522. /* Skip over leading LWS */
  2523. while (*list == ' ' || *list == '\t')
  2524. list++;
  2525. val->ptr = list;
  2526. if ((list = strchr(val->ptr, ',')) != NULL) {
  2527. /* Comma found. Store length and shift the list ptr */
  2528. val->len = ((size_t)(list - val->ptr));
  2529. list++;
  2530. } else {
  2531. /* This value is the last one */
  2532. list = val->ptr + strlen(val->ptr);
  2533. val->len = ((size_t)(list - val->ptr));
  2534. }
  2535. /* Adjust length for trailing LWS */
  2536. end = (int)val->len - 1;
  2537. while (end >= 0 && (val->ptr[end] == ' ' || val->ptr[end] == '\t'))
  2538. end--;
  2539. val->len = (size_t)(end + 1);
  2540. if (val->len == 0) {
  2541. /* Ignore any empty entries. */
  2542. goto reparse;
  2543. }
  2544. if (eq_val != NULL) {
  2545. /* Value has form "x=y", adjust pointers and lengths
  2546. * so that val points to "x", and eq_val points to "y". */
  2547. eq_val->len = 0;
  2548. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  2549. if (eq_val->ptr != NULL) {
  2550. eq_val->ptr++; /* Skip over '=' character */
  2551. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  2552. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  2553. }
  2554. }
  2555. }
  2556. return list;
  2557. }
  2558. /* A helper function for checking if a comma separated list of values contains
  2559. * the given option (case insensitvely).
  2560. * 'header' can be NULL, in which case false is returned. */
  2561. static int
  2562. header_has_option(const char *header, const char *option)
  2563. {
  2564. struct vec opt_vec;
  2565. struct vec eq_vec;
  2566. assert(option != NULL);
  2567. assert(option[0] != '\0');
  2568. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  2569. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  2570. return 1;
  2571. }
  2572. return 0;
  2573. }
  2574. /* Perform case-insensitive match of string against pattern */
  2575. static int
  2576. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  2577. {
  2578. const char *or_str;
  2579. size_t i;
  2580. int j, len, res;
  2581. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  2582. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  2583. return (res > 0) ? res : match_prefix(or_str + 1,
  2584. (size_t)((pattern + pattern_len)
  2585. - (or_str + 1)),
  2586. str);
  2587. }
  2588. for (i = 0, j = 0; i < pattern_len; i++, j++) {
  2589. if (pattern[i] == '?' && str[j] != '\0') {
  2590. continue;
  2591. } else if (pattern[i] == '$') {
  2592. return (str[j] == '\0') ? j : -1;
  2593. } else if (pattern[i] == '*') {
  2594. i++;
  2595. if (pattern[i] == '*') {
  2596. i++;
  2597. len = (int)strlen(str + j);
  2598. } else {
  2599. len = (int)strcspn(str + j, "/");
  2600. }
  2601. if (i == pattern_len) {
  2602. return j + len;
  2603. }
  2604. do {
  2605. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  2606. } while (res == -1 && len-- > 0);
  2607. return (res == -1) ? -1 : j + res + len;
  2608. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  2609. return -1;
  2610. }
  2611. }
  2612. return j;
  2613. }
  2614. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  2615. * This function must tolerate situations when connection info is not
  2616. * set up, for example if request parsing failed. */
  2617. static int
  2618. should_keep_alive(const struct mg_connection *conn)
  2619. {
  2620. if (conn != NULL) {
  2621. const char *http_version = conn->request_info.http_version;
  2622. const char *header = mg_get_header(conn, "Connection");
  2623. if (conn->must_close || conn->status_code == 401
  2624. || mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0
  2625. || (header != NULL && !header_has_option(header, "keep-alive"))
  2626. || (header == NULL && http_version
  2627. && 0 != strcmp(http_version, "1.1"))) {
  2628. return 0;
  2629. }
  2630. return 1;
  2631. }
  2632. return 0;
  2633. }
  2634. static int
  2635. should_decode_url(const struct mg_connection *conn)
  2636. {
  2637. if (!conn || !conn->ctx) {
  2638. return 0;
  2639. }
  2640. return (mg_strcasecmp(conn->ctx->config[DECODE_URL], "yes") == 0);
  2641. }
  2642. static const char *
  2643. suggest_connection_header(const struct mg_connection *conn)
  2644. {
  2645. return should_keep_alive(conn) ? "keep-alive" : "close";
  2646. }
  2647. static int
  2648. send_no_cache_header(struct mg_connection *conn)
  2649. {
  2650. /* Send all current and obsolete cache opt-out directives. */
  2651. return mg_printf(conn,
  2652. "Cache-Control: no-cache, no-store, "
  2653. "must-revalidate, private, max-age=0\r\n"
  2654. "Pragma: no-cache\r\n"
  2655. "Expires: 0\r\n");
  2656. }
  2657. static int
  2658. send_static_cache_header(struct mg_connection *conn)
  2659. {
  2660. #if !defined(NO_CACHING)
  2661. /* Read the server config to check how long a file may be cached.
  2662. * The configuration is in seconds. */
  2663. int max_age = atoi(conn->ctx->config[STATIC_FILE_MAX_AGE]);
  2664. if (max_age <= 0) {
  2665. /* 0 means "do not cache". All values <0 are reserved
  2666. * and may be used differently in the future. */
  2667. /* If a file should not be cached, do not only send
  2668. * max-age=0, but also pragmas and Expires headers. */
  2669. return send_no_cache_header(conn);
  2670. }
  2671. /* Use "Cache-Control: max-age" instead of "Expires" header.
  2672. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  2673. /* See also https://www.mnot.net/cache_docs/ */
  2674. /* According to RFC 2616, Section 14.21, caching times should not exceed
  2675. * one year. A year with 365 days corresponds to 31536000 seconds, a leap
  2676. * year to 31622400 seconds. For the moment, we just send whatever has
  2677. * been configured, still the behavior for >1 year should be considered
  2678. * as undefined. */
  2679. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  2680. #else /* NO_CACHING */
  2681. return send_no_cache_header(conn);
  2682. #endif /* !NO_CACHING */
  2683. }
  2684. static int
  2685. send_additional_header(struct mg_connection *conn)
  2686. {
  2687. int i = 0;
  2688. #if 0
  2689. i += mg_printf(conn, "Strict-Transport-Security: max-age=%u\r\n", 3600);
  2690. #endif
  2691. i += mg_printf(conn, "X-Some-Test-Header: %u\r\n", 42);
  2692. return i;
  2693. }
  2694. static void handle_file_based_request(struct mg_connection *conn,
  2695. const char *path,
  2696. struct mg_file *filep);
  2697. const char *
  2698. mg_get_response_code_text(struct mg_connection *conn, int response_code)
  2699. {
  2700. /* See IANA HTTP status code assignment:
  2701. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  2702. */
  2703. switch (response_code) {
  2704. /* RFC2616 Section 10.1 - Informational 1xx */
  2705. case 100:
  2706. return "Continue"; /* RFC2616 Section 10.1.1 */
  2707. case 101:
  2708. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  2709. case 102:
  2710. return "Processing"; /* RFC2518 Section 10.1 */
  2711. /* RFC2616 Section 10.2 - Successful 2xx */
  2712. case 200:
  2713. return "OK"; /* RFC2616 Section 10.2.1 */
  2714. case 201:
  2715. return "Created"; /* RFC2616 Section 10.2.2 */
  2716. case 202:
  2717. return "Accepted"; /* RFC2616 Section 10.2.3 */
  2718. case 203:
  2719. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  2720. case 204:
  2721. return "No Content"; /* RFC2616 Section 10.2.5 */
  2722. case 205:
  2723. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  2724. case 206:
  2725. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  2726. case 207:
  2727. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1 */
  2728. case 208:
  2729. return "Already Reported"; /* RFC5842 Section 7.1 */
  2730. case 226:
  2731. return "IM used"; /* RFC3229 Section 10.4.1 */
  2732. /* RFC2616 Section 10.3 - Redirection 3xx */
  2733. case 300:
  2734. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  2735. case 301:
  2736. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  2737. case 302:
  2738. return "Found"; /* RFC2616 Section 10.3.3 */
  2739. case 303:
  2740. return "See Other"; /* RFC2616 Section 10.3.4 */
  2741. case 304:
  2742. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  2743. case 305:
  2744. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  2745. case 307:
  2746. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  2747. case 308:
  2748. return "Permanent Redirect"; /* RFC7238 Section 3 */
  2749. /* RFC2616 Section 10.4 - Client Error 4xx */
  2750. case 400:
  2751. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  2752. case 401:
  2753. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  2754. case 402:
  2755. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  2756. case 403:
  2757. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  2758. case 404:
  2759. return "Not Found"; /* RFC2616 Section 10.4.5 */
  2760. case 405:
  2761. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  2762. case 406:
  2763. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  2764. case 407:
  2765. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  2766. case 408:
  2767. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  2768. case 409:
  2769. return "Conflict"; /* RFC2616 Section 10.4.10 */
  2770. case 410:
  2771. return "Gone"; /* RFC2616 Section 10.4.11 */
  2772. case 411:
  2773. return "Length Required"; /* RFC2616 Section 10.4.12 */
  2774. case 412:
  2775. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  2776. case 413:
  2777. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  2778. case 414:
  2779. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  2780. case 415:
  2781. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  2782. case 416:
  2783. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17 */
  2784. case 417:
  2785. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  2786. case 421:
  2787. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  2788. case 422:
  2789. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  2790. * Section 11.2 */
  2791. case 423:
  2792. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  2793. case 424:
  2794. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  2795. * Section 11.4 */
  2796. case 426:
  2797. return "Upgrade Required"; /* RFC 2817 Section 4 */
  2798. case 428:
  2799. return "Precondition Required"; /* RFC 6585, Section 3 */
  2800. case 429:
  2801. return "Too Many Requests"; /* RFC 6585, Section 4 */
  2802. case 431:
  2803. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  2804. case 451:
  2805. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  2806. * Section 3 */
  2807. /* RFC2616 Section 10.5 - Server Error 5xx */
  2808. case 500:
  2809. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  2810. case 501:
  2811. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  2812. case 502:
  2813. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  2814. case 503:
  2815. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  2816. case 504:
  2817. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  2818. case 505:
  2819. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  2820. case 506:
  2821. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  2822. case 507:
  2823. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  2824. * Section 11.5 */
  2825. case 508:
  2826. return "Loop Detected"; /* RFC5842 Section 7.1 */
  2827. case 510:
  2828. return "Not Extended"; /* RFC 2774, Section 7 */
  2829. case 511:
  2830. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  2831. /* Other status codes, not shown in the IANA HTTP status code assignment.
  2832. * E.g., "de facto" standards due to common use, ... */
  2833. case 418:
  2834. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  2835. case 419:
  2836. return "Authentication Timeout"; /* common use */
  2837. case 420:
  2838. return "Enhance Your Calm"; /* common use */
  2839. case 440:
  2840. return "Login Timeout"; /* common use */
  2841. case 509:
  2842. return "Bandwidth Limit Exceeded"; /* common use */
  2843. default:
  2844. /* This error code is unknown. This should not happen. */
  2845. if (conn) {
  2846. mg_cry(conn, "Unknown HTTP response code: %u", response_code);
  2847. }
  2848. /* Return at least a category according to RFC 2616 Section 10. */
  2849. if (response_code >= 100 && response_code < 200) {
  2850. /* Unknown informational status code */
  2851. return "Information";
  2852. }
  2853. if (response_code >= 200 && response_code < 300) {
  2854. /* Unknown success code */
  2855. return "Success";
  2856. }
  2857. if (response_code >= 300 && response_code < 400) {
  2858. /* Unknown redirection code */
  2859. return "Redirection";
  2860. }
  2861. if (response_code >= 400 && response_code < 500) {
  2862. /* Unknown request error code */
  2863. return "Client Error";
  2864. }
  2865. if (response_code >= 500 && response_code < 600) {
  2866. /* Unknown server error code */
  2867. return "Server Error";
  2868. }
  2869. /* Response code not even within reasonable range */
  2870. return "";
  2871. }
  2872. }
  2873. static void send_http_error(struct mg_connection *,
  2874. int,
  2875. PRINTF_FORMAT_STRING(const char *fmt),
  2876. ...) PRINTF_ARGS(3, 4);
  2877. static void
  2878. send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  2879. {
  2880. char buf[MG_BUF_LEN];
  2881. va_list ap;
  2882. int len, i, page_handler_found, scope, truncated, has_body;
  2883. char date[64];
  2884. time_t curtime = time(NULL);
  2885. const char *error_handler = NULL;
  2886. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  2887. const char *error_page_file_ext, *tstr;
  2888. const char *status_text = mg_get_response_code_text(conn, status);
  2889. if (conn == NULL) {
  2890. return;
  2891. }
  2892. conn->status_code = status;
  2893. if (conn->in_error_handler || conn->ctx->callbacks.http_error == NULL
  2894. || conn->ctx->callbacks.http_error(conn, status)) {
  2895. if (!conn->in_error_handler) {
  2896. /* Send user defined error pages, if defined */
  2897. error_handler = conn->ctx->config[ERROR_PAGES];
  2898. error_page_file_ext = conn->ctx->config[INDEX_FILES];
  2899. page_handler_found = 0;
  2900. if (error_handler != NULL) {
  2901. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  2902. switch (scope) {
  2903. case 1: /* Handler for specific error, e.g. 404 error */
  2904. mg_snprintf(conn,
  2905. &truncated,
  2906. buf,
  2907. sizeof(buf) - 32,
  2908. "%serror%03u.",
  2909. error_handler,
  2910. status);
  2911. break;
  2912. case 2: /* Handler for error group, e.g., 5xx error handler
  2913. * for all server errors (500-599) */
  2914. mg_snprintf(conn,
  2915. &truncated,
  2916. buf,
  2917. sizeof(buf) - 32,
  2918. "%serror%01uxx.",
  2919. error_handler,
  2920. status / 100);
  2921. break;
  2922. default: /* Handler for all errors */
  2923. mg_snprintf(conn,
  2924. &truncated,
  2925. buf,
  2926. sizeof(buf) - 32,
  2927. "%serror.",
  2928. error_handler);
  2929. break;
  2930. }
  2931. /* String truncation in buf may only occur if error_handler
  2932. * is too long. This string is from the config, not from a
  2933. * client. */
  2934. (void)truncated;
  2935. len = (int)strlen(buf);
  2936. tstr = strchr(error_page_file_ext, '.');
  2937. while (tstr) {
  2938. for (i = 1; i < 32 && tstr[i] != 0 && tstr[i] != ',';
  2939. i++)
  2940. buf[len + i - 1] = tstr[i];
  2941. buf[len + i - 1] = 0;
  2942. if (mg_stat(conn, buf, &error_page_file.stat)) {
  2943. page_handler_found = 1;
  2944. break;
  2945. }
  2946. tstr = strchr(tstr + i, '.');
  2947. }
  2948. }
  2949. }
  2950. if (page_handler_found) {
  2951. conn->in_error_handler = 1;
  2952. handle_file_based_request(conn, buf, &error_page_file);
  2953. conn->in_error_handler = 0;
  2954. return;
  2955. }
  2956. }
  2957. /* No custom error page. Send default error page. */
  2958. gmt_time_string(date, sizeof(date), &curtime);
  2959. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  2960. has_body = (status > 199 && status != 204 && status != 304);
  2961. conn->must_close = 1;
  2962. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  2963. send_no_cache_header(conn);
  2964. send_additional_header(conn);
  2965. if (has_body) {
  2966. mg_printf(conn,
  2967. "%s",
  2968. "Content-Type: text/plain; charset=utf-8\r\n");
  2969. }
  2970. mg_printf(conn,
  2971. "Date: %s\r\n"
  2972. "Connection: close\r\n\r\n",
  2973. date);
  2974. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  2975. if (has_body) {
  2976. mg_printf(conn, "Error %d: %s\n", status, status_text);
  2977. if (fmt != NULL) {
  2978. va_start(ap, fmt);
  2979. mg_vsnprintf(conn, NULL, buf, sizeof(buf), fmt, ap);
  2980. va_end(ap);
  2981. mg_write(conn, buf, strlen(buf));
  2982. DEBUG_TRACE("Error %i - [%s]", status, buf);
  2983. }
  2984. } else {
  2985. /* No body allowed. Close the connection. */
  2986. DEBUG_TRACE("Error %i", status);
  2987. }
  2988. }
  2989. }
  2990. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  2991. /* Create substitutes for POSIX functions in Win32. */
  2992. #if defined(__MINGW32__)
  2993. /* Show no warning in case system functions are not used. */
  2994. #pragma GCC diagnostic push
  2995. #pragma GCC diagnostic ignored "-Wunused-function"
  2996. #endif
  2997. static int
  2998. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  2999. {
  3000. (void)unused;
  3001. *mutex = CreateMutex(NULL, FALSE, NULL);
  3002. return (*mutex == NULL) ? -1 : 0;
  3003. }
  3004. static int
  3005. pthread_mutex_destroy(pthread_mutex_t *mutex)
  3006. {
  3007. return (CloseHandle(*mutex) == 0) ? -1 : 0;
  3008. }
  3009. static int
  3010. pthread_mutex_lock(pthread_mutex_t *mutex)
  3011. {
  3012. return (WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0) ? 0 : -1;
  3013. }
  3014. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  3015. static int
  3016. pthread_mutex_trylock(pthread_mutex_t *mutex)
  3017. {
  3018. switch (WaitForSingleObject(*mutex, 0)) {
  3019. case WAIT_OBJECT_0:
  3020. return 0;
  3021. case WAIT_TIMEOUT:
  3022. return -2; /* EBUSY */
  3023. }
  3024. return -1;
  3025. }
  3026. #endif
  3027. static int
  3028. pthread_mutex_unlock(pthread_mutex_t *mutex)
  3029. {
  3030. return (ReleaseMutex(*mutex) == 0) ? -1 : 0;
  3031. }
  3032. static int
  3033. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  3034. {
  3035. (void)unused;
  3036. InitializeCriticalSection(&cv->threadIdSec);
  3037. cv->waiting_thread = NULL;
  3038. return 0;
  3039. }
  3040. static int
  3041. pthread_cond_timedwait(pthread_cond_t *cv,
  3042. pthread_mutex_t *mutex,
  3043. const struct timespec *abstime)
  3044. {
  3045. struct mg_workerTLS **ptls,
  3046. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3047. int ok;
  3048. int64_t nsnow, nswaitabs, nswaitrel;
  3049. DWORD mswaitrel;
  3050. EnterCriticalSection(&cv->threadIdSec);
  3051. /* Add this thread to cv's waiting list */
  3052. ptls = &cv->waiting_thread;
  3053. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  3054. ;
  3055. tls->next_waiting_thread = NULL;
  3056. *ptls = tls;
  3057. LeaveCriticalSection(&cv->threadIdSec);
  3058. if (abstime) {
  3059. nsnow = mg_get_current_time_ns();
  3060. nswaitabs =
  3061. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  3062. nswaitrel = nswaitabs - nsnow;
  3063. if (nswaitrel < 0) {
  3064. nswaitrel = 0;
  3065. }
  3066. mswaitrel = (DWORD)(nswaitrel / 1000000);
  3067. } else {
  3068. mswaitrel = INFINITE;
  3069. }
  3070. pthread_mutex_unlock(mutex);
  3071. ok = (WAIT_OBJECT_0
  3072. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  3073. if (!ok) {
  3074. ok = 1;
  3075. EnterCriticalSection(&cv->threadIdSec);
  3076. ptls = &cv->waiting_thread;
  3077. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  3078. if (*ptls == tls) {
  3079. *ptls = tls->next_waiting_thread;
  3080. ok = 0;
  3081. break;
  3082. }
  3083. }
  3084. LeaveCriticalSection(&cv->threadIdSec);
  3085. if (ok) {
  3086. WaitForSingleObject(tls->pthread_cond_helper_mutex, INFINITE);
  3087. }
  3088. }
  3089. /* This thread has been removed from cv's waiting list */
  3090. pthread_mutex_lock(mutex);
  3091. return ok ? 0 : -1;
  3092. }
  3093. static int
  3094. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  3095. {
  3096. return pthread_cond_timedwait(cv, mutex, NULL);
  3097. }
  3098. static int
  3099. pthread_cond_signal(pthread_cond_t *cv)
  3100. {
  3101. HANDLE wkup = NULL;
  3102. BOOL ok = FALSE;
  3103. EnterCriticalSection(&cv->threadIdSec);
  3104. if (cv->waiting_thread) {
  3105. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  3106. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  3107. ok = SetEvent(wkup);
  3108. assert(ok);
  3109. }
  3110. LeaveCriticalSection(&cv->threadIdSec);
  3111. return ok ? 0 : 1;
  3112. }
  3113. static int
  3114. pthread_cond_broadcast(pthread_cond_t *cv)
  3115. {
  3116. EnterCriticalSection(&cv->threadIdSec);
  3117. while (cv->waiting_thread) {
  3118. pthread_cond_signal(cv);
  3119. }
  3120. LeaveCriticalSection(&cv->threadIdSec);
  3121. return 0;
  3122. }
  3123. static int
  3124. pthread_cond_destroy(pthread_cond_t *cv)
  3125. {
  3126. EnterCriticalSection(&cv->threadIdSec);
  3127. assert(cv->waiting_thread == NULL);
  3128. LeaveCriticalSection(&cv->threadIdSec);
  3129. DeleteCriticalSection(&cv->threadIdSec);
  3130. return 0;
  3131. }
  3132. #ifdef ALTERNATIVE_QUEUE
  3133. static void *
  3134. event_create(void)
  3135. {
  3136. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  3137. }
  3138. static int
  3139. event_wait(void *eventhdl)
  3140. {
  3141. int res = WaitForSingleObject((HANDLE)eventhdl, INFINITE);
  3142. return (res == WAIT_OBJECT_0);
  3143. }
  3144. static int
  3145. event_signal(void *eventhdl)
  3146. {
  3147. return (int)SetEvent((HANDLE)eventhdl);
  3148. }
  3149. static void
  3150. event_destroy(void *eventhdl)
  3151. {
  3152. CloseHandle((HANDLE)eventhdl);
  3153. }
  3154. #endif
  3155. #if defined(__MINGW32__)
  3156. /* Enable unused function warning again */
  3157. #pragma GCC diagnostic pop
  3158. #endif
  3159. /* For Windows, change all slashes to backslashes in path names. */
  3160. static void
  3161. change_slashes_to_backslashes(char *path)
  3162. {
  3163. int i;
  3164. for (i = 0; path[i] != '\0'; i++) {
  3165. if (path[i] == '/') {
  3166. path[i] = '\\';
  3167. }
  3168. /* remove double backslash (check i > 0 to preserve UNC paths,
  3169. * like \\server\file.txt) */
  3170. if ((path[i] == '\\') && (i > 0)) {
  3171. while (path[i + 1] == '\\' || path[i + 1] == '/') {
  3172. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  3173. }
  3174. }
  3175. }
  3176. }
  3177. static int
  3178. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  3179. {
  3180. int diff;
  3181. do {
  3182. diff = tolower(*s1) - tolower(*s2);
  3183. s1++;
  3184. s2++;
  3185. } while (diff == 0 && s1[-1] != '\0');
  3186. return diff;
  3187. }
  3188. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  3189. * wbuf and wbuf_len is a target buffer and its length. */
  3190. static void
  3191. path_to_unicode(const struct mg_connection *conn,
  3192. const char *path,
  3193. wchar_t *wbuf,
  3194. size_t wbuf_len)
  3195. {
  3196. char buf[PATH_MAX], buf2[PATH_MAX];
  3197. wchar_t wbuf2[MAX_PATH + 1];
  3198. DWORD long_len, err;
  3199. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  3200. mg_strlcpy(buf, path, sizeof(buf));
  3201. change_slashes_to_backslashes(buf);
  3202. /* Convert to Unicode and back. If doubly-converted string does not
  3203. * match the original, something is fishy, reject. */
  3204. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  3205. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  3206. WideCharToMultiByte(
  3207. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  3208. if (strcmp(buf, buf2) != 0) {
  3209. wbuf[0] = L'\0';
  3210. }
  3211. /* Windows file systems are not case sensitive, but you can still use
  3212. * uppercase and lowercase letters (on all modern file systems).
  3213. * The server can check if the URI uses the same upper/lowercase
  3214. * letters an the file system, effectively making Windows servers
  3215. * case sensitive (like Linux servers are). It is still not possible
  3216. * to use two files with the same name in different cases on Windows
  3217. * (like /a and /A) - this would be possible in Linux.
  3218. * As a default, Windows is not case sensitive, but the case sensitive
  3219. * file name check can be activated by an additional configuration. */
  3220. if (conn) {
  3221. if (conn->ctx->config[CASE_SENSITIVE_FILES]
  3222. && !mg_strcasecmp(conn->ctx->config[CASE_SENSITIVE_FILES], "yes")) {
  3223. /* Use case sensitive compare function */
  3224. fcompare = wcscmp;
  3225. }
  3226. }
  3227. (void)conn; /* conn is currently unused */
  3228. #if !defined(_WIN32_WCE)
  3229. /* Only accept a full file path, not a Windows short (8.3) path. */
  3230. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  3231. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  3232. if (long_len == 0) {
  3233. err = GetLastError();
  3234. if (err == ERROR_FILE_NOT_FOUND) {
  3235. /* File does not exist. This is not always a problem here. */
  3236. return;
  3237. }
  3238. }
  3239. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  3240. /* Short name is used. */
  3241. wbuf[0] = L'\0';
  3242. }
  3243. #else
  3244. (void)long_len;
  3245. (void)wbuf2;
  3246. (void)err;
  3247. if (strchr(path, '~')) {
  3248. wbuf[0] = L'\0';
  3249. }
  3250. #endif
  3251. }
  3252. /* Windows happily opens files with some garbage at the end of file name.
  3253. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  3254. * "a.cgi", despite one would expect an error back.
  3255. * This function returns non-0 if path ends with some garbage. */
  3256. static int
  3257. path_cannot_disclose_cgi(const char *path)
  3258. {
  3259. static const char *allowed_last_characters = "_-";
  3260. int last = path[strlen(path) - 1];
  3261. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  3262. }
  3263. static int
  3264. mg_stat(const struct mg_connection *conn,
  3265. const char *path,
  3266. struct mg_file_stat *filep)
  3267. {
  3268. wchar_t wbuf[PATH_MAX];
  3269. WIN32_FILE_ATTRIBUTE_DATA info;
  3270. time_t creation_time;
  3271. if (!filep) {
  3272. return 0;
  3273. }
  3274. memset(filep, 0, sizeof(*filep));
  3275. if (conn && is_file_in_memory(conn, path)) {
  3276. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  3277. * memset */
  3278. /* Quick fix (for 1.9.x): */
  3279. /* mg_stat must fill all fields, also for files in memory */
  3280. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  3281. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  3282. filep->size = tmp_file.stat.size;
  3283. filep->location = 2;
  3284. /* TODO: for 1.10: restructure how files in memory are handled */
  3285. filep->last_modified = time(NULL); /* xxxxxxxx */
  3286. /* last_modified = now ... assumes the file may change during runtime,
  3287. * so every mg_fopen call may return different data */
  3288. /* last_modified = conn->ctx.start_time;
  3289. * May be used it the data does not change during runtime. This allows
  3290. * browser caching. Since we do not know, we have to assume the file
  3291. * in memory may change. */
  3292. return 1;
  3293. }
  3294. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3295. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  3296. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  3297. filep->last_modified =
  3298. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  3299. info.ftLastWriteTime.dwHighDateTime);
  3300. /* On Windows, the file creation time can be higher than the
  3301. * modification time, e.g. when a file is copied.
  3302. * Since the Last-Modified timestamp is used for caching
  3303. * it should be based on the most recent timestamp. */
  3304. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  3305. info.ftCreationTime.dwHighDateTime);
  3306. if (creation_time > filep->last_modified) {
  3307. filep->last_modified = creation_time;
  3308. }
  3309. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  3310. /* If file name is fishy, reset the file structure and return
  3311. * error.
  3312. * Note it is important to reset, not just return the error, cause
  3313. * functions like is_file_opened() check the struct. */
  3314. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  3315. memset(filep, 0, sizeof(*filep));
  3316. return 0;
  3317. }
  3318. return 1;
  3319. }
  3320. return 0;
  3321. }
  3322. static int
  3323. mg_remove(const struct mg_connection *conn, const char *path)
  3324. {
  3325. wchar_t wbuf[PATH_MAX];
  3326. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3327. return DeleteFileW(wbuf) ? 0 : -1;
  3328. }
  3329. static int
  3330. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  3331. {
  3332. wchar_t wbuf[PATH_MAX];
  3333. (void)mode;
  3334. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3335. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  3336. }
  3337. /* Create substitutes for POSIX functions in Win32. */
  3338. #if defined(__MINGW32__)
  3339. /* Show no warning in case system functions are not used. */
  3340. #pragma GCC diagnostic push
  3341. #pragma GCC diagnostic ignored "-Wunused-function"
  3342. #endif
  3343. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  3344. static DIR *
  3345. mg_opendir(const struct mg_connection *conn, const char *name)
  3346. {
  3347. DIR *dir = NULL;
  3348. wchar_t wpath[PATH_MAX];
  3349. DWORD attrs;
  3350. if (name == NULL) {
  3351. SetLastError(ERROR_BAD_ARGUMENTS);
  3352. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  3353. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  3354. } else {
  3355. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  3356. attrs = GetFileAttributesW(wpath);
  3357. if (attrs != 0xFFFFFFFF && ((attrs & FILE_ATTRIBUTE_DIRECTORY)
  3358. == FILE_ATTRIBUTE_DIRECTORY)) {
  3359. (void)wcscat(wpath, L"\\*");
  3360. dir->handle = FindFirstFileW(wpath, &dir->info);
  3361. dir->result.d_name[0] = '\0';
  3362. } else {
  3363. mg_free(dir);
  3364. dir = NULL;
  3365. }
  3366. }
  3367. return dir;
  3368. }
  3369. static int
  3370. mg_closedir(DIR *dir)
  3371. {
  3372. int result = 0;
  3373. if (dir != NULL) {
  3374. if (dir->handle != INVALID_HANDLE_VALUE)
  3375. result = FindClose(dir->handle) ? 0 : -1;
  3376. mg_free(dir);
  3377. } else {
  3378. result = -1;
  3379. SetLastError(ERROR_BAD_ARGUMENTS);
  3380. }
  3381. return result;
  3382. }
  3383. static struct dirent *
  3384. mg_readdir(DIR *dir)
  3385. {
  3386. struct dirent *result = 0;
  3387. if (dir) {
  3388. if (dir->handle != INVALID_HANDLE_VALUE) {
  3389. result = &dir->result;
  3390. (void)WideCharToMultiByte(CP_UTF8,
  3391. 0,
  3392. dir->info.cFileName,
  3393. -1,
  3394. result->d_name,
  3395. sizeof(result->d_name),
  3396. NULL,
  3397. NULL);
  3398. if (!FindNextFileW(dir->handle, &dir->info)) {
  3399. (void)FindClose(dir->handle);
  3400. dir->handle = INVALID_HANDLE_VALUE;
  3401. }
  3402. } else {
  3403. SetLastError(ERROR_FILE_NOT_FOUND);
  3404. }
  3405. } else {
  3406. SetLastError(ERROR_BAD_ARGUMENTS);
  3407. }
  3408. return result;
  3409. }
  3410. #ifndef HAVE_POLL
  3411. static int
  3412. poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  3413. {
  3414. struct timeval tv;
  3415. fd_set set;
  3416. unsigned int i;
  3417. int result;
  3418. SOCKET maxfd = 0;
  3419. memset(&tv, 0, sizeof(tv));
  3420. tv.tv_sec = milliseconds / 1000;
  3421. tv.tv_usec = (milliseconds % 1000) * 1000;
  3422. FD_ZERO(&set);
  3423. for (i = 0; i < n; i++) {
  3424. FD_SET((SOCKET)pfd[i].fd, &set);
  3425. pfd[i].revents = 0;
  3426. if (pfd[i].fd > maxfd) {
  3427. maxfd = pfd[i].fd;
  3428. }
  3429. }
  3430. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  3431. for (i = 0; i < n; i++) {
  3432. if (FD_ISSET(pfd[i].fd, &set)) {
  3433. pfd[i].revents = POLLIN;
  3434. }
  3435. }
  3436. }
  3437. /* We should subtract the time used in select from remaining
  3438. * "milliseconds", in particular if called from mg_poll with a
  3439. * timeout quantum.
  3440. * Unfortunately, the remaining time is not stored in "tv" in all
  3441. * implementations, so the result in "tv" must be considered undefined.
  3442. * See http://man7.org/linux/man-pages/man2/select.2.html */
  3443. return result;
  3444. }
  3445. #endif /* HAVE_POLL */
  3446. #if defined(__MINGW32__)
  3447. /* Enable unused function warning again */
  3448. #pragma GCC diagnostic pop
  3449. #endif
  3450. static void
  3451. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  3452. {
  3453. (void)conn; /* Unused. */
  3454. #if defined(_WIN32_WCE)
  3455. (void)sock;
  3456. #else
  3457. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  3458. #endif
  3459. }
  3460. int
  3461. mg_start_thread(mg_thread_func_t f, void *p)
  3462. {
  3463. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3464. /* Compile-time option to control stack size, e.g. -DUSE_STACK_SIZE=16384
  3465. */
  3466. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  3467. == ((uintptr_t)(-1L)))
  3468. ? -1
  3469. : 0);
  3470. #else
  3471. return (
  3472. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  3473. ? -1
  3474. : 0);
  3475. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3476. }
  3477. /* Start a thread storing the thread context. */
  3478. static int
  3479. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  3480. void *p,
  3481. pthread_t *threadidptr)
  3482. {
  3483. uintptr_t uip;
  3484. HANDLE threadhandle;
  3485. int result = -1;
  3486. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  3487. threadhandle = (HANDLE)uip;
  3488. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  3489. *threadidptr = threadhandle;
  3490. result = 0;
  3491. }
  3492. return result;
  3493. }
  3494. /* Wait for a thread to finish. */
  3495. static int
  3496. mg_join_thread(pthread_t threadid)
  3497. {
  3498. int result;
  3499. DWORD dwevent;
  3500. result = -1;
  3501. dwevent = WaitForSingleObject(threadid, INFINITE);
  3502. if (dwevent == WAIT_FAILED) {
  3503. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  3504. } else {
  3505. if (dwevent == WAIT_OBJECT_0) {
  3506. CloseHandle(threadid);
  3507. result = 0;
  3508. }
  3509. }
  3510. return result;
  3511. }
  3512. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  3513. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  3514. /* Create substitutes for POSIX functions in Win32. */
  3515. #if defined(__MINGW32__)
  3516. /* Show no warning in case system functions are not used. */
  3517. #pragma GCC diagnostic push
  3518. #pragma GCC diagnostic ignored "-Wunused-function"
  3519. #endif
  3520. static HANDLE
  3521. dlopen(const char *dll_name, int flags)
  3522. {
  3523. wchar_t wbuf[PATH_MAX];
  3524. (void)flags;
  3525. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  3526. return LoadLibraryW(wbuf);
  3527. }
  3528. static int
  3529. dlclose(void *handle)
  3530. {
  3531. int result;
  3532. if (FreeLibrary((HMODULE)handle) != 0) {
  3533. result = 0;
  3534. } else {
  3535. result = -1;
  3536. }
  3537. return result;
  3538. }
  3539. #if defined(__MINGW32__)
  3540. /* Enable unused function warning again */
  3541. #pragma GCC diagnostic pop
  3542. #endif
  3543. #endif
  3544. #if !defined(NO_CGI)
  3545. #define SIGKILL (0)
  3546. static int
  3547. kill(pid_t pid, int sig_num)
  3548. {
  3549. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  3550. (void)CloseHandle((HANDLE)pid);
  3551. return 0;
  3552. }
  3553. static void
  3554. trim_trailing_whitespaces(char *s)
  3555. {
  3556. char *e = s + strlen(s) - 1;
  3557. while (e > s && isspace(*(unsigned char *)e)) {
  3558. *e-- = '\0';
  3559. }
  3560. }
  3561. static pid_t
  3562. spawn_process(struct mg_connection *conn,
  3563. const char *prog,
  3564. char *envblk,
  3565. char *envp[],
  3566. int fdin[2],
  3567. int fdout[2],
  3568. int fderr[2],
  3569. const char *dir)
  3570. {
  3571. HANDLE me;
  3572. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  3573. cmdline[PATH_MAX], buf[PATH_MAX];
  3574. int truncated;
  3575. struct mg_file file = STRUCT_FILE_INITIALIZER;
  3576. STARTUPINFOA si;
  3577. PROCESS_INFORMATION pi = {0};
  3578. (void)envp;
  3579. memset(&si, 0, sizeof(si));
  3580. si.cb = sizeof(si);
  3581. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  3582. si.wShowWindow = SW_HIDE;
  3583. me = GetCurrentProcess();
  3584. DuplicateHandle(me,
  3585. (HANDLE)_get_osfhandle(fdin[0]),
  3586. me,
  3587. &si.hStdInput,
  3588. 0,
  3589. TRUE,
  3590. DUPLICATE_SAME_ACCESS);
  3591. DuplicateHandle(me,
  3592. (HANDLE)_get_osfhandle(fdout[1]),
  3593. me,
  3594. &si.hStdOutput,
  3595. 0,
  3596. TRUE,
  3597. DUPLICATE_SAME_ACCESS);
  3598. DuplicateHandle(me,
  3599. (HANDLE)_get_osfhandle(fderr[1]),
  3600. me,
  3601. &si.hStdError,
  3602. 0,
  3603. TRUE,
  3604. DUPLICATE_SAME_ACCESS);
  3605. /* Mark handles that should not be inherited. See
  3606. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  3607. */
  3608. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  3609. HANDLE_FLAG_INHERIT,
  3610. 0);
  3611. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  3612. HANDLE_FLAG_INHERIT,
  3613. 0);
  3614. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  3615. HANDLE_FLAG_INHERIT,
  3616. 0);
  3617. /* If CGI file is a script, try to read the interpreter line */
  3618. interp = conn->ctx->config[CGI_INTERPRETER];
  3619. if (interp == NULL) {
  3620. buf[0] = buf[1] = '\0';
  3621. /* Read the first line of the script into the buffer */
  3622. mg_snprintf(
  3623. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  3624. if (truncated) {
  3625. pi.hProcess = (pid_t)-1;
  3626. goto spawn_cleanup;
  3627. }
  3628. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  3629. p = (char *)file.access.membuf;
  3630. mg_fgets(buf, sizeof(buf), &file, &p);
  3631. (void)mg_fclose(&file.access); /* ignore error on read only file */
  3632. buf[sizeof(buf) - 1] = '\0';
  3633. }
  3634. if (buf[0] == '#' && buf[1] == '!') {
  3635. trim_trailing_whitespaces(buf + 2);
  3636. } else {
  3637. buf[2] = '\0';
  3638. }
  3639. interp = buf + 2;
  3640. }
  3641. if (interp[0] != '\0') {
  3642. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  3643. interp = full_interp;
  3644. }
  3645. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  3646. if (interp[0] != '\0') {
  3647. mg_snprintf(conn,
  3648. &truncated,
  3649. cmdline,
  3650. sizeof(cmdline),
  3651. "\"%s\" \"%s\\%s\"",
  3652. interp,
  3653. full_dir,
  3654. prog);
  3655. } else {
  3656. mg_snprintf(conn,
  3657. &truncated,
  3658. cmdline,
  3659. sizeof(cmdline),
  3660. "\"%s\\%s\"",
  3661. full_dir,
  3662. prog);
  3663. }
  3664. if (truncated) {
  3665. pi.hProcess = (pid_t)-1;
  3666. goto spawn_cleanup;
  3667. }
  3668. DEBUG_TRACE("Running [%s]", cmdline);
  3669. if (CreateProcessA(NULL,
  3670. cmdline,
  3671. NULL,
  3672. NULL,
  3673. TRUE,
  3674. CREATE_NEW_PROCESS_GROUP,
  3675. envblk,
  3676. NULL,
  3677. &si,
  3678. &pi) == 0) {
  3679. mg_cry(
  3680. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  3681. pi.hProcess = (pid_t)-1;
  3682. /* goto spawn_cleanup; */
  3683. }
  3684. spawn_cleanup:
  3685. (void)CloseHandle(si.hStdOutput);
  3686. (void)CloseHandle(si.hStdError);
  3687. (void)CloseHandle(si.hStdInput);
  3688. if (pi.hThread != NULL) {
  3689. (void)CloseHandle(pi.hThread);
  3690. }
  3691. return (pid_t)pi.hProcess;
  3692. }
  3693. #endif /* !NO_CGI */
  3694. static int
  3695. set_blocking_mode(SOCKET sock, int blocking)
  3696. {
  3697. unsigned long non_blocking = !blocking;
  3698. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  3699. }
  3700. #else
  3701. static int
  3702. mg_stat(const struct mg_connection *conn,
  3703. const char *path,
  3704. struct mg_file_stat *filep)
  3705. {
  3706. struct stat st;
  3707. if (!filep) {
  3708. return 0;
  3709. }
  3710. memset(filep, 0, sizeof(*filep));
  3711. if (conn && is_file_in_memory(conn, path)) {
  3712. /* Quick fix (for 1.9.x): */
  3713. /* mg_stat must fill all fields, also for files in memory */
  3714. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  3715. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  3716. filep->size = tmp_file.stat.size;
  3717. filep->last_modified = time(NULL);
  3718. filep->location = 2;
  3719. /* TODO: for 1.10: restructure how files in memory are handled */
  3720. return 1;
  3721. }
  3722. if (0 == stat(path, &st)) {
  3723. filep->size = (uint64_t)(st.st_size);
  3724. filep->last_modified = st.st_mtime;
  3725. filep->is_directory = S_ISDIR(st.st_mode);
  3726. return 1;
  3727. }
  3728. return 0;
  3729. }
  3730. static void
  3731. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  3732. {
  3733. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  3734. if (conn) {
  3735. mg_cry(conn,
  3736. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  3737. __func__,
  3738. strerror(ERRNO));
  3739. }
  3740. }
  3741. }
  3742. int
  3743. mg_start_thread(mg_thread_func_t func, void *param)
  3744. {
  3745. pthread_t thread_id;
  3746. pthread_attr_t attr;
  3747. int result;
  3748. (void)pthread_attr_init(&attr);
  3749. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  3750. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3751. /* Compile-time option to control stack size,
  3752. * e.g. -DUSE_STACK_SIZE=16384 */
  3753. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3754. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3755. result = pthread_create(&thread_id, &attr, func, param);
  3756. pthread_attr_destroy(&attr);
  3757. return result;
  3758. }
  3759. /* Start a thread storing the thread context. */
  3760. static int
  3761. mg_start_thread_with_id(mg_thread_func_t func,
  3762. void *param,
  3763. pthread_t *threadidptr)
  3764. {
  3765. pthread_t thread_id;
  3766. pthread_attr_t attr;
  3767. int result;
  3768. (void)pthread_attr_init(&attr);
  3769. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3770. /* Compile-time option to control stack size,
  3771. * e.g. -DUSE_STACK_SIZE=16384 */
  3772. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3773. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  3774. result = pthread_create(&thread_id, &attr, func, param);
  3775. pthread_attr_destroy(&attr);
  3776. if ((result == 0) && (threadidptr != NULL)) {
  3777. *threadidptr = thread_id;
  3778. }
  3779. return result;
  3780. }
  3781. /* Wait for a thread to finish. */
  3782. static int
  3783. mg_join_thread(pthread_t threadid)
  3784. {
  3785. int result;
  3786. result = pthread_join(threadid, NULL);
  3787. return result;
  3788. }
  3789. #ifndef NO_CGI
  3790. static pid_t
  3791. spawn_process(struct mg_connection *conn,
  3792. const char *prog,
  3793. char *envblk,
  3794. char *envp[],
  3795. int fdin[2],
  3796. int fdout[2],
  3797. int fderr[2],
  3798. const char *dir)
  3799. {
  3800. pid_t pid;
  3801. const char *interp;
  3802. (void)envblk;
  3803. if (conn == NULL) {
  3804. return 0;
  3805. }
  3806. if ((pid = fork()) == -1) {
  3807. /* Parent */
  3808. send_http_error(conn,
  3809. 500,
  3810. "Error: Creating CGI process\nfork(): %s",
  3811. strerror(ERRNO));
  3812. } else if (pid == 0) {
  3813. /* Child */
  3814. if (chdir(dir) != 0) {
  3815. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  3816. } else if (dup2(fdin[0], 0) == -1) {
  3817. mg_cry(conn,
  3818. "%s: dup2(%d, 0): %s",
  3819. __func__,
  3820. fdin[0],
  3821. strerror(ERRNO));
  3822. } else if (dup2(fdout[1], 1) == -1) {
  3823. mg_cry(conn,
  3824. "%s: dup2(%d, 1): %s",
  3825. __func__,
  3826. fdout[1],
  3827. strerror(ERRNO));
  3828. } else if (dup2(fderr[1], 2) == -1) {
  3829. mg_cry(conn,
  3830. "%s: dup2(%d, 2): %s",
  3831. __func__,
  3832. fderr[1],
  3833. strerror(ERRNO));
  3834. } else {
  3835. /* Keep stderr and stdout in two different pipes.
  3836. * Stdout will be sent back to the client,
  3837. * stderr should go into a server error log. */
  3838. (void)close(fdin[0]);
  3839. (void)close(fdout[1]);
  3840. (void)close(fderr[1]);
  3841. /* Close write end fdin and read end fdout and fderr */
  3842. (void)close(fdin[1]);
  3843. (void)close(fdout[0]);
  3844. (void)close(fderr[0]);
  3845. /* After exec, all signal handlers are restored to their default
  3846. * values, with one exception of SIGCHLD. According to
  3847. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler will
  3848. * leave unchanged after exec if it was set to be ignored. Restore
  3849. * it to default action. */
  3850. signal(SIGCHLD, SIG_DFL);
  3851. interp = conn->ctx->config[CGI_INTERPRETER];
  3852. if (interp == NULL) {
  3853. (void)execle(prog, prog, NULL, envp);
  3854. mg_cry(conn,
  3855. "%s: execle(%s): %s",
  3856. __func__,
  3857. prog,
  3858. strerror(ERRNO));
  3859. } else {
  3860. (void)execle(interp, interp, prog, NULL, envp);
  3861. mg_cry(conn,
  3862. "%s: execle(%s %s): %s",
  3863. __func__,
  3864. interp,
  3865. prog,
  3866. strerror(ERRNO));
  3867. }
  3868. }
  3869. exit(EXIT_FAILURE);
  3870. }
  3871. return pid;
  3872. }
  3873. #endif /* !NO_CGI */
  3874. static int
  3875. set_blocking_mode(SOCKET sock, int blocking)
  3876. {
  3877. int flags;
  3878. flags = fcntl(sock, F_GETFL, 0);
  3879. if (blocking) {
  3880. (void)fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  3881. } else {
  3882. (void)fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK)));
  3883. }
  3884. return 0;
  3885. }
  3886. #endif /* _WIN32 */
  3887. /* End of initial operating system specific define block. */
  3888. /* Get a random number (independent of C rand function) */
  3889. static uint64_t
  3890. get_random(void)
  3891. {
  3892. static uint64_t lfsr = 0; /* Linear feedback shift register */
  3893. static uint64_t lcg = 0; /* Linear congruential generator */
  3894. if (lfsr == 0) {
  3895. /* lfsr will be only 0 if has not been initialized,
  3896. * so this code is called only once. */
  3897. lfsr = mg_get_current_time_ns();
  3898. lcg = mg_get_current_time_ns();
  3899. } else {
  3900. /* Get the next step of both random number generators. */
  3901. lfsr = (lfsr >> 1)
  3902. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  3903. << 63);
  3904. lcg = lcg * 6364136223846793005 + 1442695040888963407;
  3905. }
  3906. /* Combining two pseudo-random number generators and a high resolution part
  3907. * of the current server time will make it hard (impossible?) to guess the
  3908. * next number. */
  3909. return (lfsr ^ lcg ^ (uint64_t)now.tv_nsec);
  3910. }
  3911. static int
  3912. mg_poll(struct pollfd *pfd,
  3913. unsigned int n,
  3914. int milliseconds,
  3915. volatile int *stop_server)
  3916. {
  3917. int ms_now, result;
  3918. /* Call poll, but only for a maximum time of a few seconds.
  3919. * This will allow to stop the server after some seconds, instead
  3920. * of having to wait for a long socket timeout. */
  3921. ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  3922. do {
  3923. if (*stop_server) {
  3924. /* Shut down signal */
  3925. return -2;
  3926. }
  3927. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  3928. ms_now = milliseconds;
  3929. }
  3930. result = poll(pfd, n, ms_now);
  3931. if (result != 0) {
  3932. /* Poll returned either success (1) or error (-1).
  3933. * Forward both to the caller. */
  3934. return result;
  3935. }
  3936. /* Poll returned timeout (0). */
  3937. if (milliseconds > 0) {
  3938. milliseconds -= ms_now;
  3939. }
  3940. } while (milliseconds != 0);
  3941. return result;
  3942. }
  3943. /* Write data to the IO channel - opened file descriptor, socket or SSL
  3944. * descriptor. Return number of bytes written. */
  3945. static int
  3946. push(struct mg_context *ctx,
  3947. FILE *fp,
  3948. SOCKET sock,
  3949. SSL *ssl,
  3950. const char *buf,
  3951. int len,
  3952. double timeout)
  3953. {
  3954. uint64_t start, now, timeout_ns;
  3955. int n, err;
  3956. #ifdef _WIN32
  3957. typedef int len_t;
  3958. #else
  3959. typedef size_t len_t;
  3960. #endif
  3961. if (timeout > 0) {
  3962. start = mg_get_current_time_ns();
  3963. timeout_ns = (uint64_t)(timeout * 1.0E9);
  3964. } else {
  3965. timeout_ns = 0;
  3966. }
  3967. if (ctx == NULL) {
  3968. return -1;
  3969. }
  3970. #ifdef NO_SSL
  3971. if (ssl) {
  3972. return -1;
  3973. }
  3974. #endif
  3975. do {
  3976. #ifndef NO_SSL
  3977. if (ssl != NULL) {
  3978. n = SSL_write(ssl, buf, len);
  3979. if (n <= 0) {
  3980. err = SSL_get_error(ssl, n);
  3981. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  3982. err = ERRNO;
  3983. } else if ((err == SSL_ERROR_WANT_READ)
  3984. || (err == SSL_ERROR_WANT_WRITE)) {
  3985. n = 0;
  3986. } else {
  3987. DEBUG_TRACE("SSL_write() failed, error %d", err);
  3988. return -1;
  3989. }
  3990. } else {
  3991. err = 0;
  3992. }
  3993. } else
  3994. #endif
  3995. if (fp != NULL) {
  3996. n = (int)fwrite(buf, 1, (size_t)len, fp);
  3997. if (ferror(fp)) {
  3998. n = -1;
  3999. err = ERRNO;
  4000. } else {
  4001. err = 0;
  4002. }
  4003. } else {
  4004. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  4005. err = (n < 0) ? ERRNO : 0;
  4006. #ifdef _WIN32
  4007. if (err == WSAEWOULDBLOCK) {
  4008. err = 0;
  4009. n = 0;
  4010. }
  4011. #else
  4012. if (err == EWOULDBLOCK) {
  4013. err = 0;
  4014. n = 0;
  4015. }
  4016. #endif
  4017. if (n < 0) {
  4018. /* shutdown of the socket at client side */
  4019. return -1;
  4020. }
  4021. }
  4022. if (ctx->stop_flag) {
  4023. return -1;
  4024. }
  4025. if ((n > 0) || (n == 0 && len == 0)) {
  4026. /* some data has been read, or no data was requested */
  4027. return n;
  4028. }
  4029. if (n < 0) {
  4030. /* socket error - check errno */
  4031. DEBUG_TRACE("send() failed, error %d", err);
  4032. /* TODO (mid): error handling depending on the error code.
  4033. * These codes are different between Windows and Linux.
  4034. * Currently there is no problem with failing send calls,
  4035. * if there is a reproducible situation, it should be
  4036. * investigated in detail.
  4037. */
  4038. return -1;
  4039. }
  4040. /* Only in case n=0 (timeout), repeat calling the write function */
  4041. if (timeout >= 0) {
  4042. now = mg_get_current_time_ns();
  4043. }
  4044. } while ((timeout <= 0) || ((start - now) <= timeout_ns));
  4045. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  4046. used */
  4047. return -1;
  4048. }
  4049. static int64_t
  4050. push_all(struct mg_context *ctx,
  4051. FILE *fp,
  4052. SOCKET sock,
  4053. SSL *ssl,
  4054. const char *buf,
  4055. int64_t len)
  4056. {
  4057. double timeout = -1.0;
  4058. int64_t n, nwritten = 0;
  4059. if (ctx == NULL) {
  4060. return -1;
  4061. }
  4062. if (ctx->config[REQUEST_TIMEOUT]) {
  4063. timeout = atoi(ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  4064. }
  4065. while (len > 0 && ctx->stop_flag == 0) {
  4066. n = push(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  4067. if (n < 0) {
  4068. if (nwritten == 0) {
  4069. nwritten = n; /* Propagate the error */
  4070. }
  4071. break;
  4072. } else if (n == 0) {
  4073. break; /* No more data to write */
  4074. } else {
  4075. nwritten += n;
  4076. len -= n;
  4077. }
  4078. }
  4079. return nwritten;
  4080. }
  4081. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  4082. * Return value:
  4083. * >=0 .. number of bytes successfully read
  4084. * -1 .. timeout
  4085. * -2 .. error
  4086. */
  4087. static int
  4088. pull_inner(FILE *fp,
  4089. struct mg_connection *conn,
  4090. char *buf,
  4091. int len,
  4092. double timeout)
  4093. {
  4094. int nread, err = 0;
  4095. #ifdef _WIN32
  4096. typedef int len_t;
  4097. #else
  4098. typedef size_t len_t;
  4099. #endif
  4100. /* We need an additional wait loop around this, because in some cases
  4101. * with TLSwe may get data from the socket but not from SSL_read.
  4102. * In this case we need to repeat at least once.
  4103. */
  4104. if (fp != NULL) {
  4105. #if !defined(_WIN32_WCE)
  4106. /* Use read() instead of fread(), because if we're reading from the
  4107. * CGI pipe, fread() may block until IO buffer is filled up. We
  4108. * cannot afford to block and must pass all read bytes immediately
  4109. * to the client. */
  4110. nread = (int)read(fileno(fp), buf, (size_t)len);
  4111. #else
  4112. /* WinCE does not support CGI pipes */
  4113. nread = (int)fread(buf, 1, (size_t)len, fp);
  4114. #endif
  4115. err = (nread < 0) ? ERRNO : 0;
  4116. #ifndef NO_SSL
  4117. } else if (conn->ssl != NULL) {
  4118. struct pollfd pfd[1];
  4119. int pollres;
  4120. pfd[0].fd = conn->client.sock;
  4121. pfd[0].events = POLLIN;
  4122. pollres =
  4123. mg_poll(pfd, 1, (int)(timeout * 1000.0), &(conn->ctx->stop_flag));
  4124. if (conn->ctx->stop_flag) {
  4125. return -2;
  4126. }
  4127. if (pollres > 0) {
  4128. nread = SSL_read(conn->ssl, buf, len);
  4129. if (nread <= 0) {
  4130. err = SSL_get_error(conn->ssl, nread);
  4131. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  4132. err = ERRNO;
  4133. } else if ((err == SSL_ERROR_WANT_READ)
  4134. || (err == SSL_ERROR_WANT_WRITE)) {
  4135. nread = 0;
  4136. } else {
  4137. DEBUG_TRACE("SSL_read() failed, error %d", err);
  4138. return -2;
  4139. }
  4140. } else {
  4141. err = 0;
  4142. }
  4143. } else if (pollres < 0) {
  4144. /* Error */
  4145. return -2;
  4146. } else {
  4147. /* pollres = 0 means timeout */
  4148. nread = 0;
  4149. }
  4150. #endif
  4151. } else {
  4152. struct pollfd pfd[1];
  4153. int pollres;
  4154. pfd[0].fd = conn->client.sock;
  4155. pfd[0].events = POLLIN;
  4156. pollres =
  4157. mg_poll(pfd, 1, (int)(timeout * 1000.0), &(conn->ctx->stop_flag));
  4158. if (conn->ctx->stop_flag) {
  4159. return -2;
  4160. }
  4161. if (pollres > 0) {
  4162. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  4163. err = (nread < 0) ? ERRNO : 0;
  4164. if (nread <= 0) {
  4165. /* shutdown of the socket at client side */
  4166. return -2;
  4167. }
  4168. } else if (pollres < 0) {
  4169. /* error callint poll */
  4170. return -2;
  4171. } else {
  4172. /* pollres = 0 means timeout */
  4173. nread = 0;
  4174. }
  4175. }
  4176. if (conn->ctx->stop_flag) {
  4177. return -2;
  4178. }
  4179. if ((nread > 0) || (nread == 0 && len == 0)) {
  4180. /* some data has been read, or no data was requested */
  4181. return nread;
  4182. }
  4183. if (nread < 0) {
  4184. /* socket error - check errno */
  4185. #ifdef _WIN32
  4186. if (err == WSAEWOULDBLOCK) {
  4187. /* TODO (low): check if this is still required */
  4188. /* standard case if called from close_socket_gracefully */
  4189. return -2;
  4190. } else if (err == WSAETIMEDOUT) {
  4191. /* TODO (low): check if this is still required */
  4192. /* timeout is handled by the while loop */
  4193. return 0;
  4194. } else if (err == WSAECONNABORTED) {
  4195. /* See https://www.chilkatsoft.com/p/p_299.asp */
  4196. return -2;
  4197. } else {
  4198. DEBUG_TRACE("recv() failed, error %d", err);
  4199. return -2;
  4200. }
  4201. #else
  4202. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  4203. * if the timeout is reached and if the socket was set to non-
  4204. * blocking in close_socket_gracefully, so we can not distinguish
  4205. * here. We have to wait for the timeout in both cases for now.
  4206. */
  4207. if (err == EAGAIN || err == EWOULDBLOCK || err == EINTR) {
  4208. /* TODO (low): check if this is still required */
  4209. /* EAGAIN/EWOULDBLOCK:
  4210. * standard case if called from close_socket_gracefully
  4211. * => should return -1 */
  4212. /* or timeout occured
  4213. * => the code must stay in the while loop */
  4214. /* EINTR can be generated on a socket with a timeout set even
  4215. * when SA_RESTART is effective for all relevant signals
  4216. * (see signal(7)).
  4217. * => stay in the while loop */
  4218. } else {
  4219. DEBUG_TRACE("recv() failed, error %d", err);
  4220. return -2;
  4221. }
  4222. #endif
  4223. }
  4224. /* Timeout occured, but no data available. */
  4225. return -1;
  4226. }
  4227. static int
  4228. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  4229. {
  4230. int n, nread = 0;
  4231. double timeout = -1.0;
  4232. uint64_t start_time, now, timeout_ns;
  4233. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  4234. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  4235. }
  4236. if (timeout >= 0.0) {
  4237. start_time = mg_get_current_time_ns();
  4238. timeout_ns = (uint64_t)(timeout * 1.0E9);
  4239. } else {
  4240. /* The variable is not used, but if it is left uninitialized,
  4241. * we get a spurious warning. */
  4242. start_time = 0;
  4243. }
  4244. while (len > 0 && conn->ctx->stop_flag == 0) {
  4245. n = pull_inner(fp, conn, buf + nread, len, timeout);
  4246. if (n == -2) {
  4247. if (nread == 0) {
  4248. nread = -1; /* Propagate the error */
  4249. }
  4250. break;
  4251. } else if (n == -1) {
  4252. /* timeout */
  4253. if (timeout >= 0.0) {
  4254. now = mg_get_current_time_ns();
  4255. if ((now - start_time) <= timeout_ns) {
  4256. continue;
  4257. }
  4258. }
  4259. break;
  4260. } else if (n == 0) {
  4261. break; /* No more data to read */
  4262. } else {
  4263. conn->consumed_content += n;
  4264. nread += n;
  4265. len -= n;
  4266. }
  4267. }
  4268. return nread;
  4269. }
  4270. static void
  4271. discard_unread_request_data(struct mg_connection *conn)
  4272. {
  4273. char buf[MG_BUF_LEN];
  4274. size_t to_read;
  4275. int nread;
  4276. if (conn == NULL) {
  4277. return;
  4278. }
  4279. to_read = sizeof(buf);
  4280. if (conn->is_chunked) {
  4281. /* Chunked encoding: 1=chunk not read completely, 2=chunk read
  4282. * completely */
  4283. while (conn->is_chunked == 1) {
  4284. nread = mg_read(conn, buf, to_read);
  4285. if (nread <= 0) {
  4286. break;
  4287. }
  4288. }
  4289. } else {
  4290. /* Not chunked: content length is known */
  4291. while (conn->consumed_content < conn->content_len) {
  4292. if (to_read
  4293. > (size_t)(conn->content_len - conn->consumed_content)) {
  4294. to_read = (size_t)(conn->content_len - conn->consumed_content);
  4295. }
  4296. nread = mg_read(conn, buf, to_read);
  4297. if (nread <= 0) {
  4298. break;
  4299. }
  4300. }
  4301. }
  4302. }
  4303. static int
  4304. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  4305. {
  4306. int64_t n, buffered_len, nread;
  4307. int64_t len64 =
  4308. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  4309. * int, we may not read more
  4310. * bytes */
  4311. const char *body;
  4312. if (conn == NULL) {
  4313. return 0;
  4314. }
  4315. /* If Content-Length is not set for a PUT or POST request, read until
  4316. * socket is closed */
  4317. if (conn->consumed_content == 0 && conn->content_len == -1) {
  4318. conn->content_len = INT64_MAX;
  4319. conn->must_close = 1;
  4320. }
  4321. nread = 0;
  4322. if (conn->consumed_content < conn->content_len) {
  4323. /* Adjust number of bytes to read. */
  4324. int64_t left_to_read = conn->content_len - conn->consumed_content;
  4325. if (left_to_read < len64) {
  4326. /* Do not read more than the total content length of the request.
  4327. */
  4328. len64 = left_to_read;
  4329. }
  4330. /* Return buffered data */
  4331. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  4332. - conn->consumed_content;
  4333. if (buffered_len > 0) {
  4334. if (len64 < buffered_len) {
  4335. buffered_len = len64;
  4336. }
  4337. body = conn->buf + conn->request_len + conn->consumed_content;
  4338. memcpy(buf, body, (size_t)buffered_len);
  4339. len64 -= buffered_len;
  4340. conn->consumed_content += buffered_len;
  4341. nread += buffered_len;
  4342. buf = (char *)buf + buffered_len;
  4343. }
  4344. /* We have returned all buffered data. Read new data from the remote
  4345. * socket.
  4346. */
  4347. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  4348. nread += n;
  4349. } else {
  4350. nread = ((nread > 0) ? nread : n);
  4351. }
  4352. }
  4353. return (int)nread;
  4354. }
  4355. static char
  4356. mg_getc(struct mg_connection *conn)
  4357. {
  4358. char c;
  4359. if (conn == NULL) {
  4360. return 0;
  4361. }
  4362. conn->content_len++;
  4363. if (mg_read_inner(conn, &c, 1) <= 0) {
  4364. return (char)0;
  4365. }
  4366. return c;
  4367. }
  4368. int
  4369. mg_read(struct mg_connection *conn, void *buf, size_t len)
  4370. {
  4371. if (len > INT_MAX) {
  4372. len = INT_MAX;
  4373. }
  4374. if (conn == NULL) {
  4375. return 0;
  4376. }
  4377. if (conn->is_chunked) {
  4378. size_t all_read = 0;
  4379. while (len > 0) {
  4380. if (conn->is_chunked == 2) {
  4381. /* No more data left to read */
  4382. return 0;
  4383. }
  4384. if (conn->chunk_remainder) {
  4385. /* copy from the remainder of the last received chunk */
  4386. long read_ret;
  4387. size_t read_now =
  4388. ((conn->chunk_remainder > len) ? (len)
  4389. : (conn->chunk_remainder));
  4390. conn->content_len += (int)read_now;
  4391. read_ret =
  4392. mg_read_inner(conn, (char *)buf + all_read, read_now);
  4393. if (read_ret < 1) {
  4394. /* read error */
  4395. return -1;
  4396. }
  4397. all_read += (size_t)read_ret;
  4398. conn->chunk_remainder -= (size_t)read_ret;
  4399. len -= (size_t)read_ret;
  4400. if (conn->chunk_remainder == 0) {
  4401. /* Add data bytes in the current chunk have been read,
  4402. * so we are expecting \r\n now. */
  4403. char x1 = mg_getc(conn);
  4404. char x2 = mg_getc(conn);
  4405. if ((x1 != '\r') || (x2 != '\n')) {
  4406. /* Protocol violation */
  4407. return -1;
  4408. }
  4409. }
  4410. } else {
  4411. /* fetch a new chunk */
  4412. int i = 0;
  4413. char lenbuf[64];
  4414. char *end = 0;
  4415. unsigned long chunkSize = 0;
  4416. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  4417. lenbuf[i] = mg_getc(conn);
  4418. if (i > 0 && lenbuf[i] == '\r' && lenbuf[i - 1] != '\r') {
  4419. continue;
  4420. }
  4421. if (i > 1 && lenbuf[i] == '\n' && lenbuf[i - 1] == '\r') {
  4422. lenbuf[i + 1] = 0;
  4423. chunkSize = strtoul(lenbuf, &end, 16);
  4424. if (chunkSize == 0) {
  4425. /* regular end of content */
  4426. conn->is_chunked = 2;
  4427. }
  4428. break;
  4429. }
  4430. if (!isxdigit(lenbuf[i])) {
  4431. /* illegal character for chunk length */
  4432. return -1;
  4433. }
  4434. }
  4435. if ((end == NULL) || (*end != '\r')) {
  4436. /* chunksize not set correctly */
  4437. return -1;
  4438. }
  4439. if (chunkSize == 0) {
  4440. break;
  4441. }
  4442. conn->chunk_remainder = chunkSize;
  4443. }
  4444. }
  4445. return (int)all_read;
  4446. }
  4447. return mg_read_inner(conn, buf, len);
  4448. }
  4449. int
  4450. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  4451. {
  4452. time_t now;
  4453. int64_t n, total, allowed;
  4454. if (conn == NULL) {
  4455. return 0;
  4456. }
  4457. if (conn->throttle > 0) {
  4458. if ((now = time(NULL)) != conn->last_throttle_time) {
  4459. conn->last_throttle_time = now;
  4460. conn->last_throttle_bytes = 0;
  4461. }
  4462. allowed = conn->throttle - conn->last_throttle_bytes;
  4463. if (allowed > (int64_t)len) {
  4464. allowed = (int64_t)len;
  4465. }
  4466. if ((total = push_all(conn->ctx,
  4467. NULL,
  4468. conn->client.sock,
  4469. conn->ssl,
  4470. (const char *)buf,
  4471. (int64_t)allowed)) == allowed) {
  4472. buf = (const char *)buf + total;
  4473. conn->last_throttle_bytes += total;
  4474. while (total < (int64_t)len && conn->ctx->stop_flag == 0) {
  4475. allowed = (conn->throttle > ((int64_t)len - total))
  4476. ? (int64_t)len - total
  4477. : conn->throttle;
  4478. if ((n = push_all(conn->ctx,
  4479. NULL,
  4480. conn->client.sock,
  4481. conn->ssl,
  4482. (const char *)buf,
  4483. (int64_t)allowed)) != allowed) {
  4484. break;
  4485. }
  4486. sleep(1);
  4487. conn->last_throttle_bytes = allowed;
  4488. conn->last_throttle_time = time(NULL);
  4489. buf = (const char *)buf + n;
  4490. total += n;
  4491. }
  4492. }
  4493. } else {
  4494. total = push_all(conn->ctx,
  4495. NULL,
  4496. conn->client.sock,
  4497. conn->ssl,
  4498. (const char *)buf,
  4499. (int64_t)len);
  4500. }
  4501. return (int)total;
  4502. }
  4503. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  4504. static int
  4505. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  4506. {
  4507. va_list ap_copy;
  4508. size_t size = MG_BUF_LEN / 4;
  4509. int len = -1;
  4510. *buf = NULL;
  4511. while (len < 0) {
  4512. if (*buf) {
  4513. mg_free(*buf);
  4514. }
  4515. size *= 4;
  4516. *buf = (char *)mg_malloc(size);
  4517. if (!*buf) {
  4518. break;
  4519. }
  4520. va_copy(ap_copy, ap);
  4521. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  4522. va_end(ap_copy);
  4523. (*buf)[size - 1] = 0;
  4524. }
  4525. return len;
  4526. }
  4527. /* Print message to buffer. If buffer is large enough to hold the message,
  4528. * return buffer. If buffer is to small, allocate large enough buffer on heap,
  4529. * and return allocated buffer. */
  4530. static int
  4531. alloc_vprintf(char **out_buf,
  4532. char *prealloc_buf,
  4533. size_t prealloc_size,
  4534. const char *fmt,
  4535. va_list ap)
  4536. {
  4537. va_list ap_copy;
  4538. int len;
  4539. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  4540. * buffer is too small. Also, older versions of msvcrt.dll do not have
  4541. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  4542. * Therefore, we make two passes: on first pass, get required message
  4543. * length.
  4544. * On second pass, actually print the message. */
  4545. va_copy(ap_copy, ap);
  4546. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  4547. va_end(ap_copy);
  4548. if (len < 0) {
  4549. /* C runtime is not standard compliant, vsnprintf() returned -1.
  4550. * Switch to alternative code path that uses incremental allocations.
  4551. */
  4552. va_copy(ap_copy, ap);
  4553. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  4554. va_end(ap_copy);
  4555. } else if ((size_t)(len) >= prealloc_size) {
  4556. /* The pre-allocated buffer not large enough. */
  4557. /* Allocate a new buffer. */
  4558. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  4559. if (!*out_buf) {
  4560. /* Allocation failed. Return -1 as "out of memory" error. */
  4561. return -1;
  4562. }
  4563. /* Buffer allocation successful. Store the string there. */
  4564. va_copy(ap_copy, ap);
  4565. IGNORE_UNUSED_RESULT(
  4566. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  4567. va_end(ap_copy);
  4568. } else {
  4569. /* The pre-allocated buffer is large enough.
  4570. * Use it to store the string and return the address. */
  4571. va_copy(ap_copy, ap);
  4572. IGNORE_UNUSED_RESULT(
  4573. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  4574. va_end(ap_copy);
  4575. *out_buf = prealloc_buf;
  4576. }
  4577. return len;
  4578. }
  4579. static int
  4580. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  4581. {
  4582. char mem[MG_BUF_LEN];
  4583. char *buf = NULL;
  4584. int len;
  4585. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  4586. len = mg_write(conn, buf, (size_t)len);
  4587. }
  4588. if (buf != mem && buf != NULL) {
  4589. mg_free(buf);
  4590. }
  4591. return len;
  4592. }
  4593. int
  4594. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  4595. {
  4596. va_list ap;
  4597. int result;
  4598. va_start(ap, fmt);
  4599. result = mg_vprintf(conn, fmt, ap);
  4600. va_end(ap);
  4601. return result;
  4602. }
  4603. int
  4604. mg_url_decode(const char *src,
  4605. int src_len,
  4606. char *dst,
  4607. int dst_len,
  4608. int is_form_url_encoded)
  4609. {
  4610. int i, j, a, b;
  4611. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  4612. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  4613. if (i < src_len - 2 && src[i] == '%'
  4614. && isxdigit(*(const unsigned char *)(src + i + 1))
  4615. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  4616. a = tolower(*(const unsigned char *)(src + i + 1));
  4617. b = tolower(*(const unsigned char *)(src + i + 2));
  4618. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  4619. i += 2;
  4620. } else if (is_form_url_encoded && src[i] == '+') {
  4621. dst[j] = ' ';
  4622. } else {
  4623. dst[j] = src[i];
  4624. }
  4625. }
  4626. dst[j] = '\0'; /* Null-terminate the destination */
  4627. return (i >= src_len) ? j : -1;
  4628. }
  4629. int
  4630. mg_get_var(const char *data,
  4631. size_t data_len,
  4632. const char *name,
  4633. char *dst,
  4634. size_t dst_len)
  4635. {
  4636. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  4637. }
  4638. int
  4639. mg_get_var2(const char *data,
  4640. size_t data_len,
  4641. const char *name,
  4642. char *dst,
  4643. size_t dst_len,
  4644. size_t occurrence)
  4645. {
  4646. const char *p, *e, *s;
  4647. size_t name_len;
  4648. int len;
  4649. if (dst == NULL || dst_len == 0) {
  4650. len = -2;
  4651. } else if (data == NULL || name == NULL || data_len == 0) {
  4652. len = -1;
  4653. dst[0] = '\0';
  4654. } else {
  4655. name_len = strlen(name);
  4656. e = data + data_len;
  4657. len = -1;
  4658. dst[0] = '\0';
  4659. /* data is "var1=val1&var2=val2...". Find variable first */
  4660. for (p = data; p + name_len < e; p++) {
  4661. if ((p == data || p[-1] == '&') && p[name_len] == '='
  4662. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  4663. /* Point p to variable value */
  4664. p += name_len + 1;
  4665. /* Point s to the end of the value */
  4666. s = (const char *)memchr(p, '&', (size_t)(e - p));
  4667. if (s == NULL) {
  4668. s = e;
  4669. }
  4670. /* assert(s >= p); */
  4671. if (s < p) {
  4672. return -3;
  4673. }
  4674. /* Decode variable into destination buffer */
  4675. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  4676. /* Redirect error code from -1 to -2 (destination buffer too
  4677. * small). */
  4678. if (len == -1) {
  4679. len = -2;
  4680. }
  4681. break;
  4682. }
  4683. }
  4684. }
  4685. return len;
  4686. }
  4687. /* HCP24: some changes to compare hole var_name */
  4688. int
  4689. mg_get_cookie(const char *cookie_header,
  4690. const char *var_name,
  4691. char *dst,
  4692. size_t dst_size)
  4693. {
  4694. const char *s, *p, *end;
  4695. int name_len, len = -1;
  4696. if (dst == NULL || dst_size == 0) {
  4697. return -2;
  4698. }
  4699. dst[0] = '\0';
  4700. if (var_name == NULL || (s = cookie_header) == NULL) {
  4701. return -1;
  4702. }
  4703. name_len = (int)strlen(var_name);
  4704. end = s + strlen(s);
  4705. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  4706. if (s[name_len] == '=') {
  4707. /* HCP24: now check is it a substring or a full cookie name */
  4708. if ((s == cookie_header) || (s[-1] == ' ')) {
  4709. s += name_len + 1;
  4710. if ((p = strchr(s, ' ')) == NULL) {
  4711. p = end;
  4712. }
  4713. if (p[-1] == ';') {
  4714. p--;
  4715. }
  4716. if (*s == '"' && p[-1] == '"' && p > s + 1) {
  4717. s++;
  4718. p--;
  4719. }
  4720. if ((size_t)(p - s) < dst_size) {
  4721. len = (int)(p - s);
  4722. mg_strlcpy(dst, s, (size_t)len + 1);
  4723. } else {
  4724. len = -3;
  4725. }
  4726. break;
  4727. }
  4728. }
  4729. }
  4730. return len;
  4731. }
  4732. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  4733. static void
  4734. base64_encode(const unsigned char *src, int src_len, char *dst)
  4735. {
  4736. static const char *b64 =
  4737. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  4738. int i, j, a, b, c;
  4739. for (i = j = 0; i < src_len; i += 3) {
  4740. a = src[i];
  4741. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  4742. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  4743. dst[j++] = b64[a >> 2];
  4744. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  4745. if (i + 1 < src_len) {
  4746. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  4747. }
  4748. if (i + 2 < src_len) {
  4749. dst[j++] = b64[c & 63];
  4750. }
  4751. }
  4752. while (j % 4 != 0) {
  4753. dst[j++] = '=';
  4754. }
  4755. dst[j++] = '\0';
  4756. }
  4757. #endif
  4758. #if defined(USE_LUA)
  4759. static unsigned char
  4760. b64reverse(char letter)
  4761. {
  4762. if (letter >= 'A' && letter <= 'Z') {
  4763. return letter - 'A';
  4764. }
  4765. if (letter >= 'a' && letter <= 'z') {
  4766. return letter - 'a' + 26;
  4767. }
  4768. if (letter >= '0' && letter <= '9') {
  4769. return letter - '0' + 52;
  4770. }
  4771. if (letter == '+') {
  4772. return 62;
  4773. }
  4774. if (letter == '/') {
  4775. return 63;
  4776. }
  4777. if (letter == '=') {
  4778. return 255; /* normal end */
  4779. }
  4780. return 254; /* error */
  4781. }
  4782. static int
  4783. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  4784. {
  4785. int i;
  4786. unsigned char a, b, c, d;
  4787. *dst_len = 0;
  4788. for (i = 0; i < src_len; i += 4) {
  4789. a = b64reverse(src[i]);
  4790. if (a >= 254) {
  4791. return i;
  4792. }
  4793. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  4794. if (b >= 254) {
  4795. return i + 1;
  4796. }
  4797. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  4798. if (c == 254) {
  4799. return i + 2;
  4800. }
  4801. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  4802. if (d == 254) {
  4803. return i + 3;
  4804. }
  4805. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  4806. if (c != 255) {
  4807. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  4808. if (d != 255) {
  4809. dst[(*dst_len)++] = (c << 6) + d;
  4810. }
  4811. }
  4812. }
  4813. return -1;
  4814. }
  4815. #endif
  4816. static int
  4817. is_put_or_delete_method(const struct mg_connection *conn)
  4818. {
  4819. if (conn) {
  4820. const char *s = conn->request_info.request_method;
  4821. return s != NULL && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  4822. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  4823. }
  4824. return 0;
  4825. }
  4826. static void
  4827. interpret_uri(struct mg_connection *conn, /* in: request (must be valid) */
  4828. char *filename, /* out: filename */
  4829. size_t filename_buf_len, /* in: size of filename buffer */
  4830. struct mg_file_stat *filestat, /* out: file structure */
  4831. int *is_found, /* out: file found (directly) */
  4832. int *is_script_resource, /* out: handled by a script? */
  4833. int *is_websocket_request, /* out: websocket connetion? */
  4834. int *is_put_or_delete_request /* out: put/delete a file? */
  4835. )
  4836. {
  4837. /* TODO (high / maintainability issue): Restructure this function */
  4838. #if !defined(NO_FILES)
  4839. const char *uri = conn->request_info.local_uri;
  4840. const char *root = conn->ctx->config[DOCUMENT_ROOT];
  4841. const char *rewrite;
  4842. struct vec a, b;
  4843. int match_len;
  4844. char gz_path[PATH_MAX];
  4845. char const *accept_encoding;
  4846. int truncated;
  4847. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  4848. char *p;
  4849. #endif
  4850. #else
  4851. (void)filename_buf_len; /* unused if NO_FILES is defined */
  4852. #endif
  4853. memset(filestat, 0, sizeof(*filestat));
  4854. *filename = 0;
  4855. *is_found = 0;
  4856. *is_script_resource = 0;
  4857. *is_put_or_delete_request = is_put_or_delete_method(conn);
  4858. #if defined(USE_WEBSOCKET)
  4859. *is_websocket_request = is_websocket_protocol(conn);
  4860. #if !defined(NO_FILES)
  4861. if (*is_websocket_request && conn->ctx->config[WEBSOCKET_ROOT]) {
  4862. root = conn->ctx->config[WEBSOCKET_ROOT];
  4863. }
  4864. #endif /* !NO_FILES */
  4865. #else /* USE_WEBSOCKET */
  4866. *is_websocket_request = 0;
  4867. #endif /* USE_WEBSOCKET */
  4868. #if !defined(NO_FILES)
  4869. /* Note that root == NULL is a regular use case here. This occurs,
  4870. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  4871. * config is not required. */
  4872. if (root == NULL) {
  4873. /* all file related outputs have already been set to 0, just return
  4874. */
  4875. return;
  4876. }
  4877. /* Using buf_len - 1 because memmove() for PATH_INFO may shift part
  4878. * of the path one byte on the right.
  4879. * If document_root is NULL, leave the file empty. */
  4880. mg_snprintf(
  4881. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  4882. if (truncated) {
  4883. goto interpret_cleanup;
  4884. }
  4885. rewrite = conn->ctx->config[REWRITE];
  4886. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  4887. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  4888. mg_snprintf(conn,
  4889. &truncated,
  4890. filename,
  4891. filename_buf_len - 1,
  4892. "%.*s%s",
  4893. (int)b.len,
  4894. b.ptr,
  4895. uri + match_len);
  4896. break;
  4897. }
  4898. }
  4899. if (truncated) {
  4900. goto interpret_cleanup;
  4901. }
  4902. /* Local file path and name, corresponding to requested URI
  4903. * is now stored in "filename" variable. */
  4904. if (mg_stat(conn, filename, filestat)) {
  4905. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  4906. /* File exists. Check if it is a script type. */
  4907. if (0
  4908. #if !defined(NO_CGI)
  4909. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  4910. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4911. filename) > 0
  4912. #endif
  4913. #if defined(USE_LUA)
  4914. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  4915. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  4916. filename) > 0
  4917. #endif
  4918. #if defined(USE_DUKTAPE)
  4919. || match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  4920. strlen(
  4921. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  4922. filename) > 0
  4923. #endif
  4924. ) {
  4925. /* The request addresses a CGI script or a Lua script. The URI
  4926. * corresponds to the script itself (like /path/script.cgi),
  4927. * and there is no additional resource path
  4928. * (like /path/script.cgi/something).
  4929. * Requests that modify (replace or delete) a resource, like
  4930. * PUT and DELETE requests, should replace/delete the script
  4931. * file.
  4932. * Requests that read or write from/to a resource, like GET and
  4933. * POST requests, should call the script and return the
  4934. * generated response. */
  4935. *is_script_resource = (!*is_put_or_delete_request);
  4936. }
  4937. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  4938. *is_found = 1;
  4939. return;
  4940. }
  4941. /* If we can't find the actual file, look for the file
  4942. * with the same name but a .gz extension. If we find it,
  4943. * use that and set the gzipped flag in the file struct
  4944. * to indicate that the response need to have the content-
  4945. * encoding: gzip header.
  4946. * We can only do this if the browser declares support. */
  4947. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  4948. if (strstr(accept_encoding, "gzip") != NULL) {
  4949. mg_snprintf(
  4950. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  4951. if (truncated) {
  4952. goto interpret_cleanup;
  4953. }
  4954. if (mg_stat(conn, gz_path, filestat)) {
  4955. if (filestat) {
  4956. filestat->is_gzipped = 1;
  4957. *is_found = 1;
  4958. }
  4959. /* Currently gz files can not be scripts. */
  4960. return;
  4961. }
  4962. }
  4963. }
  4964. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  4965. /* Support PATH_INFO for CGI scripts. */
  4966. for (p = filename + strlen(filename); p > filename + 1; p--) {
  4967. if (*p == '/') {
  4968. *p = '\0';
  4969. if ((0
  4970. #if !defined(NO_CGI)
  4971. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  4972. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4973. filename) > 0
  4974. #endif
  4975. #if defined(USE_LUA)
  4976. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  4977. strlen(
  4978. conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  4979. filename) > 0
  4980. #endif
  4981. #if defined(USE_DUKTAPE)
  4982. || match_prefix(
  4983. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  4984. strlen(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  4985. filename) > 0
  4986. #endif
  4987. ) && mg_stat(conn, filename, filestat)) {
  4988. /* Shift PATH_INFO block one character right, e.g.
  4989. * "/x.cgi/foo/bar\x00" => "/x.cgi\x00/foo/bar\x00"
  4990. * conn->path_info is pointing to the local variable "path"
  4991. * declared in handle_request(), so PATH_INFO is not valid
  4992. * after handle_request returns. */
  4993. conn->path_info = p + 1;
  4994. memmove(p + 2, p + 1, strlen(p + 1) + 1); /* +1 is for
  4995. * trailing \0 */
  4996. p[1] = '/';
  4997. *is_script_resource = 1;
  4998. break;
  4999. } else {
  5000. *p = '/';
  5001. }
  5002. }
  5003. }
  5004. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  5005. #endif /* !defined(NO_FILES) */
  5006. return;
  5007. #if !defined(NO_FILES)
  5008. /* Reset all outputs */
  5009. interpret_cleanup:
  5010. memset(filestat, 0, sizeof(*filestat));
  5011. *filename = 0;
  5012. *is_found = 0;
  5013. *is_script_resource = 0;
  5014. *is_websocket_request = 0;
  5015. *is_put_or_delete_request = 0;
  5016. #endif /* !defined(NO_FILES) */
  5017. }
  5018. /* Check whether full request is buffered. Return:
  5019. * -1 if request is malformed
  5020. * 0 if request is not yet fully buffered
  5021. * >0 actual request length, including last \r\n\r\n */
  5022. static int
  5023. get_request_len(const char *buf, int buflen)
  5024. {
  5025. const char *s, *e;
  5026. int len = 0;
  5027. for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
  5028. /* Control characters are not allowed but >=128 is. */
  5029. if (!isprint(*(const unsigned char *)s) && *s != '\r' && *s != '\n'
  5030. && *(const unsigned char *)s < 128) {
  5031. len = -1;
  5032. break; /* [i_a] abort scan as soon as one malformed character is
  5033. * found; */
  5034. /* don't let subsequent \r\n\r\n win us over anyhow */
  5035. } else if (s[0] == '\n' && s[1] == '\n') {
  5036. len = (int)(s - buf) + 2;
  5037. } else if (s[0] == '\n' && &s[1] < e && s[1] == '\r' && s[2] == '\n') {
  5038. len = (int)(s - buf) + 3;
  5039. }
  5040. return len;
  5041. }
  5042. #if !defined(NO_CACHING)
  5043. /* Convert month to the month number. Return -1 on error, or month number */
  5044. static int
  5045. get_month_index(const char *s)
  5046. {
  5047. size_t i;
  5048. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  5049. if (!strcmp(s, month_names[i])) {
  5050. return (int)i;
  5051. }
  5052. }
  5053. return -1;
  5054. }
  5055. /* Parse UTC date-time string, and return the corresponding time_t value. */
  5056. static time_t
  5057. parse_date_string(const char *datetime)
  5058. {
  5059. char month_str[32] = {0};
  5060. int second, minute, hour, day, month, year;
  5061. time_t result = (time_t)0;
  5062. struct tm tm;
  5063. if ((sscanf(datetime,
  5064. "%d/%3s/%d %d:%d:%d",
  5065. &day,
  5066. month_str,
  5067. &year,
  5068. &hour,
  5069. &minute,
  5070. &second) == 6) || (sscanf(datetime,
  5071. "%d %3s %d %d:%d:%d",
  5072. &day,
  5073. month_str,
  5074. &year,
  5075. &hour,
  5076. &minute,
  5077. &second) == 6)
  5078. || (sscanf(datetime,
  5079. "%*3s, %d %3s %d %d:%d:%d",
  5080. &day,
  5081. month_str,
  5082. &year,
  5083. &hour,
  5084. &minute,
  5085. &second) == 6) || (sscanf(datetime,
  5086. "%d-%3s-%d %d:%d:%d",
  5087. &day,
  5088. month_str,
  5089. &year,
  5090. &hour,
  5091. &minute,
  5092. &second) == 6)) {
  5093. month = get_month_index(month_str);
  5094. if ((month >= 0) && (year >= 1970)) {
  5095. memset(&tm, 0, sizeof(tm));
  5096. tm.tm_year = year - 1900;
  5097. tm.tm_mon = month;
  5098. tm.tm_mday = day;
  5099. tm.tm_hour = hour;
  5100. tm.tm_min = minute;
  5101. tm.tm_sec = second;
  5102. result = timegm(&tm);
  5103. }
  5104. }
  5105. return result;
  5106. }
  5107. #endif /* !NO_CACHING */
  5108. /* Protect against directory disclosure attack by removing '..',
  5109. * excessive '/' and '\' characters */
  5110. static void
  5111. remove_double_dots_and_double_slashes(char *s)
  5112. {
  5113. char *p = s;
  5114. while ((s[0] == '.') && (s[1] == '.')) {
  5115. s++;
  5116. }
  5117. while (*s != '\0') {
  5118. *p++ = *s++;
  5119. if (s[-1] == '/' || s[-1] == '\\') {
  5120. /* Skip all following slashes, backslashes and double-dots */
  5121. while (s[0] != '\0') {
  5122. if (s[0] == '/' || s[0] == '\\') {
  5123. s++;
  5124. } else if (s[0] == '.' && s[1] == '.') {
  5125. s += 2;
  5126. } else {
  5127. break;
  5128. }
  5129. }
  5130. }
  5131. }
  5132. *p = '\0';
  5133. }
  5134. static const struct {
  5135. const char *extension;
  5136. size_t ext_len;
  5137. const char *mime_type;
  5138. } builtin_mime_types[] = {
  5139. /* IANA registered MIME types (http://www.iana.org/assignments/media-types)
  5140. * application types */
  5141. {".doc", 4, "application/msword"},
  5142. {".eps", 4, "application/postscript"},
  5143. {".exe", 4, "application/octet-stream"},
  5144. {".js", 3, "application/javascript"},
  5145. {".json", 5, "application/json"},
  5146. {".pdf", 4, "application/pdf"},
  5147. {".ps", 3, "application/postscript"},
  5148. {".rtf", 4, "application/rtf"},
  5149. {".xhtml", 6, "application/xhtml+xml"},
  5150. {".xsl", 4, "application/xml"},
  5151. {".xslt", 5, "application/xml"},
  5152. /* fonts */
  5153. {".ttf", 4, "application/font-sfnt"},
  5154. {".cff", 4, "application/font-sfnt"},
  5155. {".otf", 4, "application/font-sfnt"},
  5156. {".aat", 4, "application/font-sfnt"},
  5157. {".sil", 4, "application/font-sfnt"},
  5158. {".pfr", 4, "application/font-tdpfr"},
  5159. {".woff", 5, "application/font-woff"},
  5160. /* audio */
  5161. {".mp3", 4, "audio/mpeg"},
  5162. {".oga", 4, "audio/ogg"},
  5163. {".ogg", 4, "audio/ogg"},
  5164. /* image */
  5165. {".gif", 4, "image/gif"},
  5166. {".ief", 4, "image/ief"},
  5167. {".jpeg", 5, "image/jpeg"},
  5168. {".jpg", 4, "image/jpeg"},
  5169. {".jpm", 4, "image/jpm"},
  5170. {".jpx", 4, "image/jpx"},
  5171. {".png", 4, "image/png"},
  5172. {".svg", 4, "image/svg+xml"},
  5173. {".tif", 4, "image/tiff"},
  5174. {".tiff", 5, "image/tiff"},
  5175. /* model */
  5176. {".wrl", 4, "model/vrml"},
  5177. /* text */
  5178. {".css", 4, "text/css"},
  5179. {".csv", 4, "text/csv"},
  5180. {".htm", 4, "text/html"},
  5181. {".html", 5, "text/html"},
  5182. {".sgm", 4, "text/sgml"},
  5183. {".shtm", 5, "text/html"},
  5184. {".shtml", 6, "text/html"},
  5185. {".txt", 4, "text/plain"},
  5186. {".xml", 4, "text/xml"},
  5187. /* video */
  5188. {".mov", 4, "video/quicktime"},
  5189. {".mp4", 4, "video/mp4"},
  5190. {".mpeg", 5, "video/mpeg"},
  5191. {".mpg", 4, "video/mpeg"},
  5192. {".ogv", 4, "video/ogg"},
  5193. {".qt", 3, "video/quicktime"},
  5194. /* not registered types
  5195. * (http://reference.sitepoint.com/html/mime-types-full,
  5196. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  5197. {".arj", 4, "application/x-arj-compressed"},
  5198. {".gz", 3, "application/x-gunzip"},
  5199. {".rar", 4, "application/x-arj-compressed"},
  5200. {".swf", 4, "application/x-shockwave-flash"},
  5201. {".tar", 4, "application/x-tar"},
  5202. {".tgz", 4, "application/x-tar-gz"},
  5203. {".torrent", 8, "application/x-bittorrent"},
  5204. {".ppt", 4, "application/x-mspowerpoint"},
  5205. {".xls", 4, "application/x-msexcel"},
  5206. {".zip", 4, "application/x-zip-compressed"},
  5207. {".aac",
  5208. 4,
  5209. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  5210. {".aif", 4, "audio/x-aif"},
  5211. {".m3u", 4, "audio/x-mpegurl"},
  5212. {".mid", 4, "audio/x-midi"},
  5213. {".ra", 3, "audio/x-pn-realaudio"},
  5214. {".ram", 4, "audio/x-pn-realaudio"},
  5215. {".wav", 4, "audio/x-wav"},
  5216. {".bmp", 4, "image/bmp"},
  5217. {".ico", 4, "image/x-icon"},
  5218. {".pct", 4, "image/x-pct"},
  5219. {".pict", 5, "image/pict"},
  5220. {".rgb", 4, "image/x-rgb"},
  5221. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  5222. {".asf", 4, "video/x-ms-asf"},
  5223. {".avi", 4, "video/x-msvideo"},
  5224. {".m4v", 4, "video/x-m4v"},
  5225. {NULL, 0, NULL}};
  5226. const char *
  5227. mg_get_builtin_mime_type(const char *path)
  5228. {
  5229. const char *ext;
  5230. size_t i, path_len;
  5231. path_len = strlen(path);
  5232. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  5233. ext = path + (path_len - builtin_mime_types[i].ext_len);
  5234. if (path_len > builtin_mime_types[i].ext_len
  5235. && mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {
  5236. return builtin_mime_types[i].mime_type;
  5237. }
  5238. }
  5239. return "text/plain";
  5240. }
  5241. /* Look at the "path" extension and figure what mime type it has.
  5242. * Store mime type in the vector. */
  5243. static void
  5244. get_mime_type(struct mg_context *ctx, const char *path, struct vec *vec)
  5245. {
  5246. struct vec ext_vec, mime_vec;
  5247. const char *list, *ext;
  5248. size_t path_len;
  5249. path_len = strlen(path);
  5250. if (ctx == NULL || vec == NULL) {
  5251. return;
  5252. }
  5253. /* Scan user-defined mime types first, in case user wants to
  5254. * override default mime types. */
  5255. list = ctx->config[EXTRA_MIME_TYPES];
  5256. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  5257. /* ext now points to the path suffix */
  5258. ext = path + path_len - ext_vec.len;
  5259. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  5260. *vec = mime_vec;
  5261. return;
  5262. }
  5263. }
  5264. vec->ptr = mg_get_builtin_mime_type(path);
  5265. vec->len = strlen(vec->ptr);
  5266. }
  5267. /* Stringify binary data. Output buffer must be twice as big as input,
  5268. * because each byte takes 2 bytes in string representation */
  5269. static void
  5270. bin2str(char *to, const unsigned char *p, size_t len)
  5271. {
  5272. static const char *hex = "0123456789abcdef";
  5273. for (; len--; p++) {
  5274. *to++ = hex[p[0] >> 4];
  5275. *to++ = hex[p[0] & 0x0f];
  5276. }
  5277. *to = '\0';
  5278. }
  5279. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes. */
  5280. char *
  5281. mg_md5(char buf[33], ...)
  5282. {
  5283. md5_byte_t hash[16];
  5284. const char *p;
  5285. va_list ap;
  5286. md5_state_t ctx;
  5287. md5_init(&ctx);
  5288. va_start(ap, buf);
  5289. while ((p = va_arg(ap, const char *)) != NULL) {
  5290. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  5291. }
  5292. va_end(ap);
  5293. md5_finish(&ctx, hash);
  5294. bin2str(buf, hash, sizeof(hash));
  5295. return buf;
  5296. }
  5297. /* Check the user's password, return 1 if OK */
  5298. static int
  5299. check_password(const char *method,
  5300. const char *ha1,
  5301. const char *uri,
  5302. const char *nonce,
  5303. const char *nc,
  5304. const char *cnonce,
  5305. const char *qop,
  5306. const char *response)
  5307. {
  5308. char ha2[32 + 1], expected_response[32 + 1];
  5309. /* Some of the parameters may be NULL */
  5310. if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL
  5311. || qop == NULL
  5312. || response == NULL) {
  5313. return 0;
  5314. }
  5315. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  5316. if (strlen(response) != 32) {
  5317. return 0;
  5318. }
  5319. mg_md5(ha2, method, ":", uri, NULL);
  5320. mg_md5(expected_response,
  5321. ha1,
  5322. ":",
  5323. nonce,
  5324. ":",
  5325. nc,
  5326. ":",
  5327. cnonce,
  5328. ":",
  5329. qop,
  5330. ":",
  5331. ha2,
  5332. NULL);
  5333. return mg_strcasecmp(response, expected_response) == 0;
  5334. }
  5335. /* Use the global passwords file, if specified by auth_gpass option,
  5336. * or search for .htpasswd in the requested directory. */
  5337. static void
  5338. open_auth_file(struct mg_connection *conn,
  5339. const char *path,
  5340. struct mg_file *filep)
  5341. {
  5342. if (conn != NULL && conn->ctx != NULL) {
  5343. char name[PATH_MAX];
  5344. const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
  5345. int truncated;
  5346. if (gpass != NULL) {
  5347. /* Use global passwords file */
  5348. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  5349. #ifdef DEBUG
  5350. /* Use mg_cry here, since gpass has been configured. */
  5351. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  5352. #endif
  5353. }
  5354. /* Important: using local struct mg_file to test path for
  5355. * is_directory flag. If filep is used, mg_stat() makes it
  5356. * appear as if auth file was opened.
  5357. * TODO(mid): Check if this is still required after rewriting
  5358. * mg_stat */
  5359. } else if (mg_stat(conn, path, &filep->stat)
  5360. && filep->stat.is_directory) {
  5361. mg_snprintf(conn,
  5362. &truncated,
  5363. name,
  5364. sizeof(name),
  5365. "%s/%s",
  5366. path,
  5367. PASSWORDS_FILE_NAME);
  5368. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  5369. #ifdef DEBUG
  5370. /* Don't use mg_cry here, but only a trace, since this is
  5371. * a typical case. It will occur for every directory
  5372. * without a password file. */
  5373. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  5374. #endif
  5375. }
  5376. } else {
  5377. /* Try to find .htpasswd in requested directory. */
  5378. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  5379. if (e[0] == '/') {
  5380. break;
  5381. }
  5382. }
  5383. mg_snprintf(conn,
  5384. &truncated,
  5385. name,
  5386. sizeof(name),
  5387. "%.*s/%s",
  5388. (int)(e - p),
  5389. p,
  5390. PASSWORDS_FILE_NAME);
  5391. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  5392. #ifdef DEBUG
  5393. /* Don't use mg_cry here, but only a trace, since this is
  5394. * a typical case. It will occur for every directory
  5395. * without a password file. */
  5396. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  5397. #endif
  5398. }
  5399. }
  5400. }
  5401. }
  5402. /* Parsed Authorization header */
  5403. struct ah {
  5404. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  5405. };
  5406. /* Return 1 on success. Always initializes the ah structure. */
  5407. static int
  5408. parse_auth_header(struct mg_connection *conn,
  5409. char *buf,
  5410. size_t buf_size,
  5411. struct ah *ah)
  5412. {
  5413. char *name, *value, *s;
  5414. const char *auth_header;
  5415. uint64_t nonce;
  5416. if (!ah || !conn) {
  5417. return 0;
  5418. }
  5419. (void)memset(ah, 0, sizeof(*ah));
  5420. if ((auth_header = mg_get_header(conn, "Authorization")) == NULL
  5421. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  5422. return 0;
  5423. }
  5424. /* Make modifiable copy of the auth header */
  5425. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  5426. s = buf;
  5427. /* Parse authorization header */
  5428. for (;;) {
  5429. /* Gobble initial spaces */
  5430. while (isspace(*(unsigned char *)s)) {
  5431. s++;
  5432. }
  5433. name = skip_quoted(&s, "=", " ", 0);
  5434. /* Value is either quote-delimited, or ends at first comma or space. */
  5435. if (s[0] == '\"') {
  5436. s++;
  5437. value = skip_quoted(&s, "\"", " ", '\\');
  5438. if (s[0] == ',') {
  5439. s++;
  5440. }
  5441. } else {
  5442. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  5443. * spaces */
  5444. }
  5445. if (*name == '\0') {
  5446. break;
  5447. }
  5448. if (!strcmp(name, "username")) {
  5449. ah->user = value;
  5450. } else if (!strcmp(name, "cnonce")) {
  5451. ah->cnonce = value;
  5452. } else if (!strcmp(name, "response")) {
  5453. ah->response = value;
  5454. } else if (!strcmp(name, "uri")) {
  5455. ah->uri = value;
  5456. } else if (!strcmp(name, "qop")) {
  5457. ah->qop = value;
  5458. } else if (!strcmp(name, "nc")) {
  5459. ah->nc = value;
  5460. } else if (!strcmp(name, "nonce")) {
  5461. ah->nonce = value;
  5462. }
  5463. }
  5464. #ifndef NO_NONCE_CHECK
  5465. /* Read the nonce from the response. */
  5466. if (ah->nonce == NULL) {
  5467. return 0;
  5468. }
  5469. s = NULL;
  5470. nonce = strtoull(ah->nonce, &s, 10);
  5471. if ((s == NULL) || (*s != 0)) {
  5472. return 0;
  5473. }
  5474. /* Convert the nonce from the client to a number. */
  5475. nonce ^= conn->ctx->auth_nonce_mask;
  5476. /* The converted number corresponds to the time the nounce has been
  5477. * created. This should not be earlier than the server start. */
  5478. /* Server side nonce check is valuable in all situations but one:
  5479. * if the server restarts frequently, but the client should not see
  5480. * that, so the server should accept nonces from previous starts. */
  5481. /* However, the reasonable default is to not accept a nonce from a
  5482. * previous start, so if anyone changed the access rights between
  5483. * two restarts, a new login is required. */
  5484. if (nonce < (uint64_t)conn->ctx->start_time) {
  5485. /* nonce is from a previous start of the server and no longer valid
  5486. * (replay attack?) */
  5487. return 0;
  5488. }
  5489. /* Check if the nonce is too high, so it has not (yet) been used by the
  5490. * server. */
  5491. if (nonce >= ((uint64_t)conn->ctx->start_time + conn->ctx->nonce_count)) {
  5492. return 0;
  5493. }
  5494. #else
  5495. (void)nonce;
  5496. #endif
  5497. /* CGI needs it as REMOTE_USER */
  5498. if (ah->user != NULL) {
  5499. conn->request_info.remote_user = mg_strdup(ah->user);
  5500. } else {
  5501. return 0;
  5502. }
  5503. return 1;
  5504. }
  5505. static const char *
  5506. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  5507. {
  5508. const char *eof;
  5509. size_t len;
  5510. const char *memend;
  5511. if (!filep) {
  5512. return NULL;
  5513. }
  5514. if (filep->access.membuf != NULL && *p != NULL) {
  5515. memend = (const char *)&filep->access.membuf[filep->stat.size];
  5516. /* Search for \n from p till the end of stream */
  5517. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  5518. if (eof != NULL) {
  5519. eof += 1; /* Include \n */
  5520. } else {
  5521. eof = memend; /* Copy remaining data */
  5522. }
  5523. len =
  5524. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  5525. memcpy(buf, *p, len);
  5526. buf[len] = '\0';
  5527. *p += len;
  5528. return len ? eof : NULL;
  5529. } else if (filep->access.fp != NULL) {
  5530. return fgets(buf, (int)size, filep->access.fp);
  5531. } else {
  5532. return NULL;
  5533. }
  5534. }
  5535. /* Define the initial recursion depth for procesesing htpasswd files that
  5536. * include other htpasswd
  5537. * (or even the same) files. It is not difficult to provide a file or files
  5538. * s.t. they force civetweb
  5539. * to infinitely recurse and then crash.
  5540. */
  5541. #define INITIAL_DEPTH 9
  5542. #if INITIAL_DEPTH <= 0
  5543. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  5544. #endif
  5545. struct read_auth_file_struct {
  5546. struct mg_connection *conn;
  5547. struct ah ah;
  5548. char *domain;
  5549. char buf[256 + 256 + 40];
  5550. char *f_user;
  5551. char *f_domain;
  5552. char *f_ha1;
  5553. };
  5554. static int
  5555. read_auth_file(struct mg_file *filep,
  5556. struct read_auth_file_struct *workdata,
  5557. int depth)
  5558. {
  5559. char *p;
  5560. int is_authorized = 0;
  5561. struct mg_file fp;
  5562. size_t l;
  5563. if (!filep || !workdata || 0 == depth) {
  5564. return 0;
  5565. }
  5566. /* Loop over passwords file */
  5567. p = (char *)filep->access.membuf;
  5568. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  5569. l = strlen(workdata->buf);
  5570. while (l > 0) {
  5571. if (isspace(workdata->buf[l - 1])
  5572. || iscntrl(workdata->buf[l - 1])) {
  5573. l--;
  5574. workdata->buf[l] = 0;
  5575. } else
  5576. break;
  5577. }
  5578. if (l < 1) {
  5579. continue;
  5580. }
  5581. workdata->f_user = workdata->buf;
  5582. if (workdata->f_user[0] == ':') {
  5583. /* user names may not contain a ':' and may not be empty,
  5584. * so lines starting with ':' may be used for a special purpose */
  5585. if (workdata->f_user[1] == '#') {
  5586. /* :# is a comment */
  5587. continue;
  5588. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  5589. if (mg_fopen(workdata->conn,
  5590. workdata->f_user + 9,
  5591. MG_FOPEN_MODE_READ,
  5592. &fp)) {
  5593. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  5594. (void)mg_fclose(
  5595. &fp.access); /* ignore error on read only file */
  5596. /* No need to continue processing files once we have a
  5597. * match, since nothing will reset it back
  5598. * to 0.
  5599. */
  5600. if (is_authorized) {
  5601. return is_authorized;
  5602. }
  5603. } else {
  5604. mg_cry(workdata->conn,
  5605. "%s: cannot open authorization file: %s",
  5606. __func__,
  5607. workdata->buf);
  5608. }
  5609. continue;
  5610. }
  5611. /* everything is invalid for the moment (might change in the
  5612. * future) */
  5613. mg_cry(workdata->conn,
  5614. "%s: syntax error in authorization file: %s",
  5615. __func__,
  5616. workdata->buf);
  5617. continue;
  5618. }
  5619. workdata->f_domain = strchr(workdata->f_user, ':');
  5620. if (workdata->f_domain == NULL) {
  5621. mg_cry(workdata->conn,
  5622. "%s: syntax error in authorization file: %s",
  5623. __func__,
  5624. workdata->buf);
  5625. continue;
  5626. }
  5627. *(workdata->f_domain) = 0;
  5628. (workdata->f_domain)++;
  5629. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  5630. if (workdata->f_ha1 == NULL) {
  5631. mg_cry(workdata->conn,
  5632. "%s: syntax error in authorization file: %s",
  5633. __func__,
  5634. workdata->buf);
  5635. continue;
  5636. }
  5637. *(workdata->f_ha1) = 0;
  5638. (workdata->f_ha1)++;
  5639. if (!strcmp(workdata->ah.user, workdata->f_user)
  5640. && !strcmp(workdata->domain, workdata->f_domain)) {
  5641. return check_password(workdata->conn->request_info.request_method,
  5642. workdata->f_ha1,
  5643. workdata->ah.uri,
  5644. workdata->ah.nonce,
  5645. workdata->ah.nc,
  5646. workdata->ah.cnonce,
  5647. workdata->ah.qop,
  5648. workdata->ah.response);
  5649. }
  5650. }
  5651. return is_authorized;
  5652. }
  5653. /* Authorize against the opened passwords file. Return 1 if authorized. */
  5654. static int
  5655. authorize(struct mg_connection *conn, struct mg_file *filep)
  5656. {
  5657. struct read_auth_file_struct workdata;
  5658. char buf[MG_BUF_LEN];
  5659. if (!conn || !conn->ctx) {
  5660. return 0;
  5661. }
  5662. memset(&workdata, 0, sizeof(workdata));
  5663. workdata.conn = conn;
  5664. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  5665. return 0;
  5666. }
  5667. workdata.domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  5668. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  5669. }
  5670. /* Return 1 if request is authorised, 0 otherwise. */
  5671. static int
  5672. check_authorization(struct mg_connection *conn, const char *path)
  5673. {
  5674. char fname[PATH_MAX];
  5675. struct vec uri_vec, filename_vec;
  5676. const char *list;
  5677. struct mg_file file = STRUCT_FILE_INITIALIZER;
  5678. int authorized = 1, truncated;
  5679. if (!conn || !conn->ctx) {
  5680. return 0;
  5681. }
  5682. list = conn->ctx->config[PROTECT_URI];
  5683. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  5684. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  5685. mg_snprintf(conn,
  5686. &truncated,
  5687. fname,
  5688. sizeof(fname),
  5689. "%.*s",
  5690. (int)filename_vec.len,
  5691. filename_vec.ptr);
  5692. if (truncated
  5693. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  5694. mg_cry(conn,
  5695. "%s: cannot open %s: %s",
  5696. __func__,
  5697. fname,
  5698. strerror(errno));
  5699. }
  5700. break;
  5701. }
  5702. }
  5703. if (!is_file_opened(&file.access)) {
  5704. open_auth_file(conn, path, &file);
  5705. }
  5706. if (is_file_opened(&file.access)) {
  5707. authorized = authorize(conn, &file);
  5708. (void)mg_fclose(&file.access); /* ignore error on read only file */
  5709. }
  5710. return authorized;
  5711. }
  5712. static void
  5713. send_authorization_request(struct mg_connection *conn)
  5714. {
  5715. char date[64];
  5716. time_t curtime = time(NULL);
  5717. if (conn && conn->ctx) {
  5718. uint64_t nonce = (uint64_t)(conn->ctx->start_time);
  5719. (void)pthread_mutex_lock(&conn->ctx->nonce_mutex);
  5720. nonce += conn->ctx->nonce_count;
  5721. ++conn->ctx->nonce_count;
  5722. (void)pthread_mutex_unlock(&conn->ctx->nonce_mutex);
  5723. nonce ^= conn->ctx->auth_nonce_mask;
  5724. conn->status_code = 401;
  5725. conn->must_close = 1;
  5726. gmt_time_string(date, sizeof(date), &curtime);
  5727. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  5728. send_no_cache_header(conn);
  5729. send_additional_header(conn);
  5730. mg_printf(conn,
  5731. "Date: %s\r\n"
  5732. "Connection: %s\r\n"
  5733. "Content-Length: 0\r\n"
  5734. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  5735. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  5736. date,
  5737. suggest_connection_header(conn),
  5738. conn->ctx->config[AUTHENTICATION_DOMAIN],
  5739. nonce);
  5740. }
  5741. }
  5742. #if !defined(NO_FILES)
  5743. static int
  5744. is_authorized_for_put(struct mg_connection *conn)
  5745. {
  5746. if (conn) {
  5747. struct mg_file file = STRUCT_FILE_INITIALIZER;
  5748. const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
  5749. int ret = 0;
  5750. if (passfile != NULL
  5751. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  5752. ret = authorize(conn, &file);
  5753. (void)mg_fclose(&file.access); /* ignore error on read only file */
  5754. }
  5755. return ret;
  5756. }
  5757. return 0;
  5758. }
  5759. #endif
  5760. int
  5761. mg_modify_passwords_file(const char *fname,
  5762. const char *domain,
  5763. const char *user,
  5764. const char *pass)
  5765. {
  5766. int found, i;
  5767. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  5768. FILE *fp, *fp2;
  5769. found = 0;
  5770. fp = fp2 = NULL;
  5771. /* Regard empty password as no password - remove user record. */
  5772. if (pass != NULL && pass[0] == '\0') {
  5773. pass = NULL;
  5774. }
  5775. /* Other arguments must not be empty */
  5776. if (fname == NULL || domain == NULL || user == NULL) {
  5777. return 0;
  5778. }
  5779. /* Using the given file format, user name and domain must not contain ':'
  5780. */
  5781. if (strchr(user, ':') != NULL) {
  5782. return 0;
  5783. }
  5784. if (strchr(domain, ':') != NULL) {
  5785. return 0;
  5786. }
  5787. /* Do not allow control characters like newline in user name and domain.
  5788. * Do not allow excessively long names either. */
  5789. for (i = 0; i < 255 && user[i] != 0; i++) {
  5790. if (iscntrl(user[i])) {
  5791. return 0;
  5792. }
  5793. }
  5794. if (user[i]) {
  5795. return 0;
  5796. }
  5797. for (i = 0; i < 255 && domain[i] != 0; i++) {
  5798. if (iscntrl(domain[i])) {
  5799. return 0;
  5800. }
  5801. }
  5802. if (domain[i]) {
  5803. return 0;
  5804. }
  5805. /* The maximum length of the path to the password file is limited */
  5806. if ((strlen(fname) + 4) >= PATH_MAX) {
  5807. return 0;
  5808. }
  5809. /* Create a temporary file name. Length has been checked before. */
  5810. strcpy(tmp, fname);
  5811. strcat(tmp, ".tmp");
  5812. /* Create the file if does not exist */
  5813. /* Use of fopen here is OK, since fname is only ASCII */
  5814. if ((fp = fopen(fname, "a+")) != NULL) {
  5815. (void)fclose(fp);
  5816. }
  5817. /* Open the given file and temporary file */
  5818. if ((fp = fopen(fname, "r")) == NULL) {
  5819. return 0;
  5820. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  5821. fclose(fp);
  5822. return 0;
  5823. }
  5824. /* Copy the stuff to temporary file */
  5825. while (fgets(line, sizeof(line), fp) != NULL) {
  5826. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  5827. continue;
  5828. }
  5829. u[255] = 0;
  5830. d[255] = 0;
  5831. if (!strcmp(u, user) && !strcmp(d, domain)) {
  5832. found++;
  5833. if (pass != NULL) {
  5834. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  5835. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  5836. }
  5837. } else {
  5838. fprintf(fp2, "%s", line);
  5839. }
  5840. }
  5841. /* If new user, just add it */
  5842. if (!found && pass != NULL) {
  5843. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  5844. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  5845. }
  5846. /* Close files */
  5847. fclose(fp);
  5848. fclose(fp2);
  5849. /* Put the temp file in place of real file */
  5850. IGNORE_UNUSED_RESULT(remove(fname));
  5851. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  5852. return 1;
  5853. }
  5854. static int
  5855. is_valid_port(unsigned long port)
  5856. {
  5857. return (port <= 0xffff);
  5858. }
  5859. static int
  5860. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  5861. {
  5862. struct addrinfo hints, *res, *ressave;
  5863. int func_ret = 0;
  5864. int gai_ret;
  5865. memset(&hints, 0, sizeof(struct addrinfo));
  5866. hints.ai_family = af;
  5867. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  5868. if (gai_ret != 0) {
  5869. /* gai_strerror could be used to convert gai_ret to a string */
  5870. /* POSIX return values: see
  5871. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  5872. */
  5873. /* Windows return values: see
  5874. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  5875. */
  5876. return 0;
  5877. }
  5878. ressave = res;
  5879. while (res) {
  5880. if (dstlen >= res->ai_addrlen) {
  5881. memcpy(dst, res->ai_addr, res->ai_addrlen);
  5882. func_ret = 1;
  5883. }
  5884. res = res->ai_next;
  5885. }
  5886. freeaddrinfo(ressave);
  5887. return func_ret;
  5888. }
  5889. static int
  5890. connect_socket(struct mg_context *ctx /* may be NULL */,
  5891. const char *host,
  5892. int port,
  5893. int use_ssl,
  5894. char *ebuf,
  5895. size_t ebuf_len,
  5896. SOCKET *sock /* output: socket, must not be NULL */,
  5897. union usa *sa /* output: socket address, must not be NULL */
  5898. )
  5899. {
  5900. int ip_ver = 0;
  5901. *sock = INVALID_SOCKET;
  5902. memset(sa, 0, sizeof(*sa));
  5903. if (ebuf_len > 0) {
  5904. *ebuf = 0;
  5905. }
  5906. if (host == NULL) {
  5907. mg_snprintf(NULL,
  5908. NULL, /* No truncation check for ebuf */
  5909. ebuf,
  5910. ebuf_len,
  5911. "%s",
  5912. "NULL host");
  5913. return 0;
  5914. }
  5915. if (port <= 0 || !is_valid_port((unsigned)port)) {
  5916. mg_snprintf(NULL,
  5917. NULL, /* No truncation check for ebuf */
  5918. ebuf,
  5919. ebuf_len,
  5920. "%s",
  5921. "invalid port");
  5922. return 0;
  5923. }
  5924. #if !defined(NO_SSL)
  5925. #if !defined(NO_SSL_DL)
  5926. #ifdef OPENSSL_API_1_1
  5927. if (use_ssl && (TLS_client_method == NULL)) {
  5928. mg_snprintf(NULL,
  5929. NULL, /* No truncation check for ebuf */
  5930. ebuf,
  5931. ebuf_len,
  5932. "%s",
  5933. "SSL is not initialized");
  5934. return 0;
  5935. }
  5936. #else
  5937. if (use_ssl && (SSLv23_client_method == NULL)) {
  5938. mg_snprintf(NULL,
  5939. NULL, /* No truncation check for ebuf */
  5940. ebuf,
  5941. ebuf_len,
  5942. "%s",
  5943. "SSL is not initialized");
  5944. return 0;
  5945. }
  5946. #endif /* OPENSSL_API_1_1 */
  5947. #else
  5948. (void)use_ssl;
  5949. #endif /* NO_SSL_DL */
  5950. #else
  5951. (void)use_ssl;
  5952. #endif /* !defined(NO_SSL) */
  5953. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  5954. sa->sin.sin_port = htons((uint16_t)port);
  5955. ip_ver = 4;
  5956. #ifdef USE_IPV6
  5957. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  5958. sa->sin6.sin6_port = htons((uint16_t)port);
  5959. ip_ver = 6;
  5960. } else if (host[0] == '[') {
  5961. /* While getaddrinfo on Windows will work with [::1],
  5962. * getaddrinfo on Linux only works with ::1 (without []). */
  5963. size_t l = strlen(host + 1);
  5964. char *h = (l > 1) ? mg_strdup(host + 1) : NULL;
  5965. if (h) {
  5966. h[l - 1] = 0;
  5967. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  5968. sa->sin6.sin6_port = htons((uint16_t)port);
  5969. ip_ver = 6;
  5970. }
  5971. mg_free(h);
  5972. }
  5973. #endif
  5974. }
  5975. if (ip_ver == 0) {
  5976. mg_snprintf(NULL,
  5977. NULL, /* No truncation check for ebuf */
  5978. ebuf,
  5979. ebuf_len,
  5980. "%s",
  5981. "host not found");
  5982. return 0;
  5983. }
  5984. if (ip_ver == 4) {
  5985. *sock = socket(PF_INET, SOCK_STREAM, 0);
  5986. }
  5987. #ifdef USE_IPV6
  5988. else if (ip_ver == 6) {
  5989. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  5990. }
  5991. #endif
  5992. if (*sock == INVALID_SOCKET) {
  5993. mg_snprintf(NULL,
  5994. NULL, /* No truncation check for ebuf */
  5995. ebuf,
  5996. ebuf_len,
  5997. "socket(): %s",
  5998. strerror(ERRNO));
  5999. return 0;
  6000. }
  6001. set_close_on_exec(*sock, fc(ctx));
  6002. if ((ip_ver == 4)
  6003. && (connect(*sock, (struct sockaddr *)&sa->sin, sizeof(sa->sin))
  6004. == 0)) {
  6005. /* connected with IPv4 */
  6006. set_blocking_mode(*sock, 0);
  6007. return 1;
  6008. }
  6009. #ifdef USE_IPV6
  6010. if ((ip_ver == 6)
  6011. && (connect(*sock, (struct sockaddr *)&sa->sin6, sizeof(sa->sin6))
  6012. == 0)) {
  6013. /* connected with IPv6 */
  6014. set_blocking_mode(*sock, 0);
  6015. return 1;
  6016. }
  6017. #endif
  6018. /* Not connected */
  6019. mg_snprintf(NULL,
  6020. NULL, /* No truncation check for ebuf */
  6021. ebuf,
  6022. ebuf_len,
  6023. "connect(%s:%d): %s",
  6024. host,
  6025. port,
  6026. strerror(ERRNO));
  6027. closesocket(*sock);
  6028. *sock = INVALID_SOCKET;
  6029. return 0;
  6030. }
  6031. int
  6032. mg_url_encode(const char *src, char *dst, size_t dst_len)
  6033. {
  6034. static const char *dont_escape = "._-$,;~()";
  6035. static const char *hex = "0123456789abcdef";
  6036. char *pos = dst;
  6037. const char *end = dst + dst_len - 1;
  6038. for (; *src != '\0' && pos < end; src++, pos++) {
  6039. if (isalnum(*(const unsigned char *)src)
  6040. || strchr(dont_escape, *(const unsigned char *)src) != NULL) {
  6041. *pos = *src;
  6042. } else if (pos + 2 < end) {
  6043. pos[0] = '%';
  6044. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  6045. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  6046. pos += 2;
  6047. } else {
  6048. break;
  6049. }
  6050. }
  6051. *pos = '\0';
  6052. return (*src == '\0') ? (int)(pos - dst) : -1;
  6053. }
  6054. static void
  6055. print_dir_entry(struct de *de)
  6056. {
  6057. char size[64], mod[64], href[PATH_MAX * 3 /* worst case */];
  6058. struct tm *tm;
  6059. if (de->file.is_directory) {
  6060. mg_snprintf(de->conn,
  6061. NULL, /* Buffer is big enough */
  6062. size,
  6063. sizeof(size),
  6064. "%s",
  6065. "[DIRECTORY]");
  6066. } else {
  6067. /* We use (signed) cast below because MSVC 6 compiler cannot
  6068. * convert unsigned __int64 to double. Sigh. */
  6069. if (de->file.size < 1024) {
  6070. mg_snprintf(de->conn,
  6071. NULL, /* Buffer is big enough */
  6072. size,
  6073. sizeof(size),
  6074. "%d",
  6075. (int)de->file.size);
  6076. } else if (de->file.size < 0x100000) {
  6077. mg_snprintf(de->conn,
  6078. NULL, /* Buffer is big enough */
  6079. size,
  6080. sizeof(size),
  6081. "%.1fk",
  6082. (double)de->file.size / 1024.0);
  6083. } else if (de->file.size < 0x40000000) {
  6084. mg_snprintf(de->conn,
  6085. NULL, /* Buffer is big enough */
  6086. size,
  6087. sizeof(size),
  6088. "%.1fM",
  6089. (double)de->file.size / 1048576);
  6090. } else {
  6091. mg_snprintf(de->conn,
  6092. NULL, /* Buffer is big enough */
  6093. size,
  6094. sizeof(size),
  6095. "%.1fG",
  6096. (double)de->file.size / 1073741824);
  6097. }
  6098. }
  6099. /* Note: mg_snprintf will not cause a buffer overflow above.
  6100. * So, string truncation checks are not required here. */
  6101. tm = localtime(&de->file.last_modified);
  6102. if (tm != NULL) {
  6103. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  6104. } else {
  6105. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  6106. mod[sizeof(mod) - 1] = '\0';
  6107. }
  6108. mg_url_encode(de->file_name, href, sizeof(href));
  6109. de->conn->num_bytes_sent +=
  6110. mg_printf(de->conn,
  6111. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  6112. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  6113. de->conn->request_info.local_uri,
  6114. href,
  6115. de->file.is_directory ? "/" : "",
  6116. de->file_name,
  6117. de->file.is_directory ? "/" : "",
  6118. mod,
  6119. size);
  6120. }
  6121. /* This function is called from send_directory() and used for
  6122. * sorting directory entries by size, or name, or modification time.
  6123. * On windows, __cdecl specification is needed in case if project is built
  6124. * with __stdcall convention. qsort always requires __cdels callback. */
  6125. static int WINCDECL
  6126. compare_dir_entries(const void *p1, const void *p2)
  6127. {
  6128. if (p1 && p2) {
  6129. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  6130. const char *query_string = a->conn->request_info.query_string;
  6131. int cmp_result = 0;
  6132. if (query_string == NULL) {
  6133. query_string = "na";
  6134. }
  6135. if (a->file.is_directory && !b->file.is_directory) {
  6136. return -1; /* Always put directories on top */
  6137. } else if (!a->file.is_directory && b->file.is_directory) {
  6138. return 1; /* Always put directories on top */
  6139. } else if (*query_string == 'n') {
  6140. cmp_result = strcmp(a->file_name, b->file_name);
  6141. } else if (*query_string == 's') {
  6142. cmp_result = (a->file.size == b->file.size)
  6143. ? 0
  6144. : ((a->file.size > b->file.size) ? 1 : -1);
  6145. } else if (*query_string == 'd') {
  6146. cmp_result =
  6147. (a->file.last_modified == b->file.last_modified)
  6148. ? 0
  6149. : ((a->file.last_modified > b->file.last_modified) ? 1
  6150. : -1);
  6151. }
  6152. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  6153. }
  6154. return 0;
  6155. }
  6156. static int
  6157. must_hide_file(struct mg_connection *conn, const char *path)
  6158. {
  6159. if (conn && conn->ctx) {
  6160. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  6161. const char *pattern = conn->ctx->config[HIDE_FILES];
  6162. return match_prefix(pw_pattern, strlen(pw_pattern), path) > 0
  6163. || (pattern != NULL
  6164. && match_prefix(pattern, strlen(pattern), path) > 0);
  6165. }
  6166. return 0;
  6167. }
  6168. static int
  6169. scan_directory(struct mg_connection *conn,
  6170. const char *dir,
  6171. void *data,
  6172. void (*cb)(struct de *, void *))
  6173. {
  6174. char path[PATH_MAX];
  6175. struct dirent *dp;
  6176. DIR *dirp;
  6177. struct de de;
  6178. int truncated;
  6179. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  6180. return 0;
  6181. } else {
  6182. de.conn = conn;
  6183. while ((dp = mg_readdir(dirp)) != NULL) {
  6184. /* Do not show current dir and hidden files */
  6185. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  6186. || must_hide_file(conn, dp->d_name)) {
  6187. continue;
  6188. }
  6189. mg_snprintf(
  6190. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  6191. /* If we don't memset stat structure to zero, mtime will have
  6192. * garbage and strftime() will segfault later on in
  6193. * print_dir_entry(). memset is required only if mg_stat()
  6194. * fails. For more details, see
  6195. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  6196. memset(&de.file, 0, sizeof(de.file));
  6197. if (truncated) {
  6198. /* If the path is not complete, skip processing. */
  6199. continue;
  6200. }
  6201. if (!mg_stat(conn, path, &de.file)) {
  6202. mg_cry(conn,
  6203. "%s: mg_stat(%s) failed: %s",
  6204. __func__,
  6205. path,
  6206. strerror(ERRNO));
  6207. }
  6208. de.file_name = dp->d_name;
  6209. cb(&de, data);
  6210. }
  6211. (void)mg_closedir(dirp);
  6212. }
  6213. return 1;
  6214. }
  6215. #if !defined(NO_FILES)
  6216. static int
  6217. remove_directory(struct mg_connection *conn, const char *dir)
  6218. {
  6219. char path[PATH_MAX];
  6220. struct dirent *dp;
  6221. DIR *dirp;
  6222. struct de de;
  6223. int truncated;
  6224. int ok = 1;
  6225. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  6226. return 0;
  6227. } else {
  6228. de.conn = conn;
  6229. while ((dp = mg_readdir(dirp)) != NULL) {
  6230. /* Do not show current dir (but show hidden files as they will
  6231. * also be removed) */
  6232. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  6233. continue;
  6234. }
  6235. mg_snprintf(
  6236. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  6237. /* If we don't memset stat structure to zero, mtime will have
  6238. * garbage and strftime() will segfault later on in
  6239. * print_dir_entry(). memset is required only if mg_stat()
  6240. * fails. For more details, see
  6241. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  6242. memset(&de.file, 0, sizeof(de.file));
  6243. if (truncated) {
  6244. /* Do not delete anything shorter */
  6245. ok = 0;
  6246. continue;
  6247. }
  6248. if (!mg_stat(conn, path, &de.file)) {
  6249. mg_cry(conn,
  6250. "%s: mg_stat(%s) failed: %s",
  6251. __func__,
  6252. path,
  6253. strerror(ERRNO));
  6254. ok = 0;
  6255. }
  6256. if (de.file.is_directory) {
  6257. if (remove_directory(conn, path) == 0) {
  6258. ok = 0;
  6259. }
  6260. } else {
  6261. /* This will fail file is the file is in memory */
  6262. if (mg_remove(conn, path) == 0) {
  6263. ok = 0;
  6264. }
  6265. }
  6266. }
  6267. (void)mg_closedir(dirp);
  6268. IGNORE_UNUSED_RESULT(rmdir(dir));
  6269. }
  6270. return ok;
  6271. }
  6272. #endif
  6273. struct dir_scan_data {
  6274. struct de *entries;
  6275. unsigned int num_entries;
  6276. unsigned int arr_size;
  6277. };
  6278. /* Behaves like realloc(), but frees original pointer on failure */
  6279. static void *
  6280. realloc2(void *ptr, size_t size)
  6281. {
  6282. void *new_ptr = mg_realloc(ptr, size);
  6283. if (new_ptr == NULL) {
  6284. mg_free(ptr);
  6285. }
  6286. return new_ptr;
  6287. }
  6288. static void
  6289. dir_scan_callback(struct de *de, void *data)
  6290. {
  6291. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  6292. if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {
  6293. dsd->arr_size *= 2;
  6294. dsd->entries =
  6295. (struct de *)realloc2(dsd->entries,
  6296. dsd->arr_size * sizeof(dsd->entries[0]));
  6297. }
  6298. if (dsd->entries == NULL) {
  6299. /* TODO(lsm, low): propagate an error to the caller */
  6300. dsd->num_entries = 0;
  6301. } else {
  6302. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  6303. dsd->entries[dsd->num_entries].file = de->file;
  6304. dsd->entries[dsd->num_entries].conn = de->conn;
  6305. dsd->num_entries++;
  6306. }
  6307. }
  6308. static void
  6309. handle_directory_request(struct mg_connection *conn, const char *dir)
  6310. {
  6311. unsigned int i;
  6312. int sort_direction;
  6313. struct dir_scan_data data = {NULL, 0, 128};
  6314. char date[64];
  6315. time_t curtime = time(NULL);
  6316. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  6317. send_http_error(conn,
  6318. 500,
  6319. "Error: Cannot open directory\nopendir(%s): %s",
  6320. dir,
  6321. strerror(ERRNO));
  6322. return;
  6323. }
  6324. gmt_time_string(date, sizeof(date), &curtime);
  6325. if (!conn) {
  6326. return;
  6327. }
  6328. sort_direction = ((conn->request_info.query_string != NULL)
  6329. && (conn->request_info.query_string[1] == 'd'))
  6330. ? 'a'
  6331. : 'd';
  6332. conn->must_close = 1;
  6333. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  6334. send_static_cache_header(conn);
  6335. send_additional_header(conn);
  6336. mg_printf(conn,
  6337. "Date: %s\r\n"
  6338. "Connection: close\r\n"
  6339. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  6340. date);
  6341. conn->num_bytes_sent +=
  6342. mg_printf(conn,
  6343. "<html><head><title>Index of %s</title>"
  6344. "<style>th {text-align: left;}</style></head>"
  6345. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  6346. "<tr><th><a href=\"?n%c\">Name</a></th>"
  6347. "<th><a href=\"?d%c\">Modified</a></th>"
  6348. "<th><a href=\"?s%c\">Size</a></th></tr>"
  6349. "<tr><td colspan=\"3\"><hr></td></tr>",
  6350. conn->request_info.local_uri,
  6351. conn->request_info.local_uri,
  6352. sort_direction,
  6353. sort_direction,
  6354. sort_direction);
  6355. /* Print first entry - link to a parent directory */
  6356. conn->num_bytes_sent +=
  6357. mg_printf(conn,
  6358. "<tr><td><a href=\"%s%s\">%s</a></td>"
  6359. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  6360. conn->request_info.local_uri,
  6361. "..",
  6362. "Parent directory",
  6363. "-",
  6364. "-");
  6365. /* Sort and print directory entries */
  6366. if (data.entries != NULL) {
  6367. qsort(data.entries,
  6368. (size_t)data.num_entries,
  6369. sizeof(data.entries[0]),
  6370. compare_dir_entries);
  6371. for (i = 0; i < data.num_entries; i++) {
  6372. print_dir_entry(&data.entries[i]);
  6373. mg_free(data.entries[i].file_name);
  6374. }
  6375. mg_free(data.entries);
  6376. }
  6377. conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");
  6378. conn->status_code = 200;
  6379. }
  6380. /* Send len bytes from the opened file to the client. */
  6381. static void
  6382. send_file_data(struct mg_connection *conn,
  6383. struct mg_file *filep,
  6384. int64_t offset,
  6385. int64_t len)
  6386. {
  6387. char buf[MG_BUF_LEN];
  6388. int to_read, num_read, num_written;
  6389. int64_t size;
  6390. if (!filep || !conn) {
  6391. return;
  6392. }
  6393. /* Sanity check the offset */
  6394. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  6395. : (int64_t)(filep->stat.size);
  6396. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  6397. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  6398. /* file stored in memory */
  6399. if (len > size - offset) {
  6400. len = size - offset;
  6401. }
  6402. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  6403. } else if (len > 0 && filep->access.fp != NULL) {
  6404. /* file stored on disk */
  6405. #if defined(__linux__)
  6406. /* sendfile is only available for Linux */
  6407. if ((conn->ssl == 0) && (conn->throttle == 0)
  6408. && (!mg_strcasecmp(conn->ctx->config[ALLOW_SENDFILE_CALL],
  6409. "yes"))) {
  6410. off_t sf_offs = (off_t)offset;
  6411. ssize_t sf_sent;
  6412. int sf_file = fileno(filep->access.fp);
  6413. int loop_cnt = 0;
  6414. do {
  6415. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  6416. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  6417. size_t sf_tosend =
  6418. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  6419. sf_sent =
  6420. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  6421. if (sf_sent > 0) {
  6422. conn->num_bytes_sent += sf_sent;
  6423. len -= sf_sent;
  6424. offset += sf_sent;
  6425. } else if (loop_cnt == 0) {
  6426. /* This file can not be sent using sendfile.
  6427. * This might be the case for pseudo-files in the
  6428. * /sys/ and /proc/ file system.
  6429. * Use the regular user mode copy code instead. */
  6430. break;
  6431. } else if (sf_sent == 0) {
  6432. /* No error, but 0 bytes sent. May be EOF? */
  6433. return;
  6434. }
  6435. loop_cnt++;
  6436. } while ((len > 0) && (sf_sent >= 0));
  6437. if (sf_sent > 0) {
  6438. return; /* OK */
  6439. }
  6440. /* sf_sent<0 means error, thus fall back to the classic way */
  6441. /* This is always the case, if sf_file is not a "normal" file,
  6442. * e.g., for sending data from the output of a CGI process. */
  6443. offset = (int64_t)sf_offs;
  6444. }
  6445. #endif
  6446. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  6447. mg_cry(conn, "%s: fseeko() failed: %s", __func__, strerror(ERRNO));
  6448. send_http_error(
  6449. conn,
  6450. 500,
  6451. "%s",
  6452. "Error: Unable to access file at requested position.");
  6453. } else {
  6454. while (len > 0) {
  6455. /* Calculate how much to read from the file in the buffer */
  6456. to_read = sizeof(buf);
  6457. if ((int64_t)to_read > len) {
  6458. to_read = (int)len;
  6459. }
  6460. /* Read from file, exit the loop on error */
  6461. if ((num_read =
  6462. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  6463. <= 0) {
  6464. break;
  6465. }
  6466. /* Send read bytes to the client, exit the loop on error */
  6467. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  6468. != num_read) {
  6469. break;
  6470. }
  6471. /* Both read and were successful, adjust counters */
  6472. conn->num_bytes_sent += num_written;
  6473. len -= num_written;
  6474. }
  6475. }
  6476. }
  6477. }
  6478. static int
  6479. parse_range_header(const char *header, int64_t *a, int64_t *b)
  6480. {
  6481. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  6482. }
  6483. static void
  6484. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  6485. {
  6486. if (filestat != NULL && buf != NULL) {
  6487. mg_snprintf(NULL,
  6488. NULL, /* All calls to construct_etag use 64 byte buffer */
  6489. buf,
  6490. buf_len,
  6491. "\"%lx.%" INT64_FMT "\"",
  6492. (unsigned long)filestat->last_modified,
  6493. filestat->size);
  6494. }
  6495. }
  6496. static void
  6497. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  6498. {
  6499. if (filep != NULL && filep->fp != NULL) {
  6500. #ifdef _WIN32
  6501. (void)conn; /* Unused. */
  6502. #else
  6503. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  6504. mg_cry(conn,
  6505. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  6506. __func__,
  6507. strerror(ERRNO));
  6508. }
  6509. #endif
  6510. }
  6511. }
  6512. static void
  6513. handle_static_file_request(struct mg_connection *conn,
  6514. const char *path,
  6515. struct mg_file *filep,
  6516. const char *mime_type,
  6517. const char *additional_headers)
  6518. {
  6519. char date[64], lm[64], etag[64];
  6520. char range[128]; /* large enough, so there will be no overflow */
  6521. const char *msg = "OK", *hdr;
  6522. time_t curtime = time(NULL);
  6523. int64_t cl, r1, r2;
  6524. struct vec mime_vec;
  6525. int n, truncated;
  6526. char gz_path[PATH_MAX];
  6527. const char *encoding = "";
  6528. const char *cors1, *cors2, *cors3;
  6529. if (conn == NULL || conn->ctx == NULL || filep == NULL) {
  6530. return;
  6531. }
  6532. if (mime_type == NULL) {
  6533. get_mime_type(conn->ctx, path, &mime_vec);
  6534. } else {
  6535. mime_vec.ptr = mime_type;
  6536. mime_vec.len = strlen(mime_type);
  6537. }
  6538. if (filep->stat.size > INT64_MAX) {
  6539. send_http_error(conn,
  6540. 500,
  6541. "Error: File size is too large to send\n%" INT64_FMT,
  6542. filep->stat.size);
  6543. }
  6544. cl = (int64_t)filep->stat.size;
  6545. conn->status_code = 200;
  6546. range[0] = '\0';
  6547. /* if this file is in fact a pre-gzipped file, rewrite its filename
  6548. * it's important to rewrite the filename after resolving
  6549. * the mime type from it, to preserve the actual file's type */
  6550. if (filep->stat.is_gzipped) {
  6551. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  6552. if (truncated) {
  6553. send_http_error(conn,
  6554. 500,
  6555. "Error: Path of zipped file too long (%s)",
  6556. path);
  6557. return;
  6558. }
  6559. path = gz_path;
  6560. encoding = "Content-Encoding: gzip\r\n";
  6561. }
  6562. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  6563. send_http_error(conn,
  6564. 500,
  6565. "Error: Cannot open file\nfopen(%s): %s",
  6566. path,
  6567. strerror(ERRNO));
  6568. return;
  6569. }
  6570. fclose_on_exec(&filep->access, conn);
  6571. /* If Range: header specified, act accordingly */
  6572. r1 = r2 = 0;
  6573. hdr = mg_get_header(conn, "Range");
  6574. if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 && r1 >= 0
  6575. && r2 >= 0) {
  6576. /* actually, range requests don't play well with a pre-gzipped
  6577. * file (since the range is specified in the uncompressed space) */
  6578. if (filep->stat.is_gzipped) {
  6579. send_http_error(
  6580. conn,
  6581. 501,
  6582. "%s",
  6583. "Error: Range requests in gzipped files are not supported");
  6584. (void)mg_fclose(
  6585. &filep->access); /* ignore error on read only file */
  6586. return;
  6587. }
  6588. conn->status_code = 206;
  6589. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  6590. mg_snprintf(conn,
  6591. NULL, /* range buffer is big enough */
  6592. range,
  6593. sizeof(range),
  6594. "Content-Range: bytes "
  6595. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  6596. r1,
  6597. r1 + cl - 1,
  6598. filep->stat.size);
  6599. msg = "Partial Content";
  6600. }
  6601. hdr = mg_get_header(conn, "Origin");
  6602. if (hdr) {
  6603. /* Cross-origin resource sharing (CORS), see
  6604. * http://www.html5rocks.com/en/tutorials/cors/,
  6605. * http://www.html5rocks.com/static/images/cors_server_flowchart.png -
  6606. * preflight is not supported for files. */
  6607. cors1 = "Access-Control-Allow-Origin: ";
  6608. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  6609. cors3 = "\r\n";
  6610. } else {
  6611. cors1 = cors2 = cors3 = "";
  6612. }
  6613. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
  6614. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  6615. gmt_time_string(date, sizeof(date), &curtime);
  6616. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  6617. construct_etag(etag, sizeof(etag), &filep->stat);
  6618. (void)mg_printf(conn,
  6619. "HTTP/1.1 %d %s\r\n"
  6620. "%s%s%s"
  6621. "Date: %s\r\n",
  6622. conn->status_code,
  6623. msg,
  6624. cors1,
  6625. cors2,
  6626. cors3,
  6627. date);
  6628. send_static_cache_header(conn);
  6629. send_additional_header(conn);
  6630. (void)mg_printf(conn,
  6631. "Last-Modified: %s\r\n"
  6632. "Etag: %s\r\n"
  6633. "Content-Type: %.*s\r\n"
  6634. "Content-Length: %" INT64_FMT "\r\n"
  6635. "Connection: %s\r\n"
  6636. "Accept-Ranges: bytes\r\n"
  6637. "%s%s",
  6638. lm,
  6639. etag,
  6640. (int)mime_vec.len,
  6641. mime_vec.ptr,
  6642. cl,
  6643. suggest_connection_header(conn),
  6644. range,
  6645. encoding);
  6646. /* The previous code must not add any header starting with X- to make
  6647. * sure no one of the additional_headers is included twice */
  6648. if (additional_headers != NULL) {
  6649. (void)mg_printf(conn,
  6650. "%.*s\r\n\r\n",
  6651. (int)strlen(additional_headers),
  6652. additional_headers);
  6653. } else {
  6654. (void)mg_printf(conn, "\r\n");
  6655. }
  6656. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  6657. send_file_data(conn, filep, r1, cl);
  6658. }
  6659. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  6660. }
  6661. #if !defined(NO_CACHING)
  6662. static void
  6663. handle_not_modified_static_file_request(struct mg_connection *conn,
  6664. struct mg_file *filep)
  6665. {
  6666. char date[64], lm[64], etag[64];
  6667. time_t curtime = time(NULL);
  6668. if (conn == NULL || filep == NULL) {
  6669. return;
  6670. }
  6671. conn->status_code = 304;
  6672. gmt_time_string(date, sizeof(date), &curtime);
  6673. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  6674. construct_etag(etag, sizeof(etag), &filep->stat);
  6675. (void)mg_printf(conn,
  6676. "HTTP/1.1 %d %s\r\n"
  6677. "Date: %s\r\n",
  6678. conn->status_code,
  6679. mg_get_response_code_text(conn, conn->status_code),
  6680. date);
  6681. send_static_cache_header(conn);
  6682. send_additional_header(conn);
  6683. (void)mg_printf(conn,
  6684. "Last-Modified: %s\r\n"
  6685. "Etag: %s\r\n"
  6686. "Connection: %s\r\n"
  6687. "\r\n",
  6688. lm,
  6689. etag,
  6690. suggest_connection_header(conn));
  6691. }
  6692. #endif
  6693. void
  6694. mg_send_file(struct mg_connection *conn, const char *path)
  6695. {
  6696. mg_send_mime_file(conn, path, NULL);
  6697. }
  6698. void
  6699. mg_send_mime_file(struct mg_connection *conn,
  6700. const char *path,
  6701. const char *mime_type)
  6702. {
  6703. mg_send_mime_file2(conn, path, mime_type, NULL);
  6704. }
  6705. void
  6706. mg_send_mime_file2(struct mg_connection *conn,
  6707. const char *path,
  6708. const char *mime_type,
  6709. const char *additional_headers)
  6710. {
  6711. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6712. if (mg_stat(conn, path, &file.stat)) {
  6713. if (file.stat.is_directory) {
  6714. if (!conn) {
  6715. return;
  6716. }
  6717. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  6718. "yes")) {
  6719. handle_directory_request(conn, path);
  6720. } else {
  6721. send_http_error(conn,
  6722. 403,
  6723. "%s",
  6724. "Error: Directory listing denied");
  6725. }
  6726. } else {
  6727. handle_static_file_request(
  6728. conn, path, &file, mime_type, additional_headers);
  6729. }
  6730. } else {
  6731. send_http_error(conn, 404, "%s", "Error: File not found");
  6732. }
  6733. }
  6734. /* For a given PUT path, create all intermediate subdirectories.
  6735. * Return 0 if the path itself is a directory.
  6736. * Return 1 if the path leads to a file.
  6737. * Return -1 for if the path is too long.
  6738. * Return -2 if path can not be created.
  6739. */
  6740. static int
  6741. put_dir(struct mg_connection *conn, const char *path)
  6742. {
  6743. char buf[PATH_MAX];
  6744. const char *s, *p;
  6745. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6746. size_t len;
  6747. int res = 1;
  6748. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  6749. len = (size_t)(p - path);
  6750. if (len >= sizeof(buf)) {
  6751. /* path too long */
  6752. res = -1;
  6753. break;
  6754. }
  6755. memcpy(buf, path, len);
  6756. buf[len] = '\0';
  6757. /* Try to create intermediate directory */
  6758. DEBUG_TRACE("mkdir(%s)", buf);
  6759. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  6760. /* path does not exixt and can not be created */
  6761. res = -2;
  6762. break;
  6763. }
  6764. /* Is path itself a directory? */
  6765. if (p[1] == '\0') {
  6766. res = 0;
  6767. }
  6768. }
  6769. return res;
  6770. }
  6771. static void
  6772. remove_bad_file(const struct mg_connection *conn, const char *path)
  6773. {
  6774. int r = mg_remove(conn, path);
  6775. if (r != 0) {
  6776. mg_cry(conn, "%s: Cannot remove invalid file %s", __func__, path);
  6777. }
  6778. }
  6779. long long
  6780. mg_store_body(struct mg_connection *conn, const char *path)
  6781. {
  6782. char buf[MG_BUF_LEN];
  6783. long long len = 0;
  6784. int ret, n;
  6785. struct mg_file fi;
  6786. if (conn->consumed_content != 0) {
  6787. mg_cry(conn, "%s: Contents already consumed", __func__);
  6788. return -11;
  6789. }
  6790. ret = put_dir(conn, path);
  6791. if (ret < 0) {
  6792. /* -1 for path too long,
  6793. * -2 for path can not be created. */
  6794. return ret;
  6795. }
  6796. if (ret != 1) {
  6797. /* Return 0 means, path itself is a directory. */
  6798. return 0;
  6799. }
  6800. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  6801. return -12;
  6802. }
  6803. ret = mg_read(conn, buf, sizeof(buf));
  6804. while (ret > 0) {
  6805. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  6806. if (n != ret) {
  6807. (void)mg_fclose(
  6808. &fi.access); /* File is bad and will be removed anyway. */
  6809. remove_bad_file(conn, path);
  6810. return -13;
  6811. }
  6812. ret = mg_read(conn, buf, sizeof(buf));
  6813. }
  6814. /* File is open for writing. If fclose fails, there was probably an
  6815. * error flushing the buffer to disk, so the file on disk might be
  6816. * broken. Delete it and return an error to the caller. */
  6817. if (mg_fclose(&fi.access) != 0) {
  6818. remove_bad_file(conn, path);
  6819. return -14;
  6820. }
  6821. return len;
  6822. }
  6823. /* Parse HTTP headers from the given buffer, advance buf pointer
  6824. * to the point where parsing stopped.
  6825. * All parameters must be valid pointers (not NULL).
  6826. * Return <0 on error. */
  6827. static int
  6828. parse_http_headers(char **buf, struct mg_request_info *ri)
  6829. {
  6830. int i;
  6831. ri->num_headers = 0;
  6832. for (i = 0; i < (int)ARRAY_SIZE(ri->http_headers); i++) {
  6833. char *dp = *buf;
  6834. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  6835. dp++;
  6836. }
  6837. if (dp == *buf) {
  6838. /* End of headers reached. */
  6839. break;
  6840. }
  6841. if (*dp != ':') {
  6842. /* This is not a valid field. */
  6843. return -1;
  6844. }
  6845. /* End of header key (*dp == ':') */
  6846. /* Truncate here and set the key name */
  6847. *dp = 0;
  6848. ri->http_headers[i].name = *buf;
  6849. do {
  6850. dp++;
  6851. } while (*dp == ' ');
  6852. /* The rest of the line is the value */
  6853. ri->http_headers[i].value = dp;
  6854. *buf = dp + strcspn(dp, "\r\n");
  6855. if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) {
  6856. *buf = NULL;
  6857. }
  6858. ri->num_headers = i + 1;
  6859. if (*buf) {
  6860. (*buf)[0] = 0;
  6861. (*buf)[1] = 0;
  6862. *buf += 2;
  6863. } else {
  6864. *buf = dp;
  6865. break;
  6866. }
  6867. if ((*buf)[0] == '\r') {
  6868. /* This is the end of the header */
  6869. break;
  6870. }
  6871. }
  6872. return ri->num_headers;
  6873. }
  6874. static int
  6875. is_valid_http_method(const char *method)
  6876. {
  6877. return !strcmp(method, "GET") /* HTTP (RFC 2616) */
  6878. || !strcmp(method, "POST") /* HTTP (RFC 2616) */
  6879. || !strcmp(method, "HEAD") /* HTTP (RFC 2616) */
  6880. || !strcmp(method, "PUT") /* HTTP (RFC 2616) */
  6881. || !strcmp(method, "DELETE") /* HTTP (RFC 2616) */
  6882. || !strcmp(method, "OPTIONS") /* HTTP (RFC 2616) */
  6883. /* TRACE method (RFC 2616) is not supported for security reasons */
  6884. || !strcmp(method, "CONNECT") /* HTTP (RFC 2616) */
  6885. || !strcmp(method, "PROPFIND") /* WEBDAV (RFC 2518) */
  6886. || !strcmp(method, "MKCOL") /* WEBDAV (RFC 2518) */
  6887. /* Unsupported WEBDAV Methods: */
  6888. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  6889. /* + 11 methods from RFC 3253 */
  6890. /* ORDERPATCH (RFC 3648) */
  6891. /* ACL (RFC 3744) */
  6892. /* SEARCH (RFC 5323) */
  6893. /* + MicroSoft extensions
  6894. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  6895. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  6896. || !strcmp(method, "PATCH"); /* PATCH method (RFC 5789) */
  6897. }
  6898. /* Parse HTTP request, fill in mg_request_info structure.
  6899. * This function modifies the buffer by NUL-terminating
  6900. * HTTP request components, header names and header values.
  6901. * Parameters:
  6902. * buf (in/out): pointer to the HTTP header to parse and split
  6903. * len (in): length of HTTP header buffer
  6904. * re (out): parsed header as mg_request_info
  6905. * buf and ri must be valid pointers (not NULL), len>0.
  6906. * Returns <0 on error. */
  6907. static int
  6908. parse_http_message(char *buf, int len, struct mg_request_info *ri)
  6909. {
  6910. int is_request, request_length;
  6911. char *start_line;
  6912. request_length = get_request_len(buf, len);
  6913. if (request_length > 0) {
  6914. /* Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_addr,
  6915. * remote_port */
  6916. ri->remote_user = ri->request_method = ri->request_uri =
  6917. ri->http_version = NULL;
  6918. ri->num_headers = 0;
  6919. buf[request_length - 1] = '\0';
  6920. /* RFC says that all initial whitespaces should be ingored */
  6921. while (*buf != '\0' && isspace(*(unsigned char *)buf)) {
  6922. buf++;
  6923. }
  6924. start_line = skip(&buf, "\r\n");
  6925. ri->request_method = skip(&start_line, " ");
  6926. ri->request_uri = skip(&start_line, " ");
  6927. ri->http_version = start_line;
  6928. /* HTTP message could be either HTTP request:
  6929. * "GET / HTTP/1.0 ..."
  6930. * or a HTTP response:
  6931. * "HTTP/1.0 200 OK ..."
  6932. * otherwise it is invalid.
  6933. */
  6934. is_request = is_valid_http_method(ri->request_method);
  6935. if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0)
  6936. || (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
  6937. /* Not a valid request or response: invalid */
  6938. return -1;
  6939. }
  6940. if (is_request) {
  6941. ri->http_version += 5;
  6942. }
  6943. if (parse_http_headers(&buf, ri) < 0) {
  6944. /* Error while parsing headers */
  6945. return -1;
  6946. }
  6947. }
  6948. return request_length;
  6949. }
  6950. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  6951. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  6952. * buffer (which marks the end of HTTP request). Buffer buf may already
  6953. * have some data. The length of the data is stored in nread.
  6954. * Upon every read operation, increase nread by the number of bytes read. */
  6955. static int
  6956. read_request(FILE *fp,
  6957. struct mg_connection *conn,
  6958. char *buf,
  6959. int bufsiz,
  6960. int *nread)
  6961. {
  6962. int request_len, n = 0;
  6963. struct timespec last_action_time;
  6964. double request_timeout;
  6965. if (!conn) {
  6966. return 0;
  6967. }
  6968. memset(&last_action_time, 0, sizeof(last_action_time));
  6969. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  6970. /* value of request_timeout is in seconds, config in milliseconds */
  6971. request_timeout = atof(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  6972. } else {
  6973. request_timeout = -1.0;
  6974. }
  6975. if (conn->handled_requests > 0) {
  6976. if (conn->ctx->config[KEEP_ALIVE_TIMEOUT]) {
  6977. request_timeout =
  6978. atof(conn->ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  6979. }
  6980. }
  6981. request_len = get_request_len(buf, *nread);
  6982. /* first time reading from this connection */
  6983. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  6984. while (request_len == 0) {
  6985. /* Full request not yet received */
  6986. if (conn->ctx->stop_flag != 0) {
  6987. /* Server is to be stopped. */
  6988. return -1;
  6989. }
  6990. if (*nread >= bufsiz) {
  6991. /* Request too long */
  6992. return -2;
  6993. }
  6994. n = pull_inner(
  6995. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  6996. if (n == -2) {
  6997. /* Receive error */
  6998. return -1;
  6999. }
  7000. if (n > 0) {
  7001. *nread += n;
  7002. request_len = get_request_len(buf, *nread);
  7003. } else {
  7004. request_len = 0;
  7005. }
  7006. if ((request_len == 0) && (request_timeout >= 0)) {
  7007. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  7008. > request_timeout) {
  7009. /* Timeout */
  7010. return -1;
  7011. }
  7012. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  7013. }
  7014. }
  7015. return request_len;
  7016. }
  7017. #if !defined(NO_FILES)
  7018. /* For given directory path, substitute it to valid index file.
  7019. * Return 1 if index file has been found, 0 if not found.
  7020. * If the file is found, it's stats is returned in stp. */
  7021. static int
  7022. substitute_index_file(struct mg_connection *conn,
  7023. char *path,
  7024. size_t path_len,
  7025. struct mg_file *filep)
  7026. {
  7027. if (conn && conn->ctx) {
  7028. const char *list = conn->ctx->config[INDEX_FILES];
  7029. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7030. struct vec filename_vec;
  7031. size_t n = strlen(path);
  7032. int found = 0;
  7033. /* The 'path' given to us points to the directory. Remove all trailing
  7034. * directory separator characters from the end of the path, and
  7035. * then append single directory separator character. */
  7036. while (n > 0 && path[n - 1] == '/') {
  7037. n--;
  7038. }
  7039. path[n] = '/';
  7040. /* Traverse index files list. For each entry, append it to the given
  7041. * path and see if the file exists. If it exists, break the loop */
  7042. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  7043. /* Ignore too long entries that may overflow path buffer */
  7044. if (filename_vec.len > path_len - (n + 2)) {
  7045. continue;
  7046. }
  7047. /* Prepare full path to the index file */
  7048. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  7049. /* Does it exist? */
  7050. if (mg_stat(conn, path, &file.stat)) {
  7051. /* Yes it does, break the loop */
  7052. *filep = file;
  7053. found = 1;
  7054. break;
  7055. }
  7056. }
  7057. /* If no index file exists, restore directory path */
  7058. if (!found) {
  7059. path[n] = '\0';
  7060. }
  7061. return found;
  7062. }
  7063. return 0;
  7064. }
  7065. #endif
  7066. #if !defined(NO_CACHING)
  7067. /* Return True if we should reply 304 Not Modified. */
  7068. static int
  7069. is_not_modified(const struct mg_connection *conn,
  7070. const struct mg_file_stat *filestat)
  7071. {
  7072. char etag[64];
  7073. const char *ims = mg_get_header(conn, "If-Modified-Since");
  7074. const char *inm = mg_get_header(conn, "If-None-Match");
  7075. construct_etag(etag, sizeof(etag), filestat);
  7076. return (inm != NULL && !mg_strcasecmp(etag, inm))
  7077. || ((ims != NULL)
  7078. && (filestat->last_modified <= parse_date_string(ims)));
  7079. }
  7080. #endif /* !NO_CACHING */
  7081. #if !defined(NO_CGI) || !defined(NO_FILES)
  7082. static int
  7083. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  7084. {
  7085. const char *expect, *body;
  7086. char buf[MG_BUF_LEN];
  7087. int to_read, nread, success = 0;
  7088. int64_t buffered_len;
  7089. double timeout = -1.0;
  7090. if (!conn) {
  7091. return 0;
  7092. }
  7093. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  7094. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  7095. }
  7096. expect = mg_get_header(conn, "Expect");
  7097. /* assert(fp != NULL); */
  7098. if (!fp) {
  7099. send_http_error(conn, 500, "%s", "Error: NULL File");
  7100. return 0;
  7101. }
  7102. if (conn->content_len == -1 && !conn->is_chunked) {
  7103. /* Content length is not specified by the client. */
  7104. send_http_error(conn,
  7105. 411,
  7106. "%s",
  7107. "Error: Client did not specify content length");
  7108. } else if ((expect != NULL)
  7109. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  7110. /* Client sent an "Expect: xyz" header and xyz is not 100-continue. */
  7111. send_http_error(conn,
  7112. 417,
  7113. "Error: Can not fulfill expectation %s",
  7114. expect);
  7115. } else {
  7116. if (expect != NULL) {
  7117. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  7118. conn->status_code = 100;
  7119. } else {
  7120. conn->status_code = 200;
  7121. }
  7122. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  7123. - conn->consumed_content;
  7124. /* assert(buffered_len >= 0); */
  7125. /* assert(conn->consumed_content == 0); */
  7126. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  7127. send_http_error(conn, 500, "%s", "Error: Size mismatch");
  7128. return 0;
  7129. }
  7130. if (buffered_len > 0) {
  7131. if ((int64_t)buffered_len > conn->content_len) {
  7132. buffered_len = (int)conn->content_len;
  7133. }
  7134. body = conn->buf + conn->request_len + conn->consumed_content;
  7135. push_all(conn->ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  7136. conn->consumed_content += buffered_len;
  7137. }
  7138. nread = 0;
  7139. while (conn->consumed_content < conn->content_len) {
  7140. to_read = sizeof(buf);
  7141. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  7142. to_read = (int)(conn->content_len - conn->consumed_content);
  7143. }
  7144. nread = pull_inner(NULL, conn, buf, to_read, timeout);
  7145. if (nread == -2) {
  7146. /* error */
  7147. break;
  7148. }
  7149. if (nread > 0) {
  7150. if (push_all(conn->ctx, fp, sock, ssl, buf, nread) != nread) {
  7151. break;
  7152. }
  7153. }
  7154. conn->consumed_content += nread;
  7155. }
  7156. if (conn->consumed_content == conn->content_len) {
  7157. success = (nread >= 0);
  7158. }
  7159. /* Each error code path in this function must send an error */
  7160. if (!success) {
  7161. /* NOTE: Maybe some data has already been sent. */
  7162. /* TODO (low): If some data has been sent, a correct error
  7163. * reply can no longer be sent, so just close the connection */
  7164. send_http_error(conn, 500, "%s", "");
  7165. }
  7166. }
  7167. return success;
  7168. }
  7169. #endif
  7170. #if !defined(NO_CGI)
  7171. /* This structure helps to create an environment for the spawned CGI program.
  7172. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  7173. * last element must be NULL.
  7174. * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  7175. * strings must reside in a contiguous buffer. The end of the buffer is
  7176. * marked by two '\0' characters.
  7177. * We satisfy both worlds: we create an envp array (which is vars), all
  7178. * entries are actually pointers inside buf. */
  7179. struct cgi_environment {
  7180. struct mg_connection *conn;
  7181. /* Data block */
  7182. char *buf; /* Environment buffer */
  7183. size_t buflen; /* Space available in buf */
  7184. size_t bufused; /* Space taken in buf */
  7185. /* Index block */
  7186. char **var; /* char **envp */
  7187. size_t varlen; /* Number of variables available in var */
  7188. size_t varused; /* Number of variables stored in var */
  7189. };
  7190. static void addenv(struct cgi_environment *env,
  7191. PRINTF_FORMAT_STRING(const char *fmt),
  7192. ...) PRINTF_ARGS(2, 3);
  7193. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  7194. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  7195. static void
  7196. addenv(struct cgi_environment *env, const char *fmt, ...)
  7197. {
  7198. size_t n, space;
  7199. int truncated = 0;
  7200. char *added;
  7201. va_list ap;
  7202. /* Calculate how much space is left in the buffer */
  7203. space = (env->buflen - env->bufused);
  7204. /* Calculate an estimate for the required space */
  7205. n = strlen(fmt) + 2 + 128;
  7206. do {
  7207. if (space <= n) {
  7208. /* Allocate new buffer */
  7209. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  7210. added = (char *)mg_realloc(env->buf, n);
  7211. if (!added) {
  7212. /* Out of memory */
  7213. mg_cry(env->conn,
  7214. "%s: Cannot allocate memory for CGI variable [%s]",
  7215. __func__,
  7216. fmt);
  7217. return;
  7218. }
  7219. env->buf = added;
  7220. env->buflen = n;
  7221. space = (env->buflen - env->bufused);
  7222. }
  7223. /* Make a pointer to the free space int the buffer */
  7224. added = env->buf + env->bufused;
  7225. /* Copy VARIABLE=VALUE\0 string into the free space */
  7226. va_start(ap, fmt);
  7227. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  7228. va_end(ap);
  7229. /* Do not add truncated strings to the environment */
  7230. if (truncated) {
  7231. /* Reallocate the buffer */
  7232. space = 0;
  7233. n = 1;
  7234. }
  7235. } while (truncated);
  7236. /* Calculate number of bytes added to the environment */
  7237. n = strlen(added) + 1;
  7238. env->bufused += n;
  7239. /* Now update the variable index */
  7240. space = (env->varlen - env->varused);
  7241. if (space < 2) {
  7242. mg_cry(env->conn,
  7243. "%s: Cannot register CGI variable [%s]",
  7244. __func__,
  7245. fmt);
  7246. return;
  7247. }
  7248. /* Append a pointer to the added string into the envp array */
  7249. env->var[env->varused] = added;
  7250. env->varused++;
  7251. }
  7252. static void
  7253. prepare_cgi_environment(struct mg_connection *conn,
  7254. const char *prog,
  7255. struct cgi_environment *env)
  7256. {
  7257. const char *s;
  7258. struct vec var_vec;
  7259. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  7260. int i, truncated, uri_len;
  7261. if (conn == NULL || prog == NULL || env == NULL) {
  7262. return;
  7263. }
  7264. env->conn = conn;
  7265. env->buflen = CGI_ENVIRONMENT_SIZE;
  7266. env->bufused = 0;
  7267. env->buf = (char *)mg_malloc(env->buflen);
  7268. env->varlen = MAX_CGI_ENVIR_VARS;
  7269. env->varused = 0;
  7270. env->var = (char **)mg_malloc(env->buflen * sizeof(char *));
  7271. addenv(env, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  7272. addenv(env, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  7273. addenv(env, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  7274. addenv(env, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  7275. /* Prepare the environment block */
  7276. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  7277. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  7278. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  7279. #if defined(USE_IPV6)
  7280. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  7281. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  7282. } else
  7283. #endif
  7284. {
  7285. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  7286. }
  7287. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  7288. addenv(env, "REMOTE_ADDR=%s", src_addr);
  7289. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  7290. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  7291. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  7292. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  7293. /* SCRIPT_NAME */
  7294. uri_len = (int)strlen(conn->request_info.local_uri);
  7295. if (conn->path_info == NULL) {
  7296. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  7297. /* URI: /path_to_script/script.cgi */
  7298. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  7299. } else {
  7300. /* URI: /path_to_script/ ... using index.cgi */
  7301. char *index_file = strrchr(prog, '/');
  7302. if (index_file) {
  7303. addenv(env,
  7304. "SCRIPT_NAME=%s%s",
  7305. conn->request_info.local_uri,
  7306. index_file + 1);
  7307. }
  7308. }
  7309. } else {
  7310. /* URI: /path_to_script/script.cgi/path_info */
  7311. addenv(env,
  7312. "SCRIPT_NAME=%.*s",
  7313. uri_len - (int)strlen(conn->path_info),
  7314. conn->request_info.local_uri);
  7315. }
  7316. addenv(env, "SCRIPT_FILENAME=%s", prog);
  7317. if (conn->path_info == NULL) {
  7318. addenv(env, "PATH_TRANSLATED=%s", conn->ctx->config[DOCUMENT_ROOT]);
  7319. } else {
  7320. addenv(env,
  7321. "PATH_TRANSLATED=%s%s",
  7322. conn->ctx->config[DOCUMENT_ROOT],
  7323. conn->path_info);
  7324. }
  7325. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  7326. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  7327. addenv(env, "CONTENT_TYPE=%s", s);
  7328. }
  7329. if (conn->request_info.query_string != NULL) {
  7330. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  7331. }
  7332. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  7333. addenv(env, "CONTENT_LENGTH=%s", s);
  7334. }
  7335. if ((s = getenv("PATH")) != NULL) {
  7336. addenv(env, "PATH=%s", s);
  7337. }
  7338. if (conn->path_info != NULL) {
  7339. addenv(env, "PATH_INFO=%s", conn->path_info);
  7340. }
  7341. if (conn->status_code > 0) {
  7342. /* CGI error handler should show the status code */
  7343. addenv(env, "STATUS=%d", conn->status_code);
  7344. }
  7345. #if defined(_WIN32)
  7346. if ((s = getenv("COMSPEC")) != NULL) {
  7347. addenv(env, "COMSPEC=%s", s);
  7348. }
  7349. if ((s = getenv("SYSTEMROOT")) != NULL) {
  7350. addenv(env, "SYSTEMROOT=%s", s);
  7351. }
  7352. if ((s = getenv("SystemDrive")) != NULL) {
  7353. addenv(env, "SystemDrive=%s", s);
  7354. }
  7355. if ((s = getenv("ProgramFiles")) != NULL) {
  7356. addenv(env, "ProgramFiles=%s", s);
  7357. }
  7358. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  7359. addenv(env, "ProgramFiles(x86)=%s", s);
  7360. }
  7361. #else
  7362. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  7363. addenv(env, "LD_LIBRARY_PATH=%s", s);
  7364. }
  7365. #endif /* _WIN32 */
  7366. if ((s = getenv("PERLLIB")) != NULL) {
  7367. addenv(env, "PERLLIB=%s", s);
  7368. }
  7369. if (conn->request_info.remote_user != NULL) {
  7370. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  7371. addenv(env, "%s", "AUTH_TYPE=Digest");
  7372. }
  7373. /* Add all headers as HTTP_* variables */
  7374. for (i = 0; i < conn->request_info.num_headers; i++) {
  7375. (void)mg_snprintf(conn,
  7376. &truncated,
  7377. http_var_name,
  7378. sizeof(http_var_name),
  7379. "HTTP_%s",
  7380. conn->request_info.http_headers[i].name);
  7381. if (truncated) {
  7382. mg_cry(conn,
  7383. "%s: HTTP header variable too long [%s]",
  7384. __func__,
  7385. conn->request_info.http_headers[i].name);
  7386. continue;
  7387. }
  7388. /* Convert variable name into uppercase, and change - to _ */
  7389. for (p = http_var_name; *p != '\0'; p++) {
  7390. if (*p == '-') {
  7391. *p = '_';
  7392. }
  7393. *p = (char)toupper(*(unsigned char *)p);
  7394. }
  7395. addenv(env,
  7396. "%s=%s",
  7397. http_var_name,
  7398. conn->request_info.http_headers[i].value);
  7399. }
  7400. /* Add user-specified variables */
  7401. s = conn->ctx->config[CGI_ENVIRONMENT];
  7402. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  7403. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  7404. }
  7405. env->var[env->varused] = NULL;
  7406. env->buf[env->bufused] = '\0';
  7407. }
  7408. static void
  7409. handle_cgi_request(struct mg_connection *conn, const char *prog)
  7410. {
  7411. char *buf;
  7412. size_t buflen;
  7413. int headers_len, data_len, i, truncated;
  7414. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  7415. const char *status, *status_text, *connection_state;
  7416. char *pbuf, dir[PATH_MAX], *p;
  7417. struct mg_request_info ri;
  7418. struct cgi_environment blk;
  7419. FILE *in = NULL, *out = NULL, *err = NULL;
  7420. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  7421. pid_t pid = (pid_t)-1;
  7422. if (conn == NULL) {
  7423. return;
  7424. }
  7425. buf = NULL;
  7426. buflen = 16384;
  7427. prepare_cgi_environment(conn, prog, &blk);
  7428. /* CGI must be executed in its own directory. 'dir' must point to the
  7429. * directory containing executable program, 'p' must point to the
  7430. * executable program name relative to 'dir'. */
  7431. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  7432. if (truncated) {
  7433. mg_cry(conn, "Error: CGI program \"%s\": Path too long", prog);
  7434. send_http_error(conn, 500, "Error: %s", "CGI path too long");
  7435. goto done;
  7436. }
  7437. if ((p = strrchr(dir, '/')) != NULL) {
  7438. *p++ = '\0';
  7439. } else {
  7440. dir[0] = '.', dir[1] = '\0';
  7441. p = (char *)prog;
  7442. }
  7443. if (pipe(fdin) != 0 || pipe(fdout) != 0 || pipe(fderr) != 0) {
  7444. status = strerror(ERRNO);
  7445. mg_cry(conn,
  7446. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  7447. prog,
  7448. status);
  7449. send_http_error(conn, 500, "Error: Cannot create CGI pipe: %s", status);
  7450. goto done;
  7451. }
  7452. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  7453. if (pid == (pid_t)-1) {
  7454. status = strerror(ERRNO);
  7455. mg_cry(conn,
  7456. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  7457. prog,
  7458. status);
  7459. send_http_error(conn,
  7460. 500,
  7461. "Error: Cannot spawn CGI process [%s]: %s",
  7462. prog,
  7463. status);
  7464. goto done;
  7465. }
  7466. /* Make sure child closes all pipe descriptors. It must dup them to 0,1 */
  7467. set_close_on_exec((SOCKET)fdin[0], conn); /* stdin read */
  7468. set_close_on_exec((SOCKET)fdout[1], conn); /* stdout write */
  7469. set_close_on_exec((SOCKET)fderr[1], conn); /* stderr write */
  7470. set_close_on_exec((SOCKET)fdin[1], conn); /* stdin write */
  7471. set_close_on_exec((SOCKET)fdout[0], conn); /* stdout read */
  7472. set_close_on_exec((SOCKET)fderr[0], conn); /* stderr read */
  7473. /* Parent closes only one side of the pipes.
  7474. * If we don't mark them as closed, close() attempt before
  7475. * return from this function throws an exception on Windows.
  7476. * Windows does not like when closed descriptor is closed again. */
  7477. (void)close(fdin[0]);
  7478. (void)close(fdout[1]);
  7479. (void)close(fderr[1]);
  7480. fdin[0] = fdout[1] = fderr[1] = -1;
  7481. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  7482. status = strerror(ERRNO);
  7483. mg_cry(conn,
  7484. "Error: CGI program \"%s\": Can not open stdin: %s",
  7485. prog,
  7486. status);
  7487. send_http_error(conn,
  7488. 500,
  7489. "Error: CGI can not open fdin\nfopen: %s",
  7490. status);
  7491. goto done;
  7492. }
  7493. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  7494. status = strerror(ERRNO);
  7495. mg_cry(conn,
  7496. "Error: CGI program \"%s\": Can not open stdout: %s",
  7497. prog,
  7498. status);
  7499. send_http_error(conn,
  7500. 500,
  7501. "Error: CGI can not open fdout\nfopen: %s",
  7502. status);
  7503. goto done;
  7504. }
  7505. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  7506. status = strerror(ERRNO);
  7507. mg_cry(conn,
  7508. "Error: CGI program \"%s\": Can not open stderr: %s",
  7509. prog,
  7510. status);
  7511. send_http_error(conn,
  7512. 500,
  7513. "Error: CGI can not open fdout\nfopen: %s",
  7514. status);
  7515. goto done;
  7516. }
  7517. setbuf(in, NULL);
  7518. setbuf(out, NULL);
  7519. setbuf(err, NULL);
  7520. fout.access.fp = out;
  7521. if ((conn->request_info.content_length > 0) || conn->is_chunked) {
  7522. /* This is a POST/PUT request, or another request with body data. */
  7523. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  7524. /* Error sending the body data */
  7525. mg_cry(conn,
  7526. "Error: CGI program \"%s\": Forward body data failed",
  7527. prog);
  7528. goto done;
  7529. }
  7530. }
  7531. /* Close so child gets an EOF. */
  7532. fclose(in);
  7533. in = NULL;
  7534. fdin[1] = -1;
  7535. /* Now read CGI reply into a buffer. We need to set correct
  7536. * status code, thus we need to see all HTTP headers first.
  7537. * Do not send anything back to client, until we buffer in all
  7538. * HTTP headers. */
  7539. data_len = 0;
  7540. buf = (char *)mg_malloc(buflen);
  7541. if (buf == NULL) {
  7542. send_http_error(conn,
  7543. 500,
  7544. "Error: Not enough memory for CGI buffer (%u bytes)",
  7545. (unsigned int)buflen);
  7546. mg_cry(conn,
  7547. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  7548. "bytes)",
  7549. prog,
  7550. (unsigned int)buflen);
  7551. goto done;
  7552. }
  7553. headers_len = read_request(out, conn, buf, (int)buflen, &data_len);
  7554. if (headers_len <= 0) {
  7555. /* Could not parse the CGI response. Check if some error message on
  7556. * stderr. */
  7557. i = pull_all(err, conn, buf, (int)buflen);
  7558. if (i > 0) {
  7559. mg_cry(conn,
  7560. "Error: CGI program \"%s\" sent error "
  7561. "message: [%.*s]",
  7562. prog,
  7563. i,
  7564. buf);
  7565. send_http_error(conn,
  7566. 500,
  7567. "Error: CGI program \"%s\" sent error "
  7568. "message: [%.*s]",
  7569. prog,
  7570. i,
  7571. buf);
  7572. } else {
  7573. mg_cry(conn,
  7574. "Error: CGI program sent malformed or too big "
  7575. "(>%u bytes) HTTP headers: [%.*s]",
  7576. (unsigned)buflen,
  7577. data_len,
  7578. buf);
  7579. send_http_error(conn,
  7580. 500,
  7581. "Error: CGI program sent malformed or too big "
  7582. "(>%u bytes) HTTP headers: [%.*s]",
  7583. (unsigned)buflen,
  7584. data_len,
  7585. buf);
  7586. }
  7587. goto done;
  7588. }
  7589. pbuf = buf;
  7590. buf[headers_len - 1] = '\0';
  7591. parse_http_headers(&pbuf, &ri);
  7592. /* Make up and send the status line */
  7593. status_text = "OK";
  7594. if ((status = get_header(&ri, "Status")) != NULL) {
  7595. conn->status_code = atoi(status);
  7596. status_text = status;
  7597. while (isdigit(*(const unsigned char *)status_text)
  7598. || *status_text == ' ') {
  7599. status_text++;
  7600. }
  7601. } else if (get_header(&ri, "Location") != NULL) {
  7602. conn->status_code = 302;
  7603. } else {
  7604. conn->status_code = 200;
  7605. }
  7606. connection_state = get_header(&ri, "Connection");
  7607. if (!header_has_option(connection_state, "keep-alive")) {
  7608. conn->must_close = 1;
  7609. }
  7610. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  7611. /* Send headers */
  7612. for (i = 0; i < ri.num_headers; i++) {
  7613. mg_printf(conn,
  7614. "%s: %s\r\n",
  7615. ri.http_headers[i].name,
  7616. ri.http_headers[i].value);
  7617. }
  7618. mg_write(conn, "\r\n", 2);
  7619. /* Send chunk of data that may have been read after the headers */
  7620. conn->num_bytes_sent +=
  7621. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  7622. /* Read the rest of CGI output and send to the client */
  7623. send_file_data(conn, &fout, 0, INT64_MAX);
  7624. done:
  7625. mg_free(blk.var);
  7626. mg_free(blk.buf);
  7627. if (pid != (pid_t)-1) {
  7628. kill(pid, SIGKILL);
  7629. #if !defined(_WIN32)
  7630. {
  7631. int st;
  7632. while (waitpid(pid, &st, 0) != -1)
  7633. ; /* clean zombies */
  7634. }
  7635. #endif
  7636. }
  7637. if (fdin[0] != -1) {
  7638. close(fdin[0]);
  7639. }
  7640. if (fdout[1] != -1) {
  7641. close(fdout[1]);
  7642. }
  7643. if (in != NULL) {
  7644. fclose(in);
  7645. } else if (fdin[1] != -1) {
  7646. close(fdin[1]);
  7647. }
  7648. if (out != NULL) {
  7649. fclose(out);
  7650. } else if (fdout[0] != -1) {
  7651. close(fdout[0]);
  7652. }
  7653. if (err != NULL) {
  7654. fclose(err);
  7655. } else if (fderr[0] != -1) {
  7656. close(fderr[0]);
  7657. }
  7658. if (buf != NULL) {
  7659. mg_free(buf);
  7660. }
  7661. }
  7662. #endif /* !NO_CGI */
  7663. #if !defined(NO_FILES)
  7664. static void
  7665. mkcol(struct mg_connection *conn, const char *path)
  7666. {
  7667. int rc, body_len;
  7668. struct de de;
  7669. char date[64];
  7670. time_t curtime = time(NULL);
  7671. if (conn == NULL) {
  7672. return;
  7673. }
  7674. /* TODO (mid): Check the send_http_error situations in this function */
  7675. memset(&de.file, 0, sizeof(de.file));
  7676. if (!mg_stat(conn, path, &de.file)) {
  7677. mg_cry(conn,
  7678. "%s: mg_stat(%s) failed: %s",
  7679. __func__,
  7680. path,
  7681. strerror(ERRNO));
  7682. }
  7683. if (de.file.last_modified) {
  7684. /* TODO (mid): This check does not seem to make any sense ! */
  7685. /* TODO (mid): Add a webdav unit test first, before changing
  7686. * anything here. */
  7687. send_http_error(
  7688. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7689. return;
  7690. }
  7691. body_len = conn->data_len - conn->request_len;
  7692. if (body_len > 0) {
  7693. send_http_error(
  7694. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7695. return;
  7696. }
  7697. rc = mg_mkdir(conn, path, 0755);
  7698. if (rc == 0) {
  7699. conn->status_code = 201;
  7700. gmt_time_string(date, sizeof(date), &curtime);
  7701. mg_printf(conn,
  7702. "HTTP/1.1 %d Created\r\n"
  7703. "Date: %s\r\n",
  7704. conn->status_code,
  7705. date);
  7706. send_static_cache_header(conn);
  7707. send_additional_header(conn);
  7708. mg_printf(conn,
  7709. "Content-Length: 0\r\n"
  7710. "Connection: %s\r\n\r\n",
  7711. suggest_connection_header(conn));
  7712. } else if (rc == -1) {
  7713. if (errno == EEXIST) {
  7714. send_http_error(
  7715. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7716. } else if (errno == EACCES) {
  7717. send_http_error(
  7718. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7719. } else if (errno == ENOENT) {
  7720. send_http_error(
  7721. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7722. } else {
  7723. send_http_error(conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  7724. }
  7725. }
  7726. }
  7727. static void
  7728. put_file(struct mg_connection *conn, const char *path)
  7729. {
  7730. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7731. const char *range;
  7732. int64_t r1, r2;
  7733. int rc;
  7734. char date[64];
  7735. time_t curtime = time(NULL);
  7736. if (conn == NULL) {
  7737. return;
  7738. }
  7739. if (mg_stat(conn, path, &file.stat)) {
  7740. /* File already exists */
  7741. conn->status_code = 200;
  7742. if (file.stat.is_directory) {
  7743. /* This is an already existing directory,
  7744. * so there is nothing to do for the server. */
  7745. rc = 0;
  7746. } else {
  7747. /* File exists and is not a directory. */
  7748. /* Can it be replaced? */
  7749. if (file.access.membuf != NULL) {
  7750. /* This is an "in-memory" file, that can not be replaced */
  7751. send_http_error(
  7752. conn,
  7753. 405,
  7754. "Error: Put not possible\nReplacing %s is not supported",
  7755. path);
  7756. return;
  7757. }
  7758. /* Check if the server may write this file */
  7759. if (access(path, W_OK) == 0) {
  7760. /* Access granted */
  7761. conn->status_code = 200;
  7762. rc = 1;
  7763. } else {
  7764. send_http_error(
  7765. conn,
  7766. 403,
  7767. "Error: Put not possible\nReplacing %s is not allowed",
  7768. path);
  7769. return;
  7770. }
  7771. }
  7772. } else {
  7773. /* File should be created */
  7774. conn->status_code = 201;
  7775. rc = put_dir(conn, path);
  7776. }
  7777. if (rc == 0) {
  7778. /* put_dir returns 0 if path is a directory */
  7779. gmt_time_string(date, sizeof(date), &curtime);
  7780. mg_printf(conn,
  7781. "HTTP/1.1 %d %s\r\n",
  7782. conn->status_code,
  7783. mg_get_response_code_text(NULL, conn->status_code));
  7784. send_no_cache_header(conn);
  7785. send_additional_header(conn);
  7786. mg_printf(conn,
  7787. "Date: %s\r\n"
  7788. "Content-Length: 0\r\n"
  7789. "Connection: %s\r\n\r\n",
  7790. date,
  7791. suggest_connection_header(conn));
  7792. /* Request to create a directory has been fulfilled successfully.
  7793. * No need to put a file. */
  7794. return;
  7795. }
  7796. if (rc == -1) {
  7797. /* put_dir returns -1 if the path is too long */
  7798. send_http_error(conn,
  7799. 414,
  7800. "Error: Path too long\nput_dir(%s): %s",
  7801. path,
  7802. strerror(ERRNO));
  7803. return;
  7804. }
  7805. if (rc == -2) {
  7806. /* put_dir returns -2 if the directory can not be created */
  7807. send_http_error(conn,
  7808. 500,
  7809. "Error: Can not create directory\nput_dir(%s): %s",
  7810. path,
  7811. strerror(ERRNO));
  7812. return;
  7813. }
  7814. /* A file should be created or overwritten. */
  7815. /* Currently CivetWeb does not nead read+write access. */
  7816. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  7817. || file.access.fp == NULL) {
  7818. (void)mg_fclose(&file.access);
  7819. send_http_error(conn,
  7820. 500,
  7821. "Error: Can not create file\nfopen(%s): %s",
  7822. path,
  7823. strerror(ERRNO));
  7824. return;
  7825. }
  7826. fclose_on_exec(&file.access, conn);
  7827. range = mg_get_header(conn, "Content-Range");
  7828. r1 = r2 = 0;
  7829. if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
  7830. conn->status_code = 206; /* Partial content */
  7831. fseeko(file.access.fp, r1, SEEK_SET);
  7832. }
  7833. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  7834. /* forward_body_data failed.
  7835. * The error code has already been sent to the client,
  7836. * and conn->status_code is already set. */
  7837. (void)mg_fclose(&file.access);
  7838. return;
  7839. }
  7840. if (mg_fclose(&file.access) != 0) {
  7841. /* fclose failed. This might have different reasons, but a likely
  7842. * one is "no space on disk", http 507. */
  7843. conn->status_code = 507;
  7844. }
  7845. gmt_time_string(date, sizeof(date), &curtime);
  7846. mg_printf(conn,
  7847. "HTTP/1.1 %d %s\r\n",
  7848. conn->status_code,
  7849. mg_get_response_code_text(NULL, conn->status_code));
  7850. send_no_cache_header(conn);
  7851. send_additional_header(conn);
  7852. mg_printf(conn,
  7853. "Date: %s\r\n"
  7854. "Content-Length: 0\r\n"
  7855. "Connection: %s\r\n\r\n",
  7856. date,
  7857. suggest_connection_header(conn));
  7858. }
  7859. static void
  7860. delete_file(struct mg_connection *conn, const char *path)
  7861. {
  7862. struct de de;
  7863. memset(&de.file, 0, sizeof(de.file));
  7864. if (!mg_stat(conn, path, &de.file)) {
  7865. /* mg_stat returns 0 if the file does not exist */
  7866. send_http_error(conn,
  7867. 404,
  7868. "Error: Cannot delete file\nFile %s not found",
  7869. path);
  7870. return;
  7871. }
  7872. #if 0 /* Ignore if a file in memory is inside a folder */
  7873. if (de.access.membuf != NULL) {
  7874. /* the file is cached in memory */
  7875. send_http_error(
  7876. conn,
  7877. 405,
  7878. "Error: Delete not possible\nDeleting %s is not supported",
  7879. path);
  7880. return;
  7881. }
  7882. #endif
  7883. if (de.file.is_directory) {
  7884. if (remove_directory(conn, path)) {
  7885. /* Delete is successful: Return 204 without content. */
  7886. send_http_error(conn, 204, "%s", "");
  7887. } else {
  7888. /* Delete is not successful: Return 500 (Server error). */
  7889. send_http_error(conn, 500, "Error: Could not delete %s", path);
  7890. }
  7891. return;
  7892. }
  7893. /* This is an existing file (not a directory).
  7894. * Check if write permission is granted. */
  7895. if (access(path, W_OK) != 0) {
  7896. /* File is read only */
  7897. send_http_error(
  7898. conn,
  7899. 403,
  7900. "Error: Delete not possible\nDeleting %s is not allowed",
  7901. path);
  7902. return;
  7903. }
  7904. /* Try to delete it. */
  7905. if (mg_remove(conn, path) == 0) {
  7906. /* Delete was successful: Return 204 without content. */
  7907. send_http_error(conn, 204, "%s", "");
  7908. } else {
  7909. /* Delete not successful (file locked). */
  7910. send_http_error(conn,
  7911. 423,
  7912. "Error: Cannot delete file\nremove(%s): %s",
  7913. path,
  7914. strerror(ERRNO));
  7915. }
  7916. }
  7917. #endif /* !NO_FILES */
  7918. static void
  7919. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  7920. static void
  7921. do_ssi_include(struct mg_connection *conn,
  7922. const char *ssi,
  7923. char *tag,
  7924. int include_level)
  7925. {
  7926. char file_name[MG_BUF_LEN], path[512], *p;
  7927. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7928. size_t len;
  7929. int truncated = 0;
  7930. if (conn == NULL) {
  7931. return;
  7932. }
  7933. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  7934. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  7935. * always < MG_BUF_LEN. */
  7936. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  7937. /* File name is relative to the webserver root */
  7938. file_name[511] = 0;
  7939. (void)mg_snprintf(conn,
  7940. &truncated,
  7941. path,
  7942. sizeof(path),
  7943. "%s/%s",
  7944. conn->ctx->config[DOCUMENT_ROOT],
  7945. file_name);
  7946. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  7947. /* File name is relative to the webserver working directory
  7948. * or it is absolute system path */
  7949. file_name[511] = 0;
  7950. (void)
  7951. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  7952. } else if (sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1
  7953. || sscanf(tag, " \"%511[^\"]\"", file_name) == 1) {
  7954. /* File name is relative to the currect document */
  7955. file_name[511] = 0;
  7956. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  7957. if (!truncated) {
  7958. if ((p = strrchr(path, '/')) != NULL) {
  7959. p[1] = '\0';
  7960. }
  7961. len = strlen(path);
  7962. (void)mg_snprintf(conn,
  7963. &truncated,
  7964. path + len,
  7965. sizeof(path) - len,
  7966. "%s",
  7967. file_name);
  7968. }
  7969. } else {
  7970. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  7971. return;
  7972. }
  7973. if (truncated) {
  7974. mg_cry(conn, "SSI #include path length overflow: [%s]", tag);
  7975. return;
  7976. }
  7977. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  7978. mg_cry(conn,
  7979. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  7980. tag,
  7981. path,
  7982. strerror(ERRNO));
  7983. } else {
  7984. fclose_on_exec(&file.access, conn);
  7985. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  7986. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  7987. path) > 0) {
  7988. send_ssi_file(conn, path, &file, include_level + 1);
  7989. } else {
  7990. send_file_data(conn, &file, 0, INT64_MAX);
  7991. }
  7992. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  7993. }
  7994. }
  7995. #if !defined(NO_POPEN)
  7996. static void
  7997. do_ssi_exec(struct mg_connection *conn, char *tag)
  7998. {
  7999. char cmd[1024] = "";
  8000. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8001. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  8002. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  8003. } else {
  8004. cmd[1023] = 0;
  8005. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  8006. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  8007. } else {
  8008. send_file_data(conn, &file, 0, INT64_MAX);
  8009. pclose(file.access.fp);
  8010. }
  8011. }
  8012. }
  8013. #endif /* !NO_POPEN */
  8014. static int
  8015. mg_fgetc(struct mg_file *filep, int offset)
  8016. {
  8017. if (filep == NULL) {
  8018. return EOF;
  8019. }
  8020. if (filep->access.membuf != NULL && offset >= 0
  8021. && ((unsigned int)(offset)) < filep->stat.size) {
  8022. return ((const unsigned char *)filep->access.membuf)[offset];
  8023. } else if (filep->access.fp != NULL) {
  8024. return fgetc(filep->access.fp);
  8025. } else {
  8026. return EOF;
  8027. }
  8028. }
  8029. static void
  8030. send_ssi_file(struct mg_connection *conn,
  8031. const char *path,
  8032. struct mg_file *filep,
  8033. int include_level)
  8034. {
  8035. char buf[MG_BUF_LEN];
  8036. int ch, offset, len, in_ssi_tag;
  8037. if (include_level > 10) {
  8038. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  8039. return;
  8040. }
  8041. in_ssi_tag = len = offset = 0;
  8042. while ((ch = mg_fgetc(filep, offset)) != EOF) {
  8043. if (in_ssi_tag && ch == '>') {
  8044. in_ssi_tag = 0;
  8045. buf[len++] = (char)ch;
  8046. buf[len] = '\0';
  8047. /* assert(len <= (int) sizeof(buf)); */
  8048. if (len > (int)sizeof(buf)) {
  8049. break;
  8050. }
  8051. if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
  8052. /* Not an SSI tag, pass it */
  8053. (void)mg_write(conn, buf, (size_t)len);
  8054. } else {
  8055. if (!memcmp(buf + 5, "include", 7)) {
  8056. do_ssi_include(conn, path, buf + 12, include_level);
  8057. #if !defined(NO_POPEN)
  8058. } else if (!memcmp(buf + 5, "exec", 4)) {
  8059. do_ssi_exec(conn, buf + 9);
  8060. #endif /* !NO_POPEN */
  8061. } else {
  8062. mg_cry(conn,
  8063. "%s: unknown SSI "
  8064. "command: \"%s\"",
  8065. path,
  8066. buf);
  8067. }
  8068. }
  8069. len = 0;
  8070. } else if (in_ssi_tag) {
  8071. if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
  8072. /* Not an SSI tag */
  8073. in_ssi_tag = 0;
  8074. } else if (len == (int)sizeof(buf) - 2) {
  8075. mg_cry(conn, "%s: SSI tag is too large", path);
  8076. len = 0;
  8077. }
  8078. buf[len++] = (char)(ch & 0xff);
  8079. } else if (ch == '<') {
  8080. in_ssi_tag = 1;
  8081. if (len > 0) {
  8082. mg_write(conn, buf, (size_t)len);
  8083. }
  8084. len = 0;
  8085. buf[len++] = (char)(ch & 0xff);
  8086. } else {
  8087. buf[len++] = (char)(ch & 0xff);
  8088. if (len == (int)sizeof(buf)) {
  8089. mg_write(conn, buf, (size_t)len);
  8090. len = 0;
  8091. }
  8092. }
  8093. }
  8094. /* Send the rest of buffered data */
  8095. if (len > 0) {
  8096. mg_write(conn, buf, (size_t)len);
  8097. }
  8098. }
  8099. static void
  8100. handle_ssi_file_request(struct mg_connection *conn,
  8101. const char *path,
  8102. struct mg_file *filep)
  8103. {
  8104. char date[64];
  8105. time_t curtime = time(NULL);
  8106. const char *cors1, *cors2, *cors3;
  8107. if (conn == NULL || path == NULL || filep == NULL) {
  8108. return;
  8109. }
  8110. if (mg_get_header(conn, "Origin")) {
  8111. /* Cross-origin resource sharing (CORS). */
  8112. cors1 = "Access-Control-Allow-Origin: ";
  8113. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  8114. cors3 = "\r\n";
  8115. } else {
  8116. cors1 = cors2 = cors3 = "";
  8117. }
  8118. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8119. /* File exists (precondition for calling this function),
  8120. * but can not be opened by the server. */
  8121. send_http_error(conn,
  8122. 500,
  8123. "Error: Cannot read file\nfopen(%s): %s",
  8124. path,
  8125. strerror(ERRNO));
  8126. } else {
  8127. conn->must_close = 1;
  8128. gmt_time_string(date, sizeof(date), &curtime);
  8129. fclose_on_exec(&filep->access, conn);
  8130. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  8131. send_no_cache_header(conn);
  8132. send_additional_header(conn);
  8133. mg_printf(conn,
  8134. "%s%s%s"
  8135. "Date: %s\r\n"
  8136. "Content-Type: text/html\r\n"
  8137. "Connection: %s\r\n\r\n",
  8138. cors1,
  8139. cors2,
  8140. cors3,
  8141. date,
  8142. suggest_connection_header(conn));
  8143. send_ssi_file(conn, path, filep, 0);
  8144. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  8145. }
  8146. }
  8147. #if !defined(NO_FILES)
  8148. static void
  8149. send_options(struct mg_connection *conn)
  8150. {
  8151. char date[64];
  8152. time_t curtime = time(NULL);
  8153. if (!conn) {
  8154. return;
  8155. }
  8156. conn->status_code = 200;
  8157. conn->must_close = 1;
  8158. gmt_time_string(date, sizeof(date), &curtime);
  8159. /* We do not set a "Cache-Control" header here, but leave the default.
  8160. * Since browsers do not send an OPTIONS request, we can not test the
  8161. * effect anyway. */
  8162. mg_printf(conn,
  8163. "HTTP/1.1 200 OK\r\n"
  8164. "Date: %s\r\n"
  8165. "Connection: %s\r\n"
  8166. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  8167. "PROPFIND, MKCOL\r\n"
  8168. "DAV: 1\r\n",
  8169. date,
  8170. suggest_connection_header(conn));
  8171. send_additional_header(conn);
  8172. mg_printf(conn, "\r\n");
  8173. }
  8174. /* Writes PROPFIND properties for a collection element */
  8175. static void
  8176. print_props(struct mg_connection *conn,
  8177. const char *uri,
  8178. struct mg_file_stat *filep)
  8179. {
  8180. char mtime[64];
  8181. if (conn == NULL || uri == NULL || filep == NULL) {
  8182. return;
  8183. }
  8184. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  8185. conn->num_bytes_sent +=
  8186. mg_printf(conn,
  8187. "<d:response>"
  8188. "<d:href>%s</d:href>"
  8189. "<d:propstat>"
  8190. "<d:prop>"
  8191. "<d:resourcetype>%s</d:resourcetype>"
  8192. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  8193. "<d:getlastmodified>%s</d:getlastmodified>"
  8194. "</d:prop>"
  8195. "<d:status>HTTP/1.1 200 OK</d:status>"
  8196. "</d:propstat>"
  8197. "</d:response>\n",
  8198. uri,
  8199. filep->is_directory ? "<d:collection/>" : "",
  8200. filep->size,
  8201. mtime);
  8202. }
  8203. static void
  8204. print_dav_dir_entry(struct de *de, void *data)
  8205. {
  8206. char href[PATH_MAX];
  8207. char href_encoded[PATH_MAX * 3 /* worst case */];
  8208. int truncated;
  8209. struct mg_connection *conn = (struct mg_connection *)data;
  8210. if (!de || !conn) {
  8211. return;
  8212. }
  8213. mg_snprintf(conn,
  8214. &truncated,
  8215. href,
  8216. sizeof(href),
  8217. "%s%s",
  8218. conn->request_info.local_uri,
  8219. de->file_name);
  8220. if (!truncated) {
  8221. mg_url_encode(href, href_encoded, PATH_MAX * 3);
  8222. print_props(conn, href_encoded, &de->file);
  8223. }
  8224. }
  8225. static void
  8226. handle_propfind(struct mg_connection *conn,
  8227. const char *path,
  8228. struct mg_file_stat *filep)
  8229. {
  8230. const char *depth = mg_get_header(conn, "Depth");
  8231. char date[64];
  8232. time_t curtime = time(NULL);
  8233. gmt_time_string(date, sizeof(date), &curtime);
  8234. if (!conn || !path || !filep || !conn->ctx) {
  8235. return;
  8236. }
  8237. conn->must_close = 1;
  8238. conn->status_code = 207;
  8239. mg_printf(conn,
  8240. "HTTP/1.1 207 Multi-Status\r\n"
  8241. "Date: %s\r\n",
  8242. date);
  8243. send_static_cache_header(conn);
  8244. send_additional_header(conn);
  8245. mg_printf(conn,
  8246. "Connection: %s\r\n"
  8247. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  8248. suggest_connection_header(conn));
  8249. conn->num_bytes_sent +=
  8250. mg_printf(conn,
  8251. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  8252. "<d:multistatus xmlns:d='DAV:'>\n");
  8253. /* Print properties for the requested resource itself */
  8254. print_props(conn, conn->request_info.local_uri, filep);
  8255. /* If it is a directory, print directory entries too if Depth is not 0 */
  8256. if (filep && filep->is_directory
  8257. && !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")
  8258. && (depth == NULL || strcmp(depth, "0") != 0)) {
  8259. scan_directory(conn, path, conn, &print_dav_dir_entry);
  8260. }
  8261. conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");
  8262. }
  8263. #endif
  8264. void
  8265. mg_lock_connection(struct mg_connection *conn)
  8266. {
  8267. if (conn) {
  8268. (void)pthread_mutex_lock(&conn->mutex);
  8269. }
  8270. }
  8271. void
  8272. mg_unlock_connection(struct mg_connection *conn)
  8273. {
  8274. if (conn) {
  8275. (void)pthread_mutex_unlock(&conn->mutex);
  8276. }
  8277. }
  8278. void
  8279. mg_lock_context(struct mg_context *ctx)
  8280. {
  8281. if (ctx) {
  8282. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  8283. }
  8284. }
  8285. void
  8286. mg_unlock_context(struct mg_context *ctx)
  8287. {
  8288. if (ctx) {
  8289. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  8290. }
  8291. }
  8292. #if defined(USE_TIMERS)
  8293. #include "timer.inl"
  8294. #endif /* USE_TIMERS */
  8295. #ifdef USE_LUA
  8296. #include "mod_lua.inl"
  8297. #endif /* USE_LUA */
  8298. #ifdef USE_DUKTAPE
  8299. #include "mod_duktape.inl"
  8300. #endif /* USE_DUKTAPE */
  8301. #if defined(USE_WEBSOCKET)
  8302. #if !defined(NO_SSL_DL)
  8303. #define SHA_API static
  8304. #include "sha1.inl"
  8305. #endif
  8306. static int
  8307. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  8308. {
  8309. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  8310. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  8311. SHA_CTX sha_ctx;
  8312. int truncated;
  8313. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  8314. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  8315. if (truncated) {
  8316. conn->must_close = 1;
  8317. return 0;
  8318. }
  8319. SHA1_Init(&sha_ctx);
  8320. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  8321. SHA1_Final((unsigned char *)sha, &sha_ctx);
  8322. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  8323. mg_printf(conn,
  8324. "HTTP/1.1 101 Switching Protocols\r\n"
  8325. "Upgrade: websocket\r\n"
  8326. "Connection: Upgrade\r\n"
  8327. "Sec-WebSocket-Accept: %s\r\n",
  8328. b64_sha);
  8329. if (conn->request_info.acceptedWebSocketSubprotocol) {
  8330. mg_printf(conn,
  8331. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  8332. conn->request_info.acceptedWebSocketSubprotocol);
  8333. } else {
  8334. mg_printf(conn, "%s", "\r\n");
  8335. }
  8336. return 1;
  8337. }
  8338. static void
  8339. read_websocket(struct mg_connection *conn,
  8340. mg_websocket_data_handler ws_data_handler,
  8341. void *callback_data)
  8342. {
  8343. /* Pointer to the beginning of the portion of the incoming websocket
  8344. * message queue.
  8345. * The original websocket upgrade request is never removed, so the queue
  8346. * begins after it. */
  8347. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  8348. int n, error, exit_by_callback;
  8349. /* body_len is the length of the entire queue in bytes
  8350. * len is the length of the current message
  8351. * data_len is the length of the current message's data payload
  8352. * header_len is the length of the current message's header */
  8353. size_t i, len, mask_len = 0, data_len = 0, header_len, body_len;
  8354. /* "The masking key is a 32-bit value chosen at random by the client."
  8355. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  8356. */
  8357. unsigned char mask[4];
  8358. /* data points to the place where the message is stored when passed to
  8359. * the
  8360. * websocket_data callback. This is either mem on the stack, or a
  8361. * dynamically allocated buffer if it is too large. */
  8362. unsigned char mem[4096];
  8363. unsigned char *data = mem;
  8364. unsigned char mop; /* mask flag and opcode */
  8365. double timeout = -1.0;
  8366. if (conn->ctx->config[WEBSOCKET_TIMEOUT]) {
  8367. timeout = atoi(conn->ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  8368. }
  8369. if ((timeout <= 0.0) && (conn->ctx->config[REQUEST_TIMEOUT])) {
  8370. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  8371. }
  8372. mg_set_thread_name("wsock");
  8373. /* Loop continuously, reading messages from the socket, invoking the
  8374. * callback, and waiting repeatedly until an error occurs. */
  8375. while (!conn->ctx->stop_flag) {
  8376. header_len = 0;
  8377. assert(conn->data_len >= conn->request_len);
  8378. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  8379. len = buf[1] & 127;
  8380. mask_len = (buf[1] & 128) ? 4 : 0;
  8381. if ((len < 126) && (body_len >= mask_len)) {
  8382. data_len = len;
  8383. header_len = 2 + mask_len;
  8384. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  8385. header_len = 4 + mask_len;
  8386. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  8387. } else if (body_len >= (10 + mask_len)) {
  8388. header_len = 10 + mask_len;
  8389. data_len = (((uint64_t)ntohl(*(uint32_t *)(void *)&buf[2]))
  8390. << 32) + ntohl(*(uint32_t *)(void *)&buf[6]);
  8391. }
  8392. }
  8393. if (header_len > 0 && body_len >= header_len) {
  8394. /* Allocate space to hold websocket payload */
  8395. data = mem;
  8396. if (data_len > sizeof(mem)) {
  8397. data = (unsigned char *)mg_malloc(data_len);
  8398. if (data == NULL) {
  8399. /* Allocation failed, exit the loop and then close the
  8400. * connection */
  8401. mg_cry(conn, "websocket out of memory; closing connection");
  8402. break;
  8403. }
  8404. }
  8405. /* Copy the mask before we shift the queue and destroy it */
  8406. if (mask_len > 0) {
  8407. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  8408. } else {
  8409. memset(mask, 0, sizeof(mask));
  8410. }
  8411. /* Read frame payload from the first message in the queue into
  8412. * data and advance the queue by moving the memory in place. */
  8413. assert(body_len >= header_len);
  8414. if (data_len + header_len > body_len) {
  8415. mop = buf[0]; /* current mask and opcode */
  8416. /* Overflow case */
  8417. len = body_len - header_len;
  8418. memcpy(data, buf + header_len, len);
  8419. error = 0;
  8420. while (len < data_len) {
  8421. n = pull_inner(NULL,
  8422. conn,
  8423. (char *)(data + len),
  8424. (int)(data_len - len),
  8425. timeout);
  8426. if (n <= -2) {
  8427. error = 1;
  8428. break;
  8429. } else if (n > 0) {
  8430. len += (size_t)n;
  8431. } else {
  8432. /* Timeout: should retry */
  8433. /* TODO: retry condition */
  8434. }
  8435. }
  8436. if (error) {
  8437. mg_cry(conn, "Websocket pull failed; closing connection");
  8438. break;
  8439. }
  8440. conn->data_len = conn->request_len;
  8441. } else {
  8442. mop = buf[0]; /* current mask and opcode, overwritten by
  8443. * memmove() */
  8444. /* Length of the message being read at the front of the
  8445. * queue */
  8446. len = data_len + header_len;
  8447. /* Copy the data payload into the data pointer for the
  8448. * callback */
  8449. memcpy(data, buf + header_len, data_len);
  8450. /* Move the queue forward len bytes */
  8451. memmove(buf, buf + len, body_len - len);
  8452. /* Mark the queue as advanced */
  8453. conn->data_len -= (int)len;
  8454. }
  8455. /* Apply mask if necessary */
  8456. if (mask_len > 0) {
  8457. for (i = 0; i < data_len; ++i) {
  8458. data[i] ^= mask[i & 3];
  8459. }
  8460. }
  8461. /* Exit the loop if callback signals to exit (server side),
  8462. * or "connection close" opcode received (client side). */
  8463. exit_by_callback = 0;
  8464. if ((ws_data_handler != NULL)
  8465. && !ws_data_handler(
  8466. conn, mop, (char *)data, data_len, callback_data)) {
  8467. exit_by_callback = 1;
  8468. }
  8469. if (data != mem) {
  8470. mg_free(data);
  8471. }
  8472. if (exit_by_callback
  8473. || ((mop & 0xf) == WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  8474. /* Opcode == 8, connection close */
  8475. break;
  8476. }
  8477. /* Not breaking the loop, process next websocket frame. */
  8478. } else {
  8479. /* Read from the socket into the next available location in the
  8480. * message queue. */
  8481. n = pull_inner(NULL,
  8482. conn,
  8483. conn->buf + conn->data_len,
  8484. conn->buf_size - conn->data_len,
  8485. timeout);
  8486. if (n <= -2) {
  8487. /* Error, no bytes read */
  8488. break;
  8489. }
  8490. if (n > 0) {
  8491. conn->data_len += n;
  8492. } else {
  8493. /* Timeout: should retry */
  8494. /* TODO: get timeout def */
  8495. }
  8496. }
  8497. }
  8498. mg_set_thread_name("worker");
  8499. }
  8500. static int
  8501. mg_websocket_write_exec(struct mg_connection *conn,
  8502. int opcode,
  8503. const char *data,
  8504. size_t dataLen,
  8505. uint32_t masking_key)
  8506. {
  8507. unsigned char header[14];
  8508. size_t headerLen = 1;
  8509. int retval = -1;
  8510. #if defined(__GNUC__) || defined(__MINGW32__)
  8511. /* Disable spurious conversion warning for GCC */
  8512. #pragma GCC diagnostic push
  8513. #pragma GCC diagnostic ignored "-Wconversion"
  8514. #endif
  8515. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  8516. #if defined(__GNUC__) || defined(__MINGW32__)
  8517. #pragma GCC diagnostic pop
  8518. #endif
  8519. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  8520. if (dataLen < 126) {
  8521. /* inline 7-bit length field */
  8522. header[1] = (unsigned char)dataLen;
  8523. headerLen = 2;
  8524. } else if (dataLen <= 0xFFFF) {
  8525. /* 16-bit length field */
  8526. uint16_t len = htons((uint16_t)dataLen);
  8527. header[1] = 126;
  8528. memcpy(header + 2, &len, 2);
  8529. headerLen = 4;
  8530. } else {
  8531. /* 64-bit length field */
  8532. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  8533. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  8534. header[1] = 127;
  8535. memcpy(header + 2, &len1, 4);
  8536. memcpy(header + 6, &len2, 4);
  8537. headerLen = 10;
  8538. }
  8539. if (masking_key) {
  8540. /* add mask */
  8541. header[1] |= 0x80;
  8542. memcpy(header + headerLen, &masking_key, 4);
  8543. headerLen += 4;
  8544. }
  8545. /* Note that POSIX/Winsock's send() is threadsafe
  8546. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  8547. * but mongoose's mg_printf/mg_write is not (because of the loop in
  8548. * push(), although that is only a problem if the packet is large or
  8549. * outgoing buffer is full). */
  8550. (void)mg_lock_connection(conn);
  8551. retval = mg_write(conn, header, headerLen);
  8552. if (dataLen > 0) {
  8553. retval = mg_write(conn, data, dataLen);
  8554. }
  8555. mg_unlock_connection(conn);
  8556. return retval;
  8557. }
  8558. int
  8559. mg_websocket_write(struct mg_connection *conn,
  8560. int opcode,
  8561. const char *data,
  8562. size_t dataLen)
  8563. {
  8564. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  8565. }
  8566. static void
  8567. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  8568. {
  8569. size_t i = 0;
  8570. i = 0;
  8571. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  8572. /* Convert in 32 bit words, if data is 4 byte aligned */
  8573. while (i < (in_len - 3)) {
  8574. *(uint32_t *)(void *)(out + i) =
  8575. *(uint32_t *)(void *)(in + i) ^ masking_key;
  8576. i += 4;
  8577. }
  8578. }
  8579. if (i != in_len) {
  8580. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  8581. while (i < in_len) {
  8582. *(uint8_t *)(void *)(out + i) =
  8583. *(uint8_t *)(void *)(in + i)
  8584. ^ *(((uint8_t *)&masking_key) + (i % 4));
  8585. i++;
  8586. }
  8587. }
  8588. }
  8589. int
  8590. mg_websocket_client_write(struct mg_connection *conn,
  8591. int opcode,
  8592. const char *data,
  8593. size_t dataLen)
  8594. {
  8595. int retval = -1;
  8596. char *masked_data = (char *)mg_malloc(((dataLen + 7) / 4) * 4);
  8597. uint32_t masking_key = (uint32_t)get_random();
  8598. if (masked_data == NULL) {
  8599. /* Return -1 in an error case */
  8600. mg_cry(conn,
  8601. "Cannot allocate buffer for masked websocket response: "
  8602. "Out of memory");
  8603. return -1;
  8604. }
  8605. mask_data(data, dataLen, masking_key, masked_data);
  8606. retval = mg_websocket_write_exec(
  8607. conn, opcode, masked_data, dataLen, masking_key);
  8608. mg_free(masked_data);
  8609. return retval;
  8610. }
  8611. static void
  8612. handle_websocket_request(struct mg_connection *conn,
  8613. const char *path,
  8614. int is_callback_resource,
  8615. struct mg_websocket_subprotocols *subprotocols,
  8616. mg_websocket_connect_handler ws_connect_handler,
  8617. mg_websocket_ready_handler ws_ready_handler,
  8618. mg_websocket_data_handler ws_data_handler,
  8619. mg_websocket_close_handler ws_close_handler,
  8620. void *cbData)
  8621. {
  8622. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  8623. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  8624. int lua_websock = 0;
  8625. #if !defined(USE_LUA)
  8626. (void)path;
  8627. #endif
  8628. /* Step 1: Check websocket protocol version. */
  8629. /* Step 1.1: Check Sec-WebSocket-Key. */
  8630. if (!websock_key) {
  8631. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  8632. * requires a Sec-WebSocket-Key header.
  8633. */
  8634. /* It could be the hixie draft version
  8635. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  8636. */
  8637. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  8638. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  8639. char key3[8];
  8640. if ((key1 != NULL) && (key2 != NULL)) {
  8641. /* This version uses 8 byte body data in a GET request */
  8642. conn->content_len = 8;
  8643. if (8 == mg_read(conn, key3, 8)) {
  8644. /* This is the hixie version */
  8645. send_http_error(conn,
  8646. 426,
  8647. "%s",
  8648. "Protocol upgrade to RFC 6455 required");
  8649. return;
  8650. }
  8651. }
  8652. /* This is an unknown version */
  8653. send_http_error(conn, 400, "%s", "Malformed websocket request");
  8654. return;
  8655. }
  8656. /* Step 1.2: Check websocket protocol version. */
  8657. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  8658. if (version == NULL || strcmp(version, "13") != 0) {
  8659. /* Reject wrong versions */
  8660. send_http_error(conn, 426, "%s", "Protocol upgrade required");
  8661. return;
  8662. }
  8663. /* Step 1.3: Could check for "Host", but we do not really nead this
  8664. * value for anything, so just ignore it. */
  8665. /* Step 2: If a callback is responsible, call it. */
  8666. if (is_callback_resource) {
  8667. /* Step 2.1 check and select subprotocol */
  8668. const char *protocol = mg_get_header(conn, "Sec-WebSocket-Protocol");
  8669. if (protocol && subprotocols) {
  8670. int idx;
  8671. unsigned long len;
  8672. const char *sep, *curSubProtocol,
  8673. *acceptedWebSocketSubprotocol = NULL;
  8674. /* look for matching subprotocol */
  8675. do {
  8676. sep = strchr(protocol, ',');
  8677. curSubProtocol = protocol;
  8678. len = sep ? (unsigned long)(sep - protocol)
  8679. : (unsigned long)strlen(protocol);
  8680. while (sep && isspace(*++sep)) {
  8681. ; /* ignore leading whitespaces */
  8682. }
  8683. protocol = sep;
  8684. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  8685. if ((strlen(subprotocols->subprotocols[idx]) == len)
  8686. && (strncmp(curSubProtocol,
  8687. subprotocols->subprotocols[idx],
  8688. len) == 0)) {
  8689. acceptedWebSocketSubprotocol =
  8690. subprotocols->subprotocols[idx];
  8691. break;
  8692. }
  8693. }
  8694. } while (sep && !acceptedWebSocketSubprotocol);
  8695. conn->request_info.acceptedWebSocketSubprotocol =
  8696. acceptedWebSocketSubprotocol;
  8697. } else if (protocol) {
  8698. /* keep legacy behavior */
  8699. /* The protocol is a comma seperated list of names. */
  8700. /* The server must only return one value from this list. */
  8701. /* First check if it is a list or just a single value. */
  8702. const char *sep = strrchr(protocol, ',');
  8703. if (sep == NULL) {
  8704. /* Just a single protocol -> accept it. */
  8705. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  8706. } else {
  8707. /* Multiple protocols -> accept the last one. */
  8708. /* This is just a quick fix if the client offers multiple
  8709. * protocols. The handler should have a list of accepted
  8710. * protocols on his own
  8711. * and use it to select one protocol among those the client has
  8712. * offered.
  8713. */
  8714. while (isspace(*++sep)) {
  8715. ; /* ignore leading whitespaces */
  8716. }
  8717. conn->request_info.acceptedWebSocketSubprotocol = sep;
  8718. }
  8719. }
  8720. if (ws_connect_handler != NULL
  8721. && ws_connect_handler(conn, cbData) != 0) {
  8722. /* C callback has returned non-zero, do not proceed with
  8723. * handshake.
  8724. */
  8725. /* Note that C callbacks are no longer called when Lua is
  8726. * responsible, so C can no longer filter callbacks for Lua. */
  8727. return;
  8728. }
  8729. }
  8730. #if defined(USE_LUA)
  8731. /* Step 3: No callback. Check if Lua is responsible. */
  8732. else {
  8733. /* Step 3.1: Check if Lua is responsible. */
  8734. if (conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  8735. lua_websock =
  8736. match_prefix(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  8737. strlen(
  8738. conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  8739. path);
  8740. }
  8741. if (lua_websock) {
  8742. /* Step 3.2: Lua is responsible: call it. */
  8743. conn->lua_websocket_state = lua_websocket_new(path, conn);
  8744. if (!conn->lua_websocket_state) {
  8745. /* Lua rejected the new client */
  8746. return;
  8747. }
  8748. }
  8749. }
  8750. #endif
  8751. /* Step 4: Check if there is a responsible websocket handler. */
  8752. if (!is_callback_resource && !lua_websock) {
  8753. /* There is no callback, and Lua is not responsible either. */
  8754. /* Reply with a 404 Not Found. We are still at a standard
  8755. * HTTP request here, before the websocket handshake, so
  8756. * we can still send standard HTTP error replies. */
  8757. send_http_error(conn, 404, "%s", "Not found");
  8758. return;
  8759. }
  8760. /* Step 5: The websocket connection has been accepted */
  8761. if (!send_websocket_handshake(conn, websock_key)) {
  8762. send_http_error(conn, 500, "%s", "Websocket handshake failed");
  8763. return;
  8764. }
  8765. /* Step 6: Call the ready handler */
  8766. if (is_callback_resource) {
  8767. if (ws_ready_handler != NULL) {
  8768. ws_ready_handler(conn, cbData);
  8769. }
  8770. #if defined(USE_LUA)
  8771. } else if (lua_websock) {
  8772. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  8773. /* the ready handler returned false */
  8774. return;
  8775. }
  8776. #endif
  8777. }
  8778. /* Step 7: Enter the read loop */
  8779. if (is_callback_resource) {
  8780. read_websocket(conn, ws_data_handler, cbData);
  8781. #if defined(USE_LUA)
  8782. } else if (lua_websock) {
  8783. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  8784. #endif
  8785. }
  8786. /* Step 8: Call the close handler */
  8787. if (ws_close_handler) {
  8788. ws_close_handler(conn, cbData);
  8789. }
  8790. }
  8791. static int
  8792. is_websocket_protocol(const struct mg_connection *conn)
  8793. {
  8794. const char *upgrade, *connection;
  8795. /* A websocket protocoll has the following HTTP headers:
  8796. *
  8797. * Connection: Upgrade
  8798. * Upgrade: Websocket
  8799. */
  8800. upgrade = mg_get_header(conn, "Upgrade");
  8801. if (upgrade == NULL) {
  8802. return 0; /* fail early, don't waste time checking other header
  8803. * fields
  8804. */
  8805. }
  8806. if (!mg_strcasestr(upgrade, "websocket")) {
  8807. return 0;
  8808. }
  8809. connection = mg_get_header(conn, "Connection");
  8810. if (connection == NULL) {
  8811. return 0;
  8812. }
  8813. if (!mg_strcasestr(connection, "upgrade")) {
  8814. return 0;
  8815. }
  8816. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  8817. * "Sec-WebSocket-Version" are also required.
  8818. * Don't check them here, since even an unsupported websocket protocol
  8819. * request still IS a websocket request (in contrast to a standard HTTP
  8820. * request). It will fail later in handle_websocket_request.
  8821. */
  8822. return 1;
  8823. }
  8824. #endif /* !USE_WEBSOCKET */
  8825. static int
  8826. isbyte(int n)
  8827. {
  8828. return n >= 0 && n <= 255;
  8829. }
  8830. static int
  8831. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  8832. {
  8833. int n, a, b, c, d, slash = 32, len = 0;
  8834. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5
  8835. || sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) && isbyte(a)
  8836. && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0
  8837. && slash < 33) {
  8838. len = n;
  8839. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  8840. | (uint32_t)d;
  8841. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  8842. }
  8843. return len;
  8844. }
  8845. static int
  8846. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  8847. {
  8848. int throttle = 0;
  8849. struct vec vec, val;
  8850. uint32_t net, mask;
  8851. char mult;
  8852. double v;
  8853. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  8854. mult = ',';
  8855. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  8856. || (v < 0) || ((lowercase(&mult) != 'k')
  8857. && (lowercase(&mult) != 'm') && (mult != ','))) {
  8858. continue;
  8859. }
  8860. v *= (lowercase(&mult) == 'k')
  8861. ? 1024
  8862. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  8863. if (vec.len == 1 && vec.ptr[0] == '*') {
  8864. throttle = (int)v;
  8865. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  8866. if ((remote_ip & mask) == net) {
  8867. throttle = (int)v;
  8868. }
  8869. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  8870. throttle = (int)v;
  8871. }
  8872. }
  8873. return throttle;
  8874. }
  8875. static uint32_t
  8876. get_remote_ip(const struct mg_connection *conn)
  8877. {
  8878. if (!conn) {
  8879. return 0;
  8880. }
  8881. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  8882. }
  8883. /* The mg_upload function is superseeded by mg_handle_form_request. */
  8884. #include "handle_form.inl"
  8885. #if defined(MG_LEGACY_INTERFACE)
  8886. /* Implement the deprecated mg_upload function by calling the new
  8887. * mg_handle_form_request function. While mg_upload could only handle
  8888. * HTML forms sent as POST request in multipart/form-data format
  8889. * containing only file input elements, mg_handle_form_request can
  8890. * handle all form input elements and all standard request methods. */
  8891. struct mg_upload_user_data {
  8892. struct mg_connection *conn;
  8893. const char *destination_dir;
  8894. int num_uploaded_files;
  8895. };
  8896. /* Helper function for deprecated mg_upload. */
  8897. static int
  8898. mg_upload_field_found(const char *key,
  8899. const char *filename,
  8900. char *path,
  8901. size_t pathlen,
  8902. void *user_data)
  8903. {
  8904. int truncated = 0;
  8905. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  8906. (void)key;
  8907. if (!filename) {
  8908. mg_cry(fud->conn, "%s: No filename set", __func__);
  8909. return FORM_FIELD_STORAGE_ABORT;
  8910. }
  8911. mg_snprintf(fud->conn,
  8912. &truncated,
  8913. path,
  8914. pathlen - 1,
  8915. "%s/%s",
  8916. fud->destination_dir,
  8917. filename);
  8918. if (!truncated) {
  8919. mg_cry(fud->conn, "%s: File path too long", __func__);
  8920. return FORM_FIELD_STORAGE_ABORT;
  8921. }
  8922. return FORM_FIELD_STORAGE_STORE;
  8923. }
  8924. /* Helper function for deprecated mg_upload. */
  8925. static int
  8926. mg_upload_field_get(const char *key,
  8927. const char *value,
  8928. size_t value_size,
  8929. void *user_data)
  8930. {
  8931. /* Function should never be called */
  8932. (void)key;
  8933. (void)value;
  8934. (void)value_size;
  8935. (void)user_data;
  8936. return 0;
  8937. }
  8938. /* Helper function for deprecated mg_upload. */
  8939. static int
  8940. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  8941. {
  8942. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  8943. (void)file_size;
  8944. fud->num_uploaded_files++;
  8945. fud->conn->ctx->callbacks.upload(fud->conn, path);
  8946. return 0;
  8947. }
  8948. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  8949. int
  8950. mg_upload(struct mg_connection *conn, const char *destination_dir)
  8951. {
  8952. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  8953. struct mg_form_data_handler fdh = {mg_upload_field_found,
  8954. mg_upload_field_get,
  8955. mg_upload_field_stored,
  8956. 0};
  8957. int ret;
  8958. fdh.user_data = (void *)&fud;
  8959. ret = mg_handle_form_request(conn, &fdh);
  8960. if (ret < 0) {
  8961. mg_cry(conn, "%s: Error while parsing the request", __func__);
  8962. }
  8963. return fud.num_uploaded_files;
  8964. }
  8965. #endif
  8966. static int
  8967. get_first_ssl_listener_index(const struct mg_context *ctx)
  8968. {
  8969. unsigned int i;
  8970. int idx = -1;
  8971. if (ctx) {
  8972. for (i = 0; idx == -1 && i < ctx->num_listening_sockets; i++) {
  8973. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  8974. }
  8975. }
  8976. return idx;
  8977. }
  8978. static void
  8979. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  8980. {
  8981. char host[1025];
  8982. const char *host_header;
  8983. size_t hostlen;
  8984. host_header = mg_get_header(conn, "Host");
  8985. hostlen = sizeof(host);
  8986. if (host_header != NULL) {
  8987. char *pos;
  8988. mg_strlcpy(host, host_header, hostlen);
  8989. host[hostlen - 1] = '\0';
  8990. pos = strchr(host, ':');
  8991. if (pos != NULL) {
  8992. *pos = '\0';
  8993. }
  8994. } else {
  8995. /* Cannot get host from the Host: header.
  8996. * Fallback to our IP address. */
  8997. if (conn) {
  8998. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  8999. }
  9000. }
  9001. /* Send host, port, uri and (if it exists) ?query_string */
  9002. if (conn) {
  9003. mg_printf(conn,
  9004. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  9005. host,
  9006. #if defined(USE_IPV6)
  9007. (conn->ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  9008. == AF_INET6)
  9009. ? (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  9010. .lsa.sin6.sin6_port)
  9011. :
  9012. #endif
  9013. (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  9014. .lsa.sin.sin_port),
  9015. conn->request_info.local_uri,
  9016. (conn->request_info.query_string == NULL) ? "" : "?",
  9017. (conn->request_info.query_string == NULL)
  9018. ? ""
  9019. : conn->request_info.query_string);
  9020. }
  9021. }
  9022. static void
  9023. mg_set_handler_type(struct mg_context *ctx,
  9024. const char *uri,
  9025. int handler_type,
  9026. int is_delete_request,
  9027. mg_request_handler handler,
  9028. struct mg_websocket_subprotocols *subprotocols,
  9029. mg_websocket_connect_handler connect_handler,
  9030. mg_websocket_ready_handler ready_handler,
  9031. mg_websocket_data_handler data_handler,
  9032. mg_websocket_close_handler close_handler,
  9033. mg_authorization_handler auth_handler,
  9034. void *cbdata)
  9035. {
  9036. struct mg_handler_info *tmp_rh, **lastref;
  9037. size_t urilen = strlen(uri);
  9038. if (handler_type == WEBSOCKET_HANDLER) {
  9039. /* assert(handler == NULL); */
  9040. /* assert(is_delete_request || connect_handler!=NULL ||
  9041. * ready_handler!=NULL || data_handler!=NULL ||
  9042. * close_handler!=NULL);
  9043. */
  9044. /* assert(auth_handler == NULL); */
  9045. if (handler != NULL) {
  9046. return;
  9047. }
  9048. if (!is_delete_request && connect_handler == NULL
  9049. && ready_handler == NULL
  9050. && data_handler == NULL
  9051. && close_handler == NULL) {
  9052. return;
  9053. }
  9054. if (auth_handler != NULL) {
  9055. return;
  9056. }
  9057. } else if (handler_type == REQUEST_HANDLER) {
  9058. /* assert(connect_handler==NULL && ready_handler==NULL &&
  9059. * data_handler==NULL && close_handler==NULL); */
  9060. /* assert(is_delete_request || (handler!=NULL));
  9061. */
  9062. /* assert(auth_handler == NULL); */
  9063. if (connect_handler != NULL || ready_handler != NULL
  9064. || data_handler != NULL
  9065. || close_handler != NULL) {
  9066. return;
  9067. }
  9068. if (!is_delete_request && (handler == NULL)) {
  9069. return;
  9070. }
  9071. if (auth_handler != NULL) {
  9072. return;
  9073. }
  9074. } else { /* AUTH_HANDLER */
  9075. /* assert(handler == NULL); */
  9076. /* assert(connect_handler==NULL && ready_handler==NULL &&
  9077. * data_handler==NULL && close_handler==NULL); */
  9078. /* assert(auth_handler != NULL); */
  9079. if (handler != NULL) {
  9080. return;
  9081. }
  9082. if (connect_handler != NULL || ready_handler != NULL
  9083. || data_handler != NULL
  9084. || close_handler != NULL) {
  9085. return;
  9086. }
  9087. if (!is_delete_request && (auth_handler == NULL)) {
  9088. return;
  9089. }
  9090. }
  9091. if (!ctx) {
  9092. return;
  9093. }
  9094. mg_lock_context(ctx);
  9095. /* first try to find an existing handler */
  9096. lastref = &(ctx->handlers);
  9097. for (tmp_rh = ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  9098. if (tmp_rh->handler_type == handler_type) {
  9099. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  9100. if (!is_delete_request) {
  9101. /* update existing handler */
  9102. if (handler_type == REQUEST_HANDLER) {
  9103. tmp_rh->handler = handler;
  9104. } else if (handler_type == WEBSOCKET_HANDLER) {
  9105. tmp_rh->subprotocols = subprotocols;
  9106. tmp_rh->connect_handler = connect_handler;
  9107. tmp_rh->ready_handler = ready_handler;
  9108. tmp_rh->data_handler = data_handler;
  9109. tmp_rh->close_handler = close_handler;
  9110. } else { /* AUTH_HANDLER */
  9111. tmp_rh->auth_handler = auth_handler;
  9112. }
  9113. tmp_rh->cbdata = cbdata;
  9114. } else {
  9115. /* remove existing handler */
  9116. *lastref = tmp_rh->next;
  9117. mg_free(tmp_rh->uri);
  9118. mg_free(tmp_rh);
  9119. }
  9120. mg_unlock_context(ctx);
  9121. return;
  9122. }
  9123. }
  9124. lastref = &(tmp_rh->next);
  9125. }
  9126. if (is_delete_request) {
  9127. /* no handler to set, this was a remove request to a non-existing
  9128. * handler */
  9129. mg_unlock_context(ctx);
  9130. return;
  9131. }
  9132. tmp_rh =
  9133. (struct mg_handler_info *)mg_calloc(sizeof(struct mg_handler_info), 1);
  9134. if (tmp_rh == NULL) {
  9135. mg_unlock_context(ctx);
  9136. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  9137. return;
  9138. }
  9139. tmp_rh->uri = mg_strdup(uri);
  9140. if (!tmp_rh->uri) {
  9141. mg_unlock_context(ctx);
  9142. mg_free(tmp_rh);
  9143. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  9144. return;
  9145. }
  9146. tmp_rh->uri_len = urilen;
  9147. if (handler_type == REQUEST_HANDLER) {
  9148. tmp_rh->handler = handler;
  9149. } else if (handler_type == WEBSOCKET_HANDLER) {
  9150. tmp_rh->subprotocols = subprotocols;
  9151. tmp_rh->connect_handler = connect_handler;
  9152. tmp_rh->ready_handler = ready_handler;
  9153. tmp_rh->data_handler = data_handler;
  9154. tmp_rh->close_handler = close_handler;
  9155. } else { /* AUTH_HANDLER */
  9156. tmp_rh->auth_handler = auth_handler;
  9157. }
  9158. tmp_rh->cbdata = cbdata;
  9159. tmp_rh->handler_type = handler_type;
  9160. tmp_rh->next = NULL;
  9161. *lastref = tmp_rh;
  9162. mg_unlock_context(ctx);
  9163. }
  9164. void
  9165. mg_set_request_handler(struct mg_context *ctx,
  9166. const char *uri,
  9167. mg_request_handler handler,
  9168. void *cbdata)
  9169. {
  9170. mg_set_handler_type(ctx,
  9171. uri,
  9172. REQUEST_HANDLER,
  9173. handler == NULL,
  9174. handler,
  9175. NULL,
  9176. NULL,
  9177. NULL,
  9178. NULL,
  9179. NULL,
  9180. NULL,
  9181. cbdata);
  9182. }
  9183. void
  9184. mg_set_websocket_handler(struct mg_context *ctx,
  9185. const char *uri,
  9186. mg_websocket_connect_handler connect_handler,
  9187. mg_websocket_ready_handler ready_handler,
  9188. mg_websocket_data_handler data_handler,
  9189. mg_websocket_close_handler close_handler,
  9190. void *cbdata)
  9191. {
  9192. mg_set_websocket_handler_with_subprotocols(ctx,
  9193. uri,
  9194. NULL,
  9195. connect_handler,
  9196. ready_handler,
  9197. data_handler,
  9198. close_handler,
  9199. cbdata);
  9200. }
  9201. void
  9202. mg_set_websocket_handler_with_subprotocols(
  9203. struct mg_context *ctx,
  9204. const char *uri,
  9205. struct mg_websocket_subprotocols *subprotocols,
  9206. mg_websocket_connect_handler connect_handler,
  9207. mg_websocket_ready_handler ready_handler,
  9208. mg_websocket_data_handler data_handler,
  9209. mg_websocket_close_handler close_handler,
  9210. void *cbdata)
  9211. {
  9212. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  9213. && (data_handler == NULL)
  9214. && (close_handler == NULL);
  9215. mg_set_handler_type(ctx,
  9216. uri,
  9217. WEBSOCKET_HANDLER,
  9218. is_delete_request,
  9219. NULL,
  9220. subprotocols,
  9221. connect_handler,
  9222. ready_handler,
  9223. data_handler,
  9224. close_handler,
  9225. NULL,
  9226. cbdata);
  9227. }
  9228. void
  9229. mg_set_auth_handler(struct mg_context *ctx,
  9230. const char *uri,
  9231. mg_request_handler handler,
  9232. void *cbdata)
  9233. {
  9234. mg_set_handler_type(ctx,
  9235. uri,
  9236. AUTH_HANDLER,
  9237. handler == NULL,
  9238. NULL,
  9239. NULL,
  9240. NULL,
  9241. NULL,
  9242. NULL,
  9243. NULL,
  9244. handler,
  9245. cbdata);
  9246. }
  9247. static int
  9248. get_request_handler(struct mg_connection *conn,
  9249. int handler_type,
  9250. mg_request_handler *handler,
  9251. struct mg_websocket_subprotocols **subprotocols,
  9252. mg_websocket_connect_handler *connect_handler,
  9253. mg_websocket_ready_handler *ready_handler,
  9254. mg_websocket_data_handler *data_handler,
  9255. mg_websocket_close_handler *close_handler,
  9256. mg_authorization_handler *auth_handler,
  9257. void **cbdata)
  9258. {
  9259. const struct mg_request_info *request_info = mg_get_request_info(conn);
  9260. if (request_info) {
  9261. const char *uri = request_info->local_uri;
  9262. size_t urilen = strlen(uri);
  9263. struct mg_handler_info *tmp_rh;
  9264. if (!conn || !conn->ctx) {
  9265. return 0;
  9266. }
  9267. mg_lock_context(conn->ctx);
  9268. /* first try for an exact match */
  9269. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  9270. tmp_rh = tmp_rh->next) {
  9271. if (tmp_rh->handler_type == handler_type) {
  9272. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  9273. if (handler_type == WEBSOCKET_HANDLER) {
  9274. *subprotocols = tmp_rh->subprotocols;
  9275. *connect_handler = tmp_rh->connect_handler;
  9276. *ready_handler = tmp_rh->ready_handler;
  9277. *data_handler = tmp_rh->data_handler;
  9278. *close_handler = tmp_rh->close_handler;
  9279. } else if (handler_type == REQUEST_HANDLER) {
  9280. *handler = tmp_rh->handler;
  9281. } else { /* AUTH_HANDLER */
  9282. *auth_handler = tmp_rh->auth_handler;
  9283. }
  9284. *cbdata = tmp_rh->cbdata;
  9285. mg_unlock_context(conn->ctx);
  9286. return 1;
  9287. }
  9288. }
  9289. }
  9290. /* next try for a partial match, we will accept uri/something */
  9291. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  9292. tmp_rh = tmp_rh->next) {
  9293. if (tmp_rh->handler_type == handler_type) {
  9294. if (tmp_rh->uri_len < urilen && uri[tmp_rh->uri_len] == '/'
  9295. && memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0) {
  9296. if (handler_type == WEBSOCKET_HANDLER) {
  9297. *subprotocols = tmp_rh->subprotocols;
  9298. *connect_handler = tmp_rh->connect_handler;
  9299. *ready_handler = tmp_rh->ready_handler;
  9300. *data_handler = tmp_rh->data_handler;
  9301. *close_handler = tmp_rh->close_handler;
  9302. } else if (handler_type == REQUEST_HANDLER) {
  9303. *handler = tmp_rh->handler;
  9304. } else { /* AUTH_HANDLER */
  9305. *auth_handler = tmp_rh->auth_handler;
  9306. }
  9307. *cbdata = tmp_rh->cbdata;
  9308. mg_unlock_context(conn->ctx);
  9309. return 1;
  9310. }
  9311. }
  9312. }
  9313. /* finally try for pattern match */
  9314. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  9315. tmp_rh = tmp_rh->next) {
  9316. if (tmp_rh->handler_type == handler_type) {
  9317. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  9318. if (handler_type == WEBSOCKET_HANDLER) {
  9319. *subprotocols = tmp_rh->subprotocols;
  9320. *connect_handler = tmp_rh->connect_handler;
  9321. *ready_handler = tmp_rh->ready_handler;
  9322. *data_handler = tmp_rh->data_handler;
  9323. *close_handler = tmp_rh->close_handler;
  9324. } else if (handler_type == REQUEST_HANDLER) {
  9325. *handler = tmp_rh->handler;
  9326. } else { /* AUTH_HANDLER */
  9327. *auth_handler = tmp_rh->auth_handler;
  9328. }
  9329. *cbdata = tmp_rh->cbdata;
  9330. mg_unlock_context(conn->ctx);
  9331. return 1;
  9332. }
  9333. }
  9334. }
  9335. mg_unlock_context(conn->ctx);
  9336. }
  9337. return 0; /* none found */
  9338. }
  9339. /* Check if the script file is in a path, allowed for script files.
  9340. * This can be used if uploading files is possible not only for the server
  9341. * admin, and the upload mechanism does not check the file extension.
  9342. */
  9343. static int
  9344. is_in_script_path(const struct mg_connection *conn, const char *path)
  9345. {
  9346. /* TODO: Add config value for allowed script path.
  9347. * Default: All allowed. */
  9348. (void)conn;
  9349. (void)path;
  9350. return 1;
  9351. }
  9352. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  9353. static int
  9354. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  9355. void *cbdata)
  9356. {
  9357. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9358. if (pcallbacks->websocket_connect) {
  9359. return pcallbacks->websocket_connect(conn);
  9360. }
  9361. /* No handler set - assume "OK" */
  9362. return 0;
  9363. }
  9364. static void
  9365. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  9366. {
  9367. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9368. if (pcallbacks->websocket_ready) {
  9369. pcallbacks->websocket_ready(conn);
  9370. }
  9371. }
  9372. static int
  9373. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  9374. int bits,
  9375. char *data,
  9376. size_t len,
  9377. void *cbdata)
  9378. {
  9379. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9380. if (pcallbacks->websocket_data) {
  9381. return pcallbacks->websocket_data(conn, bits, data, len);
  9382. }
  9383. /* No handler set - assume "OK" */
  9384. return 1;
  9385. }
  9386. #endif
  9387. /* This is the heart of the Civetweb's logic.
  9388. * This function is called when the request is read, parsed and validated,
  9389. * and Civetweb must decide what action to take: serve a file, or
  9390. * a directory, or call embedded function, etcetera. */
  9391. static void
  9392. handle_request(struct mg_connection *conn)
  9393. {
  9394. struct mg_request_info *ri = &conn->request_info;
  9395. char path[PATH_MAX];
  9396. int uri_len, ssl_index;
  9397. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  9398. is_put_or_delete_request = 0, is_callback_resource = 0;
  9399. int i;
  9400. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9401. mg_request_handler callback_handler = NULL;
  9402. struct mg_websocket_subprotocols *subprotocols;
  9403. mg_websocket_connect_handler ws_connect_handler = NULL;
  9404. mg_websocket_ready_handler ws_ready_handler = NULL;
  9405. mg_websocket_data_handler ws_data_handler = NULL;
  9406. mg_websocket_close_handler ws_close_handler = NULL;
  9407. void *callback_data = NULL;
  9408. mg_authorization_handler auth_handler = NULL;
  9409. void *auth_callback_data = NULL;
  9410. #if !defined(NO_FILES)
  9411. time_t curtime = time(NULL);
  9412. char date[64];
  9413. #endif
  9414. path[0] = 0;
  9415. if (!ri) {
  9416. return;
  9417. }
  9418. /* 1. get the request url */
  9419. /* 1.1. split into url and query string */
  9420. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  9421. != NULL) {
  9422. *((char *)conn->request_info.query_string++) = '\0';
  9423. }
  9424. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  9425. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  9426. ssl_index = get_first_ssl_listener_index(conn->ctx);
  9427. if (ssl_index >= 0) {
  9428. redirect_to_https_port(conn, ssl_index);
  9429. } else {
  9430. /* A http to https forward port has been specified,
  9431. * but no https port to forward to. */
  9432. send_http_error(conn,
  9433. 503,
  9434. "%s",
  9435. "Error: SSL forward not configured properly");
  9436. mg_cry(conn, "Can not redirect to SSL, no SSL port available");
  9437. }
  9438. return;
  9439. }
  9440. uri_len = (int)strlen(ri->local_uri);
  9441. /* 1.3. decode url (if config says so) */
  9442. if (should_decode_url(conn)) {
  9443. mg_url_decode(
  9444. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  9445. }
  9446. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  9447. * not possible */
  9448. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  9449. /* step 1. completed, the url is known now */
  9450. uri_len = (int)strlen(ri->local_uri);
  9451. DEBUG_TRACE("URL: %s", ri->local_uri);
  9452. /* 3. if this ip has limited speed, set it for this connection */
  9453. conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
  9454. get_remote_ip(conn),
  9455. ri->local_uri);
  9456. /* 4. call a "handle everything" callback, if registered */
  9457. if (conn->ctx->callbacks.begin_request != NULL) {
  9458. /* Note that since V1.7 the "begin_request" function is called
  9459. * before an authorization check. If an authorization check is
  9460. * required, use a request_handler instead. */
  9461. i = conn->ctx->callbacks.begin_request(conn);
  9462. if (i > 0) {
  9463. /* callback already processed the request. Store the
  9464. return value as a status code for the access log. */
  9465. conn->status_code = i;
  9466. discard_unread_request_data(conn);
  9467. return;
  9468. } else if (i == 0) {
  9469. /* civetweb should process the request */
  9470. } else {
  9471. /* unspecified - may change with the next version */
  9472. return;
  9473. }
  9474. }
  9475. /* request not yet handled by a handler or redirect, so the request
  9476. * is processed here */
  9477. /* 5. interpret the url to find out how the request must be handled
  9478. */
  9479. /* 5.1. first test, if the request targets the regular http(s)://
  9480. * protocol namespace or the websocket ws(s):// protocol namespace.
  9481. */
  9482. is_websocket_request = is_websocket_protocol(conn);
  9483. /* 5.2. check if the request will be handled by a callback */
  9484. if (get_request_handler(conn,
  9485. is_websocket_request ? WEBSOCKET_HANDLER
  9486. : REQUEST_HANDLER,
  9487. &callback_handler,
  9488. &subprotocols,
  9489. &ws_connect_handler,
  9490. &ws_ready_handler,
  9491. &ws_data_handler,
  9492. &ws_close_handler,
  9493. NULL,
  9494. &callback_data)) {
  9495. /* 5.2.1. A callback will handle this request. All requests
  9496. * handled
  9497. * by a callback have to be considered as requests to a script
  9498. * resource. */
  9499. is_callback_resource = 1;
  9500. is_script_resource = 1;
  9501. is_put_or_delete_request = is_put_or_delete_method(conn);
  9502. } else {
  9503. no_callback_resource:
  9504. /* 5.2.2. No callback is responsible for this request. The URI
  9505. * addresses a file based resource (static content or Lua/cgi
  9506. * scripts in the file system). */
  9507. is_callback_resource = 0;
  9508. interpret_uri(conn,
  9509. path,
  9510. sizeof(path),
  9511. &file.stat,
  9512. &is_found,
  9513. &is_script_resource,
  9514. &is_websocket_request,
  9515. &is_put_or_delete_request);
  9516. }
  9517. /* 6. authorization check */
  9518. /* 6.1. a custom authorization handler is installed */
  9519. if (get_request_handler(conn,
  9520. AUTH_HANDLER,
  9521. NULL,
  9522. NULL,
  9523. NULL,
  9524. NULL,
  9525. NULL,
  9526. NULL,
  9527. &auth_handler,
  9528. &auth_callback_data)) {
  9529. if (!auth_handler(conn, auth_callback_data)) {
  9530. return;
  9531. }
  9532. } else if (is_put_or_delete_request && !is_script_resource
  9533. && !is_callback_resource) {
  9534. /* 6.2. this request is a PUT/DELETE to a real file */
  9535. /* 6.2.1. thus, the server must have real files */
  9536. #if defined(NO_FILES)
  9537. if (1) {
  9538. #else
  9539. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  9540. #endif
  9541. /* This server does not have any real files, thus the
  9542. * PUT/DELETE methods are not valid. */
  9543. send_http_error(conn,
  9544. 405,
  9545. "%s method not allowed",
  9546. conn->request_info.request_method);
  9547. return;
  9548. }
  9549. #if !defined(NO_FILES)
  9550. /* 6.2.2. Check if put authorization for static files is
  9551. * available.
  9552. */
  9553. if (!is_authorized_for_put(conn)) {
  9554. send_authorization_request(conn);
  9555. return;
  9556. }
  9557. #endif
  9558. } else {
  9559. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  9560. * or it is a PUT or DELETE request to a resource that does not
  9561. * correspond to a file. Check authorization. */
  9562. if (!check_authorization(conn, path)) {
  9563. send_authorization_request(conn);
  9564. return;
  9565. }
  9566. }
  9567. /* request is authorized or does not need authorization */
  9568. /* 7. check if there are request handlers for this uri */
  9569. if (is_callback_resource) {
  9570. if (!is_websocket_request) {
  9571. i = callback_handler(conn, callback_data);
  9572. if (i > 0) {
  9573. /* Do nothing, callback has served the request. Store
  9574. * the
  9575. * return value as status code for the log and discard
  9576. * all
  9577. * data from the client not used by the callback. */
  9578. conn->status_code = i;
  9579. discard_unread_request_data(conn);
  9580. } else {
  9581. /* TODO (high): what if the handler did NOT handle the
  9582. * request */
  9583. /* The last version did handle this as a file request,
  9584. * but
  9585. * since a file request is not always a script resource,
  9586. * the authorization check might be different */
  9587. interpret_uri(conn,
  9588. path,
  9589. sizeof(path),
  9590. &file.stat,
  9591. &is_found,
  9592. &is_script_resource,
  9593. &is_websocket_request,
  9594. &is_put_or_delete_request);
  9595. callback_handler = NULL;
  9596. /* Here we are at a dead end:
  9597. * According to URI matching, a callback should be
  9598. * responsible for handling the request,
  9599. * we called it, but the callback declared itself
  9600. * not responsible.
  9601. * We use a goto here, to get out of this dead end,
  9602. * and continue with the default handling.
  9603. * A goto here is simpler and better to understand
  9604. * than some curious loop. */
  9605. goto no_callback_resource;
  9606. }
  9607. } else {
  9608. #if defined(USE_WEBSOCKET)
  9609. handle_websocket_request(conn,
  9610. path,
  9611. is_callback_resource,
  9612. subprotocols,
  9613. ws_connect_handler,
  9614. ws_ready_handler,
  9615. ws_data_handler,
  9616. ws_close_handler,
  9617. callback_data);
  9618. #endif
  9619. }
  9620. return;
  9621. }
  9622. /* 8. handle websocket requests */
  9623. #if defined(USE_WEBSOCKET)
  9624. if (is_websocket_request) {
  9625. if (is_script_resource) {
  9626. if (is_in_script_path(conn, path)) {
  9627. /* Websocket Lua script */
  9628. handle_websocket_request(conn,
  9629. path,
  9630. 0 /* Lua Script */,
  9631. NULL,
  9632. NULL,
  9633. NULL,
  9634. NULL,
  9635. NULL,
  9636. &conn->ctx->callbacks);
  9637. } else {
  9638. /* Script was in an illegal path */
  9639. send_http_error(conn, 403, "%s", "Forbidden");
  9640. }
  9641. } else {
  9642. #if defined(MG_LEGACY_INTERFACE)
  9643. handle_websocket_request(
  9644. conn,
  9645. path,
  9646. !is_script_resource /* could be deprecated global callback */,
  9647. NULL,
  9648. deprecated_websocket_connect_wrapper,
  9649. deprecated_websocket_ready_wrapper,
  9650. deprecated_websocket_data_wrapper,
  9651. NULL,
  9652. &conn->ctx->callbacks);
  9653. #else
  9654. send_http_error(conn, 404, "%s", "Not found");
  9655. #endif
  9656. }
  9657. return;
  9658. } else
  9659. #endif
  9660. #if defined(NO_FILES)
  9661. /* 9a. In case the server uses only callbacks, this uri is
  9662. * unknown.
  9663. * Then, all request handling ends here. */
  9664. send_http_error(conn, 404, "%s", "Not Found");
  9665. #else
  9666. /* 9b. This request is either for a static file or resource handled
  9667. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  9668. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  9669. send_http_error(conn, 404, "%s", "Not Found");
  9670. return;
  9671. }
  9672. /* 10. File is handled by a script. */
  9673. if (is_script_resource) {
  9674. handle_file_based_request(conn, path, &file);
  9675. return;
  9676. }
  9677. /* 11. Handle put/delete/mkcol requests */
  9678. if (is_put_or_delete_request) {
  9679. /* 11.1. PUT method */
  9680. if (!strcmp(ri->request_method, "PUT")) {
  9681. put_file(conn, path);
  9682. return;
  9683. }
  9684. /* 11.2. DELETE method */
  9685. if (!strcmp(ri->request_method, "DELETE")) {
  9686. delete_file(conn, path);
  9687. return;
  9688. }
  9689. /* 11.3. MKCOL method */
  9690. if (!strcmp(ri->request_method, "MKCOL")) {
  9691. mkcol(conn, path);
  9692. return;
  9693. }
  9694. /* 11.4. PATCH method
  9695. * This method is not supported for static resources,
  9696. * only for scripts (Lua, CGI) and callbacks. */
  9697. send_http_error(conn,
  9698. 405,
  9699. "%s method not allowed",
  9700. conn->request_info.request_method);
  9701. return;
  9702. }
  9703. /* 11. File does not exist, or it was configured that it should be
  9704. * hidden */
  9705. if (!is_found || (must_hide_file(conn, path))) {
  9706. send_http_error(conn, 404, "%s", "Not found");
  9707. return;
  9708. }
  9709. /* 12. Directory uris should end with a slash */
  9710. if (file.stat.is_directory && (uri_len > 0)
  9711. && (ri->local_uri[uri_len - 1] != '/')) {
  9712. gmt_time_string(date, sizeof(date), &curtime);
  9713. mg_printf(conn,
  9714. "HTTP/1.1 301 Moved Permanently\r\n"
  9715. "Location: %s/\r\n"
  9716. "Date: %s\r\n"
  9717. /* "Cache-Control: private\r\n" (= default) */
  9718. "Content-Length: 0\r\n"
  9719. "Connection: %s\r\n",
  9720. ri->request_uri,
  9721. date,
  9722. suggest_connection_header(conn));
  9723. send_additional_header(conn);
  9724. mg_printf(conn, "\r\n");
  9725. return;
  9726. }
  9727. /* 13. Handle other methods than GET/HEAD */
  9728. /* 13.1. Handle PROPFIND */
  9729. if (!strcmp(ri->request_method, "PROPFIND")) {
  9730. handle_propfind(conn, path, &file.stat);
  9731. return;
  9732. }
  9733. /* 13.2. Handle OPTIONS for files */
  9734. if (!strcmp(ri->request_method, "OPTIONS")) {
  9735. /* This standard handler is only used for real files.
  9736. * Scripts should support the OPTIONS method themselves, to allow a
  9737. * maximum flexibility.
  9738. * Lua and CGI scripts may fully support CORS this way (including
  9739. * preflights). */
  9740. send_options(conn);
  9741. return;
  9742. }
  9743. /* 13.3. everything but GET and HEAD (e.g. POST) */
  9744. if (0 != strcmp(ri->request_method, "GET")
  9745. && 0 != strcmp(ri->request_method, "HEAD")) {
  9746. send_http_error(conn,
  9747. 405,
  9748. "%s method not allowed",
  9749. conn->request_info.request_method);
  9750. return;
  9751. }
  9752. /* 14. directories */
  9753. if (file.stat.is_directory) {
  9754. if (substitute_index_file(conn, path, sizeof(path), &file)) {
  9755. /* 14.1. use a substitute file */
  9756. /* TODO (high): substitute index may be a script resource.
  9757. * define what should be possible in this case. */
  9758. } else {
  9759. /* 14.2. no substitute file */
  9760. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  9761. "yes")) {
  9762. handle_directory_request(conn, path);
  9763. } else {
  9764. send_http_error(conn,
  9765. 403,
  9766. "%s",
  9767. "Error: Directory listing denied");
  9768. }
  9769. return;
  9770. }
  9771. }
  9772. handle_file_based_request(conn, path, &file);
  9773. #endif /* !defined(NO_FILES) */
  9774. #if 0
  9775. /* Perform redirect and auth checks before calling begin_request()
  9776. * handler.
  9777. * Otherwise, begin_request() would need to perform auth checks and
  9778. * redirects. */
  9779. #endif
  9780. }
  9781. static void
  9782. handle_file_based_request(struct mg_connection *conn,
  9783. const char *path,
  9784. struct mg_file *file)
  9785. {
  9786. if (!conn || !conn->ctx) {
  9787. return;
  9788. }
  9789. if (0) {
  9790. #ifdef USE_LUA
  9791. } else if (match_prefix(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  9792. strlen(
  9793. conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  9794. path) > 0) {
  9795. if (is_in_script_path(conn, path)) {
  9796. /* Lua server page: an SSI like page containing mostly plain html
  9797. * code
  9798. * plus some tags with server generated contents. */
  9799. handle_lsp_request(conn, path, file, NULL);
  9800. } else {
  9801. /* Script was in an illegal path */
  9802. send_http_error(conn, 403, "%s", "Forbidden");
  9803. }
  9804. } else if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  9805. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  9806. path) > 0) {
  9807. if (is_in_script_path(conn, path)) {
  9808. /* Lua in-server module script: a CGI like script used to generate
  9809. * the
  9810. * entire reply. */
  9811. mg_exec_lua_script(conn, path, NULL);
  9812. } else {
  9813. /* Script was in an illegal path */
  9814. send_http_error(conn, 403, "%s", "Forbidden");
  9815. }
  9816. #endif
  9817. #if defined(USE_DUKTAPE)
  9818. } else if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  9819. strlen(
  9820. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  9821. path) > 0) {
  9822. if (is_in_script_path(conn, path)) {
  9823. /* Call duktape to generate the page */
  9824. mg_exec_duktape_script(conn, path);
  9825. } else {
  9826. /* Script was in an illegal path */
  9827. send_http_error(conn, 403, "%s", "Forbidden");
  9828. }
  9829. #endif
  9830. #if !defined(NO_CGI)
  9831. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  9832. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  9833. path) > 0) {
  9834. if (is_in_script_path(conn, path)) {
  9835. /* CGI scripts may support all HTTP methods */
  9836. handle_cgi_request(conn, path);
  9837. } else {
  9838. /* Script was in an illegal path */
  9839. send_http_error(conn, 403, "%s", "Forbidden");
  9840. }
  9841. #endif /* !NO_CGI */
  9842. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  9843. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  9844. path) > 0) {
  9845. if (is_in_script_path(conn, path)) {
  9846. handle_ssi_file_request(conn, path, file);
  9847. } else {
  9848. /* Script was in an illegal path */
  9849. send_http_error(conn, 403, "%s", "Forbidden");
  9850. }
  9851. #if !defined(NO_CACHING)
  9852. } else if ((!conn->in_error_handler)
  9853. && is_not_modified(conn, &file->stat)) {
  9854. /* Send 304 "Not Modified" - this must not send any body data */
  9855. handle_not_modified_static_file_request(conn, file);
  9856. #endif /* !NO_CACHING */
  9857. } else {
  9858. handle_static_file_request(conn, path, file, NULL, NULL);
  9859. }
  9860. }
  9861. static void
  9862. close_all_listening_sockets(struct mg_context *ctx)
  9863. {
  9864. unsigned int i;
  9865. if (!ctx) {
  9866. return;
  9867. }
  9868. for (i = 0; i < ctx->num_listening_sockets; i++) {
  9869. closesocket(ctx->listening_sockets[i].sock);
  9870. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  9871. }
  9872. mg_free(ctx->listening_sockets);
  9873. ctx->listening_sockets = NULL;
  9874. mg_free(ctx->listening_socket_fds);
  9875. ctx->listening_socket_fds = NULL;
  9876. }
  9877. /* Valid listening port specification is: [ip_address:]port[s]
  9878. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  9879. * Examples for IPv6: [::]:80, [::1]:80,
  9880. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  9881. * see https://tools.ietf.org/html/rfc3513#section-2.2
  9882. * In order to bind to both, IPv4 and IPv6, you can either add
  9883. * both ports using 8080,[::]:8080, or the short form +8080.
  9884. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  9885. * one only accepting IPv4 the other only IPv6. +8080 creates
  9886. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  9887. * environment, they might work differently, or might not work
  9888. * at all - it must be tested what options work best in the
  9889. * relevant network environment.
  9890. */
  9891. static int
  9892. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  9893. {
  9894. unsigned int a, b, c, d, port;
  9895. int ch, len;
  9896. #if defined(USE_IPV6)
  9897. char buf[100] = {0};
  9898. #endif
  9899. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  9900. * Also, all-zeroes in the socket address means binding to all addresses
  9901. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  9902. memset(so, 0, sizeof(*so));
  9903. so->lsa.sin.sin_family = AF_INET;
  9904. *ip_version = 0;
  9905. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  9906. == 5) {
  9907. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  9908. so->lsa.sin.sin_addr.s_addr =
  9909. htonl((a << 24) | (b << 16) | (c << 8) | d);
  9910. so->lsa.sin.sin_port = htons((uint16_t)port);
  9911. *ip_version = 4;
  9912. #if defined(USE_IPV6)
  9913. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  9914. && mg_inet_pton(
  9915. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  9916. /* IPv6 address, examples: see above */
  9917. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  9918. */
  9919. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  9920. *ip_version = 6;
  9921. #endif
  9922. } else if ((vec->ptr[0] == '+')
  9923. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  9924. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  9925. /* Add 1 to len for the + character we skipped before */
  9926. len++;
  9927. #if defined(USE_IPV6)
  9928. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  9929. so->lsa.sin6.sin6_family = AF_INET6;
  9930. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  9931. *ip_version = 4 + 6;
  9932. #else
  9933. /* Bind to IPv4 only, since IPv6 is not built in. */
  9934. so->lsa.sin.sin_port = htons((uint16_t)port);
  9935. *ip_version = 4;
  9936. #endif
  9937. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  9938. /* If only port is specified, bind to IPv4, INADDR_ANY */
  9939. so->lsa.sin.sin_port = htons((uint16_t)port);
  9940. *ip_version = 4;
  9941. } else {
  9942. /* Parsing failure. Make port invalid. */
  9943. port = 0;
  9944. len = 0;
  9945. }
  9946. /* sscanf and the option splitting code ensure the following condition
  9947. */
  9948. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  9949. *ip_version = 0;
  9950. return 0;
  9951. }
  9952. ch = vec->ptr[len]; /* Next character after the port number */
  9953. so->is_ssl = (ch == 's');
  9954. so->ssl_redir = (ch == 'r');
  9955. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  9956. if (is_valid_port(port)
  9957. && (ch == '\0' || ch == 's' || ch == 'r' || ch == ',')) {
  9958. return 1;
  9959. }
  9960. /* Reset ip_version to 0 of there is an error */
  9961. *ip_version = 0;
  9962. return 0;
  9963. }
  9964. static int
  9965. set_ports_option(struct mg_context *ctx)
  9966. {
  9967. const char *list;
  9968. int on = 1;
  9969. #if defined(USE_IPV6)
  9970. int off = 0;
  9971. #endif
  9972. struct vec vec;
  9973. struct socket so, *ptr;
  9974. struct pollfd *pfd;
  9975. union usa usa;
  9976. socklen_t len;
  9977. int ip_version;
  9978. int portsTotal = 0;
  9979. int portsOk = 0;
  9980. if (!ctx) {
  9981. return 0;
  9982. }
  9983. memset(&so, 0, sizeof(so));
  9984. memset(&usa, 0, sizeof(usa));
  9985. len = sizeof(usa);
  9986. list = ctx->config[LISTENING_PORTS];
  9987. while ((list = next_option(list, &vec, NULL)) != NULL) {
  9988. portsTotal++;
  9989. if (!parse_port_string(&vec, &so, &ip_version)) {
  9990. mg_cry(fc(ctx),
  9991. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  9992. (int)vec.len,
  9993. vec.ptr,
  9994. portsTotal,
  9995. "[IP_ADDRESS:]PORT[s|r]");
  9996. continue;
  9997. }
  9998. #if !defined(NO_SSL)
  9999. if (so.is_ssl && ctx->ssl_ctx == NULL) {
  10000. mg_cry(fc(ctx),
  10001. "Cannot add SSL socket (entry %i). Is -ssl_certificate "
  10002. "option set?",
  10003. portsTotal);
  10004. continue;
  10005. }
  10006. #endif
  10007. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  10008. == INVALID_SOCKET) {
  10009. mg_cry(fc(ctx), "cannot create socket (entry %i)", portsTotal);
  10010. continue;
  10011. }
  10012. #ifdef _WIN32
  10013. /* Windows SO_REUSEADDR lets many procs binds to a
  10014. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  10015. * if someone already has the socket -- DTL */
  10016. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  10017. * Windows might need a few seconds before
  10018. * the same port can be used again in the
  10019. * same process, so a short Sleep may be
  10020. * required between mg_stop and mg_start.
  10021. */
  10022. if (setsockopt(so.sock,
  10023. SOL_SOCKET,
  10024. SO_EXCLUSIVEADDRUSE,
  10025. (SOCK_OPT_TYPE)&on,
  10026. sizeof(on)) != 0) {
  10027. /* Set reuse option, but don't abort on errors. */
  10028. mg_cry(fc(ctx),
  10029. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  10030. portsTotal);
  10031. }
  10032. #else
  10033. if (setsockopt(so.sock,
  10034. SOL_SOCKET,
  10035. SO_REUSEADDR,
  10036. (SOCK_OPT_TYPE)&on,
  10037. sizeof(on)) != 0) {
  10038. /* Set reuse option, but don't abort on errors. */
  10039. mg_cry(fc(ctx),
  10040. "cannot set socket option SO_REUSEADDR (entry %i)",
  10041. portsTotal);
  10042. }
  10043. #endif
  10044. if (ip_version > 4) {
  10045. #if defined(USE_IPV6)
  10046. if (ip_version == 6) {
  10047. if (so.lsa.sa.sa_family == AF_INET6
  10048. && setsockopt(so.sock,
  10049. IPPROTO_IPV6,
  10050. IPV6_V6ONLY,
  10051. (void *)&off,
  10052. sizeof(off)) != 0) {
  10053. /* Set IPv6 only option, but don't abort on errors. */
  10054. mg_cry(fc(ctx),
  10055. "cannot set socket option IPV6_V6ONLY (entry %i)",
  10056. portsTotal);
  10057. }
  10058. }
  10059. #else
  10060. mg_cry(fc(ctx), "IPv6 not available");
  10061. closesocket(so.sock);
  10062. so.sock = INVALID_SOCKET;
  10063. continue;
  10064. #endif
  10065. }
  10066. if (so.lsa.sa.sa_family == AF_INET) {
  10067. len = sizeof(so.lsa.sin);
  10068. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  10069. mg_cry(fc(ctx),
  10070. "cannot bind to %.*s: %d (%s)",
  10071. (int)vec.len,
  10072. vec.ptr,
  10073. (int)ERRNO,
  10074. strerror(errno));
  10075. closesocket(so.sock);
  10076. so.sock = INVALID_SOCKET;
  10077. continue;
  10078. }
  10079. }
  10080. #if defined(USE_IPV6)
  10081. else if (so.lsa.sa.sa_family == AF_INET6) {
  10082. len = sizeof(so.lsa.sin6);
  10083. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  10084. mg_cry(fc(ctx),
  10085. "cannot bind to IPv6 %.*s: %d (%s)",
  10086. (int)vec.len,
  10087. vec.ptr,
  10088. (int)ERRNO,
  10089. strerror(errno));
  10090. closesocket(so.sock);
  10091. so.sock = INVALID_SOCKET;
  10092. continue;
  10093. }
  10094. }
  10095. #endif
  10096. else {
  10097. mg_cry(fc(ctx),
  10098. "cannot bind: address family not supported (entry %i)",
  10099. portsTotal);
  10100. continue;
  10101. }
  10102. if (listen(so.sock, SOMAXCONN) != 0) {
  10103. mg_cry(fc(ctx),
  10104. "cannot listen to %.*s: %d (%s)",
  10105. (int)vec.len,
  10106. vec.ptr,
  10107. (int)ERRNO,
  10108. strerror(errno));
  10109. closesocket(so.sock);
  10110. so.sock = INVALID_SOCKET;
  10111. continue;
  10112. }
  10113. if (getsockname(so.sock, &(usa.sa), &len) != 0
  10114. || usa.sa.sa_family != so.lsa.sa.sa_family) {
  10115. int err = (int)ERRNO;
  10116. mg_cry(fc(ctx),
  10117. "call to getsockname failed %.*s: %d (%s)",
  10118. (int)vec.len,
  10119. vec.ptr,
  10120. err,
  10121. strerror(errno));
  10122. closesocket(so.sock);
  10123. so.sock = INVALID_SOCKET;
  10124. continue;
  10125. }
  10126. /* Update lsa port in case of random free ports */
  10127. #if defined(USE_IPV6)
  10128. if (so.lsa.sa.sa_family == AF_INET6) {
  10129. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  10130. } else
  10131. #endif
  10132. {
  10133. so.lsa.sin.sin_port = usa.sin.sin_port;
  10134. }
  10135. if ((ptr = (struct socket *)
  10136. mg_realloc(ctx->listening_sockets,
  10137. (ctx->num_listening_sockets + 1)
  10138. * sizeof(ctx->listening_sockets[0]))) == NULL) {
  10139. mg_cry(fc(ctx), "%s", "Out of memory");
  10140. closesocket(so.sock);
  10141. so.sock = INVALID_SOCKET;
  10142. continue;
  10143. }
  10144. if ((pfd = (struct pollfd *)mg_realloc(
  10145. ctx->listening_socket_fds,
  10146. (ctx->num_listening_sockets + 1)
  10147. * sizeof(ctx->listening_socket_fds[0]))) == NULL) {
  10148. mg_cry(fc(ctx), "%s", "Out of memory");
  10149. closesocket(so.sock);
  10150. so.sock = INVALID_SOCKET;
  10151. mg_free(ptr);
  10152. continue;
  10153. }
  10154. set_close_on_exec(so.sock, fc(ctx));
  10155. ctx->listening_sockets = ptr;
  10156. ctx->listening_sockets[ctx->num_listening_sockets] = so;
  10157. ctx->listening_socket_fds = pfd;
  10158. ctx->num_listening_sockets++;
  10159. portsOk++;
  10160. }
  10161. if (portsOk != portsTotal) {
  10162. close_all_listening_sockets(ctx);
  10163. portsOk = 0;
  10164. }
  10165. return portsOk;
  10166. }
  10167. static const char *
  10168. header_val(const struct mg_connection *conn, const char *header)
  10169. {
  10170. const char *header_value;
  10171. if ((header_value = mg_get_header(conn, header)) == NULL) {
  10172. return "-";
  10173. } else {
  10174. return header_value;
  10175. }
  10176. }
  10177. static void
  10178. log_access(const struct mg_connection *conn)
  10179. {
  10180. const struct mg_request_info *ri;
  10181. struct mg_file fi;
  10182. char date[64], src_addr[IP_ADDR_STR_LEN];
  10183. struct tm *tm;
  10184. const char *referer;
  10185. const char *user_agent;
  10186. char buf[4096];
  10187. if (!conn || !conn->ctx) {
  10188. return;
  10189. }
  10190. if (conn->ctx->config[ACCESS_LOG_FILE] != NULL) {
  10191. if (mg_fopen(conn,
  10192. conn->ctx->config[ACCESS_LOG_FILE],
  10193. MG_FOPEN_MODE_APPEND,
  10194. &fi) == 0) {
  10195. fi.access.fp = NULL;
  10196. }
  10197. } else {
  10198. fi.access.fp = NULL;
  10199. }
  10200. /* Log is written to a file and/or a callback. If both are not set,
  10201. * executing the rest of the function is pointless. */
  10202. if ((fi.access.fp == NULL) && (conn->ctx->callbacks.log_access == NULL)) {
  10203. return;
  10204. }
  10205. tm = localtime(&conn->conn_birth_time);
  10206. if (tm != NULL) {
  10207. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  10208. } else {
  10209. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  10210. date[sizeof(date) - 1] = '\0';
  10211. }
  10212. ri = &conn->request_info;
  10213. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  10214. referer = header_val(conn, "Referer");
  10215. user_agent = header_val(conn, "User-Agent");
  10216. mg_snprintf(conn,
  10217. NULL, /* Ignore truncation in access log */
  10218. buf,
  10219. sizeof(buf),
  10220. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  10221. src_addr,
  10222. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  10223. date,
  10224. ri->request_method ? ri->request_method : "-",
  10225. ri->request_uri ? ri->request_uri : "-",
  10226. ri->query_string ? "?" : "",
  10227. ri->query_string ? ri->query_string : "",
  10228. ri->http_version,
  10229. conn->status_code,
  10230. conn->num_bytes_sent,
  10231. referer,
  10232. user_agent);
  10233. if (conn->ctx->callbacks.log_access) {
  10234. conn->ctx->callbacks.log_access(conn, buf);
  10235. }
  10236. if (fi.access.fp) {
  10237. int ok = 1;
  10238. flockfile(fi.access.fp);
  10239. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  10240. ok = 0;
  10241. }
  10242. if (fflush(fi.access.fp) != 0) {
  10243. ok = 0;
  10244. }
  10245. funlockfile(fi.access.fp);
  10246. if (mg_fclose(&fi.access) != 0) {
  10247. ok = 0;
  10248. }
  10249. if (!ok) {
  10250. mg_cry(conn,
  10251. "Error writing log file %s",
  10252. conn->ctx->config[ACCESS_LOG_FILE]);
  10253. }
  10254. }
  10255. }
  10256. /* Verify given socket address against the ACL.
  10257. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  10258. */
  10259. static int
  10260. check_acl(struct mg_context *ctx, uint32_t remote_ip)
  10261. {
  10262. int allowed, flag;
  10263. uint32_t net, mask;
  10264. struct vec vec;
  10265. if (ctx) {
  10266. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  10267. /* If any ACL is set, deny by default */
  10268. allowed = (list == NULL) ? '+' : '-';
  10269. while ((list = next_option(list, &vec, NULL)) != NULL) {
  10270. flag = vec.ptr[0];
  10271. if ((flag != '+' && flag != '-')
  10272. || parse_net(&vec.ptr[1], &net, &mask) == 0) {
  10273. mg_cry(fc(ctx),
  10274. "%s: subnet must be [+|-]x.x.x.x[/x]",
  10275. __func__);
  10276. return -1;
  10277. }
  10278. if (net == (remote_ip & mask)) {
  10279. allowed = flag;
  10280. }
  10281. }
  10282. return allowed == '+';
  10283. }
  10284. return -1;
  10285. }
  10286. #if !defined(_WIN32)
  10287. static int
  10288. set_uid_option(struct mg_context *ctx)
  10289. {
  10290. struct passwd *pw;
  10291. if (ctx) {
  10292. const char *uid = ctx->config[RUN_AS_USER];
  10293. int success = 0;
  10294. if (uid == NULL) {
  10295. success = 1;
  10296. } else {
  10297. if ((pw = getpwnam(uid)) == NULL) {
  10298. mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  10299. } else if (setgid(pw->pw_gid) == -1) {
  10300. mg_cry(fc(ctx),
  10301. "%s: setgid(%s): %s",
  10302. __func__,
  10303. uid,
  10304. strerror(errno));
  10305. } else if (setgroups(0, NULL)) {
  10306. mg_cry(fc(ctx),
  10307. "%s: setgroups(): %s",
  10308. __func__,
  10309. strerror(errno));
  10310. } else if (setuid(pw->pw_uid) == -1) {
  10311. mg_cry(fc(ctx),
  10312. "%s: setuid(%s): %s",
  10313. __func__,
  10314. uid,
  10315. strerror(errno));
  10316. } else {
  10317. success = 1;
  10318. }
  10319. }
  10320. return success;
  10321. }
  10322. return 0;
  10323. }
  10324. #endif /* !_WIN32 */
  10325. static void
  10326. tls_dtor(void *key)
  10327. {
  10328. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  10329. /* key == pthread_getspecific(sTlsKey); */
  10330. if (tls) {
  10331. if (tls->is_master == 2) {
  10332. tls->is_master = -3; /* Mark memory as dead */
  10333. mg_free(tls);
  10334. }
  10335. }
  10336. pthread_setspecific(sTlsKey, NULL);
  10337. }
  10338. #if !defined(NO_SSL)
  10339. static int ssl_use_pem_file(struct mg_context *ctx, const char *pem);
  10340. static const char *ssl_error(void);
  10341. static int
  10342. refresh_trust(struct mg_connection *conn)
  10343. {
  10344. static int reload_lock = 0;
  10345. static long int data_check = 0;
  10346. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  10347. struct stat cert_buf;
  10348. long int t;
  10349. char *pem;
  10350. int should_verify_peer;
  10351. if ((pem = conn->ctx->config[SSL_CERTIFICATE]) == NULL) {
  10352. /* If peem is NULL and conn->ctx->callbacks.init_ssl is not,
  10353. * refresh_trust still can not work. */
  10354. return 0;
  10355. }
  10356. t = data_check;
  10357. if (stat(pem, &cert_buf) != -1) {
  10358. t = (long int)cert_buf.st_mtime;
  10359. }
  10360. if (data_check != t) {
  10361. data_check = t;
  10362. should_verify_peer =
  10363. (conn->ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  10364. && (mg_strcasecmp(conn->ctx->config[SSL_DO_VERIFY_PEER], "yes")
  10365. == 0);
  10366. if (should_verify_peer) {
  10367. char *ca_path = conn->ctx->config[SSL_CA_PATH];
  10368. char *ca_file = conn->ctx->config[SSL_CA_FILE];
  10369. if (SSL_CTX_load_verify_locations(conn->ctx->ssl_ctx,
  10370. ca_file,
  10371. ca_path) != 1) {
  10372. mg_cry(fc(conn->ctx),
  10373. "SSL_CTX_load_verify_locations error: %s "
  10374. "ssl_verify_peer requires setting "
  10375. "either ssl_ca_path or ssl_ca_file. Is any of them "
  10376. "present in "
  10377. "the .conf file?",
  10378. ssl_error());
  10379. return 0;
  10380. }
  10381. }
  10382. if (1 == mg_atomic_inc(p_reload_lock)) {
  10383. if (ssl_use_pem_file(conn->ctx, pem) == 0) {
  10384. return 0;
  10385. }
  10386. *p_reload_lock = 0;
  10387. }
  10388. }
  10389. /* lock while cert is reloading */
  10390. while (*p_reload_lock) {
  10391. sleep(1);
  10392. }
  10393. return 1;
  10394. }
  10395. #ifdef OPENSSL_API_1_1
  10396. #else
  10397. static pthread_mutex_t *ssl_mutexes;
  10398. #endif /* OPENSSL_API_1_1 */
  10399. static int
  10400. sslize(struct mg_connection *conn,
  10401. SSL_CTX *s,
  10402. int (*func)(SSL *),
  10403. volatile int *stop_server)
  10404. {
  10405. int ret, err;
  10406. int short_trust;
  10407. unsigned i;
  10408. if (!conn) {
  10409. return 0;
  10410. }
  10411. short_trust =
  10412. (conn->ctx->config[SSL_SHORT_TRUST] != NULL)
  10413. && (mg_strcasecmp(conn->ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  10414. if (short_trust) {
  10415. int trust_ret = refresh_trust(conn);
  10416. if (!trust_ret) {
  10417. return trust_ret;
  10418. }
  10419. }
  10420. conn->ssl = SSL_new(s);
  10421. if (conn->ssl == NULL) {
  10422. return 0;
  10423. }
  10424. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  10425. if (ret != 1) {
  10426. err = SSL_get_error(conn->ssl, ret);
  10427. (void)err; /* TODO: set some error message */
  10428. SSL_free(conn->ssl);
  10429. conn->ssl = NULL;
  10430. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  10431. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  10432. #ifndef OPENSSL_API_1_1
  10433. ERR_remove_state(0);
  10434. #endif
  10435. return 0;
  10436. }
  10437. /* SSL functions may fail and require to be called again:
  10438. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  10439. * Here "func" could be SSL_connect or SSL_accept. */
  10440. for (i = 16; i <= 1024; i *= 2) {
  10441. ret = func(conn->ssl);
  10442. if (ret != 1) {
  10443. err = SSL_get_error(conn->ssl, ret);
  10444. if ((err == SSL_ERROR_WANT_CONNECT)
  10445. || (err == SSL_ERROR_WANT_ACCEPT)
  10446. || (err == SSL_ERROR_WANT_READ)
  10447. || (err == SSL_ERROR_WANT_WRITE)) {
  10448. /* Need to retry the function call "later".
  10449. * See https://linux.die.net/man/3/ssl_get_error
  10450. * This is typical for non-blocking sockets. */
  10451. if (*stop_server) {
  10452. /* Don't wait if the server is going to be stopped. */
  10453. break;
  10454. }
  10455. mg_sleep(i);
  10456. } else if (err == SSL_ERROR_SYSCALL) {
  10457. /* This is an IO error. Look at errno. */
  10458. err = errno;
  10459. /* TODO: set some error message */
  10460. break;
  10461. } else {
  10462. /* This is an SSL specific error */
  10463. /* TODO: set some error message */
  10464. break;
  10465. }
  10466. } else {
  10467. /* success */
  10468. break;
  10469. }
  10470. }
  10471. if (ret != 1) {
  10472. SSL_free(conn->ssl);
  10473. conn->ssl = NULL;
  10474. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  10475. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  10476. #ifndef OPENSSL_API_1_1
  10477. ERR_remove_state(0);
  10478. #endif
  10479. return 0;
  10480. }
  10481. return 1;
  10482. }
  10483. /* Return OpenSSL error message (from CRYPTO lib) */
  10484. static const char *
  10485. ssl_error(void)
  10486. {
  10487. unsigned long err;
  10488. err = ERR_get_error();
  10489. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  10490. }
  10491. static int
  10492. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  10493. {
  10494. int i;
  10495. const char hexdigit[] = "0123456789abcdef";
  10496. if (memlen <= 0 || buflen <= 0) {
  10497. return 0;
  10498. }
  10499. if (buflen < (3 * memlen)) {
  10500. return 0;
  10501. }
  10502. for (i = 0; i < memlen; i++) {
  10503. if (i > 0) {
  10504. buf[3 * i - 1] = ' ';
  10505. }
  10506. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  10507. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  10508. }
  10509. buf[3 * memlen - 1] = 0;
  10510. return 1;
  10511. }
  10512. static void
  10513. ssl_get_client_cert_info(struct mg_connection *conn)
  10514. {
  10515. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  10516. if (cert) {
  10517. char str_subject[1024];
  10518. char str_issuer[1024];
  10519. char str_finger[1024];
  10520. unsigned char buf[256];
  10521. char *str_serial = NULL;
  10522. unsigned int ulen;
  10523. /* Handle to algorithm used for fingerprint */
  10524. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  10525. /* Get Subject and issuer */
  10526. X509_NAME *subj = X509_get_subject_name(cert);
  10527. X509_NAME *iss = X509_get_issuer_name(cert);
  10528. /* Get serial number */
  10529. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  10530. /* Translate serial number to a hex string */
  10531. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  10532. str_serial = BN_bn2hex(serial_bn);
  10533. BN_free(serial_bn);
  10534. /* Translate subject and issuer to a string */
  10535. (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
  10536. (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
  10537. /* Calculate SHA1 fingerprint and store as a hex string */
  10538. ulen = 0;
  10539. ASN1_digest((int (*)())i2d_X509, digest, (char *)cert, buf, &ulen);
  10540. if (!hexdump2string(
  10541. buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
  10542. *str_finger = 0;
  10543. }
  10544. conn->request_info.client_cert =
  10545. (struct client_cert *)mg_malloc(sizeof(struct client_cert));
  10546. if (conn->request_info.client_cert) {
  10547. conn->request_info.client_cert->subject = mg_strdup(str_subject);
  10548. conn->request_info.client_cert->issuer = mg_strdup(str_issuer);
  10549. conn->request_info.client_cert->serial = mg_strdup(str_serial);
  10550. conn->request_info.client_cert->finger = mg_strdup(str_finger);
  10551. } else {
  10552. /* TODO: write some OOM message */
  10553. }
  10554. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  10555. * see https://linux.die.net/man/3/bn_bn2hex */
  10556. OPENSSL_free(str_serial);
  10557. /* Free certificate memory */
  10558. X509_free(cert);
  10559. }
  10560. }
  10561. #ifdef OPENSSL_API_1_1
  10562. #else
  10563. static void
  10564. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  10565. {
  10566. (void)line;
  10567. (void)file;
  10568. if (mode & 1) {
  10569. /* 1 is CRYPTO_LOCK */
  10570. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  10571. } else {
  10572. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  10573. }
  10574. }
  10575. #endif /* OPENSSL_API_1_1 */
  10576. #if !defined(NO_SSL_DL)
  10577. static void *
  10578. load_dll(struct mg_context *ctx, const char *dll_name, struct ssl_func *sw)
  10579. {
  10580. union {
  10581. void *p;
  10582. void (*fp)(void);
  10583. } u;
  10584. void *dll_handle;
  10585. struct ssl_func *fp;
  10586. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  10587. mg_cry(fc(ctx), "%s: cannot load %s", __func__, dll_name);
  10588. return NULL;
  10589. }
  10590. for (fp = sw; fp->name != NULL; fp++) {
  10591. #ifdef _WIN32
  10592. /* GetProcAddress() returns pointer to function */
  10593. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  10594. #else
  10595. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  10596. * pointers to function pointers. We need to use a union to make a
  10597. * cast. */
  10598. u.p = dlsym(dll_handle, fp->name);
  10599. #endif /* _WIN32 */
  10600. if (u.fp == NULL) {
  10601. mg_cry(fc(ctx),
  10602. "%s: %s: cannot find %s",
  10603. __func__,
  10604. dll_name,
  10605. fp->name);
  10606. dlclose(dll_handle);
  10607. return NULL;
  10608. } else {
  10609. fp->ptr = u.fp;
  10610. }
  10611. }
  10612. return dll_handle;
  10613. }
  10614. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  10615. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  10616. #endif /* NO_SSL_DL */
  10617. #if defined(SSL_ALREADY_INITIALIZED)
  10618. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  10619. #else
  10620. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  10621. #endif
  10622. static int
  10623. initialize_ssl(struct mg_context *ctx)
  10624. {
  10625. #ifdef OPENSSL_API_1_1
  10626. #if !defined(NO_SSL_DL)
  10627. if (!cryptolib_dll_handle) {
  10628. cryptolib_dll_handle = load_dll(ctx, CRYPTO_LIB, crypto_sw);
  10629. if (!cryptolib_dll_handle) {
  10630. return 0;
  10631. }
  10632. }
  10633. #else
  10634. (void)ctx;
  10635. #endif /* NO_SSL_DL */
  10636. if (mg_atomic_inc(&cryptolib_users) > 1) {
  10637. return 1;
  10638. }
  10639. #else
  10640. int i;
  10641. size_t size;
  10642. #if !defined(NO_SSL_DL)
  10643. if (!cryptolib_dll_handle) {
  10644. cryptolib_dll_handle = load_dll(ctx, CRYPTO_LIB, crypto_sw);
  10645. if (!cryptolib_dll_handle) {
  10646. return 0;
  10647. }
  10648. }
  10649. #else
  10650. (void)ctx;
  10651. #endif /* NO_SSL_DL */
  10652. if (mg_atomic_inc(&cryptolib_users) > 1) {
  10653. return 1;
  10654. }
  10655. /* Initialize locking callbacks, needed for thread safety.
  10656. * http://www.openssl.org/support/faq.html#PROG1
  10657. */
  10658. i = CRYPTO_num_locks();
  10659. if (i < 0) {
  10660. i = 0;
  10661. }
  10662. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  10663. if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  10664. mg_cry(fc(ctx),
  10665. "%s: cannot allocate mutexes: %s",
  10666. __func__,
  10667. ssl_error());
  10668. return 0;
  10669. }
  10670. for (i = 0; i < CRYPTO_num_locks(); i++) {
  10671. pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr);
  10672. }
  10673. CRYPTO_set_locking_callback(&ssl_locking_callback);
  10674. CRYPTO_set_id_callback(&mg_current_thread_id);
  10675. #endif /* OPENSSL_API_1_1 */
  10676. return 1;
  10677. }
  10678. static int
  10679. ssl_use_pem_file(struct mg_context *ctx, const char *pem)
  10680. {
  10681. if (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0) {
  10682. mg_cry(fc(ctx),
  10683. "%s: cannot open certificate file %s: %s",
  10684. __func__,
  10685. pem,
  10686. ssl_error());
  10687. return 0;
  10688. }
  10689. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  10690. if (SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0) {
  10691. mg_cry(fc(ctx),
  10692. "%s: cannot open private key file %s: %s",
  10693. __func__,
  10694. pem,
  10695. ssl_error());
  10696. return 0;
  10697. }
  10698. if (SSL_CTX_check_private_key(ctx->ssl_ctx) == 0) {
  10699. mg_cry(fc(ctx),
  10700. "%s: certificate and private key do not match: %s",
  10701. __func__,
  10702. pem);
  10703. return 0;
  10704. }
  10705. if (SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem) == 0) {
  10706. mg_cry(fc(ctx),
  10707. "%s: cannot use certificate chain file %s: %s",
  10708. __func__,
  10709. pem,
  10710. ssl_error());
  10711. return 0;
  10712. }
  10713. return 1;
  10714. }
  10715. #ifdef OPENSSL_API_1_1
  10716. static unsigned long
  10717. ssl_get_protocol(int version_id)
  10718. {
  10719. long unsigned ret = SSL_OP_ALL;
  10720. if (version_id > 0)
  10721. ret |= SSL_OP_NO_SSLv2;
  10722. if (version_id > 1)
  10723. ret |= SSL_OP_NO_SSLv3;
  10724. if (version_id > 2)
  10725. ret |= SSL_OP_NO_TLSv1;
  10726. if (version_id > 3)
  10727. ret |= SSL_OP_NO_TLSv1_1;
  10728. return ret;
  10729. }
  10730. #else
  10731. static long
  10732. ssl_get_protocol(int version_id)
  10733. {
  10734. long ret = SSL_OP_ALL;
  10735. if (version_id > 0)
  10736. ret |= SSL_OP_NO_SSLv2;
  10737. if (version_id > 1)
  10738. ret |= SSL_OP_NO_SSLv3;
  10739. if (version_id > 2)
  10740. ret |= SSL_OP_NO_TLSv1;
  10741. if (version_id > 3)
  10742. ret |= SSL_OP_NO_TLSv1_1;
  10743. return ret;
  10744. }
  10745. #endif /* OPENSSL_API_1_1 */
  10746. /* Dynamically load SSL library. Set up ctx->ssl_ctx pointer. */
  10747. static int
  10748. set_ssl_option(struct mg_context *ctx)
  10749. {
  10750. const char *pem;
  10751. int callback_ret;
  10752. int should_verify_peer;
  10753. const char *ca_path;
  10754. const char *ca_file;
  10755. int use_default_verify_paths;
  10756. int verify_depth;
  10757. time_t now_rt = time(NULL);
  10758. struct timespec now_mt;
  10759. md5_byte_t ssl_context_id[16];
  10760. md5_state_t md5state;
  10761. int protocol_ver;
  10762. /* If PEM file is not specified and the init_ssl callback
  10763. * is not specified, skip SSL initialization. */
  10764. if (!ctx) {
  10765. return 0;
  10766. }
  10767. if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL
  10768. && ctx->callbacks.init_ssl == NULL) {
  10769. return 1;
  10770. }
  10771. if (!initialize_ssl(ctx)) {
  10772. return 0;
  10773. }
  10774. #if !defined(NO_SSL_DL)
  10775. if (!ssllib_dll_handle) {
  10776. ssllib_dll_handle = load_dll(ctx, SSL_LIB, ssl_sw);
  10777. if (!ssllib_dll_handle) {
  10778. return 0;
  10779. }
  10780. }
  10781. #endif /* NO_SSL_DL */
  10782. #ifdef OPENSSL_API_1_1
  10783. /* Initialize SSL library */
  10784. OPENSSL_init_ssl(0, NULL);
  10785. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  10786. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  10787. NULL);
  10788. if ((ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  10789. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  10790. return 0;
  10791. }
  10792. #else
  10793. /* Initialize SSL library */
  10794. SSL_library_init();
  10795. SSL_load_error_strings();
  10796. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  10797. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  10798. return 0;
  10799. }
  10800. #endif /* OPENSSL_API_1_1 */
  10801. SSL_CTX_clear_options(ctx->ssl_ctx,
  10802. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  10803. | SSL_OP_NO_TLSv1_1);
  10804. protocol_ver = atoi(ctx->config[SSL_PROTOCOL_VERSION]);
  10805. SSL_CTX_set_options(ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  10806. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  10807. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  10808. #if !defined(NO_SSL_DL)
  10809. SSL_CTX_set_ecdh_auto(ctx->ssl_ctx, 1);
  10810. #endif /* NO_SSL_DL */
  10811. /* If a callback has been specified, call it. */
  10812. callback_ret =
  10813. (ctx->callbacks.init_ssl == NULL)
  10814. ? 0
  10815. : (ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data));
  10816. /* If callback returns 0, civetweb sets up the SSL certificate.
  10817. * If it returns 1, civetweb assumes the calback already did this.
  10818. * If it returns -1, initializing ssl fails. */
  10819. if (callback_ret < 0) {
  10820. mg_cry(fc(ctx), "SSL callback returned error: %i", callback_ret);
  10821. return 0;
  10822. }
  10823. if (callback_ret > 0) {
  10824. if (pem != NULL) {
  10825. (void)SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
  10826. }
  10827. return 1;
  10828. }
  10829. /* Use some UID as session context ID. */
  10830. md5_init(&md5state);
  10831. md5_append(&md5state, (const md5_byte_t *)&now_rt, sizeof(now_rt));
  10832. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  10833. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  10834. md5_append(&md5state,
  10835. (const md5_byte_t *)ctx->config[LISTENING_PORTS],
  10836. strlen(ctx->config[LISTENING_PORTS]));
  10837. md5_append(&md5state, (const md5_byte_t *)ctx, sizeof(*ctx));
  10838. md5_finish(&md5state, ssl_context_id);
  10839. SSL_CTX_set_session_id_context(ctx->ssl_ctx,
  10840. (const unsigned char *)&ssl_context_id,
  10841. sizeof(ssl_context_id));
  10842. if (pem != NULL) {
  10843. if (!ssl_use_pem_file(ctx, pem)) {
  10844. return 0;
  10845. }
  10846. }
  10847. should_verify_peer =
  10848. (ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  10849. && (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0);
  10850. use_default_verify_paths =
  10851. (ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  10852. && (mg_strcasecmp(ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes") == 0);
  10853. if (should_verify_peer) {
  10854. ca_path = ctx->config[SSL_CA_PATH];
  10855. ca_file = ctx->config[SSL_CA_FILE];
  10856. if (SSL_CTX_load_verify_locations(ctx->ssl_ctx, ca_file, ca_path)
  10857. != 1) {
  10858. mg_cry(fc(ctx),
  10859. "SSL_CTX_load_verify_locations error: %s "
  10860. "ssl_verify_peer requires setting "
  10861. "either ssl_ca_path or ssl_ca_file. Is any of them "
  10862. "present in "
  10863. "the .conf file?",
  10864. ssl_error());
  10865. return 0;
  10866. }
  10867. SSL_CTX_set_verify(ctx->ssl_ctx,
  10868. SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  10869. NULL);
  10870. if (use_default_verify_paths
  10871. && SSL_CTX_set_default_verify_paths(ctx->ssl_ctx) != 1) {
  10872. mg_cry(fc(ctx),
  10873. "SSL_CTX_set_default_verify_paths error: %s",
  10874. ssl_error());
  10875. return 0;
  10876. }
  10877. if (ctx->config[SSL_VERIFY_DEPTH]) {
  10878. verify_depth = atoi(ctx->config[SSL_VERIFY_DEPTH]);
  10879. SSL_CTX_set_verify_depth(ctx->ssl_ctx, verify_depth);
  10880. }
  10881. }
  10882. if (ctx->config[SSL_CIPHER_LIST] != NULL) {
  10883. if (SSL_CTX_set_cipher_list(ctx->ssl_ctx, ctx->config[SSL_CIPHER_LIST])
  10884. != 1) {
  10885. mg_cry(fc(ctx), "SSL_CTX_set_cipher_list error: %s", ssl_error());
  10886. }
  10887. }
  10888. return 1;
  10889. }
  10890. static void
  10891. uninitialize_ssl(struct mg_context *ctx)
  10892. {
  10893. #ifdef OPENSSL_API_1_1
  10894. (void)ctx;
  10895. if (mg_atomic_dec(&cryptolib_users) == 0) {
  10896. /* Shutdown according to
  10897. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  10898. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  10899. */
  10900. CONF_modules_unload(1);
  10901. #else
  10902. int i;
  10903. (void)ctx;
  10904. if (mg_atomic_dec(&cryptolib_users) == 0) {
  10905. /* Shutdown according to
  10906. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  10907. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  10908. */
  10909. CRYPTO_set_locking_callback(NULL);
  10910. CRYPTO_set_id_callback(NULL);
  10911. ENGINE_cleanup();
  10912. CONF_modules_unload(1);
  10913. ERR_free_strings();
  10914. EVP_cleanup();
  10915. CRYPTO_cleanup_all_ex_data();
  10916. ERR_remove_state(0);
  10917. for (i = 0; i < CRYPTO_num_locks(); i++) {
  10918. pthread_mutex_destroy(&ssl_mutexes[i]);
  10919. }
  10920. mg_free(ssl_mutexes);
  10921. ssl_mutexes = NULL;
  10922. #endif /* OPENSSL_API_1_1 */
  10923. }
  10924. }
  10925. #endif /* !NO_SSL */
  10926. static int
  10927. set_gpass_option(struct mg_context *ctx)
  10928. {
  10929. if (ctx) {
  10930. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10931. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  10932. if (path != NULL && !mg_stat(fc(ctx), path, &file.stat)) {
  10933. mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  10934. return 0;
  10935. }
  10936. return 1;
  10937. }
  10938. return 0;
  10939. }
  10940. static int
  10941. set_acl_option(struct mg_context *ctx)
  10942. {
  10943. return check_acl(ctx, (uint32_t)0x7f000001UL) != -1;
  10944. }
  10945. static void
  10946. reset_per_request_attributes(struct mg_connection *conn)
  10947. {
  10948. if (!conn) {
  10949. return;
  10950. }
  10951. conn->path_info = NULL;
  10952. conn->num_bytes_sent = conn->consumed_content = 0;
  10953. conn->status_code = -1;
  10954. conn->is_chunked = 0;
  10955. conn->must_close = conn->request_len = conn->throttle = 0;
  10956. conn->request_info.content_length = -1;
  10957. conn->request_info.remote_user = NULL;
  10958. conn->request_info.request_method = NULL;
  10959. conn->request_info.request_uri = NULL;
  10960. conn->request_info.local_uri = NULL;
  10961. conn->request_info.uri = NULL; /* TODO: cleanup uri,
  10962. * local_uri and request_uri */
  10963. conn->request_info.http_version = NULL;
  10964. conn->request_info.num_headers = 0;
  10965. conn->data_len = 0;
  10966. conn->chunk_remainder = 0;
  10967. }
  10968. #if 0
  10969. /* Note: set_sock_timeout is not required for non-blocking sockets.
  10970. * Leave this function here (commented out) for reference until
  10971. * CivetWeb 1.9 is tested, and the tests confirme this function is
  10972. * no longer required.
  10973. */
  10974. static int
  10975. set_sock_timeout(SOCKET sock, int milliseconds)
  10976. {
  10977. int r0 = 0, r1, r2;
  10978. #ifdef _WIN32
  10979. /* Windows specific */
  10980. DWORD tv = (DWORD)milliseconds;
  10981. #else
  10982. /* Linux, ... (not Windows) */
  10983. struct timeval tv;
  10984. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  10985. * max. time waiting for the acknowledged of TCP data before the connection
  10986. * will be forcefully closed and ETIMEDOUT is returned to the application.
  10987. * If this option is not set, the default timeout of 20-30 minutes is used.
  10988. */
  10989. /* #define TCP_USER_TIMEOUT (18) */
  10990. #if defined(TCP_USER_TIMEOUT)
  10991. unsigned int uto = (unsigned int)milliseconds;
  10992. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  10993. #endif
  10994. memset(&tv, 0, sizeof(tv));
  10995. tv.tv_sec = milliseconds / 1000;
  10996. tv.tv_usec = (milliseconds * 1000) % 1000000;
  10997. #endif /* _WIN32 */
  10998. r1 = setsockopt(
  10999. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  11000. r2 = setsockopt(
  11001. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  11002. return r0 || r1 || r2;
  11003. }
  11004. #endif
  11005. static int
  11006. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  11007. {
  11008. if (setsockopt(sock,
  11009. IPPROTO_TCP,
  11010. TCP_NODELAY,
  11011. (SOCK_OPT_TYPE)&nodelay_on,
  11012. sizeof(nodelay_on)) != 0) {
  11013. /* Error */
  11014. return 1;
  11015. }
  11016. /* OK */
  11017. return 0;
  11018. }
  11019. static void
  11020. close_socket_gracefully(struct mg_connection *conn)
  11021. {
  11022. #if defined(_WIN32)
  11023. char buf[MG_BUF_LEN];
  11024. int n;
  11025. #endif
  11026. struct linger linger;
  11027. int error_code = 0;
  11028. int linger_timeout = -2;
  11029. socklen_t opt_len = sizeof(error_code);
  11030. if (!conn) {
  11031. return;
  11032. }
  11033. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  11034. * "Note that enabling a nonzero timeout on a nonblocking socket
  11035. * is not recommended.", so set it to blocking now */
  11036. set_blocking_mode(conn->client.sock, 1);
  11037. /* Send FIN to the client */
  11038. shutdown(conn->client.sock, SHUTDOWN_WR);
  11039. #if defined(_WIN32)
  11040. /* Read and discard pending incoming data. If we do not do that and
  11041. * close
  11042. * the socket, the data in the send buffer may be discarded. This
  11043. * behaviour is seen on Windows, when client keeps sending data
  11044. * when server decides to close the connection; then when client
  11045. * does recv() it gets no data back. */
  11046. do {
  11047. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  11048. } while (n > 0);
  11049. #endif
  11050. if (conn->ctx->config[LINGER_TIMEOUT]) {
  11051. linger_timeout = atoi(conn->ctx->config[LINGER_TIMEOUT]);
  11052. }
  11053. /* Set linger option according to configuration */
  11054. if (linger_timeout >= 0) {
  11055. /* Set linger option to avoid socket hanging out after close. This
  11056. * prevent ephemeral port exhaust problem under high QPS. */
  11057. linger.l_onoff = 1;
  11058. #if defined(_MSC_VER)
  11059. #pragma warning(push)
  11060. #pragma warning(disable : 4244)
  11061. #endif
  11062. linger.l_linger = (linger_timeout + 999) / 1000;
  11063. #if defined(_MSC_VER)
  11064. #pragma warning(pop)
  11065. #endif
  11066. } else {
  11067. linger.l_onoff = 0;
  11068. linger.l_linger = 0;
  11069. }
  11070. if (linger_timeout < -1) {
  11071. /* Default: don't configure any linger */
  11072. } else if (getsockopt(conn->client.sock,
  11073. SOL_SOCKET,
  11074. SO_ERROR,
  11075. (char *)&error_code,
  11076. &opt_len) != 0) {
  11077. /* Cannot determine if socket is already closed. This should
  11078. * not occur and never did in a test. Log an error message
  11079. * and continue. */
  11080. mg_cry(conn,
  11081. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  11082. __func__,
  11083. strerror(ERRNO));
  11084. } else if (error_code == ECONNRESET) {
  11085. /* Socket already closed by client/peer, close socket without linger */
  11086. } else {
  11087. /* Set linger timeout */
  11088. if (setsockopt(conn->client.sock,
  11089. SOL_SOCKET,
  11090. SO_LINGER,
  11091. (char *)&linger,
  11092. sizeof(linger)) != 0) {
  11093. mg_cry(conn,
  11094. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  11095. __func__,
  11096. linger.l_onoff,
  11097. linger.l_linger,
  11098. strerror(ERRNO));
  11099. }
  11100. }
  11101. /* Now we know that our FIN is ACK-ed, safe to close */
  11102. closesocket(conn->client.sock);
  11103. conn->client.sock = INVALID_SOCKET;
  11104. }
  11105. static void
  11106. close_connection(struct mg_connection *conn)
  11107. {
  11108. if (!conn || !conn->ctx) {
  11109. return;
  11110. }
  11111. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  11112. if (conn->lua_websocket_state) {
  11113. lua_websocket_close(conn, conn->lua_websocket_state);
  11114. conn->lua_websocket_state = NULL;
  11115. }
  11116. #endif
  11117. /* call the connection_close callback if assigned */
  11118. if ((conn->ctx->callbacks.connection_close != NULL)
  11119. && (conn->ctx->context_type == 1)) {
  11120. conn->ctx->callbacks.connection_close(conn);
  11121. }
  11122. mg_lock_connection(conn);
  11123. conn->must_close = 1;
  11124. #ifndef NO_SSL
  11125. if (conn->ssl != NULL) {
  11126. /* Run SSL_shutdown twice to ensure completly close SSL connection
  11127. */
  11128. SSL_shutdown(conn->ssl);
  11129. SSL_free(conn->ssl);
  11130. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  11131. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  11132. #ifndef OPENSSL_API_1_1
  11133. ERR_remove_state(0);
  11134. #endif
  11135. conn->ssl = NULL;
  11136. }
  11137. #endif
  11138. if (conn->client.sock != INVALID_SOCKET) {
  11139. close_socket_gracefully(conn);
  11140. conn->client.sock = INVALID_SOCKET;
  11141. }
  11142. mg_unlock_connection(conn);
  11143. }
  11144. void
  11145. mg_close_connection(struct mg_connection *conn)
  11146. {
  11147. struct mg_context *client_ctx = NULL;
  11148. if (conn == NULL) {
  11149. return;
  11150. }
  11151. #if defined(USE_WEBSOCKET)
  11152. if (conn->ctx->context_type == 2) {
  11153. unsigned int i;
  11154. /* ws/wss client */
  11155. client_ctx = conn->ctx;
  11156. /* client context: loops must end */
  11157. conn->ctx->stop_flag = 1;
  11158. /* We need to get the client thread out of the select/recv call here. */
  11159. /* Since we use a sleep quantum of some seconds to check for recv
  11160. * timeouts, we will just wait a few seconds in mg_join_thread. */
  11161. /* join worker thread */
  11162. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  11163. if (client_ctx->worker_threadids[i] != 0) {
  11164. mg_join_thread(client_ctx->worker_threadids[i]);
  11165. }
  11166. }
  11167. }
  11168. #else
  11169. (void)client_ctx;
  11170. #endif
  11171. close_connection(conn);
  11172. #ifndef NO_SSL
  11173. if (conn->client_ssl_ctx != NULL) {
  11174. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  11175. }
  11176. #endif
  11177. if (client_ctx != NULL) {
  11178. /* free context */
  11179. mg_free(client_ctx->worker_threadids);
  11180. mg_free(client_ctx);
  11181. (void)pthread_mutex_destroy(&conn->mutex);
  11182. mg_free(conn);
  11183. }
  11184. }
  11185. static struct mg_connection *
  11186. mg_connect_client_impl(const struct mg_client_options *client_options,
  11187. int use_ssl,
  11188. char *ebuf,
  11189. size_t ebuf_len)
  11190. {
  11191. static struct mg_context fake_ctx;
  11192. struct mg_connection *conn = NULL;
  11193. SOCKET sock;
  11194. union usa sa;
  11195. if (!connect_socket(&fake_ctx,
  11196. client_options->host,
  11197. client_options->port,
  11198. use_ssl,
  11199. ebuf,
  11200. ebuf_len,
  11201. &sock,
  11202. &sa)) {
  11203. ;
  11204. } else if ((conn = (struct mg_connection *)
  11205. mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) {
  11206. mg_snprintf(NULL,
  11207. NULL, /* No truncation check for ebuf */
  11208. ebuf,
  11209. ebuf_len,
  11210. "calloc(): %s",
  11211. strerror(ERRNO));
  11212. closesocket(sock);
  11213. #ifndef NO_SSL
  11214. #ifdef OPENSSL_API_1_1
  11215. } else if (use_ssl
  11216. && (conn->client_ssl_ctx = SSL_CTX_new(TLS_client_method()))
  11217. == NULL) {
  11218. mg_snprintf(NULL,
  11219. NULL, /* No truncation check for ebuf */
  11220. ebuf,
  11221. ebuf_len,
  11222. "SSL_CTX_new error");
  11223. closesocket(sock);
  11224. mg_free(conn);
  11225. conn = NULL;
  11226. #else
  11227. } else if (use_ssl
  11228. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  11229. == NULL) {
  11230. mg_snprintf(NULL,
  11231. NULL, /* No truncation check for ebuf */
  11232. ebuf,
  11233. ebuf_len,
  11234. "SSL_CTX_new error");
  11235. closesocket(sock);
  11236. mg_free(conn);
  11237. conn = NULL;
  11238. #endif /* OPENSSL_API_1_1 */
  11239. #endif /* NO_SSL */
  11240. } else {
  11241. #ifdef USE_IPV6
  11242. socklen_t len = (sa.sa.sa_family == AF_INET)
  11243. ? sizeof(conn->client.rsa.sin)
  11244. : sizeof(conn->client.rsa.sin6);
  11245. struct sockaddr *psa =
  11246. (sa.sa.sa_family == AF_INET)
  11247. ? (struct sockaddr *)&(conn->client.rsa.sin)
  11248. : (struct sockaddr *)&(conn->client.rsa.sin6);
  11249. #else
  11250. socklen_t len = sizeof(conn->client.rsa.sin);
  11251. struct sockaddr *psa = (struct sockaddr *)&(conn->client.rsa.sin);
  11252. #endif
  11253. conn->buf_size = MAX_REQUEST_SIZE;
  11254. conn->buf = (char *)(conn + 1);
  11255. conn->ctx = &fake_ctx;
  11256. conn->client.sock = sock;
  11257. conn->client.lsa = sa;
  11258. if (getsockname(sock, psa, &len) != 0) {
  11259. mg_cry(conn,
  11260. "%s: getsockname() failed: %s",
  11261. __func__,
  11262. strerror(ERRNO));
  11263. }
  11264. conn->client.is_ssl = use_ssl ? 1 : 0;
  11265. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  11266. #ifndef NO_SSL
  11267. if (use_ssl) {
  11268. fake_ctx.ssl_ctx = conn->client_ssl_ctx;
  11269. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  11270. * SSL_CTX_set_verify call is needed to switch off server
  11271. * certificate checking, which is off by default in OpenSSL and
  11272. * on in yaSSL. */
  11273. /* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  11274. * SSL_VERIFY_PEER, verify_ssl_server); */
  11275. if (client_options->client_cert) {
  11276. if (!ssl_use_pem_file(&fake_ctx, client_options->client_cert)) {
  11277. mg_snprintf(NULL,
  11278. NULL, /* No truncation check for ebuf */
  11279. ebuf,
  11280. ebuf_len,
  11281. "Can not use SSL client certificate");
  11282. SSL_CTX_free(conn->client_ssl_ctx);
  11283. closesocket(sock);
  11284. mg_free(conn);
  11285. conn = NULL;
  11286. }
  11287. }
  11288. if (client_options->server_cert) {
  11289. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  11290. client_options->server_cert,
  11291. NULL);
  11292. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  11293. } else {
  11294. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  11295. }
  11296. if (!sslize(conn,
  11297. conn->client_ssl_ctx,
  11298. SSL_connect,
  11299. &(conn->ctx->stop_flag))) {
  11300. mg_snprintf(NULL,
  11301. NULL, /* No truncation check for ebuf */
  11302. ebuf,
  11303. ebuf_len,
  11304. "SSL connection error");
  11305. SSL_CTX_free(conn->client_ssl_ctx);
  11306. closesocket(sock);
  11307. mg_free(conn);
  11308. conn = NULL;
  11309. }
  11310. }
  11311. #endif
  11312. }
  11313. if (conn) {
  11314. set_blocking_mode(sock, 0);
  11315. }
  11316. return conn;
  11317. }
  11318. CIVETWEB_API struct mg_connection *
  11319. mg_connect_client_secure(const struct mg_client_options *client_options,
  11320. char *error_buffer,
  11321. size_t error_buffer_size)
  11322. {
  11323. return mg_connect_client_impl(client_options,
  11324. 1,
  11325. error_buffer,
  11326. error_buffer_size);
  11327. }
  11328. struct mg_connection *
  11329. mg_connect_client(const char *host,
  11330. int port,
  11331. int use_ssl,
  11332. char *error_buffer,
  11333. size_t error_buffer_size)
  11334. {
  11335. struct mg_client_options opts;
  11336. memset(&opts, 0, sizeof(opts));
  11337. opts.host = host;
  11338. opts.port = port;
  11339. return mg_connect_client_impl(&opts,
  11340. use_ssl,
  11341. error_buffer,
  11342. error_buffer_size);
  11343. }
  11344. static const struct {
  11345. const char *proto;
  11346. size_t proto_len;
  11347. unsigned default_port;
  11348. } abs_uri_protocols[] = {{"http://", 7, 80},
  11349. {"https://", 8, 443},
  11350. {"ws://", 5, 80},
  11351. {"wss://", 6, 443},
  11352. {NULL, 0, 0}};
  11353. /* Check if the uri is valid.
  11354. * return 0 for invalid uri,
  11355. * return 1 for *,
  11356. * return 2 for relative uri,
  11357. * return 3 for absolute uri without port,
  11358. * return 4 for absolute uri with port */
  11359. static int
  11360. get_uri_type(const char *uri)
  11361. {
  11362. int i;
  11363. char *hostend, *portbegin, *portend;
  11364. unsigned long port;
  11365. /* According to the HTTP standard
  11366. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  11367. * URI can be an asterisk (*) or should start with slash (relative uri),
  11368. * or it should start with the protocol (absolute uri). */
  11369. if (uri[0] == '*' && uri[1] == '\0') {
  11370. /* asterisk */
  11371. return 1;
  11372. }
  11373. /* Valid URIs according to RFC 3986
  11374. * (https://www.ietf.org/rfc/rfc3986.txt)
  11375. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  11376. * and unreserved characters A-Z a-z 0-9 and -._~
  11377. * and % encoded symbols.
  11378. */
  11379. for (i = 0; uri[i] != 0; i++) {
  11380. if (uri[i] < 33) {
  11381. /* control characters and spaces are invalid */
  11382. return 0;
  11383. }
  11384. if (uri[i] > 126) {
  11385. /* non-ascii characters must be % encoded */
  11386. return 0;
  11387. } else {
  11388. switch (uri[i]) {
  11389. case '"': /* 34 */
  11390. case '<': /* 60 */
  11391. case '>': /* 62 */
  11392. case '\\': /* 92 */
  11393. case '^': /* 94 */
  11394. case '`': /* 96 */
  11395. case '{': /* 123 */
  11396. case '|': /* 124 */
  11397. case '}': /* 125 */
  11398. return 0;
  11399. default:
  11400. /* character is ok */
  11401. break;
  11402. }
  11403. }
  11404. }
  11405. /* A relative uri starts with a / character */
  11406. if (uri[0] == '/') {
  11407. /* relative uri */
  11408. return 2;
  11409. }
  11410. /* It could be an absolute uri: */
  11411. /* This function only checks if the uri is valid, not if it is
  11412. * addressing the current server. So civetweb can also be used
  11413. * as a proxy server. */
  11414. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  11415. if (mg_strncasecmp(uri,
  11416. abs_uri_protocols[i].proto,
  11417. abs_uri_protocols[i].proto_len) == 0) {
  11418. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  11419. if (!hostend) {
  11420. return 0;
  11421. }
  11422. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  11423. if (!portbegin) {
  11424. return 3;
  11425. }
  11426. port = strtoul(portbegin + 1, &portend, 10);
  11427. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  11428. return 0;
  11429. }
  11430. return 4;
  11431. }
  11432. }
  11433. return 0;
  11434. }
  11435. /* Return NULL or the relative uri at the current server */
  11436. static const char *
  11437. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  11438. {
  11439. const char *server_domain;
  11440. size_t server_domain_len;
  11441. size_t request_domain_len = 0;
  11442. unsigned long port = 0;
  11443. int i, auth_domain_check_enabled;
  11444. const char *hostbegin = NULL;
  11445. const char *hostend = NULL;
  11446. const char *portbegin;
  11447. char *portend;
  11448. auth_domain_check_enabled =
  11449. !strcmp(conn->ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  11450. /* DNS is case insensitive, so use case insensitive string compare here
  11451. */
  11452. server_domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  11453. if (!server_domain && auth_domain_check_enabled) {
  11454. return 0;
  11455. }
  11456. server_domain_len = strlen(server_domain);
  11457. if (!server_domain_len) {
  11458. return 0;
  11459. }
  11460. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  11461. if (mg_strncasecmp(uri,
  11462. abs_uri_protocols[i].proto,
  11463. abs_uri_protocols[i].proto_len) == 0) {
  11464. hostbegin = uri + abs_uri_protocols[i].proto_len;
  11465. hostend = strchr(hostbegin, '/');
  11466. if (!hostend) {
  11467. return 0;
  11468. }
  11469. portbegin = strchr(hostbegin, ':');
  11470. if ((!portbegin) || (portbegin > hostend)) {
  11471. port = abs_uri_protocols[i].default_port;
  11472. request_domain_len = (size_t)(hostend - hostbegin);
  11473. } else {
  11474. port = strtoul(portbegin + 1, &portend, 10);
  11475. if ((portend != hostend) || (port <= 0)
  11476. || !is_valid_port(port)) {
  11477. return 0;
  11478. }
  11479. request_domain_len = (size_t)(portbegin - hostbegin);
  11480. }
  11481. /* protocol found, port set */
  11482. break;
  11483. }
  11484. }
  11485. if (!port) {
  11486. /* port remains 0 if the protocol is not found */
  11487. return 0;
  11488. }
  11489. /* Check if the request is directed to a different server. */
  11490. /* First check if the port is the same (IPv4 and IPv6). */
  11491. #if defined(USE_IPV6)
  11492. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  11493. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  11494. /* Request is directed to a different port */
  11495. return 0;
  11496. }
  11497. } else
  11498. #endif
  11499. {
  11500. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  11501. /* Request is directed to a different port */
  11502. return 0;
  11503. }
  11504. }
  11505. /* Finally check if the server corresponds to the authentication
  11506. * domain of the server (the server domain).
  11507. * Allow full matches (like http://mydomain.com/path/file.ext), and
  11508. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  11509. * but do not allow substrings (like http://notmydomain.com/path/file.ext
  11510. * or http://mydomain.com.fake/path/file.ext).
  11511. */
  11512. if (auth_domain_check_enabled) {
  11513. if ((request_domain_len == server_domain_len)
  11514. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  11515. /* Request is directed to this server - full name match. */
  11516. } else {
  11517. if (request_domain_len < (server_domain_len + 2)) {
  11518. /* Request is directed to another server: The server name is
  11519. * longer
  11520. * than
  11521. * the request name. Drop this case here to avoid overflows in
  11522. * the
  11523. * following checks. */
  11524. return 0;
  11525. }
  11526. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  11527. /* Request is directed to another server: It could be a
  11528. * substring
  11529. * like notmyserver.com */
  11530. return 0;
  11531. }
  11532. if (0 != memcmp(server_domain,
  11533. hostbegin + request_domain_len - server_domain_len,
  11534. server_domain_len)) {
  11535. /* Request is directed to another server:
  11536. * The server name is different. */
  11537. return 0;
  11538. }
  11539. }
  11540. }
  11541. return hostend;
  11542. }
  11543. static int
  11544. getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  11545. {
  11546. const char *cl;
  11547. if (ebuf_len > 0) {
  11548. ebuf[0] = '\0';
  11549. }
  11550. *err = 0;
  11551. reset_per_request_attributes(conn);
  11552. if (!conn) {
  11553. mg_snprintf(conn,
  11554. NULL, /* No truncation check for ebuf */
  11555. ebuf,
  11556. ebuf_len,
  11557. "%s",
  11558. "Internal error");
  11559. *err = 500;
  11560. return 0;
  11561. }
  11562. /* Set the time the request was received. This value should be used for
  11563. * timeouts. */
  11564. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  11565. conn->request_len =
  11566. read_request(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  11567. /* assert(conn->request_len < 0 || conn->data_len >= conn->request_len);
  11568. */
  11569. if (conn->request_len >= 0 && conn->data_len < conn->request_len) {
  11570. mg_snprintf(conn,
  11571. NULL, /* No truncation check for ebuf */
  11572. ebuf,
  11573. ebuf_len,
  11574. "%s",
  11575. "Invalid request size");
  11576. *err = 500;
  11577. return 0;
  11578. }
  11579. if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
  11580. mg_snprintf(conn,
  11581. NULL, /* No truncation check for ebuf */
  11582. ebuf,
  11583. ebuf_len,
  11584. "%s",
  11585. "Request Too Large");
  11586. *err = 413;
  11587. return 0;
  11588. } else if (conn->request_len <= 0) {
  11589. if (conn->data_len > 0) {
  11590. mg_snprintf(conn,
  11591. NULL, /* No truncation check for ebuf */
  11592. ebuf,
  11593. ebuf_len,
  11594. "%s",
  11595. "Client sent malformed request");
  11596. *err = 400;
  11597. } else {
  11598. /* Server did not recv anything -> just close the connection */
  11599. conn->must_close = 1;
  11600. mg_snprintf(conn,
  11601. NULL, /* No truncation check for ebuf */
  11602. ebuf,
  11603. ebuf_len,
  11604. "%s",
  11605. "Client did not send a request");
  11606. *err = 0;
  11607. }
  11608. return 0;
  11609. } else if (parse_http_message(conn->buf,
  11610. conn->buf_size,
  11611. &conn->request_info) <= 0) {
  11612. mg_snprintf(conn,
  11613. NULL, /* No truncation check for ebuf */
  11614. ebuf,
  11615. ebuf_len,
  11616. "%s",
  11617. "Bad Request");
  11618. *err = 400;
  11619. return 0;
  11620. } else {
  11621. /* Message is a valid request or response */
  11622. if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) {
  11623. /* Request/response has content length set */
  11624. char *endptr = NULL;
  11625. conn->content_len = strtoll(cl, &endptr, 10);
  11626. if (endptr == cl) {
  11627. mg_snprintf(conn,
  11628. NULL, /* No truncation check for ebuf */
  11629. ebuf,
  11630. ebuf_len,
  11631. "%s",
  11632. "Bad Request");
  11633. *err = 411;
  11634. return 0;
  11635. }
  11636. /* Publish the content length back to the request info. */
  11637. conn->request_info.content_length = conn->content_len;
  11638. } else if ((cl = get_header(&conn->request_info, "Transfer-Encoding"))
  11639. != NULL
  11640. && !mg_strcasecmp(cl, "chunked")) {
  11641. conn->is_chunked = 1;
  11642. } else if (!mg_strcasecmp(conn->request_info.request_method, "POST")
  11643. || !mg_strcasecmp(conn->request_info.request_method,
  11644. "PUT")) {
  11645. /* POST or PUT request without content length set */
  11646. conn->content_len = -1;
  11647. } else if (!mg_strncasecmp(conn->request_info.request_method,
  11648. "HTTP/",
  11649. 5)) {
  11650. /* Response without content length set */
  11651. conn->content_len = -1;
  11652. } else {
  11653. /* Other request */
  11654. conn->content_len = 0;
  11655. }
  11656. }
  11657. return 1;
  11658. }
  11659. int
  11660. mg_get_response(struct mg_connection *conn,
  11661. char *ebuf,
  11662. size_t ebuf_len,
  11663. int timeout)
  11664. {
  11665. if (conn) {
  11666. /* Implementation of API function for HTTP clients */
  11667. int err, ret;
  11668. struct mg_context *octx = conn->ctx;
  11669. struct mg_context rctx = *(conn->ctx);
  11670. char txt[32]; /* will not overflow */
  11671. if (timeout >= 0) {
  11672. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  11673. rctx.config[REQUEST_TIMEOUT] = txt;
  11674. /* Not required for non-blocking sockets.
  11675. set_sock_timeout(conn->client.sock, timeout);
  11676. */
  11677. } else {
  11678. rctx.config[REQUEST_TIMEOUT] = NULL;
  11679. }
  11680. conn->ctx = &rctx;
  11681. ret = getreq(conn, ebuf, ebuf_len, &err);
  11682. conn->ctx = octx;
  11683. /* TODO: 1) uri is deprecated;
  11684. * 2) here, ri.uri is the http response code */
  11685. conn->request_info.uri = conn->request_info.request_uri;
  11686. /* TODO (mid): Define proper return values - maybe return length?
  11687. * For the first test use <0 for error and >0 for OK */
  11688. return (ret == 0) ? -1 : +1;
  11689. }
  11690. return -1;
  11691. }
  11692. struct mg_connection *
  11693. mg_download(const char *host,
  11694. int port,
  11695. int use_ssl,
  11696. char *ebuf,
  11697. size_t ebuf_len,
  11698. const char *fmt,
  11699. ...)
  11700. {
  11701. struct mg_connection *conn;
  11702. va_list ap;
  11703. int i;
  11704. int reqerr;
  11705. va_start(ap, fmt);
  11706. ebuf[0] = '\0';
  11707. /* open a connection */
  11708. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  11709. if (conn != NULL) {
  11710. i = mg_vprintf(conn, fmt, ap);
  11711. if (i <= 0) {
  11712. mg_snprintf(conn,
  11713. NULL, /* No truncation check for ebuf */
  11714. ebuf,
  11715. ebuf_len,
  11716. "%s",
  11717. "Error sending request");
  11718. } else {
  11719. getreq(conn, ebuf, ebuf_len, &reqerr);
  11720. /* TODO: 1) uri is deprecated;
  11721. * 2) here, ri.uri is the http response code */
  11722. conn->request_info.uri = conn->request_info.request_uri;
  11723. }
  11724. }
  11725. /* if an error occured, close the connection */
  11726. if (ebuf[0] != '\0' && conn != NULL) {
  11727. mg_close_connection(conn);
  11728. conn = NULL;
  11729. }
  11730. va_end(ap);
  11731. return conn;
  11732. }
  11733. struct websocket_client_thread_data {
  11734. struct mg_connection *conn;
  11735. mg_websocket_data_handler data_handler;
  11736. mg_websocket_close_handler close_handler;
  11737. void *callback_data;
  11738. };
  11739. #if defined(USE_WEBSOCKET)
  11740. #ifdef _WIN32
  11741. static unsigned __stdcall websocket_client_thread(void *data)
  11742. #else
  11743. static void *
  11744. websocket_client_thread(void *data)
  11745. #endif
  11746. {
  11747. struct websocket_client_thread_data *cdata =
  11748. (struct websocket_client_thread_data *)data;
  11749. mg_set_thread_name("ws-clnt");
  11750. if (cdata->conn->ctx) {
  11751. if (cdata->conn->ctx->callbacks.init_thread) {
  11752. /* 3 indicates a websocket client thread */
  11753. /* TODO: check if conn->ctx can be set */
  11754. cdata->conn->ctx->callbacks.init_thread(cdata->conn->ctx, 3);
  11755. }
  11756. }
  11757. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  11758. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  11759. if (cdata->close_handler != NULL) {
  11760. cdata->close_handler(cdata->conn, cdata->callback_data);
  11761. }
  11762. /* The websocket_client context has only this thread. If it runs out,
  11763. set the stop_flag to 2 (= "stopped"). */
  11764. cdata->conn->ctx->stop_flag = 2;
  11765. mg_free((void *)cdata);
  11766. #ifdef _WIN32
  11767. return 0;
  11768. #else
  11769. return NULL;
  11770. #endif
  11771. }
  11772. #endif
  11773. struct mg_connection *
  11774. mg_connect_websocket_client(const char *host,
  11775. int port,
  11776. int use_ssl,
  11777. char *error_buffer,
  11778. size_t error_buffer_size,
  11779. const char *path,
  11780. const char *origin,
  11781. mg_websocket_data_handler data_func,
  11782. mg_websocket_close_handler close_func,
  11783. void *user_data)
  11784. {
  11785. struct mg_connection *conn = NULL;
  11786. #if defined(USE_WEBSOCKET)
  11787. struct mg_context *newctx = NULL;
  11788. struct websocket_client_thread_data *thread_data;
  11789. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  11790. static const char *handshake_req;
  11791. if (origin != NULL) {
  11792. handshake_req = "GET %s HTTP/1.1\r\n"
  11793. "Host: %s\r\n"
  11794. "Upgrade: websocket\r\n"
  11795. "Connection: Upgrade\r\n"
  11796. "Sec-WebSocket-Key: %s\r\n"
  11797. "Sec-WebSocket-Version: 13\r\n"
  11798. "Origin: %s\r\n"
  11799. "\r\n";
  11800. } else {
  11801. handshake_req = "GET %s HTTP/1.1\r\n"
  11802. "Host: %s\r\n"
  11803. "Upgrade: websocket\r\n"
  11804. "Connection: Upgrade\r\n"
  11805. "Sec-WebSocket-Key: %s\r\n"
  11806. "Sec-WebSocket-Version: 13\r\n"
  11807. "\r\n";
  11808. }
  11809. /* Establish the client connection and request upgrade */
  11810. conn = mg_download(host,
  11811. port,
  11812. use_ssl,
  11813. error_buffer,
  11814. error_buffer_size,
  11815. handshake_req,
  11816. path,
  11817. host,
  11818. magic,
  11819. origin);
  11820. /* Connection object will be null if something goes wrong */
  11821. if (conn == NULL || (strcmp(conn->request_info.request_uri, "101") != 0)) {
  11822. if (!*error_buffer) {
  11823. /* if there is a connection, but it did not return 101,
  11824. * error_buffer is not yet set */
  11825. mg_snprintf(conn,
  11826. NULL, /* No truncation check for ebuf */
  11827. error_buffer,
  11828. error_buffer_size,
  11829. "Unexpected server reply");
  11830. }
  11831. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  11832. if (conn != NULL) {
  11833. mg_free(conn);
  11834. conn = NULL;
  11835. }
  11836. return conn;
  11837. }
  11838. /* For client connections, mg_context is fake. Since we need to set a
  11839. * callback function, we need to create a copy and modify it. */
  11840. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  11841. memcpy(newctx, conn->ctx, sizeof(struct mg_context));
  11842. newctx->user_data = user_data;
  11843. newctx->context_type = 2; /* ws/wss client context type */
  11844. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  11845. newctx->worker_threadids =
  11846. (pthread_t *)mg_calloc(newctx->cfg_worker_threads, sizeof(pthread_t));
  11847. conn->ctx = newctx;
  11848. thread_data = (struct websocket_client_thread_data *)
  11849. mg_calloc(sizeof(struct websocket_client_thread_data), 1);
  11850. thread_data->conn = conn;
  11851. thread_data->data_handler = data_func;
  11852. thread_data->close_handler = close_func;
  11853. thread_data->callback_data = NULL;
  11854. /* Start a thread to read the websocket client connection
  11855. * This thread will automatically stop when mg_disconnect is
  11856. * called on the client connection */
  11857. if (mg_start_thread_with_id(websocket_client_thread,
  11858. (void *)thread_data,
  11859. newctx->worker_threadids) != 0) {
  11860. mg_free((void *)thread_data);
  11861. mg_free((void *)newctx->worker_threadids);
  11862. mg_free((void *)newctx);
  11863. mg_free((void *)conn);
  11864. conn = NULL;
  11865. DEBUG_TRACE("%s",
  11866. "Websocket client connect thread could not be started\r\n");
  11867. }
  11868. #else
  11869. /* Appease "unused parameter" warnings */
  11870. (void)host;
  11871. (void)port;
  11872. (void)use_ssl;
  11873. (void)error_buffer;
  11874. (void)error_buffer_size;
  11875. (void)path;
  11876. (void)origin;
  11877. (void)user_data;
  11878. (void)data_func;
  11879. (void)close_func;
  11880. #endif
  11881. return conn;
  11882. }
  11883. static void
  11884. process_new_connection(struct mg_connection *conn)
  11885. {
  11886. if (conn && conn->ctx) {
  11887. struct mg_request_info *ri = &conn->request_info;
  11888. int keep_alive_enabled, keep_alive, discard_len;
  11889. char ebuf[100];
  11890. const char *hostend;
  11891. int reqerr, uri_type;
  11892. keep_alive_enabled =
  11893. !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  11894. /* Important: on new connection, reset the receiving buffer. Credit
  11895. * goes to crule42. */
  11896. conn->data_len = 0;
  11897. conn->handled_requests = 0;
  11898. do {
  11899. DEBUG_TRACE("calling getreq (%i times for this connection)",
  11900. conn->handled_requests + 1);
  11901. if (!getreq(conn, ebuf, sizeof(ebuf), &reqerr)) {
  11902. /* The request sent by the client could not be understood by
  11903. * the server, or it was incomplete or a timeout. Send an
  11904. * error message and close the connection. */
  11905. if (reqerr > 0) {
  11906. /*assert(ebuf[0] != '\0');*/
  11907. send_http_error(conn, reqerr, "%s", ebuf);
  11908. }
  11909. } else if (strcmp(ri->http_version, "1.0")
  11910. && strcmp(ri->http_version, "1.1")) {
  11911. mg_snprintf(conn,
  11912. NULL, /* No truncation check for ebuf */
  11913. ebuf,
  11914. sizeof(ebuf),
  11915. "Bad HTTP version: [%s]",
  11916. ri->http_version);
  11917. send_http_error(conn, 505, "%s", ebuf);
  11918. }
  11919. if (ebuf[0] == '\0') {
  11920. uri_type = get_uri_type(conn->request_info.request_uri);
  11921. switch (uri_type) {
  11922. case 1:
  11923. /* Asterisk */
  11924. conn->request_info.local_uri = NULL;
  11925. break;
  11926. case 2:
  11927. /* relative uri */
  11928. conn->request_info.local_uri =
  11929. conn->request_info.request_uri;
  11930. break;
  11931. case 3:
  11932. case 4:
  11933. /* absolute uri (with/without port) */
  11934. hostend = get_rel_url_at_current_server(
  11935. conn->request_info.request_uri, conn);
  11936. if (hostend) {
  11937. conn->request_info.local_uri = hostend;
  11938. } else {
  11939. conn->request_info.local_uri = NULL;
  11940. }
  11941. break;
  11942. default:
  11943. mg_snprintf(conn,
  11944. NULL, /* No truncation check for ebuf */
  11945. ebuf,
  11946. sizeof(ebuf),
  11947. "Invalid URI");
  11948. send_http_error(conn, 400, "%s", ebuf);
  11949. conn->request_info.local_uri = NULL;
  11950. break;
  11951. }
  11952. /* TODO: cleanup uri, local_uri and request_uri */
  11953. conn->request_info.uri = conn->request_info.local_uri;
  11954. }
  11955. DEBUG_TRACE("http: %s, error: %s",
  11956. (ri->http_version ? ri->http_version : "none"),
  11957. (ebuf[0] ? ebuf : "none"));
  11958. if (ebuf[0] == '\0') {
  11959. if (conn->request_info.local_uri) {
  11960. /* handle request to local server */
  11961. handle_request(conn);
  11962. DEBUG_TRACE("%s", "handle_request done");
  11963. if (conn->ctx->callbacks.end_request != NULL) {
  11964. conn->ctx->callbacks.end_request(conn,
  11965. conn->status_code);
  11966. DEBUG_TRACE("%s", "end_request callback done");
  11967. }
  11968. log_access(conn);
  11969. } else {
  11970. /* TODO: handle non-local request (PROXY) */
  11971. conn->must_close = 1;
  11972. }
  11973. } else {
  11974. conn->must_close = 1;
  11975. }
  11976. if (ri->remote_user != NULL) {
  11977. mg_free((void *)ri->remote_user);
  11978. /* Important! When having connections with and without auth
  11979. * would cause double free and then crash */
  11980. ri->remote_user = NULL;
  11981. }
  11982. /* NOTE(lsm): order is important here. should_keep_alive() call
  11983. * is
  11984. * using parsed request, which will be invalid after memmove's
  11985. * below.
  11986. * Therefore, memorize should_keep_alive() result now for later
  11987. * use
  11988. * in loop exit condition. */
  11989. keep_alive = (conn->ctx->stop_flag == 0) && keep_alive_enabled
  11990. && (conn->content_len >= 0) && should_keep_alive(conn);
  11991. /* Discard all buffered data for this request */
  11992. discard_len = ((conn->content_len >= 0) && (conn->request_len > 0)
  11993. && ((conn->request_len + conn->content_len)
  11994. < (int64_t)conn->data_len))
  11995. ? (int)(conn->request_len + conn->content_len)
  11996. : conn->data_len;
  11997. /*assert(discard_len >= 0);*/
  11998. if (discard_len < 0) {
  11999. DEBUG_TRACE("internal error: discard_len = %li",
  12000. (long int)discard_len);
  12001. break;
  12002. }
  12003. conn->data_len -= discard_len;
  12004. if (conn->data_len > 0) {
  12005. DEBUG_TRACE("discard_len = %lu", (long unsigned)discard_len);
  12006. memmove(conn->buf,
  12007. conn->buf + discard_len,
  12008. (size_t)conn->data_len);
  12009. }
  12010. /* assert(conn->data_len >= 0); */
  12011. /* assert(conn->data_len <= conn->buf_size); */
  12012. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  12013. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  12014. (long int)conn->data_len,
  12015. (long int)conn->buf_size);
  12016. break;
  12017. }
  12018. conn->handled_requests++;
  12019. } while (keep_alive);
  12020. }
  12021. }
  12022. #if defined(ALTERNATIVE_QUEUE)
  12023. static void
  12024. produce_socket(struct mg_context *ctx, const struct socket *sp)
  12025. {
  12026. unsigned int i;
  12027. for (;;) {
  12028. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  12029. /* find a free worker slot and signal it */
  12030. if (ctx->client_socks[i].in_use == 0) {
  12031. ctx->client_socks[i] = *sp;
  12032. ctx->client_socks[i].in_use = 1;
  12033. event_signal(ctx->client_wait_events[i]);
  12034. return;
  12035. }
  12036. }
  12037. /* queue is full */
  12038. mg_sleep(1);
  12039. }
  12040. }
  12041. static int
  12042. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  12043. {
  12044. DEBUG_TRACE("%s", "going idle");
  12045. ctx->client_socks[thread_index].in_use = 0;
  12046. event_wait(ctx->client_wait_events[thread_index]);
  12047. *sp = ctx->client_socks[thread_index];
  12048. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  12049. return !ctx->stop_flag;
  12050. }
  12051. #else /* ALTERNATIVE_QUEUE */
  12052. /* Worker threads take accepted socket from the queue */
  12053. static int
  12054. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  12055. {
  12056. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  12057. (void)thread_index;
  12058. (void)pthread_mutex_lock(&ctx->thread_mutex);
  12059. DEBUG_TRACE("%s", "going idle");
  12060. /* If the queue is empty, wait. We're idle at this point. */
  12061. while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
  12062. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  12063. }
  12064. /* If we're stopping, sq_head may be equal to sq_tail. */
  12065. if (ctx->sq_head > ctx->sq_tail) {
  12066. /* Copy socket from the queue and increment tail */
  12067. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  12068. ctx->sq_tail++;
  12069. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  12070. /* Wrap pointers if needed */
  12071. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  12072. ctx->sq_tail -= QUEUE_SIZE(ctx);
  12073. ctx->sq_head -= QUEUE_SIZE(ctx);
  12074. }
  12075. }
  12076. (void)pthread_cond_signal(&ctx->sq_empty);
  12077. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  12078. return !ctx->stop_flag;
  12079. #undef QUEUE_SIZE
  12080. }
  12081. /* Master thread adds accepted socket to a queue */
  12082. static void
  12083. produce_socket(struct mg_context *ctx, const struct socket *sp)
  12084. {
  12085. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  12086. if (!ctx) {
  12087. return;
  12088. }
  12089. (void)pthread_mutex_lock(&ctx->thread_mutex);
  12090. /* If the queue is full, wait */
  12091. while (ctx->stop_flag == 0
  12092. && ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx)) {
  12093. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  12094. }
  12095. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  12096. /* Copy socket to the queue and increment head */
  12097. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  12098. ctx->sq_head++;
  12099. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  12100. }
  12101. (void)pthread_cond_signal(&ctx->sq_full);
  12102. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  12103. #undef QUEUE_SIZE
  12104. }
  12105. #endif /* ALTERNATIVE_QUEUE */
  12106. struct worker_thread_args {
  12107. struct mg_context *ctx;
  12108. int index;
  12109. };
  12110. static void *
  12111. worker_thread_run(struct worker_thread_args *thread_args)
  12112. {
  12113. struct mg_context *ctx = thread_args->ctx;
  12114. struct mg_connection *conn;
  12115. struct mg_workerTLS tls;
  12116. #if defined(MG_LEGACY_INTERFACE)
  12117. uint32_t addr;
  12118. #endif
  12119. mg_set_thread_name("worker");
  12120. tls.is_master = 0;
  12121. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  12122. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12123. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  12124. #endif
  12125. /* Initialize thread local storage before calling any callback */
  12126. pthread_setspecific(sTlsKey, &tls);
  12127. if (ctx->callbacks.init_thread) {
  12128. /* call init_thread for a worker thread (type 1) */
  12129. ctx->callbacks.init_thread(ctx, 1);
  12130. }
  12131. /* Connection structure has been pre-allocated */
  12132. if (((int)thread_args->index < 0)
  12133. || ((unsigned)thread_args->index
  12134. >= (unsigned)ctx->cfg_worker_threads)) {
  12135. mg_cry(fc(ctx),
  12136. "Internal error: Invalid worker index %i",
  12137. (int)thread_args->index);
  12138. return NULL;
  12139. }
  12140. conn = ctx->worker_connections + thread_args->index;
  12141. /* Request buffers are not pre-allocated. They are private to the
  12142. * request and do not contain any state information that might be
  12143. * of interest to anyone observing a server status. */
  12144. conn->buf = (char *)mg_malloc(MAX_REQUEST_SIZE);
  12145. if (conn->buf == NULL) {
  12146. mg_cry(fc(ctx),
  12147. "Out of memory: Cannot allocate buffer for worker %i",
  12148. (int)thread_args->index);
  12149. return NULL;
  12150. }
  12151. conn->buf_size = MAX_REQUEST_SIZE;
  12152. conn->ctx = ctx;
  12153. conn->thread_index = thread_args->index;
  12154. conn->request_info.user_data = ctx->user_data;
  12155. /* Allocate a mutex for this connection to allow communication both
  12156. * within the request handler and from elsewhere in the application
  12157. */
  12158. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  12159. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  12160. * signal sq_empty condvar to wake up the master waiting in
  12161. * produce_socket() */
  12162. while (consume_socket(ctx, &conn->client, conn->thread_index)) {
  12163. conn->conn_birth_time = time(NULL);
  12164. /* Fill in IP, port info early so even if SSL setup below fails,
  12165. * error handler would have the corresponding info.
  12166. * Thanks to Johannes Winkelmann for the patch.
  12167. */
  12168. #if defined(USE_IPV6)
  12169. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  12170. conn->request_info.remote_port =
  12171. ntohs(conn->client.rsa.sin6.sin6_port);
  12172. } else
  12173. #endif
  12174. {
  12175. conn->request_info.remote_port =
  12176. ntohs(conn->client.rsa.sin.sin_port);
  12177. }
  12178. sockaddr_to_string(conn->request_info.remote_addr,
  12179. sizeof(conn->request_info.remote_addr),
  12180. &conn->client.rsa);
  12181. DEBUG_TRACE("Start processing connection from %s",
  12182. conn->request_info.remote_addr);
  12183. #if defined(MG_LEGACY_INTERFACE)
  12184. /* This legacy interface only works for the IPv4 case */
  12185. addr = ntohl(conn->client.rsa.sin.sin_addr.s_addr);
  12186. memcpy(&conn->request_info.remote_ip, &addr, 4);
  12187. #endif
  12188. conn->request_info.is_ssl = conn->client.is_ssl;
  12189. if (conn->client.is_ssl) {
  12190. #ifndef NO_SSL
  12191. /* HTTPS connection */
  12192. if (sslize(conn,
  12193. conn->ctx->ssl_ctx,
  12194. SSL_accept,
  12195. &(conn->ctx->stop_flag))) {
  12196. /* Get SSL client certificate information (if set) */
  12197. ssl_get_client_cert_info(conn);
  12198. /* process HTTPS connection */
  12199. process_new_connection(conn);
  12200. /* Free client certificate info */
  12201. if (conn->request_info.client_cert) {
  12202. mg_free((void *)(conn->request_info.client_cert->subject));
  12203. mg_free((void *)(conn->request_info.client_cert->issuer));
  12204. mg_free((void *)(conn->request_info.client_cert->serial));
  12205. mg_free((void *)(conn->request_info.client_cert->finger));
  12206. conn->request_info.client_cert->subject = 0;
  12207. conn->request_info.client_cert->issuer = 0;
  12208. conn->request_info.client_cert->serial = 0;
  12209. conn->request_info.client_cert->finger = 0;
  12210. mg_free(conn->request_info.client_cert);
  12211. conn->request_info.client_cert = 0;
  12212. }
  12213. }
  12214. #endif
  12215. } else {
  12216. /* process HTTP connection */
  12217. process_new_connection(conn);
  12218. }
  12219. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  12220. conn->request_info.remote_addr,
  12221. difftime(time(NULL), conn->conn_birth_time));
  12222. close_connection(conn);
  12223. DEBUG_TRACE("%s", "Connection closed");
  12224. }
  12225. pthread_setspecific(sTlsKey, NULL);
  12226. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12227. CloseHandle(tls.pthread_cond_helper_mutex);
  12228. #endif
  12229. pthread_mutex_destroy(&conn->mutex);
  12230. /* Free the request buffer. */
  12231. conn->buf_size = 0;
  12232. mg_free(conn->buf);
  12233. conn->buf = NULL;
  12234. DEBUG_TRACE("%s", "exiting");
  12235. return NULL;
  12236. }
  12237. /* Threads have different return types on Windows and Unix. */
  12238. #ifdef _WIN32
  12239. static unsigned __stdcall worker_thread(void *thread_func_param)
  12240. {
  12241. struct worker_thread_args *pwta =
  12242. (struct worker_thread_args *)thread_func_param;
  12243. worker_thread_run(pwta);
  12244. mg_free(thread_func_param);
  12245. return 0;
  12246. }
  12247. #else
  12248. static void *
  12249. worker_thread(void *thread_func_param)
  12250. {
  12251. struct worker_thread_args *pwta =
  12252. (struct worker_thread_args *)thread_func_param;
  12253. worker_thread_run(pwta);
  12254. mg_free(thread_func_param);
  12255. return NULL;
  12256. }
  12257. #endif /* _WIN32 */
  12258. static void
  12259. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  12260. {
  12261. struct socket so;
  12262. char src_addr[IP_ADDR_STR_LEN];
  12263. socklen_t len = sizeof(so.rsa);
  12264. int on = 1;
  12265. if (!listener) {
  12266. return;
  12267. }
  12268. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  12269. == INVALID_SOCKET) {
  12270. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  12271. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  12272. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  12273. closesocket(so.sock);
  12274. so.sock = INVALID_SOCKET;
  12275. } else {
  12276. /* Put so socket structure into the queue */
  12277. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  12278. set_close_on_exec(so.sock, fc(ctx));
  12279. so.is_ssl = listener->is_ssl;
  12280. so.ssl_redir = listener->ssl_redir;
  12281. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  12282. mg_cry(fc(ctx),
  12283. "%s: getsockname() failed: %s",
  12284. __func__,
  12285. strerror(ERRNO));
  12286. }
  12287. /* Set TCP keep-alive. This is needed because if HTTP-level
  12288. * keep-alive
  12289. * is enabled, and client resets the connection, server won't get
  12290. * TCP FIN or RST and will keep the connection open forever. With
  12291. * TCP keep-alive, next keep-alive handshake will figure out that
  12292. * the client is down and will close the server end.
  12293. * Thanks to Igor Klopov who suggested the patch. */
  12294. if (setsockopt(so.sock,
  12295. SOL_SOCKET,
  12296. SO_KEEPALIVE,
  12297. (SOCK_OPT_TYPE)&on,
  12298. sizeof(on)) != 0) {
  12299. mg_cry(fc(ctx),
  12300. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  12301. __func__,
  12302. strerror(ERRNO));
  12303. }
  12304. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  12305. * to effectively fill up the underlying IP packet payload and
  12306. * reduce the overhead of sending lots of small buffers. However
  12307. * this hurts the server's throughput (ie. operations per second)
  12308. * when HTTP 1.1 persistent connections are used and the responses
  12309. * are relatively small (eg. less than 1400 bytes).
  12310. */
  12311. if ((ctx != NULL) && (ctx->config[CONFIG_TCP_NODELAY] != NULL)
  12312. && (!strcmp(ctx->config[CONFIG_TCP_NODELAY], "1"))) {
  12313. if (set_tcp_nodelay(so.sock, 1) != 0) {
  12314. mg_cry(fc(ctx),
  12315. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  12316. __func__,
  12317. strerror(ERRNO));
  12318. }
  12319. }
  12320. /* We are using non-blocking sockets. Thus, the
  12321. * set_sock_timeout(so.sock, timeout);
  12322. * call is no longer required. */
  12323. set_blocking_mode(so.sock, 0);
  12324. produce_socket(ctx, &so);
  12325. }
  12326. }
  12327. static void
  12328. master_thread_run(void *thread_func_param)
  12329. {
  12330. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  12331. struct mg_workerTLS tls;
  12332. struct pollfd *pfd;
  12333. unsigned int i;
  12334. unsigned int workerthreadcount;
  12335. if (!ctx) {
  12336. return;
  12337. }
  12338. mg_set_thread_name("master");
  12339. /* Increase priority of the master thread */
  12340. #if defined(_WIN32)
  12341. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  12342. #elif defined(USE_MASTER_THREAD_PRIORITY)
  12343. int min_prio = sched_get_priority_min(SCHED_RR);
  12344. int max_prio = sched_get_priority_max(SCHED_RR);
  12345. if ((min_prio >= 0) && (max_prio >= 0)
  12346. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  12347. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  12348. struct sched_param sched_param = {0};
  12349. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  12350. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  12351. }
  12352. #endif
  12353. /* Initialize thread local storage */
  12354. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12355. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  12356. #endif
  12357. tls.is_master = 1;
  12358. pthread_setspecific(sTlsKey, &tls);
  12359. if (ctx->callbacks.init_thread) {
  12360. /* Callback for the master thread (type 0) */
  12361. ctx->callbacks.init_thread(ctx, 0);
  12362. }
  12363. /* Server starts *now* */
  12364. ctx->start_time = time(NULL);
  12365. /* Start the server */
  12366. pfd = ctx->listening_socket_fds;
  12367. while (ctx->stop_flag == 0) {
  12368. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12369. pfd[i].fd = ctx->listening_sockets[i].sock;
  12370. pfd[i].events = POLLIN;
  12371. }
  12372. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  12373. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12374. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  12375. * successful poll, and POLLIN is defined as
  12376. * (POLLRDNORM | POLLRDBAND)
  12377. * Therefore, we're checking pfd[i].revents & POLLIN, not
  12378. * pfd[i].revents == POLLIN. */
  12379. if (ctx->stop_flag == 0 && (pfd[i].revents & POLLIN)) {
  12380. accept_new_connection(&ctx->listening_sockets[i], ctx);
  12381. }
  12382. }
  12383. }
  12384. }
  12385. /* Here stop_flag is 1 - Initiate shutdown. */
  12386. DEBUG_TRACE("%s", "stopping workers");
  12387. /* Stop signal received: somebody called mg_stop. Quit. */
  12388. close_all_listening_sockets(ctx);
  12389. /* Wakeup workers that are waiting for connections to handle. */
  12390. (void)pthread_mutex_lock(&ctx->thread_mutex);
  12391. #if defined(ALTERNATIVE_QUEUE)
  12392. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  12393. event_signal(ctx->client_wait_events[i]);
  12394. /* Since we know all sockets, we can shutdown the connections. */
  12395. if (ctx->client_socks[i].in_use) {
  12396. shutdown(ctx->client_socks[i].sock, SHUTDOWN_BOTH);
  12397. }
  12398. }
  12399. #else
  12400. pthread_cond_broadcast(&ctx->sq_full);
  12401. #endif
  12402. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  12403. /* Join all worker threads to avoid leaking threads. */
  12404. workerthreadcount = ctx->cfg_worker_threads;
  12405. for (i = 0; i < workerthreadcount; i++) {
  12406. if (ctx->worker_threadids[i] != 0) {
  12407. mg_join_thread(ctx->worker_threadids[i]);
  12408. }
  12409. }
  12410. #if defined(USE_LUA)
  12411. /* Free Lua state of lua background task */
  12412. if (ctx->lua_background_state) {
  12413. lua_close((lua_State *)ctx->lua_background_state);
  12414. ctx->lua_background_state = 0;
  12415. }
  12416. #endif
  12417. #if !defined(NO_SSL)
  12418. if (ctx->ssl_ctx != NULL) {
  12419. uninitialize_ssl(ctx);
  12420. }
  12421. #endif
  12422. DEBUG_TRACE("%s", "exiting");
  12423. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12424. CloseHandle(tls.pthread_cond_helper_mutex);
  12425. #endif
  12426. pthread_setspecific(sTlsKey, NULL);
  12427. /* Signal mg_stop() that we're done.
  12428. * WARNING: This must be the very last thing this
  12429. * thread does, as ctx becomes invalid after this line. */
  12430. ctx->stop_flag = 2;
  12431. }
  12432. /* Threads have different return types on Windows and Unix. */
  12433. #ifdef _WIN32
  12434. static unsigned __stdcall master_thread(void *thread_func_param)
  12435. {
  12436. master_thread_run(thread_func_param);
  12437. return 0;
  12438. }
  12439. #else
  12440. static void *
  12441. master_thread(void *thread_func_param)
  12442. {
  12443. master_thread_run(thread_func_param);
  12444. return NULL;
  12445. }
  12446. #endif /* _WIN32 */
  12447. static void
  12448. free_context(struct mg_context *ctx)
  12449. {
  12450. int i;
  12451. struct mg_handler_info *tmp_rh;
  12452. if (ctx == NULL) {
  12453. return;
  12454. }
  12455. if (ctx->callbacks.exit_context) {
  12456. ctx->callbacks.exit_context(ctx);
  12457. }
  12458. /* All threads exited, no sync is needed. Destroy thread mutex and
  12459. * condvars
  12460. */
  12461. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  12462. #if defined(ALTERNATIVE_QUEUE)
  12463. mg_free(ctx->client_socks);
  12464. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  12465. event_destroy(ctx->client_wait_events[i]);
  12466. }
  12467. mg_free(ctx->client_wait_events);
  12468. #else
  12469. (void)pthread_cond_destroy(&ctx->sq_empty);
  12470. (void)pthread_cond_destroy(&ctx->sq_full);
  12471. #endif
  12472. /* Destroy other context global data structures mutex */
  12473. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  12474. #if defined(USE_TIMERS)
  12475. timers_exit(ctx);
  12476. #endif
  12477. /* Deallocate config parameters */
  12478. for (i = 0; i < NUM_OPTIONS; i++) {
  12479. if (ctx->config[i] != NULL) {
  12480. #if defined(_MSC_VER)
  12481. #pragma warning(suppress : 6001)
  12482. #endif
  12483. mg_free(ctx->config[i]);
  12484. }
  12485. }
  12486. /* Deallocate request handlers */
  12487. while (ctx->handlers) {
  12488. tmp_rh = ctx->handlers;
  12489. ctx->handlers = tmp_rh->next;
  12490. mg_free(tmp_rh->uri);
  12491. mg_free(tmp_rh);
  12492. }
  12493. #ifndef NO_SSL
  12494. /* Deallocate SSL context */
  12495. if (ctx->ssl_ctx != NULL) {
  12496. SSL_CTX_free(ctx->ssl_ctx);
  12497. }
  12498. #endif /* !NO_SSL */
  12499. /* Deallocate worker thread ID array */
  12500. if (ctx->worker_threadids != NULL) {
  12501. mg_free(ctx->worker_threadids);
  12502. }
  12503. /* Deallocate worker thread ID array */
  12504. if (ctx->worker_connections != NULL) {
  12505. mg_free(ctx->worker_connections);
  12506. }
  12507. /* Deallocate the tls variable */
  12508. if (mg_atomic_dec(&sTlsInit) == 0) {
  12509. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12510. DeleteCriticalSection(&global_log_file_lock);
  12511. #endif /* _WIN32 && !__SYMBIAN32__ */
  12512. #if !defined(_WIN32)
  12513. pthread_mutexattr_destroy(&pthread_mutex_attr);
  12514. #endif
  12515. pthread_key_delete(sTlsKey);
  12516. #if defined(USE_LUA)
  12517. lua_exit_optional_libraries();
  12518. #endif
  12519. }
  12520. /* deallocate system name string */
  12521. mg_free(ctx->systemName);
  12522. /* Deallocate context itself */
  12523. mg_free(ctx);
  12524. }
  12525. void
  12526. mg_stop(struct mg_context *ctx)
  12527. {
  12528. pthread_t mt;
  12529. if (!ctx) {
  12530. return;
  12531. }
  12532. /* We don't use a lock here. Calling mg_stop with the same ctx from
  12533. * two threads is not allowed. */
  12534. mt = ctx->masterthreadid;
  12535. if (mt == 0) {
  12536. return;
  12537. }
  12538. ctx->masterthreadid = 0;
  12539. /* Set stop flag, so all threads know they have to exit. */
  12540. ctx->stop_flag = 1;
  12541. /* Wait until everything has stopped. */
  12542. while (ctx->stop_flag != 2) {
  12543. (void)mg_sleep(10);
  12544. }
  12545. mg_join_thread(mt);
  12546. free_context(ctx);
  12547. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12548. (void)WSACleanup();
  12549. #endif /* _WIN32 && !__SYMBIAN32__ */
  12550. }
  12551. static void
  12552. get_system_name(char **sysName)
  12553. {
  12554. #if defined(_WIN32)
  12555. #if !defined(__SYMBIAN32__)
  12556. #if defined(_WIN32_WCE)
  12557. *sysName = mg_strdup("WinCE");
  12558. #else
  12559. char name[128];
  12560. DWORD dwVersion = 0;
  12561. DWORD dwMajorVersion = 0;
  12562. DWORD dwMinorVersion = 0;
  12563. DWORD dwBuild = 0;
  12564. #ifdef _MSC_VER
  12565. #pragma warning(push)
  12566. /* GetVersion was declared deprecated */
  12567. #pragma warning(disable : 4996)
  12568. #endif
  12569. dwVersion = GetVersion();
  12570. #ifdef _MSC_VER
  12571. #pragma warning(pop)
  12572. #endif
  12573. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  12574. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  12575. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  12576. (void)dwBuild;
  12577. sprintf(name,
  12578. "Windows %u.%u",
  12579. (unsigned)dwMajorVersion,
  12580. (unsigned)dwMinorVersion);
  12581. *sysName = mg_strdup(name);
  12582. #endif
  12583. #else
  12584. *sysName = mg_strdup("Symbian");
  12585. #endif
  12586. #else
  12587. struct utsname name;
  12588. memset(&name, 0, sizeof(name));
  12589. uname(&name);
  12590. *sysName = mg_strdup(name.sysname);
  12591. #endif
  12592. }
  12593. struct mg_context *
  12594. mg_start(const struct mg_callbacks *callbacks,
  12595. void *user_data,
  12596. const char **options)
  12597. {
  12598. struct mg_context *ctx;
  12599. const char *name, *value, *default_value;
  12600. int idx, ok, workerthreadcount;
  12601. unsigned int i;
  12602. void (*exit_callback)(const struct mg_context *ctx) = 0;
  12603. struct mg_workerTLS tls;
  12604. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12605. WSADATA data;
  12606. WSAStartup(MAKEWORD(2, 2), &data);
  12607. #endif /* _WIN32 && !__SYMBIAN32__ */
  12608. /* Allocate context and initialize reasonable general case defaults. */
  12609. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  12610. return NULL;
  12611. }
  12612. /* Random number generator will initialize at the first call */
  12613. ctx->auth_nonce_mask =
  12614. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  12615. if (mg_atomic_inc(&sTlsInit) == 1) {
  12616. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12617. InitializeCriticalSection(&global_log_file_lock);
  12618. #endif /* _WIN32 && !__SYMBIAN32__ */
  12619. #if !defined(_WIN32)
  12620. pthread_mutexattr_init(&pthread_mutex_attr);
  12621. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  12622. #endif
  12623. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  12624. /* Fatal error - abort start. However, this situation should
  12625. * never
  12626. * occur in practice. */
  12627. mg_atomic_dec(&sTlsInit);
  12628. mg_cry(fc(ctx), "Cannot initialize thread local storage");
  12629. mg_free(ctx);
  12630. return NULL;
  12631. }
  12632. #if defined(USE_LUA)
  12633. lua_init_optional_libraries();
  12634. #endif
  12635. } else {
  12636. /* TODO (low): istead of sleeping, check if sTlsKey is already
  12637. * initialized. */
  12638. mg_sleep(1);
  12639. }
  12640. tls.is_master = -1;
  12641. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  12642. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12643. tls.pthread_cond_helper_mutex = NULL;
  12644. #endif
  12645. pthread_setspecific(sTlsKey, &tls);
  12646. /* Dummy use this function - in some #ifdef combinations it's used,
  12647. * while it's not used in others, but GCC seems to stupid to understand
  12648. * #pragma GCC diagnostic ignored "-Wunused-function"
  12649. * in cases the function is unused, and it also complains on
  12650. * __attribute((unused))__ in cases it is used.
  12651. * So dummy use it, to have our peace. */
  12652. (void)mg_current_thread_id();
  12653. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr);
  12654. #if !defined(ALTERNATIVE_QUEUE)
  12655. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  12656. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  12657. #endif
  12658. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr);
  12659. if (!ok) {
  12660. /* Fatal error - abort start. However, this situation should never
  12661. * occur in practice. */
  12662. mg_cry(fc(ctx), "Cannot initialize thread synchronization objects");
  12663. mg_free(ctx);
  12664. pthread_setspecific(sTlsKey, NULL);
  12665. return NULL;
  12666. }
  12667. if (callbacks) {
  12668. ctx->callbacks = *callbacks;
  12669. exit_callback = callbacks->exit_context;
  12670. ctx->callbacks.exit_context = 0;
  12671. }
  12672. ctx->user_data = user_data;
  12673. ctx->handlers = NULL;
  12674. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  12675. ctx->shared_lua_websockets = 0;
  12676. #endif
  12677. while (options && (name = *options++) != NULL) {
  12678. if ((idx = get_option_index(name)) == -1) {
  12679. mg_cry(fc(ctx), "Invalid option: %s", name);
  12680. free_context(ctx);
  12681. pthread_setspecific(sTlsKey, NULL);
  12682. return NULL;
  12683. } else if ((value = *options++) == NULL) {
  12684. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  12685. free_context(ctx);
  12686. pthread_setspecific(sTlsKey, NULL);
  12687. return NULL;
  12688. }
  12689. if (ctx->config[idx] != NULL) {
  12690. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  12691. mg_free(ctx->config[idx]);
  12692. }
  12693. ctx->config[idx] = mg_strdup(value);
  12694. DEBUG_TRACE("[%s] -> [%s]", name, value);
  12695. }
  12696. /* Set default value if needed */
  12697. for (i = 0; config_options[i].name != NULL; i++) {
  12698. default_value = config_options[i].default_value;
  12699. if (ctx->config[i] == NULL && default_value != NULL) {
  12700. ctx->config[i] = mg_strdup(default_value);
  12701. }
  12702. }
  12703. workerthreadcount = atoi(ctx->config[NUM_THREADS]);
  12704. if (workerthreadcount > MAX_WORKER_THREADS) {
  12705. mg_cry(fc(ctx), "Too many worker threads");
  12706. free_context(ctx);
  12707. pthread_setspecific(sTlsKey, NULL);
  12708. return NULL;
  12709. }
  12710. if (workerthreadcount <= 0) {
  12711. mg_cry(fc(ctx), "Invalid number of worker threads");
  12712. free_context(ctx);
  12713. pthread_setspecific(sTlsKey, NULL);
  12714. return NULL;
  12715. }
  12716. #if defined(NO_FILES)
  12717. if (ctx->config[DOCUMENT_ROOT] != NULL) {
  12718. mg_cry(fc(ctx), "%s", "Document root must not be set");
  12719. free_context(ctx);
  12720. pthread_setspecific(sTlsKey, NULL);
  12721. return NULL;
  12722. }
  12723. #endif
  12724. get_system_name(&ctx->systemName);
  12725. #if defined(USE_LUA)
  12726. /* If a Lua background script has been configured, start it. */
  12727. if (ctx->config[LUA_BACKGROUND_SCRIPT] != NULL) {
  12728. char ebuf[256];
  12729. void *state = (void *)mg_prepare_lua_context_script(
  12730. ctx->config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  12731. if (!state) {
  12732. mg_cry(fc(ctx), "lua_background_script error: %s", ebuf);
  12733. free_context(ctx);
  12734. pthread_setspecific(sTlsKey, NULL);
  12735. return NULL;
  12736. }
  12737. ctx->lua_background_state = state;
  12738. } else {
  12739. ctx->lua_background_state = 0;
  12740. }
  12741. #endif
  12742. /* NOTE(lsm): order is important here. SSL certificates must
  12743. * be initialized before listening ports. UID must be set last. */
  12744. if (!set_gpass_option(ctx) ||
  12745. #if !defined(NO_SSL)
  12746. !set_ssl_option(ctx) ||
  12747. #endif
  12748. !set_ports_option(ctx) ||
  12749. #if !defined(_WIN32)
  12750. !set_uid_option(ctx) ||
  12751. #endif
  12752. !set_acl_option(ctx)) {
  12753. free_context(ctx);
  12754. pthread_setspecific(sTlsKey, NULL);
  12755. return NULL;
  12756. }
  12757. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  12758. /* Ignore SIGPIPE signal, so if browser cancels the request, it
  12759. * won't kill the whole process. */
  12760. (void)signal(SIGPIPE, SIG_IGN);
  12761. #endif /* !_WIN32 && !__SYMBIAN32__ */
  12762. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  12763. ctx->worker_threadids =
  12764. (pthread_t *)mg_calloc(ctx->cfg_worker_threads, sizeof(pthread_t));
  12765. if (ctx->worker_threadids == NULL) {
  12766. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  12767. free_context(ctx);
  12768. pthread_setspecific(sTlsKey, NULL);
  12769. return NULL;
  12770. }
  12771. ctx->worker_connections =
  12772. (struct mg_connection *)mg_calloc(ctx->cfg_worker_threads,
  12773. sizeof(struct mg_connection));
  12774. if (ctx->worker_connections == NULL) {
  12775. mg_cry(fc(ctx), "Not enough memory for worker thread connection array");
  12776. free_context(ctx);
  12777. pthread_setspecific(sTlsKey, NULL);
  12778. return NULL;
  12779. }
  12780. #if defined(ALTERNATIVE_QUEUE)
  12781. ctx->client_wait_events =
  12782. mg_calloc(sizeof(ctx->client_wait_events[0]), ctx->cfg_worker_threads);
  12783. if (ctx->client_wait_events == NULL) {
  12784. mg_cry(fc(ctx), "Not enough memory for worker event array");
  12785. mg_free(ctx->worker_threadids);
  12786. free_context(ctx);
  12787. pthread_setspecific(sTlsKey, NULL);
  12788. return NULL;
  12789. }
  12790. ctx->client_socks =
  12791. mg_calloc(sizeof(ctx->client_socks[0]), ctx->cfg_worker_threads);
  12792. if (ctx->client_wait_events == NULL) {
  12793. mg_cry(fc(ctx), "Not enough memory for worker socket array");
  12794. mg_free(ctx->client_socks);
  12795. mg_free(ctx->worker_threadids);
  12796. free_context(ctx);
  12797. pthread_setspecific(sTlsKey, NULL);
  12798. return NULL;
  12799. }
  12800. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  12801. ctx->client_wait_events[i] = event_create();
  12802. if (ctx->client_wait_events[i] == 0) {
  12803. mg_cry(fc(ctx), "Error creating worker event %i", i);
  12804. while (i > 0) {
  12805. i--;
  12806. event_destroy(ctx->client_wait_events[i]);
  12807. }
  12808. mg_free(ctx->client_socks);
  12809. mg_free(ctx->worker_threadids);
  12810. free_context(ctx);
  12811. pthread_setspecific(sTlsKey, NULL);
  12812. return NULL;
  12813. }
  12814. }
  12815. #endif
  12816. #if defined(USE_TIMERS)
  12817. if (timers_init(ctx) != 0) {
  12818. mg_cry(fc(ctx), "Error creating timers");
  12819. free_context(ctx);
  12820. pthread_setspecific(sTlsKey, NULL);
  12821. return NULL;
  12822. }
  12823. #endif
  12824. /* Context has been created - init user libraries */
  12825. if (ctx->callbacks.init_context) {
  12826. ctx->callbacks.init_context(ctx);
  12827. }
  12828. ctx->callbacks.exit_context = exit_callback;
  12829. ctx->context_type = 1; /* server context */
  12830. /* Start master (listening) thread */
  12831. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  12832. /* Start worker threads */
  12833. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  12834. struct worker_thread_args *wta =
  12835. mg_malloc(sizeof(struct worker_thread_args));
  12836. if (wta) {
  12837. wta->ctx = ctx;
  12838. wta->index = (int)i;
  12839. }
  12840. if ((wta == NULL)
  12841. || (mg_start_thread_with_id(worker_thread,
  12842. wta,
  12843. &ctx->worker_threadids[i]) != 0)) {
  12844. /* thread was not created */
  12845. if (wta != NULL) {
  12846. mg_free(wta);
  12847. }
  12848. if (i > 0) {
  12849. mg_cry(fc(ctx),
  12850. "Cannot start worker thread %i: error %ld",
  12851. i + 1,
  12852. (long)ERRNO);
  12853. } else {
  12854. mg_cry(fc(ctx),
  12855. "Cannot create threads: error %ld",
  12856. (long)ERRNO);
  12857. free_context(ctx);
  12858. pthread_setspecific(sTlsKey, NULL);
  12859. return NULL;
  12860. }
  12861. break;
  12862. }
  12863. }
  12864. pthread_setspecific(sTlsKey, NULL);
  12865. return ctx;
  12866. }
  12867. /* Feature check API function */
  12868. unsigned
  12869. mg_check_feature(unsigned feature)
  12870. {
  12871. static const unsigned feature_set = 0
  12872. /* Set bits for available features according to API documentation.
  12873. * This bit mask is created at compile time, according to the active
  12874. * preprocessor defines. It is a single const value at runtime. */
  12875. #if !defined(NO_FILES)
  12876. | 0x0001u
  12877. #endif
  12878. #if !defined(NO_SSL)
  12879. | 0x0002u
  12880. #endif
  12881. #if !defined(NO_CGI)
  12882. | 0x0004u
  12883. #endif
  12884. #if defined(USE_IPV6)
  12885. | 0x0008u
  12886. #endif
  12887. #if defined(USE_WEBSOCKET)
  12888. | 0x0010u
  12889. #endif
  12890. #if defined(USE_LUA)
  12891. | 0x0020u
  12892. #endif
  12893. #if defined(USE_DUKTAPE)
  12894. | 0x0040u
  12895. #endif
  12896. #if !defined(NO_CACHING)
  12897. | 0x0080u
  12898. #endif
  12899. /* Set some extra bits not defined in the API documentation.
  12900. * These bits may change without further notice. */
  12901. #if defined(MG_LEGACY_INTERFACE)
  12902. | 0x8000u
  12903. #endif
  12904. #if defined(MEMORY_DEBUGGING)
  12905. | 0x0100u
  12906. #endif
  12907. #if defined(USE_TIMERS)
  12908. | 0x0200u
  12909. #endif
  12910. #if !defined(NO_NONCE_CHECK)
  12911. | 0x0400u
  12912. #endif
  12913. #if !defined(NO_POPEN)
  12914. | 0x0800u
  12915. #endif
  12916. ;
  12917. return (feature & feature_set);
  12918. }
  12919. /* Get system information. It can be printed or stored by the caller.
  12920. * Return the size of available information. */
  12921. static int
  12922. mg_get_system_info_impl(char *buffer, int buflen)
  12923. {
  12924. char block[256];
  12925. int system_info_length = 0;
  12926. #if defined(_WIN32)
  12927. const char *eol = "\r\n";
  12928. #else
  12929. const char *eol = "\n";
  12930. #endif
  12931. /* Server version */
  12932. {
  12933. const char *version = mg_version();
  12934. mg_snprintf(NULL,
  12935. NULL,
  12936. block,
  12937. sizeof(block),
  12938. "Server Version: %s%s",
  12939. version,
  12940. eol);
  12941. system_info_length += (int)strlen(block);
  12942. if (system_info_length < buflen) {
  12943. strcat(buffer, block);
  12944. }
  12945. }
  12946. /* System info */
  12947. {
  12948. #if defined(_WIN32)
  12949. #if !defined(__SYMBIAN32__)
  12950. DWORD dwVersion = 0;
  12951. DWORD dwMajorVersion = 0;
  12952. DWORD dwMinorVersion = 0;
  12953. SYSTEM_INFO si;
  12954. GetSystemInfo(&si);
  12955. #ifdef _MSC_VER
  12956. #pragma warning(push)
  12957. /* GetVersion was declared deprecated */
  12958. #pragma warning(disable : 4996)
  12959. #endif
  12960. dwVersion = GetVersion();
  12961. #ifdef _MSC_VER
  12962. #pragma warning(pop)
  12963. #endif
  12964. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  12965. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  12966. mg_snprintf(NULL,
  12967. NULL,
  12968. block,
  12969. sizeof(block),
  12970. "Windows %u.%u%s",
  12971. (unsigned)dwMajorVersion,
  12972. (unsigned)dwMinorVersion,
  12973. eol);
  12974. system_info_length += (int)strlen(block);
  12975. if (system_info_length < buflen) {
  12976. strcat(buffer, block);
  12977. }
  12978. mg_snprintf(NULL,
  12979. NULL,
  12980. block,
  12981. sizeof(block),
  12982. "CPU: type %u, cores %u, mask %x%s",
  12983. (unsigned)si.wProcessorArchitecture,
  12984. (unsigned)si.dwNumberOfProcessors,
  12985. (unsigned)si.dwActiveProcessorMask,
  12986. eol);
  12987. system_info_length += (int)strlen(block);
  12988. if (system_info_length < buflen) {
  12989. strcat(buffer, block);
  12990. }
  12991. #else
  12992. mg_snprintf(NULL, NULL, block, sizeof(block), "%s - Symbian%s", eol);
  12993. system_info_length += (int)strlen(block);
  12994. if (system_info_length < buflen) {
  12995. strcat(buffer, block);
  12996. }
  12997. #endif
  12998. #else
  12999. struct utsname name;
  13000. memset(&name, 0, sizeof(name));
  13001. uname(&name);
  13002. mg_snprintf(NULL,
  13003. NULL,
  13004. block,
  13005. sizeof(block),
  13006. "%s %s (%s) - %s%s",
  13007. name.sysname,
  13008. name.version,
  13009. name.release,
  13010. name.machine,
  13011. eol);
  13012. system_info_length += (int)strlen(block);
  13013. if (system_info_length < buflen) {
  13014. strcat(buffer, block);
  13015. }
  13016. #endif
  13017. }
  13018. /* Features */
  13019. {
  13020. mg_snprintf(NULL,
  13021. NULL,
  13022. block,
  13023. sizeof(block),
  13024. "Features: %X%s%s%s%s%s%s%s%s%s%s",
  13025. mg_check_feature(0xFFFFFFFFu),
  13026. eol,
  13027. mg_check_feature(1) ? " Files" : "",
  13028. mg_check_feature(2) ? " HTTPS" : "",
  13029. mg_check_feature(4) ? " CGI" : "",
  13030. mg_check_feature(8) ? " IPv6" : "",
  13031. mg_check_feature(16) ? " WebSockets" : "",
  13032. mg_check_feature(32) ? " Lua" : "",
  13033. mg_check_feature(64) ? " JavaScript" : "",
  13034. mg_check_feature(128) ? " Cache" : "",
  13035. eol);
  13036. system_info_length += (int)strlen(block);
  13037. if (system_info_length < buflen) {
  13038. strcat(buffer, block);
  13039. }
  13040. #ifdef USE_LUA
  13041. mg_snprintf(NULL,
  13042. NULL,
  13043. block,
  13044. sizeof(block),
  13045. "Lua Version: %u (%s)%s",
  13046. (unsigned)LUA_VERSION_NUM,
  13047. LUA_RELEASE,
  13048. eol);
  13049. system_info_length += (int)strlen(block);
  13050. if (system_info_length < buflen) {
  13051. strcat(buffer, block);
  13052. }
  13053. #endif
  13054. #if defined(USE_DUKTAPE)
  13055. mg_snprintf(NULL,
  13056. NULL,
  13057. block,
  13058. sizeof(block),
  13059. "JavaScript: Duktape %u.%u.%u%s",
  13060. (unsigned)DUK_VERSION / 10000,
  13061. ((unsigned)DUK_VERSION / 100) % 100,
  13062. (unsigned)DUK_VERSION % 100,
  13063. eol);
  13064. system_info_length += (int)strlen(block);
  13065. if (system_info_length < buflen) {
  13066. strcat(buffer, block);
  13067. }
  13068. #endif
  13069. }
  13070. /* Build date */
  13071. {
  13072. mg_snprintf(
  13073. NULL, NULL, block, sizeof(block), "Build: %s%s", __DATE__, eol);
  13074. system_info_length += (int)strlen(block);
  13075. if (system_info_length < buflen) {
  13076. strcat(buffer, block);
  13077. }
  13078. }
  13079. /* Compiler information */
  13080. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  13081. {
  13082. #if defined(_MSC_VER)
  13083. mg_snprintf(NULL,
  13084. NULL,
  13085. block,
  13086. sizeof(block),
  13087. "MSC: %u (%u)%s",
  13088. (unsigned)_MSC_VER,
  13089. (unsigned)_MSC_FULL_VER,
  13090. eol);
  13091. system_info_length += (int)strlen(block);
  13092. if (system_info_length < buflen) {
  13093. strcat(buffer, block);
  13094. }
  13095. #elif defined(__MINGW64__)
  13096. mg_snprintf(NULL,
  13097. NULL,
  13098. block,
  13099. sizeof(block),
  13100. "MinGW64: %u.%u%s",
  13101. (unsigned)__MINGW64_VERSION_MAJOR,
  13102. (unsigned)__MINGW64_VERSION_MINOR,
  13103. eol);
  13104. system_info_length += (int)strlen(block);
  13105. if (system_info_length < buflen) {
  13106. strcat(buffer, block);
  13107. }
  13108. mg_snprintf(NULL,
  13109. NULL,
  13110. block,
  13111. sizeof(block),
  13112. "MinGW32: %u.%u%s",
  13113. (unsigned)__MINGW32_MAJOR_VERSION,
  13114. (unsigned)__MINGW32_MINOR_VERSION,
  13115. eol);
  13116. system_info_length += (int)strlen(block);
  13117. if (system_info_length < buflen) {
  13118. strcat(buffer, block);
  13119. }
  13120. #elif defined(__MINGW32__)
  13121. mg_snprintf(NULL,
  13122. NULL,
  13123. block,
  13124. sizeof(block),
  13125. "MinGW32: %u.%u%s",
  13126. (unsigned)__MINGW32_MAJOR_VERSION,
  13127. (unsigned)__MINGW32_MINOR_VERSION,
  13128. eol);
  13129. system_info_length += (int)strlen(block);
  13130. if (system_info_length < buflen) {
  13131. strcat(buffer, block);
  13132. }
  13133. #elif defined(__clang__)
  13134. mg_snprintf(NULL,
  13135. NULL,
  13136. block,
  13137. sizeof(block),
  13138. "clang: %u.%u.%u (%s)%s",
  13139. __clang_major__,
  13140. __clang_minor__,
  13141. __clang_patchlevel__,
  13142. __clang_version__,
  13143. eol);
  13144. system_info_length += (int)strlen(block);
  13145. if (system_info_length < buflen) {
  13146. strcat(buffer, block);
  13147. }
  13148. #elif defined(__GNUC__)
  13149. mg_snprintf(NULL,
  13150. NULL,
  13151. block,
  13152. sizeof(block),
  13153. "gcc: %u.%u.%u%s",
  13154. (unsigned)__GNUC__,
  13155. (unsigned)__GNUC_MINOR__,
  13156. (unsigned)__GNUC_PATCHLEVEL__,
  13157. eol);
  13158. system_info_length += (int)strlen(block);
  13159. if (system_info_length < buflen) {
  13160. strcat(buffer, block);
  13161. }
  13162. #elif defined(__INTEL_COMPILER)
  13163. mg_snprintf(NULL,
  13164. NULL,
  13165. block,
  13166. sizeof(block),
  13167. "Intel C/C++: %u%s",
  13168. (unsigned)__INTEL_COMPILER,
  13169. eol);
  13170. system_info_length += (int)strlen(block);
  13171. if (system_info_length < buflen) {
  13172. strcat(buffer, block);
  13173. }
  13174. #elif defined(__BORLANDC__)
  13175. mg_snprintf(NULL,
  13176. NULL,
  13177. block,
  13178. sizeof(block),
  13179. "Borland C: 0x%x%s",
  13180. (unsigned)__BORLANDC__,
  13181. eol);
  13182. system_info_length += (int)strlen(block);
  13183. if (system_info_length < buflen) {
  13184. strcat(buffer, block);
  13185. }
  13186. #elif defined(__SUNPRO_C)
  13187. mg_snprintf(NULL,
  13188. NULL,
  13189. block,
  13190. sizeof(block),
  13191. "Solaris: 0x%x%s",
  13192. (unsigned)__SUNPRO_C,
  13193. eol);
  13194. system_info_length += (int)strlen(block);
  13195. if (system_info_length < buflen) {
  13196. strcat(buffer, block);
  13197. }
  13198. #else
  13199. mg_snprintf(NULL, NULL, block, sizeof(block), "Other compiler%s", eol);
  13200. system_info_length += (int)strlen(block);
  13201. if (system_info_length < buflen) {
  13202. strcat(buffer, block);
  13203. }
  13204. #endif
  13205. }
  13206. /* Determine 32/64 bit data mode.
  13207. * see https://en.wikipedia.org/wiki/64-bit_computing */
  13208. {
  13209. mg_snprintf(NULL,
  13210. NULL,
  13211. block,
  13212. sizeof(block),
  13213. "Data model: int:%u/%u/%u/%u, float:%u/%u/%u, char:%u/%u, "
  13214. "ptr:%u, size:%u, time:%u%s",
  13215. (unsigned)sizeof(short),
  13216. (unsigned)sizeof(int),
  13217. (unsigned)sizeof(long),
  13218. (unsigned)sizeof(long long),
  13219. (unsigned)sizeof(float),
  13220. (unsigned)sizeof(double),
  13221. (unsigned)sizeof(long double),
  13222. (unsigned)sizeof(char),
  13223. (unsigned)sizeof(wchar_t),
  13224. (unsigned)sizeof(void *),
  13225. (unsigned)sizeof(size_t),
  13226. (unsigned)sizeof(time_t),
  13227. eol);
  13228. system_info_length += (int)strlen(block);
  13229. if (system_info_length < buflen) {
  13230. strcat(buffer, block);
  13231. }
  13232. }
  13233. return system_info_length;
  13234. }
  13235. /* Get system information. It can be printed or stored by the caller.
  13236. * Return the size of available information. */
  13237. int
  13238. mg_get_system_info(char *buffer, int buflen)
  13239. {
  13240. if ((buffer == NULL) || (buflen < 1)) {
  13241. return mg_get_system_info_impl(NULL, 0);
  13242. } else {
  13243. /* Reset buffer, so we can always use strcat. */
  13244. buffer[0] = 0;
  13245. return mg_get_system_info_impl(buffer, buflen);
  13246. }
  13247. }
  13248. /* mg_init_library counter */
  13249. static int mg_init_library_called = 0;
  13250. /* Initialize this library. This function does not need to be thread safe. */
  13251. unsigned
  13252. mg_init_library(unsigned features)
  13253. {
  13254. /* Currently we do nothing here. This is planned for Version 1.10.
  13255. * For now, we just add this function, so clients can be changed early. */
  13256. if (mg_init_library_called <= 0) {
  13257. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13258. WSADATA data;
  13259. WSAStartup(MAKEWORD(2, 2), &data);
  13260. #endif /* _WIN32 && !__SYMBIAN32__ */
  13261. mg_init_library_called = 1;
  13262. } else {
  13263. mg_init_library_called++;
  13264. }
  13265. return mg_check_feature(features & 0xFFu);
  13266. }
  13267. /* Un-initialize this library. */
  13268. unsigned
  13269. mg_exit_library(void)
  13270. {
  13271. if (mg_init_library_called <= 0) {
  13272. return 0;
  13273. }
  13274. mg_init_library_called--;
  13275. if (mg_init_library_called == 0) {
  13276. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  13277. (void)WSACleanup();
  13278. #endif /* _WIN32 && !__SYMBIAN32__ */
  13279. }
  13280. return 1;
  13281. }
  13282. /* End of civetweb.c */