civetweb.c 290 KB

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