civetweb.c 304 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589
  1. /* Copyright (c) 2013-2015 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. #ifdef __linux__
  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) && defined(USE_WEBSOCKET)
  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. /* mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8, "size_t data
  92. * type size check"); */
  93. /* DTL -- including winsock2.h works better if lean and mean */
  94. #ifndef WIN32_LEAN_AND_MEAN
  95. #define WIN32_LEAN_AND_MEAN
  96. #endif
  97. #if defined(__SYMBIAN32__)
  98. #define NO_SSL /* SSL is not supported */
  99. #define NO_CGI /* CGI is not supported */
  100. #define PATH_MAX FILENAME_MAX
  101. #endif /* __SYMBIAN32__ */
  102. #ifndef IGNORE_UNUSED_RESULT
  103. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  104. #endif
  105. #ifndef _WIN32_WCE /* Some ANSI #includes are not available on Windows CE */
  106. #include <sys/types.h>
  107. #include <sys/stat.h>
  108. #include <errno.h>
  109. #include <signal.h>
  110. #include <fcntl.h>
  111. #endif /* !_WIN32_WCE */
  112. #ifdef __MACH__
  113. #define CLOCK_MONOTONIC (1)
  114. #define CLOCK_REALTIME (2)
  115. #include <sys/time.h>
  116. #include <mach/clock.h>
  117. #include <mach/mach.h>
  118. #include <mach/mach_time.h>
  119. #include <assert.h>
  120. /* clock_gettime is not implemented on OSX */
  121. int clock_gettime(int clk_id, struct timespec *t);
  122. int clock_gettime(int clk_id, struct timespec *t)
  123. {
  124. if (clk_id == CLOCK_REALTIME) {
  125. struct timeval now;
  126. int rv = gettimeofday(&now, NULL);
  127. if (rv) {
  128. return rv;
  129. }
  130. t->tv_sec = now.tv_sec;
  131. t->tv_nsec = now.tv_usec * 1000;
  132. return 0;
  133. } else if (clk_id == CLOCK_MONOTONIC) {
  134. static uint64_t start_time = 0;
  135. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  136. uint64_t now = mach_absolute_time();
  137. if (start_time == 0) {
  138. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  139. #if defined(DEBUG)
  140. assert(mach_status == KERN_SUCCESS);
  141. #else
  142. /* appease "unused variable" warning for release builds */
  143. (void)mach_status;
  144. #endif
  145. start_time = now;
  146. }
  147. now =
  148. (uint64_t)((double)(now - start_time) * (double)timebase_ifo.numer /
  149. (double)timebase_ifo.denom);
  150. t->tv_sec = now / 1000000000;
  151. t->tv_nsec = now % 1000000000;
  152. return 0;
  153. }
  154. return -1; /* EINVAL - Clock ID is unknown */
  155. }
  156. #endif
  157. #include <time.h>
  158. #include <stdlib.h>
  159. #include <stdarg.h>
  160. #include <assert.h>
  161. #include <string.h>
  162. #include <ctype.h>
  163. #include <limits.h>
  164. #include <stddef.h>
  165. #include <stdio.h>
  166. #ifndef MAX_WORKER_THREADS
  167. #define MAX_WORKER_THREADS (1024 * 64)
  168. #endif
  169. #ifndef SOCKET_TIMEOUT_QUANTUM
  170. #define SOCKET_TIMEOUT_QUANTUM (10000)
  171. #endif
  172. mg_static_assert(MAX_WORKER_THREADS >= 1,
  173. "worker threads must be a positive number");
  174. #if defined(_WIN32) && \
  175. !defined(__SYMBIAN32__) /* WINDOWS / UNIX include block */
  176. #include <windows.h>
  177. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  178. #include <ws2tcpip.h>
  179. typedef const char *SOCK_OPT_TYPE;
  180. #if !defined(PATH_MAX)
  181. #define PATH_MAX (MAX_PATH)
  182. #endif
  183. #if !defined(PATH_MAX)
  184. #define PATH_MAX (4096)
  185. #endif
  186. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  187. #ifndef _IN_PORT_T
  188. #ifndef in_port_t
  189. #define in_port_t u_short
  190. #endif
  191. #endif
  192. #ifndef _WIN32_WCE
  193. #include <process.h>
  194. #include <direct.h>
  195. #include <io.h>
  196. #else /* _WIN32_WCE */
  197. #define NO_CGI /* WinCE has no pipes */
  198. typedef long off_t;
  199. #define errno ((int)(GetLastError()))
  200. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  201. #endif /* _WIN32_WCE */
  202. #define MAKEUQUAD(lo, hi) \
  203. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  204. #define RATE_DIFF (10000000) /* 100 nsecs */
  205. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  206. #define SYS2UNIX_TIME(lo, hi) \
  207. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  208. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  209. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  210. * Also use _strtoui64 on modern M$ compilers */
  211. #if defined(_MSC_VER)
  212. #if (_MSC_VER < 1300)
  213. #define STRX(x) #x
  214. #define STR(x) STRX(x)
  215. #define __func__ __FILE__ ":" STR(__LINE__)
  216. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  217. #define strtoll(x, y, z) (_atoi64(x))
  218. #else
  219. #define __func__ __FUNCTION__
  220. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  221. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  222. #endif
  223. #endif /* _MSC_VER */
  224. #define ERRNO ((int)(GetLastError()))
  225. #define NO_SOCKLEN_T
  226. #define SSL_LIB "ssleay32.dll"
  227. #define CRYPTO_LIB "libeay32.dll"
  228. #define O_NONBLOCK (0)
  229. #ifndef W_OK
  230. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  231. #endif
  232. #if !defined(EWOULDBLOCK)
  233. #define EWOULDBLOCK WSAEWOULDBLOCK
  234. #endif /* !EWOULDBLOCK */
  235. #define _POSIX_
  236. #define INT64_FMT "I64d"
  237. #define WINCDECL __cdecl
  238. #define SHUT_RD (0)
  239. #define SHUT_WR (1)
  240. #define SHUT_BOTH (2)
  241. #define vsnprintf_impl _vsnprintf
  242. #define access _access
  243. #define mg_sleep(x) (Sleep(x))
  244. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  245. #ifndef popen
  246. #define popen(x, y) (_popen(x, y))
  247. #endif
  248. #ifndef pclose
  249. #define pclose(x) (_pclose(x))
  250. #endif
  251. #define close(x) (_close(x))
  252. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  253. #define RTLD_LAZY (0)
  254. #define fseeko(x, y, z) (_lseeki64(_fileno(x), (y), (z)) == -1 ? -1 : 0)
  255. #define fdopen(x, y) (_fdopen((x), (y)))
  256. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  257. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  258. #define flockfile(x) (EnterCriticalSection(&global_log_file_lock))
  259. #define funlockfile(x) (LeaveCriticalSection(&global_log_file_lock))
  260. #define sleep(x) (Sleep((x)*1000))
  261. #define rmdir(x) (_rmdir(x))
  262. #if !defined(fileno)
  263. #define fileno(x) (_fileno(x))
  264. #endif /* !fileno MINGW #defines fileno */
  265. typedef HANDLE pthread_mutex_t;
  266. typedef DWORD pthread_key_t;
  267. typedef HANDLE pthread_t;
  268. typedef struct {
  269. CRITICAL_SECTION threadIdSec;
  270. int waitingthreadcount; /* The number of threads queued. */
  271. pthread_t *waitingthreadhdls; /* The thread handles. */
  272. } pthread_cond_t;
  273. #ifndef __clockid_t_defined
  274. typedef DWORD clockid_t;
  275. #endif
  276. #ifndef CLOCK_MONOTONIC
  277. #define CLOCK_MONOTONIC (1)
  278. #endif
  279. #ifndef CLOCK_REALTIME
  280. #define CLOCK_REALTIME (2)
  281. #endif
  282. #ifndef _TIMESPEC_DEFINED
  283. struct timespec {
  284. time_t tv_sec; /* seconds */
  285. long tv_nsec; /* nanoseconds */
  286. };
  287. #endif
  288. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  289. static int pthread_mutex_lock(pthread_mutex_t *);
  290. static int pthread_mutex_unlock(pthread_mutex_t *);
  291. static void to_unicode(const char *path, wchar_t *wbuf, size_t wbuf_len);
  292. struct file;
  293. static char *mg_fgets(char *buf, size_t size, struct file *filep, char **p);
  294. #if defined(HAVE_STDINT)
  295. #include <stdint.h>
  296. #else
  297. typedef unsigned int uint32_t;
  298. typedef unsigned short uint16_t;
  299. typedef unsigned __int64 uint64_t;
  300. typedef __int64 int64_t;
  301. #define INT64_MAX (9223372036854775807)
  302. #endif /* HAVE_STDINT */
  303. /* POSIX dirent interface */
  304. struct dirent {
  305. char d_name[PATH_MAX];
  306. };
  307. typedef struct DIR {
  308. HANDLE handle;
  309. WIN32_FIND_DATAW info;
  310. struct dirent result;
  311. } DIR;
  312. #if defined(_WIN32) && !defined(POLLIN)
  313. #ifndef HAVE_POLL
  314. struct pollfd {
  315. SOCKET fd;
  316. short events;
  317. short revents;
  318. };
  319. #define POLLIN (0x0300)
  320. #endif
  321. #endif
  322. /* Mark required libraries */
  323. #if defined(_MSC_VER)
  324. #pragma comment(lib, "Ws2_32.lib")
  325. #endif
  326. #else /* defined(_WIN32) && !defined(__SYMBIAN32__) - WINDOWS / UNIX include \
  327. block */
  328. #include <sys/wait.h>
  329. #include <sys/socket.h>
  330. #include <sys/poll.h>
  331. #include <netinet/in.h>
  332. #include <arpa/inet.h>
  333. #include <sys/time.h>
  334. #include <sys/utsname.h>
  335. #include <stdint.h>
  336. #include <inttypes.h>
  337. #include <netdb.h>
  338. typedef const void *SOCK_OPT_TYPE;
  339. #if defined(ANDROID)
  340. typedef unsigned short int in_port_t;
  341. #endif
  342. #include <pwd.h>
  343. #include <unistd.h>
  344. #include <grp.h>
  345. #include <dirent.h>
  346. #define vsnprintf_impl vsnprintf
  347. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  348. #include <dlfcn.h>
  349. #endif
  350. #include <pthread.h>
  351. #if defined(__MACH__)
  352. #define SSL_LIB "libssl.dylib"
  353. #define CRYPTO_LIB "libcrypto.dylib"
  354. #else
  355. #if !defined(SSL_LIB)
  356. #define SSL_LIB "libssl.so"
  357. #endif
  358. #if !defined(CRYPTO_LIB)
  359. #define CRYPTO_LIB "libcrypto.so"
  360. #endif
  361. #endif
  362. #ifndef O_BINARY
  363. #define O_BINARY (0)
  364. #endif /* O_BINARY */
  365. #define closesocket(a) (close(a))
  366. #define mg_mkdir(x, y) (mkdir(x, y))
  367. #define mg_remove(x) (remove(x))
  368. #define mg_sleep(x) (usleep((x)*1000))
  369. #define ERRNO (errno)
  370. #define INVALID_SOCKET (-1)
  371. #define INT64_FMT PRId64
  372. typedef int SOCKET;
  373. #define WINCDECL
  374. #if defined(__hpux)
  375. /* HPUX 11 does not have monotonic, fall back to realtime */
  376. #ifndef CLOCK_MONOTONIC
  377. #define CLOCK_MONOTONIC CLOCK_REALTIME
  378. #endif
  379. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  380. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  381. * the prototypes use int* rather than socklen_t* which matches the
  382. * actual library expectation. When called with the wrong size arg
  383. * accept() returns a zero client inet addr and check_acl() always
  384. * fails. Since socklen_t is widely used below, just force replace
  385. * their typedef with int. - DTL
  386. */
  387. #define socklen_t int
  388. #endif /* hpux */
  389. #endif /* defined(_WIN32) && !defined(__SYMBIAN32__) - WINDOWS / UNIX include \
  390. block */
  391. /* va_copy should always be a macro, C99 and C++11 - DTL */
  392. #ifndef va_copy
  393. #define va_copy(x, y) ((x) = (y))
  394. #endif
  395. #ifdef _WIN32
  396. /* Create substitutes for POSIX functions in Win32. */
  397. #if defined(__MINGW32__)
  398. /* Show no warning in case system functions are not used. */
  399. #pragma GCC diagnostic push
  400. #pragma GCC diagnostic ignored "-Wunused-function"
  401. #endif
  402. static CRITICAL_SECTION global_log_file_lock;
  403. static DWORD pthread_self(void)
  404. {
  405. return GetCurrentThreadId();
  406. }
  407. static int pthread_key_create(
  408. pthread_key_t *key,
  409. void (*_ignored)(void *) /* destructor not supported for Windows */
  410. )
  411. {
  412. (void)_ignored;
  413. if ((key != 0)) {
  414. *key = TlsAlloc();
  415. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  416. }
  417. return -2;
  418. }
  419. static int pthread_key_delete(pthread_key_t key)
  420. {
  421. return TlsFree(key) ? 0 : 1;
  422. }
  423. static int pthread_setspecific(pthread_key_t key, void *value)
  424. {
  425. return TlsSetValue(key, value) ? 0 : 1;
  426. }
  427. static void *pthread_getspecific(pthread_key_t key)
  428. {
  429. return TlsGetValue(key);
  430. }
  431. #if defined(__MINGW32__)
  432. /* Enable unused function warning again */
  433. #pragma GCC diagnostic pop
  434. #endif
  435. #endif /* _WIN32 */
  436. #include "civetweb.h"
  437. #define PASSWORDS_FILE_NAME ".htpasswd"
  438. #define CGI_ENVIRONMENT_SIZE (4096)
  439. #define MAX_CGI_ENVIR_VARS (256)
  440. #define MG_BUF_LEN (8192)
  441. #ifndef MAX_REQUEST_SIZE
  442. #define MAX_REQUEST_SIZE (16384)
  443. #endif
  444. mg_static_assert(MAX_REQUEST_SIZE >= 256,
  445. "request size length must be a positive number");
  446. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  447. #if !defined(DEBUG_TRACE)
  448. #if defined(DEBUG)
  449. static void DEBUG_TRACE_FUNC(const char *func,
  450. unsigned line,
  451. PRINTF_FORMAT_STRING(const char *fmt),
  452. ...) PRINTF_ARGS(3, 4);
  453. static void
  454. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  455. {
  456. va_list args;
  457. flockfile(stdout);
  458. printf("*** %lu.%p.%s.%u: ",
  459. (unsigned long)time(NULL),
  460. (void *)pthread_self(),
  461. func,
  462. line);
  463. va_start(args, fmt);
  464. vprintf(fmt, args);
  465. va_end(args);
  466. putchar('\n');
  467. fflush(stdout);
  468. funlockfile(stdout);
  469. }
  470. #define DEBUG_TRACE(fmt, ...) \
  471. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  472. #else
  473. #define DEBUG_TRACE(fmt, ...) \
  474. do { \
  475. } while (0)
  476. #endif /* DEBUG */
  477. #endif /* DEBUG_TRACE */
  478. #if defined(MEMORY_DEBUGGING)
  479. unsigned long mg_memory_debug_blockCount = 0;
  480. unsigned long mg_memory_debug_totalMemUsed = 0;
  481. static void *mg_malloc_ex(size_t size, const char *file, unsigned line)
  482. {
  483. void *data = malloc(size + sizeof(size_t));
  484. void *memory = 0;
  485. char mallocStr[256];
  486. if (data) {
  487. *(size_t *)data = size;
  488. mg_memory_debug_totalMemUsed += size;
  489. mg_memory_debug_blockCount++;
  490. memory = (void *)(((char *)data) + sizeof(size_t));
  491. }
  492. sprintf(mallocStr,
  493. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  494. memory,
  495. (unsigned long)size,
  496. mg_memory_debug_totalMemUsed,
  497. mg_memory_debug_blockCount,
  498. file,
  499. line);
  500. #if defined(_WIN32)
  501. OutputDebugStringA(mallocStr);
  502. #else
  503. DEBUG_TRACE("%s", mallocStr);
  504. #endif
  505. return memory;
  506. }
  507. static void *
  508. mg_calloc_ex(size_t count, size_t size, const char *file, unsigned line)
  509. {
  510. void *data = mg_malloc_ex(size * count, file, line);
  511. if (data) {
  512. memset(data, 0, size);
  513. }
  514. return data;
  515. }
  516. static void mg_free_ex(void *memory, const char *file, unsigned line)
  517. {
  518. char mallocStr[256];
  519. void *data = (void *)(((char *)memory) - sizeof(size_t));
  520. size_t size;
  521. if (memory) {
  522. size = *(size_t *)data;
  523. mg_memory_debug_totalMemUsed -= size;
  524. mg_memory_debug_blockCount--;
  525. sprintf(mallocStr,
  526. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  527. memory,
  528. (unsigned long)size,
  529. mg_memory_debug_totalMemUsed,
  530. mg_memory_debug_blockCount,
  531. file,
  532. line);
  533. #if defined(_WIN32)
  534. OutputDebugStringA(mallocStr);
  535. #else
  536. DEBUG_TRACE("%s", mallocStr);
  537. #endif
  538. free(data);
  539. }
  540. }
  541. static void *
  542. mg_realloc_ex(void *memory, size_t newsize, const char *file, unsigned line)
  543. {
  544. char mallocStr[256];
  545. void *data;
  546. void *_realloc;
  547. size_t oldsize;
  548. if (newsize) {
  549. if (memory) {
  550. data = (void *)(((char *)memory) - sizeof(size_t));
  551. oldsize = *(size_t *)data;
  552. _realloc = realloc(data, newsize + sizeof(size_t));
  553. if (_realloc) {
  554. data = _realloc;
  555. mg_memory_debug_totalMemUsed -= oldsize;
  556. sprintf(mallocStr,
  557. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  558. memory,
  559. (unsigned long)oldsize,
  560. mg_memory_debug_totalMemUsed,
  561. mg_memory_debug_blockCount,
  562. file,
  563. line);
  564. #if defined(_WIN32)
  565. OutputDebugStringA(mallocStr);
  566. #else
  567. DEBUG_TRACE("%s", mallocStr);
  568. #endif
  569. mg_memory_debug_totalMemUsed += newsize;
  570. sprintf(mallocStr,
  571. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  572. memory,
  573. (unsigned long)newsize,
  574. mg_memory_debug_totalMemUsed,
  575. mg_memory_debug_blockCount,
  576. file,
  577. line);
  578. #if defined(_WIN32)
  579. OutputDebugStringA(mallocStr);
  580. #else
  581. DEBUG_TRACE("%s", mallocStr);
  582. #endif
  583. *(size_t *)data = newsize;
  584. data = (void *)(((char *)data) + sizeof(size_t));
  585. } else {
  586. #if defined(_WIN32)
  587. OutputDebugStringA("MEM: realloc failed\n");
  588. #else
  589. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  590. #endif
  591. return _realloc;
  592. }
  593. } else {
  594. data = mg_malloc_ex(newsize, file, line);
  595. }
  596. } else {
  597. data = 0;
  598. mg_free_ex(memory, file, line);
  599. }
  600. return data;
  601. }
  602. #define mg_malloc(a) mg_malloc_ex(a, __FILE__, __LINE__)
  603. #define mg_calloc(a, b) mg_calloc_ex(a, b, __FILE__, __LINE__)
  604. #define mg_realloc(a, b) mg_realloc_ex(a, b, __FILE__, __LINE__)
  605. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  606. #else
  607. static __inline void *mg_malloc(size_t a)
  608. {
  609. return malloc(a);
  610. }
  611. static __inline void *mg_calloc(size_t a, size_t b)
  612. {
  613. return calloc(a, b);
  614. }
  615. static __inline void *mg_realloc(void *a, size_t b)
  616. {
  617. return realloc(a, b);
  618. }
  619. static __inline void mg_free(void *a)
  620. {
  621. free(a);
  622. }
  623. #endif
  624. static void mg_vsnprintf(const struct mg_connection *conn,
  625. int *truncated,
  626. char *buf,
  627. size_t buflen,
  628. const char *fmt,
  629. va_list ap);
  630. static void mg_snprintf(const struct mg_connection *conn,
  631. int *truncated,
  632. char *buf,
  633. size_t buflen,
  634. PRINTF_FORMAT_STRING(const char *fmt),
  635. ...) PRINTF_ARGS(5, 6);
  636. /* This following lines are just meant as a reminder to use the mg-functions
  637. * for memory management */
  638. #ifdef malloc
  639. #undef malloc
  640. #endif
  641. #ifdef calloc
  642. #undef calloc
  643. #endif
  644. #ifdef realloc
  645. #undef realloc
  646. #endif
  647. #ifdef free
  648. #undef free
  649. #endif
  650. #ifdef snprintf
  651. #undef snprintf
  652. #endif
  653. #ifdef vsnprintf
  654. #undef vsnprintf
  655. #endif
  656. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  657. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  658. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  659. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  660. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  661. #ifdef _WIN32 /* vsnprintf must not be used in any system, * \
  662. * but this define only works well for Windows. */
  663. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  664. #endif
  665. #define MD5_STATIC static
  666. #include "md5.inl"
  667. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  668. #ifdef NO_SOCKLEN_T
  669. typedef int socklen_t;
  670. #endif /* NO_SOCKLEN_T */
  671. #define _DARWIN_UNLIMITED_SELECT
  672. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  673. #if !defined(MSG_NOSIGNAL)
  674. #define MSG_NOSIGNAL (0)
  675. #endif
  676. #if !defined(SOMAXCONN)
  677. #define SOMAXCONN (100)
  678. #endif
  679. /* Size of the accepted socket queue */
  680. #if !defined(MGSQLEN)
  681. #define MGSQLEN (20)
  682. #endif
  683. #if defined(NO_SSL_DL)
  684. #include <openssl/ssl.h>
  685. #include <openssl/err.h>
  686. #else
  687. /* SSL loaded dynamically from DLL.
  688. * I put the prototypes here to be independent from OpenSSL source
  689. * installation. */
  690. typedef struct ssl_st SSL;
  691. typedef struct ssl_method_st SSL_METHOD;
  692. typedef struct ssl_ctx_st SSL_CTX;
  693. struct ssl_func {
  694. const char *name; /* SSL function name */
  695. void (*ptr)(void); /* Function pointer */
  696. };
  697. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  698. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  699. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  700. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  701. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  702. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  703. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  704. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  705. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  706. #define SSLv23_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  707. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  708. #define SSL_CTX_use_PrivateKey_file \
  709. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  710. #define SSL_CTX_use_certificate_file \
  711. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  712. #define SSL_CTX_set_default_passwd_cb \
  713. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  714. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  715. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  716. #define SSL_CTX_use_certificate_chain_file \
  717. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  718. #define SSLv23_client_method (*(SSL_METHOD * (*)(void))ssl_sw[17].ptr)
  719. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  720. #define SSL_CTX_set_verify (*(void (*)(SSL_CTX *, int, int))ssl_sw[19].ptr)
  721. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  722. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  723. #define CRYPTO_set_locking_callback \
  724. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  725. #define CRYPTO_set_id_callback \
  726. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  727. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  728. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  729. /* set_ssl_option() function updates this array.
  730. * It loads SSL library dynamically and changes NULLs to the actual addresses
  731. * of respective functions. The macros above (like SSL_connect()) are really
  732. * just calling these functions indirectly via the pointer. */
  733. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  734. {"SSL_accept", NULL},
  735. {"SSL_connect", NULL},
  736. {"SSL_read", NULL},
  737. {"SSL_write", NULL},
  738. {"SSL_get_error", NULL},
  739. {"SSL_set_fd", NULL},
  740. {"SSL_new", NULL},
  741. {"SSL_CTX_new", NULL},
  742. {"SSLv23_server_method", NULL},
  743. {"SSL_library_init", NULL},
  744. {"SSL_CTX_use_PrivateKey_file", NULL},
  745. {"SSL_CTX_use_certificate_file", NULL},
  746. {"SSL_CTX_set_default_passwd_cb", NULL},
  747. {"SSL_CTX_free", NULL},
  748. {"SSL_load_error_strings", NULL},
  749. {"SSL_CTX_use_certificate_chain_file", NULL},
  750. {"SSLv23_client_method", NULL},
  751. {"SSL_pending", NULL},
  752. {"SSL_CTX_set_verify", NULL},
  753. {"SSL_shutdown", NULL},
  754. {NULL, NULL}};
  755. /* Similar array as ssl_sw. These functions could be located in different
  756. * lib. */
  757. #if !defined(NO_SSL)
  758. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  759. {"CRYPTO_set_locking_callback", NULL},
  760. {"CRYPTO_set_id_callback", NULL},
  761. {"ERR_get_error", NULL},
  762. {"ERR_error_string", NULL},
  763. {NULL, NULL}};
  764. #endif /* NO_SSL */
  765. #endif /* NO_SSL_DL */
  766. static const char *month_names[] = {"Jan",
  767. "Feb",
  768. "Mar",
  769. "Apr",
  770. "May",
  771. "Jun",
  772. "Jul",
  773. "Aug",
  774. "Sep",
  775. "Oct",
  776. "Nov",
  777. "Dec"};
  778. /* Unified socket address. For IPv6 support, add IPv6 address structure in the
  779. * union u. */
  780. union usa {
  781. struct sockaddr sa;
  782. struct sockaddr_in sin;
  783. #if defined(USE_IPV6)
  784. struct sockaddr_in6 sin6;
  785. #endif
  786. };
  787. /* Describes a string (chunk of memory). */
  788. struct vec {
  789. const char *ptr;
  790. size_t len;
  791. };
  792. struct file {
  793. uint64_t size;
  794. time_t last_modified;
  795. FILE *fp;
  796. const char *membuf; /* Non-NULL if file data is in memory */
  797. int is_directory;
  798. int gzipped; /* set to 1 if the content is gzipped
  799. * in which case we need a content-encoding: gzip header */
  800. };
  801. #define STRUCT_FILE_INITIALIZER \
  802. { \
  803. (uint64_t)0, (time_t)0, (FILE *)NULL, (const char *)NULL, 0, 0 \
  804. }
  805. /* Describes listening socket, or socket which was accept()-ed by the master
  806. * thread and queued for future handling by the worker thread. */
  807. struct socket {
  808. SOCKET sock; /* Listening socket */
  809. union usa lsa; /* Local socket address */
  810. union usa rsa; /* Remote socket address */
  811. unsigned char is_ssl; /* Is port SSL-ed */
  812. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  813. * port */
  814. };
  815. /* NOTE(lsm): this enum shoulds be in sync with the config_options below. */
  816. enum {
  817. CGI_EXTENSIONS,
  818. CGI_ENVIRONMENT,
  819. PUT_DELETE_PASSWORDS_FILE,
  820. CGI_INTERPRETER,
  821. PROTECT_URI,
  822. AUTHENTICATION_DOMAIN,
  823. SSI_EXTENSIONS,
  824. THROTTLE,
  825. ACCESS_LOG_FILE,
  826. ENABLE_DIRECTORY_LISTING,
  827. ERROR_LOG_FILE,
  828. GLOBAL_PASSWORDS_FILE,
  829. INDEX_FILES,
  830. ENABLE_KEEP_ALIVE,
  831. ACCESS_CONTROL_LIST,
  832. EXTRA_MIME_TYPES,
  833. LISTENING_PORTS,
  834. DOCUMENT_ROOT,
  835. SSL_CERTIFICATE,
  836. NUM_THREADS,
  837. RUN_AS_USER,
  838. REWRITE,
  839. HIDE_FILES,
  840. REQUEST_TIMEOUT,
  841. #if defined(USE_WEBSOCKET)
  842. WEBSOCKET_TIMEOUT,
  843. #endif
  844. DECODE_URL,
  845. #if defined(USE_LUA)
  846. LUA_PRELOAD_FILE,
  847. LUA_SCRIPT_EXTENSIONS,
  848. LUA_SERVER_PAGE_EXTENSIONS,
  849. #endif
  850. #if defined(USE_DUKTAPE)
  851. DUKTAPE_SCRIPT_EXTENSIONS,
  852. #endif
  853. #if defined(USE_WEBSOCKET)
  854. WEBSOCKET_ROOT,
  855. #endif
  856. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  857. LUA_WEBSOCKET_EXTENSIONS,
  858. #endif
  859. ACCESS_CONTROL_ALLOW_ORIGIN,
  860. ERROR_PAGES,
  861. NUM_OPTIONS
  862. };
  863. /* Config option name, config types, default value */
  864. static struct mg_option config_options[] = {
  865. {"cgi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  866. {"cgi_environment", CONFIG_TYPE_STRING, NULL},
  867. {"put_delete_auth_file", CONFIG_TYPE_FILE, NULL},
  868. {"cgi_interpreter", CONFIG_TYPE_FILE, NULL},
  869. {"protect_uri", CONFIG_TYPE_STRING, NULL},
  870. {"authentication_domain", CONFIG_TYPE_STRING, "mydomain.com"},
  871. {"ssi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  872. {"throttle", CONFIG_TYPE_STRING, NULL},
  873. {"access_log_file", CONFIG_TYPE_FILE, NULL},
  874. {"enable_directory_listing", CONFIG_TYPE_BOOLEAN, "yes"},
  875. {"error_log_file", CONFIG_TYPE_FILE, NULL},
  876. {"global_auth_file", CONFIG_TYPE_FILE, NULL},
  877. {"index_files",
  878. CONFIG_TYPE_STRING,
  879. #ifdef USE_LUA
  880. "index.xhtml,index.html,index.htm,index.lp,index.lsp,index.lua,index.cgi,"
  881. "index.shtml,index.php"},
  882. #else
  883. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  884. #endif
  885. {"enable_keep_alive", CONFIG_TYPE_BOOLEAN, "no"},
  886. {"access_control_list", CONFIG_TYPE_STRING, NULL},
  887. {"extra_mime_types", CONFIG_TYPE_STRING, NULL},
  888. {"listening_ports", CONFIG_TYPE_STRING, "8080"},
  889. {"document_root", CONFIG_TYPE_DIRECTORY, NULL},
  890. {"ssl_certificate", CONFIG_TYPE_FILE, NULL},
  891. {"num_threads", CONFIG_TYPE_NUMBER, "50"},
  892. {"run_as_user", CONFIG_TYPE_STRING, NULL},
  893. {"url_rewrite_patterns", CONFIG_TYPE_STRING, NULL},
  894. {"hide_files_patterns", CONFIG_TYPE_EXT_PATTERN, NULL},
  895. {"request_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  896. #if defined(USE_WEBSOCKET)
  897. {"websocket_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  898. #endif
  899. {"decode_url", CONFIG_TYPE_BOOLEAN, "yes"},
  900. #if defined(USE_LUA)
  901. {"lua_preload_file", CONFIG_TYPE_FILE, NULL},
  902. {"lua_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  903. {"lua_server_page_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  904. #endif
  905. #if defined(USE_DUKTAPE)
  906. {"_experimental_duktape_script_pattern",
  907. CONFIG_TYPE_EXT_PATTERN,
  908. "**.ssjs$"}, /* TODO: redefine parameter */
  909. #endif
  910. #if defined(USE_WEBSOCKET)
  911. {"websocket_root", CONFIG_TYPE_DIRECTORY, NULL},
  912. #endif
  913. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  914. {"lua_websocket_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  915. #endif
  916. {"access_control_allow_origin", CONFIG_TYPE_STRING, "*"},
  917. {"error_pages", CONFIG_TYPE_DIRECTORY, NULL},
  918. {NULL, CONFIG_TYPE_UNKNOWN, NULL}};
  919. /* Check if the config_options and the corresponding enum have compatible
  920. * sizes. */
  921. mg_static_assert((sizeof(config_options) / sizeof(config_options[0])) ==
  922. (NUM_OPTIONS + 1),
  923. "config_options and enum not sync");
  924. struct mg_request_handler_info {
  925. /* Name/Pattern of the URI. */
  926. char *uri;
  927. size_t uri_len;
  928. /* URI type: ws/wss (websocket) or http/https (web page). */
  929. int is_websocket_handler;
  930. /* Handler for http/https requests. */
  931. mg_request_handler handler;
  932. /* Handler for ws/wss (websocket) requests. */
  933. mg_websocket_connect_handler connect_handler;
  934. mg_websocket_ready_handler ready_handler;
  935. mg_websocket_data_handler data_handler;
  936. mg_websocket_close_handler close_handler;
  937. /* User supplied argument for the handler function. */
  938. void *cbdata;
  939. /* next request handler in a linked list */
  940. struct mg_request_handler_info *next;
  941. };
  942. struct mg_context {
  943. volatile int stop_flag; /* Should we stop event loop */
  944. SSL_CTX *ssl_ctx; /* SSL context */
  945. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  946. struct mg_callbacks callbacks; /* User-defined callback function */
  947. void *user_data; /* User-defined data */
  948. int context_type; /* 1 = server context, 2 = client context */
  949. struct socket *listening_sockets;
  950. in_port_t *listening_ports;
  951. unsigned int num_listening_sockets;
  952. volatile int
  953. running_worker_threads; /* Number of currently running worker threads */
  954. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  955. pthread_cond_t thread_cond; /* Condvar for tracking workers terminations */
  956. struct socket queue[MGSQLEN]; /* Accepted sockets */
  957. volatile int sq_head; /* Head of the socket queue */
  958. volatile int sq_tail; /* Tail of the socket queue */
  959. pthread_cond_t sq_full; /* Signaled when socket is produced */
  960. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  961. pthread_t masterthreadid; /* The master thread ID */
  962. unsigned int
  963. cfg_worker_threads; /* The number of configured worker threads. */
  964. pthread_t *workerthreadids; /* The worker thread IDs */
  965. unsigned long start_time; /* Server start time, used for authentication */
  966. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  967. unsigned long nonce_count; /* Used nonces, used for authentication */
  968. char *systemName; /* What operating system is running */
  969. /* linked list of uri handlers */
  970. struct mg_request_handler_info *request_handlers;
  971. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  972. /* linked list of shared lua websockets */
  973. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  974. #endif
  975. #ifdef USE_TIMERS
  976. struct ttimers *timers;
  977. #endif
  978. };
  979. struct mg_connection {
  980. struct mg_request_info request_info;
  981. struct mg_context *ctx;
  982. SSL *ssl; /* SSL descriptor */
  983. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  984. struct socket client; /* Connected client */
  985. time_t conn_birth_time; /* Time (wall clock) when connection was
  986. * established */
  987. struct timespec req_time; /* Time (since system start) when the request
  988. * was received */
  989. int64_t num_bytes_sent; /* Total bytes sent to client */
  990. int64_t content_len; /* Content-Length header value */
  991. int64_t consumed_content; /* How many bytes of content have been read */
  992. int is_chunked; /* Transfer-Encoding is chunked: 0=no, 1=yes:
  993. * data available, 2: all data read */
  994. size_t chunk_remainder; /* Unread data from the last chunk */
  995. char *buf; /* Buffer for received data */
  996. char *path_info; /* PATH_INFO part of the URL */
  997. int must_close; /* 1 if connection must be closed */
  998. int in_error_handler; /* 1 if in handler for user defined error
  999. * pages */
  1000. int internal_error; /* 1 if an error occured while processing the
  1001. * request */
  1002. int buf_size; /* Buffer size */
  1003. int request_len; /* Size of the request + headers in a buffer */
  1004. int data_len; /* Total size of data in a buffer */
  1005. int status_code; /* HTTP reply status code, e.g. 200 */
  1006. int throttle; /* Throttling, bytes/sec. <= 0 means no
  1007. * throttle */
  1008. time_t last_throttle_time; /* Last time throttled data was sent */
  1009. int64_t last_throttle_bytes; /* Bytes sent this second */
  1010. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  1011. * atomic transmissions for websockets */
  1012. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1013. void *lua_websocket_state; /* Lua_State for a websocket connection */
  1014. #endif
  1015. };
  1016. static pthread_key_t sTlsKey; /* Thread local storage index */
  1017. static int sTlsInit = 0;
  1018. static int thread_idx_max = 0;
  1019. struct mg_workerTLS {
  1020. int is_master;
  1021. unsigned long thread_idx;
  1022. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1023. HANDLE pthread_cond_helper_mutex;
  1024. #endif
  1025. };
  1026. /* Directory entry */
  1027. struct de {
  1028. struct mg_connection *conn;
  1029. char *file_name;
  1030. struct file file;
  1031. };
  1032. #if defined(USE_WEBSOCKET)
  1033. static int is_websocket_protocol(const struct mg_connection *conn);
  1034. #else
  1035. #define is_websocket_protocol(conn) (0)
  1036. #endif
  1037. static int mg_atomic_inc(volatile int *addr)
  1038. {
  1039. int ret;
  1040. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1041. /* Depending on the SDK, this function uses either
  1042. * (volatile unsigned int *) or (volatile LONG *),
  1043. * so whatever you use, the other SDK is likely to raise a warning. */
  1044. ret = InterlockedIncrement((volatile long *)addr);
  1045. #elif defined(__GNUC__)
  1046. ret = __sync_add_and_fetch(addr, 1);
  1047. #else
  1048. ret = (++(*addr));
  1049. #endif
  1050. return ret;
  1051. }
  1052. static int mg_atomic_dec(volatile int *addr)
  1053. {
  1054. int ret;
  1055. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1056. /* Depending on the SDK, this function uses either
  1057. * (volatile unsigned int *) or (volatile LONG *),
  1058. * so whatever you use, the other SDK is likely to raise a warning. */
  1059. ret = InterlockedDecrement((volatile long *)addr);
  1060. #elif defined(__GNUC__)
  1061. ret = __sync_sub_and_fetch(addr, 1);
  1062. #else
  1063. ret = (--(*addr));
  1064. #endif
  1065. return ret;
  1066. }
  1067. #if !defined(NO_THREAD_NAME)
  1068. #if defined(_WIN32) && defined(_MSC_VER)
  1069. /* Set the thread name for debugging purposes in Visual Studio
  1070. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  1071. */
  1072. #pragma pack(push, 8)
  1073. typedef struct tagTHREADNAME_INFO {
  1074. DWORD dwType; /* Must be 0x1000. */
  1075. LPCSTR szName; /* Pointer to name (in user addr space). */
  1076. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  1077. DWORD dwFlags; /* Reserved for future use, must be zero. */
  1078. } THREADNAME_INFO;
  1079. #pragma pack(pop)
  1080. #elif defined(__linux__)
  1081. #include <sys/prctl.h>
  1082. #include <sys/sendfile.h>
  1083. #endif
  1084. static void mg_set_thread_name(const char *name)
  1085. {
  1086. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  1087. mg_snprintf(
  1088. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  1089. #if defined(_WIN32)
  1090. #if defined(_MSC_VER)
  1091. /* Windows and Visual Studio Compiler */
  1092. __try
  1093. {
  1094. THREADNAME_INFO info;
  1095. info.dwType = 0x1000;
  1096. info.szName = threadName;
  1097. info.dwThreadID = ~0U;
  1098. info.dwFlags = 0;
  1099. RaiseException(0x406D1388,
  1100. 0,
  1101. sizeof(info) / sizeof(ULONG_PTR),
  1102. (ULONG_PTR *)&info);
  1103. }
  1104. __except(EXCEPTION_EXECUTE_HANDLER)
  1105. {
  1106. }
  1107. #elif defined(__MINGW32__)
  1108. /* No option known to set thread name for MinGW */
  1109. #endif
  1110. #elif defined(__GLIBC__) && \
  1111. ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  1112. /* pthread_setname_np first appeared in glibc in version 2.12*/
  1113. (void)pthread_setname_np(pthread_self(), threadName);
  1114. #elif defined(__linux__)
  1115. /* on linux we can use the old prctl function */
  1116. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  1117. #endif
  1118. }
  1119. #else /* !defined(NO_THREAD_NAME) */
  1120. void mg_set_thread_name(const char *threadName)
  1121. {
  1122. }
  1123. #endif
  1124. #if defined(MG_LEGACY_INTERFACE)
  1125. const char **mg_get_valid_option_names(void)
  1126. {
  1127. /* This function is deprecated. Use mg_get_valid_options instead. */
  1128. static const char *
  1129. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  1130. int i;
  1131. for (i = 0; config_options[i].name != NULL; i++) {
  1132. data[i * 2] = config_options[i].name;
  1133. data[i * 2 + 1] = config_options[i].default_value;
  1134. }
  1135. return data;
  1136. }
  1137. #endif
  1138. const struct mg_option *mg_get_valid_options(void)
  1139. {
  1140. return config_options;
  1141. }
  1142. static int is_file_in_memory(struct mg_connection *conn,
  1143. const char *path,
  1144. struct file *filep)
  1145. {
  1146. size_t size = 0;
  1147. if (!conn || !filep) {
  1148. return 0;
  1149. }
  1150. filep->last_modified = (time_t)0;
  1151. if ((filep->membuf =
  1152. conn->ctx->callbacks.open_file == NULL
  1153. ? NULL
  1154. : conn->ctx->callbacks.open_file(conn, path, &size)) != NULL) {
  1155. /* NOTE: override filep->size only on success. Otherwise, it might
  1156. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  1157. filep->size = size;
  1158. }
  1159. return filep->membuf != NULL;
  1160. }
  1161. static int is_file_opened(const struct file *filep)
  1162. {
  1163. if (!filep) {
  1164. return 0;
  1165. }
  1166. return filep->membuf != NULL || filep->fp != NULL;
  1167. }
  1168. static int mg_fopen(struct mg_connection *conn,
  1169. const char *path,
  1170. const char *mode,
  1171. struct file *filep)
  1172. {
  1173. if (!filep) {
  1174. return 0;
  1175. }
  1176. if (!is_file_in_memory(conn, path, filep)) {
  1177. #ifdef _WIN32
  1178. wchar_t wbuf[PATH_MAX], wmode[20];
  1179. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  1180. MultiByteToWideChar(CP_UTF8, 0, mode, -1, wmode, ARRAY_SIZE(wmode));
  1181. filep->fp = _wfopen(wbuf, wmode);
  1182. #else
  1183. filep->fp = fopen(path, mode);
  1184. #endif
  1185. }
  1186. return is_file_opened(filep);
  1187. }
  1188. static void mg_fclose(struct file *filep)
  1189. {
  1190. if (filep != NULL && filep->fp != NULL) {
  1191. fclose(filep->fp);
  1192. }
  1193. }
  1194. static void mg_strlcpy(register char *dst, register const char *src, size_t n)
  1195. {
  1196. for (; *src != '\0' && n > 1; n--) {
  1197. *dst++ = *src++;
  1198. }
  1199. *dst = '\0';
  1200. }
  1201. static int lowercase(const char *s)
  1202. {
  1203. return tolower(*(const unsigned char *)s);
  1204. }
  1205. int mg_strncasecmp(const char *s1, const char *s2, size_t len)
  1206. {
  1207. int diff = 0;
  1208. if (len > 0) {
  1209. do {
  1210. diff = lowercase(s1++) - lowercase(s2++);
  1211. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  1212. }
  1213. return diff;
  1214. }
  1215. static int mg_strcasecmp(const char *s1, const char *s2)
  1216. {
  1217. int diff;
  1218. do {
  1219. diff = lowercase(s1++) - lowercase(s2++);
  1220. } while (diff == 0 && s1[-1] != '\0');
  1221. return diff;
  1222. }
  1223. static char *mg_strndup(const char *ptr, size_t len)
  1224. {
  1225. char *p;
  1226. if ((p = (char *)mg_malloc(len + 1)) != NULL) {
  1227. mg_strlcpy(p, ptr, len + 1);
  1228. }
  1229. return p;
  1230. }
  1231. static char *mg_strdup(const char *str)
  1232. {
  1233. return mg_strndup(str, strlen(str));
  1234. }
  1235. static const char *mg_strcasestr(const char *big_str, const char *small_str)
  1236. {
  1237. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  1238. if (big_len >= small_len) {
  1239. for (i = 0; i <= (big_len - small_len); i++) {
  1240. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  1241. return big_str + i;
  1242. }
  1243. }
  1244. }
  1245. return NULL;
  1246. }
  1247. /* Return null terminated string of given maximum length.
  1248. * Report errors if length is exceeded. */
  1249. static void mg_vsnprintf(const struct mg_connection *conn,
  1250. int *truncated,
  1251. char *buf,
  1252. size_t buflen,
  1253. const char *fmt,
  1254. va_list ap)
  1255. {
  1256. int n, ok;
  1257. if (buflen == 0) {
  1258. return;
  1259. }
  1260. #ifdef __clang__
  1261. #pragma clang diagnostic push
  1262. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  1263. /* Using fmt as a non-literal is intended here, since it is mostly called
  1264. * indirectly by mg_snprintf */
  1265. #endif
  1266. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  1267. ok = (n >= 0) && ((size_t)n < buflen);
  1268. #ifdef __clang__
  1269. #pragma clang diagnostic pop
  1270. #endif
  1271. if (ok) {
  1272. if (truncated) {
  1273. *truncated = 0;
  1274. }
  1275. } else {
  1276. if (truncated) {
  1277. *truncated = 1;
  1278. }
  1279. mg_cry(conn,
  1280. "truncating vsnprintf buffer: [%.*s]",
  1281. (int)((buflen > 200) ? 200 : (buflen - 1)),
  1282. buf);
  1283. n = (int)buflen - 1;
  1284. }
  1285. buf[n] = '\0';
  1286. }
  1287. static void mg_snprintf(const struct mg_connection *conn,
  1288. int *truncated,
  1289. char *buf,
  1290. size_t buflen,
  1291. const char *fmt,
  1292. ...)
  1293. {
  1294. va_list ap;
  1295. va_start(ap, fmt);
  1296. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  1297. va_end(ap);
  1298. }
  1299. static int get_option_index(const char *name)
  1300. {
  1301. int i;
  1302. for (i = 0; config_options[i].name != NULL; i++) {
  1303. if (strcmp(config_options[i].name, name) == 0) {
  1304. return i;
  1305. }
  1306. }
  1307. return -1;
  1308. }
  1309. const char *mg_get_option(const struct mg_context *ctx, const char *name)
  1310. {
  1311. int i;
  1312. if ((i = get_option_index(name)) == -1) {
  1313. return NULL;
  1314. } else if (!ctx || ctx->config[i] == NULL) {
  1315. return "";
  1316. } else {
  1317. return ctx->config[i];
  1318. }
  1319. }
  1320. struct mg_context *mg_get_context(const struct mg_connection *conn)
  1321. {
  1322. return (conn == NULL) ? (struct mg_context *)NULL : (conn->ctx);
  1323. }
  1324. void *mg_get_user_data(const struct mg_context *ctx)
  1325. {
  1326. return (ctx == NULL) ? NULL : ctx->user_data;
  1327. }
  1328. void mg_set_user_connection_data(const struct mg_connection *conn, void *data)
  1329. {
  1330. if (conn != NULL) {
  1331. ((struct mg_connection *)conn)->request_info.conn_data = data;
  1332. }
  1333. }
  1334. void *mg_get_user_connection_data(const struct mg_connection *conn)
  1335. {
  1336. if (conn != NULL) {
  1337. return conn->request_info.conn_data;
  1338. }
  1339. return NULL;
  1340. }
  1341. size_t
  1342. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  1343. {
  1344. size_t i;
  1345. if (!ctx) {
  1346. return 0;
  1347. }
  1348. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  1349. ssl[i] = ctx->listening_sockets[i].is_ssl;
  1350. ports[i] = ctx->listening_ports[i];
  1351. }
  1352. return i;
  1353. }
  1354. static void sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  1355. {
  1356. buf[0] = '\0';
  1357. if (!usa) {
  1358. return;
  1359. }
  1360. if (usa->sa.sa_family == AF_INET) {
  1361. getnameinfo(&usa->sa,
  1362. sizeof(usa->sin),
  1363. buf,
  1364. (unsigned)len,
  1365. NULL,
  1366. 0,
  1367. NI_NUMERICHOST);
  1368. }
  1369. #if defined(USE_IPV6)
  1370. else if (usa->sa.sa_family == AF_INET6) {
  1371. getnameinfo(&usa->sa,
  1372. sizeof(usa->sin6),
  1373. buf,
  1374. (unsigned)len,
  1375. NULL,
  1376. 0,
  1377. NI_NUMERICHOST);
  1378. }
  1379. #endif
  1380. }
  1381. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  1382. * included in all responses other than 100, 101, 5xx. */
  1383. static void gmt_time_string(char *buf, size_t buf_len, time_t *t)
  1384. {
  1385. struct tm *tm;
  1386. tm = gmtime(t);
  1387. if (tm != NULL) {
  1388. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  1389. } else {
  1390. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  1391. buf[buf_len - 1] = '\0';
  1392. }
  1393. }
  1394. /* difftime for struct timespec. Return value is in seconds. */
  1395. static double mg_difftimespec(const struct timespec *ts_now,
  1396. const struct timespec *ts_before)
  1397. {
  1398. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9 +
  1399. (double)(ts_now->tv_sec - ts_before->tv_sec);
  1400. }
  1401. /* Print error message to the opened error log stream. */
  1402. void mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  1403. {
  1404. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  1405. va_list ap;
  1406. FILE *fp;
  1407. time_t timestamp;
  1408. va_start(ap, fmt);
  1409. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  1410. va_end(ap);
  1411. buf[sizeof(buf) - 1] = 0;
  1412. /* Do not lock when getting the callback value, here and below.
  1413. * I suppose this is fine, since function cannot disappear in the
  1414. * same way string option can. */
  1415. if (conn && (conn->ctx->callbacks.log_message == NULL ||
  1416. conn->ctx->callbacks.log_message(conn, buf) == 0)) {
  1417. fp = conn->ctx->config[ERROR_LOG_FILE] == NULL
  1418. ? NULL
  1419. : fopen(conn->ctx->config[ERROR_LOG_FILE], "a+");
  1420. if (fp != NULL) {
  1421. flockfile(fp);
  1422. timestamp = time(NULL);
  1423. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  1424. fprintf(fp,
  1425. "[%010lu] [error] [client %s] ",
  1426. (unsigned long)timestamp,
  1427. src_addr);
  1428. if (conn->request_info.request_method != NULL) {
  1429. fprintf(fp,
  1430. "%s %s: ",
  1431. conn->request_info.request_method,
  1432. conn->request_info.request_uri);
  1433. }
  1434. fprintf(fp, "%s", buf);
  1435. fputc('\n', fp);
  1436. funlockfile(fp);
  1437. fclose(fp);
  1438. }
  1439. }
  1440. }
  1441. /* Return fake connection structure. Used for logging, if connection
  1442. * is not applicable at the moment of logging. */
  1443. static struct mg_connection *fc(struct mg_context *ctx)
  1444. {
  1445. static struct mg_connection fake_connection;
  1446. fake_connection.ctx = ctx;
  1447. return &fake_connection;
  1448. }
  1449. const char *mg_version(void)
  1450. {
  1451. return CIVETWEB_VERSION;
  1452. }
  1453. const struct mg_request_info *
  1454. mg_get_request_info(const struct mg_connection *conn)
  1455. {
  1456. if (!conn) {
  1457. return NULL;
  1458. }
  1459. return &conn->request_info;
  1460. }
  1461. /* Skip the characters until one of the delimiters characters found.
  1462. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  1463. * Advance pointer to buffer to the next word. Return found 0-terminated word.
  1464. * Delimiters can be quoted with quotechar. */
  1465. static char *skip_quoted(char **buf,
  1466. const char *delimiters,
  1467. const char *whitespace,
  1468. char quotechar)
  1469. {
  1470. char *p, *begin_word, *end_word, *end_whitespace;
  1471. begin_word = *buf;
  1472. end_word = begin_word + strcspn(begin_word, delimiters);
  1473. /* Check for quotechar */
  1474. if (end_word > begin_word) {
  1475. p = end_word - 1;
  1476. while (*p == quotechar) {
  1477. /* TODO (bel, low): it seems this code is never reached, so
  1478. * quotechar is actually not needed - check if this code may be
  1479. * droped */
  1480. /* If there is anything beyond end_word, copy it */
  1481. if (*end_word == '\0') {
  1482. *p = '\0';
  1483. break;
  1484. } else {
  1485. size_t end_off = strcspn(end_word + 1, delimiters);
  1486. memmove(p, end_word, end_off + 1);
  1487. p += end_off; /* p must correspond to end_word - 1 */
  1488. end_word += end_off + 1;
  1489. }
  1490. }
  1491. for (p++; p < end_word; p++) {
  1492. *p = '\0';
  1493. }
  1494. }
  1495. if (*end_word == '\0') {
  1496. *buf = end_word;
  1497. } else {
  1498. end_whitespace = end_word + 1 + strspn(end_word + 1, whitespace);
  1499. for (p = end_word; p < end_whitespace; p++) {
  1500. *p = '\0';
  1501. }
  1502. *buf = end_whitespace;
  1503. }
  1504. return begin_word;
  1505. }
  1506. /* Simplified version of skip_quoted without quote char
  1507. * and whitespace == delimiters */
  1508. static char *skip(char **buf, const char *delimiters)
  1509. {
  1510. return skip_quoted(buf, delimiters, delimiters, 0);
  1511. }
  1512. /* Return HTTP header value, or NULL if not found. */
  1513. static const char *get_header(const struct mg_request_info *ri,
  1514. const char *name)
  1515. {
  1516. int i;
  1517. if (ri) {
  1518. for (i = 0; i < ri->num_headers; i++) {
  1519. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  1520. return ri->http_headers[i].value;
  1521. }
  1522. }
  1523. }
  1524. return NULL;
  1525. }
  1526. const char *mg_get_header(const struct mg_connection *conn, const char *name)
  1527. {
  1528. if (!conn) {
  1529. return NULL;
  1530. }
  1531. return get_header(&conn->request_info, name);
  1532. }
  1533. /* A helper function for traversing a comma separated list of values.
  1534. * It returns a list pointer shifted to the next value, or NULL if the end
  1535. * of the list found.
  1536. * Value is stored in val vector. If value has form "x=y", then eq_val
  1537. * vector is initialized to point to the "y" part, and val vector length
  1538. * is adjusted to point only to "x". */
  1539. static const char *
  1540. next_option(const char *list, struct vec *val, struct vec *eq_val)
  1541. {
  1542. if (val == NULL || list == NULL || *list == '\0') {
  1543. /* End of the list */
  1544. list = NULL;
  1545. } else {
  1546. val->ptr = list;
  1547. if ((list = strchr(val->ptr, ',')) != NULL) {
  1548. /* Comma found. Store length and shift the list ptr */
  1549. val->len = ((size_t)(list - val->ptr));
  1550. list++;
  1551. } else {
  1552. /* This value is the last one */
  1553. list = val->ptr + strlen(val->ptr);
  1554. val->len = ((size_t)(list - val->ptr));
  1555. }
  1556. if (eq_val != NULL) {
  1557. /* Value has form "x=y", adjust pointers and lengths
  1558. * so that val points to "x", and eq_val points to "y". */
  1559. eq_val->len = 0;
  1560. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  1561. if (eq_val->ptr != NULL) {
  1562. eq_val->ptr++; /* Skip over '=' character */
  1563. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  1564. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  1565. }
  1566. }
  1567. }
  1568. return list;
  1569. }
  1570. /* Perform case-insensitive match of string against pattern */
  1571. static int
  1572. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  1573. {
  1574. const char *or_str;
  1575. size_t i;
  1576. int j, len, res;
  1577. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  1578. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  1579. return res > 0 ? res : match_prefix(or_str + 1,
  1580. (size_t)((pattern + pattern_len) -
  1581. (or_str + 1)),
  1582. str);
  1583. }
  1584. for (i = 0, j = 0; i < pattern_len; i++, j++) {
  1585. if (pattern[i] == '?' && str[j] != '\0') {
  1586. continue;
  1587. } else if (pattern[i] == '$') {
  1588. return str[j] == '\0' ? j : -1;
  1589. } else if (pattern[i] == '*') {
  1590. i++;
  1591. if (pattern[i] == '*') {
  1592. i++;
  1593. len = (int)strlen(str + j);
  1594. } else {
  1595. len = (int)strcspn(str + j, "/");
  1596. }
  1597. if (i == pattern_len) {
  1598. return j + len;
  1599. }
  1600. do {
  1601. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  1602. } while (res == -1 && len-- > 0);
  1603. return res == -1 ? -1 : j + res + len;
  1604. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  1605. return -1;
  1606. }
  1607. }
  1608. return j;
  1609. }
  1610. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  1611. * This function must tolerate situations when connection info is not
  1612. * set up, for example if request parsing failed. */
  1613. static int should_keep_alive(const struct mg_connection *conn)
  1614. {
  1615. if (conn != NULL) {
  1616. const char *http_version = conn->request_info.http_version;
  1617. const char *header = mg_get_header(conn, "Connection");
  1618. if (conn->must_close || conn->internal_error ||
  1619. conn->status_code == 401 ||
  1620. mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0 ||
  1621. (header != NULL && mg_strcasecmp(header, "keep-alive") != 0) ||
  1622. (header == NULL && http_version &&
  1623. 0 != strcmp(http_version, "1.1"))) {
  1624. return 0;
  1625. }
  1626. return 1;
  1627. }
  1628. return 0;
  1629. }
  1630. static int should_decode_url(const struct mg_connection *conn)
  1631. {
  1632. if (!conn || !conn->ctx) {
  1633. return 0;
  1634. }
  1635. return (mg_strcasecmp(conn->ctx->config[DECODE_URL], "yes") == 0);
  1636. }
  1637. static const char *suggest_connection_header(const struct mg_connection *conn)
  1638. {
  1639. return should_keep_alive(conn) ? "keep-alive" : "close";
  1640. }
  1641. static void handle_file_based_request(struct mg_connection *conn,
  1642. const char *path,
  1643. struct file *filep);
  1644. static int
  1645. mg_stat(struct mg_connection *conn, const char *path, struct file *filep);
  1646. static const char *mg_get_response_code_text(int response_code,
  1647. struct mg_connection *conn)
  1648. {
  1649. switch (response_code) {
  1650. /* RFC2616 Section 10.1 - Informational 1xx */
  1651. case 100:
  1652. return "Continue"; /* RFC2616 Section 10.1.1 */
  1653. case 101:
  1654. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  1655. case 102:
  1656. return "Processing"; /* RFC2518 Section 10.1 */
  1657. /* RFC2616 Section 10.2 - Successful 2xx */
  1658. case 200:
  1659. return "OK"; /* RFC2616 Section 10.2.1 */
  1660. case 201:
  1661. return "Created"; /* RFC2616 Section 10.2.2 */
  1662. case 202:
  1663. return "Accepted"; /* RFC2616 Section 10.2.3 */
  1664. case 203:
  1665. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  1666. case 204:
  1667. return "No Content"; /* RFC2616 Section 10.2.5 */
  1668. case 205:
  1669. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  1670. case 206:
  1671. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  1672. case 207:
  1673. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1 */
  1674. /* RFC2616 Section 10.3 - Redirection 3xx */
  1675. case 300:
  1676. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  1677. case 301:
  1678. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  1679. case 302:
  1680. return "Found"; /* RFC2616 Section 10.3.3 */
  1681. case 303:
  1682. return "See Other"; /* RFC2616 Section 10.3.4 */
  1683. case 304:
  1684. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  1685. case 305:
  1686. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  1687. case 307:
  1688. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  1689. /* RFC2616 Section 10.4 - Client Error 4xx */
  1690. case 400:
  1691. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  1692. case 401:
  1693. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  1694. case 402:
  1695. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  1696. case 403:
  1697. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  1698. case 404:
  1699. return "Not Found"; /* RFC2616 Section 10.4.5 */
  1700. case 405:
  1701. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  1702. case 406:
  1703. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  1704. case 407:
  1705. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  1706. case 408:
  1707. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  1708. case 409:
  1709. return "Conflict"; /* RFC2616 Section 10.4.10 */
  1710. case 410:
  1711. return "Gone"; /* RFC2616 Section 10.4.11 */
  1712. case 411:
  1713. return "Length Required"; /* RFC2616 Section 10.4.12 */
  1714. case 412:
  1715. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  1716. case 413:
  1717. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  1718. case 414:
  1719. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  1720. case 415:
  1721. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  1722. case 416:
  1723. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17 */
  1724. case 417:
  1725. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  1726. case 422:
  1727. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  1728. * Section 11.2 */
  1729. case 423:
  1730. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  1731. case 424:
  1732. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  1733. * Section 11.4 */
  1734. case 428:
  1735. return "Precondition Required"; /* RFC 6585, Section 3 */
  1736. case 429:
  1737. return "Too Many Requests"; /* RFC 6585, Section 4 */
  1738. case 431:
  1739. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  1740. /* RFC2616 Section 10.5 - Server Error 5xx */
  1741. case 500:
  1742. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  1743. case 501:
  1744. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  1745. case 502:
  1746. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  1747. case 503:
  1748. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  1749. case 504:
  1750. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  1751. case 505:
  1752. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  1753. case 507:
  1754. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  1755. * Section 11.5 */
  1756. case 511:
  1757. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  1758. /* Other RFCs */
  1759. case 426:
  1760. return "Upgrade Required"; /* RFC 2817 */
  1761. /* Return codes from non normative RFCs: */
  1762. /* Informative and experimental RFCs, "de facto" standards due to common
  1763. * use, ... */
  1764. case 208:
  1765. return "Already Reported"; /* RFC5842 Section 7.1 */
  1766. case 226:
  1767. return "IM used"; /* RFC3229 Section 10.4.1 */
  1768. case 308:
  1769. return "Permanent Redirect"; /* RFC7238 Section 3 */
  1770. case 418:
  1771. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  1772. case 419:
  1773. return "Authentication Timeout"; /* common use */
  1774. case 451:
  1775. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  1776. * Section 3 */
  1777. case 506:
  1778. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  1779. case 508:
  1780. return "Loop Detected"; /* RFC5842 Section 7.1 */
  1781. case 510:
  1782. return "Not Extended"; /* RFC 2774, Section 7 */
  1783. default:
  1784. /* This error code is unknown. This should not happen. */
  1785. if (conn) {
  1786. mg_cry(conn, "Unknown HTTP response code: %u", response_code);
  1787. }
  1788. /* Return at least a category according to RFC 2616 Section 10. */
  1789. if (response_code >= 100 && response_code < 200) {
  1790. /* Unknown informational status code */
  1791. return "Information";
  1792. }
  1793. if (response_code >= 200 && response_code < 300) {
  1794. /* Unknown success code */
  1795. return "Success";
  1796. }
  1797. if (response_code >= 300 && response_code < 400) {
  1798. /* Unknown redirection code */
  1799. return "Redirection";
  1800. }
  1801. if (response_code >= 400 && response_code < 500) {
  1802. /* Unknown request error code */
  1803. return "Client Error";
  1804. }
  1805. if (response_code >= 500 && response_code < 600) {
  1806. /* Unknown server error code */
  1807. return "Server Error";
  1808. }
  1809. /* Response code not even within reasonable range */
  1810. return "";
  1811. }
  1812. }
  1813. static void send_http_error(struct mg_connection *,
  1814. int,
  1815. PRINTF_FORMAT_STRING(const char *fmt),
  1816. ...) PRINTF_ARGS(3, 4);
  1817. static void
  1818. send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  1819. {
  1820. char buf[MG_BUF_LEN];
  1821. va_list ap;
  1822. int len, i, page_handler_found, scope, truncated;
  1823. char date[64];
  1824. time_t curtime = time(NULL);
  1825. const char *error_handler = NULL;
  1826. struct file error_page_file = STRUCT_FILE_INITIALIZER;
  1827. const char *error_page_file_ext, *tstr;
  1828. const char *status_text = mg_get_response_code_text(status, conn);
  1829. if (conn == NULL) {
  1830. return;
  1831. }
  1832. conn->status_code = status;
  1833. if (conn->in_error_handler || conn->ctx->callbacks.http_error == NULL ||
  1834. conn->ctx->callbacks.http_error(conn, status)) {
  1835. if (!conn->in_error_handler) {
  1836. /* Send user defined error pages, if defined */
  1837. error_handler = conn->ctx->config[ERROR_PAGES];
  1838. error_page_file_ext = conn->ctx->config[INDEX_FILES];
  1839. page_handler_found = 0;
  1840. if (error_handler != NULL) {
  1841. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  1842. switch (scope) {
  1843. case 1: /* Handler for specific error, e.g. 404 error */
  1844. mg_snprintf(conn,
  1845. &truncated,
  1846. buf,
  1847. sizeof(buf) - 32,
  1848. "%serror%03u.",
  1849. error_handler,
  1850. status);
  1851. break;
  1852. case 2: /* Handler for error group, e.g., 5xx error handler
  1853. * for all server errors (500-599) */
  1854. mg_snprintf(conn,
  1855. &truncated,
  1856. buf,
  1857. sizeof(buf) - 32,
  1858. "%serror%01uxx.",
  1859. error_handler,
  1860. status / 100);
  1861. break;
  1862. default: /* Handler for all errors */
  1863. mg_snprintf(conn,
  1864. &truncated,
  1865. buf,
  1866. sizeof(buf) - 32,
  1867. "%serror.",
  1868. error_handler);
  1869. break;
  1870. }
  1871. /* String truncation in buf may only occur if error_handler
  1872. * is too long. This string is from the config, not from a
  1873. * client. */
  1874. (void)truncated;
  1875. len = (int)strlen(buf);
  1876. tstr = strchr(error_page_file_ext, '.');
  1877. while (tstr) {
  1878. for (i = 1; i < 32 && tstr[i] != 0 && tstr[i] != ',';
  1879. i++)
  1880. buf[len + i - 1] = tstr[i];
  1881. buf[len + i - 1] = 0;
  1882. if (mg_stat(conn, buf, &error_page_file)) {
  1883. page_handler_found = 1;
  1884. break;
  1885. }
  1886. tstr = strchr(tstr + i, '.');
  1887. }
  1888. }
  1889. }
  1890. if (page_handler_found) {
  1891. conn->in_error_handler = 1;
  1892. handle_file_based_request(conn, buf, &error_page_file);
  1893. conn->in_error_handler = 0;
  1894. return;
  1895. }
  1896. }
  1897. /* No custom error page. Send default error page. */
  1898. gmt_time_string(date, sizeof(date), &curtime);
  1899. conn->must_close = 1;
  1900. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  1901. mg_printf(conn,
  1902. "Date: %s\r\n"
  1903. "Connection: close\r\n\r\n",
  1904. date);
  1905. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  1906. if (status > 199 && status != 204 && status != 304) {
  1907. mg_printf(conn, "Error %d: %s\n", status, status_text);
  1908. if (fmt != NULL) {
  1909. va_start(ap, fmt);
  1910. mg_vsnprintf(conn, NULL, buf, sizeof(buf), fmt, ap);
  1911. va_end(ap);
  1912. mg_write(conn, buf, strlen(buf));
  1913. DEBUG_TRACE("Error %i - [%s]", status, buf);
  1914. }
  1915. } else {
  1916. /* No body allowed. Close the connection. */
  1917. DEBUG_TRACE("Error %i", status);
  1918. }
  1919. }
  1920. }
  1921. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1922. /* Create substitutes for POSIX functions in Win32. */
  1923. #if defined(__MINGW32__)
  1924. /* Show no warning in case system functions are not used. */
  1925. #pragma GCC diagnostic push
  1926. #pragma GCC diagnostic ignored "-Wunused-function"
  1927. #endif
  1928. static int pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  1929. {
  1930. (void)unused;
  1931. *mutex = CreateMutex(NULL, FALSE, NULL);
  1932. return *mutex == NULL ? -1 : 0;
  1933. }
  1934. static int pthread_mutex_destroy(pthread_mutex_t *mutex)
  1935. {
  1936. return CloseHandle(*mutex) == 0 ? -1 : 0;
  1937. }
  1938. static int pthread_mutex_lock(pthread_mutex_t *mutex)
  1939. {
  1940. return WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0 ? 0 : -1;
  1941. }
  1942. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  1943. static int pthread_mutex_trylock(pthread_mutex_t *mutex)
  1944. {
  1945. switch (WaitForSingleObject(*mutex, 0)) {
  1946. case WAIT_OBJECT_0:
  1947. return 0;
  1948. case WAIT_TIMEOUT:
  1949. return -2; /* EBUSY */
  1950. }
  1951. return -1;
  1952. }
  1953. #endif
  1954. static int pthread_mutex_unlock(pthread_mutex_t *mutex)
  1955. {
  1956. return ReleaseMutex(*mutex) == 0 ? -1 : 0;
  1957. }
  1958. #ifndef WIN_PTHREADS_TIME_H
  1959. static int clock_gettime(clockid_t clk_id, struct timespec *tp)
  1960. {
  1961. FILETIME ft;
  1962. ULARGE_INTEGER li;
  1963. BOOL ok = FALSE;
  1964. double d;
  1965. static double perfcnt_per_sec = 0.0;
  1966. if (tp) {
  1967. if (clk_id == CLOCK_REALTIME) {
  1968. GetSystemTimeAsFileTime(&ft);
  1969. li.LowPart = ft.dwLowDateTime;
  1970. li.HighPart = ft.dwHighDateTime;
  1971. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  1972. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  1973. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  1974. ok = TRUE;
  1975. } else if (clk_id == CLOCK_MONOTONIC) {
  1976. if (perfcnt_per_sec == 0.0) {
  1977. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  1978. perfcnt_per_sec = 1.0 / li.QuadPart;
  1979. }
  1980. if (perfcnt_per_sec != 0.0) {
  1981. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  1982. d = li.QuadPart * perfcnt_per_sec;
  1983. tp->tv_sec = (time_t)d;
  1984. d -= tp->tv_sec;
  1985. tp->tv_nsec = (long)(d * 1.0E9);
  1986. ok = TRUE;
  1987. }
  1988. }
  1989. }
  1990. return ok ? 0 : -1;
  1991. }
  1992. #endif
  1993. static int pthread_cond_init(pthread_cond_t *cv, const void *unused)
  1994. {
  1995. (void)unused;
  1996. InitializeCriticalSection(&cv->threadIdSec);
  1997. cv->waitingthreadcount = 0;
  1998. cv->waitingthreadhdls =
  1999. (pthread_t *)mg_calloc(MAX_WORKER_THREADS, sizeof(pthread_t));
  2000. return (cv->waitingthreadhdls != NULL) ? 0 : -1;
  2001. }
  2002. static int pthread_cond_timedwait(pthread_cond_t *cv,
  2003. pthread_mutex_t *mutex,
  2004. const struct timespec *abstime)
  2005. {
  2006. struct mg_workerTLS *tls =
  2007. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2008. int ok;
  2009. struct timespec tsnow;
  2010. int64_t nsnow, nswaitabs, nswaitrel;
  2011. DWORD mswaitrel;
  2012. EnterCriticalSection(&cv->threadIdSec);
  2013. assert(cv->waitingthreadcount < MAX_WORKER_THREADS);
  2014. cv->waitingthreadhdls[cv->waitingthreadcount] =
  2015. tls->pthread_cond_helper_mutex;
  2016. cv->waitingthreadcount++;
  2017. LeaveCriticalSection(&cv->threadIdSec);
  2018. if (abstime) {
  2019. clock_gettime(CLOCK_REALTIME, &tsnow);
  2020. nsnow = (((int64_t)tsnow.tv_sec) * 1000000000) + tsnow.tv_nsec;
  2021. nswaitabs =
  2022. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  2023. nswaitrel = nswaitabs - nsnow;
  2024. if (nswaitrel < 0) {
  2025. nswaitrel = 0;
  2026. }
  2027. mswaitrel = (DWORD)(nswaitrel / 1000000);
  2028. } else {
  2029. mswaitrel = INFINITE;
  2030. }
  2031. pthread_mutex_unlock(mutex);
  2032. ok = (WAIT_OBJECT_0 ==
  2033. WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  2034. pthread_mutex_lock(mutex);
  2035. return ok ? 0 : -1;
  2036. }
  2037. static int pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  2038. {
  2039. return pthread_cond_timedwait(cv, mutex, NULL);
  2040. }
  2041. static int pthread_cond_signal(pthread_cond_t *cv)
  2042. {
  2043. int i;
  2044. HANDLE wkup = NULL;
  2045. BOOL ok = FALSE;
  2046. EnterCriticalSection(&cv->threadIdSec);
  2047. if (cv->waitingthreadcount) {
  2048. wkup = cv->waitingthreadhdls[0];
  2049. ok = SetEvent(wkup);
  2050. for (i = 1; i < cv->waitingthreadcount; i++) {
  2051. cv->waitingthreadhdls[i - 1] = cv->waitingthreadhdls[i];
  2052. }
  2053. cv->waitingthreadcount--;
  2054. assert(ok);
  2055. }
  2056. LeaveCriticalSection(&cv->threadIdSec);
  2057. return ok ? 0 : 1;
  2058. }
  2059. static int pthread_cond_broadcast(pthread_cond_t *cv)
  2060. {
  2061. EnterCriticalSection(&cv->threadIdSec);
  2062. while (cv->waitingthreadcount) {
  2063. pthread_cond_signal(cv);
  2064. }
  2065. LeaveCriticalSection(&cv->threadIdSec);
  2066. return 0;
  2067. }
  2068. static int pthread_cond_destroy(pthread_cond_t *cv)
  2069. {
  2070. EnterCriticalSection(&cv->threadIdSec);
  2071. assert(cv->waitingthreadcount == 0);
  2072. mg_free(cv->waitingthreadhdls);
  2073. cv->waitingthreadhdls = 0;
  2074. LeaveCriticalSection(&cv->threadIdSec);
  2075. DeleteCriticalSection(&cv->threadIdSec);
  2076. return 0;
  2077. }
  2078. #if defined(__MINGW32__)
  2079. /* Enable unused function warning again */
  2080. #pragma GCC diagnostic pop
  2081. #endif
  2082. /* For Windows, change all slashes to backslashes in path names. */
  2083. static void change_slashes_to_backslashes(char *path)
  2084. {
  2085. int i;
  2086. for (i = 0; path[i] != '\0'; i++) {
  2087. if (path[i] == '/') {
  2088. path[i] = '\\';
  2089. }
  2090. /* remove double backslash (check i > 0 to preserve UNC paths,
  2091. * like \\server\file.txt) */
  2092. if ((path[i] == '\\') && (i > 0)) {
  2093. while (path[i + 1] == '\\' || path[i + 1] == '/') {
  2094. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  2095. }
  2096. }
  2097. }
  2098. }
  2099. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  2100. * wbuf and wbuf_len is a target buffer and its length. */
  2101. static void to_unicode(const char *path, wchar_t *wbuf, size_t wbuf_len)
  2102. {
  2103. char buf[PATH_MAX], buf2[PATH_MAX];
  2104. mg_strlcpy(buf, path, sizeof(buf));
  2105. change_slashes_to_backslashes(buf);
  2106. /* Convert to Unicode and back. If doubly-converted string does not
  2107. * match the original, something is fishy, reject. */
  2108. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  2109. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  2110. WideCharToMultiByte(
  2111. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  2112. if (strcmp(buf, buf2) != 0) {
  2113. wbuf[0] = L'\0';
  2114. }
  2115. }
  2116. #if defined(_WIN32_WCE)
  2117. /* Create substitutes for POSIX functions in Win32. */
  2118. #if defined(__MINGW32__)
  2119. /* Show no warning in case system functions are not used. */
  2120. #pragma GCC diagnostic push
  2121. #pragma GCC diagnostic ignored "-Wunused-function"
  2122. #endif
  2123. static time_t time(time_t *ptime)
  2124. {
  2125. time_t t;
  2126. SYSTEMTIME st;
  2127. FILETIME ft;
  2128. GetSystemTime(&st);
  2129. SystemTimeToFileTime(&st, &ft);
  2130. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  2131. if (ptime != NULL) {
  2132. *ptime = t;
  2133. }
  2134. return t;
  2135. }
  2136. static struct tm *localtime(const time_t *ptime, struct tm *ptm)
  2137. {
  2138. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  2139. FILETIME ft, lft;
  2140. SYSTEMTIME st;
  2141. TIME_ZONE_INFORMATION tzinfo;
  2142. if (ptm == NULL) {
  2143. return NULL;
  2144. }
  2145. *(int64_t *)&ft = t;
  2146. FileTimeToLocalFileTime(&ft, &lft);
  2147. FileTimeToSystemTime(&lft, &st);
  2148. ptm->tm_year = st.wYear - 1900;
  2149. ptm->tm_mon = st.wMonth - 1;
  2150. ptm->tm_wday = st.wDayOfWeek;
  2151. ptm->tm_mday = st.wDay;
  2152. ptm->tm_hour = st.wHour;
  2153. ptm->tm_min = st.wMinute;
  2154. ptm->tm_sec = st.wSecond;
  2155. ptm->tm_yday = 0; /* hope nobody uses this */
  2156. ptm->tm_isdst =
  2157. GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT ? 1 : 0;
  2158. return ptm;
  2159. }
  2160. static struct tm *gmtime(const time_t *ptime, struct tm *ptm)
  2161. {
  2162. /* FIXME(lsm): fix this. */
  2163. return localtime(ptime, ptm);
  2164. }
  2165. static size_t
  2166. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  2167. {
  2168. (void)mg_snprintf(NULL, dst, dst_size, "implement strftime() for WinCE");
  2169. return 0;
  2170. }
  2171. #if defined(__MINGW32__)
  2172. /* Enable unused function warning again */
  2173. #pragma GCC diagnostic pop
  2174. #endif
  2175. #endif
  2176. /* Windows happily opens files with some garbage at the end of file name.
  2177. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  2178. * "a.cgi", despite one would expect an error back.
  2179. * This function returns non-0 if path ends with some garbage. */
  2180. static int path_cannot_disclose_cgi(const char *path)
  2181. {
  2182. static const char *allowed_last_characters = "_-";
  2183. int last = path[strlen(path) - 1];
  2184. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  2185. }
  2186. static int
  2187. mg_stat(struct mg_connection *conn, const char *path, struct file *filep)
  2188. {
  2189. wchar_t wbuf[PATH_MAX];
  2190. WIN32_FILE_ATTRIBUTE_DATA info;
  2191. time_t creation_time;
  2192. if (!filep) {
  2193. return 0;
  2194. }
  2195. memset(filep, 0, sizeof(*filep));
  2196. if (conn && is_file_in_memory(conn, path, filep)) {
  2197. return 1;
  2198. }
  2199. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  2200. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  2201. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  2202. filep->last_modified =
  2203. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  2204. info.ftLastWriteTime.dwHighDateTime);
  2205. /* On Windows, the file creation time can be higher than the
  2206. * modification time, e.g. when a file is copied.
  2207. * Since the Last-Modified timestamp is used for caching
  2208. * it should be based on the most recent timestamp. */
  2209. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  2210. info.ftCreationTime.dwHighDateTime);
  2211. if (creation_time > filep->last_modified) {
  2212. filep->last_modified = creation_time;
  2213. }
  2214. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  2215. /* If file name is fishy, reset the file structure and return
  2216. * error.
  2217. * Note it is important to reset, not just return the error, cause
  2218. * functions like is_file_opened() check the struct. */
  2219. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  2220. memset(filep, 0, sizeof(*filep));
  2221. return 0;
  2222. }
  2223. return 1;
  2224. }
  2225. return 0;
  2226. }
  2227. #if !defined(NO_FILES)
  2228. static int mg_remove(const char *path)
  2229. {
  2230. wchar_t wbuf[PATH_MAX];
  2231. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  2232. return DeleteFileW(wbuf) ? 0 : -1;
  2233. }
  2234. static int mg_mkdir(const char *path, int mode)
  2235. {
  2236. char buf[PATH_MAX];
  2237. wchar_t wbuf[PATH_MAX];
  2238. (void)mode;
  2239. mg_strlcpy(buf, path, sizeof(buf));
  2240. change_slashes_to_backslashes(buf);
  2241. (void)MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, ARRAY_SIZE(wbuf));
  2242. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  2243. }
  2244. #endif
  2245. /* Create substitutes for POSIX functions in Win32. */
  2246. #if defined(__MINGW32__)
  2247. /* Show no warning in case system functions are not used. */
  2248. #pragma GCC diagnostic push
  2249. #pragma GCC diagnostic ignored "-Wunused-function"
  2250. #endif
  2251. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  2252. static DIR *opendir(const char *name)
  2253. {
  2254. DIR *dir = NULL;
  2255. wchar_t wpath[PATH_MAX];
  2256. DWORD attrs;
  2257. if (name == NULL) {
  2258. SetLastError(ERROR_BAD_ARGUMENTS);
  2259. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  2260. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  2261. } else {
  2262. to_unicode(name, wpath, ARRAY_SIZE(wpath));
  2263. attrs = GetFileAttributesW(wpath);
  2264. if (attrs != 0xFFFFFFFF &&
  2265. ((attrs & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)) {
  2266. (void)wcscat(wpath, L"\\*");
  2267. dir->handle = FindFirstFileW(wpath, &dir->info);
  2268. dir->result.d_name[0] = '\0';
  2269. } else {
  2270. mg_free(dir);
  2271. dir = NULL;
  2272. }
  2273. }
  2274. return dir;
  2275. }
  2276. static int closedir(DIR *dir)
  2277. {
  2278. int result = 0;
  2279. if (dir != NULL) {
  2280. if (dir->handle != INVALID_HANDLE_VALUE)
  2281. result = FindClose(dir->handle) ? 0 : -1;
  2282. mg_free(dir);
  2283. } else {
  2284. result = -1;
  2285. SetLastError(ERROR_BAD_ARGUMENTS);
  2286. }
  2287. return result;
  2288. }
  2289. static struct dirent *readdir(DIR *dir)
  2290. {
  2291. struct dirent *result = 0;
  2292. if (dir) {
  2293. if (dir->handle != INVALID_HANDLE_VALUE) {
  2294. result = &dir->result;
  2295. (void)WideCharToMultiByte(CP_UTF8,
  2296. 0,
  2297. dir->info.cFileName,
  2298. -1,
  2299. result->d_name,
  2300. sizeof(result->d_name),
  2301. NULL,
  2302. NULL);
  2303. if (!FindNextFileW(dir->handle, &dir->info)) {
  2304. (void)FindClose(dir->handle);
  2305. dir->handle = INVALID_HANDLE_VALUE;
  2306. }
  2307. } else {
  2308. SetLastError(ERROR_FILE_NOT_FOUND);
  2309. }
  2310. } else {
  2311. SetLastError(ERROR_BAD_ARGUMENTS);
  2312. }
  2313. return result;
  2314. }
  2315. #ifndef HAVE_POLL
  2316. static int poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  2317. {
  2318. struct timeval tv;
  2319. fd_set set;
  2320. unsigned int i;
  2321. int result;
  2322. SOCKET maxfd = 0;
  2323. tv.tv_sec = milliseconds / 1000;
  2324. tv.tv_usec = (milliseconds % 1000) * 1000;
  2325. FD_ZERO(&set);
  2326. for (i = 0; i < n; i++) {
  2327. FD_SET((SOCKET)pfd[i].fd, &set);
  2328. pfd[i].revents = 0;
  2329. if (pfd[i].fd > maxfd) {
  2330. maxfd = pfd[i].fd;
  2331. }
  2332. }
  2333. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  2334. for (i = 0; i < n; i++) {
  2335. if (FD_ISSET(pfd[i].fd, &set)) {
  2336. pfd[i].revents = POLLIN;
  2337. }
  2338. }
  2339. }
  2340. return result;
  2341. }
  2342. #endif /* HAVE_POLL */
  2343. #if defined(__MINGW32__)
  2344. /* Enable unused function warning again */
  2345. #pragma GCC diagnostic pop
  2346. #endif
  2347. static void set_close_on_exec(SOCKET sock,
  2348. struct mg_connection *conn /* may be null */)
  2349. {
  2350. (void)conn; /* Unused. */
  2351. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  2352. }
  2353. int mg_start_thread(mg_thread_func_t f, void *p)
  2354. {
  2355. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  2356. /* Compile-time option to control stack size, e.g. -DUSE_STACK_SIZE=16384
  2357. */
  2358. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p) ==
  2359. ((uintptr_t)(-1L)))
  2360. ? -1
  2361. : 0);
  2362. #else
  2363. return (
  2364. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  2365. ? -1
  2366. : 0);
  2367. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  2368. }
  2369. /* Start a thread storing the thread context. */
  2370. static int mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  2371. void *p,
  2372. pthread_t *threadidptr)
  2373. {
  2374. uintptr_t uip;
  2375. HANDLE threadhandle;
  2376. int result = -1;
  2377. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  2378. threadhandle = (HANDLE)uip;
  2379. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  2380. *threadidptr = threadhandle;
  2381. result = 0;
  2382. }
  2383. return result;
  2384. }
  2385. /* Wait for a thread to finish. */
  2386. static int mg_join_thread(pthread_t threadid)
  2387. {
  2388. int result;
  2389. DWORD dwevent;
  2390. result = -1;
  2391. dwevent = WaitForSingleObject(threadid, INFINITE);
  2392. if (dwevent == WAIT_FAILED) {
  2393. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  2394. } else {
  2395. if (dwevent == WAIT_OBJECT_0) {
  2396. CloseHandle(threadid);
  2397. result = 0;
  2398. }
  2399. }
  2400. return result;
  2401. }
  2402. #if !defined(NO_SSL_DL)
  2403. /* Create substitutes for POSIX functions in Win32. */
  2404. #if defined(__MINGW32__)
  2405. /* Show no warning in case system functions are not used. */
  2406. #pragma GCC diagnostic push
  2407. #pragma GCC diagnostic ignored "-Wunused-function"
  2408. #endif
  2409. static HANDLE dlopen(const char *dll_name, int flags)
  2410. {
  2411. wchar_t wbuf[PATH_MAX];
  2412. (void)flags;
  2413. to_unicode(dll_name, wbuf, ARRAY_SIZE(wbuf));
  2414. return LoadLibraryW(wbuf);
  2415. }
  2416. static int dlclose(void *handle)
  2417. {
  2418. int result;
  2419. if (FreeLibrary((HMODULE)handle) != 0) {
  2420. result = 0;
  2421. } else {
  2422. result = -1;
  2423. }
  2424. return result;
  2425. }
  2426. #if defined(__MINGW32__)
  2427. /* Enable unused function warning again */
  2428. #pragma GCC diagnostic pop
  2429. #endif
  2430. #endif
  2431. #if !defined(NO_CGI)
  2432. #define SIGKILL (0)
  2433. static int kill(pid_t pid, int sig_num)
  2434. {
  2435. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  2436. (void)CloseHandle((HANDLE)pid);
  2437. return 0;
  2438. }
  2439. static void trim_trailing_whitespaces(char *s)
  2440. {
  2441. char *e = s + strlen(s) - 1;
  2442. while (e > s && isspace(*(unsigned char *)e)) {
  2443. *e-- = '\0';
  2444. }
  2445. }
  2446. static pid_t spawn_process(struct mg_connection *conn,
  2447. const char *prog,
  2448. char *envblk,
  2449. char *envp[],
  2450. int fdin,
  2451. int fdout,
  2452. int fderr,
  2453. const char *dir)
  2454. {
  2455. HANDLE me;
  2456. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  2457. cmdline[PATH_MAX], buf[PATH_MAX];
  2458. int truncated;
  2459. struct file file = STRUCT_FILE_INITIALIZER;
  2460. STARTUPINFOA si;
  2461. PROCESS_INFORMATION pi = {0};
  2462. (void)envp;
  2463. memset(&si, 0, sizeof(si));
  2464. si.cb = sizeof(si);
  2465. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  2466. si.wShowWindow = SW_HIDE;
  2467. me = GetCurrentProcess();
  2468. DuplicateHandle(me,
  2469. (HANDLE)_get_osfhandle(fdin),
  2470. me,
  2471. &si.hStdInput,
  2472. 0,
  2473. TRUE,
  2474. DUPLICATE_SAME_ACCESS);
  2475. DuplicateHandle(me,
  2476. (HANDLE)_get_osfhandle(fdout),
  2477. me,
  2478. &si.hStdOutput,
  2479. 0,
  2480. TRUE,
  2481. DUPLICATE_SAME_ACCESS);
  2482. DuplicateHandle(me,
  2483. (HANDLE)_get_osfhandle(fderr),
  2484. me,
  2485. &si.hStdError,
  2486. 0,
  2487. TRUE,
  2488. DUPLICATE_SAME_ACCESS);
  2489. /* If CGI file is a script, try to read the interpreter line */
  2490. interp = conn->ctx->config[CGI_INTERPRETER];
  2491. if (interp == NULL) {
  2492. buf[0] = buf[1] = '\0';
  2493. /* Read the first line of the script into the buffer */
  2494. mg_snprintf(
  2495. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  2496. if (truncated) {
  2497. pi.hProcess = (pid_t)-1;
  2498. goto spawn_cleanup;
  2499. }
  2500. if (mg_fopen(conn, cmdline, "r", &file)) {
  2501. p = (char *)file.membuf;
  2502. mg_fgets(buf, sizeof(buf), &file, &p);
  2503. mg_fclose(&file);
  2504. buf[sizeof(buf) - 1] = '\0';
  2505. }
  2506. if (buf[0] == '#' && buf[1] == '!') {
  2507. trim_trailing_whitespaces(buf + 2);
  2508. } else {
  2509. buf[2] = '\0';
  2510. }
  2511. interp = buf + 2;
  2512. }
  2513. if (interp[0] != '\0') {
  2514. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  2515. interp = full_interp;
  2516. }
  2517. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  2518. if (interp[0] != '\0') {
  2519. mg_snprintf(conn,
  2520. &truncated,
  2521. cmdline,
  2522. sizeof(cmdline),
  2523. "\"%s\" \"%s\\%s\"",
  2524. interp,
  2525. full_dir,
  2526. prog);
  2527. } else {
  2528. mg_snprintf(conn,
  2529. &truncated,
  2530. cmdline,
  2531. sizeof(cmdline),
  2532. "\"%s\\%s\"",
  2533. full_dir,
  2534. prog);
  2535. }
  2536. if (truncated) {
  2537. pi.hProcess = (pid_t)-1;
  2538. goto spawn_cleanup;
  2539. }
  2540. DEBUG_TRACE("Running [%s]", cmdline);
  2541. if (CreateProcessA(NULL,
  2542. cmdline,
  2543. NULL,
  2544. NULL,
  2545. TRUE,
  2546. CREATE_NEW_PROCESS_GROUP,
  2547. envblk,
  2548. NULL,
  2549. &si,
  2550. &pi) == 0) {
  2551. mg_cry(
  2552. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  2553. pi.hProcess = (pid_t)-1;
  2554. /* goto spawn_cleanup; */
  2555. }
  2556. spawn_cleanup:
  2557. (void)CloseHandle(si.hStdOutput);
  2558. (void)CloseHandle(si.hStdError);
  2559. (void)CloseHandle(si.hStdInput);
  2560. if (pi.hThread != NULL) {
  2561. (void)CloseHandle(pi.hThread);
  2562. }
  2563. return (pid_t)pi.hProcess;
  2564. }
  2565. #endif /* !NO_CGI */
  2566. static int set_non_blocking_mode(SOCKET sock)
  2567. {
  2568. unsigned long on = 1;
  2569. return ioctlsocket(sock, (long)FIONBIO, &on);
  2570. }
  2571. #else
  2572. static int
  2573. mg_stat(struct mg_connection *conn, const char *path, struct file *filep)
  2574. {
  2575. struct stat st;
  2576. if (!filep) {
  2577. return 0;
  2578. }
  2579. memset(filep, 0, sizeof(*filep));
  2580. if (conn && is_file_in_memory(conn, path, filep)) {
  2581. return 1;
  2582. }
  2583. if (0 == stat(path, &st)) {
  2584. filep->size = (uint64_t)(st.st_size);
  2585. filep->last_modified = st.st_mtime;
  2586. filep->is_directory = S_ISDIR(st.st_mode);
  2587. return 1;
  2588. }
  2589. return 0;
  2590. }
  2591. static void set_close_on_exec(SOCKET fd,
  2592. struct mg_connection *conn /* may be null */)
  2593. {
  2594. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  2595. if (conn) {
  2596. mg_cry(conn,
  2597. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  2598. __func__,
  2599. strerror(ERRNO));
  2600. }
  2601. }
  2602. }
  2603. int mg_start_thread(mg_thread_func_t func, void *param)
  2604. {
  2605. pthread_t thread_id;
  2606. pthread_attr_t attr;
  2607. int result;
  2608. (void)pthread_attr_init(&attr);
  2609. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  2610. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  2611. /* Compile-time option to control stack size,
  2612. * e.g. -DUSE_STACK_SIZE=16384 */
  2613. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  2614. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  2615. result = pthread_create(&thread_id, &attr, func, param);
  2616. pthread_attr_destroy(&attr);
  2617. return result;
  2618. }
  2619. /* Start a thread storing the thread context. */
  2620. static int mg_start_thread_with_id(mg_thread_func_t func,
  2621. void *param,
  2622. pthread_t *threadidptr)
  2623. {
  2624. pthread_t thread_id;
  2625. pthread_attr_t attr;
  2626. int result;
  2627. (void)pthread_attr_init(&attr);
  2628. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  2629. /* Compile-time option to control stack size,
  2630. * e.g. -DUSE_STACK_SIZE=16384 */
  2631. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  2632. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  2633. result = pthread_create(&thread_id, &attr, func, param);
  2634. pthread_attr_destroy(&attr);
  2635. if ((result == 0) && (threadidptr != NULL)) {
  2636. *threadidptr = thread_id;
  2637. }
  2638. return result;
  2639. }
  2640. /* Wait for a thread to finish. */
  2641. static int mg_join_thread(pthread_t threadid)
  2642. {
  2643. int result;
  2644. result = pthread_join(threadid, NULL);
  2645. return result;
  2646. }
  2647. #ifndef NO_CGI
  2648. static pid_t spawn_process(struct mg_connection *conn,
  2649. const char *prog,
  2650. char *envblk,
  2651. char *envp[],
  2652. int fdin,
  2653. int fdout,
  2654. int fderr,
  2655. const char *dir)
  2656. {
  2657. pid_t pid;
  2658. const char *interp;
  2659. (void)envblk;
  2660. if (conn == NULL) {
  2661. return 0;
  2662. }
  2663. if ((pid = fork()) == -1) {
  2664. /* Parent */
  2665. send_http_error(conn,
  2666. 500,
  2667. "Error: Creating CGI process\nfork(): %s",
  2668. strerror(ERRNO));
  2669. } else if (pid == 0) {
  2670. /* Child */
  2671. if (chdir(dir) != 0) {
  2672. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  2673. } else if (dup2(fdin, 0) == -1) {
  2674. mg_cry(
  2675. conn, "%s: dup2(%d, 0): %s", __func__, fdin, strerror(ERRNO));
  2676. } else if (dup2(fdout, 1) == -1) {
  2677. mg_cry(
  2678. conn, "%s: dup2(%d, 1): %s", __func__, fdout, strerror(ERRNO));
  2679. } else if (dup2(fderr, 2) == -1) {
  2680. mg_cry(
  2681. conn, "%s: dup2(%d, 2): %s", __func__, fderr, strerror(ERRNO));
  2682. } else {
  2683. /* Keep stderr and stdout in two different pipes.
  2684. * Stdout will be sent back to the client,
  2685. * stderr should go into a server error log. */
  2686. (void)close(fdin);
  2687. (void)close(fdout);
  2688. (void)close(fderr);
  2689. /* After exec, all signal handlers are restored to their default
  2690. * values, with one exception of SIGCHLD. According to
  2691. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler will
  2692. * leave unchanged after exec if it was set to be ignored. Restore
  2693. * it to default action. */
  2694. signal(SIGCHLD, SIG_DFL);
  2695. interp = conn->ctx->config[CGI_INTERPRETER];
  2696. if (interp == NULL) {
  2697. (void)execle(prog, prog, NULL, envp);
  2698. mg_cry(conn,
  2699. "%s: execle(%s): %s",
  2700. __func__,
  2701. prog,
  2702. strerror(ERRNO));
  2703. } else {
  2704. (void)execle(interp, interp, prog, NULL, envp);
  2705. mg_cry(conn,
  2706. "%s: execle(%s %s): %s",
  2707. __func__,
  2708. interp,
  2709. prog,
  2710. strerror(ERRNO));
  2711. }
  2712. }
  2713. exit(EXIT_FAILURE);
  2714. }
  2715. return pid;
  2716. }
  2717. #endif /* !NO_CGI */
  2718. static int set_non_blocking_mode(SOCKET sock)
  2719. {
  2720. int flags;
  2721. flags = fcntl(sock, F_GETFL, 0);
  2722. (void)fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  2723. return 0;
  2724. }
  2725. #endif /* _WIN32 */
  2726. /* Write data to the IO channel - opened file descriptor, socket or SSL
  2727. * descriptor. Return number of bytes written. */
  2728. static int push(struct mg_context *ctx,
  2729. FILE *fp,
  2730. SOCKET sock,
  2731. SSL *ssl,
  2732. const char *buf,
  2733. int len,
  2734. double timeout)
  2735. {
  2736. struct timespec start, now;
  2737. int n, err;
  2738. #ifdef _WIN32
  2739. typedef int len_t;
  2740. #else
  2741. typedef size_t len_t;
  2742. #endif
  2743. if (timeout > 0) {
  2744. memset(&start, 0, sizeof(start));
  2745. memset(&now, 0, sizeof(now));
  2746. clock_gettime(CLOCK_MONOTONIC, &start);
  2747. }
  2748. if (ctx == NULL) {
  2749. return -1;
  2750. }
  2751. #ifdef NO_SSL
  2752. if (ssl) {
  2753. return -1;
  2754. }
  2755. #endif
  2756. do {
  2757. #ifndef NO_SSL
  2758. if (ssl != NULL) {
  2759. n = SSL_write(ssl, buf, len);
  2760. if (n <= 0) {
  2761. err = SSL_get_error(ssl, n);
  2762. if ((err == 5 /* SSL_ERROR_SYSCALL */) && (n == -1)) {
  2763. err = ERRNO;
  2764. } else {
  2765. DEBUG_TRACE("SSL_write() failed, error %d", err);
  2766. return -1;
  2767. }
  2768. } else {
  2769. err = 0;
  2770. }
  2771. } else
  2772. #endif
  2773. if (fp != NULL) {
  2774. n = (int)fwrite(buf, 1, (size_t)len, fp);
  2775. if (ferror(fp)) {
  2776. n = -1;
  2777. err = ERRNO;
  2778. } else {
  2779. err = 0;
  2780. }
  2781. } else {
  2782. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  2783. err = (n < 0) ? ERRNO : 0;
  2784. }
  2785. if (ctx->stop_flag) {
  2786. return -1;
  2787. }
  2788. if ((n > 0) || (n == 0 && len == 0)) {
  2789. /* some data has been read, or no data was requested */
  2790. return n;
  2791. }
  2792. if (n == 0) {
  2793. /* shutdown of the socket at client side */
  2794. return -1;
  2795. }
  2796. if (n < 0) {
  2797. /* socket error - check errno */
  2798. DEBUG_TRACE("send() failed, error %d", err);
  2799. /* TODO: error handling depending on the error code.
  2800. * These codes are different between Windows and Linux.
  2801. */
  2802. return -1;
  2803. }
  2804. if (timeout > 0) {
  2805. clock_gettime(CLOCK_MONOTONIC, &now);
  2806. }
  2807. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  2808. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  2809. used */
  2810. return -1;
  2811. }
  2812. static int64_t push_all(struct mg_context *ctx,
  2813. FILE *fp,
  2814. SOCKET sock,
  2815. SSL *ssl,
  2816. const char *buf,
  2817. int64_t len)
  2818. {
  2819. double timeout = -1.0;
  2820. int64_t n, nwritten = 0;
  2821. if (ctx == NULL) {
  2822. return -1;
  2823. }
  2824. if (ctx->config[REQUEST_TIMEOUT]) {
  2825. timeout = atoi(ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  2826. }
  2827. while (len > 0 && ctx->stop_flag == 0) {
  2828. n = push(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  2829. if (n < 0) {
  2830. if (nwritten == 0) {
  2831. nwritten = n; /* Propagate the error */
  2832. }
  2833. break;
  2834. } else if (n == 0) {
  2835. break; /* No more data to write */
  2836. } else {
  2837. nwritten += n;
  2838. len -= n;
  2839. }
  2840. }
  2841. return nwritten;
  2842. }
  2843. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  2844. * Return negative value on error, or number of bytes read on success. */
  2845. static int
  2846. pull(FILE *fp, struct mg_connection *conn, char *buf, int len, double timeout)
  2847. {
  2848. int nread, err;
  2849. struct timespec start, now;
  2850. #ifdef _WIN32
  2851. typedef int len_t;
  2852. #else
  2853. typedef size_t len_t;
  2854. #endif
  2855. if (timeout > 0) {
  2856. memset(&start, 0, sizeof(start));
  2857. memset(&now, 0, sizeof(now));
  2858. clock_gettime(CLOCK_MONOTONIC, &start);
  2859. }
  2860. do {
  2861. if (fp != NULL) {
  2862. /* Use read() instead of fread(), because if we're reading from the
  2863. * CGI pipe, fread() may block until IO buffer is filled up. We
  2864. * cannot afford to block and must pass all read bytes immediately
  2865. * to the client. */
  2866. nread = (int)read(fileno(fp), buf, (size_t)len);
  2867. err = (nread < 0) ? ERRNO : 0;
  2868. #ifndef NO_SSL
  2869. } else if (conn->ssl != NULL) {
  2870. nread = SSL_read(conn->ssl, buf, len);
  2871. if (nread <= 0) {
  2872. err = SSL_get_error(conn->ssl, nread);
  2873. if ((err == 5 /* SSL_ERROR_SYSCALL */) && (nread == -1)) {
  2874. err = ERRNO;
  2875. } else {
  2876. DEBUG_TRACE("SSL_read() failed, error %d", err);
  2877. return -1;
  2878. }
  2879. } else {
  2880. err = 0;
  2881. }
  2882. #endif
  2883. } else {
  2884. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  2885. err = (nread < 0) ? ERRNO : 0;
  2886. }
  2887. if (conn->ctx->stop_flag) {
  2888. return -1;
  2889. }
  2890. if ((nread > 0) || (nread == 0 && len == 0)) {
  2891. /* some data has been read, or no data was requested */
  2892. return nread;
  2893. }
  2894. if (nread == 0) {
  2895. /* shutdown of the socket at client side */
  2896. return -1;
  2897. }
  2898. if (nread < 0) {
  2899. /* socket error - check errno */
  2900. #ifdef _WIN32
  2901. if (err == WSAEWOULDBLOCK) {
  2902. /* standard case if called from close_socket_gracefully */
  2903. return -1;
  2904. } else if (err == WSAETIMEDOUT) {
  2905. /* timeout is handled by the while loop */
  2906. } else {
  2907. DEBUG_TRACE("recv() failed, error %d", err);
  2908. return -1;
  2909. }
  2910. #else
  2911. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  2912. * if the timeout is reached and if the socket was set to non-
  2913. * blocking in close_socket_gracefully, so we can not distinguish
  2914. * here. We have to wait for the timeout in both cases for now.
  2915. */
  2916. if (err == EAGAIN || err == EWOULDBLOCK) {
  2917. /* standard case if called from close_socket_gracefully
  2918. * => should return -1 */
  2919. /* or timeout occured
  2920. * => the code must stay in the while loop */
  2921. } else {
  2922. DEBUG_TRACE("recv() failed, error %d", err);
  2923. return -1;
  2924. }
  2925. #endif
  2926. }
  2927. if (timeout > 0) {
  2928. clock_gettime(CLOCK_MONOTONIC, &now);
  2929. }
  2930. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  2931. /* Timeout occured, but no data available. */
  2932. return -1;
  2933. }
  2934. static int pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  2935. {
  2936. int n, nread = 0;
  2937. double timeout = -1.0;
  2938. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  2939. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  2940. }
  2941. while (len > 0 && conn->ctx->stop_flag == 0) {
  2942. n = pull(fp, conn, buf + nread, len, timeout);
  2943. if (n < 0) {
  2944. if (nread == 0) {
  2945. nread = n; /* Propagate the error */
  2946. }
  2947. break;
  2948. } else if (n == 0) {
  2949. break; /* No more data to read */
  2950. } else {
  2951. conn->consumed_content += n;
  2952. nread += n;
  2953. len -= n;
  2954. }
  2955. }
  2956. return nread;
  2957. }
  2958. static void discard_unread_request_data(struct mg_connection *conn)
  2959. {
  2960. char buf[MG_BUF_LEN];
  2961. size_t to_read;
  2962. int nread;
  2963. if (conn == NULL) {
  2964. return;
  2965. }
  2966. to_read = sizeof(buf);
  2967. if (conn->is_chunked) {
  2968. /* Chunked encoding: 1=chunk not read completely, 2=chunk read
  2969. * completely */
  2970. while (conn->is_chunked == 1) {
  2971. nread = mg_read(conn, buf, to_read);
  2972. if (nread <= 0) {
  2973. break;
  2974. }
  2975. }
  2976. } else {
  2977. /* Not chunked: content length is known */
  2978. while (conn->consumed_content < conn->content_len) {
  2979. if (to_read >
  2980. (size_t)(conn->content_len - conn->consumed_content)) {
  2981. to_read = (size_t)(conn->content_len - conn->consumed_content);
  2982. }
  2983. nread = mg_read(conn, buf, to_read);
  2984. if (nread <= 0) {
  2985. break;
  2986. }
  2987. }
  2988. }
  2989. }
  2990. static int mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  2991. {
  2992. int64_t n, buffered_len, nread;
  2993. int64_t len64 =
  2994. (int64_t)(len > INT_MAX ? INT_MAX : len); /* since the return value is
  2995. * int, we may not read more
  2996. * bytes */
  2997. const char *body;
  2998. if (conn == NULL) {
  2999. return 0;
  3000. }
  3001. /* If Content-Length is not set for a PUT or POST request, read until
  3002. * socket is closed */
  3003. if (conn->consumed_content == 0 && conn->content_len == -1) {
  3004. conn->content_len = INT64_MAX;
  3005. conn->must_close = 1;
  3006. }
  3007. nread = 0;
  3008. if (conn->consumed_content < conn->content_len) {
  3009. /* Adjust number of bytes to read. */
  3010. int64_t left_to_read = conn->content_len - conn->consumed_content;
  3011. if (left_to_read < len64) {
  3012. /* Do not read more than the total content length of the request.
  3013. */
  3014. len64 = left_to_read;
  3015. }
  3016. /* Return buffered data */
  3017. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len -
  3018. conn->consumed_content;
  3019. if (buffered_len > 0) {
  3020. if (len64 < buffered_len) {
  3021. buffered_len = len64;
  3022. }
  3023. body = conn->buf + conn->request_len + conn->consumed_content;
  3024. memcpy(buf, body, (size_t)buffered_len);
  3025. len64 -= buffered_len;
  3026. conn->consumed_content += buffered_len;
  3027. nread += buffered_len;
  3028. buf = (char *)buf + buffered_len;
  3029. }
  3030. /* We have returned all buffered data. Read new data from the remote
  3031. * socket.
  3032. */
  3033. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  3034. nread += n;
  3035. } else {
  3036. nread = (nread > 0 ? nread : n);
  3037. }
  3038. }
  3039. return (int)nread;
  3040. }
  3041. static char mg_getc(struct mg_connection *conn)
  3042. {
  3043. char c;
  3044. if (conn == NULL) {
  3045. return 0;
  3046. }
  3047. conn->content_len++;
  3048. if (mg_read_inner(conn, &c, 1) <= 0) {
  3049. return (char)0;
  3050. }
  3051. return c;
  3052. }
  3053. int mg_read(struct mg_connection *conn, void *buf, size_t len)
  3054. {
  3055. if (len > INT_MAX) {
  3056. len = INT_MAX;
  3057. }
  3058. if (conn == NULL) {
  3059. return 0;
  3060. }
  3061. if (conn->is_chunked) {
  3062. size_t all_read = 0;
  3063. while (len > 0) {
  3064. if (conn->chunk_remainder) {
  3065. /* copy from the remainder of the last received chunk */
  3066. long read_ret;
  3067. size_t read_now =
  3068. ((conn->chunk_remainder > len) ? (len)
  3069. : (conn->chunk_remainder));
  3070. conn->content_len += (int)read_now;
  3071. read_ret =
  3072. mg_read_inner(conn, (char *)buf + all_read, read_now);
  3073. all_read += (size_t)read_ret;
  3074. conn->chunk_remainder -= read_now;
  3075. len -= read_now;
  3076. if (conn->chunk_remainder == 0) {
  3077. /* the rest of the data in the current chunk has been read
  3078. */
  3079. if ((mg_getc(conn) != '\r') || (mg_getc(conn) != '\n')) {
  3080. /* Protocol violation */
  3081. return -1;
  3082. }
  3083. }
  3084. } else {
  3085. /* fetch a new chunk */
  3086. int i = 0;
  3087. char lenbuf[64];
  3088. char *end = 0;
  3089. unsigned long chunkSize = 0;
  3090. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  3091. lenbuf[i] = mg_getc(conn);
  3092. if (i > 0 && lenbuf[i] == '\r' && lenbuf[i - 1] != '\r') {
  3093. continue;
  3094. }
  3095. if (i > 1 && lenbuf[i] == '\n' && lenbuf[i - 1] == '\r') {
  3096. lenbuf[i + 1] = 0;
  3097. chunkSize = strtoul(lenbuf, &end, 16);
  3098. break;
  3099. }
  3100. if (!isalnum(lenbuf[i])) {
  3101. /* illegal character for chunk length */
  3102. return -1;
  3103. }
  3104. }
  3105. if ((end == NULL) || (*end != '\r')) {
  3106. /* chunksize not set correctly */
  3107. return -1;
  3108. }
  3109. conn->chunk_remainder = chunkSize;
  3110. if (chunkSize == 0) {
  3111. /* regular end of content */
  3112. conn->is_chunked = 2;
  3113. break;
  3114. }
  3115. }
  3116. }
  3117. return (int)all_read;
  3118. }
  3119. return mg_read_inner(conn, buf, len);
  3120. }
  3121. int mg_write(struct mg_connection *conn, const void *buf, size_t len)
  3122. {
  3123. time_t now;
  3124. int64_t n, total, allowed;
  3125. if (conn == NULL) {
  3126. return 0;
  3127. }
  3128. if (conn->throttle > 0) {
  3129. if ((now = time(NULL)) != conn->last_throttle_time) {
  3130. conn->last_throttle_time = now;
  3131. conn->last_throttle_bytes = 0;
  3132. }
  3133. allowed = conn->throttle - conn->last_throttle_bytes;
  3134. if (allowed > (int64_t)len) {
  3135. allowed = (int64_t)len;
  3136. }
  3137. if ((total = push_all(conn->ctx,
  3138. NULL,
  3139. conn->client.sock,
  3140. conn->ssl,
  3141. (const char *)buf,
  3142. (int64_t)allowed)) == allowed) {
  3143. buf = (char *)buf + total;
  3144. conn->last_throttle_bytes += total;
  3145. while (total < (int64_t)len && conn->ctx->stop_flag == 0) {
  3146. allowed = conn->throttle > (int64_t)len - total
  3147. ? (int64_t)len - total
  3148. : conn->throttle;
  3149. if ((n = push_all(conn->ctx,
  3150. NULL,
  3151. conn->client.sock,
  3152. conn->ssl,
  3153. (const char *)buf,
  3154. (int64_t)allowed)) != allowed) {
  3155. break;
  3156. }
  3157. sleep(1);
  3158. conn->last_throttle_bytes = allowed;
  3159. conn->last_throttle_time = time(NULL);
  3160. buf = (char *)buf + n;
  3161. total += n;
  3162. }
  3163. }
  3164. } else {
  3165. total = push_all(conn->ctx,
  3166. NULL,
  3167. conn->client.sock,
  3168. conn->ssl,
  3169. (const char *)buf,
  3170. (int64_t)len);
  3171. }
  3172. return (int)total;
  3173. }
  3174. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  3175. static int alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  3176. {
  3177. va_list ap_copy;
  3178. size_t size = MG_BUF_LEN;
  3179. int len = -1;
  3180. *buf = NULL;
  3181. while (len < 0) {
  3182. if (*buf) {
  3183. mg_free(*buf);
  3184. }
  3185. *buf = (char *)mg_malloc(size *= 4);
  3186. if (!*buf) {
  3187. break;
  3188. }
  3189. va_copy(ap_copy, ap);
  3190. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  3191. va_end(ap_copy);
  3192. *buf[size - 1] = 0;
  3193. }
  3194. return len;
  3195. }
  3196. /* Print message to buffer. If buffer is large enough to hold the message,
  3197. * return buffer. If buffer is to small, allocate large enough buffer on heap,
  3198. * and return allocated buffer. */
  3199. static int alloc_vprintf(char **buf, size_t size, const char *fmt, va_list ap)
  3200. {
  3201. va_list ap_copy;
  3202. int len;
  3203. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  3204. * buffer is too small. Also, older versions of msvcrt.dll do not have
  3205. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  3206. * Therefore, we make two passes: on first pass, get required message
  3207. * length.
  3208. * On second pass, actually print the message. */
  3209. va_copy(ap_copy, ap);
  3210. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  3211. va_end(ap_copy);
  3212. if (len < 0) {
  3213. /* C runtime is not standard compliant, vsnprintf() returned -1.
  3214. * Switch to alternative code path that uses incremental allocations.
  3215. */
  3216. va_copy(ap_copy, ap);
  3217. len = alloc_vprintf2(buf, fmt, ap);
  3218. va_end(ap_copy);
  3219. } else if ((size_t)(len) > size && (size = (size_t)(len) + 1) > 0 &&
  3220. (*buf = (char *)mg_malloc(size)) == NULL) {
  3221. len = -1; /* Allocation failed, mark failure */
  3222. } else {
  3223. va_copy(ap_copy, ap);
  3224. IGNORE_UNUSED_RESULT(vsnprintf_impl(*buf, size, fmt, ap_copy));
  3225. va_end(ap_copy);
  3226. }
  3227. return len;
  3228. }
  3229. static int mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  3230. {
  3231. char mem[MG_BUF_LEN], *buf = mem;
  3232. int len;
  3233. if ((len = alloc_vprintf(&buf, sizeof(mem), fmt, ap)) > 0) {
  3234. len = mg_write(conn, buf, (size_t)len);
  3235. }
  3236. if (buf != mem && buf != NULL) {
  3237. mg_free(buf);
  3238. }
  3239. return len;
  3240. }
  3241. int mg_printf(struct mg_connection *conn, const char *fmt, ...)
  3242. {
  3243. va_list ap;
  3244. int result;
  3245. va_start(ap, fmt);
  3246. result = mg_vprintf(conn, fmt, ap);
  3247. va_end(ap);
  3248. return result;
  3249. }
  3250. int mg_url_decode(const char *src,
  3251. int src_len,
  3252. char *dst,
  3253. int dst_len,
  3254. int is_form_url_encoded)
  3255. {
  3256. int i, j, a, b;
  3257. #define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W')
  3258. for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) {
  3259. if (i < src_len - 2 && src[i] == '%' &&
  3260. isxdigit(*(const unsigned char *)(src + i + 1)) &&
  3261. isxdigit(*(const unsigned char *)(src + i + 2))) {
  3262. a = tolower(*(const unsigned char *)(src + i + 1));
  3263. b = tolower(*(const unsigned char *)(src + i + 2));
  3264. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  3265. i += 2;
  3266. } else if (is_form_url_encoded && src[i] == '+') {
  3267. dst[j] = ' ';
  3268. } else {
  3269. dst[j] = src[i];
  3270. }
  3271. }
  3272. dst[j] = '\0'; /* Null-terminate the destination */
  3273. return i >= src_len ? j : -1;
  3274. }
  3275. int mg_get_var(const char *data,
  3276. size_t data_len,
  3277. const char *name,
  3278. char *dst,
  3279. size_t dst_len)
  3280. {
  3281. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  3282. }
  3283. int mg_get_var2(const char *data,
  3284. size_t data_len,
  3285. const char *name,
  3286. char *dst,
  3287. size_t dst_len,
  3288. size_t occurrence)
  3289. {
  3290. const char *p, *e, *s;
  3291. size_t name_len;
  3292. int len;
  3293. if (dst == NULL || dst_len == 0) {
  3294. len = -2;
  3295. } else if (data == NULL || name == NULL || data_len == 0) {
  3296. len = -1;
  3297. dst[0] = '\0';
  3298. } else {
  3299. name_len = strlen(name);
  3300. e = data + data_len;
  3301. len = -1;
  3302. dst[0] = '\0';
  3303. /* data is "var1=val1&var2=val2...". Find variable first */
  3304. for (p = data; p + name_len < e; p++) {
  3305. if ((p == data || p[-1] == '&') && p[name_len] == '=' &&
  3306. !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  3307. /* Point p to variable value */
  3308. p += name_len + 1;
  3309. /* Point s to the end of the value */
  3310. s = (const char *)memchr(p, '&', (size_t)(e - p));
  3311. if (s == NULL) {
  3312. s = e;
  3313. }
  3314. /* assert(s >= p); */
  3315. if (s < p) {
  3316. return -3;
  3317. }
  3318. /* Decode variable into destination buffer */
  3319. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  3320. /* Redirect error code from -1 to -2 (destination buffer too
  3321. * small). */
  3322. if (len == -1) {
  3323. len = -2;
  3324. }
  3325. break;
  3326. }
  3327. }
  3328. }
  3329. return len;
  3330. }
  3331. int mg_get_cookie(const char *cookie_header,
  3332. const char *var_name,
  3333. char *dst,
  3334. size_t dst_size)
  3335. {
  3336. const char *s, *p, *end;
  3337. int name_len, len = -1;
  3338. if (dst == NULL || dst_size == 0) {
  3339. len = -2;
  3340. } else if (var_name == NULL || (s = cookie_header) == NULL) {
  3341. len = -1;
  3342. dst[0] = '\0';
  3343. } else {
  3344. name_len = (int)strlen(var_name);
  3345. end = s + strlen(s);
  3346. dst[0] = '\0';
  3347. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  3348. if (s[name_len] == '=') {
  3349. s += name_len + 1;
  3350. if ((p = strchr(s, ' ')) == NULL) {
  3351. p = end;
  3352. }
  3353. if (p[-1] == ';') {
  3354. p--;
  3355. }
  3356. if (*s == '"' && p[-1] == '"' && p > s + 1) {
  3357. s++;
  3358. p--;
  3359. }
  3360. if ((size_t)(p - s) < dst_size) {
  3361. len = (int)(p - s);
  3362. mg_strlcpy(dst, s, (size_t)len + 1);
  3363. } else {
  3364. len = -3;
  3365. }
  3366. break;
  3367. }
  3368. }
  3369. }
  3370. return len;
  3371. }
  3372. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  3373. static void base64_encode(const unsigned char *src, int src_len, char *dst)
  3374. {
  3375. static const char *b64 =
  3376. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3377. int i, j, a, b, c;
  3378. for (i = j = 0; i < src_len; i += 3) {
  3379. a = src[i];
  3380. b = i + 1 >= src_len ? 0 : src[i + 1];
  3381. c = i + 2 >= src_len ? 0 : src[i + 2];
  3382. dst[j++] = b64[a >> 2];
  3383. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  3384. if (i + 1 < src_len) {
  3385. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  3386. }
  3387. if (i + 2 < src_len) {
  3388. dst[j++] = b64[c & 63];
  3389. }
  3390. }
  3391. while (j % 4 != 0) {
  3392. dst[j++] = '=';
  3393. }
  3394. dst[j++] = '\0';
  3395. }
  3396. #endif
  3397. #if defined(USE_LUA)
  3398. static unsigned char b64reverse(char letter)
  3399. {
  3400. if (letter >= 'A' && letter <= 'Z') {
  3401. return letter - 'A';
  3402. }
  3403. if (letter >= 'a' && letter <= 'z') {
  3404. return letter - 'a' + 26;
  3405. }
  3406. if (letter >= '0' && letter <= '9') {
  3407. return letter - '0' + 52;
  3408. }
  3409. if (letter == '+') {
  3410. return 62;
  3411. }
  3412. if (letter == '/') {
  3413. return 63;
  3414. }
  3415. if (letter == '=') {
  3416. return 255; /* normal end */
  3417. }
  3418. return 254; /* error */
  3419. }
  3420. static int
  3421. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  3422. {
  3423. int i;
  3424. unsigned char a, b, c, d;
  3425. *dst_len = 0;
  3426. for (i = 0; i < src_len; i += 4) {
  3427. a = b64reverse(src[i]);
  3428. if (a >= 254) {
  3429. return i;
  3430. }
  3431. b = b64reverse(i + 1 >= src_len ? 0 : src[i + 1]);
  3432. if (b >= 254) {
  3433. return i + 1;
  3434. }
  3435. c = b64reverse(i + 2 >= src_len ? 0 : src[i + 2]);
  3436. if (c == 254) {
  3437. return i + 2;
  3438. }
  3439. d = b64reverse(i + 3 >= src_len ? 0 : src[i + 3]);
  3440. if (d == 254) {
  3441. return i + 3;
  3442. }
  3443. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  3444. if (c != 255) {
  3445. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  3446. if (d != 255) {
  3447. dst[(*dst_len)++] = (c << 6) + d;
  3448. }
  3449. }
  3450. }
  3451. return -1;
  3452. }
  3453. #endif
  3454. static int is_put_or_delete_method(const struct mg_connection *conn)
  3455. {
  3456. if (conn) {
  3457. const char *s = conn->request_info.request_method;
  3458. return s != NULL && (!strcmp(s, "PUT") || !strcmp(s, "DELETE") ||
  3459. !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  3460. }
  3461. return 0;
  3462. }
  3463. static void
  3464. interpret_uri(struct mg_connection *conn, /* in: request */
  3465. char *filename, /* out: filename */
  3466. size_t filename_buf_len, /* in: size of filename buffer */
  3467. struct file *filep, /* out: file structure */
  3468. int *is_found, /* out: file is found (directly) */
  3469. int *is_script_ressource, /* out: handled by a script? */
  3470. int *is_websocket_request, /* out: websocket connetion? */
  3471. int *is_put_or_delete_request /* out: put/delete a file? */
  3472. )
  3473. {
  3474. /* TODO (high): Restructure this function */
  3475. if (conn && conn->ctx) {
  3476. #if !defined(NO_FILES)
  3477. const char *uri = conn->request_info.rel_uri;
  3478. const char *root = conn->ctx->config[DOCUMENT_ROOT];
  3479. const char *rewrite;
  3480. struct vec a, b;
  3481. int match_len;
  3482. char gz_path[PATH_MAX];
  3483. char const *accept_encoding;
  3484. int truncated;
  3485. #if !defined(NO_CGI) || defined(USE_LUA)
  3486. char *p;
  3487. #endif
  3488. #else
  3489. (void)filename_buf_len; /* unused if NO_FILES is defined */
  3490. #endif
  3491. memset(filep, 0, sizeof(*filep));
  3492. *filename = 0;
  3493. *is_found = 0;
  3494. *is_script_ressource = 0;
  3495. *is_put_or_delete_request = is_put_or_delete_method(conn);
  3496. #if defined(USE_WEBSOCKET)
  3497. *is_websocket_request = is_websocket_protocol(conn);
  3498. #if !defined(NO_FILES)
  3499. if (*is_websocket_request && conn->ctx->config[WEBSOCKET_ROOT]) {
  3500. root = conn->ctx->config[WEBSOCKET_ROOT];
  3501. }
  3502. #endif /* !NO_FILES */
  3503. #else /* USE_WEBSOCKET */
  3504. *is_websocket_request = 0;
  3505. #endif /* USE_WEBSOCKET */
  3506. #if !defined(NO_FILES)
  3507. /* Note that root == NULL is a regular use case here. This occurs,
  3508. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  3509. * config is not required. */
  3510. if (root == NULL) {
  3511. /* all file related outputs have already been set to 0, just return
  3512. */
  3513. return;
  3514. }
  3515. /* Using buf_len - 1 because memmove() for PATH_INFO may shift part
  3516. * of the path one byte on the right.
  3517. * If document_root is NULL, leave the file empty. */
  3518. mg_snprintf(conn,
  3519. &truncated,
  3520. filename,
  3521. filename_buf_len - 1,
  3522. "%s%s",
  3523. root,
  3524. uri);
  3525. if (truncated) {
  3526. goto interpret_cleanup;
  3527. }
  3528. rewrite = conn->ctx->config[REWRITE];
  3529. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  3530. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  3531. mg_snprintf(conn,
  3532. &truncated,
  3533. filename,
  3534. filename_buf_len - 1,
  3535. "%.*s%s",
  3536. (int)b.len,
  3537. b.ptr,
  3538. uri + match_len);
  3539. break;
  3540. }
  3541. }
  3542. if (truncated) {
  3543. goto interpret_cleanup;
  3544. }
  3545. /* Local file path and name, corresponding to requested URI
  3546. * is now stored in "filename" variable. */
  3547. if (mg_stat(conn, filename, filep)) {
  3548. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  3549. /* File exists. Check if it is a script type. */
  3550. if (0
  3551. #if !defined(NO_CGI)
  3552. ||
  3553. match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  3554. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  3555. filename) > 0
  3556. #endif
  3557. #if defined(USE_LUA)
  3558. ||
  3559. match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  3560. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  3561. filename) > 0
  3562. #endif
  3563. #if defined(USE_DUKTAPE)
  3564. ||
  3565. match_prefix(
  3566. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  3567. strlen(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  3568. filename) > 0
  3569. #endif
  3570. ) {
  3571. /* The request addresses a CGI script or a Lua script. The URI
  3572. * corresponds to the script itself (like /path/script.cgi),
  3573. * and there is no additional resource path
  3574. * (like /path/script.cgi/something).
  3575. * Requests that modify (replace or delete) a resource, like
  3576. * PUT and DELETE requests, should replace/delete the script
  3577. * file.
  3578. * Requests that read or write from/to a resource, like GET and
  3579. * POST requests, should call the script and return the
  3580. * generated response. */
  3581. *is_script_ressource = !*is_put_or_delete_request;
  3582. }
  3583. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  3584. *is_found = 1;
  3585. return;
  3586. }
  3587. /* If we can't find the actual file, look for the file
  3588. * with the same name but a .gz extension. If we find it,
  3589. * use that and set the gzipped flag in the file struct
  3590. * to indicate that the response need to have the content-
  3591. * encoding: gzip header.
  3592. * We can only do this if the browser declares support. */
  3593. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) !=
  3594. NULL) {
  3595. if (strstr(accept_encoding, "gzip") != NULL) {
  3596. mg_snprintf(conn,
  3597. &truncated,
  3598. gz_path,
  3599. sizeof(gz_path),
  3600. "%s.gz",
  3601. filename);
  3602. if (truncated) {
  3603. goto interpret_cleanup;
  3604. }
  3605. if (mg_stat(conn, gz_path, filep)) {
  3606. if (filep) {
  3607. filep->gzipped = 1;
  3608. *is_found = 1;
  3609. }
  3610. /* Currently gz files can not be scripts. */
  3611. return;
  3612. }
  3613. }
  3614. }
  3615. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  3616. /* Support PATH_INFO for CGI scripts. */
  3617. for (p = filename + strlen(filename); p > filename + 1; p--) {
  3618. if (*p == '/') {
  3619. *p = '\0';
  3620. if ((0
  3621. #if !defined(NO_CGI)
  3622. ||
  3623. match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  3624. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  3625. filename) > 0
  3626. #endif
  3627. #if defined(USE_LUA)
  3628. ||
  3629. match_prefix(
  3630. conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  3631. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  3632. filename) > 0
  3633. #endif
  3634. #if defined(USE_DUKTAPE)
  3635. ||
  3636. match_prefix(
  3637. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  3638. strlen(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  3639. filename) > 0
  3640. #endif
  3641. ) &&
  3642. mg_stat(conn, filename, filep)) {
  3643. /* Shift PATH_INFO block one character right, e.g.
  3644. * "/x.cgi/foo/bar\x00" => "/x.cgi\x00/foo/bar\x00"
  3645. * conn->path_info is pointing to the local variable "path"
  3646. * declared in handle_request(), so PATH_INFO is not valid
  3647. * after handle_request returns. */
  3648. conn->path_info = p + 1;
  3649. memmove(p + 2, p + 1, strlen(p + 1) + 1); /* +1 is for
  3650. * trailing \0 */
  3651. p[1] = '/';
  3652. *is_script_ressource = 1;
  3653. break;
  3654. } else {
  3655. *p = '/';
  3656. }
  3657. }
  3658. }
  3659. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  3660. #endif /* !defined(NO_FILES) */
  3661. }
  3662. return;
  3663. #if !defined(NO_FILES)
  3664. /* Reset all outputs */
  3665. interpret_cleanup:
  3666. memset(filep, 0, sizeof(*filep));
  3667. *filename = 0;
  3668. *is_found = 0;
  3669. *is_script_ressource = 0;
  3670. #endif
  3671. }
  3672. /* Check whether full request is buffered. Return:
  3673. * -1 if request is malformed
  3674. * 0 if request is not yet fully buffered
  3675. * >0 actual request length, including last \r\n\r\n */
  3676. static int get_request_len(const char *buf, int buflen)
  3677. {
  3678. const char *s, *e;
  3679. int len = 0;
  3680. for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
  3681. /* Control characters are not allowed but >=128 is. */
  3682. if (!isprint(*(const unsigned char *)s) && *s != '\r' && *s != '\n' &&
  3683. *(const unsigned char *)s < 128) {
  3684. len = -1;
  3685. break; /* [i_a] abort scan as soon as one malformed character is
  3686. * found; */
  3687. /* don't let subsequent \r\n\r\n win us over anyhow */
  3688. } else if (s[0] == '\n' && s[1] == '\n') {
  3689. len = (int)(s - buf) + 2;
  3690. } else if (s[0] == '\n' && &s[1] < e && s[1] == '\r' && s[2] == '\n') {
  3691. len = (int)(s - buf) + 3;
  3692. }
  3693. return len;
  3694. }
  3695. /* Convert month to the month number. Return -1 on error, or month number */
  3696. static int get_month_index(const char *s)
  3697. {
  3698. size_t i;
  3699. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  3700. if (!strcmp(s, month_names[i])) {
  3701. return (int)i;
  3702. }
  3703. }
  3704. return -1;
  3705. }
  3706. static int num_leap_years(int year)
  3707. {
  3708. return year / 4 - year / 100 + year / 400;
  3709. }
  3710. /* Parse UTC date-time string, and return the corresponding time_t value. */
  3711. static time_t parse_date_string(const char *datetime)
  3712. {
  3713. static const unsigned short days_before_month[] = {
  3714. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
  3715. char month_str[32] = {0};
  3716. int second, minute, hour, day, month, year, leap_days, days;
  3717. time_t result = (time_t)0;
  3718. if ((sscanf(datetime,
  3719. "%d/%3s/%d %d:%d:%d",
  3720. &day,
  3721. month_str,
  3722. &year,
  3723. &hour,
  3724. &minute,
  3725. &second) == 6) ||
  3726. (sscanf(datetime,
  3727. "%d %3s %d %d:%d:%d",
  3728. &day,
  3729. month_str,
  3730. &year,
  3731. &hour,
  3732. &minute,
  3733. &second) == 6) ||
  3734. (sscanf(datetime,
  3735. "%*3s, %d %3s %d %d:%d:%d",
  3736. &day,
  3737. month_str,
  3738. &year,
  3739. &hour,
  3740. &minute,
  3741. &second) == 6) ||
  3742. (sscanf(datetime,
  3743. "%d-%3s-%d %d:%d:%d",
  3744. &day,
  3745. month_str,
  3746. &year,
  3747. &hour,
  3748. &minute,
  3749. &second) == 6)) {
  3750. month = get_month_index(month_str);
  3751. if ((month >= 0) && (year > 1970)) {
  3752. leap_days = num_leap_years(year) - num_leap_years(1970);
  3753. year -= 1970;
  3754. days =
  3755. year * 365 + days_before_month[month] + (day - 1) + leap_days;
  3756. result = (time_t)days * 24 * 3600 + (time_t)hour * 3600 +
  3757. minute * 60 + second;
  3758. }
  3759. }
  3760. return result;
  3761. }
  3762. /* Protect against directory disclosure attack by removing '..',
  3763. * excessive '/' and '\' characters */
  3764. static void remove_double_dots_and_double_slashes(char *s)
  3765. {
  3766. char *p = s;
  3767. while (*s != '\0') {
  3768. *p++ = *s++;
  3769. if (s[-1] == '/' || s[-1] == '\\') {
  3770. /* Skip all following slashes, backslashes and double-dots */
  3771. while (s[0] != '\0') {
  3772. if (s[0] == '/' || s[0] == '\\') {
  3773. s++;
  3774. } else if (s[0] == '.' && s[1] == '.') {
  3775. s += 2;
  3776. } else {
  3777. break;
  3778. }
  3779. }
  3780. }
  3781. }
  3782. *p = '\0';
  3783. }
  3784. static const struct {
  3785. const char *extension;
  3786. size_t ext_len;
  3787. const char *mime_type;
  3788. } builtin_mime_types[] = {
  3789. /* IANA registered MIME types (http://www.iana.org/assignments/media-types)
  3790. * application types */
  3791. {".doc", 4, "application/msword"},
  3792. {".eps", 4, "application/postscript"},
  3793. {".exe", 4, "application/octet-stream"},
  3794. {".js", 3, "application/javascript"},
  3795. {".json", 5, "application/json"},
  3796. {".pdf", 4, "application/pdf"},
  3797. {".ps", 3, "application/postscript"},
  3798. {".rtf", 4, "application/rtf"},
  3799. {".xhtml", 6, "application/xhtml+xml"},
  3800. {".xsl", 4, "application/xml"},
  3801. {".xslt", 5, "application/xml"},
  3802. /* audio */
  3803. {".mp3", 4, "audio/mpeg"},
  3804. {".oga", 4, "audio/ogg"},
  3805. {".ogg", 4, "audio/ogg"},
  3806. /* image */
  3807. {".gif", 4, "image/gif"},
  3808. {".ief", 4, "image/ief"},
  3809. {".jpeg", 5, "image/jpeg"},
  3810. {".jpg", 4, "image/jpeg"},
  3811. {".jpm", 4, "image/jpm"},
  3812. {".jpx", 4, "image/jpx"},
  3813. {".png", 4, "image/png"},
  3814. {".svg", 4, "image/svg+xml"},
  3815. {".tif", 4, "image/tiff"},
  3816. {".tiff", 5, "image/tiff"},
  3817. /* model */
  3818. {".wrl", 4, "model/vrml"},
  3819. /* text */
  3820. {".css", 4, "text/css"},
  3821. {".csv", 4, "text/csv"},
  3822. {".htm", 4, "text/html"},
  3823. {".html", 5, "text/html"},
  3824. {".sgm", 4, "text/sgml"},
  3825. {".shtm", 5, "text/html"},
  3826. {".shtml", 6, "text/html"},
  3827. {".txt", 4, "text/plain"},
  3828. {".xml", 4, "text/xml"},
  3829. /* video */
  3830. {".mov", 4, "video/quicktime"},
  3831. {".mp4", 4, "video/mp4"},
  3832. {".mpeg", 5, "video/mpeg"},
  3833. {".mpg", 4, "video/mpeg"},
  3834. {".ogv", 4, "video/ogg"},
  3835. {".qt", 3, "video/quicktime"},
  3836. /* not registered types
  3837. * (http://reference.sitepoint.com/html/mime-types-full,
  3838. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  3839. {".arj", 4, "application/x-arj-compressed"},
  3840. {".gz", 3, "application/x-gunzip"},
  3841. {".rar", 4, "application/x-arj-compressed"},
  3842. {".swf", 4, "application/x-shockwave-flash"},
  3843. {".tar", 4, "application/x-tar"},
  3844. {".tgz", 4, "application/x-tar-gz"},
  3845. {".torrent", 8, "application/x-bittorrent"},
  3846. {".ppt", 4, "application/x-mspowerpoint"},
  3847. {".xls", 4, "application/x-msexcel"},
  3848. {".zip", 4, "application/x-zip-compressed"},
  3849. {".aac",
  3850. 4,
  3851. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  3852. {".aif", 4, "audio/x-aif"},
  3853. {".m3u", 4, "audio/x-mpegurl"},
  3854. {".mid", 4, "audio/x-midi"},
  3855. {".ra", 3, "audio/x-pn-realaudio"},
  3856. {".ram", 4, "audio/x-pn-realaudio"},
  3857. {".wav", 4, "audio/x-wav"},
  3858. {".bmp", 4, "image/bmp"},
  3859. {".ico", 4, "image/x-icon"},
  3860. {".pct", 4, "image/x-pct"},
  3861. {".pict", 5, "image/pict"},
  3862. {".rgb", 4, "image/x-rgb"},
  3863. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  3864. {".asf", 4, "video/x-ms-asf"},
  3865. {".avi", 4, "video/x-msvideo"},
  3866. {".m4v", 4, "video/x-m4v"},
  3867. {NULL, 0, NULL}};
  3868. const char *mg_get_builtin_mime_type(const char *path)
  3869. {
  3870. const char *ext;
  3871. size_t i, path_len;
  3872. path_len = strlen(path);
  3873. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  3874. ext = path + (path_len - builtin_mime_types[i].ext_len);
  3875. if (path_len > builtin_mime_types[i].ext_len &&
  3876. mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {
  3877. return builtin_mime_types[i].mime_type;
  3878. }
  3879. }
  3880. return "text/plain";
  3881. }
  3882. /* Look at the "path" extension and figure what mime type it has.
  3883. * Store mime type in the vector. */
  3884. static void
  3885. get_mime_type(struct mg_context *ctx, const char *path, struct vec *vec)
  3886. {
  3887. struct vec ext_vec, mime_vec;
  3888. const char *list, *ext;
  3889. size_t path_len;
  3890. path_len = strlen(path);
  3891. if (ctx == NULL || vec == NULL) {
  3892. return;
  3893. }
  3894. /* Scan user-defined mime types first, in case user wants to
  3895. * override default mime types. */
  3896. list = ctx->config[EXTRA_MIME_TYPES];
  3897. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  3898. /* ext now points to the path suffix */
  3899. ext = path + path_len - ext_vec.len;
  3900. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  3901. *vec = mime_vec;
  3902. return;
  3903. }
  3904. }
  3905. vec->ptr = mg_get_builtin_mime_type(path);
  3906. vec->len = strlen(vec->ptr);
  3907. }
  3908. /* Stringify binary data. Output buffer must be twice as big as input,
  3909. * because each byte takes 2 bytes in string representation */
  3910. static void bin2str(char *to, const unsigned char *p, size_t len)
  3911. {
  3912. static const char *hex = "0123456789abcdef";
  3913. for (; len--; p++) {
  3914. *to++ = hex[p[0] >> 4];
  3915. *to++ = hex[p[0] & 0x0f];
  3916. }
  3917. *to = '\0';
  3918. }
  3919. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes. */
  3920. char *mg_md5(char buf[33], ...)
  3921. {
  3922. md5_byte_t hash[16];
  3923. const char *p;
  3924. va_list ap;
  3925. md5_state_t ctx;
  3926. md5_init(&ctx);
  3927. va_start(ap, buf);
  3928. while ((p = va_arg(ap, const char *)) != NULL) {
  3929. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  3930. }
  3931. va_end(ap);
  3932. md5_finish(&ctx, hash);
  3933. bin2str(buf, hash, sizeof(hash));
  3934. return buf;
  3935. }
  3936. /* Check the user's password, return 1 if OK */
  3937. static int check_password(const char *method,
  3938. const char *ha1,
  3939. const char *uri,
  3940. const char *nonce,
  3941. const char *nc,
  3942. const char *cnonce,
  3943. const char *qop,
  3944. const char *response)
  3945. {
  3946. char ha2[32 + 1], expected_response[32 + 1];
  3947. /* Some of the parameters may be NULL */
  3948. if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL ||
  3949. qop == NULL || response == NULL) {
  3950. return 0;
  3951. }
  3952. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  3953. /* TODO(lsm): check for authentication timeout */
  3954. if (/* strcmp(dig->uri, c->ouri) != 0 || */
  3955. strlen(response) != 32
  3956. /* || now - strtoul(dig->nonce, NULL, 10) > 3600 */
  3957. ) {
  3958. return 0;
  3959. }
  3960. mg_md5(ha2, method, ":", uri, NULL);
  3961. mg_md5(expected_response,
  3962. ha1,
  3963. ":",
  3964. nonce,
  3965. ":",
  3966. nc,
  3967. ":",
  3968. cnonce,
  3969. ":",
  3970. qop,
  3971. ":",
  3972. ha2,
  3973. NULL);
  3974. return mg_strcasecmp(response, expected_response) == 0;
  3975. }
  3976. /* Use the global passwords file, if specified by auth_gpass option,
  3977. * or search for .htpasswd in the requested directory. */
  3978. static void
  3979. open_auth_file(struct mg_connection *conn, const char *path, struct file *filep)
  3980. {
  3981. if (conn != NULL && conn->ctx != NULL) {
  3982. char name[PATH_MAX];
  3983. const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
  3984. struct file file = STRUCT_FILE_INITIALIZER;
  3985. int truncated;
  3986. if (gpass != NULL) {
  3987. /* Use global passwords file */
  3988. if (!mg_fopen(conn, gpass, "r", filep)) {
  3989. #ifdef DEBUG
  3990. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  3991. #endif
  3992. }
  3993. /* Important: using local struct file to test path for is_directory
  3994. * flag. If filep is used, mg_stat() makes it appear as if auth file
  3995. * was opened. */
  3996. } else if (mg_stat(conn, path, &file) && file.is_directory) {
  3997. mg_snprintf(conn,
  3998. &truncated,
  3999. name,
  4000. sizeof(name),
  4001. "%s/%s",
  4002. path,
  4003. PASSWORDS_FILE_NAME);
  4004. if (truncated || !mg_fopen(conn, name, "r", filep)) {
  4005. #ifdef DEBUG
  4006. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  4007. #endif
  4008. }
  4009. } else {
  4010. /* Try to find .htpasswd in requested directory. */
  4011. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  4012. if (e[0] == '/') {
  4013. break;
  4014. }
  4015. }
  4016. mg_snprintf(conn,
  4017. &truncated,
  4018. name,
  4019. sizeof(name),
  4020. "%.*s%s",
  4021. (int)(e - p),
  4022. p,
  4023. PASSWORDS_FILE_NAME);
  4024. if (truncated || !mg_fopen(conn, name, "r", filep)) {
  4025. #ifdef DEBUG
  4026. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  4027. #endif
  4028. }
  4029. }
  4030. }
  4031. }
  4032. /* Parsed Authorization header */
  4033. struct ah {
  4034. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  4035. };
  4036. /* Return 1 on success. Always initializes the ah structure. */
  4037. static int parse_auth_header(struct mg_connection *conn,
  4038. char *buf,
  4039. size_t buf_size,
  4040. struct ah *ah)
  4041. {
  4042. char *name, *value, *s;
  4043. const char *auth_header;
  4044. unsigned long nonce;
  4045. if (!ah || !conn) {
  4046. return 0;
  4047. }
  4048. (void)memset(ah, 0, sizeof(*ah));
  4049. if ((auth_header = mg_get_header(conn, "Authorization")) == NULL ||
  4050. mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  4051. return 0;
  4052. }
  4053. /* Make modifiable copy of the auth header */
  4054. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  4055. s = buf;
  4056. /* Parse authorization header */
  4057. for (;;) {
  4058. /* Gobble initial spaces */
  4059. while (isspace(*(unsigned char *)s)) {
  4060. s++;
  4061. }
  4062. name = skip_quoted(&s, "=", " ", 0);
  4063. /* Value is either quote-delimited, or ends at first comma or space. */
  4064. if (s[0] == '\"') {
  4065. s++;
  4066. value = skip_quoted(&s, "\"", " ", '\\');
  4067. if (s[0] == ',') {
  4068. s++;
  4069. }
  4070. } else {
  4071. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  4072. * spaces */
  4073. }
  4074. if (*name == '\0') {
  4075. break;
  4076. }
  4077. if (!strcmp(name, "username")) {
  4078. ah->user = value;
  4079. } else if (!strcmp(name, "cnonce")) {
  4080. ah->cnonce = value;
  4081. } else if (!strcmp(name, "response")) {
  4082. ah->response = value;
  4083. } else if (!strcmp(name, "uri")) {
  4084. ah->uri = value;
  4085. } else if (!strcmp(name, "qop")) {
  4086. ah->qop = value;
  4087. } else if (!strcmp(name, "nc")) {
  4088. ah->nc = value;
  4089. } else if (!strcmp(name, "nonce")) {
  4090. ah->nonce = value;
  4091. }
  4092. }
  4093. #ifndef NO_NONCE_CHECK
  4094. /* Convert the nonce from the client to a number and check it. */
  4095. /* Server side nonce check is valuable in all situations but one: if the
  4096. * server restarts frequently,
  4097. * but the client should not see that, so the server should accept nonces
  4098. * from
  4099. * previous starts. */
  4100. if (ah->nonce == NULL) {
  4101. return 0;
  4102. }
  4103. s = NULL;
  4104. nonce = strtoul(ah->nonce, &s, 10);
  4105. if ((s == NULL) || (*s != 0)) {
  4106. return 0;
  4107. }
  4108. nonce ^= (uintptr_t)(conn->ctx);
  4109. if (nonce < conn->ctx->start_time) {
  4110. /* nonce is from a previous start of the server and no longer valid
  4111. * (replay attack?) */
  4112. return 0;
  4113. }
  4114. if (nonce >= conn->ctx->start_time + conn->ctx->nonce_count) {
  4115. return 0;
  4116. }
  4117. #endif
  4118. /* CGI needs it as REMOTE_USER */
  4119. if (ah->user != NULL) {
  4120. conn->request_info.remote_user = mg_strdup(ah->user);
  4121. } else {
  4122. return 0;
  4123. }
  4124. return 1;
  4125. }
  4126. static char *mg_fgets(char *buf, size_t size, struct file *filep, char **p)
  4127. {
  4128. char *eof;
  4129. size_t len;
  4130. char *memend;
  4131. if (!filep) {
  4132. return NULL;
  4133. }
  4134. if (filep->membuf != NULL && *p != NULL) {
  4135. memend = (char *)&filep->membuf[filep->size];
  4136. /* Search for \n from p till the end of stream */
  4137. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  4138. if (eof != NULL) {
  4139. eof += 1; /* Include \n */
  4140. } else {
  4141. eof = memend; /* Copy remaining data */
  4142. }
  4143. len = (size_t)(eof - *p) > size - 1 ? size - 1 : (size_t)(eof - *p);
  4144. memcpy(buf, *p, len);
  4145. buf[len] = '\0';
  4146. *p += len;
  4147. return len ? eof : NULL;
  4148. } else if (filep->fp != NULL) {
  4149. return fgets(buf, (int)size, filep->fp);
  4150. } else {
  4151. return NULL;
  4152. }
  4153. }
  4154. struct read_auth_file_struct {
  4155. struct mg_connection *conn;
  4156. struct ah ah;
  4157. char *domain;
  4158. char buf[256 + 256 + 40];
  4159. char *f_user;
  4160. char *f_domain;
  4161. char *f_ha1;
  4162. };
  4163. static int read_auth_file(struct file *filep,
  4164. struct read_auth_file_struct *workdata)
  4165. {
  4166. char *p;
  4167. int is_authorized = 0;
  4168. struct file fp;
  4169. size_t l;
  4170. if (!filep || !workdata) {
  4171. return 0;
  4172. }
  4173. /* Loop over passwords file */
  4174. p = (char *)filep->membuf;
  4175. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  4176. l = strlen(workdata->buf);
  4177. while (l > 0) {
  4178. if (isspace(workdata->buf[l - 1]) ||
  4179. iscntrl(workdata->buf[l - 1])) {
  4180. l--;
  4181. workdata->buf[l] = 0;
  4182. } else
  4183. break;
  4184. }
  4185. if (l < 1) {
  4186. continue;
  4187. }
  4188. workdata->f_user = workdata->buf;
  4189. if (workdata->f_user[0] == ':') {
  4190. /* user names may not contain a ':' and may not be empty,
  4191. * so lines starting with ':' may be used for a special purpose */
  4192. if (workdata->f_user[1] == '#') {
  4193. /* :# is a comment */
  4194. continue;
  4195. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  4196. if (mg_fopen(workdata->conn, workdata->f_user + 9, "r", &fp)) {
  4197. is_authorized = read_auth_file(&fp, workdata);
  4198. mg_fclose(&fp);
  4199. } else {
  4200. mg_cry(workdata->conn,
  4201. "%s: cannot open authorization file: %s",
  4202. __func__,
  4203. workdata->buf);
  4204. }
  4205. continue;
  4206. }
  4207. /* everything is invalid for the moment (might change in the
  4208. * future) */
  4209. mg_cry(workdata->conn,
  4210. "%s: syntax error in authorization file: %s",
  4211. __func__,
  4212. workdata->buf);
  4213. continue;
  4214. }
  4215. workdata->f_domain = strchr(workdata->f_user, ':');
  4216. if (workdata->f_domain == NULL) {
  4217. mg_cry(workdata->conn,
  4218. "%s: syntax error in authorization file: %s",
  4219. __func__,
  4220. workdata->buf);
  4221. continue;
  4222. }
  4223. *(workdata->f_domain) = 0;
  4224. (workdata->f_domain)++;
  4225. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  4226. if (workdata->f_ha1 == NULL) {
  4227. mg_cry(workdata->conn,
  4228. "%s: syntax error in authorization file: %s",
  4229. __func__,
  4230. workdata->buf);
  4231. continue;
  4232. }
  4233. *(workdata->f_ha1) = 0;
  4234. (workdata->f_ha1)++;
  4235. if (!strcmp(workdata->ah.user, workdata->f_user) &&
  4236. !strcmp(workdata->domain, workdata->f_domain)) {
  4237. return check_password(workdata->conn->request_info.request_method,
  4238. workdata->f_ha1,
  4239. workdata->ah.uri,
  4240. workdata->ah.nonce,
  4241. workdata->ah.nc,
  4242. workdata->ah.cnonce,
  4243. workdata->ah.qop,
  4244. workdata->ah.response);
  4245. }
  4246. }
  4247. return is_authorized;
  4248. }
  4249. /* Authorize against the opened passwords file. Return 1 if authorized. */
  4250. static int authorize(struct mg_connection *conn, struct file *filep)
  4251. {
  4252. struct read_auth_file_struct workdata;
  4253. char buf[MG_BUF_LEN];
  4254. if (!conn || !conn->ctx) {
  4255. return 0;
  4256. }
  4257. memset(&workdata, 0, sizeof(workdata));
  4258. workdata.conn = conn;
  4259. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  4260. return 0;
  4261. }
  4262. workdata.domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  4263. return read_auth_file(filep, &workdata);
  4264. }
  4265. /* Return 1 if request is authorised, 0 otherwise. */
  4266. static int check_authorization(struct mg_connection *conn, const char *path)
  4267. {
  4268. char fname[PATH_MAX];
  4269. struct vec uri_vec, filename_vec;
  4270. const char *list;
  4271. struct file file = STRUCT_FILE_INITIALIZER;
  4272. int authorized = 1, truncated;
  4273. if (!conn || !conn->ctx) {
  4274. return 0;
  4275. }
  4276. list = conn->ctx->config[PROTECT_URI];
  4277. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  4278. if (!memcmp(conn->request_info.rel_uri, uri_vec.ptr, uri_vec.len)) {
  4279. mg_snprintf(conn,
  4280. &truncated,
  4281. fname,
  4282. sizeof(fname),
  4283. "%.*s",
  4284. (int)filename_vec.len,
  4285. filename_vec.ptr);
  4286. if (truncated || !mg_fopen(conn, fname, "r", &file)) {
  4287. mg_cry(conn,
  4288. "%s: cannot open %s: %s",
  4289. __func__,
  4290. fname,
  4291. strerror(errno));
  4292. }
  4293. break;
  4294. }
  4295. }
  4296. if (!is_file_opened(&file)) {
  4297. open_auth_file(conn, path, &file);
  4298. }
  4299. if (is_file_opened(&file)) {
  4300. authorized = authorize(conn, &file);
  4301. mg_fclose(&file);
  4302. }
  4303. return authorized;
  4304. }
  4305. static void send_authorization_request(struct mg_connection *conn)
  4306. {
  4307. char date[64];
  4308. time_t curtime = time(NULL);
  4309. if (conn && conn->ctx) {
  4310. unsigned long nonce = (unsigned long)(conn->ctx->start_time);
  4311. (void)pthread_mutex_lock(&conn->ctx->nonce_mutex);
  4312. nonce += conn->ctx->nonce_count;
  4313. ++conn->ctx->nonce_count;
  4314. (void)pthread_mutex_unlock(&conn->ctx->nonce_mutex);
  4315. nonce ^= (uintptr_t)(conn->ctx);
  4316. conn->status_code = 401;
  4317. conn->must_close = 1;
  4318. gmt_time_string(date, sizeof(date), &curtime);
  4319. mg_printf(conn,
  4320. "HTTP/1.1 401 Unauthorized\r\n"
  4321. "Date: %s\r\n"
  4322. "Connection: %s\r\n"
  4323. "Content-Length: 0\r\n"
  4324. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  4325. "nonce=\"%lu\"\r\n\r\n",
  4326. date,
  4327. suggest_connection_header(conn),
  4328. conn->ctx->config[AUTHENTICATION_DOMAIN],
  4329. nonce);
  4330. }
  4331. }
  4332. #if !defined(NO_FILES)
  4333. static int is_authorized_for_put(struct mg_connection *conn)
  4334. {
  4335. if (conn) {
  4336. struct file file = STRUCT_FILE_INITIALIZER;
  4337. const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
  4338. int ret = 0;
  4339. if (passfile != NULL && mg_fopen(conn, passfile, "r", &file)) {
  4340. ret = authorize(conn, &file);
  4341. mg_fclose(&file);
  4342. }
  4343. return ret;
  4344. }
  4345. return 0;
  4346. }
  4347. #endif
  4348. int mg_modify_passwords_file(const char *fname,
  4349. const char *domain,
  4350. const char *user,
  4351. const char *pass)
  4352. {
  4353. int found, i;
  4354. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  4355. FILE *fp, *fp2;
  4356. found = 0;
  4357. fp = fp2 = NULL;
  4358. /* Regard empty password as no password - remove user record. */
  4359. if (pass != NULL && pass[0] == '\0') {
  4360. pass = NULL;
  4361. }
  4362. /* Other arguments must not be empty */
  4363. if (fname == NULL || domain == NULL || user == NULL) {
  4364. return 0;
  4365. }
  4366. /* Using the given file format, user name and domain must not contain ':'
  4367. */
  4368. if (strchr(user, ':') != NULL) {
  4369. return 0;
  4370. }
  4371. if (strchr(domain, ':') != NULL) {
  4372. return 0;
  4373. }
  4374. /* Do not allow control characters like newline in user name and domain.
  4375. * Do not allow excessively long names either. */
  4376. for (i = 0; i < 255 && user[i] != 0; i++) {
  4377. if (iscntrl(user[i])) {
  4378. return 0;
  4379. }
  4380. }
  4381. if (user[i]) {
  4382. return 0;
  4383. }
  4384. for (i = 0; i < 255 && domain[i] != 0; i++) {
  4385. if (iscntrl(domain[i])) {
  4386. return 0;
  4387. }
  4388. }
  4389. if (domain[i]) {
  4390. return 0;
  4391. }
  4392. /* The maximum length of the path to the password file is limited */
  4393. if ((strlen(fname) + 4) >= PATH_MAX) {
  4394. return 0;
  4395. }
  4396. /* Create a temporary file name. Length has been checked before. */
  4397. strcpy(tmp, fname);
  4398. strcat(tmp, ".tmp");
  4399. /* Create the file if does not exist */
  4400. if ((fp = fopen(fname, "a+")) != NULL) {
  4401. (void)fclose(fp);
  4402. }
  4403. /* Open the given file and temporary file */
  4404. if ((fp = fopen(fname, "r")) == NULL) {
  4405. return 0;
  4406. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  4407. fclose(fp);
  4408. return 0;
  4409. }
  4410. /* Copy the stuff to temporary file */
  4411. while (fgets(line, sizeof(line), fp) != NULL) {
  4412. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  4413. continue;
  4414. }
  4415. u[255] = 0;
  4416. d[255] = 0;
  4417. if (!strcmp(u, user) && !strcmp(d, domain)) {
  4418. found++;
  4419. if (pass != NULL) {
  4420. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  4421. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  4422. }
  4423. } else {
  4424. fprintf(fp2, "%s", line);
  4425. }
  4426. }
  4427. /* If new user, just add it */
  4428. if (!found && pass != NULL) {
  4429. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  4430. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  4431. }
  4432. /* Close files */
  4433. fclose(fp);
  4434. fclose(fp2);
  4435. /* Put the temp file in place of real file */
  4436. IGNORE_UNUSED_RESULT(remove(fname));
  4437. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  4438. return 1;
  4439. }
  4440. static int is_valid_port(unsigned long port)
  4441. {
  4442. return port < 0xffff;
  4443. }
  4444. static int mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  4445. {
  4446. struct addrinfo hints, *res, *ressave;
  4447. int ret = 0;
  4448. memset(&hints, 0, sizeof(struct addrinfo));
  4449. hints.ai_family = af;
  4450. if (getaddrinfo(src, NULL, &hints, &res) != 0) {
  4451. /* bad src string or bad address family */
  4452. return 0;
  4453. }
  4454. ressave = res;
  4455. while (res) {
  4456. if (dstlen >= res->ai_addrlen) {
  4457. memcpy(dst, res->ai_addr, res->ai_addrlen);
  4458. ret = 1;
  4459. }
  4460. res = res->ai_next;
  4461. }
  4462. freeaddrinfo(ressave);
  4463. return ret;
  4464. }
  4465. static int
  4466. connect_socket(struct mg_context *ctx /* may be NULL */,
  4467. const char *host,
  4468. int port,
  4469. int use_ssl,
  4470. char *ebuf,
  4471. size_t ebuf_len,
  4472. SOCKET *sock /* output: socket, must not be NULL */,
  4473. union usa *sa /* output: socket address, must not be NULL */
  4474. )
  4475. {
  4476. int ip_ver = 0;
  4477. *sock = INVALID_SOCKET;
  4478. memset(sa, 0, sizeof(*sa));
  4479. if (ebuf_len > 0) {
  4480. *ebuf = 0;
  4481. }
  4482. if (host == NULL) {
  4483. mg_snprintf(NULL,
  4484. NULL, /* No truncation check for ebuf */
  4485. ebuf,
  4486. ebuf_len,
  4487. "%s",
  4488. "NULL host");
  4489. return 0;
  4490. }
  4491. if (port < 0 || !is_valid_port((unsigned)port)) {
  4492. mg_snprintf(NULL,
  4493. NULL, /* No truncation check for ebuf */
  4494. ebuf,
  4495. ebuf_len,
  4496. "%s",
  4497. "invalid port");
  4498. return 0;
  4499. }
  4500. if (use_ssl && (SSLv23_client_method == NULL)) {
  4501. mg_snprintf(NULL,
  4502. NULL, /* No truncation check for ebuf */
  4503. ebuf,
  4504. ebuf_len,
  4505. "%s",
  4506. "SSL is not initialized");
  4507. return 0;
  4508. }
  4509. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  4510. sa->sin.sin_port = htons((uint16_t)port);
  4511. ip_ver = 4;
  4512. #ifdef USE_IPV6
  4513. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  4514. sa->sin6.sin6_port = htons((uint16_t)port);
  4515. ip_ver = 6;
  4516. } else if (host[0] == '[') {
  4517. /* While getaddrinfo on Windows will work with [::1],
  4518. * getaddrinfo on Linux only works with ::1 (without []). */
  4519. size_t l = strlen(host + 1);
  4520. char *h = l > 1 ? mg_strdup(host + 1) : NULL;
  4521. if (h) {
  4522. h[l - 1] = 0;
  4523. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  4524. sa->sin6.sin6_port = htons((uint16_t)port);
  4525. ip_ver = 6;
  4526. }
  4527. mg_free(h);
  4528. }
  4529. #endif
  4530. }
  4531. if (ip_ver == 0) {
  4532. mg_snprintf(NULL,
  4533. NULL, /* No truncation check for ebuf */
  4534. ebuf,
  4535. ebuf_len,
  4536. "%s",
  4537. "host not found");
  4538. return 0;
  4539. }
  4540. if (ip_ver == 4) {
  4541. *sock = socket(PF_INET, SOCK_STREAM, 0);
  4542. }
  4543. #ifdef USE_IPV6
  4544. else if (ip_ver == 6) {
  4545. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  4546. }
  4547. #endif
  4548. if (*sock == INVALID_SOCKET) {
  4549. mg_snprintf(NULL,
  4550. NULL, /* No truncation check for ebuf */
  4551. ebuf,
  4552. ebuf_len,
  4553. "socket(): %s",
  4554. strerror(ERRNO));
  4555. return 0;
  4556. }
  4557. set_close_on_exec(*sock, fc(ctx));
  4558. if ((ip_ver == 4) &&
  4559. (connect(*sock, (struct sockaddr *)&sa->sin, sizeof(sa->sin)) == 0)) {
  4560. /* connected with IPv4 */
  4561. return 1;
  4562. }
  4563. #ifdef USE_IPV6
  4564. if ((ip_ver == 6) &&
  4565. (connect(*sock, (struct sockaddr *)&sa->sin6, sizeof(sa->sin6)) == 0)) {
  4566. /* connected with IPv6 */
  4567. return 1;
  4568. }
  4569. #endif
  4570. /* Not connected */
  4571. mg_snprintf(NULL,
  4572. NULL, /* No truncation check for ebuf */
  4573. ebuf,
  4574. ebuf_len,
  4575. "connect(%s:%d): %s",
  4576. host,
  4577. port,
  4578. strerror(ERRNO));
  4579. closesocket(*sock);
  4580. *sock = INVALID_SOCKET;
  4581. return 0;
  4582. }
  4583. int mg_url_encode(const char *src, char *dst, size_t dst_len)
  4584. {
  4585. static const char *dont_escape = "._-$,;~()";
  4586. static const char *hex = "0123456789abcdef";
  4587. char *pos = dst;
  4588. const char *end = dst + dst_len - 1;
  4589. for (; *src != '\0' && pos < end; src++, pos++) {
  4590. if (isalnum(*(const unsigned char *)src) ||
  4591. strchr(dont_escape, *(const unsigned char *)src) != NULL) {
  4592. *pos = *src;
  4593. } else if (pos + 2 < end) {
  4594. pos[0] = '%';
  4595. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  4596. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  4597. pos += 2;
  4598. } else {
  4599. break;
  4600. }
  4601. }
  4602. *pos = '\0';
  4603. return (*src == '\0') ? (int)(pos - dst) : -1;
  4604. }
  4605. static void print_dir_entry(struct de *de)
  4606. {
  4607. char size[64], mod[64], href[PATH_MAX];
  4608. struct tm *tm;
  4609. if (de->file.is_directory) {
  4610. mg_snprintf(de->conn,
  4611. NULL, /* Buffer is big enough */
  4612. size,
  4613. sizeof(size),
  4614. "%s",
  4615. "[DIRECTORY]");
  4616. } else {
  4617. /* We use (signed) cast below because MSVC 6 compiler cannot
  4618. * convert unsigned __int64 to double. Sigh. */
  4619. if (de->file.size < 1024) {
  4620. mg_snprintf(de->conn,
  4621. NULL, /* Buffer is big enough */
  4622. size,
  4623. sizeof(size),
  4624. "%d",
  4625. (int)de->file.size);
  4626. } else if (de->file.size < 0x100000) {
  4627. mg_snprintf(de->conn,
  4628. NULL, /* Buffer is big enough */
  4629. size,
  4630. sizeof(size),
  4631. "%.1fk",
  4632. (double)de->file.size / 1024.0);
  4633. } else if (de->file.size < 0x40000000) {
  4634. mg_snprintf(de->conn,
  4635. NULL, /* Buffer is big enough */
  4636. size,
  4637. sizeof(size),
  4638. "%.1fM",
  4639. (double)de->file.size / 1048576);
  4640. } else {
  4641. mg_snprintf(de->conn,
  4642. NULL, /* Buffer is big enough */
  4643. size,
  4644. sizeof(size),
  4645. "%.1fG",
  4646. (double)de->file.size / 1073741824);
  4647. }
  4648. }
  4649. /* Note: mg_snprintf will not cause a buffer overflow above.
  4650. * So, string truncation checks are not required here. */
  4651. tm = localtime(&de->file.last_modified);
  4652. if (tm != NULL) {
  4653. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  4654. } else {
  4655. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  4656. mod[sizeof(mod) - 1] = '\0';
  4657. }
  4658. mg_url_encode(de->file_name, href, sizeof(href));
  4659. de->conn->num_bytes_sent +=
  4660. mg_printf(de->conn,
  4661. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  4662. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  4663. de->conn->request_info.rel_uri,
  4664. href,
  4665. de->file.is_directory ? "/" : "",
  4666. de->file_name,
  4667. de->file.is_directory ? "/" : "",
  4668. mod,
  4669. size);
  4670. }
  4671. /* This function is called from send_directory() and used for
  4672. * sorting directory entries by size, or name, or modification time.
  4673. * On windows, __cdecl specification is needed in case if project is built
  4674. * with __stdcall convention. qsort always requires __cdels callback. */
  4675. static int WINCDECL compare_dir_entries(const void *p1, const void *p2)
  4676. {
  4677. if (p1 && p2) {
  4678. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  4679. const char *query_string = a->conn->request_info.query_string;
  4680. int cmp_result = 0;
  4681. if (query_string == NULL) {
  4682. query_string = "na";
  4683. }
  4684. if (a->file.is_directory && !b->file.is_directory) {
  4685. return -1; /* Always put directories on top */
  4686. } else if (!a->file.is_directory && b->file.is_directory) {
  4687. return 1; /* Always put directories on top */
  4688. } else if (*query_string == 'n') {
  4689. cmp_result = strcmp(a->file_name, b->file_name);
  4690. } else if (*query_string == 's') {
  4691. cmp_result = a->file.size == b->file.size
  4692. ? 0
  4693. : a->file.size > b->file.size ? 1 : -1;
  4694. } else if (*query_string == 'd') {
  4695. cmp_result =
  4696. (a->file.last_modified == b->file.last_modified)
  4697. ? 0
  4698. : ((a->file.last_modified > b->file.last_modified) ? 1
  4699. : -1);
  4700. }
  4701. return query_string[1] == 'd' ? -cmp_result : cmp_result;
  4702. }
  4703. return 0;
  4704. }
  4705. static int must_hide_file(struct mg_connection *conn, const char *path)
  4706. {
  4707. if (conn && conn->ctx) {
  4708. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  4709. const char *pattern = conn->ctx->config[HIDE_FILES];
  4710. return match_prefix(pw_pattern, strlen(pw_pattern), path) > 0 ||
  4711. (pattern != NULL &&
  4712. match_prefix(pattern, strlen(pattern), path) > 0);
  4713. }
  4714. return 0;
  4715. }
  4716. static int scan_directory(struct mg_connection *conn,
  4717. const char *dir,
  4718. void *data,
  4719. void (*cb)(struct de *, void *))
  4720. {
  4721. char path[PATH_MAX];
  4722. struct dirent *dp;
  4723. DIR *dirp;
  4724. struct de de;
  4725. int truncated;
  4726. if ((dirp = opendir(dir)) == NULL) {
  4727. return 0;
  4728. } else {
  4729. de.conn = conn;
  4730. while ((dp = readdir(dirp)) != NULL) {
  4731. /* Do not show current dir and hidden files */
  4732. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..") ||
  4733. must_hide_file(conn, dp->d_name)) {
  4734. continue;
  4735. }
  4736. mg_snprintf(
  4737. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  4738. /* If we don't memset stat structure to zero, mtime will have
  4739. * garbage and strftime() will segfault later on in
  4740. * print_dir_entry(). memset is required only if mg_stat()
  4741. * fails. For more details, see
  4742. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  4743. memset(&de.file, 0, sizeof(de.file));
  4744. if (truncated) {
  4745. /* If the path is not complete, skip processing. */
  4746. continue;
  4747. }
  4748. if (!mg_stat(conn, path, &de.file)) {
  4749. mg_cry(conn,
  4750. "%s: mg_stat(%s) failed: %s",
  4751. __func__,
  4752. path,
  4753. strerror(ERRNO));
  4754. }
  4755. de.file_name = dp->d_name;
  4756. cb(&de, data);
  4757. }
  4758. (void)closedir(dirp);
  4759. }
  4760. return 1;
  4761. }
  4762. #if !defined(NO_FILES)
  4763. static int remove_directory(struct mg_connection *conn, const char *dir)
  4764. {
  4765. char path[PATH_MAX];
  4766. struct dirent *dp;
  4767. DIR *dirp;
  4768. struct de de;
  4769. int truncated;
  4770. int ok = 1;
  4771. if ((dirp = opendir(dir)) == NULL) {
  4772. return 0;
  4773. } else {
  4774. de.conn = conn;
  4775. while ((dp = readdir(dirp)) != NULL) {
  4776. /* Do not show current dir (but show hidden files as they will
  4777. * also be removed) */
  4778. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  4779. continue;
  4780. }
  4781. mg_snprintf(
  4782. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  4783. /* If we don't memset stat structure to zero, mtime will have
  4784. * garbage and strftime() will segfault later on in
  4785. * print_dir_entry(). memset is required only if mg_stat()
  4786. * fails. For more details, see
  4787. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  4788. memset(&de.file, 0, sizeof(de.file));
  4789. if (truncated) {
  4790. /* Do not delete anything shorter */
  4791. continue;
  4792. }
  4793. if (!mg_stat(conn, path, &de.file)) {
  4794. mg_cry(conn,
  4795. "%s: mg_stat(%s) failed: %s",
  4796. __func__,
  4797. path,
  4798. strerror(ERRNO));
  4799. }
  4800. if (de.file.membuf == NULL) {
  4801. /* file is not in memory */
  4802. if (de.file.is_directory) {
  4803. if (remove_directory(conn, path) == 0) {
  4804. ok = 0;
  4805. }
  4806. } else {
  4807. if (mg_remove(path) == 0) {
  4808. ok = 0;
  4809. }
  4810. }
  4811. }
  4812. }
  4813. (void)closedir(dirp);
  4814. IGNORE_UNUSED_RESULT(rmdir(dir));
  4815. }
  4816. return ok;
  4817. }
  4818. #endif
  4819. struct dir_scan_data {
  4820. struct de *entries;
  4821. unsigned int num_entries;
  4822. unsigned int arr_size;
  4823. };
  4824. /* Behaves like realloc(), but frees original pointer on failure */
  4825. static void *realloc2(void *ptr, size_t size)
  4826. {
  4827. void *new_ptr = mg_realloc(ptr, size);
  4828. if (new_ptr == NULL) {
  4829. mg_free(ptr);
  4830. }
  4831. return new_ptr;
  4832. }
  4833. static void dir_scan_callback(struct de *de, void *data)
  4834. {
  4835. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  4836. if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {
  4837. dsd->arr_size *= 2;
  4838. dsd->entries = (struct de *)realloc2(
  4839. dsd->entries, dsd->arr_size * sizeof(dsd->entries[0]));
  4840. }
  4841. if (dsd->entries == NULL) {
  4842. /* TODO(lsm, low): propagate an error to the caller */
  4843. dsd->num_entries = 0;
  4844. } else {
  4845. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  4846. dsd->entries[dsd->num_entries].file = de->file;
  4847. dsd->entries[dsd->num_entries].conn = de->conn;
  4848. dsd->num_entries++;
  4849. }
  4850. }
  4851. static void handle_directory_request(struct mg_connection *conn,
  4852. const char *dir)
  4853. {
  4854. unsigned int i;
  4855. int sort_direction;
  4856. struct dir_scan_data data = {NULL, 0, 128};
  4857. char date[64];
  4858. time_t curtime = time(NULL);
  4859. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  4860. send_http_error(conn,
  4861. 500,
  4862. "Error: Cannot open directory\nopendir(%s): %s",
  4863. dir,
  4864. strerror(ERRNO));
  4865. return;
  4866. }
  4867. gmt_time_string(date, sizeof(date), &curtime);
  4868. if (!conn) {
  4869. return;
  4870. }
  4871. sort_direction = conn->request_info.query_string != NULL &&
  4872. conn->request_info.query_string[1] == 'd'
  4873. ? 'a'
  4874. : 'd';
  4875. conn->must_close = 1;
  4876. mg_printf(conn,
  4877. "HTTP/1.1 200 OK\r\n"
  4878. "Date: %s\r\n"
  4879. "Connection: close\r\n"
  4880. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  4881. date);
  4882. conn->num_bytes_sent +=
  4883. mg_printf(conn,
  4884. "<html><head><title>Index of %s</title>"
  4885. "<style>th {text-align: left;}</style></head>"
  4886. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  4887. "<tr><th><a href=\"?n%c\">Name</a></th>"
  4888. "<th><a href=\"?d%c\">Modified</a></th>"
  4889. "<th><a href=\"?s%c\">Size</a></th></tr>"
  4890. "<tr><td colspan=\"3\"><hr></td></tr>",
  4891. conn->request_info.rel_uri,
  4892. conn->request_info.rel_uri,
  4893. sort_direction,
  4894. sort_direction,
  4895. sort_direction);
  4896. /* Print first entry - link to a parent directory */
  4897. conn->num_bytes_sent +=
  4898. mg_printf(conn,
  4899. "<tr><td><a href=\"%s%s\">%s</a></td>"
  4900. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  4901. conn->request_info.rel_uri,
  4902. "..",
  4903. "Parent directory",
  4904. "-",
  4905. "-");
  4906. /* Sort and print directory entries */
  4907. if (data.entries != NULL) {
  4908. qsort(data.entries,
  4909. (size_t)data.num_entries,
  4910. sizeof(data.entries[0]),
  4911. compare_dir_entries);
  4912. for (i = 0; i < data.num_entries; i++) {
  4913. print_dir_entry(&data.entries[i]);
  4914. mg_free(data.entries[i].file_name);
  4915. }
  4916. mg_free(data.entries);
  4917. }
  4918. conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");
  4919. conn->status_code = 200;
  4920. }
  4921. /* Send len bytes from the opened file to the client. */
  4922. static void send_file_data(struct mg_connection *conn,
  4923. struct file *filep,
  4924. int64_t offset,
  4925. int64_t len)
  4926. {
  4927. char buf[MG_BUF_LEN];
  4928. int to_read, num_read, num_written;
  4929. int64_t size;
  4930. if (!filep || !conn) {
  4931. return;
  4932. }
  4933. /* Sanity check the offset */
  4934. size = filep->size > INT64_MAX ? INT64_MAX : (int64_t)(filep->size);
  4935. offset = offset < 0 ? 0 : offset > size ? size : offset;
  4936. if (len > 0 && filep->membuf != NULL && size > 0) {
  4937. /* file stored in memory */
  4938. if (len > size - offset) {
  4939. len = size - offset;
  4940. }
  4941. mg_write(conn, filep->membuf + offset, (size_t)len);
  4942. } else if (len > 0 && filep->fp != NULL) {
  4943. /* file stored on disk */
  4944. #if defined(__linux__)
  4945. /* sendfile is only available for Linux */
  4946. if (conn->throttle == 0 && conn->ssl == 0) {
  4947. off_t sf_offs = (off_t)offset;
  4948. ssize_t sf_sent;
  4949. int sf_file = fileno(filep->fp);
  4950. int loop_cnt = 0;
  4951. do {
  4952. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  4953. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  4954. size_t sf_tosend =
  4955. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  4956. sf_sent =
  4957. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  4958. if (sf_sent > 0) {
  4959. conn->num_bytes_sent += sf_sent;
  4960. len -= sf_sent;
  4961. offset += sf_sent;
  4962. } else if (loop_cnt == 0) {
  4963. /* This file can not be sent using sendfile.
  4964. * This might be the case for pseudo-files in the
  4965. * /sys/ and /proc/ file system.
  4966. * Use the regular user mode copy code instead. */
  4967. break;
  4968. } else if (sf_sent == 0) {
  4969. /* No error, but 0 bytes sent. May be EOF? */
  4970. return;
  4971. }
  4972. loop_cnt++;
  4973. } while ((len > 0) && (sf_sent >= 0));
  4974. if (sf_sent > 0) {
  4975. return; /* OK */
  4976. }
  4977. /* sf_sent<0 means error, thus fall back to the classic way */
  4978. /* This is always the case, if sf_file is not a "normal" file,
  4979. * e.g., for sending data from the output of a CGI process. */
  4980. offset = (int64_t)sf_offs;
  4981. }
  4982. #endif
  4983. if ((offset > 0) && (fseeko(filep->fp, offset, SEEK_SET) != 0)) {
  4984. mg_cry(conn, "%s: fseeko() failed: %s", __func__, strerror(ERRNO));
  4985. send_http_error(
  4986. conn,
  4987. 500,
  4988. "%s",
  4989. "Error: Unable to access file at requested position.");
  4990. } else {
  4991. while (len > 0) {
  4992. /* Calculate how much to read from the file in the buffer */
  4993. to_read = sizeof(buf);
  4994. if ((int64_t)to_read > len) {
  4995. to_read = (int)len;
  4996. }
  4997. /* Read from file, exit the loop on error */
  4998. if ((num_read =
  4999. (int)fread(buf, 1, (size_t)to_read, filep->fp)) <= 0) {
  5000. break;
  5001. }
  5002. /* Send read bytes to the client, exit the loop on error */
  5003. if ((num_written = mg_write(conn, buf, (size_t)num_read)) !=
  5004. num_read) {
  5005. break;
  5006. }
  5007. /* Both read and were successful, adjust counters */
  5008. conn->num_bytes_sent += num_written;
  5009. len -= num_written;
  5010. }
  5011. }
  5012. }
  5013. }
  5014. static int parse_range_header(const char *header, int64_t *a, int64_t *b)
  5015. {
  5016. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  5017. }
  5018. static void construct_etag(char *buf, size_t buf_len, const struct file *filep)
  5019. {
  5020. if (filep != NULL && buf != NULL) {
  5021. mg_snprintf(NULL,
  5022. NULL, /* All calls to construct_etag use 64 byte buffer */
  5023. buf,
  5024. buf_len,
  5025. "\"%lx.%" INT64_FMT "\"",
  5026. (unsigned long)filep->last_modified,
  5027. filep->size);
  5028. }
  5029. }
  5030. static void fclose_on_exec(struct file *filep, struct mg_connection *conn)
  5031. {
  5032. if (filep != NULL && filep->fp != NULL) {
  5033. #ifdef _WIN32
  5034. (void)conn; /* Unused. */
  5035. #else
  5036. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  5037. mg_cry(conn,
  5038. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  5039. __func__,
  5040. strerror(ERRNO));
  5041. }
  5042. #endif
  5043. }
  5044. }
  5045. static void handle_static_file_request(struct mg_connection *conn,
  5046. const char *path,
  5047. struct file *filep)
  5048. {
  5049. char date[64], lm[64], etag[64];
  5050. char range[128]; /* large enough, so there will be no overflow */
  5051. const char *msg = "OK", *hdr;
  5052. time_t curtime = time(NULL);
  5053. int64_t cl, r1, r2;
  5054. struct vec mime_vec;
  5055. int n, truncated;
  5056. char gz_path[PATH_MAX];
  5057. const char *encoding = "";
  5058. const char *cors1, *cors2, *cors3;
  5059. if (conn == NULL || conn->ctx == NULL || filep == NULL) {
  5060. return;
  5061. }
  5062. get_mime_type(conn->ctx, path, &mime_vec);
  5063. if (filep->size > INT64_MAX) {
  5064. send_http_error(conn,
  5065. 500,
  5066. "Error: File size is too large to send\n%" INT64_FMT,
  5067. filep->size);
  5068. }
  5069. cl = (int64_t)filep->size;
  5070. conn->status_code = 200;
  5071. range[0] = '\0';
  5072. /* if this file is in fact a pre-gzipped file, rewrite its filename
  5073. * it's important to rewrite the filename after resolving
  5074. * the mime type from it, to preserve the actual file's type */
  5075. if (filep->gzipped) {
  5076. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  5077. if (truncated) {
  5078. send_http_error(
  5079. conn, 500, "Error: Path of zipped file too long (%s)", path);
  5080. return;
  5081. }
  5082. path = gz_path;
  5083. encoding = "Content-Encoding: gzip\r\n";
  5084. }
  5085. if (!mg_fopen(conn, path, "rb", filep)) {
  5086. send_http_error(conn,
  5087. 500,
  5088. "Error: Cannot open file\nfopen(%s): %s",
  5089. path,
  5090. strerror(ERRNO));
  5091. return;
  5092. }
  5093. fclose_on_exec(filep, conn);
  5094. /* If Range: header specified, act accordingly */
  5095. r1 = r2 = 0;
  5096. hdr = mg_get_header(conn, "Range");
  5097. if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 && r1 >= 0 &&
  5098. r2 >= 0) {
  5099. /* actually, range requests don't play well with a pre-gzipped
  5100. * file (since the range is specified in the uncompressed space) */
  5101. if (filep->gzipped) {
  5102. send_http_error(
  5103. conn,
  5104. 501,
  5105. "%s",
  5106. "Error: Range requests in gzipped files are not supported");
  5107. mg_fclose(filep);
  5108. return;
  5109. }
  5110. conn->status_code = 206;
  5111. cl = n == 2 ? (r2 > cl ? cl : r2) - r1 + 1 : cl - r1;
  5112. mg_snprintf(conn,
  5113. NULL, /* range buffer is big enough */
  5114. range,
  5115. sizeof(range),
  5116. "Content-Range: bytes "
  5117. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  5118. r1,
  5119. r1 + cl - 1,
  5120. filep->size);
  5121. msg = "Partial Content";
  5122. }
  5123. hdr = mg_get_header(conn, "Origin");
  5124. if (hdr) {
  5125. /* Cross-origin resource sharing (CORS), see
  5126. * http://www.html5rocks.com/en/tutorials/cors/,
  5127. * http://www.html5rocks.com/static/images/cors_server_flowchart.png -
  5128. * preflight is not supported for files. */
  5129. cors1 = "Access-Control-Allow-Origin: ";
  5130. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  5131. cors3 = "\r\n";
  5132. } else {
  5133. cors1 = cors2 = cors3 = "";
  5134. }
  5135. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
  5136. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  5137. gmt_time_string(date, sizeof(date), &curtime);
  5138. gmt_time_string(lm, sizeof(lm), &filep->last_modified);
  5139. construct_etag(etag, sizeof(etag), filep);
  5140. (void)mg_printf(conn,
  5141. "HTTP/1.1 %d %s\r\n"
  5142. "%s%s%s"
  5143. "Date: %s\r\n"
  5144. "Last-Modified: %s\r\n"
  5145. "Etag: %s\r\n"
  5146. "Content-Type: %.*s\r\n"
  5147. "Content-Length: %" INT64_FMT "\r\n"
  5148. "Connection: %s\r\n"
  5149. "Accept-Ranges: bytes\r\n"
  5150. "%s%s\r\n",
  5151. conn->status_code,
  5152. msg,
  5153. cors1,
  5154. cors2,
  5155. cors3,
  5156. date,
  5157. lm,
  5158. etag,
  5159. (int)mime_vec.len,
  5160. mime_vec.ptr,
  5161. cl,
  5162. suggest_connection_header(conn),
  5163. range,
  5164. encoding);
  5165. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  5166. send_file_data(conn, filep, r1, cl);
  5167. }
  5168. mg_fclose(filep);
  5169. }
  5170. void mg_send_file(struct mg_connection *conn, const char *path)
  5171. {
  5172. struct file file = STRUCT_FILE_INITIALIZER;
  5173. if (mg_stat(conn, path, &file)) {
  5174. if (file.is_directory) {
  5175. if (!conn) {
  5176. return;
  5177. }
  5178. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  5179. "yes")) {
  5180. handle_directory_request(conn, path);
  5181. } else {
  5182. send_http_error(
  5183. conn, 403, "%s", "Error: Directory listing denied");
  5184. }
  5185. } else {
  5186. handle_static_file_request(conn, path, &file);
  5187. }
  5188. } else {
  5189. send_http_error(conn, 404, "%s", "Error: File not found");
  5190. }
  5191. }
  5192. /* Parse HTTP headers from the given buffer, advance buffer to the point
  5193. * where parsing stopped. */
  5194. static void parse_http_headers(char **buf, struct mg_request_info *ri)
  5195. {
  5196. int i;
  5197. if (!ri) {
  5198. return;
  5199. }
  5200. ri->num_headers = 0;
  5201. for (i = 0; i < (int)ARRAY_SIZE(ri->http_headers); i++) {
  5202. ri->http_headers[i].name = skip_quoted(buf, ":", " ", 0);
  5203. ri->http_headers[i].value = skip(buf, "\r\n");
  5204. if (ri->http_headers[i].name[0] == '\0') {
  5205. break;
  5206. }
  5207. ri->num_headers = i + 1;
  5208. }
  5209. }
  5210. static int is_valid_http_method(const char *method)
  5211. {
  5212. return !strcmp(method, "GET") || !strcmp(method, "POST") ||
  5213. !strcmp(method, "HEAD") || !strcmp(method, "CONNECT") ||
  5214. !strcmp(method, "PUT") || !strcmp(method, "DELETE") ||
  5215. !strcmp(method, "OPTIONS") || !strcmp(method, "PROPFIND") ||
  5216. !strcmp(method, "MKCOL") || !strcmp(method, "PATCH");
  5217. /* TRACE method is not supported for security reasons */
  5218. /* PATCH method (RFC 5789) only allowed for CGI/Lua/LSP and callbacks. */
  5219. }
  5220. /* Parse HTTP request, fill in mg_request_info structure.
  5221. * This function modifies the buffer by NUL-terminating
  5222. * HTTP request components, header names and header values. */
  5223. static int parse_http_message(char *buf, int len, struct mg_request_info *ri)
  5224. {
  5225. int is_request, request_length;
  5226. if (!ri) {
  5227. return 0;
  5228. }
  5229. request_length = get_request_len(buf, len);
  5230. if (request_length > 0) {
  5231. /* Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_addr,
  5232. * remote_port */
  5233. ri->remote_user = ri->request_method = ri->request_uri =
  5234. ri->http_version = NULL;
  5235. ri->num_headers = 0;
  5236. buf[request_length - 1] = '\0';
  5237. /* RFC says that all initial whitespaces should be ingored */
  5238. while (*buf != '\0' && isspace(*(unsigned char *)buf)) {
  5239. buf++;
  5240. }
  5241. ri->request_method = skip(&buf, " ");
  5242. ri->request_uri = skip(&buf, " ");
  5243. ri->http_version = skip(&buf, "\r\n");
  5244. /* HTTP message could be either HTTP request or HTTP response, e.g.
  5245. * "GET / HTTP/1.0 ...." or "HTTP/1.0 200 OK ..." */
  5246. is_request = is_valid_http_method(ri->request_method);
  5247. if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0) ||
  5248. (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
  5249. request_length = -1;
  5250. } else {
  5251. if (is_request) {
  5252. ri->http_version += 5;
  5253. }
  5254. parse_http_headers(&buf, ri);
  5255. }
  5256. }
  5257. return request_length;
  5258. }
  5259. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  5260. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  5261. * buffer (which marks the end of HTTP request). Buffer buf may already
  5262. * have some data. The length of the data is stored in nread.
  5263. * Upon every read operation, increase nread by the number of bytes read. */
  5264. static int read_request(FILE *fp,
  5265. struct mg_connection *conn,
  5266. char *buf,
  5267. int bufsiz,
  5268. int *nread)
  5269. {
  5270. int request_len, n = 0;
  5271. struct timespec last_action_time = {0, 0};
  5272. double request_timeout;
  5273. if (!conn) {
  5274. return 0;
  5275. }
  5276. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  5277. /* value of request_timeout is in seconds, config in milliseconds */
  5278. request_timeout = atof(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5279. } else {
  5280. request_timeout = -1.0;
  5281. }
  5282. request_len = get_request_len(buf, *nread);
  5283. while (
  5284. (conn->ctx->stop_flag == 0) && (*nread < bufsiz) &&
  5285. (request_len == 0) &&
  5286. ((mg_difftimespec(&last_action_time, &(conn->req_time)) <=
  5287. request_timeout) ||
  5288. (request_timeout < 0)) &&
  5289. ((n = pull(fp, conn, buf + *nread, bufsiz - *nread, request_timeout)) >
  5290. 0)) {
  5291. *nread += n;
  5292. /* assert(*nread <= bufsiz); */
  5293. if (*nread > bufsiz) {
  5294. return -2;
  5295. }
  5296. request_len = get_request_len(buf, *nread);
  5297. if (request_timeout > 0.0) {
  5298. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  5299. }
  5300. }
  5301. return (request_len <= 0 && n <= 0) ? -1 : request_len;
  5302. }
  5303. #if !defined(NO_FILES)
  5304. /* For given directory path, substitute it to valid index file.
  5305. * Return 1 if index file has been found, 0 if not found.
  5306. * If the file is found, it's stats is returned in stp. */
  5307. static int substitute_index_file(struct mg_connection *conn,
  5308. char *path,
  5309. size_t path_len,
  5310. struct file *filep)
  5311. {
  5312. if (conn && conn->ctx) {
  5313. const char *list = conn->ctx->config[INDEX_FILES];
  5314. struct file file = STRUCT_FILE_INITIALIZER;
  5315. struct vec filename_vec;
  5316. size_t n = strlen(path);
  5317. int found = 0;
  5318. /* The 'path' given to us points to the directory. Remove all trailing
  5319. * directory separator characters from the end of the path, and
  5320. * then append single directory separator character. */
  5321. while (n > 0 && path[n - 1] == '/') {
  5322. n--;
  5323. }
  5324. path[n] = '/';
  5325. /* Traverse index files list. For each entry, append it to the given
  5326. * path and see if the file exists. If it exists, break the loop */
  5327. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  5328. /* Ignore too long entries that may overflow path buffer */
  5329. if (filename_vec.len > path_len - (n + 2)) {
  5330. continue;
  5331. }
  5332. /* Prepare full path to the index file */
  5333. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  5334. /* Does it exist? */
  5335. if (mg_stat(conn, path, &file)) {
  5336. /* Yes it does, break the loop */
  5337. *filep = file;
  5338. found = 1;
  5339. break;
  5340. }
  5341. }
  5342. /* If no index file exists, restore directory path */
  5343. if (!found) {
  5344. path[n] = '\0';
  5345. }
  5346. return found;
  5347. }
  5348. return 0;
  5349. }
  5350. #endif
  5351. /* Return True if we should reply 304 Not Modified. */
  5352. static int is_not_modified(const struct mg_connection *conn,
  5353. const struct file *filep)
  5354. {
  5355. char etag[64];
  5356. const char *ims = mg_get_header(conn, "If-Modified-Since");
  5357. const char *inm = mg_get_header(conn, "If-None-Match");
  5358. construct_etag(etag, sizeof(etag), filep);
  5359. if (!filep) {
  5360. return 0;
  5361. }
  5362. return (inm != NULL && !mg_strcasecmp(etag, inm)) ||
  5363. (ims != NULL && (filep->last_modified <= parse_date_string(ims)));
  5364. }
  5365. #if !defined(NO_CGI) || !defined(NO_FILES)
  5366. static int
  5367. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  5368. {
  5369. const char *expect, *body;
  5370. char buf[MG_BUF_LEN];
  5371. int to_read, nread, success = 0;
  5372. int64_t buffered_len;
  5373. double timeout = -1.0;
  5374. if (!conn) {
  5375. return 0;
  5376. }
  5377. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  5378. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5379. }
  5380. expect = mg_get_header(conn, "Expect");
  5381. /* assert(fp != NULL); */
  5382. if (!fp) {
  5383. send_http_error(conn, 500, "%s", "Error: NULL File");
  5384. return 0;
  5385. }
  5386. if (conn->content_len == -1 && !conn->is_chunked) {
  5387. /* Content length is not specified by the client. */
  5388. send_http_error(
  5389. conn, 411, "%s", "Error: Client did not specify content length");
  5390. } else if ((expect != NULL) &&
  5391. (mg_strcasecmp(expect, "100-continue") != 0)) {
  5392. /* Client sent an "Expect: xyz" header and xyz is not 100-continue. */
  5393. send_http_error(
  5394. conn, 417, "Error: Can not fulfill expectation %s", expect);
  5395. } else {
  5396. if (expect != NULL) {
  5397. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  5398. conn->status_code = 100;
  5399. } else {
  5400. conn->status_code = 200;
  5401. }
  5402. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len -
  5403. conn->consumed_content;
  5404. /* assert(buffered_len >= 0); */
  5405. /* assert(conn->consumed_content == 0); */
  5406. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  5407. send_http_error(conn, 500, "%s", "Error: Size mismatch");
  5408. return 0;
  5409. }
  5410. if (buffered_len > 0) {
  5411. if ((int64_t)buffered_len > conn->content_len) {
  5412. buffered_len = (int)conn->content_len;
  5413. }
  5414. body = conn->buf + conn->request_len + conn->consumed_content;
  5415. push_all(conn->ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  5416. conn->consumed_content += buffered_len;
  5417. }
  5418. nread = 0;
  5419. while (conn->consumed_content < conn->content_len) {
  5420. to_read = sizeof(buf);
  5421. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  5422. to_read = (int)(conn->content_len - conn->consumed_content);
  5423. }
  5424. nread = pull(NULL, conn, buf, to_read, timeout);
  5425. if (nread <= 0 ||
  5426. push_all(conn->ctx, fp, sock, ssl, buf, nread) != nread) {
  5427. break;
  5428. }
  5429. conn->consumed_content += nread;
  5430. }
  5431. if (conn->consumed_content == conn->content_len) {
  5432. success = nread >= 0;
  5433. }
  5434. /* Each error code path in this function must send an error */
  5435. if (!success) {
  5436. /* NOTE: Maybe some data has already been sent. */
  5437. /* TODO (low): If some data has been sent, a correct error
  5438. * reply can no longer be sent, so just close the connection */
  5439. send_http_error(conn, 500, "%s", "");
  5440. }
  5441. }
  5442. return success;
  5443. }
  5444. #endif
  5445. #if !defined(NO_CGI)
  5446. /* This structure helps to create an environment for the spawned CGI program.
  5447. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  5448. * last element must be NULL.
  5449. * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  5450. * strings must reside in a contiguous buffer. The end of the buffer is
  5451. * marked by two '\0' characters.
  5452. * We satisfy both worlds: we create an envp array (which is vars), all
  5453. * entries are actually pointers inside buf. */
  5454. struct cgi_environment {
  5455. struct mg_connection *conn;
  5456. /* Data block */
  5457. char *buf; /* Environment buffer */
  5458. size_t buflen; /* Space available in buf */
  5459. size_t bufused; /* Space taken in buf */
  5460. /* Index block */
  5461. char **var; /* char **envp */
  5462. size_t varlen; /* Number of variables available in var */
  5463. size_t varused; /* Number of variables stored in var */
  5464. };
  5465. static void addenv(struct cgi_environment *env,
  5466. PRINTF_FORMAT_STRING(const char *fmt),
  5467. ...) PRINTF_ARGS(2, 3);
  5468. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  5469. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  5470. static void addenv(struct cgi_environment *env, const char *fmt, ...)
  5471. {
  5472. size_t n, space;
  5473. int truncated;
  5474. char *added;
  5475. va_list ap;
  5476. /* Calculate how much space is left in the buffer */
  5477. space = (env->buflen - env->bufused);
  5478. /* Calculate an estimate for the required space */
  5479. n = strlen(fmt) + 2 + 128;
  5480. do {
  5481. if (space <= n) {
  5482. /* Allocate new buffer */
  5483. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  5484. added = (char *)mg_realloc(env->buf, n);
  5485. if (!added) {
  5486. /* Out of memory */
  5487. mg_cry(env->conn,
  5488. "%s: Cannot allocate memory for CGI variable [%s]",
  5489. __func__,
  5490. fmt);
  5491. return;
  5492. }
  5493. env->buf = added;
  5494. env->buflen = n;
  5495. space = (env->buflen - env->bufused);
  5496. }
  5497. /* Make a pointer to the free space int the buffer */
  5498. added = env->buf + env->bufused;
  5499. /* Copy VARIABLE=VALUE\0 string into the free space */
  5500. va_start(ap, fmt);
  5501. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  5502. va_end(ap);
  5503. /* Do not add truncated strings to the environment */
  5504. if (truncated) {
  5505. /* Reallocate the buffer */
  5506. space = 0;
  5507. n = 1;
  5508. }
  5509. } while (truncated);
  5510. /* Calculate number of bytes added to the environment */
  5511. n = strlen(added) + 1;
  5512. env->bufused += n;
  5513. /* Now update the variable index */
  5514. space = (env->varlen - env->varused);
  5515. if (space < 2) {
  5516. mg_cry(
  5517. env->conn, "%s: Cannot register CGI variable [%s]", __func__, fmt);
  5518. return;
  5519. }
  5520. /* Append a pointer to the added string into the envp array */
  5521. env->var[env->varused] = added;
  5522. env->varused++;
  5523. }
  5524. static void prepare_cgi_environment(struct mg_connection *conn,
  5525. const char *prog,
  5526. struct cgi_environment *env)
  5527. {
  5528. const char *s;
  5529. struct vec var_vec;
  5530. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  5531. int i, truncated;
  5532. if (conn == NULL || prog == NULL || env == NULL) {
  5533. return;
  5534. }
  5535. env->conn = conn;
  5536. env->buflen = CGI_ENVIRONMENT_SIZE;
  5537. env->bufused = 0;
  5538. env->buf = (char *)mg_malloc(env->buflen);
  5539. env->varlen = MAX_CGI_ENVIR_VARS;
  5540. env->varused = 0;
  5541. env->var = (char **)mg_malloc(env->buflen * sizeof(char *));
  5542. addenv(env, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  5543. addenv(env, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  5544. addenv(env, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  5545. addenv(env, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  5546. /* Prepare the environment block */
  5547. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  5548. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  5549. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  5550. #if defined(USE_IPV6)
  5551. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  5552. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  5553. } else
  5554. #endif
  5555. {
  5556. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  5557. }
  5558. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  5559. addenv(env, "REMOTE_ADDR=%s", src_addr);
  5560. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  5561. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  5562. /* TODO: Check if request_uri or rel_uri should be used */
  5563. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  5564. /* SCRIPT_NAME */
  5565. addenv(env,
  5566. "SCRIPT_NAME=%.*s",
  5567. (int)strlen(conn->request_info.rel_uri) -
  5568. ((conn->path_info == NULL) ? 0 : (int)strlen(conn->path_info)),
  5569. conn->request_info.rel_uri);
  5570. addenv(env, "SCRIPT_FILENAME=%s", prog);
  5571. if (conn->path_info == NULL) {
  5572. addenv(env, "PATH_TRANSLATED=%s", conn->ctx->config[DOCUMENT_ROOT]);
  5573. } else {
  5574. addenv(env,
  5575. "PATH_TRANSLATED=%s%s",
  5576. conn->ctx->config[DOCUMENT_ROOT],
  5577. conn->path_info);
  5578. }
  5579. addenv(env, "HTTPS=%s", conn->ssl == NULL ? "off" : "on");
  5580. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  5581. addenv(env, "CONTENT_TYPE=%s", s);
  5582. }
  5583. if (conn->request_info.query_string != NULL) {
  5584. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  5585. }
  5586. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  5587. addenv(env, "CONTENT_LENGTH=%s", s);
  5588. }
  5589. if ((s = getenv("PATH")) != NULL) {
  5590. addenv(env, "PATH=%s", s);
  5591. }
  5592. if (conn->path_info != NULL) {
  5593. addenv(env, "PATH_INFO=%s", conn->path_info);
  5594. }
  5595. if (conn->status_code > 0) {
  5596. /* CGI error handler should show the status code */
  5597. addenv(env, "STATUS=%d", conn->status_code);
  5598. }
  5599. #if defined(_WIN32)
  5600. if ((s = getenv("COMSPEC")) != NULL) {
  5601. addenv(env, "COMSPEC=%s", s);
  5602. }
  5603. if ((s = getenv("SYSTEMROOT")) != NULL) {
  5604. addenv(env, "SYSTEMROOT=%s", s);
  5605. }
  5606. if ((s = getenv("SystemDrive")) != NULL) {
  5607. addenv(env, "SystemDrive=%s", s);
  5608. }
  5609. if ((s = getenv("ProgramFiles")) != NULL) {
  5610. addenv(env, "ProgramFiles=%s", s);
  5611. }
  5612. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  5613. addenv(env, "ProgramFiles(x86)=%s", s);
  5614. }
  5615. #else
  5616. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  5617. addenv(env, "LD_LIBRARY_PATH=%s", s);
  5618. }
  5619. #endif /* _WIN32 */
  5620. if ((s = getenv("PERLLIB")) != NULL) {
  5621. addenv(env, "PERLLIB=%s", s);
  5622. }
  5623. if (conn->request_info.remote_user != NULL) {
  5624. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  5625. addenv(env, "%s", "AUTH_TYPE=Digest");
  5626. }
  5627. /* Add all headers as HTTP_* variables */
  5628. for (i = 0; i < conn->request_info.num_headers; i++) {
  5629. (void)mg_snprintf(conn,
  5630. &truncated,
  5631. http_var_name,
  5632. sizeof(http_var_name),
  5633. "HTTP_%s",
  5634. conn->request_info.http_headers[i].name);
  5635. if (truncated) {
  5636. mg_cry(conn,
  5637. "%s: HTTP header variable too long [%s]",
  5638. __func__,
  5639. conn->request_info.http_headers[i].name);
  5640. continue;
  5641. }
  5642. /* Convert variable name into uppercase, and change - to _ */
  5643. for (p = http_var_name; *p != '\0'; p++) {
  5644. if (*p == '-') {
  5645. *p = '_';
  5646. }
  5647. *p = (char)toupper(*(unsigned char *)p);
  5648. }
  5649. addenv(env,
  5650. "%s=%s",
  5651. http_var_name,
  5652. conn->request_info.http_headers[i].value);
  5653. }
  5654. /* Add user-specified variables */
  5655. s = conn->ctx->config[CGI_ENVIRONMENT];
  5656. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  5657. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  5658. }
  5659. env->var[env->varused] = NULL;
  5660. env->buf[env->bufused] = '\0';
  5661. }
  5662. static void handle_cgi_request(struct mg_connection *conn, const char *prog)
  5663. {
  5664. char *buf;
  5665. size_t buflen;
  5666. int headers_len, data_len, i, truncated;
  5667. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  5668. const char *status, *status_text, *connection_state;
  5669. char *pbuf, dir[PATH_MAX], *p;
  5670. struct mg_request_info ri;
  5671. struct cgi_environment blk;
  5672. FILE *in = NULL, *out = NULL, *err = NULL;
  5673. struct file fout = STRUCT_FILE_INITIALIZER;
  5674. pid_t pid = (pid_t)-1;
  5675. if (conn == NULL) {
  5676. return;
  5677. }
  5678. buf = NULL;
  5679. buflen = 16384;
  5680. prepare_cgi_environment(conn, prog, &blk);
  5681. /* CGI must be executed in its own directory. 'dir' must point to the
  5682. * directory containing executable program, 'p' must point to the
  5683. * executable program name relative to 'dir'. */
  5684. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  5685. if (truncated) {
  5686. mg_cry(conn, "Error: CGI program \"%s\": Path too long", prog);
  5687. send_http_error(conn, 500, "Error: %s", "CGI path too long");
  5688. goto done;
  5689. }
  5690. if ((p = strrchr(dir, '/')) != NULL) {
  5691. *p++ = '\0';
  5692. } else {
  5693. dir[0] = '.', dir[1] = '\0';
  5694. p = (char *)prog;
  5695. }
  5696. if (pipe(fdin) != 0 || pipe(fdout) != 0 || pipe(fderr) != 0) {
  5697. status = strerror(ERRNO);
  5698. mg_cry(conn,
  5699. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  5700. prog,
  5701. status);
  5702. send_http_error(conn, 500, "Error: Cannot create CGI pipe: %s", status);
  5703. goto done;
  5704. }
  5705. pid = spawn_process(
  5706. conn, p, blk.buf, blk.var, fdin[0], fdout[1], fderr[1], dir);
  5707. if (pid == (pid_t)-1) {
  5708. status = strerror(ERRNO);
  5709. mg_cry(conn,
  5710. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  5711. prog,
  5712. status);
  5713. send_http_error(conn,
  5714. 500,
  5715. "Error: Cannot spawn CGI process [%s]: %s",
  5716. prog,
  5717. status);
  5718. goto done;
  5719. }
  5720. /* Make sure child closes all pipe descriptors. It must dup them to 0,1 */
  5721. set_close_on_exec((SOCKET)fdin[0], conn);
  5722. set_close_on_exec((SOCKET)fdin[1], conn);
  5723. set_close_on_exec((SOCKET)fdout[0], conn);
  5724. set_close_on_exec((SOCKET)fdout[1], conn);
  5725. set_close_on_exec((SOCKET)fderr[0], conn);
  5726. set_close_on_exec((SOCKET)fderr[1], conn);
  5727. /* Parent closes only one side of the pipes.
  5728. * If we don't mark them as closed, close() attempt before
  5729. * return from this function throws an exception on Windows.
  5730. * Windows does not like when closed descriptor is closed again. */
  5731. (void)close(fdin[0]);
  5732. (void)close(fdout[1]);
  5733. (void)close(fderr[1]);
  5734. fdin[0] = fdout[1] = fderr[1] = -1;
  5735. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  5736. status = strerror(ERRNO);
  5737. mg_cry(conn,
  5738. "Error: CGI program \"%s\": Can not open stdin: %s",
  5739. prog,
  5740. status);
  5741. send_http_error(
  5742. conn, 500, "Error: CGI can not open fdin\nfopen: %s", status);
  5743. goto done;
  5744. }
  5745. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  5746. status = strerror(ERRNO);
  5747. mg_cry(conn,
  5748. "Error: CGI program \"%s\": Can not open stdout: %s",
  5749. prog,
  5750. status);
  5751. send_http_error(
  5752. conn, 500, "Error: CGI can not open fdout\nfopen: %s", status);
  5753. goto done;
  5754. }
  5755. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  5756. status = strerror(ERRNO);
  5757. mg_cry(conn,
  5758. "Error: CGI program \"%s\": Can not open stderr: %s",
  5759. prog,
  5760. status);
  5761. send_http_error(
  5762. conn, 500, "Error: CGI can not open fdout\nfopen: %s", status);
  5763. goto done;
  5764. }
  5765. setbuf(in, NULL);
  5766. setbuf(out, NULL);
  5767. setbuf(err, NULL);
  5768. fout.fp = out;
  5769. /* Send POST or PUT data to the CGI process if needed */
  5770. /* TODO(high): Methods like PATCH, MKCOL, ... also have body data. */
  5771. if (!mg_strcasecmp(conn->request_info.request_method, "POST") ||
  5772. !mg_strcasecmp(conn->request_info.request_method, "PUT")) {
  5773. /* This is a POST/PUT request */
  5774. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  5775. /* Error sending the body data */
  5776. mg_cry(conn,
  5777. "Error: CGI program \"%s\": Forward body data failed",
  5778. prog);
  5779. goto done;
  5780. }
  5781. }
  5782. /* Close so child gets an EOF. */
  5783. fclose(in);
  5784. in = NULL;
  5785. fdin[1] = -1;
  5786. /* Now read CGI reply into a buffer. We need to set correct
  5787. * status code, thus we need to see all HTTP headers first.
  5788. * Do not send anything back to client, until we buffer in all
  5789. * HTTP headers. */
  5790. data_len = 0;
  5791. buf = (char *)mg_malloc(buflen);
  5792. if (buf == NULL) {
  5793. send_http_error(conn,
  5794. 500,
  5795. "Error: Not enough memory for CGI buffer (%u bytes)",
  5796. (unsigned int)buflen);
  5797. mg_cry(conn,
  5798. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  5799. "bytes)",
  5800. prog,
  5801. (unsigned int)buflen);
  5802. goto done;
  5803. }
  5804. headers_len = read_request(out, conn, buf, (int)buflen, &data_len);
  5805. if (headers_len <= 0) {
  5806. /* Could not parse the CGI response. Check if some error message on
  5807. * stderr. */
  5808. i = pull_all(err, conn, buf, (int)buflen);
  5809. if (i > 0) {
  5810. mg_cry(conn,
  5811. "Error: CGI program \"%s\" sent error "
  5812. "message: [%.*s]",
  5813. prog,
  5814. i,
  5815. buf);
  5816. send_http_error(conn,
  5817. 500,
  5818. "Error: CGI program \"%s\" sent error "
  5819. "message: [%.*s]",
  5820. prog,
  5821. i,
  5822. buf);
  5823. } else {
  5824. mg_cry(conn,
  5825. "Error: CGI program sent malformed or too big "
  5826. "(>%u bytes) HTTP headers: [%.*s]",
  5827. (unsigned)buflen,
  5828. data_len,
  5829. buf);
  5830. send_http_error(conn,
  5831. 500,
  5832. "Error: CGI program sent malformed or too big "
  5833. "(>%u bytes) HTTP headers: [%.*s]",
  5834. (unsigned)buflen,
  5835. data_len,
  5836. buf);
  5837. }
  5838. goto done;
  5839. }
  5840. pbuf = buf;
  5841. buf[headers_len - 1] = '\0';
  5842. parse_http_headers(&pbuf, &ri);
  5843. /* Make up and send the status line */
  5844. status_text = "OK";
  5845. if ((status = get_header(&ri, "Status")) != NULL) {
  5846. conn->status_code = atoi(status);
  5847. status_text = status;
  5848. while (isdigit(*(unsigned char *)status_text) || *status_text == ' ') {
  5849. status_text++;
  5850. }
  5851. } else if (get_header(&ri, "Location") != NULL) {
  5852. conn->status_code = 302;
  5853. } else {
  5854. conn->status_code = 200;
  5855. }
  5856. connection_state = get_header(&ri, "Connection");
  5857. if (connection_state == NULL ||
  5858. mg_strcasecmp(connection_state, "keep-alive")) {
  5859. conn->must_close = 1;
  5860. }
  5861. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  5862. /* Send headers */
  5863. for (i = 0; i < ri.num_headers; i++) {
  5864. mg_printf(conn,
  5865. "%s: %s\r\n",
  5866. ri.http_headers[i].name,
  5867. ri.http_headers[i].value);
  5868. }
  5869. mg_write(conn, "\r\n", 2);
  5870. /* Send chunk of data that may have been read after the headers */
  5871. conn->num_bytes_sent +=
  5872. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  5873. /* Read the rest of CGI output and send to the client */
  5874. send_file_data(conn, &fout, 0, INT64_MAX);
  5875. done:
  5876. mg_free(blk.var);
  5877. mg_free(blk.buf);
  5878. if (pid != (pid_t)-1) {
  5879. kill(pid, SIGKILL);
  5880. #if !defined(_WIN32)
  5881. {
  5882. int st;
  5883. while (waitpid(pid, &st, 0) != -1)
  5884. ; /* clean zombies */
  5885. }
  5886. #endif
  5887. }
  5888. if (fdin[0] != -1) {
  5889. close(fdin[0]);
  5890. }
  5891. if (fdout[1] != -1) {
  5892. close(fdout[1]);
  5893. }
  5894. if (in != NULL) {
  5895. fclose(in);
  5896. } else if (fdin[1] != -1) {
  5897. close(fdin[1]);
  5898. }
  5899. if (out != NULL) {
  5900. fclose(out);
  5901. } else if (fdout[0] != -1) {
  5902. close(fdout[0]);
  5903. }
  5904. if (err != NULL) {
  5905. fclose(err);
  5906. } else if (fderr[0] != -1) {
  5907. close(fderr[0]);
  5908. }
  5909. if (buf != NULL) {
  5910. mg_free(buf);
  5911. }
  5912. }
  5913. #endif /* !NO_CGI */
  5914. #if !defined(NO_FILES)
  5915. /* For a given PUT path, create all intermediate subdirectories.
  5916. * Return 0 if the path itself is a directory.
  5917. * Return 1 if the path leads to a file.
  5918. * Return -1 for if the path is too long.
  5919. * Return -2 if path can not be created.
  5920. */
  5921. static int put_dir(struct mg_connection *conn, const char *path)
  5922. {
  5923. char buf[PATH_MAX];
  5924. const char *s, *p;
  5925. struct file file = STRUCT_FILE_INITIALIZER;
  5926. size_t len;
  5927. int res = 1;
  5928. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  5929. len = (size_t)(p - path);
  5930. if (len >= sizeof(buf)) {
  5931. /* path too long */
  5932. res = -1;
  5933. break;
  5934. }
  5935. memcpy(buf, path, len);
  5936. buf[len] = '\0';
  5937. /* Try to create intermediate directory */
  5938. DEBUG_TRACE("mkdir(%s)", buf);
  5939. if (!mg_stat(conn, buf, &file) && mg_mkdir(buf, 0755) != 0) {
  5940. /* path does not exixt and can not be created */
  5941. res = -2;
  5942. break;
  5943. }
  5944. /* Is path itself a directory? */
  5945. if (p[1] == '\0') {
  5946. res = 0;
  5947. }
  5948. }
  5949. return res;
  5950. }
  5951. static void mkcol(struct mg_connection *conn, const char *path)
  5952. {
  5953. int rc, body_len;
  5954. struct de de;
  5955. char date[64];
  5956. time_t curtime = time(NULL);
  5957. if (conn == NULL) {
  5958. return;
  5959. }
  5960. /* TODO (mid): Check the send_http_error situations in this function */
  5961. memset(&de.file, 0, sizeof(de.file));
  5962. if (!mg_stat(conn, path, &de.file)) {
  5963. mg_cry(conn,
  5964. "%s: mg_stat(%s) failed: %s",
  5965. __func__,
  5966. path,
  5967. strerror(ERRNO));
  5968. }
  5969. if (de.file.last_modified) {
  5970. /* TODO (high): This check does not seem to make any sense ! */
  5971. send_http_error(
  5972. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  5973. return;
  5974. }
  5975. body_len = conn->data_len - conn->request_len;
  5976. if (body_len > 0) {
  5977. send_http_error(
  5978. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  5979. return;
  5980. }
  5981. rc = mg_mkdir(path, 0755);
  5982. if (rc == 0) {
  5983. conn->status_code = 201;
  5984. gmt_time_string(date, sizeof(date), &curtime);
  5985. mg_printf(conn,
  5986. "HTTP/1.1 %d Created\r\nDate: %s\r\nContent-Length: "
  5987. "0\r\nConnection: %s\r\n\r\n",
  5988. conn->status_code,
  5989. date,
  5990. suggest_connection_header(conn));
  5991. } else if (rc == -1) {
  5992. if (errno == EEXIST) {
  5993. send_http_error(
  5994. conn, 405, "Error:mkcol(%s): %s", path, strerror(ERRNO));
  5995. } else if (errno == EACCES) {
  5996. send_http_error(
  5997. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  5998. } else if (errno == ENOENT) {
  5999. send_http_error(
  6000. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6001. } else {
  6002. send_http_error(conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  6003. }
  6004. }
  6005. }
  6006. static void put_file(struct mg_connection *conn, const char *path)
  6007. {
  6008. struct file file = STRUCT_FILE_INITIALIZER;
  6009. const char *range;
  6010. int64_t r1, r2;
  6011. int rc;
  6012. char date[64];
  6013. time_t curtime = time(NULL);
  6014. if (conn == NULL) {
  6015. return;
  6016. }
  6017. if (mg_stat(conn, path, &file)) {
  6018. /* File already exists */
  6019. conn->status_code = 200;
  6020. if (file.is_directory) {
  6021. /* This is an already existing directory,
  6022. * so there is nothing to do for the server. */
  6023. rc = 0;
  6024. } else {
  6025. /* File exists and is not a directory. */
  6026. /* Can it be replaced? */
  6027. if (file.membuf != NULL) {
  6028. /* This is an "in-memory" file, that can not be replaced */
  6029. send_http_error(
  6030. conn,
  6031. 405,
  6032. "Error: Put not possible\nReplacing %s is not supported",
  6033. path);
  6034. return;
  6035. }
  6036. /* Check if the server may write this file */
  6037. if (access(path, W_OK) == 0) {
  6038. /* Access granted */
  6039. conn->status_code = 200;
  6040. rc = 1;
  6041. } else {
  6042. send_http_error(
  6043. conn,
  6044. 403,
  6045. "Error: Put not possible\nReplacing %s is not allowed",
  6046. path);
  6047. return;
  6048. }
  6049. }
  6050. } else {
  6051. /* File should be created */
  6052. conn->status_code = 201;
  6053. rc = put_dir(conn, path);
  6054. }
  6055. if (rc == 0) {
  6056. /* put_dir returns 0 if path is a directory */
  6057. gmt_time_string(date, sizeof(date), &curtime);
  6058. mg_printf(conn,
  6059. "HTTP/1.1 %d %s\r\n"
  6060. "Date: %s\r\n"
  6061. "Content-Length: 0\r\n"
  6062. "Connection: %s\r\n\r\n",
  6063. conn->status_code,
  6064. mg_get_response_code_text(conn->status_code, NULL),
  6065. date,
  6066. suggest_connection_header(conn));
  6067. /* Request to create a directory has been fulfilled successfully.
  6068. * No need to put a file. */
  6069. return;
  6070. }
  6071. if (rc == -1) {
  6072. /* put_dir returns -1 if the path is too long */
  6073. send_http_error(conn,
  6074. 414,
  6075. "Error: Path too long\nput_dir(%s): %s",
  6076. path,
  6077. strerror(ERRNO));
  6078. return;
  6079. }
  6080. if (rc == -2) {
  6081. /* put_dir returns -2 if the directory can not be created */
  6082. send_http_error(conn,
  6083. 500,
  6084. "Error: Can not create directory\nput_dir(%s): %s",
  6085. path,
  6086. strerror(ERRNO));
  6087. return;
  6088. }
  6089. /* A file should be created or overwritten. */
  6090. if (!mg_fopen(conn, path, "wb+", &file) || file.fp == NULL) {
  6091. mg_fclose(&file);
  6092. send_http_error(conn,
  6093. 500,
  6094. "Error: Can not create file\nfopen(%s): %s",
  6095. path,
  6096. strerror(ERRNO));
  6097. return;
  6098. }
  6099. fclose_on_exec(&file, conn);
  6100. range = mg_get_header(conn, "Content-Range");
  6101. r1 = r2 = 0;
  6102. if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
  6103. conn->status_code = 206; /* Partial content */
  6104. fseeko(file.fp, r1, SEEK_SET);
  6105. }
  6106. if (!forward_body_data(conn, file.fp, INVALID_SOCKET, NULL)) {
  6107. /* forward_body_data failed.
  6108. * The error code has already been sent to the client,
  6109. * and conn->status_code is already set. */
  6110. return;
  6111. }
  6112. gmt_time_string(date, sizeof(date), &curtime);
  6113. mg_printf(conn,
  6114. "HTTP/1.1 %d %s\r\n"
  6115. "Date: %s\r\n"
  6116. "Content-Length: 0\r\n"
  6117. "Connection: %s\r\n\r\n",
  6118. conn->status_code,
  6119. mg_get_response_code_text(conn->status_code, NULL),
  6120. date,
  6121. suggest_connection_header(conn));
  6122. mg_fclose(&file);
  6123. }
  6124. static void delete_file(struct mg_connection *conn, const char *path)
  6125. {
  6126. struct de de;
  6127. memset(&de.file, 0, sizeof(de.file));
  6128. if (!mg_stat(conn, path, &de.file)) {
  6129. /* mg_stat returns 0 if the file does not exist */
  6130. send_http_error(
  6131. conn, 404, "Error: Cannot delete file\nFile %s not found", path);
  6132. return;
  6133. }
  6134. if (de.file.membuf != NULL) {
  6135. /* the file is cached in memory */
  6136. send_http_error(
  6137. conn,
  6138. 405,
  6139. "Error: Delete not possible\nDeleting %s is not supported",
  6140. path);
  6141. return;
  6142. }
  6143. if (de.file.is_directory) {
  6144. remove_directory(conn, path);
  6145. /* TODO (mid): remove_dir does not return success of the operation */
  6146. /* Assume delete is successful: Return 204 without content. */
  6147. send_http_error(conn, 204, "%s", "");
  6148. return;
  6149. }
  6150. /* This is an existing file (not a directory).
  6151. * Check if write permission is granted. */
  6152. if (access(path, W_OK) != 0) {
  6153. /* File is read only */
  6154. send_http_error(
  6155. conn,
  6156. 403,
  6157. "Error: Delete not possible\nDeleting %s is not allowed",
  6158. path);
  6159. return;
  6160. }
  6161. /* Try to delete it. */
  6162. if (mg_remove(path) == 0) {
  6163. /* Delete was successful: Return 204 without content. */
  6164. send_http_error(conn, 204, "%s", "");
  6165. } else {
  6166. /* Delete not successful (file locked). */
  6167. send_http_error(conn,
  6168. 423,
  6169. "Error: Cannot delete file\nremove(%s): %s",
  6170. path,
  6171. strerror(ERRNO));
  6172. }
  6173. }
  6174. #endif /* !NO_FILES */
  6175. static void
  6176. send_ssi_file(struct mg_connection *, const char *, struct file *, int);
  6177. static void do_ssi_include(struct mg_connection *conn,
  6178. const char *ssi,
  6179. char *tag,
  6180. int include_level)
  6181. {
  6182. char file_name[MG_BUF_LEN], path[512], *p;
  6183. struct file file = STRUCT_FILE_INITIALIZER;
  6184. size_t len;
  6185. int truncated = 0;
  6186. if (conn == NULL) {
  6187. return;
  6188. }
  6189. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  6190. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  6191. * always < MG_BUF_LEN. */
  6192. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  6193. /* File name is relative to the webserver root */
  6194. file_name[511] = 0;
  6195. (void)mg_snprintf(conn,
  6196. &truncated,
  6197. path,
  6198. sizeof(path),
  6199. "%s/%s",
  6200. conn->ctx->config[DOCUMENT_ROOT],
  6201. file_name);
  6202. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  6203. /* File name is relative to the webserver working directory
  6204. * or it is absolute system path */
  6205. file_name[511] = 0;
  6206. (void)mg_snprintf(
  6207. conn, &truncated, path, sizeof(path), "%s", file_name);
  6208. } else if (sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1 ||
  6209. sscanf(tag, " \"%511[^\"]\"", file_name) == 1) {
  6210. /* File name is relative to the currect document */
  6211. file_name[511] = 0;
  6212. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  6213. if (!truncated) {
  6214. if ((p = strrchr(path, '/')) != NULL) {
  6215. p[1] = '\0';
  6216. }
  6217. len = strlen(path);
  6218. (void)mg_snprintf(conn,
  6219. &truncated,
  6220. path + len,
  6221. sizeof(path) - len,
  6222. "%s",
  6223. file_name);
  6224. }
  6225. } else {
  6226. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  6227. return;
  6228. }
  6229. if (truncated) {
  6230. mg_cry(conn, "SSI #include path length overflow: [%s]", tag);
  6231. return;
  6232. }
  6233. if (!mg_fopen(conn, path, "rb", &file)) {
  6234. mg_cry(conn,
  6235. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  6236. tag,
  6237. path,
  6238. strerror(ERRNO));
  6239. } else {
  6240. fclose_on_exec(&file, conn);
  6241. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  6242. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  6243. path) > 0) {
  6244. send_ssi_file(conn, path, &file, include_level + 1);
  6245. } else {
  6246. send_file_data(conn, &file, 0, INT64_MAX);
  6247. }
  6248. mg_fclose(&file);
  6249. }
  6250. }
  6251. #if !defined(NO_POPEN)
  6252. static void do_ssi_exec(struct mg_connection *conn, char *tag)
  6253. {
  6254. char cmd[1024] = "";
  6255. struct file file = STRUCT_FILE_INITIALIZER;
  6256. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  6257. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  6258. } else {
  6259. cmd[1023] = 0;
  6260. if ((file.fp = popen(cmd, "r")) == NULL) {
  6261. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  6262. } else {
  6263. send_file_data(conn, &file, 0, INT64_MAX);
  6264. pclose(file.fp);
  6265. }
  6266. }
  6267. }
  6268. #endif /* !NO_POPEN */
  6269. static int mg_fgetc(struct file *filep, int offset)
  6270. {
  6271. if (filep == NULL) {
  6272. return EOF;
  6273. }
  6274. if (filep->membuf != NULL && offset >= 0 &&
  6275. ((unsigned int)(offset)) < filep->size) {
  6276. return ((unsigned char *)filep->membuf)[offset];
  6277. } else if (filep->fp != NULL) {
  6278. return fgetc(filep->fp);
  6279. } else {
  6280. return EOF;
  6281. }
  6282. }
  6283. static void send_ssi_file(struct mg_connection *conn,
  6284. const char *path,
  6285. struct file *filep,
  6286. int include_level)
  6287. {
  6288. char buf[MG_BUF_LEN];
  6289. int ch, offset, len, in_ssi_tag;
  6290. if (include_level > 10) {
  6291. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  6292. return;
  6293. }
  6294. in_ssi_tag = len = offset = 0;
  6295. while ((ch = mg_fgetc(filep, offset)) != EOF) {
  6296. if (in_ssi_tag && ch == '>') {
  6297. in_ssi_tag = 0;
  6298. buf[len++] = (char)ch;
  6299. buf[len] = '\0';
  6300. /* assert(len <= (int) sizeof(buf)); */
  6301. if (len > (int)sizeof(buf)) {
  6302. break;
  6303. }
  6304. if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
  6305. /* Not an SSI tag, pass it */
  6306. (void)mg_write(conn, buf, (size_t)len);
  6307. } else {
  6308. if (!memcmp(buf + 5, "include", 7)) {
  6309. do_ssi_include(conn, path, buf + 12, include_level);
  6310. #if !defined(NO_POPEN)
  6311. } else if (!memcmp(buf + 5, "exec", 4)) {
  6312. do_ssi_exec(conn, buf + 9);
  6313. #endif /* !NO_POPEN */
  6314. } else {
  6315. mg_cry(conn,
  6316. "%s: unknown SSI "
  6317. "command: \"%s\"",
  6318. path,
  6319. buf);
  6320. }
  6321. }
  6322. len = 0;
  6323. } else if (in_ssi_tag) {
  6324. if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
  6325. /* Not an SSI tag */
  6326. in_ssi_tag = 0;
  6327. } else if (len == (int)sizeof(buf) - 2) {
  6328. mg_cry(conn, "%s: SSI tag is too large", path);
  6329. len = 0;
  6330. }
  6331. buf[len++] = (char)(ch & 0xff);
  6332. } else if (ch == '<') {
  6333. in_ssi_tag = 1;
  6334. if (len > 0) {
  6335. mg_write(conn, buf, (size_t)len);
  6336. }
  6337. len = 0;
  6338. buf[len++] = (char)(ch & 0xff);
  6339. } else {
  6340. buf[len++] = (char)(ch & 0xff);
  6341. if (len == (int)sizeof(buf)) {
  6342. mg_write(conn, buf, (size_t)len);
  6343. len = 0;
  6344. }
  6345. }
  6346. }
  6347. /* Send the rest of buffered data */
  6348. if (len > 0) {
  6349. mg_write(conn, buf, (size_t)len);
  6350. }
  6351. }
  6352. static void handle_ssi_file_request(struct mg_connection *conn,
  6353. const char *path,
  6354. struct file *filep)
  6355. {
  6356. char date[64];
  6357. time_t curtime = time(NULL);
  6358. const char *cors1, *cors2, *cors3;
  6359. if (conn == NULL || path == NULL || filep == NULL) {
  6360. return;
  6361. }
  6362. if (mg_get_header(conn, "Origin")) {
  6363. /* Cross-origin resource sharing (CORS). */
  6364. cors1 = "Access-Control-Allow-Origin: ";
  6365. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  6366. cors3 = "\r\n";
  6367. } else {
  6368. cors1 = cors2 = cors3 = "";
  6369. }
  6370. if (!mg_fopen(conn, path, "rb", filep)) {
  6371. /* File exists (precondition for calling this function),
  6372. * but can not be opened by the server. */
  6373. send_http_error(conn,
  6374. 500,
  6375. "Error: Cannot read file\nfopen(%s): %s",
  6376. path,
  6377. strerror(ERRNO));
  6378. } else {
  6379. conn->must_close = 1;
  6380. gmt_time_string(date, sizeof(date), &curtime);
  6381. fclose_on_exec(filep, conn);
  6382. mg_printf(conn,
  6383. "HTTP/1.1 200 OK\r\n"
  6384. "%s%s%s"
  6385. "Date: %s\r\n"
  6386. "Content-Type: text/html\r\n"
  6387. "Connection: %s\r\n\r\n",
  6388. cors1,
  6389. cors2,
  6390. cors3,
  6391. date,
  6392. suggest_connection_header(conn));
  6393. send_ssi_file(conn, path, filep, 0);
  6394. mg_fclose(filep);
  6395. }
  6396. }
  6397. #if !defined(NO_FILES)
  6398. static void send_options(struct mg_connection *conn)
  6399. {
  6400. char date[64];
  6401. time_t curtime = time(NULL);
  6402. if (!conn) {
  6403. return;
  6404. }
  6405. conn->status_code = 200;
  6406. conn->must_close = 1;
  6407. gmt_time_string(date, sizeof(date), &curtime);
  6408. mg_printf(conn,
  6409. "HTTP/1.1 200 OK\r\n"
  6410. "Date: %s\r\n"
  6411. "Connection: %s\r\n"
  6412. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  6413. "PROPFIND, MKCOL\r\n"
  6414. "DAV: 1\r\n\r\n",
  6415. date,
  6416. suggest_connection_header(conn));
  6417. }
  6418. /* Writes PROPFIND properties for a collection element */
  6419. static void
  6420. print_props(struct mg_connection *conn, const char *uri, struct file *filep)
  6421. {
  6422. char mtime[64];
  6423. if (conn == NULL || uri == NULL || filep == NULL) {
  6424. return;
  6425. }
  6426. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  6427. conn->num_bytes_sent +=
  6428. mg_printf(conn,
  6429. "<d:response>"
  6430. "<d:href>%s</d:href>"
  6431. "<d:propstat>"
  6432. "<d:prop>"
  6433. "<d:resourcetype>%s</d:resourcetype>"
  6434. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  6435. "<d:getlastmodified>%s</d:getlastmodified>"
  6436. "</d:prop>"
  6437. "<d:status>HTTP/1.1 200 OK</d:status>"
  6438. "</d:propstat>"
  6439. "</d:response>\n",
  6440. uri,
  6441. filep->is_directory ? "<d:collection/>" : "",
  6442. filep->size,
  6443. mtime);
  6444. }
  6445. static void print_dav_dir_entry(struct de *de, void *data)
  6446. {
  6447. char href[PATH_MAX];
  6448. char href_encoded[PATH_MAX];
  6449. int truncated;
  6450. struct mg_connection *conn = (struct mg_connection *)data;
  6451. if (!de || !conn) {
  6452. return;
  6453. }
  6454. mg_snprintf(conn,
  6455. &truncated,
  6456. href,
  6457. sizeof(href),
  6458. "%s%s",
  6459. conn->request_info.rel_uri,
  6460. de->file_name);
  6461. if (!truncated) {
  6462. mg_url_encode(href, href_encoded, PATH_MAX - 1);
  6463. print_props(conn, href_encoded, &de->file);
  6464. }
  6465. }
  6466. static void handle_propfind(struct mg_connection *conn,
  6467. const char *path,
  6468. struct file *filep)
  6469. {
  6470. const char *depth = mg_get_header(conn, "Depth");
  6471. char date[64];
  6472. time_t curtime = time(NULL);
  6473. gmt_time_string(date, sizeof(date), &curtime);
  6474. if (!conn || !path || !filep) {
  6475. return;
  6476. }
  6477. conn->must_close = 1;
  6478. conn->status_code = 207;
  6479. mg_printf(conn,
  6480. "HTTP/1.1 207 Multi-Status\r\n"
  6481. "Date: %s\r\n"
  6482. "Connection: %s\r\n"
  6483. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  6484. date,
  6485. suggest_connection_header(conn));
  6486. conn->num_bytes_sent +=
  6487. mg_printf(conn,
  6488. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  6489. "<d:multistatus xmlns:d='DAV:'>\n");
  6490. /* Print properties for the requested resource itself */
  6491. print_props(conn, conn->request_info.rel_uri, filep);
  6492. /* If it is a directory, print directory entries too if Depth is not 0 */
  6493. if (filep && conn->ctx && filep->is_directory &&
  6494. !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes") &&
  6495. (depth == NULL || strcmp(depth, "0") != 0)) {
  6496. scan_directory(conn, path, conn, &print_dav_dir_entry);
  6497. }
  6498. conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");
  6499. }
  6500. #endif
  6501. void mg_lock_connection(struct mg_connection *conn)
  6502. {
  6503. if (conn) {
  6504. (void)pthread_mutex_lock(&conn->mutex);
  6505. }
  6506. }
  6507. void mg_unlock_connection(struct mg_connection *conn)
  6508. {
  6509. if (conn) {
  6510. (void)pthread_mutex_unlock(&conn->mutex);
  6511. }
  6512. }
  6513. void mg_lock_context(struct mg_context *ctx)
  6514. {
  6515. if (ctx) {
  6516. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  6517. }
  6518. }
  6519. void mg_unlock_context(struct mg_context *ctx)
  6520. {
  6521. if (ctx) {
  6522. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  6523. }
  6524. }
  6525. #if defined(USE_TIMERS)
  6526. #include "timer.inl"
  6527. #endif /* USE_TIMERS */
  6528. #ifdef USE_LUA
  6529. #include "mod_lua.inl"
  6530. #endif /* USE_LUA */
  6531. #ifdef USE_DUKTAPE
  6532. #include "mod_duktape.inl"
  6533. #endif /* USE_DUKTAPE */
  6534. #if defined(USE_WEBSOCKET)
  6535. /* START OF SHA-1 code
  6536. * Copyright(c) By Steve Reid <steve@edmweb.com> */
  6537. #define SHA1HANDSOFF
  6538. /* According to current tests (May 2015), the <solarisfixes.h> is not required.
  6539. *
  6540. * #if defined(__sun)
  6541. * #include "solarisfixes.h"
  6542. * #endif
  6543. */
  6544. static int is_big_endian(void)
  6545. {
  6546. static const int n = 1;
  6547. return ((char *)&n)[0] == 0;
  6548. }
  6549. union char64long16 {
  6550. unsigned char c[64];
  6551. uint32_t l[16];
  6552. };
  6553. #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
  6554. static uint32_t blk0(union char64long16 *block, int i)
  6555. {
  6556. /* Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN */
  6557. if (!is_big_endian()) {
  6558. block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00) |
  6559. (rol(block->l[i], 8) & 0x00FF00FF);
  6560. }
  6561. return block->l[i];
  6562. }
  6563. #define blk(i) \
  6564. (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] ^ \
  6565. block->l[(i + 2) & 15] ^ block->l[i & 15], \
  6566. 1))
  6567. #define R0(v, w, x, y, z, i) \
  6568. z += ((w & (x ^ y)) ^ y) + blk0(block, i) + 0x5A827999 + rol(v, 5); \
  6569. w = rol(w, 30);
  6570. #define R1(v, w, x, y, z, i) \
  6571. z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \
  6572. w = rol(w, 30);
  6573. #define R2(v, w, x, y, z, i) \
  6574. z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \
  6575. w = rol(w, 30);
  6576. #define R3(v, w, x, y, z, i) \
  6577. z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \
  6578. w = rol(w, 30);
  6579. #define R4(v, w, x, y, z, i) \
  6580. z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \
  6581. w = rol(w, 30);
  6582. typedef struct {
  6583. uint32_t state[5];
  6584. uint32_t count[2];
  6585. unsigned char buffer[64];
  6586. } SHA1_CTX;
  6587. static void SHA1Transform(uint32_t state[5], const unsigned char buffer[64])
  6588. {
  6589. uint32_t a, b, c, d, e;
  6590. union char64long16 block[1];
  6591. memcpy(block, buffer, 64);
  6592. a = state[0];
  6593. b = state[1];
  6594. c = state[2];
  6595. d = state[3];
  6596. e = state[4];
  6597. R0(a, b, c, d, e, 0);
  6598. R0(e, a, b, c, d, 1);
  6599. R0(d, e, a, b, c, 2);
  6600. R0(c, d, e, a, b, 3);
  6601. R0(b, c, d, e, a, 4);
  6602. R0(a, b, c, d, e, 5);
  6603. R0(e, a, b, c, d, 6);
  6604. R0(d, e, a, b, c, 7);
  6605. R0(c, d, e, a, b, 8);
  6606. R0(b, c, d, e, a, 9);
  6607. R0(a, b, c, d, e, 10);
  6608. R0(e, a, b, c, d, 11);
  6609. R0(d, e, a, b, c, 12);
  6610. R0(c, d, e, a, b, 13);
  6611. R0(b, c, d, e, a, 14);
  6612. R0(a, b, c, d, e, 15);
  6613. R1(e, a, b, c, d, 16);
  6614. R1(d, e, a, b, c, 17);
  6615. R1(c, d, e, a, b, 18);
  6616. R1(b, c, d, e, a, 19);
  6617. R2(a, b, c, d, e, 20);
  6618. R2(e, a, b, c, d, 21);
  6619. R2(d, e, a, b, c, 22);
  6620. R2(c, d, e, a, b, 23);
  6621. R2(b, c, d, e, a, 24);
  6622. R2(a, b, c, d, e, 25);
  6623. R2(e, a, b, c, d, 26);
  6624. R2(d, e, a, b, c, 27);
  6625. R2(c, d, e, a, b, 28);
  6626. R2(b, c, d, e, a, 29);
  6627. R2(a, b, c, d, e, 30);
  6628. R2(e, a, b, c, d, 31);
  6629. R2(d, e, a, b, c, 32);
  6630. R2(c, d, e, a, b, 33);
  6631. R2(b, c, d, e, a, 34);
  6632. R2(a, b, c, d, e, 35);
  6633. R2(e, a, b, c, d, 36);
  6634. R2(d, e, a, b, c, 37);
  6635. R2(c, d, e, a, b, 38);
  6636. R2(b, c, d, e, a, 39);
  6637. R3(a, b, c, d, e, 40);
  6638. R3(e, a, b, c, d, 41);
  6639. R3(d, e, a, b, c, 42);
  6640. R3(c, d, e, a, b, 43);
  6641. R3(b, c, d, e, a, 44);
  6642. R3(a, b, c, d, e, 45);
  6643. R3(e, a, b, c, d, 46);
  6644. R3(d, e, a, b, c, 47);
  6645. R3(c, d, e, a, b, 48);
  6646. R3(b, c, d, e, a, 49);
  6647. R3(a, b, c, d, e, 50);
  6648. R3(e, a, b, c, d, 51);
  6649. R3(d, e, a, b, c, 52);
  6650. R3(c, d, e, a, b, 53);
  6651. R3(b, c, d, e, a, 54);
  6652. R3(a, b, c, d, e, 55);
  6653. R3(e, a, b, c, d, 56);
  6654. R3(d, e, a, b, c, 57);
  6655. R3(c, d, e, a, b, 58);
  6656. R3(b, c, d, e, a, 59);
  6657. R4(a, b, c, d, e, 60);
  6658. R4(e, a, b, c, d, 61);
  6659. R4(d, e, a, b, c, 62);
  6660. R4(c, d, e, a, b, 63);
  6661. R4(b, c, d, e, a, 64);
  6662. R4(a, b, c, d, e, 65);
  6663. R4(e, a, b, c, d, 66);
  6664. R4(d, e, a, b, c, 67);
  6665. R4(c, d, e, a, b, 68);
  6666. R4(b, c, d, e, a, 69);
  6667. R4(a, b, c, d, e, 70);
  6668. R4(e, a, b, c, d, 71);
  6669. R4(d, e, a, b, c, 72);
  6670. R4(c, d, e, a, b, 73);
  6671. R4(b, c, d, e, a, 74);
  6672. R4(a, b, c, d, e, 75);
  6673. R4(e, a, b, c, d, 76);
  6674. R4(d, e, a, b, c, 77);
  6675. R4(c, d, e, a, b, 78);
  6676. R4(b, c, d, e, a, 79);
  6677. state[0] += a;
  6678. state[1] += b;
  6679. state[2] += c;
  6680. state[3] += d;
  6681. state[4] += e;
  6682. a = b = c = d = e = 0;
  6683. memset(block, '\0', sizeof(block));
  6684. }
  6685. static void SHA1Init(SHA1_CTX *context)
  6686. {
  6687. context->state[0] = 0x67452301;
  6688. context->state[1] = 0xEFCDAB89;
  6689. context->state[2] = 0x98BADCFE;
  6690. context->state[3] = 0x10325476;
  6691. context->state[4] = 0xC3D2E1F0;
  6692. context->count[0] = context->count[1] = 0;
  6693. }
  6694. static void
  6695. SHA1Update(SHA1_CTX *context, const unsigned char *data, uint32_t len)
  6696. {
  6697. uint32_t i, j;
  6698. j = context->count[0];
  6699. if ((context->count[0] += len << 3) < j) {
  6700. context->count[1]++;
  6701. }
  6702. context->count[1] += (len >> 29);
  6703. j = (j >> 3) & 63;
  6704. if ((j + len) > 63) {
  6705. memcpy(&context->buffer[j], data, (i = 64 - j));
  6706. SHA1Transform(context->state, context->buffer);
  6707. for (; i + 63 < len; i += 64) {
  6708. SHA1Transform(context->state, &data[i]);
  6709. }
  6710. j = 0;
  6711. } else
  6712. i = 0;
  6713. memcpy(&context->buffer[j], &data[i], len - i);
  6714. }
  6715. static void SHA1Final(unsigned char digest[20], SHA1_CTX *context)
  6716. {
  6717. unsigned i;
  6718. unsigned char finalcount[8], c;
  6719. for (i = 0; i < 8; i++) {
  6720. finalcount[i] = (unsigned char)((context->count[(i >= 4 ? 0 : 1)] >>
  6721. ((3 - (i & 3)) * 8)) &
  6722. 255);
  6723. }
  6724. c = 0200;
  6725. SHA1Update(context, &c, 1);
  6726. while ((context->count[0] & 504) != 448) {
  6727. c = 0000;
  6728. SHA1Update(context, &c, 1);
  6729. }
  6730. SHA1Update(context, finalcount, 8);
  6731. for (i = 0; i < 20; i++) {
  6732. digest[i] =
  6733. (unsigned char)((context->state[i >> 2] >> ((3 - (i & 3)) * 8)) &
  6734. 255);
  6735. }
  6736. memset(context, '\0', sizeof(*context));
  6737. memset(&finalcount, '\0', sizeof(finalcount));
  6738. }
  6739. /* END OF SHA1 CODE */
  6740. static int send_websocket_handshake(struct mg_connection *conn)
  6741. {
  6742. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  6743. const char *protocol = NULL;
  6744. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  6745. SHA1_CTX sha_ctx;
  6746. int truncated;
  6747. mg_snprintf(conn,
  6748. &truncated,
  6749. buf,
  6750. sizeof(buf),
  6751. "%s%s",
  6752. mg_get_header(conn, "Sec-WebSocket-Key"),
  6753. magic);
  6754. if (truncated) {
  6755. conn->must_close = 1;
  6756. return 0;
  6757. }
  6758. SHA1Init(&sha_ctx);
  6759. SHA1Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  6760. SHA1Final((unsigned char *)sha, &sha_ctx);
  6761. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  6762. mg_printf(conn,
  6763. "HTTP/1.1 101 Switching Protocols\r\n"
  6764. "Upgrade: websocket\r\n"
  6765. "Connection: Upgrade\r\n"
  6766. "Sec-WebSocket-Accept: %s\r\n",
  6767. b64_sha);
  6768. protocol = mg_get_header(conn, "Sec-WebSocket-Protocol");
  6769. if (protocol) {
  6770. mg_printf(conn, "Sec-WebSocket-Protocol: %s\r\n\r\n", protocol);
  6771. } else {
  6772. mg_printf(conn, "%s", "\r\n");
  6773. }
  6774. return 1;
  6775. }
  6776. static void read_websocket(struct mg_connection *conn,
  6777. mg_websocket_data_handler ws_data_handler,
  6778. void *callback_data)
  6779. {
  6780. /* Pointer to the beginning of the portion of the incoming websocket
  6781. * message queue.
  6782. * The original websocket upgrade request is never removed, so the queue
  6783. * begins after it. */
  6784. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  6785. int n, error, exit_by_callback;
  6786. /* body_len is the length of the entire queue in bytes
  6787. * len is the length of the current message
  6788. * data_len is the length of the current message's data payload
  6789. * header_len is the length of the current message's header */
  6790. size_t i, len, mask_len = 0, data_len = 0, header_len, body_len;
  6791. /* "The masking key is a 32-bit value chosen at random by the client."
  6792. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  6793. */
  6794. unsigned char mask[4];
  6795. /* data points to the place where the message is stored when passed to the
  6796. * websocket_data callback. This is either mem on the stack, or a
  6797. * dynamically allocated buffer if it is too large. */
  6798. char mem[4096];
  6799. char *data = mem;
  6800. unsigned char mop; /* mask flag and opcode */
  6801. double timeout = -1.0;
  6802. if (conn->ctx->config[WEBSOCKET_TIMEOUT]) {
  6803. timeout = atoi(conn->ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  6804. }
  6805. if ((timeout <= 0.0) && (conn->ctx->config[REQUEST_TIMEOUT])) {
  6806. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  6807. }
  6808. mg_set_thread_name("wsock");
  6809. /* Loop continuously, reading messages from the socket, invoking the
  6810. * callback, and waiting repeatedly until an error occurs. */
  6811. while (!conn->ctx->stop_flag) {
  6812. header_len = 0;
  6813. assert(conn->data_len >= conn->request_len);
  6814. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  6815. len = buf[1] & 127;
  6816. mask_len = buf[1] & 128 ? 4 : 0;
  6817. if (len < 126 && body_len >= mask_len) {
  6818. data_len = len;
  6819. header_len = 2 + mask_len;
  6820. } else if (len == 126 && body_len >= 4 + mask_len) {
  6821. header_len = 4 + mask_len;
  6822. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  6823. } else if (body_len >= 10 + mask_len) {
  6824. header_len = 10 + mask_len;
  6825. data_len =
  6826. (((uint64_t)ntohl(*(uint32_t *)(void *)&buf[2])) << 32) +
  6827. ntohl(*(uint32_t *)(void *)&buf[6]);
  6828. }
  6829. }
  6830. if (header_len > 0 && body_len >= header_len) {
  6831. /* Allocate space to hold websocket payload */
  6832. data = mem;
  6833. if (data_len > sizeof(mem)) {
  6834. data = (char *)mg_malloc(data_len);
  6835. if (data == NULL) {
  6836. /* Allocation failed, exit the loop and then close the
  6837. * connection */
  6838. mg_cry(conn, "websocket out of memory; closing connection");
  6839. break;
  6840. }
  6841. }
  6842. /* Copy the mask before we shift the queue and destroy it */
  6843. if (mask_len > 0) {
  6844. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  6845. } else {
  6846. memset(mask, 0, sizeof(mask));
  6847. }
  6848. /* Read frame payload from the first message in the queue into
  6849. * data and advance the queue by moving the memory in place. */
  6850. assert(body_len >= header_len);
  6851. if (data_len + header_len > body_len) {
  6852. mop = buf[0]; /* current mask and opcode */
  6853. /* Overflow case */
  6854. len = body_len - header_len;
  6855. memcpy(data, buf + header_len, len);
  6856. error = 0;
  6857. while (len < data_len) {
  6858. n = pull(
  6859. NULL, conn, data + len, (int)(data_len - len), timeout);
  6860. if (n <= 0) {
  6861. error = 1;
  6862. break;
  6863. }
  6864. len += (size_t)n;
  6865. }
  6866. if (error) {
  6867. mg_cry(conn, "Websocket pull failed; closing connection");
  6868. break;
  6869. }
  6870. conn->data_len = conn->request_len;
  6871. } else {
  6872. mop = buf[0]; /* current mask and opcode, overwritten by
  6873. * memmove() */
  6874. /* Length of the message being read at the front of the
  6875. * queue */
  6876. len = data_len + header_len;
  6877. /* Copy the data payload into the data pointer for the
  6878. * callback */
  6879. memcpy(data, buf + header_len, data_len);
  6880. /* Move the queue forward len bytes */
  6881. memmove(buf, buf + len, body_len - len);
  6882. /* Mark the queue as advanced */
  6883. conn->data_len -= (int)len;
  6884. }
  6885. /* Apply mask if necessary */
  6886. if (mask_len > 0) {
  6887. for (i = 0; i < data_len; ++i) {
  6888. data[i] ^= mask[i & 3];
  6889. }
  6890. }
  6891. /* Exit the loop if callback signals to exit (server side),
  6892. * or "connection close" opcode received (client side). */
  6893. exit_by_callback = 0;
  6894. if ((ws_data_handler != NULL) &&
  6895. !ws_data_handler(conn, mop, data, data_len, callback_data)) {
  6896. exit_by_callback = 1;
  6897. }
  6898. if (data != mem) {
  6899. mg_free(data);
  6900. }
  6901. if (exit_by_callback ||
  6902. ((mop & 0xf) == WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  6903. /* Opcode == 8, connection close */
  6904. break;
  6905. }
  6906. /* Not breaking the loop, process next websocket frame. */
  6907. } else {
  6908. /* Read from the socket into the next available location in the
  6909. * message queue. */
  6910. if ((n = pull(NULL,
  6911. conn,
  6912. conn->buf + conn->data_len,
  6913. conn->buf_size - conn->data_len,
  6914. timeout)) <= 0) {
  6915. /* Error, no bytes read */
  6916. break;
  6917. }
  6918. conn->data_len += n;
  6919. }
  6920. }
  6921. mg_set_thread_name("worker");
  6922. }
  6923. int mg_websocket_write(struct mg_connection *conn,
  6924. int opcode,
  6925. const char *data,
  6926. size_t dataLen)
  6927. {
  6928. unsigned char header[10];
  6929. size_t headerLen = 1;
  6930. int retval = -1;
  6931. header[0] = 0x80 + (opcode & 0xF);
  6932. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  6933. if (dataLen < 126) {
  6934. /* inline 7-bit length field */
  6935. header[1] = (unsigned char)dataLen;
  6936. headerLen = 2;
  6937. } else if (dataLen <= 0xFFFF) {
  6938. /* 16-bit length field */
  6939. header[1] = 126;
  6940. *(uint16_t *)(void *)(header + 2) = htons((uint16_t)dataLen);
  6941. headerLen = 4;
  6942. } else {
  6943. /* 64-bit length field */
  6944. header[1] = 127;
  6945. *(uint32_t *)(void *)(header + 2) = htonl((uint64_t)dataLen >> 32);
  6946. *(uint32_t *)(void *)(header + 6) = htonl(dataLen & 0xFFFFFFFF);
  6947. headerLen = 10;
  6948. }
  6949. /* Note that POSIX/Winsock's send() is threadsafe
  6950. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  6951. * but mongoose's mg_printf/mg_write is not (because of the loop in
  6952. * push(), although that is only a problem if the packet is large or
  6953. * outgoing buffer is full). */
  6954. (void)mg_lock_connection(conn);
  6955. retval = mg_write(conn, header, headerLen);
  6956. retval = mg_write(conn, data, dataLen);
  6957. mg_unlock_connection(conn);
  6958. return retval;
  6959. }
  6960. static void
  6961. handle_websocket_request(struct mg_connection *conn,
  6962. const char *path,
  6963. int is_callback_resource,
  6964. mg_websocket_connect_handler ws_connect_handler,
  6965. mg_websocket_ready_handler ws_ready_handler,
  6966. mg_websocket_data_handler ws_data_handler,
  6967. mg_websocket_close_handler ws_close_handler,
  6968. void *cbData)
  6969. {
  6970. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  6971. int lua_websock = 0;
  6972. #if !defined(USE_LUA)
  6973. (void)path;
  6974. #endif
  6975. /* Step 1: Check websocket protocol version. */
  6976. if (version == NULL || strcmp(version, "13") != 0) {
  6977. /* Reject wrong versions */
  6978. send_http_error(conn, 426, "%s", "Protocol upgrade required");
  6979. return;
  6980. }
  6981. /* Step 2: If a callback is responsible, call it. */
  6982. if (is_callback_resource) {
  6983. if (ws_connect_handler != NULL &&
  6984. ws_connect_handler(conn, cbData) != 0) {
  6985. /* C callback has returned non-zero, do not proceed with handshake.
  6986. */
  6987. /* Note that C callbacks are no longer called when Lua is
  6988. * responsible, so C can no longer filter callbacks for Lua. */
  6989. return;
  6990. }
  6991. }
  6992. #if defined(USE_LUA)
  6993. /* Step 3: No callback. Check if Lua is responsible. */
  6994. else {
  6995. /* Step 3.1: Check if Lua is responsible. */
  6996. if (conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  6997. lua_websock = match_prefix(
  6998. conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  6999. strlen(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  7000. path);
  7001. }
  7002. if (lua_websock) {
  7003. /* Step 3.2: Lua is responsible: call it. */
  7004. conn->lua_websocket_state = lua_websocket_new(path, conn);
  7005. if (!conn->lua_websocket_state) {
  7006. /* Lua rejected the new client */
  7007. return;
  7008. }
  7009. }
  7010. }
  7011. #endif
  7012. /* Step 4: Check if there is a responsible websocket handler. */
  7013. if (!is_callback_resource && !lua_websock) {
  7014. /* There is no callback, an Lua is not responsible either. */
  7015. /* Reply with a 404 Not Found or with nothing at all?
  7016. * TODO (mid): check the websocket standards, how to reply to
  7017. * requests to invalid websocket addresses. */
  7018. send_http_error(conn, 404, "%s", "Not found");
  7019. return;
  7020. }
  7021. /* Step 5: The websocket connection has been accepted */
  7022. if (!send_websocket_handshake(conn)) {
  7023. send_http_error(conn, 500, "%s", "Websocket handshake failed");
  7024. return;
  7025. }
  7026. /* Step 6: Call the ready handler */
  7027. if (is_callback_resource) {
  7028. if (ws_ready_handler != NULL) {
  7029. ws_ready_handler(conn, cbData);
  7030. }
  7031. #if defined(USE_LUA)
  7032. } else if (lua_websock) {
  7033. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  7034. /* the ready handler returned false */
  7035. return;
  7036. }
  7037. #endif
  7038. }
  7039. /* Step 7: Enter the read loop */
  7040. if (is_callback_resource) {
  7041. read_websocket(conn, ws_data_handler, cbData);
  7042. #if defined(USE_LUA)
  7043. } else if (lua_websock) {
  7044. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  7045. #endif
  7046. }
  7047. /* Step 8: Call the close handler */
  7048. if (ws_close_handler) {
  7049. ws_close_handler(conn, cbData);
  7050. }
  7051. }
  7052. static int is_websocket_protocol(const struct mg_connection *conn)
  7053. {
  7054. const char *host, *upgrade, *connection, *version, *key;
  7055. upgrade = mg_get_header(conn, "Upgrade");
  7056. if (upgrade == NULL) {
  7057. return 0; /* fail early, don't waste time checking other header fields
  7058. */
  7059. }
  7060. if (!mg_strcasestr(upgrade, "websocket")) {
  7061. return 0;
  7062. }
  7063. connection = mg_get_header(conn, "Connection");
  7064. if (connection == NULL) {
  7065. return 0;
  7066. }
  7067. if (!mg_strcasestr(connection, "upgrade")) {
  7068. return 0;
  7069. }
  7070. host = mg_get_header(conn, "Host");
  7071. key = mg_get_header(conn, "Sec-WebSocket-Key");
  7072. version = mg_get_header(conn, "Sec-WebSocket-Version");
  7073. return (host != NULL && key != NULL && version != NULL);
  7074. }
  7075. #endif /* !USE_WEBSOCKET */
  7076. static int isbyte(int n)
  7077. {
  7078. return n >= 0 && n <= 255;
  7079. }
  7080. static int parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  7081. {
  7082. int n, a, b, c, d, slash = 32, len = 0;
  7083. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5 ||
  7084. sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) &&
  7085. isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0 &&
  7086. slash < 33) {
  7087. len = n;
  7088. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8) |
  7089. (uint32_t)d;
  7090. *mask = slash ? 0xffffffffU << (32 - slash) : 0;
  7091. }
  7092. return len;
  7093. }
  7094. static int set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  7095. {
  7096. int throttle = 0;
  7097. struct vec vec, val;
  7098. uint32_t net, mask;
  7099. char mult;
  7100. double v;
  7101. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  7102. mult = ',';
  7103. if (sscanf(val.ptr, "%lf%c", &v, &mult) < 1 || v < 0 ||
  7104. (lowercase(&mult) != 'k' && lowercase(&mult) != 'm' &&
  7105. mult != ',')) {
  7106. continue;
  7107. }
  7108. v *= lowercase(&mult) == 'k' ? 1024 : lowercase(&mult) == 'm' ? 1048576
  7109. : 1;
  7110. if (vec.len == 1 && vec.ptr[0] == '*') {
  7111. throttle = (int)v;
  7112. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  7113. if ((remote_ip & mask) == net) {
  7114. throttle = (int)v;
  7115. }
  7116. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  7117. throttle = (int)v;
  7118. }
  7119. }
  7120. return throttle;
  7121. }
  7122. static uint32_t get_remote_ip(const struct mg_connection *conn)
  7123. {
  7124. if (!conn) {
  7125. return 0;
  7126. }
  7127. return ntohl(*(uint32_t *)&conn->client.rsa.sin.sin_addr);
  7128. }
  7129. int mg_upload(struct mg_connection *conn, const char *destination_dir)
  7130. {
  7131. /* TODO (high): completely rewrite this function. See issue #180. */
  7132. /* TODO (mid): set a timeout */
  7133. const char *content_type_header, *boundary_start, *sc;
  7134. char *s;
  7135. char buf[MG_BUF_LEN], path[PATH_MAX], tmp_path[PATH_MAX];
  7136. char fname[1024], boundary[100];
  7137. FILE *fp;
  7138. int bl, n, i, headers_len, boundary_len, eof, truncated;
  7139. int len = 0, num_uploaded_files = 0;
  7140. struct mg_request_info part_request_info;
  7141. /* Request looks like this:
  7142. *
  7143. * POST /upload HTTP/1.1
  7144. * Host: 127.0.0.1:8080
  7145. * Content-Length: 244894
  7146. * Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryRVr
  7147. *
  7148. * ------WebKitFormBoundaryRVr
  7149. * Content-Disposition: form-data; name="file"; filename="accum.png"
  7150. * Content-Type: image/png
  7151. *
  7152. * <89>PNG
  7153. * <PNG DATA>
  7154. * ------WebKitFormBoundaryRVr */
  7155. /* Extract boundary string from the Content-Type header */
  7156. if ((content_type_header = mg_get_header(conn, "Content-Type")) == NULL ||
  7157. (boundary_start = mg_strcasestr(content_type_header, "boundary=")) ==
  7158. NULL ||
  7159. (sscanf(boundary_start, "boundary=\"%99[^\"]\"", boundary) == 0 &&
  7160. sscanf(boundary_start, "boundary=%99s", boundary) == 0) ||
  7161. boundary[0] == '\0') {
  7162. return num_uploaded_files;
  7163. }
  7164. boundary[99] = 0;
  7165. boundary_len = (int)strlen(boundary);
  7166. bl = boundary_len + 4; /* \r\n--<boundary> */
  7167. for (;;) {
  7168. /* Pull in headers */
  7169. /* assert(len >= 0 && len <= (int) sizeof(buf)); */
  7170. if ((len < 0) || (len > (int)sizeof(buf))) {
  7171. break;
  7172. }
  7173. while ((n = mg_read(conn, buf + len, sizeof(buf) - (size_t)len)) > 0) {
  7174. len += n;
  7175. /* assert(len <= (int) sizeof(buf)); */
  7176. if (len > (int)sizeof(buf)) {
  7177. break;
  7178. }
  7179. }
  7180. if ((headers_len = get_request_len(buf, len)) <= 0) {
  7181. break;
  7182. }
  7183. /* terminate header */
  7184. buf[headers_len - 1] = 0;
  7185. /* Scan for the boundary string and skip it */
  7186. if (buf[0] == '-' && buf[1] == '-' &&
  7187. !memcmp(buf + 2, boundary, (size_t)boundary_len)) {
  7188. s = &buf[bl];
  7189. } else {
  7190. s = &buf[2];
  7191. }
  7192. /* Get headers for this part of the multipart message */
  7193. memset(&part_request_info, 0, sizeof(part_request_info));
  7194. parse_http_headers(&s, &part_request_info);
  7195. /* assert(&buf[headers_len-1] == s); */
  7196. if (&buf[headers_len - 1] != s) {
  7197. break;
  7198. }
  7199. /* Fetch file name. */
  7200. sc = get_header(&part_request_info, "Content-Disposition");
  7201. if (!sc) {
  7202. /* invalid part of a multipart message */
  7203. break;
  7204. }
  7205. sc = strstr(sc, "filename");
  7206. if (!sc) {
  7207. /* no filename set */
  7208. break;
  7209. }
  7210. sc += 8; /* skip "filename" */
  7211. fname[0] = '\0';
  7212. IGNORE_UNUSED_RESULT(sscanf(sc, " = \"%1023[^\"]", fname));
  7213. fname[1023] = 0;
  7214. /* Give up if the headers are not what we expect */
  7215. if (fname[0] == '\0') {
  7216. break;
  7217. }
  7218. /* Construct destination file name. Do not allow paths to have
  7219. * slashes. */
  7220. if ((s = strrchr(fname, '/')) == NULL &&
  7221. (s = strrchr(fname, '\\')) == NULL) {
  7222. s = fname;
  7223. } else {
  7224. s++;
  7225. }
  7226. /* There data is written to a temporary file first. */
  7227. /* Different users should use a different destination_dir. */
  7228. mg_snprintf(conn,
  7229. &truncated,
  7230. path,
  7231. sizeof(path) - 1,
  7232. "%s/%s",
  7233. destination_dir,
  7234. s);
  7235. /* TODO(high): kick client on buffer overflow */
  7236. strcpy(tmp_path, path);
  7237. strcat(tmp_path, "~");
  7238. /* We open the file with exclusive lock held. This guarantee us
  7239. * there is no other thread can save into the same file
  7240. * simultaneously. */
  7241. fp = NULL;
  7242. /* Open file in binary mode. */
  7243. if ((fp = fopen(tmp_path, "wb")) == NULL) {
  7244. break;
  7245. }
  7246. /* Move data to the beginning of the buffer */
  7247. /* part_request_info is no longer valid after this operation */
  7248. /* assert(len >= headers_len); */
  7249. if (len < headers_len) {
  7250. break;
  7251. }
  7252. memmove(buf, &buf[headers_len], (size_t)(len - headers_len));
  7253. len -= headers_len;
  7254. /* Read POST data, write into file until boundary is found. */
  7255. eof = n = 0;
  7256. do {
  7257. len += n;
  7258. for (i = 0; i < len - bl; i++) {
  7259. if (!memcmp(&buf[i], "\r\n--", 4) &&
  7260. !memcmp(&buf[i + 4], boundary, (size_t)boundary_len)) {
  7261. /* Found boundary, that's the end of file data. */
  7262. fwrite(buf, 1, (size_t)i, fp);
  7263. eof = 1;
  7264. memmove(buf, &buf[i + bl], (size_t)(len - (i + bl)));
  7265. len -= i + bl;
  7266. break;
  7267. }
  7268. }
  7269. if (!eof && len > bl) {
  7270. fwrite(buf, 1, (size_t)(len - bl), fp);
  7271. memmove(buf, &buf[len - bl], (size_t)bl);
  7272. len = bl;
  7273. }
  7274. if (!eof) {
  7275. n = mg_read(conn, buf + len, sizeof(buf) - ((size_t)(len)));
  7276. }
  7277. } while (!eof && (n > 0));
  7278. fclose(fp);
  7279. if (eof) {
  7280. remove(path);
  7281. rename(tmp_path, path);
  7282. num_uploaded_files++;
  7283. if (conn && conn->ctx && conn->ctx->callbacks.upload != NULL) {
  7284. conn->ctx->callbacks.upload(conn, path);
  7285. }
  7286. } else {
  7287. remove(tmp_path);
  7288. }
  7289. }
  7290. return num_uploaded_files;
  7291. }
  7292. static int get_first_ssl_listener_index(const struct mg_context *ctx)
  7293. {
  7294. unsigned int i;
  7295. int idx = -1;
  7296. if (ctx) {
  7297. for (i = 0; idx == -1 && i < ctx->num_listening_sockets; i++) {
  7298. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  7299. }
  7300. }
  7301. return idx;
  7302. }
  7303. static void redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  7304. {
  7305. char host[1025];
  7306. const char *host_header;
  7307. size_t hostlen;
  7308. host_header = mg_get_header(conn, "Host");
  7309. hostlen = sizeof(host);
  7310. if (host_header != NULL) {
  7311. char *pos;
  7312. mg_strlcpy(host, host_header, hostlen);
  7313. host[hostlen - 1] = '\0';
  7314. pos = strchr(host, ':');
  7315. if (pos != NULL) {
  7316. *pos = '\0';
  7317. }
  7318. } else {
  7319. /* Cannot get host from the Host: header.
  7320. * Fallback to our IP address. */
  7321. if (conn) {
  7322. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  7323. }
  7324. }
  7325. /* Send host, port, uri and (if it exists) ?query_string */
  7326. if (conn) {
  7327. mg_printf(conn,
  7328. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  7329. host,
  7330. (int)ntohs(
  7331. conn->ctx->listening_sockets[ssl_index].lsa.sin.sin_port),
  7332. conn->request_info.rel_uri,
  7333. (conn->request_info.query_string == NULL) ? "" : "?",
  7334. (conn->request_info.query_string == NULL)
  7335. ? ""
  7336. : conn->request_info.query_string);
  7337. }
  7338. }
  7339. static void
  7340. mg_set_request_handler_type(struct mg_context *ctx,
  7341. const char *uri,
  7342. int is_websocket_handler,
  7343. int is_delete_request,
  7344. mg_request_handler handler,
  7345. mg_websocket_connect_handler connect_handler,
  7346. mg_websocket_ready_handler ready_handler,
  7347. mg_websocket_data_handler data_handler,
  7348. mg_websocket_close_handler close_handler,
  7349. void *cbdata)
  7350. {
  7351. struct mg_request_handler_info *tmp_rh, **lastref;
  7352. size_t urilen = strlen(uri);
  7353. if (is_websocket_handler) {
  7354. /* assert(handler == NULL); */
  7355. /* assert(is_delete_request || connect_handler!=NULL ||
  7356. * ready_handler!=NULL || data_handler!=NULL ||
  7357. * close_handler!=NULL);
  7358. */
  7359. if (handler != NULL) {
  7360. return;
  7361. }
  7362. if (!is_delete_request && connect_handler == NULL &&
  7363. ready_handler == NULL && data_handler == NULL &&
  7364. close_handler == NULL) {
  7365. return;
  7366. }
  7367. } else {
  7368. /* assert(connect_handler==NULL && ready_handler==NULL &&
  7369. * data_handler==NULL && close_handler==NULL); */
  7370. /* assert(is_delete_request || (handler!=NULL));
  7371. */
  7372. if (connect_handler != NULL || ready_handler != NULL ||
  7373. data_handler != NULL || close_handler != NULL) {
  7374. return;
  7375. }
  7376. if (!is_delete_request && (handler == NULL)) {
  7377. return;
  7378. }
  7379. }
  7380. if (!ctx) {
  7381. return;
  7382. }
  7383. mg_lock_context(ctx);
  7384. /* first try to find an existing handler */
  7385. lastref = &(ctx->request_handlers);
  7386. for (tmp_rh = ctx->request_handlers; tmp_rh != NULL;
  7387. tmp_rh = tmp_rh->next) {
  7388. if (tmp_rh->is_websocket_handler == is_websocket_handler) {
  7389. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  7390. if (!is_delete_request) {
  7391. /* update existing handler */
  7392. if (!is_websocket_handler) {
  7393. tmp_rh->handler = handler;
  7394. } else {
  7395. tmp_rh->connect_handler = connect_handler;
  7396. tmp_rh->ready_handler = ready_handler;
  7397. tmp_rh->data_handler = data_handler;
  7398. tmp_rh->close_handler = close_handler;
  7399. }
  7400. tmp_rh->cbdata = cbdata;
  7401. } else {
  7402. /* remove existing handler */
  7403. *lastref = tmp_rh->next;
  7404. mg_free(tmp_rh->uri);
  7405. mg_free(tmp_rh);
  7406. }
  7407. mg_unlock_context(ctx);
  7408. return;
  7409. }
  7410. }
  7411. lastref = &(tmp_rh->next);
  7412. }
  7413. if (is_delete_request) {
  7414. /* no handler to set, this was a remove request to a non-existing
  7415. * handler */
  7416. mg_unlock_context(ctx);
  7417. return;
  7418. }
  7419. tmp_rh = (struct mg_request_handler_info *)mg_calloc(
  7420. sizeof(struct mg_request_handler_info), 1);
  7421. if (tmp_rh == NULL) {
  7422. mg_unlock_context(ctx);
  7423. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  7424. return;
  7425. }
  7426. tmp_rh->uri = mg_strdup(uri);
  7427. if (!tmp_rh->uri) {
  7428. mg_unlock_context(ctx);
  7429. mg_free(tmp_rh);
  7430. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  7431. return;
  7432. }
  7433. tmp_rh->uri_len = urilen;
  7434. if (!is_websocket_handler) {
  7435. tmp_rh->handler = handler;
  7436. } else {
  7437. tmp_rh->connect_handler = connect_handler;
  7438. tmp_rh->ready_handler = ready_handler;
  7439. tmp_rh->data_handler = data_handler;
  7440. tmp_rh->close_handler = close_handler;
  7441. }
  7442. tmp_rh->cbdata = cbdata;
  7443. tmp_rh->is_websocket_handler = is_websocket_handler;
  7444. tmp_rh->next = NULL;
  7445. *lastref = tmp_rh;
  7446. mg_unlock_context(ctx);
  7447. }
  7448. void mg_set_request_handler(struct mg_context *ctx,
  7449. const char *uri,
  7450. mg_request_handler handler,
  7451. void *cbdata)
  7452. {
  7453. mg_set_request_handler_type(
  7454. ctx, uri, 0, handler == NULL, handler, NULL, NULL, NULL, NULL, cbdata);
  7455. }
  7456. void mg_set_websocket_handler(struct mg_context *ctx,
  7457. const char *uri,
  7458. mg_websocket_connect_handler connect_handler,
  7459. mg_websocket_ready_handler ready_handler,
  7460. mg_websocket_data_handler data_handler,
  7461. mg_websocket_close_handler close_handler,
  7462. void *cbdata)
  7463. {
  7464. int is_delete_request = (connect_handler == NULL) &&
  7465. (ready_handler == NULL) && (data_handler == NULL) &&
  7466. (close_handler == NULL);
  7467. mg_set_request_handler_type(ctx,
  7468. uri,
  7469. 1,
  7470. is_delete_request,
  7471. NULL,
  7472. connect_handler,
  7473. ready_handler,
  7474. data_handler,
  7475. close_handler,
  7476. cbdata);
  7477. }
  7478. static int get_request_handler(struct mg_connection *conn,
  7479. int is_websocket_request,
  7480. mg_request_handler *handler,
  7481. mg_websocket_connect_handler *connect_handler,
  7482. mg_websocket_ready_handler *ready_handler,
  7483. mg_websocket_data_handler *data_handler,
  7484. mg_websocket_close_handler *close_handler,
  7485. void **cbdata)
  7486. {
  7487. const struct mg_request_info *request_info = mg_get_request_info(conn);
  7488. if (request_info) {
  7489. const char *uri = request_info->rel_uri;
  7490. size_t urilen = strlen(uri);
  7491. struct mg_request_handler_info *tmp_rh;
  7492. if (!conn || !conn->ctx) {
  7493. return 0;
  7494. }
  7495. mg_lock_context(conn->ctx);
  7496. /* first try for an exact match */
  7497. for (tmp_rh = conn->ctx->request_handlers; tmp_rh != NULL;
  7498. tmp_rh = tmp_rh->next) {
  7499. if (tmp_rh->is_websocket_handler == is_websocket_request) {
  7500. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  7501. if (is_websocket_request) {
  7502. *connect_handler = tmp_rh->connect_handler;
  7503. *ready_handler = tmp_rh->ready_handler;
  7504. *data_handler = tmp_rh->data_handler;
  7505. *close_handler = tmp_rh->close_handler;
  7506. } else {
  7507. *handler = tmp_rh->handler;
  7508. }
  7509. *cbdata = tmp_rh->cbdata;
  7510. mg_unlock_context(conn->ctx);
  7511. return 1;
  7512. }
  7513. }
  7514. }
  7515. /* next try for a partial match, we will accept uri/something */
  7516. for (tmp_rh = conn->ctx->request_handlers; tmp_rh != NULL;
  7517. tmp_rh = tmp_rh->next) {
  7518. if (tmp_rh->is_websocket_handler == is_websocket_request) {
  7519. if (tmp_rh->uri_len < urilen && uri[tmp_rh->uri_len] == '/' &&
  7520. memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0) {
  7521. if (is_websocket_request) {
  7522. *connect_handler = tmp_rh->connect_handler;
  7523. *ready_handler = tmp_rh->ready_handler;
  7524. *data_handler = tmp_rh->data_handler;
  7525. *close_handler = tmp_rh->close_handler;
  7526. } else {
  7527. *handler = tmp_rh->handler;
  7528. }
  7529. *cbdata = tmp_rh->cbdata;
  7530. mg_unlock_context(conn->ctx);
  7531. return 1;
  7532. }
  7533. }
  7534. }
  7535. /* finally try for pattern match */
  7536. for (tmp_rh = conn->ctx->request_handlers; tmp_rh != NULL;
  7537. tmp_rh = tmp_rh->next) {
  7538. if (tmp_rh->is_websocket_handler == is_websocket_request) {
  7539. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  7540. if (is_websocket_request) {
  7541. *connect_handler = tmp_rh->connect_handler;
  7542. *ready_handler = tmp_rh->ready_handler;
  7543. *data_handler = tmp_rh->data_handler;
  7544. *close_handler = tmp_rh->close_handler;
  7545. } else {
  7546. *handler = tmp_rh->handler;
  7547. }
  7548. *cbdata = tmp_rh->cbdata;
  7549. mg_unlock_context(conn->ctx);
  7550. return 1;
  7551. }
  7552. }
  7553. }
  7554. mg_unlock_context(conn->ctx);
  7555. }
  7556. return 0; /* none found */
  7557. }
  7558. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  7559. static int
  7560. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  7561. void *cbdata)
  7562. {
  7563. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  7564. if (pcallbacks->websocket_connect) {
  7565. return pcallbacks->websocket_connect(conn);
  7566. }
  7567. /* No handler set - assume "OK" */
  7568. return 0;
  7569. }
  7570. static void deprecated_websocket_ready_wrapper(struct mg_connection *conn,
  7571. void *cbdata)
  7572. {
  7573. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  7574. if (pcallbacks->websocket_ready) {
  7575. pcallbacks->websocket_ready(conn);
  7576. }
  7577. }
  7578. static int deprecated_websocket_data_wrapper(struct mg_connection *conn,
  7579. int bits,
  7580. char *data,
  7581. size_t len,
  7582. void *cbdata)
  7583. {
  7584. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  7585. if (pcallbacks->websocket_data) {
  7586. return pcallbacks->websocket_data(conn, bits, data, len);
  7587. }
  7588. /* No handler set - assume "OK" */
  7589. return 1;
  7590. }
  7591. #endif
  7592. /* This is the heart of the Civetweb's logic.
  7593. * This function is called when the request is read, parsed and validated,
  7594. * and Civetweb must decide what action to take: serve a file, or
  7595. * a directory, or call embedded function, etcetera. */
  7596. static void handle_request(struct mg_connection *conn)
  7597. {
  7598. if (conn) {
  7599. struct mg_request_info *ri = &conn->request_info;
  7600. char path[PATH_MAX];
  7601. int uri_len, ssl_index;
  7602. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  7603. is_put_or_delete_request = 0, is_callback_resource = 0;
  7604. int i;
  7605. struct file file = STRUCT_FILE_INITIALIZER;
  7606. mg_request_handler callback_handler = NULL;
  7607. mg_websocket_connect_handler ws_connect_handler = NULL;
  7608. mg_websocket_ready_handler ws_ready_handler = NULL;
  7609. mg_websocket_data_handler ws_data_handler = NULL;
  7610. mg_websocket_close_handler ws_close_handler = NULL;
  7611. void *callback_data = NULL;
  7612. #if !defined(NO_FILES)
  7613. time_t curtime = time(NULL);
  7614. char date[64];
  7615. #endif
  7616. path[0] = 0;
  7617. if (!ri) {
  7618. return;
  7619. }
  7620. /* 1. get the request url */
  7621. /* 1.1. split into url and query string */
  7622. if ((conn->request_info.query_string = strchr(ri->request_uri, '?')) !=
  7623. NULL) {
  7624. *((char *)conn->request_info.query_string++) = '\0';
  7625. }
  7626. uri_len = (int)strlen(ri->rel_uri);
  7627. /* 1.2. decode url (if config says so) */
  7628. if (should_decode_url(conn)) {
  7629. mg_url_decode(
  7630. ri->rel_uri, uri_len, (char *)ri->rel_uri, uri_len + 1, 0);
  7631. }
  7632. /* 1.3. clean URIs, so a path like allowed_dir/../forbidden_file is not
  7633. * possible */
  7634. remove_double_dots_and_double_slashes((char *)ri->rel_uri);
  7635. /* step 1. completed, the url is known now */
  7636. DEBUG_TRACE("URL: %s", ri->rel_uri);
  7637. /* 2. do a https redirect, if required */
  7638. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  7639. ssl_index = get_first_ssl_listener_index(conn->ctx);
  7640. if (ssl_index >= 0) {
  7641. redirect_to_https_port(conn, ssl_index);
  7642. } else {
  7643. /* A http to https forward port has been specified,
  7644. * but no https port to forward to. */
  7645. send_http_error(conn,
  7646. 503,
  7647. "%s",
  7648. "Error: SSL forward not configured properly");
  7649. mg_cry(conn, "Can not redirect to SSL, no SSL port available");
  7650. }
  7651. return;
  7652. }
  7653. /* 3. if this ip has limited speed, set it for this connection */
  7654. conn->throttle = set_throttle(
  7655. conn->ctx->config[THROTTLE], get_remote_ip(conn), ri->rel_uri);
  7656. /* 4. call a "handle everything" callback, if registered */
  7657. if (conn->ctx->callbacks.begin_request != NULL) {
  7658. /* Note that since V1.7 the "begin_request" function is called
  7659. * before an authorization check. If an authorization check is
  7660. * required, use a request_handler instead. */
  7661. i = conn->ctx->callbacks.begin_request(conn);
  7662. if (i > 0) {
  7663. /* callback already processed the request. Store the
  7664. return value as a status code for the access log. */
  7665. conn->status_code = i;
  7666. return;
  7667. } else if (i == 0) {
  7668. /* civetweb should process the request */
  7669. } else {
  7670. /* unspecified - may change with the next version */
  7671. return;
  7672. }
  7673. }
  7674. /* request not yet handled by a handler or redirect, so the request
  7675. * is processed here */
  7676. /* 5. interpret the url to find out how the request must be handled */
  7677. /* 5.1. first test, if the request targets the regular http(s)://
  7678. * protocol namespace or the websocket ws(s):// protocol namespace. */
  7679. is_websocket_request = is_websocket_protocol(conn);
  7680. /* 5.2. check if the request will be handled by a callback */
  7681. if (get_request_handler(conn,
  7682. is_websocket_request,
  7683. &callback_handler,
  7684. &ws_connect_handler,
  7685. &ws_ready_handler,
  7686. &ws_data_handler,
  7687. &ws_close_handler,
  7688. &callback_data)) {
  7689. /* 5.2.1. A callback will handle this request. All requests handled
  7690. * by a callback have to be considered as requests to a script
  7691. * resource. */
  7692. is_callback_resource = 1;
  7693. is_script_resource = 1;
  7694. is_put_or_delete_request = is_put_or_delete_method(conn);
  7695. } else {
  7696. no_callback_resource:
  7697. /* 5.2.2. No callback is responsible for this request. The URI
  7698. * addresses a file based resource (static content or Lua/cgi
  7699. * scripts in the file system). */
  7700. is_callback_resource = 0;
  7701. interpret_uri(conn,
  7702. path,
  7703. sizeof(path),
  7704. &file,
  7705. &is_found,
  7706. &is_script_resource,
  7707. &is_websocket_request,
  7708. &is_put_or_delete_request);
  7709. }
  7710. /* 6. authorization check */
  7711. if (is_put_or_delete_request && !is_script_resource &&
  7712. !is_callback_resource) {
  7713. /* 6.1. this request is a PUT/DELETE to a real file */
  7714. /* 6.1.1. thus, the server must have real files */
  7715. #if defined(NO_FILES)
  7716. if (1) {
  7717. #else
  7718. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  7719. #endif
  7720. /* This server does not have any real files, thus the
  7721. * PUT/DELETE methods are not valid. */
  7722. send_http_error(conn,
  7723. 405,
  7724. "%s method not allowed",
  7725. conn->request_info.request_method);
  7726. return;
  7727. }
  7728. #if !defined(NO_FILES)
  7729. /* 6.1.2. Check if put authorization for static files is available.
  7730. */
  7731. if (!is_authorized_for_put(conn)) {
  7732. send_authorization_request(conn);
  7733. return;
  7734. }
  7735. #endif
  7736. } else {
  7737. /* 6.2. This is either a OPTIONS, GET, HEAD or POST request,
  7738. * or it is a PUT or DELETE request to a resource that does not
  7739. * correspond to a file. Check authorization. */
  7740. if (!check_authorization(conn, path)) {
  7741. send_authorization_request(conn);
  7742. return;
  7743. }
  7744. }
  7745. /* request is authorized or does not need authorization */
  7746. /* 7. check if there are request handlers for this uri */
  7747. if (is_callback_resource) {
  7748. if (!is_websocket_request) {
  7749. i = callback_handler(conn, callback_data);
  7750. if (i > 0) {
  7751. /* Do nothing, callback has served the request. Store the
  7752. * return value as status code for the log and discard all
  7753. * data from the client not used by the callback. */
  7754. conn->status_code = i;
  7755. discard_unread_request_data(conn);
  7756. } else {
  7757. /* TODO (high): what if the handler did NOT handle the
  7758. * request */
  7759. /* The last version did handle this as a file request, but
  7760. * since a file request is not always a script resource,
  7761. * the authorization check might be different */
  7762. interpret_uri(conn,
  7763. path,
  7764. sizeof(path),
  7765. &file,
  7766. &is_found,
  7767. &is_script_resource,
  7768. &is_websocket_request,
  7769. &is_put_or_delete_request);
  7770. callback_handler = NULL;
  7771. /* TODO (very low): goto is deprecated but for the moment,
  7772. * a goto is simpler than some curious loop. */
  7773. /* The situation "callback does not handle the request"
  7774. * needs to be reconsidered anyway. */
  7775. goto no_callback_resource;
  7776. }
  7777. } else {
  7778. #if defined(USE_WEBSOCKET)
  7779. handle_websocket_request(conn,
  7780. path,
  7781. is_callback_resource,
  7782. ws_connect_handler,
  7783. ws_ready_handler,
  7784. ws_data_handler,
  7785. ws_close_handler,
  7786. callback_data);
  7787. #endif
  7788. }
  7789. return;
  7790. }
  7791. /* 8. handle websocket requests */
  7792. #if defined(USE_WEBSOCKET)
  7793. if (is_websocket_request) {
  7794. if (is_script_resource) {
  7795. /* Websocket Lua script */
  7796. handle_websocket_request(conn,
  7797. path,
  7798. 0 /* Lua Script */,
  7799. NULL,
  7800. NULL,
  7801. NULL,
  7802. NULL,
  7803. &conn->ctx->callbacks);
  7804. } else {
  7805. #if defined(MG_LEGACY_INTERFACE)
  7806. handle_websocket_request(
  7807. conn,
  7808. path,
  7809. !is_script_resource /* could be deprecated global callback */,
  7810. deprecated_websocket_connect_wrapper,
  7811. deprecated_websocket_ready_wrapper,
  7812. deprecated_websocket_data_wrapper,
  7813. NULL,
  7814. &conn->ctx->callbacks);
  7815. #else
  7816. send_http_error(conn, 404, "%s", "Not found");
  7817. #endif
  7818. }
  7819. return;
  7820. } else
  7821. #endif
  7822. #if defined(NO_FILES)
  7823. /* 9a. In case the server uses only callbacks, this uri is unknown.
  7824. * Then, all request handling ends here. */
  7825. send_http_error(conn, 404, "%s", "Not Found");
  7826. #else
  7827. /* 9b. This request is either for a static file or resource handled
  7828. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  7829. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  7830. send_http_error(conn, 404, "%s", "Not Found");
  7831. return;
  7832. }
  7833. /* 10. File is handled by a script. */
  7834. if (is_script_resource) {
  7835. handle_file_based_request(conn, path, &file);
  7836. return;
  7837. }
  7838. /* 11. Handle put/delete/mkcol requests */
  7839. if (is_put_or_delete_request) {
  7840. /* 11.1. PUT method */
  7841. if (!strcmp(ri->request_method, "PUT")) {
  7842. put_file(conn, path);
  7843. return;
  7844. }
  7845. /* 11.2. DELETE method */
  7846. if (!strcmp(ri->request_method, "DELETE")) {
  7847. delete_file(conn, path);
  7848. return;
  7849. }
  7850. /* 11.3. MKCOL method */
  7851. if (!strcmp(ri->request_method, "MKCOL")) {
  7852. mkcol(conn, path);
  7853. return;
  7854. }
  7855. /* 11.4. PATCH method
  7856. * This method is not supported for static resources,
  7857. * only for scripts (Lua, CGI) and callbacks. */
  7858. send_http_error(conn,
  7859. 405,
  7860. "%s method not allowed",
  7861. conn->request_info.request_method);
  7862. return;
  7863. }
  7864. /* 11. File does not exist, or it was configured that it should be
  7865. * hidden */
  7866. if (!is_found || (must_hide_file(conn, path))) {
  7867. send_http_error(conn, 404, "%s", "Not found");
  7868. return;
  7869. }
  7870. /* 12. Directories uris should end with a slash */
  7871. if (file.is_directory && ri->rel_uri[uri_len - 1] != '/') {
  7872. gmt_time_string(date, sizeof(date), &curtime);
  7873. mg_printf(conn,
  7874. "HTTP/1.1 301 Moved Permanently\r\n"
  7875. "Location: %s/\r\n"
  7876. "Date: %s\r\n"
  7877. "Content-Length: 0\r\n"
  7878. "Connection: %s\r\n\r\n",
  7879. ri->request_uri,
  7880. date,
  7881. suggest_connection_header(conn));
  7882. return;
  7883. }
  7884. /* 13. Handle other methods than GET/HEAD */
  7885. /* 13.1. Handle PROPFIND */
  7886. if (!strcmp(ri->request_method, "PROPFIND")) {
  7887. handle_propfind(conn, path, &file);
  7888. return;
  7889. }
  7890. /* 13.2. Handle OPTIONS for files */
  7891. if (!strcmp(ri->request_method, "OPTIONS")) {
  7892. /* This standard handler is only used for real files.
  7893. * Scripts should support the OPTIONS method themselves, to allow a
  7894. * maximum flexibility.
  7895. * Lua and CGI scripts may fully support CORS this way (including
  7896. * preflights). */
  7897. send_options(conn);
  7898. return;
  7899. }
  7900. /* 13.3. everything but GET and HEAD (e.g. POST) */
  7901. if (0 != strcmp(ri->request_method, "GET") &&
  7902. 0 != strcmp(ri->request_method, "HEAD")) {
  7903. send_http_error(conn,
  7904. 405,
  7905. "%s method not allowed",
  7906. conn->request_info.request_method);
  7907. return;
  7908. }
  7909. /* 14. directories */
  7910. if (file.is_directory) {
  7911. if (substitute_index_file(conn, path, sizeof(path), &file)) {
  7912. /* 14.1. use a substitute file */
  7913. /* TODO (high): substitute index may be a script resource.
  7914. * define what should be possible in this case. */
  7915. } else {
  7916. /* 14.2. no substitute file */
  7917. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  7918. "yes")) {
  7919. handle_directory_request(conn, path);
  7920. } else {
  7921. send_http_error(
  7922. conn, 403, "%s", "Error: Directory listing denied");
  7923. }
  7924. return;
  7925. }
  7926. }
  7927. handle_file_based_request(conn, path, &file);
  7928. #endif /* !defined(NO_FILES) */
  7929. #if 0
  7930. /* Perform redirect and auth checks before calling begin_request()
  7931. * handler.
  7932. * Otherwise, begin_request() would need to perform auth checks and
  7933. * redirects. */
  7934. #endif
  7935. }
  7936. return;
  7937. }
  7938. static void handle_file_based_request(struct mg_connection *conn,
  7939. const char *path,
  7940. struct file *file)
  7941. {
  7942. if (!conn || !conn->ctx) {
  7943. return;
  7944. }
  7945. if (0) {
  7946. #ifdef USE_LUA
  7947. } else if (match_prefix(
  7948. conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  7949. strlen(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  7950. path) > 0) {
  7951. /* Lua server page: an SSI like page containing mostly plain html code
  7952. * plus some tags with server generated contents. */
  7953. handle_lsp_request(conn, path, file, NULL);
  7954. } else if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  7955. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  7956. path) > 0) {
  7957. /* Lua in-server module script: a CGI like script used to generate the
  7958. * entire reply. */
  7959. mg_exec_lua_script(conn, path, NULL);
  7960. #endif
  7961. #if defined(USE_DUKTAPE)
  7962. } else if (match_prefix(
  7963. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  7964. strlen(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  7965. path) > 0) {
  7966. /* Call duktape to generate the page */
  7967. mg_exec_duktape_script(conn, path);
  7968. #endif
  7969. #if !defined(NO_CGI)
  7970. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  7971. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  7972. path) > 0) {
  7973. /* CGI scripts may support all HTTP methods */
  7974. handle_cgi_request(conn, path);
  7975. #endif /* !NO_CGI */
  7976. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  7977. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  7978. path) > 0) {
  7979. handle_ssi_file_request(conn, path, file);
  7980. } else if ((!conn->in_error_handler) && is_not_modified(conn, file)) {
  7981. /* Send 304 "Not Modified" - this must not send any body data */
  7982. send_http_error(conn, 304, "%s", "");
  7983. } else {
  7984. handle_static_file_request(conn, path, file);
  7985. }
  7986. }
  7987. static void close_all_listening_sockets(struct mg_context *ctx)
  7988. {
  7989. unsigned int i;
  7990. if (!ctx) {
  7991. return;
  7992. }
  7993. for (i = 0; i < ctx->num_listening_sockets; i++) {
  7994. closesocket(ctx->listening_sockets[i].sock);
  7995. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  7996. }
  7997. mg_free(ctx->listening_sockets);
  7998. ctx->listening_sockets = NULL;
  7999. mg_free(ctx->listening_ports);
  8000. ctx->listening_ports = NULL;
  8001. }
  8002. /* Valid listening port specification is: [ip_address:]port[s]
  8003. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 1.2.3.4:8080s
  8004. * Examples for IPv6: [::]:80, [::1]:80,
  8005. * [FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:443s
  8006. * see https://tools.ietf.org/html/rfc3513#section-2.2 */
  8007. static int parse_port_string(const struct vec *vec, struct socket *so)
  8008. {
  8009. unsigned int a, b, c, d, port;
  8010. int ch, len;
  8011. #if defined(USE_IPV6)
  8012. char buf[100] = {0};
  8013. #endif
  8014. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  8015. * Also, all-zeroes in the socket address means binding to all addresses
  8016. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  8017. memset(so, 0, sizeof(*so));
  8018. so->lsa.sin.sin_family = AF_INET;
  8019. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len) ==
  8020. 5) {
  8021. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  8022. so->lsa.sin.sin_addr.s_addr =
  8023. htonl((a << 24) | (b << 16) | (c << 8) | d);
  8024. so->lsa.sin.sin_port = htons((uint16_t)port);
  8025. #if defined(USE_IPV6)
  8026. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2 &&
  8027. mg_inet_pton(
  8028. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  8029. /* IPv6 address, examples: see above */
  8030. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton */
  8031. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  8032. #endif
  8033. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  8034. /* If only port is specified, bind to IPv4, INADDR_ANY */
  8035. so->lsa.sin.sin_port = htons((uint16_t)port);
  8036. } else {
  8037. /* Parsing failure. Make port invalid. */
  8038. port = 0;
  8039. len = 0;
  8040. }
  8041. /* sscanf and the option splitting code ensure the following condition */
  8042. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  8043. return 0;
  8044. }
  8045. ch = vec->ptr[len]; /* Next character after the port number */
  8046. so->is_ssl = (ch == 's');
  8047. so->ssl_redir = (ch == 'r');
  8048. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  8049. return is_valid_port(port) &&
  8050. (ch == '\0' || ch == 's' || ch == 'r' || ch == ',');
  8051. }
  8052. static int set_ports_option(struct mg_context *ctx)
  8053. {
  8054. const char *list;
  8055. int on = 1;
  8056. #if defined(USE_IPV6)
  8057. int off = 0;
  8058. #endif
  8059. struct vec vec;
  8060. struct socket so, *ptr;
  8061. in_port_t *portPtr;
  8062. union usa usa;
  8063. socklen_t len;
  8064. int portsTotal = 0;
  8065. int portsOk = 0;
  8066. if (!ctx) {
  8067. return 0;
  8068. }
  8069. memset(&so, 0, sizeof(so));
  8070. memset(&usa, 0, sizeof(usa));
  8071. len = sizeof(usa);
  8072. list = ctx->config[LISTENING_PORTS];
  8073. while ((list = next_option(list, &vec, NULL)) != NULL) {
  8074. portsTotal++;
  8075. if (!parse_port_string(&vec, &so)) {
  8076. mg_cry(fc(ctx),
  8077. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  8078. (int)vec.len,
  8079. vec.ptr,
  8080. portsTotal,
  8081. "[IP_ADDRESS:]PORT[s|r]");
  8082. continue;
  8083. }
  8084. if (so.is_ssl && ctx->ssl_ctx == NULL) {
  8085. mg_cry(fc(ctx),
  8086. "Cannot add SSL socket (entry %i). Is -ssl_certificate "
  8087. "option set?",
  8088. portsTotal);
  8089. continue;
  8090. }
  8091. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6)) ==
  8092. INVALID_SOCKET) {
  8093. mg_cry(fc(ctx), "cannot create socket (entry %i)", portsTotal);
  8094. continue;
  8095. }
  8096. #ifdef _WIN32
  8097. /* Windows SO_REUSEADDR lets many procs binds to a
  8098. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  8099. * if someone already has the socket -- DTL */
  8100. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  8101. * Windows might need a few seconds before
  8102. * the same port can be used again in the
  8103. * same process, so a short Sleep may be
  8104. * required between mg_stop and mg_start.
  8105. */
  8106. if (setsockopt(so.sock,
  8107. SOL_SOCKET,
  8108. SO_EXCLUSIVEADDRUSE,
  8109. (SOCK_OPT_TYPE)&on,
  8110. sizeof(on)) != 0) {
  8111. mg_cry(fc(ctx),
  8112. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  8113. portsTotal);
  8114. }
  8115. #else
  8116. if (setsockopt(so.sock,
  8117. SOL_SOCKET,
  8118. SO_REUSEADDR,
  8119. (SOCK_OPT_TYPE)&on,
  8120. sizeof(on)) != 0) {
  8121. mg_cry(fc(ctx),
  8122. "cannot set socket option SO_REUSEADDR (entry %i)",
  8123. portsTotal);
  8124. }
  8125. #endif
  8126. #if defined(USE_IPV6)
  8127. if (so.lsa.sa.sa_family == AF_INET6 &&
  8128. setsockopt(so.sock,
  8129. IPPROTO_IPV6,
  8130. IPV6_V6ONLY,
  8131. (void *)&off,
  8132. sizeof(off)) != 0) {
  8133. mg_cry(fc(ctx),
  8134. "cannot set socket option IPV6_V6ONLY (entry %i)",
  8135. portsTotal);
  8136. }
  8137. #endif
  8138. if (so.lsa.sa.sa_family == AF_INET) {
  8139. len = sizeof(so.lsa.sin);
  8140. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  8141. mg_cry(fc(ctx),
  8142. "cannot bind to %.*s: %d (%s)",
  8143. (int)vec.len,
  8144. vec.ptr,
  8145. (int)ERRNO,
  8146. strerror(errno));
  8147. closesocket(so.sock);
  8148. so.sock = INVALID_SOCKET;
  8149. continue;
  8150. }
  8151. }
  8152. #if defined(USE_IPV6)
  8153. else if (so.lsa.sa.sa_family == AF_INET6) {
  8154. len = sizeof(so.lsa.sin6);
  8155. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  8156. mg_cry(fc(ctx),
  8157. "cannot bind to IPv6 %.*s: %d (%s)",
  8158. (int)vec.len,
  8159. vec.ptr,
  8160. (int)ERRNO,
  8161. strerror(errno));
  8162. closesocket(so.sock);
  8163. so.sock = INVALID_SOCKET;
  8164. continue;
  8165. }
  8166. }
  8167. #endif
  8168. else {
  8169. mg_cry(fc(ctx),
  8170. "cannot bind: address family not supported (entry %i)",
  8171. portsTotal);
  8172. continue;
  8173. }
  8174. if (listen(so.sock, SOMAXCONN) != 0) {
  8175. mg_cry(fc(ctx),
  8176. "cannot listen to %.*s: %d (%s)",
  8177. (int)vec.len,
  8178. vec.ptr,
  8179. (int)ERRNO,
  8180. strerror(errno));
  8181. closesocket(so.sock);
  8182. so.sock = INVALID_SOCKET;
  8183. continue;
  8184. }
  8185. if (getsockname(so.sock, &(usa.sa), &len) != 0) {
  8186. int err = (int)ERRNO;
  8187. mg_cry(fc(ctx),
  8188. "call to getsockname failed %.*s: %d (%s)",
  8189. (int)vec.len,
  8190. vec.ptr,
  8191. err,
  8192. strerror(errno));
  8193. closesocket(so.sock);
  8194. so.sock = INVALID_SOCKET;
  8195. continue;
  8196. }
  8197. if ((ptr = (struct socket *)mg_realloc(
  8198. ctx->listening_sockets,
  8199. (ctx->num_listening_sockets + 1) *
  8200. sizeof(ctx->listening_sockets[0]))) == NULL) {
  8201. mg_cry(fc(ctx), "%s", "Out of memory");
  8202. closesocket(so.sock);
  8203. so.sock = INVALID_SOCKET;
  8204. continue;
  8205. }
  8206. if ((portPtr = (in_port_t *)mg_realloc(
  8207. ctx->listening_ports,
  8208. (ctx->num_listening_sockets + 1) *
  8209. sizeof(ctx->listening_ports[0]))) == NULL) {
  8210. mg_cry(fc(ctx), "%s", "Out of memory");
  8211. closesocket(so.sock);
  8212. so.sock = INVALID_SOCKET;
  8213. mg_free(ptr);
  8214. continue;
  8215. }
  8216. set_close_on_exec(so.sock, fc(ctx));
  8217. ctx->listening_sockets = ptr;
  8218. ctx->listening_sockets[ctx->num_listening_sockets] = so;
  8219. ctx->listening_ports = portPtr;
  8220. ctx->listening_ports[ctx->num_listening_sockets] =
  8221. ntohs(usa.sin.sin_port);
  8222. ctx->num_listening_sockets++;
  8223. portsOk++;
  8224. }
  8225. if (portsOk != portsTotal) {
  8226. close_all_listening_sockets(ctx);
  8227. portsOk = 0;
  8228. }
  8229. return portsOk;
  8230. }
  8231. static const char *header_val(const struct mg_connection *conn,
  8232. const char *header)
  8233. {
  8234. const char *header_value;
  8235. if ((header_value = mg_get_header(conn, header)) == NULL) {
  8236. return "-";
  8237. } else {
  8238. return header_value;
  8239. }
  8240. }
  8241. static void log_access(const struct mg_connection *conn)
  8242. {
  8243. const struct mg_request_info *ri;
  8244. FILE *fp;
  8245. char date[64], src_addr[IP_ADDR_STR_LEN];
  8246. struct tm *tm;
  8247. const char *referer;
  8248. const char *user_agent;
  8249. char buf[4096];
  8250. if (!conn || !conn->ctx) {
  8251. return;
  8252. }
  8253. fp = conn->ctx->config[ACCESS_LOG_FILE] == NULL
  8254. ? NULL
  8255. : fopen(conn->ctx->config[ACCESS_LOG_FILE], "a+");
  8256. if (fp == NULL && conn->ctx->callbacks.log_message == NULL) {
  8257. return;
  8258. }
  8259. tm = localtime(&conn->conn_birth_time);
  8260. if (tm != NULL) {
  8261. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  8262. } else {
  8263. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  8264. date[sizeof(date) - 1] = '\0';
  8265. }
  8266. ri = &conn->request_info;
  8267. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  8268. referer = header_val(conn, "Referer");
  8269. user_agent = header_val(conn, "User-Agent");
  8270. mg_snprintf(conn,
  8271. NULL, /* Ignore truncation in access log */
  8272. buf,
  8273. sizeof(buf),
  8274. "%s - %s [%s] \"%s %s HTTP/%s\" %d %" INT64_FMT " %s %s",
  8275. src_addr,
  8276. ri->remote_user == NULL ? "-" : ri->remote_user,
  8277. date,
  8278. ri->request_method ? ri->request_method : "-",
  8279. ri->request_uri ? ri->request_uri : "-",
  8280. ri->http_version,
  8281. conn->status_code,
  8282. conn->num_bytes_sent,
  8283. referer,
  8284. user_agent);
  8285. if (conn->ctx->callbacks.log_access) {
  8286. conn->ctx->callbacks.log_access(conn, buf);
  8287. }
  8288. if (fp) {
  8289. flockfile(fp);
  8290. fprintf(fp, "%s", buf);
  8291. fputc('\n', fp);
  8292. fflush(fp);
  8293. funlockfile(fp);
  8294. fclose(fp);
  8295. }
  8296. }
  8297. /* Verify given socket address against the ACL.
  8298. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed. */
  8299. static int check_acl(struct mg_context *ctx, uint32_t remote_ip)
  8300. {
  8301. int allowed, flag;
  8302. uint32_t net, mask;
  8303. struct vec vec;
  8304. if (ctx) {
  8305. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  8306. /* If any ACL is set, deny by default */
  8307. allowed = list == NULL ? '+' : '-';
  8308. while ((list = next_option(list, &vec, NULL)) != NULL) {
  8309. flag = vec.ptr[0];
  8310. if ((flag != '+' && flag != '-') ||
  8311. parse_net(&vec.ptr[1], &net, &mask) == 0) {
  8312. mg_cry(
  8313. fc(ctx), "%s: subnet must be [+|-]x.x.x.x[/x]", __func__);
  8314. return -1;
  8315. }
  8316. if (net == (remote_ip & mask)) {
  8317. allowed = flag;
  8318. }
  8319. }
  8320. return allowed == '+';
  8321. }
  8322. return -1;
  8323. }
  8324. #if !defined(_WIN32)
  8325. static int set_uid_option(struct mg_context *ctx)
  8326. {
  8327. struct passwd *pw;
  8328. if (ctx) {
  8329. const char *uid = ctx->config[RUN_AS_USER];
  8330. int success = 0;
  8331. if (uid == NULL) {
  8332. success = 1;
  8333. } else {
  8334. if ((pw = getpwnam(uid)) == NULL) {
  8335. mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  8336. } else if (setgid(pw->pw_gid) == -1) {
  8337. mg_cry(fc(ctx),
  8338. "%s: setgid(%s): %s",
  8339. __func__,
  8340. uid,
  8341. strerror(errno));
  8342. } else if (setgroups(0, NULL)) {
  8343. mg_cry(
  8344. fc(ctx), "%s: setgroups(): %s", __func__, strerror(errno));
  8345. } else if (setuid(pw->pw_uid) == -1) {
  8346. mg_cry(fc(ctx),
  8347. "%s: setuid(%s): %s",
  8348. __func__,
  8349. uid,
  8350. strerror(errno));
  8351. } else {
  8352. success = 1;
  8353. }
  8354. }
  8355. return success;
  8356. }
  8357. return 0;
  8358. }
  8359. #endif /* !_WIN32 */
  8360. static void tls_dtor(void *key)
  8361. {
  8362. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  8363. /* key == pthread_getspecific(sTlsKey); */
  8364. if (tls) {
  8365. if (tls->is_master == 2) {
  8366. tls->is_master = -3; /* Mark memory as dead */
  8367. mg_free(tls);
  8368. }
  8369. }
  8370. pthread_setspecific(sTlsKey, NULL);
  8371. }
  8372. #if !defined(NO_SSL)
  8373. /* Must be set if sizeof(pthread_t) > sizeof(unsigned long) */
  8374. static unsigned long ssl_id_callback(void)
  8375. {
  8376. #ifdef _WIN32
  8377. return GetCurrentThreadId();
  8378. #else
  8379. #ifdef __clang__
  8380. #pragma clang diagnostic push
  8381. #pragma clang diagnostic ignored "-Wunreachable-code"
  8382. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  8383. * or not, so one of the two conditions will be unreachable by construction.
  8384. * Unfortunately the C standard does not define a way to check this at
  8385. * compile time, since the #if preprocessor conditions can not use the sizeof
  8386. * operator as an argument. */
  8387. #endif
  8388. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  8389. /* This is the problematic case for CRYPTO_set_id_callback:
  8390. * The OS pthread_t can not be cast to unsigned long. */
  8391. struct mg_workerTLS *tls =
  8392. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  8393. if (tls == NULL) {
  8394. /* SSL called from an unknown thread: Create some thread index. */
  8395. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  8396. tls->is_master = -2; /* -2 means "3rd party thread" */
  8397. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  8398. pthread_setspecific(sTlsKey, tls);
  8399. }
  8400. return tls->thread_idx;
  8401. } else {
  8402. return (unsigned long)pthread_self();
  8403. }
  8404. #ifdef __clang__
  8405. #pragma clang diagnostic pop
  8406. #endif
  8407. #endif
  8408. }
  8409. static pthread_mutex_t *ssl_mutexes;
  8410. static int sslize(struct mg_connection *conn, SSL_CTX *s, int (*func)(SSL *))
  8411. {
  8412. if (!conn) {
  8413. return 0;
  8414. }
  8415. return (conn->ssl = SSL_new(s)) != NULL &&
  8416. SSL_set_fd(conn->ssl, conn->client.sock) == 1 &&
  8417. func(conn->ssl) == 1;
  8418. }
  8419. /* Return OpenSSL error message (from CRYPTO lib) */
  8420. static const char *ssl_error(void)
  8421. {
  8422. unsigned long err;
  8423. err = ERR_get_error();
  8424. return err == 0 ? "" : ERR_error_string(err, NULL);
  8425. }
  8426. static void
  8427. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  8428. {
  8429. (void)line;
  8430. (void)file;
  8431. if (mode & 1) {
  8432. /* 1 is CRYPTO_LOCK */
  8433. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  8434. } else {
  8435. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  8436. }
  8437. }
  8438. #if !defined(NO_SSL_DL)
  8439. static void *
  8440. load_dll(struct mg_context *ctx, const char *dll_name, struct ssl_func *sw)
  8441. {
  8442. union {
  8443. void *p;
  8444. void (*fp)(void);
  8445. } u;
  8446. void *dll_handle;
  8447. struct ssl_func *fp;
  8448. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  8449. mg_cry(fc(ctx), "%s: cannot load %s", __func__, dll_name);
  8450. return NULL;
  8451. }
  8452. for (fp = sw; fp->name != NULL; fp++) {
  8453. #ifdef _WIN32
  8454. /* GetProcAddress() returns pointer to function */
  8455. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  8456. #else
  8457. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  8458. * pointers to function pointers. We need to use a union to make a
  8459. * cast. */
  8460. u.p = dlsym(dll_handle, fp->name);
  8461. #endif /* _WIN32 */
  8462. if (u.fp == NULL) {
  8463. mg_cry(fc(ctx),
  8464. "%s: %s: cannot find %s",
  8465. __func__,
  8466. dll_name,
  8467. fp->name);
  8468. dlclose(dll_handle);
  8469. return NULL;
  8470. } else {
  8471. fp->ptr = u.fp;
  8472. }
  8473. }
  8474. return dll_handle;
  8475. }
  8476. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  8477. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  8478. #endif /* NO_SSL_DL */
  8479. #if defined(SSL_ALREADY_INITIALIZED)
  8480. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  8481. #else
  8482. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  8483. #endif
  8484. static int initialize_ssl(struct mg_context *ctx)
  8485. {
  8486. int i;
  8487. size_t size;
  8488. #if !defined(NO_SSL_DL)
  8489. if (!cryptolib_dll_handle) {
  8490. cryptolib_dll_handle = load_dll(ctx, CRYPTO_LIB, crypto_sw);
  8491. if (!cryptolib_dll_handle) {
  8492. return 0;
  8493. }
  8494. }
  8495. #endif /* NO_SSL_DL */
  8496. if (mg_atomic_inc(&cryptolib_users) > 1) {
  8497. return 1;
  8498. }
  8499. /* Initialize locking callbacks, needed for thread safety.
  8500. * http://www.openssl.org/support/faq.html#PROG1
  8501. */
  8502. i = CRYPTO_num_locks();
  8503. if (i < 0) {
  8504. i = 0;
  8505. }
  8506. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  8507. if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  8508. mg_cry(
  8509. fc(ctx), "%s: cannot allocate mutexes: %s", __func__, ssl_error());
  8510. return 0;
  8511. }
  8512. for (i = 0; i < CRYPTO_num_locks(); i++) {
  8513. pthread_mutex_init(&ssl_mutexes[i], NULL);
  8514. }
  8515. CRYPTO_set_locking_callback(&ssl_locking_callback);
  8516. CRYPTO_set_id_callback(&ssl_id_callback);
  8517. return 1;
  8518. }
  8519. /* Dynamically load SSL library. Set up ctx->ssl_ctx pointer. */
  8520. static int set_ssl_option(struct mg_context *ctx)
  8521. {
  8522. const char *pem;
  8523. int callback_ret;
  8524. /* If PEM file is not specified and the init_ssl callback
  8525. * is not specified, skip SSL initialization. */
  8526. if (!ctx) {
  8527. return 0;
  8528. }
  8529. if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL &&
  8530. ctx->callbacks.init_ssl == NULL) {
  8531. return 1;
  8532. }
  8533. if (!initialize_ssl(ctx)) {
  8534. return 0;
  8535. }
  8536. #if !defined(NO_SSL_DL)
  8537. if (!ssllib_dll_handle) {
  8538. ssllib_dll_handle = load_dll(ctx, SSL_LIB, ssl_sw);
  8539. if (!ssllib_dll_handle) {
  8540. return 0;
  8541. }
  8542. }
  8543. #endif /* NO_SSL_DL */
  8544. /* Initialize SSL library */
  8545. SSL_library_init();
  8546. SSL_load_error_strings();
  8547. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  8548. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  8549. return 0;
  8550. }
  8551. /* If a callback has been specified, call it. */
  8552. callback_ret =
  8553. (ctx->callbacks.init_ssl == NULL)
  8554. ? 0
  8555. : (ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data));
  8556. /* If callback returns 0, civetweb sets up the SSL certificate.
  8557. * If it returns 1, civetweb assumes the calback already did this.
  8558. * If it returns -1, initializing ssl fails. */
  8559. if (callback_ret < 0) {
  8560. mg_cry(fc(ctx), "SSL callback returned error: %i", callback_ret);
  8561. return 0;
  8562. }
  8563. if (callback_ret == 0) {
  8564. if (pem != NULL) {
  8565. if ((SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0) ||
  8566. (SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0)) {
  8567. mg_cry(fc(ctx),
  8568. "%s: cannot open %s: %s",
  8569. __func__,
  8570. pem,
  8571. ssl_error());
  8572. return 0;
  8573. }
  8574. }
  8575. }
  8576. if (pem != NULL) {
  8577. (void)SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
  8578. }
  8579. return 1;
  8580. }
  8581. static void uninitialize_ssl(struct mg_context *ctx)
  8582. {
  8583. int i;
  8584. (void)ctx;
  8585. if (mg_atomic_dec(&cryptolib_users) == 0) {
  8586. CRYPTO_set_locking_callback(NULL);
  8587. for (i = 0; i < CRYPTO_num_locks(); i++) {
  8588. pthread_mutex_destroy(&ssl_mutexes[i]);
  8589. }
  8590. CRYPTO_set_locking_callback(NULL);
  8591. CRYPTO_set_id_callback(NULL);
  8592. }
  8593. }
  8594. #endif /* !NO_SSL */
  8595. static int set_gpass_option(struct mg_context *ctx)
  8596. {
  8597. if (ctx) {
  8598. struct file file = STRUCT_FILE_INITIALIZER;
  8599. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  8600. if (path != NULL && !mg_stat(fc(ctx), path, &file)) {
  8601. mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  8602. return 0;
  8603. }
  8604. return 1;
  8605. }
  8606. return 0;
  8607. }
  8608. static int set_acl_option(struct mg_context *ctx)
  8609. {
  8610. return check_acl(ctx, (uint32_t)0x7f000001UL) != -1;
  8611. }
  8612. static void reset_per_request_attributes(struct mg_connection *conn)
  8613. {
  8614. if (!conn) {
  8615. return;
  8616. }
  8617. conn->path_info = NULL;
  8618. conn->num_bytes_sent = conn->consumed_content = 0;
  8619. conn->status_code = -1;
  8620. conn->is_chunked = 0;
  8621. conn->must_close = conn->request_len = conn->throttle = 0;
  8622. conn->request_info.content_length = -1;
  8623. conn->request_info.remote_user = NULL;
  8624. conn->request_info.request_method = NULL;
  8625. conn->request_info.request_uri = NULL;
  8626. conn->request_info.rel_uri = NULL;
  8627. conn->request_info.uri = NULL; /* TODO: cleanup uri,
  8628. * rel_uri and request_uri */
  8629. conn->request_info.http_version = NULL;
  8630. conn->request_info.num_headers = 0;
  8631. conn->data_len = 0;
  8632. conn->chunk_remainder = 0;
  8633. conn->internal_error = 0;
  8634. }
  8635. static int set_sock_timeout(SOCKET sock, int milliseconds)
  8636. {
  8637. int r1, r2;
  8638. #ifdef _WIN32
  8639. DWORD t = (DWORD)milliseconds;
  8640. #else
  8641. #if defined(TCP_USER_TIMEOUT)
  8642. unsigned int uto = (unsigned int)milliseconds;
  8643. #endif
  8644. struct timeval t;
  8645. t.tv_sec = milliseconds / 1000;
  8646. t.tv_usec = (milliseconds * 1000) % 1000000;
  8647. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  8648. * max. time waiting for the acknowledged of TCP data before the connection
  8649. * will be forcefully closed and ETIMEDOUT is returned to the application.
  8650. * If this option is not set, the default timeout of 20-30 minutes is used.
  8651. */
  8652. /* #define TCP_USER_TIMEOUT (18) */
  8653. #if defined(TCP_USER_TIMEOUT)
  8654. setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  8655. #endif
  8656. #endif
  8657. r1 =
  8658. setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&t, sizeof(t));
  8659. r2 =
  8660. setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&t, sizeof(t));
  8661. return r1 || r2;
  8662. }
  8663. static void close_socket_gracefully(struct mg_connection *conn)
  8664. {
  8665. #if defined(_WIN32)
  8666. char buf[MG_BUF_LEN];
  8667. int n;
  8668. #endif
  8669. struct linger linger;
  8670. if (!conn) {
  8671. return;
  8672. }
  8673. /* Set linger option to avoid socket hanging out after close. This prevent
  8674. * ephemeral port exhaust problem under high QPS. */
  8675. linger.l_onoff = 1;
  8676. linger.l_linger = 1;
  8677. if (setsockopt(conn->client.sock,
  8678. SOL_SOCKET,
  8679. SO_LINGER,
  8680. (char *)&linger,
  8681. sizeof(linger)) != 0) {
  8682. mg_cry(conn,
  8683. "%s: setsockopt(SOL_SOCKET SO_LINGER) failed: %s",
  8684. __func__,
  8685. strerror(ERRNO));
  8686. }
  8687. /* Send FIN to the client */
  8688. shutdown(conn->client.sock, SHUT_WR);
  8689. set_non_blocking_mode(conn->client.sock);
  8690. #if defined(_WIN32)
  8691. /* Read and discard pending incoming data. If we do not do that and close
  8692. * the socket, the data in the send buffer may be discarded. This
  8693. * behaviour is seen on Windows, when client keeps sending data
  8694. * when server decides to close the connection; then when client
  8695. * does recv() it gets no data back. */
  8696. do {
  8697. n = pull(
  8698. NULL, conn, buf, sizeof(buf), 1E-10 /* TODO: allow 0 as timeout */);
  8699. } while (n > 0);
  8700. #endif
  8701. /* Now we know that our FIN is ACK-ed, safe to close */
  8702. closesocket(conn->client.sock);
  8703. conn->client.sock = INVALID_SOCKET;
  8704. }
  8705. static void close_connection(struct mg_connection *conn)
  8706. {
  8707. if (!conn || !conn->ctx) {
  8708. return;
  8709. }
  8710. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  8711. if (conn->lua_websocket_state) {
  8712. lua_websocket_close(conn, conn->lua_websocket_state);
  8713. conn->lua_websocket_state = NULL;
  8714. }
  8715. #endif
  8716. /* call the connection_close callback if assigned */
  8717. if ((conn->ctx->callbacks.connection_close != NULL) &&
  8718. (conn->ctx->context_type == 1)) {
  8719. conn->ctx->callbacks.connection_close(conn);
  8720. }
  8721. mg_lock_connection(conn);
  8722. conn->must_close = 1;
  8723. #ifndef NO_SSL
  8724. if (conn->ssl != NULL) {
  8725. /* Run SSL_shutdown twice to ensure completly close SSL connection */
  8726. SSL_shutdown(conn->ssl);
  8727. SSL_free(conn->ssl);
  8728. conn->ssl = NULL;
  8729. }
  8730. #endif
  8731. if (conn->client.sock != INVALID_SOCKET) {
  8732. close_socket_gracefully(conn);
  8733. conn->client.sock = INVALID_SOCKET;
  8734. }
  8735. mg_unlock_connection(conn);
  8736. }
  8737. void mg_close_connection(struct mg_connection *conn)
  8738. {
  8739. struct mg_context *client_ctx = NULL;
  8740. unsigned int i;
  8741. if (conn == NULL) {
  8742. return;
  8743. }
  8744. if (conn->ctx->context_type == 2) {
  8745. client_ctx = conn->ctx;
  8746. /* client context: loops must end */
  8747. conn->ctx->stop_flag = 1;
  8748. }
  8749. #ifndef NO_SSL
  8750. if (conn->client_ssl_ctx != NULL) {
  8751. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  8752. }
  8753. #endif
  8754. close_connection(conn);
  8755. if (client_ctx != NULL) {
  8756. /* join worker thread and free context */
  8757. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  8758. if (client_ctx->workerthreadids[i] != 0) {
  8759. mg_join_thread(client_ctx->workerthreadids[i]);
  8760. }
  8761. }
  8762. mg_free(client_ctx->workerthreadids);
  8763. mg_free(client_ctx);
  8764. }
  8765. (void)pthread_mutex_destroy(&conn->mutex);
  8766. mg_free(conn);
  8767. }
  8768. struct mg_connection *mg_connect_client(const char *host,
  8769. int port,
  8770. int use_ssl,
  8771. char *ebuf,
  8772. size_t ebuf_len)
  8773. {
  8774. static struct mg_context fake_ctx;
  8775. struct mg_connection *conn = NULL;
  8776. SOCKET sock;
  8777. union usa sa;
  8778. if (!connect_socket(
  8779. &fake_ctx, host, port, use_ssl, ebuf, ebuf_len, &sock, &sa)) {
  8780. ;
  8781. } else if ((conn = (struct mg_connection *)mg_calloc(
  8782. 1, sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) {
  8783. mg_snprintf(NULL,
  8784. NULL, /* No truncation check for ebuf */
  8785. ebuf,
  8786. ebuf_len,
  8787. "calloc(): %s",
  8788. strerror(ERRNO));
  8789. closesocket(sock);
  8790. #ifndef NO_SSL
  8791. } else if (use_ssl &&
  8792. (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method())) ==
  8793. NULL) {
  8794. mg_snprintf(NULL,
  8795. NULL, /* No truncation check for ebuf */
  8796. ebuf,
  8797. ebuf_len,
  8798. "SSL_CTX_new error");
  8799. closesocket(sock);
  8800. mg_free(conn);
  8801. conn = NULL;
  8802. #endif /* NO_SSL */
  8803. } else {
  8804. #ifdef USE_IPV6
  8805. socklen_t len = (sa.sa.sa_family == AF_INET)
  8806. ? sizeof(conn->client.rsa.sin)
  8807. : sizeof(conn->client.rsa.sin6);
  8808. struct sockaddr *psa =
  8809. (sa.sa.sa_family == AF_INET)
  8810. ? (struct sockaddr *)&(conn->client.rsa.sin)
  8811. : (struct sockaddr *)&(conn->client.rsa.sin6);
  8812. #else
  8813. socklen_t len = sizeof(conn->client.rsa.sin);
  8814. struct sockaddr *psa = (struct sockaddr *)&(conn->client.rsa.sin);
  8815. #endif
  8816. conn->buf_size = MAX_REQUEST_SIZE;
  8817. conn->buf = (char *)(conn + 1);
  8818. conn->ctx = &fake_ctx;
  8819. conn->client.sock = sock;
  8820. conn->client.lsa = sa;
  8821. if (getsockname(sock, psa, &len) != 0) {
  8822. mg_cry(conn,
  8823. "%s: getsockname() failed: %s",
  8824. __func__,
  8825. strerror(ERRNO));
  8826. }
  8827. conn->client.is_ssl = use_ssl ? 1 : 0;
  8828. (void)pthread_mutex_init(&conn->mutex, NULL);
  8829. #ifndef NO_SSL
  8830. if (use_ssl) {
  8831. /* SSL_CTX_set_verify call is needed to switch off server
  8832. * certificate checking, which is off by default in OpenSSL and on
  8833. * in yaSSL. */
  8834. SSL_CTX_set_verify(conn->client_ssl_ctx, 0, 0);
  8835. sslize(conn, conn->client_ssl_ctx, SSL_connect);
  8836. }
  8837. #endif
  8838. }
  8839. return conn;
  8840. }
  8841. static const struct {
  8842. const char *proto;
  8843. size_t proto_len;
  8844. unsigned default_port;
  8845. } abs_uri_protocols[] = {{"http://", 7, 80},
  8846. {"https://", 8, 443},
  8847. {"ws://", 5, 80},
  8848. {"wss://", 6, 443},
  8849. {NULL, 0, 0}};
  8850. /* Check if the uri is valid.
  8851. * return 0 for invalid uri,
  8852. * return 1 for *,
  8853. * return 2 for relative uri,
  8854. * return 3 for absolute uri without port,
  8855. * return 4 for absolute uri with port */
  8856. static int get_uri_type(const char *uri)
  8857. {
  8858. int i;
  8859. char *hostend, *portbegin, *portend;
  8860. unsigned long port;
  8861. /* According to the HTTP standard
  8862. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  8863. * URI can be an asterisk (*) or should start with slash (relative uri),
  8864. * or it should start with the protocol (absolute uri). */
  8865. if (uri[0] == '*' && uri[1] == '\0') {
  8866. /* asterisk */
  8867. return 1;
  8868. }
  8869. if (uri[0] == '/') {
  8870. /* relative uri */
  8871. return 2;
  8872. }
  8873. /* It could be an absolute uri: */
  8874. /* This function only checks if the uri is valid, not if it is
  8875. * addressing the current server. So civetweb can also be used
  8876. * as a proxy server. */
  8877. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  8878. if (mg_strncasecmp(uri,
  8879. abs_uri_protocols[i].proto,
  8880. abs_uri_protocols[i].proto_len) == 0) {
  8881. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  8882. if (!hostend) {
  8883. return 0;
  8884. }
  8885. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  8886. if (!portbegin) {
  8887. return 3;
  8888. }
  8889. port = strtoul(portbegin + 1, &portend, 10);
  8890. if ((portend != hostend) || !port || !is_valid_port(port)) {
  8891. return 0;
  8892. }
  8893. return 4;
  8894. }
  8895. }
  8896. return 0;
  8897. }
  8898. /* Return NULL or the relative uri at the current server */
  8899. static const char *
  8900. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  8901. {
  8902. const char *domain;
  8903. size_t domain_len;
  8904. unsigned long port = 0;
  8905. int i;
  8906. char *hostend = NULL;
  8907. char *portbegin, *portend;
  8908. /* DNS is case insensitive, so use case insensitive string compare here */
  8909. domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  8910. if (!domain) {
  8911. return 0;
  8912. }
  8913. domain_len = strlen(domain);
  8914. if (!domain_len) {
  8915. return 0;
  8916. }
  8917. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  8918. if (mg_strncasecmp(uri,
  8919. abs_uri_protocols[i].proto,
  8920. abs_uri_protocols[i].proto_len) == 0) {
  8921. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  8922. if (!hostend) {
  8923. return 0;
  8924. }
  8925. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  8926. if (!portbegin) {
  8927. port = abs_uri_protocols[i].default_port;
  8928. } else {
  8929. port = strtoul(portbegin + 1, &portend, 10);
  8930. if ((portend != hostend) || !port || !is_valid_port(port)) {
  8931. return 0;
  8932. }
  8933. }
  8934. /* protocol found, port set */
  8935. break;
  8936. }
  8937. }
  8938. if (!port) {
  8939. /* port remains 0 if the protocol is not found */
  8940. return 0;
  8941. }
  8942. #if defined(USE_IPV6)
  8943. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  8944. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  8945. return 0;
  8946. }
  8947. } else
  8948. #endif
  8949. {
  8950. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  8951. return 0;
  8952. }
  8953. }
  8954. return hostend;
  8955. }
  8956. static int
  8957. getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  8958. {
  8959. const char *cl;
  8960. if (ebuf_len > 0) {
  8961. ebuf[0] = '\0';
  8962. }
  8963. *err = 0;
  8964. reset_per_request_attributes(conn);
  8965. if (!conn) {
  8966. mg_snprintf(conn,
  8967. NULL, /* No truncation check for ebuf */
  8968. ebuf,
  8969. ebuf_len,
  8970. "%s",
  8971. "Internal error");
  8972. *err = 500;
  8973. return 0;
  8974. }
  8975. /* Set the time the request was received. This value should be used for
  8976. * timeouts. */
  8977. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  8978. conn->request_len =
  8979. read_request(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  8980. /* assert(conn->request_len < 0 || conn->data_len >= conn->request_len); */
  8981. if (conn->request_len >= 0 && conn->data_len < conn->request_len) {
  8982. mg_snprintf(conn,
  8983. NULL, /* No truncation check for ebuf */
  8984. ebuf,
  8985. ebuf_len,
  8986. "%s",
  8987. "Invalid request size");
  8988. *err = 500;
  8989. return 0;
  8990. }
  8991. if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
  8992. mg_snprintf(conn,
  8993. NULL, /* No truncation check for ebuf */
  8994. ebuf,
  8995. ebuf_len,
  8996. "%s",
  8997. "Request Too Large");
  8998. *err = 413;
  8999. return 0;
  9000. } else if (conn->request_len <= 0) {
  9001. if (conn->data_len > 0) {
  9002. mg_snprintf(conn,
  9003. NULL, /* No truncation check for ebuf */
  9004. ebuf,
  9005. ebuf_len,
  9006. "%s",
  9007. "Client sent malformed request");
  9008. *err = 400;
  9009. } else {
  9010. /* Server did not send anything -> just close the connection */
  9011. conn->must_close = 1;
  9012. mg_snprintf(conn,
  9013. NULL, /* No truncation check for ebuf */
  9014. ebuf,
  9015. ebuf_len,
  9016. "%s",
  9017. "Client did not send a request");
  9018. *err = 0;
  9019. }
  9020. return 0;
  9021. } else if (parse_http_message(
  9022. conn->buf, conn->buf_size, &conn->request_info) <= 0) {
  9023. mg_snprintf(conn,
  9024. NULL, /* No truncation check for ebuf */
  9025. ebuf,
  9026. ebuf_len,
  9027. "%s",
  9028. "Bad Request");
  9029. *err = 400;
  9030. return 0;
  9031. } else {
  9032. /* Message is a valid request or response */
  9033. if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) {
  9034. /* Request/response has content length set */
  9035. char *endptr = NULL;
  9036. conn->content_len = strtoll(cl, &endptr, 10);
  9037. if (endptr == cl) {
  9038. mg_snprintf(conn,
  9039. NULL, /* No truncation check for ebuf */
  9040. ebuf,
  9041. ebuf_len,
  9042. "%s",
  9043. "Bad Request");
  9044. *err = 411;
  9045. return 0;
  9046. }
  9047. /* Publish the content length back to the request info. */
  9048. conn->request_info.content_length = conn->content_len;
  9049. } else if ((cl = get_header(&conn->request_info,
  9050. "Transfer-Encoding")) != NULL &&
  9051. strcmp(cl, "chunked") == 0) {
  9052. conn->is_chunked = 1;
  9053. } else if (!mg_strcasecmp(conn->request_info.request_method, "POST") ||
  9054. !mg_strcasecmp(conn->request_info.request_method, "PUT")) {
  9055. /* POST or PUT request without content length set */
  9056. conn->content_len = -1;
  9057. } else if (!mg_strncasecmp(
  9058. conn->request_info.request_method, "HTTP/", 5)) {
  9059. /* Response without content length set */
  9060. conn->content_len = -1;
  9061. } else {
  9062. /* Other request */
  9063. conn->content_len = 0;
  9064. }
  9065. }
  9066. return 1;
  9067. }
  9068. int mg_get_response(struct mg_connection *conn,
  9069. char *ebuf,
  9070. size_t ebuf_len,
  9071. int timeout)
  9072. {
  9073. if (conn) {
  9074. /* Implementation of API function for HTTP clients */
  9075. int err, ret;
  9076. struct mg_context *octx = conn->ctx;
  9077. struct mg_context rctx = *(conn->ctx);
  9078. char txt[32]; /* will not overflow */
  9079. if (timeout >= 0) {
  9080. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  9081. rctx.config[REQUEST_TIMEOUT] = txt;
  9082. set_sock_timeout(conn->client.sock, timeout);
  9083. } else {
  9084. rctx.config[REQUEST_TIMEOUT] = NULL;
  9085. }
  9086. conn->ctx = &rctx;
  9087. ret = getreq(conn, ebuf, ebuf_len, &err);
  9088. conn->ctx = octx;
  9089. /* TODO: 1) uri is deprecated;
  9090. * 2) here, ri.uri is the http response code */
  9091. conn->request_info.uri = conn->request_info.request_uri;
  9092. /* TODO (mid): Define proper return values - maybe return length?
  9093. * For the first test use <0 for error and >0 for OK */
  9094. return (ret == 0) ? -1 : +1;
  9095. }
  9096. return -1;
  9097. }
  9098. struct mg_connection *mg_download(const char *host,
  9099. int port,
  9100. int use_ssl,
  9101. char *ebuf,
  9102. size_t ebuf_len,
  9103. const char *fmt,
  9104. ...)
  9105. {
  9106. struct mg_connection *conn;
  9107. va_list ap;
  9108. int i;
  9109. int reqerr;
  9110. va_start(ap, fmt);
  9111. ebuf[0] = '\0';
  9112. /* open a connection */
  9113. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  9114. if (conn != NULL) {
  9115. i = mg_vprintf(conn, fmt, ap);
  9116. if (i <= 0) {
  9117. mg_snprintf(conn,
  9118. NULL, /* No truncation check for ebuf */
  9119. ebuf,
  9120. ebuf_len,
  9121. "%s",
  9122. "Error sending request");
  9123. } else {
  9124. getreq(conn, ebuf, ebuf_len, &reqerr);
  9125. /* TODO: 1) uri is deprecated;
  9126. * 2) here, ri.uri is the http response code */
  9127. conn->request_info.uri = conn->request_info.request_uri;
  9128. }
  9129. }
  9130. /* if an error occured, close the connection */
  9131. if (ebuf[0] != '\0' && conn != NULL) {
  9132. mg_close_connection(conn);
  9133. conn = NULL;
  9134. }
  9135. va_end(ap);
  9136. return conn;
  9137. }
  9138. struct websocket_client_thread_data {
  9139. struct mg_connection *conn;
  9140. mg_websocket_data_handler data_handler;
  9141. mg_websocket_close_handler close_handler;
  9142. void *callback_data;
  9143. };
  9144. #if defined(USE_WEBSOCKET)
  9145. #ifdef _WIN32
  9146. static unsigned __stdcall websocket_client_thread(void *data)
  9147. #else
  9148. static void *websocket_client_thread(void *data)
  9149. #endif
  9150. {
  9151. struct websocket_client_thread_data *cdata =
  9152. (struct websocket_client_thread_data *)data;
  9153. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  9154. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  9155. if (cdata->close_handler != NULL) {
  9156. cdata->close_handler(cdata->conn, cdata->callback_data);
  9157. }
  9158. mg_free((void *)cdata);
  9159. #ifdef _WIN32
  9160. return 0;
  9161. #else
  9162. return NULL;
  9163. #endif
  9164. }
  9165. #endif
  9166. struct mg_connection *
  9167. mg_connect_websocket_client(const char *host,
  9168. int port,
  9169. int use_ssl,
  9170. char *error_buffer,
  9171. size_t error_buffer_size,
  9172. const char *path,
  9173. const char *origin,
  9174. mg_websocket_data_handler data_func,
  9175. mg_websocket_close_handler close_func,
  9176. void *user_data)
  9177. {
  9178. struct mg_connection *conn = NULL;
  9179. #if defined(USE_WEBSOCKET)
  9180. struct mg_context *newctx = NULL;
  9181. struct websocket_client_thread_data *thread_data;
  9182. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  9183. static const char *handshake_req;
  9184. if (origin != NULL) {
  9185. handshake_req = "GET %s HTTP/1.1\r\n"
  9186. "Host: %s\r\n"
  9187. "Upgrade: websocket\r\n"
  9188. "Connection: Upgrade\r\n"
  9189. "Sec-WebSocket-Key: %s\r\n"
  9190. "Sec-WebSocket-Version: 13\r\n"
  9191. "Origin: %s\r\n"
  9192. "\r\n";
  9193. } else {
  9194. handshake_req = "GET %s HTTP/1.1\r\n"
  9195. "Host: %s\r\n"
  9196. "Upgrade: websocket\r\n"
  9197. "Connection: Upgrade\r\n"
  9198. "Sec-WebSocket-Key: %s\r\n"
  9199. "Sec-WebSocket-Version: 13\r\n"
  9200. "\r\n";
  9201. }
  9202. /* Establish the client connection and request upgrade */
  9203. conn = mg_download(host,
  9204. port,
  9205. use_ssl,
  9206. error_buffer,
  9207. error_buffer_size,
  9208. handshake_req,
  9209. path,
  9210. host,
  9211. magic,
  9212. origin);
  9213. /* Connection object will be null if something goes wrong */
  9214. if (conn == NULL || (strcmp(conn->request_info.request_uri, "101") != 0)) {
  9215. if (!*error_buffer) {
  9216. /* if there is a connection, but it did not return 101,
  9217. * error_buffer is not yet set */
  9218. mg_snprintf(conn,
  9219. NULL, /* No truncation check for ebuf */
  9220. error_buffer,
  9221. error_buffer_size,
  9222. "Unexpected server reply");
  9223. }
  9224. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  9225. if (conn != NULL) {
  9226. mg_free(conn);
  9227. conn = NULL;
  9228. }
  9229. return conn;
  9230. }
  9231. /* For client connections, mg_context is fake. Since we need to set a
  9232. * callback function, we need to create a copy and modify it. */
  9233. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  9234. memcpy(newctx, conn->ctx, sizeof(struct mg_context));
  9235. newctx->user_data = user_data;
  9236. newctx->context_type = 2; /* client context type */
  9237. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  9238. newctx->workerthreadids =
  9239. (pthread_t *)mg_calloc(newctx->cfg_worker_threads, sizeof(pthread_t));
  9240. conn->ctx = newctx;
  9241. thread_data = (struct websocket_client_thread_data *)mg_calloc(
  9242. sizeof(struct websocket_client_thread_data), 1);
  9243. thread_data->conn = conn;
  9244. thread_data->data_handler = data_func;
  9245. thread_data->close_handler = close_func;
  9246. thread_data->callback_data = NULL;
  9247. /* Start a thread to read the websocket client connection
  9248. * This thread will automatically stop when mg_disconnect is
  9249. * called on the client connection */
  9250. if (mg_start_thread_with_id(websocket_client_thread,
  9251. (void *)thread_data,
  9252. newctx->workerthreadids) != 0) {
  9253. mg_free((void *)thread_data);
  9254. mg_free((void *)newctx->workerthreadids);
  9255. mg_free((void *)newctx);
  9256. mg_free((void *)conn);
  9257. conn = NULL;
  9258. DEBUG_TRACE("%s",
  9259. "Websocket client connect thread could not be started\r\n");
  9260. }
  9261. #else
  9262. /* Appease "unused parameter" warnings */
  9263. (void)host;
  9264. (void)port;
  9265. (void)use_ssl;
  9266. (void)error_buffer;
  9267. (void)error_buffer_size;
  9268. (void)path;
  9269. (void)origin;
  9270. (void)user_data;
  9271. (void)data_func;
  9272. (void)close_func;
  9273. #endif
  9274. return conn;
  9275. }
  9276. static void process_new_connection(struct mg_connection *conn)
  9277. {
  9278. if (conn && conn->ctx) {
  9279. struct mg_request_info *ri = &conn->request_info;
  9280. int keep_alive_enabled, keep_alive, discard_len;
  9281. char ebuf[100];
  9282. const char *hostend;
  9283. int reqerr, uri_type;
  9284. keep_alive_enabled =
  9285. !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  9286. /* Important: on new connection, reset the receiving buffer. Credit
  9287. * goes to crule42. */
  9288. conn->data_len = 0;
  9289. do {
  9290. if (!getreq(conn, ebuf, sizeof(ebuf), &reqerr)) {
  9291. /* The request sent by the client could not be understood by
  9292. * the server, or it was incomplete or a timeout. Send an
  9293. * error message and close the connection. */
  9294. if (reqerr > 0) {
  9295. /*assert(ebuf[0] != '\0');*/
  9296. send_http_error(conn, reqerr, "%s", ebuf);
  9297. }
  9298. } else if (strcmp(ri->http_version, "1.0") &&
  9299. strcmp(ri->http_version, "1.1")) {
  9300. mg_snprintf(conn,
  9301. NULL, /* No truncation check for ebuf */
  9302. ebuf,
  9303. sizeof(ebuf),
  9304. "Bad HTTP version: [%s]",
  9305. ri->http_version);
  9306. send_http_error(conn, 505, "%s", ebuf);
  9307. }
  9308. if (ebuf[0] == '\0') {
  9309. uri_type = get_uri_type(conn->request_info.request_uri);
  9310. switch (uri_type) {
  9311. case 1:
  9312. /* Asterisk */
  9313. conn->request_info.rel_uri = NULL;
  9314. break;
  9315. case 2:
  9316. /* relative uri */
  9317. conn->request_info.rel_uri = conn->request_info.request_uri;
  9318. break;
  9319. case 3:
  9320. case 4:
  9321. /* absolute uri (with/without port) */
  9322. hostend = get_rel_url_at_current_server(
  9323. conn->request_info.request_uri, conn);
  9324. if (hostend) {
  9325. conn->request_info.rel_uri = hostend;
  9326. } else {
  9327. conn->request_info.rel_uri = NULL;
  9328. }
  9329. break;
  9330. default:
  9331. mg_snprintf(conn,
  9332. NULL, /* No truncation check for ebuf */
  9333. ebuf,
  9334. sizeof(ebuf),
  9335. "Invalid URI: [%s]",
  9336. ri->request_uri);
  9337. send_http_error(conn, 400, "%s", ebuf);
  9338. break;
  9339. }
  9340. /* TODO: cleanup uri, rel_uri and request_uri */
  9341. conn->request_info.uri = conn->request_info.rel_uri;
  9342. }
  9343. if (ebuf[0] == '\0') {
  9344. handle_request(conn);
  9345. if (conn->ctx->callbacks.end_request != NULL) {
  9346. conn->ctx->callbacks.end_request(conn, conn->status_code);
  9347. }
  9348. log_access(conn);
  9349. } else {
  9350. conn->must_close = 1;
  9351. }
  9352. if (ri->remote_user != NULL) {
  9353. mg_free((void *)ri->remote_user);
  9354. /* Important! When having connections with and without auth
  9355. * would cause double free and then crash */
  9356. ri->remote_user = NULL;
  9357. }
  9358. /* NOTE(lsm): order is important here. should_keep_alive() call is
  9359. * using parsed request, which will be invalid after memmove's
  9360. * below.
  9361. * Therefore, memorize should_keep_alive() result now for later use
  9362. * in loop exit condition. */
  9363. keep_alive = conn->ctx->stop_flag == 0 && keep_alive_enabled &&
  9364. conn->content_len >= 0 && should_keep_alive(conn);
  9365. /* Discard all buffered data for this request */
  9366. discard_len = conn->content_len >= 0 && conn->request_len > 0 &&
  9367. conn->request_len + conn->content_len <
  9368. (int64_t)conn->data_len
  9369. ? (int)(conn->request_len + conn->content_len)
  9370. : conn->data_len;
  9371. /*assert(discard_len >= 0);*/
  9372. if (discard_len < 0)
  9373. break;
  9374. conn->data_len -= discard_len;
  9375. if (conn->data_len > 0) {
  9376. memmove(
  9377. conn->buf, conn->buf + discard_len, (size_t)conn->data_len);
  9378. }
  9379. /* assert(conn->data_len >= 0); */
  9380. /* assert(conn->data_len <= conn->buf_size); */
  9381. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  9382. break;
  9383. }
  9384. } while (keep_alive);
  9385. }
  9386. }
  9387. /* Worker threads take accepted socket from the queue */
  9388. static int consume_socket(struct mg_context *ctx, struct socket *sp)
  9389. {
  9390. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  9391. if (!ctx) {
  9392. return 0;
  9393. }
  9394. (void)pthread_mutex_lock(&ctx->thread_mutex);
  9395. DEBUG_TRACE("%s", "going idle");
  9396. /* If the queue is empty, wait. We're idle at this point. */
  9397. while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
  9398. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  9399. }
  9400. /* If we're stopping, sq_head may be equal to sq_tail. */
  9401. if (ctx->sq_head > ctx->sq_tail) {
  9402. /* Copy socket from the queue and increment tail */
  9403. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  9404. ctx->sq_tail++;
  9405. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  9406. /* Wrap pointers if needed */
  9407. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  9408. ctx->sq_tail -= QUEUE_SIZE(ctx);
  9409. ctx->sq_head -= QUEUE_SIZE(ctx);
  9410. }
  9411. }
  9412. (void)pthread_cond_signal(&ctx->sq_empty);
  9413. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  9414. return !ctx->stop_flag;
  9415. #undef QUEUE_SIZE
  9416. }
  9417. static void *worker_thread_run(void *thread_func_param)
  9418. {
  9419. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  9420. struct mg_connection *conn;
  9421. struct mg_workerTLS tls;
  9422. #if defined(MG_LEGACY_INTERFACE)
  9423. uint32_t addr;
  9424. #endif
  9425. mg_set_thread_name("worker");
  9426. tls.is_master = 0;
  9427. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  9428. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  9429. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  9430. #endif
  9431. conn =
  9432. (struct mg_connection *)mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE);
  9433. if (conn == NULL) {
  9434. mg_cry(fc(ctx), "%s", "Cannot create new connection struct, OOM");
  9435. } else {
  9436. pthread_setspecific(sTlsKey, &tls);
  9437. conn->buf_size = MAX_REQUEST_SIZE;
  9438. conn->buf = (char *)(conn + 1);
  9439. conn->ctx = ctx;
  9440. conn->request_info.user_data = ctx->user_data;
  9441. /* Allocate a mutex for this connection to allow communication both
  9442. * within the request handler and from elsewhere in the application */
  9443. (void)pthread_mutex_init(&conn->mutex, NULL);
  9444. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  9445. * signal sq_empty condvar to wake up the master waiting in
  9446. * produce_socket() */
  9447. while (consume_socket(ctx, &conn->client)) {
  9448. conn->conn_birth_time = time(NULL);
  9449. /* Fill in IP, port info early so even if SSL setup below fails,
  9450. * error handler would have the corresponding info.
  9451. * Thanks to Johannes Winkelmann for the patch.
  9452. */
  9453. #if defined(USE_IPV6)
  9454. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  9455. conn->request_info.remote_port =
  9456. ntohs(conn->client.rsa.sin6.sin6_port);
  9457. } else
  9458. #endif
  9459. {
  9460. conn->request_info.remote_port =
  9461. ntohs(conn->client.rsa.sin.sin_port);
  9462. }
  9463. sockaddr_to_string(conn->request_info.remote_addr,
  9464. sizeof(conn->request_info.remote_addr),
  9465. &conn->client.rsa);
  9466. #if defined(MG_LEGACY_INTERFACE)
  9467. /* This legacy interface only works for the IPv4 case */
  9468. addr = ntohl(conn->client.rsa.sin.sin_addr.s_addr);
  9469. memcpy(&conn->request_info.remote_ip, &addr, 4);
  9470. #endif
  9471. conn->request_info.is_ssl = conn->client.is_ssl;
  9472. if (!conn->client.is_ssl
  9473. #ifndef NO_SSL
  9474. ||
  9475. sslize(conn, conn->ctx->ssl_ctx, SSL_accept)
  9476. #endif
  9477. ) {
  9478. process_new_connection(conn);
  9479. }
  9480. close_connection(conn);
  9481. }
  9482. }
  9483. /* Signal master that we're done with connection and exiting */
  9484. (void)pthread_mutex_lock(&ctx->thread_mutex);
  9485. ctx->running_worker_threads--;
  9486. (void)pthread_cond_signal(&ctx->thread_cond);
  9487. /* assert(ctx->running_worker_threads >= 0); */
  9488. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  9489. pthread_setspecific(sTlsKey, NULL);
  9490. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  9491. CloseHandle(tls.pthread_cond_helper_mutex);
  9492. #endif
  9493. mg_free(conn);
  9494. DEBUG_TRACE("%s", "exiting");
  9495. return NULL;
  9496. }
  9497. /* Threads have different return types on Windows and Unix. */
  9498. #ifdef _WIN32
  9499. static unsigned __stdcall worker_thread(void *thread_func_param)
  9500. {
  9501. worker_thread_run(thread_func_param);
  9502. return 0;
  9503. }
  9504. #else
  9505. static void *worker_thread(void *thread_func_param)
  9506. {
  9507. worker_thread_run(thread_func_param);
  9508. return NULL;
  9509. }
  9510. #endif /* _WIN32 */
  9511. /* Master thread adds accepted socket to a queue */
  9512. static void produce_socket(struct mg_context *ctx, const struct socket *sp)
  9513. {
  9514. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  9515. if (!ctx) {
  9516. return;
  9517. }
  9518. (void)pthread_mutex_lock(&ctx->thread_mutex);
  9519. /* If the queue is full, wait */
  9520. while (ctx->stop_flag == 0 &&
  9521. ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx)) {
  9522. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  9523. }
  9524. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  9525. /* Copy socket to the queue and increment head */
  9526. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  9527. ctx->sq_head++;
  9528. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  9529. }
  9530. (void)pthread_cond_signal(&ctx->sq_full);
  9531. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  9532. #undef QUEUE_SIZE
  9533. }
  9534. static void accept_new_connection(const struct socket *listener,
  9535. struct mg_context *ctx)
  9536. {
  9537. struct socket so;
  9538. char src_addr[IP_ADDR_STR_LEN];
  9539. socklen_t len = sizeof(so.rsa);
  9540. int on = 1;
  9541. int timeout;
  9542. if (!listener) {
  9543. return;
  9544. }
  9545. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len)) ==
  9546. INVALID_SOCKET) {
  9547. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  9548. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  9549. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  9550. closesocket(so.sock);
  9551. so.sock = INVALID_SOCKET;
  9552. } else {
  9553. /* Put so socket structure into the queue */
  9554. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  9555. set_close_on_exec(so.sock, fc(ctx));
  9556. so.is_ssl = listener->is_ssl;
  9557. so.ssl_redir = listener->ssl_redir;
  9558. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  9559. mg_cry(fc(ctx),
  9560. "%s: getsockname() failed: %s",
  9561. __func__,
  9562. strerror(ERRNO));
  9563. }
  9564. /* Set TCP keep-alive. This is needed because if HTTP-level keep-alive
  9565. * is enabled, and client resets the connection, server won't get
  9566. * TCP FIN or RST and will keep the connection open forever. With TCP
  9567. * keep-alive, next keep-alive handshake will figure out that the
  9568. * client is down and will close the server end.
  9569. * Thanks to Igor Klopov who suggested the patch. */
  9570. if (setsockopt(so.sock,
  9571. SOL_SOCKET,
  9572. SO_KEEPALIVE,
  9573. (SOCK_OPT_TYPE)&on,
  9574. sizeof(on)) != 0) {
  9575. mg_cry(fc(ctx),
  9576. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  9577. __func__,
  9578. strerror(ERRNO));
  9579. }
  9580. if (ctx && ctx->config[REQUEST_TIMEOUT]) {
  9581. timeout = atoi(ctx->config[REQUEST_TIMEOUT]);
  9582. } else {
  9583. timeout = -1;
  9584. }
  9585. /* Set socket timeout to the given value, but not more than a
  9586. * a certain limit (SOCKET_TIMEOUT_QUANTUM, default 10 seconds),
  9587. * so the server can exit after that time if requested. */
  9588. if ((timeout > 0) && (timeout < SOCKET_TIMEOUT_QUANTUM)) {
  9589. set_sock_timeout(so.sock, timeout);
  9590. } else {
  9591. set_sock_timeout(so.sock, SOCKET_TIMEOUT_QUANTUM);
  9592. }
  9593. produce_socket(ctx, &so);
  9594. }
  9595. }
  9596. static void master_thread_run(void *thread_func_param)
  9597. {
  9598. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  9599. struct mg_workerTLS tls;
  9600. struct pollfd *pfd;
  9601. unsigned int i;
  9602. unsigned int workerthreadcount;
  9603. if (!ctx) {
  9604. return;
  9605. }
  9606. mg_set_thread_name("master");
  9607. /* Increase priority of the master thread */
  9608. #if defined(_WIN32)
  9609. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  9610. #elif defined(USE_MASTER_THREAD_PRIORITY)
  9611. int min_prio = sched_get_priority_min(SCHED_RR);
  9612. int max_prio = sched_get_priority_max(SCHED_RR);
  9613. if ((min_prio >= 0) && (max_prio >= 0) &&
  9614. ((USE_MASTER_THREAD_PRIORITY) <= max_prio) &&
  9615. ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  9616. struct sched_param sched_param = {0};
  9617. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  9618. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  9619. }
  9620. #endif
  9621. /* Initialize thread local storage */
  9622. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  9623. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  9624. #endif
  9625. tls.is_master = 1;
  9626. pthread_setspecific(sTlsKey, &tls);
  9627. /* Server starts *now* */
  9628. ctx->start_time = (unsigned long)time(NULL);
  9629. /* Allocate memory for the listening sockets, and start the server */
  9630. pfd =
  9631. (struct pollfd *)mg_calloc(ctx->num_listening_sockets, sizeof(pfd[0]));
  9632. while (pfd != NULL && ctx->stop_flag == 0) {
  9633. for (i = 0; i < ctx->num_listening_sockets; i++) {
  9634. pfd[i].fd = ctx->listening_sockets[i].sock;
  9635. pfd[i].events = POLLIN;
  9636. }
  9637. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  9638. for (i = 0; i < ctx->num_listening_sockets; i++) {
  9639. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  9640. * successful poll, and POLLIN is defined as
  9641. * (POLLRDNORM | POLLRDBAND)
  9642. * Therefore, we're checking pfd[i].revents & POLLIN, not
  9643. * pfd[i].revents == POLLIN. */
  9644. if (ctx->stop_flag == 0 && (pfd[i].revents & POLLIN)) {
  9645. accept_new_connection(&ctx->listening_sockets[i], ctx);
  9646. }
  9647. }
  9648. }
  9649. }
  9650. mg_free(pfd);
  9651. DEBUG_TRACE("%s", "stopping workers");
  9652. /* Stop signal received: somebody called mg_stop. Quit. */
  9653. close_all_listening_sockets(ctx);
  9654. /* Wakeup workers that are waiting for connections to handle. */
  9655. pthread_cond_broadcast(&ctx->sq_full);
  9656. /* Wait until all threads finish */
  9657. (void)pthread_mutex_lock(&ctx->thread_mutex);
  9658. while (ctx->running_worker_threads > 0) {
  9659. (void)pthread_cond_wait(&ctx->thread_cond, &ctx->thread_mutex);
  9660. }
  9661. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  9662. /* Join all worker threads to avoid leaking threads. */
  9663. workerthreadcount = ctx->cfg_worker_threads;
  9664. for (i = 0; i < workerthreadcount; i++) {
  9665. if (ctx->workerthreadids[i] != 0) {
  9666. mg_join_thread(ctx->workerthreadids[i]);
  9667. }
  9668. }
  9669. #if !defined(NO_SSL)
  9670. if (ctx->ssl_ctx != NULL) {
  9671. uninitialize_ssl(ctx);
  9672. }
  9673. #endif
  9674. DEBUG_TRACE("%s", "exiting");
  9675. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  9676. CloseHandle(tls.pthread_cond_helper_mutex);
  9677. #endif
  9678. pthread_setspecific(sTlsKey, NULL);
  9679. /* Signal mg_stop() that we're done.
  9680. * WARNING: This must be the very last thing this
  9681. * thread does, as ctx becomes invalid after this line. */
  9682. ctx->stop_flag = 2;
  9683. }
  9684. /* Threads have different return types on Windows and Unix. */
  9685. #ifdef _WIN32
  9686. static unsigned __stdcall master_thread(void *thread_func_param)
  9687. {
  9688. master_thread_run(thread_func_param);
  9689. return 0;
  9690. }
  9691. #else
  9692. static void *master_thread(void *thread_func_param)
  9693. {
  9694. master_thread_run(thread_func_param);
  9695. return NULL;
  9696. }
  9697. #endif /* _WIN32 */
  9698. static void free_context(struct mg_context *ctx)
  9699. {
  9700. int i;
  9701. struct mg_request_handler_info *tmp_rh;
  9702. if (ctx == NULL) {
  9703. return;
  9704. }
  9705. if (ctx->callbacks.exit_context) {
  9706. ctx->callbacks.exit_context(ctx);
  9707. }
  9708. /* All threads exited, no sync is needed. Destroy thread mutex and condvars
  9709. */
  9710. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  9711. (void)pthread_cond_destroy(&ctx->thread_cond);
  9712. (void)pthread_cond_destroy(&ctx->sq_empty);
  9713. (void)pthread_cond_destroy(&ctx->sq_full);
  9714. /* Destroy other context global data structures mutex */
  9715. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  9716. #if defined(USE_TIMERS)
  9717. timers_exit(ctx);
  9718. #endif
  9719. /* Deallocate config parameters */
  9720. for (i = 0; i < NUM_OPTIONS; i++) {
  9721. if (ctx->config[i] != NULL) {
  9722. #if defined(_MSC_VER)
  9723. #pragma warning(suppress : 6001)
  9724. #endif
  9725. mg_free(ctx->config[i]);
  9726. }
  9727. }
  9728. /* Deallocate request handlers */
  9729. while (ctx->request_handlers) {
  9730. tmp_rh = ctx->request_handlers;
  9731. ctx->request_handlers = tmp_rh->next;
  9732. mg_free(tmp_rh->uri);
  9733. mg_free(tmp_rh);
  9734. }
  9735. #ifndef NO_SSL
  9736. /* Deallocate SSL context */
  9737. if (ctx->ssl_ctx != NULL) {
  9738. SSL_CTX_free(ctx->ssl_ctx);
  9739. }
  9740. if (ssl_mutexes != NULL) {
  9741. mg_free(ssl_mutexes);
  9742. ssl_mutexes = NULL;
  9743. }
  9744. #endif /* !NO_SSL */
  9745. /* Deallocate worker thread ID array */
  9746. if (ctx->workerthreadids != NULL) {
  9747. mg_free(ctx->workerthreadids);
  9748. }
  9749. /* Deallocate the tls variable */
  9750. if (mg_atomic_dec(&sTlsInit) == 0) {
  9751. pthread_key_delete(sTlsKey);
  9752. }
  9753. /* deallocate system name string */
  9754. mg_free(ctx->systemName);
  9755. /* Deallocate context itself */
  9756. mg_free(ctx);
  9757. }
  9758. void mg_stop(struct mg_context *ctx)
  9759. {
  9760. pthread_t mt;
  9761. if (!ctx) {
  9762. return;
  9763. }
  9764. /* We don't use a lock here. Calling mg_stop with the same ctx from
  9765. * two threads is not allowed. */
  9766. mt = ctx->masterthreadid;
  9767. if (mt == 0) {
  9768. return;
  9769. }
  9770. ctx->masterthreadid = 0;
  9771. ctx->stop_flag = 1;
  9772. /* Wait until mg_fini() stops */
  9773. while (ctx->stop_flag != 2) {
  9774. (void)mg_sleep(10);
  9775. }
  9776. mg_join_thread(mt);
  9777. free_context(ctx);
  9778. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  9779. (void)WSACleanup();
  9780. #endif /* _WIN32 && !__SYMBIAN32__ */
  9781. }
  9782. static void get_system_name(char **sysName)
  9783. {
  9784. #if defined(_WIN32)
  9785. #if !defined(__SYMBIAN32__)
  9786. char name[128];
  9787. DWORD dwVersion = 0;
  9788. DWORD dwMajorVersion = 0;
  9789. DWORD dwMinorVersion = 0;
  9790. DWORD dwBuild = 0;
  9791. #ifdef _MSC_VER
  9792. #pragma warning(push)
  9793. // GetVersion was declared deprecated
  9794. #pragma warning(disable : 4996)
  9795. #endif
  9796. dwVersion = GetVersion();
  9797. #ifdef _MSC_VER
  9798. #pragma warning(pop)
  9799. #endif
  9800. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  9801. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  9802. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  9803. (void)dwBuild;
  9804. sprintf(name,
  9805. "Windows %u.%u",
  9806. (unsigned)dwMajorVersion,
  9807. (unsigned)dwMinorVersion);
  9808. *sysName = mg_strdup(name);
  9809. #else
  9810. *sysName = mg_strdup("Symbian");
  9811. #endif
  9812. #else
  9813. struct utsname name;
  9814. memset(&name, 0, sizeof(name));
  9815. uname(&name);
  9816. *sysName = mg_strdup(name.sysname);
  9817. #endif
  9818. }
  9819. struct mg_context *mg_start(const struct mg_callbacks *callbacks,
  9820. void *user_data,
  9821. const char **options)
  9822. {
  9823. struct mg_context *ctx;
  9824. const char *name, *value, *default_value;
  9825. int idx, ok, workerthreadcount;
  9826. unsigned int i;
  9827. void (*exit_callback)(const struct mg_context *ctx) = 0;
  9828. struct mg_workerTLS tls;
  9829. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  9830. WSADATA data;
  9831. WSAStartup(MAKEWORD(2, 2), &data);
  9832. #if defined(_MSC_VER)
  9833. #pragma warning(suppress : 28125)
  9834. #endif
  9835. if (!sTlsInit) {
  9836. InitializeCriticalSection(&global_log_file_lock);
  9837. }
  9838. #endif /* _WIN32 && !__SYMBIAN32__ */
  9839. /* Allocate context and initialize reasonable general case defaults. */
  9840. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  9841. return NULL;
  9842. }
  9843. if (mg_atomic_inc(&sTlsInit) == 1) {
  9844. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  9845. /* Fatal error - abort start. However, this situation should never
  9846. * occur in practice. */
  9847. mg_atomic_dec(&sTlsInit);
  9848. mg_cry(fc(ctx), "Cannot initialize thread local storage");
  9849. mg_free(ctx);
  9850. return NULL;
  9851. }
  9852. } else {
  9853. /* TODO (low): istead of sleeping, check if sTlsKey is already
  9854. * initialized. */
  9855. mg_sleep(1);
  9856. }
  9857. tls.is_master = -1;
  9858. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  9859. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  9860. tls.pthread_cond_helper_mutex = NULL;
  9861. #endif
  9862. pthread_setspecific(sTlsKey, &tls);
  9863. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, NULL);
  9864. ok &= 0 == pthread_cond_init(&ctx->thread_cond, NULL);
  9865. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  9866. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  9867. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, NULL);
  9868. if (!ok) {
  9869. /* Fatal error - abort start. However, this situation should never
  9870. * occur in practice. */
  9871. mg_cry(fc(ctx), "Cannot initialize thread synchronization objects");
  9872. mg_free(ctx);
  9873. pthread_setspecific(sTlsKey, NULL);
  9874. return NULL;
  9875. }
  9876. if (callbacks) {
  9877. ctx->callbacks = *callbacks;
  9878. exit_callback = callbacks->exit_context;
  9879. ctx->callbacks.exit_context = 0;
  9880. }
  9881. ctx->user_data = user_data;
  9882. ctx->request_handlers = NULL;
  9883. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  9884. ctx->shared_lua_websockets = 0;
  9885. #endif
  9886. while (options && (name = *options++) != NULL) {
  9887. if ((idx = get_option_index(name)) == -1) {
  9888. mg_cry(fc(ctx), "Invalid option: %s", name);
  9889. free_context(ctx);
  9890. pthread_setspecific(sTlsKey, NULL);
  9891. return NULL;
  9892. } else if ((value = *options++) == NULL) {
  9893. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  9894. free_context(ctx);
  9895. pthread_setspecific(sTlsKey, NULL);
  9896. return NULL;
  9897. }
  9898. if (ctx->config[idx] != NULL) {
  9899. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  9900. mg_free(ctx->config[idx]);
  9901. }
  9902. ctx->config[idx] = mg_strdup(value);
  9903. DEBUG_TRACE("[%s] -> [%s]", name, value);
  9904. }
  9905. /* Set default value if needed */
  9906. for (i = 0; config_options[i].name != NULL; i++) {
  9907. default_value = config_options[i].default_value;
  9908. if (ctx->config[i] == NULL && default_value != NULL) {
  9909. ctx->config[i] = mg_strdup(default_value);
  9910. }
  9911. }
  9912. #if defined(NO_FILES)
  9913. if (ctx->config[DOCUMENT_ROOT] != NULL) {
  9914. mg_cry(fc(ctx), "%s", "Document root must not be set");
  9915. free_context(ctx);
  9916. pthread_setspecific(sTlsKey, NULL);
  9917. return NULL;
  9918. }
  9919. #endif
  9920. get_system_name(&ctx->systemName);
  9921. /* NOTE(lsm): order is important here. SSL certificates must
  9922. * be initialized before listening ports. UID must be set last. */
  9923. if (!set_gpass_option(ctx) ||
  9924. #if !defined(NO_SSL)
  9925. !set_ssl_option(ctx) ||
  9926. #endif
  9927. !set_ports_option(ctx) ||
  9928. #if !defined(_WIN32)
  9929. !set_uid_option(ctx) ||
  9930. #endif
  9931. !set_acl_option(ctx)) {
  9932. free_context(ctx);
  9933. pthread_setspecific(sTlsKey, NULL);
  9934. return NULL;
  9935. }
  9936. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  9937. /* Ignore SIGPIPE signal, so if browser cancels the request, it
  9938. * won't kill the whole process. */
  9939. (void)signal(SIGPIPE, SIG_IGN);
  9940. #endif /* !_WIN32 && !__SYMBIAN32__ */
  9941. workerthreadcount = atoi(ctx->config[NUM_THREADS]);
  9942. if (workerthreadcount > MAX_WORKER_THREADS) {
  9943. mg_cry(fc(ctx), "Too many worker threads");
  9944. free_context(ctx);
  9945. pthread_setspecific(sTlsKey, NULL);
  9946. return NULL;
  9947. }
  9948. if (workerthreadcount > 0) {
  9949. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  9950. ctx->workerthreadids =
  9951. (pthread_t *)mg_calloc(ctx->cfg_worker_threads, sizeof(pthread_t));
  9952. if (ctx->workerthreadids == NULL) {
  9953. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  9954. free_context(ctx);
  9955. pthread_setspecific(sTlsKey, NULL);
  9956. return NULL;
  9957. }
  9958. }
  9959. #if defined(USE_TIMERS)
  9960. if (timers_init(ctx) != 0) {
  9961. mg_cry(fc(ctx), "Error creating timers");
  9962. free_context(ctx);
  9963. pthread_setspecific(sTlsKey, NULL);
  9964. return NULL;
  9965. }
  9966. #endif
  9967. /* Context has been created - init user libraries */
  9968. if (ctx->callbacks.init_context) {
  9969. ctx->callbacks.init_context(ctx);
  9970. }
  9971. ctx->callbacks.exit_context = exit_callback;
  9972. ctx->context_type = 1; /* server context */
  9973. /* Start master (listening) thread */
  9974. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  9975. /* Start worker threads */
  9976. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  9977. (void)pthread_mutex_lock(&ctx->thread_mutex);
  9978. ctx->running_worker_threads++;
  9979. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  9980. if (mg_start_thread_with_id(
  9981. worker_thread, ctx, &ctx->workerthreadids[i]) != 0) {
  9982. (void)pthread_mutex_lock(&ctx->thread_mutex);
  9983. ctx->running_worker_threads--;
  9984. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  9985. if (i > 0) {
  9986. mg_cry(fc(ctx),
  9987. "Cannot start worker thread %i: error %ld",
  9988. i + 1,
  9989. (long)ERRNO);
  9990. } else {
  9991. mg_cry(
  9992. fc(ctx), "Cannot create threads: error %ld", (long)ERRNO);
  9993. free_context(ctx);
  9994. pthread_setspecific(sTlsKey, NULL);
  9995. return NULL;
  9996. }
  9997. break;
  9998. }
  9999. }
  10000. pthread_setspecific(sTlsKey, NULL);
  10001. return ctx;
  10002. }
  10003. /* Feature check API function */
  10004. unsigned mg_check_feature(unsigned feature)
  10005. {
  10006. static const unsigned feature_set = 0
  10007. /* Set bits for available features according to API documentation. */
  10008. #if !defined(NO_FILES)
  10009. | 1
  10010. #endif
  10011. #if !defined(NO_SSL)
  10012. | 2
  10013. #endif
  10014. #if !defined(NO_CGI)
  10015. | 4
  10016. #endif
  10017. #if defined(USE_IPV6)
  10018. | 8
  10019. #endif
  10020. #if defined(USE_WEBSOCKET)
  10021. | 16
  10022. #endif
  10023. #if defined(USE_LUA)
  10024. | 32
  10025. #endif
  10026. /* Set some extra bits not defined in the API documentation.
  10027. * These bits may change without further notice. */
  10028. #if !defined(NO_POPEN)
  10029. | 64
  10030. #endif
  10031. #if defined(MG_LEGACY_INTERFACE)
  10032. | 128
  10033. #endif
  10034. #if defined(MEMORY_DEBUGGING)
  10035. | 256
  10036. #endif
  10037. #if defined(USE_TIMERS)
  10038. | 512
  10039. #endif
  10040. #if !defined(NO_NONCE_CHECK)
  10041. | 1024
  10042. #endif
  10043. ;
  10044. return (feature & feature_set);
  10045. }