civetweb.c 275 KB

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