civetweb.c 279 KB

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