civetweb.c 333 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878
  1. /* Copyright (c) 2013-2016 the Civetweb developers
  2. * Copyright (c) 2004-2013 Sergey Lyubka
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. * THE SOFTWARE.
  21. */
  22. #if defined(_WIN32)
  23. #if !defined(_CRT_SECURE_NO_WARNINGS)
  24. #define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */
  25. #endif
  26. #ifndef _WIN32_WINNT /* defined for tdm-gcc so we can use getnameinfo */
  27. #define _WIN32_WINNT 0x0501
  28. #endif
  29. #else
  30. #if defined(__GNUC__) && !defined(_GNU_SOURCE)
  31. #define _GNU_SOURCE /* for setgroups() */
  32. #endif
  33. #if defined(__linux__) && !defined(_XOPEN_SOURCE)
  34. #define _XOPEN_SOURCE 600 /* For flockfile() on Linux */
  35. #endif
  36. #ifndef _LARGEFILE_SOURCE
  37. #define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
  38. #endif
  39. #ifndef _FILE_OFFSET_BITS
  40. #define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
  41. #endif
  42. #ifndef __STDC_FORMAT_MACROS
  43. #define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
  44. #endif
  45. #ifndef __STDC_LIMIT_MACROS
  46. #define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
  47. #endif
  48. #ifdef __sun
  49. #define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */
  50. #define __inline inline /* not recognized on older compiler versions */
  51. #endif
  52. #endif
  53. #if defined(USE_LUA) && 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
  123. clock_gettime(int clk_id, struct timespec *t)
  124. {
  125. memset(t, 0, sizeof(*t));
  126. if (clk_id == CLOCK_REALTIME) {
  127. struct timeval now;
  128. int rv = gettimeofday(&now, NULL);
  129. if (rv) {
  130. return rv;
  131. }
  132. t->tv_sec = now.tv_sec;
  133. t->tv_nsec = now.tv_usec * 1000;
  134. return 0;
  135. } else if (clk_id == CLOCK_MONOTONIC) {
  136. static uint64_t clock_start_time = 0;
  137. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  138. uint64_t now = mach_absolute_time();
  139. if (clock_start_time == 0) {
  140. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  141. #if defined(DEBUG)
  142. assert(mach_status == KERN_SUCCESS);
  143. #else
  144. /* appease "unused variable" warning for release builds */
  145. (void)mach_status;
  146. #endif
  147. clock_start_time = now;
  148. }
  149. now = (uint64_t)((double)(now - clock_start_time)
  150. * (double)timebase_ifo.numer
  151. / (double)timebase_ifo.denom);
  152. t->tv_sec = now / 1000000000;
  153. t->tv_nsec = now % 1000000000;
  154. return 0;
  155. }
  156. return -1; /* EINVAL - Clock ID is unknown */
  157. }
  158. #endif
  159. #include <time.h>
  160. #include <stdlib.h>
  161. #include <stdarg.h>
  162. #include <assert.h>
  163. #include <string.h>
  164. #include <ctype.h>
  165. #include <limits.h>
  166. #include <stddef.h>
  167. #include <stdio.h>
  168. #ifndef MAX_WORKER_THREADS
  169. #define MAX_WORKER_THREADS (1024 * 64)
  170. #endif
  171. #ifndef SOCKET_TIMEOUT_QUANTUM
  172. #define SOCKET_TIMEOUT_QUANTUM (10000)
  173. #endif
  174. mg_static_assert(MAX_WORKER_THREADS >= 1,
  175. "worker threads must be a positive number");
  176. #if defined(_WIN32) \
  177. && !defined(__SYMBIAN32__) /* WINDOWS / UNIX include block */
  178. #include <windows.h>
  179. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  180. #include <ws2tcpip.h>
  181. typedef const char *SOCK_OPT_TYPE;
  182. #if !defined(PATH_MAX)
  183. #define PATH_MAX (MAX_PATH)
  184. #endif
  185. #if !defined(PATH_MAX)
  186. #define PATH_MAX (4096)
  187. #endif
  188. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  189. #ifndef _IN_PORT_T
  190. #ifndef in_port_t
  191. #define in_port_t u_short
  192. #endif
  193. #endif
  194. #ifndef _WIN32_WCE
  195. #include <process.h>
  196. #include <direct.h>
  197. #include <io.h>
  198. #else /* _WIN32_WCE */
  199. #define NO_CGI /* WinCE has no pipes */
  200. typedef long off_t;
  201. #define errno ((int)(GetLastError()))
  202. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  203. #endif /* _WIN32_WCE */
  204. #define MAKEUQUAD(lo, hi) \
  205. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  206. #define RATE_DIFF (10000000) /* 100 nsecs */
  207. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  208. #define SYS2UNIX_TIME(lo, hi) \
  209. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  210. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  211. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  212. * Also use _strtoui64 on modern M$ compilers */
  213. #if defined(_MSC_VER)
  214. #if (_MSC_VER < 1300)
  215. #define STRX(x) #x
  216. #define STR(x) STRX(x)
  217. #define __func__ __FILE__ ":" STR(__LINE__)
  218. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  219. #define strtoll(x, y, z) (_atoi64(x))
  220. #else
  221. #define __func__ __FUNCTION__
  222. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  223. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  224. #endif
  225. #endif /* _MSC_VER */
  226. #define ERRNO ((int)(GetLastError()))
  227. #define NO_SOCKLEN_T
  228. #define SSL_LIB "ssleay32.dll"
  229. #define CRYPTO_LIB "libeay32.dll"
  230. #define O_NONBLOCK (0)
  231. #ifndef W_OK
  232. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  233. #endif
  234. #if !defined(EWOULDBLOCK)
  235. #define EWOULDBLOCK WSAEWOULDBLOCK
  236. #endif /* !EWOULDBLOCK */
  237. #define _POSIX_
  238. #define INT64_FMT "I64d"
  239. #define UINT64_FMT "I64u"
  240. #define WINCDECL __cdecl
  241. #define SHUT_RD (0)
  242. #define SHUT_WR (1)
  243. #define SHUT_BOTH (2)
  244. #define vsnprintf_impl _vsnprintf
  245. #define access _access
  246. #define mg_sleep(x) (Sleep(x))
  247. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  248. #ifndef popen
  249. #define popen(x, y) (_popen(x, y))
  250. #endif
  251. #ifndef pclose
  252. #define pclose(x) (_pclose(x))
  253. #endif
  254. #define close(x) (_close(x))
  255. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  256. #define RTLD_LAZY (0)
  257. #define fseeko(x, y, z) (_lseeki64(_fileno(x), (y), (z)) == -1 ? -1 : 0)
  258. #define fdopen(x, y) (_fdopen((x), (y)))
  259. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  260. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  261. #define flockfile(x) (EnterCriticalSection(&global_log_file_lock))
  262. #define funlockfile(x) (LeaveCriticalSection(&global_log_file_lock))
  263. #define sleep(x) (Sleep((x)*1000))
  264. #define rmdir(x) (_rmdir(x))
  265. #define timegm(x) (_mkgmtime(x))
  266. #if !defined(fileno)
  267. #define fileno(x) (_fileno(x))
  268. #endif /* !fileno MINGW #defines fileno */
  269. typedef HANDLE pthread_mutex_t;
  270. typedef DWORD pthread_key_t;
  271. typedef HANDLE pthread_t;
  272. typedef struct {
  273. CRITICAL_SECTION threadIdSec;
  274. int waitingthreadcount; /* The number of threads queued. */
  275. pthread_t *waitingthreadhdls; /* The thread handles. */
  276. } pthread_cond_t;
  277. #ifndef __clockid_t_defined
  278. typedef DWORD clockid_t;
  279. #endif
  280. #ifndef CLOCK_MONOTONIC
  281. #define CLOCK_MONOTONIC (1)
  282. #endif
  283. #ifndef CLOCK_REALTIME
  284. #define CLOCK_REALTIME (2)
  285. #endif
  286. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  287. #define _TIMESPEC_DEFINED
  288. #endif
  289. #ifndef _TIMESPEC_DEFINED
  290. struct timespec {
  291. time_t tv_sec; /* seconds */
  292. long tv_nsec; /* nanoseconds */
  293. };
  294. #endif
  295. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  296. static int pthread_mutex_lock(pthread_mutex_t *);
  297. static int pthread_mutex_unlock(pthread_mutex_t *);
  298. static void to_unicode(const char *path, wchar_t *wbuf, size_t wbuf_len);
  299. struct file;
  300. static char *mg_fgets(char *buf, size_t size, struct file *filep, char **p);
  301. #if defined(HAVE_STDINT)
  302. #include <stdint.h>
  303. #else
  304. typedef unsigned char uint8_t;
  305. typedef unsigned short uint16_t;
  306. typedef unsigned int uint32_t;
  307. typedef unsigned __int64 uint64_t;
  308. typedef __int64 int64_t;
  309. #define INT64_MAX (9223372036854775807)
  310. #endif /* HAVE_STDINT */
  311. /* POSIX dirent interface */
  312. struct dirent {
  313. char d_name[PATH_MAX];
  314. };
  315. typedef struct DIR {
  316. HANDLE handle;
  317. WIN32_FIND_DATAW info;
  318. struct dirent result;
  319. } DIR;
  320. #if defined(_WIN32) && !defined(POLLIN)
  321. #ifndef HAVE_POLL
  322. struct pollfd {
  323. SOCKET fd;
  324. short events;
  325. short revents;
  326. };
  327. #define POLLIN (0x0300)
  328. #endif
  329. #endif
  330. /* Mark required libraries */
  331. #if defined(_MSC_VER)
  332. #pragma comment(lib, "Ws2_32.lib")
  333. #endif
  334. #else /* defined(_WIN32) && !defined(__SYMBIAN32__) - WINDOWS / UNIX include \
  335. block */
  336. #include <sys/wait.h>
  337. #include <sys/socket.h>
  338. #include <sys/poll.h>
  339. #include <netinet/in.h>
  340. #include <arpa/inet.h>
  341. #include <sys/time.h>
  342. #include <sys/utsname.h>
  343. #include <stdint.h>
  344. #include <inttypes.h>
  345. #include <netdb.h>
  346. #include <netinet/tcp.h>
  347. typedef const void *SOCK_OPT_TYPE;
  348. #if defined(ANDROID)
  349. typedef unsigned short int in_port_t;
  350. #endif
  351. #include <pwd.h>
  352. #include <unistd.h>
  353. #include <grp.h>
  354. #include <dirent.h>
  355. #define vsnprintf_impl vsnprintf
  356. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  357. #include <dlfcn.h>
  358. #endif
  359. #include <pthread.h>
  360. #if defined(__MACH__)
  361. #define SSL_LIB "libssl.dylib"
  362. #define CRYPTO_LIB "libcrypto.dylib"
  363. #else
  364. #if !defined(SSL_LIB)
  365. #define SSL_LIB "libssl.so"
  366. #endif
  367. #if !defined(CRYPTO_LIB)
  368. #define CRYPTO_LIB "libcrypto.so"
  369. #endif
  370. #endif
  371. #ifndef O_BINARY
  372. #define O_BINARY (0)
  373. #endif /* O_BINARY */
  374. #define closesocket(a) (close(a))
  375. #define mg_mkdir(x, y) (mkdir(x, y))
  376. #define mg_remove(x) (remove(x))
  377. #define mg_sleep(x) (usleep((x)*1000))
  378. #define ERRNO (errno)
  379. #define INVALID_SOCKET (-1)
  380. #define INT64_FMT PRId64
  381. #define UINT64_FMT PRIu64
  382. typedef int SOCKET;
  383. #define WINCDECL
  384. #if defined(__hpux)
  385. /* HPUX 11 does not have monotonic, fall back to realtime */
  386. #ifndef CLOCK_MONOTONIC
  387. #define CLOCK_MONOTONIC CLOCK_REALTIME
  388. #endif
  389. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  390. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  391. * the prototypes use int* rather than socklen_t* which matches the
  392. * actual library expectation. When called with the wrong size arg
  393. * accept() returns a zero client inet addr and check_acl() always
  394. * fails. Since socklen_t is widely used below, just force replace
  395. * their typedef with int. - DTL
  396. */
  397. #define socklen_t int
  398. #endif /* hpux */
  399. #endif /* defined(_WIN32) && !defined(__SYMBIAN32__) - WINDOWS / UNIX include \
  400. block */
  401. /* va_copy should always be a macro, C99 and C++11 - DTL */
  402. #ifndef va_copy
  403. #define va_copy(x, y) ((x) = (y))
  404. #endif
  405. #ifdef _WIN32
  406. /* Create substitutes for POSIX functions in Win32. */
  407. #if defined(__MINGW32__)
  408. /* Show no warning in case system functions are not used. */
  409. #pragma GCC diagnostic push
  410. #pragma GCC diagnostic ignored "-Wunused-function"
  411. #endif
  412. static CRITICAL_SECTION global_log_file_lock;
  413. static DWORD
  414. pthread_self(void)
  415. {
  416. return GetCurrentThreadId();
  417. }
  418. static int
  419. pthread_key_create(
  420. pthread_key_t *key,
  421. void (*_ignored)(void *) /* destructor not supported for Windows */
  422. )
  423. {
  424. (void)_ignored;
  425. if ((key != 0)) {
  426. *key = TlsAlloc();
  427. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  428. }
  429. return -2;
  430. }
  431. static int
  432. pthread_key_delete(pthread_key_t key)
  433. {
  434. return TlsFree(key) ? 0 : 1;
  435. }
  436. static int
  437. pthread_setspecific(pthread_key_t key, void *value)
  438. {
  439. return TlsSetValue(key, value) ? 0 : 1;
  440. }
  441. static void *
  442. pthread_getspecific(pthread_key_t key)
  443. {
  444. return TlsGetValue(key);
  445. }
  446. #if defined(__MINGW32__)
  447. /* Enable unused function warning again */
  448. #pragma GCC diagnostic pop
  449. #endif
  450. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  451. #else
  452. static pthread_mutexattr_t pthread_mutex_attr;
  453. #endif /* _WIN32 */
  454. #include "civetweb.h"
  455. #define PASSWORDS_FILE_NAME ".htpasswd"
  456. #define CGI_ENVIRONMENT_SIZE (4096)
  457. #define MAX_CGI_ENVIR_VARS (256)
  458. #define MG_BUF_LEN (8192)
  459. #ifndef MAX_REQUEST_SIZE
  460. #define MAX_REQUEST_SIZE (16384)
  461. #endif
  462. mg_static_assert(MAX_REQUEST_SIZE >= 256,
  463. "request size length must be a positive number");
  464. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  465. #if !defined(DEBUG_TRACE)
  466. #if defined(DEBUG)
  467. static void DEBUG_TRACE_FUNC(const char *func,
  468. unsigned line,
  469. PRINTF_FORMAT_STRING(const char *fmt),
  470. ...) PRINTF_ARGS(3, 4);
  471. static void
  472. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  473. {
  474. va_list args;
  475. flockfile(stdout);
  476. printf("*** %lu.%p.%s.%u: ",
  477. (unsigned long)time(NULL),
  478. (void *)pthread_self(),
  479. func,
  480. line);
  481. va_start(args, fmt);
  482. vprintf(fmt, args);
  483. va_end(args);
  484. putchar('\n');
  485. fflush(stdout);
  486. funlockfile(stdout);
  487. }
  488. #define DEBUG_TRACE(fmt, ...) \
  489. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  490. #else
  491. #define DEBUG_TRACE(fmt, ...) \
  492. do { \
  493. } while (0)
  494. #endif /* DEBUG */
  495. #endif /* DEBUG_TRACE */
  496. #if defined(MEMORY_DEBUGGING)
  497. unsigned long mg_memory_debug_blockCount = 0;
  498. unsigned long mg_memory_debug_totalMemUsed = 0;
  499. static void *
  500. mg_malloc_ex(size_t size, const char *file, unsigned line)
  501. {
  502. void *data = malloc(size + sizeof(size_t));
  503. void *memory = 0;
  504. char mallocStr[256];
  505. if (data) {
  506. *(size_t *)data = size;
  507. mg_memory_debug_totalMemUsed += size;
  508. mg_memory_debug_blockCount++;
  509. memory = (void *)(((char *)data) + sizeof(size_t));
  510. }
  511. sprintf(mallocStr,
  512. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  513. memory,
  514. (unsigned long)size,
  515. mg_memory_debug_totalMemUsed,
  516. mg_memory_debug_blockCount,
  517. file,
  518. line);
  519. #if defined(_WIN32)
  520. OutputDebugStringA(mallocStr);
  521. #else
  522. DEBUG_TRACE("%s", mallocStr);
  523. #endif
  524. return memory;
  525. }
  526. static void *
  527. mg_calloc_ex(size_t count, size_t size, const char *file, unsigned line)
  528. {
  529. void *data = mg_malloc_ex(size * count, file, line);
  530. if (data) {
  531. memset(data, 0, size);
  532. }
  533. return data;
  534. }
  535. static void
  536. mg_free_ex(void *memory, const char *file, unsigned line)
  537. {
  538. char mallocStr[256];
  539. void *data = (void *)(((char *)memory) - sizeof(size_t));
  540. size_t size;
  541. if (memory) {
  542. size = *(size_t *)data;
  543. mg_memory_debug_totalMemUsed -= size;
  544. mg_memory_debug_blockCount--;
  545. sprintf(mallocStr,
  546. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  547. memory,
  548. (unsigned long)size,
  549. mg_memory_debug_totalMemUsed,
  550. mg_memory_debug_blockCount,
  551. file,
  552. line);
  553. #if defined(_WIN32)
  554. OutputDebugStringA(mallocStr);
  555. #else
  556. DEBUG_TRACE("%s", mallocStr);
  557. #endif
  558. free(data);
  559. }
  560. }
  561. static void *
  562. mg_realloc_ex(void *memory, size_t newsize, const char *file, unsigned line)
  563. {
  564. char mallocStr[256];
  565. void *data;
  566. void *_realloc;
  567. size_t oldsize;
  568. if (newsize) {
  569. if (memory) {
  570. data = (void *)(((char *)memory) - sizeof(size_t));
  571. oldsize = *(size_t *)data;
  572. _realloc = realloc(data, newsize + sizeof(size_t));
  573. if (_realloc) {
  574. data = _realloc;
  575. mg_memory_debug_totalMemUsed -= oldsize;
  576. sprintf(mallocStr,
  577. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  578. memory,
  579. (unsigned long)oldsize,
  580. mg_memory_debug_totalMemUsed,
  581. mg_memory_debug_blockCount,
  582. file,
  583. line);
  584. #if defined(_WIN32)
  585. OutputDebugStringA(mallocStr);
  586. #else
  587. DEBUG_TRACE("%s", mallocStr);
  588. #endif
  589. mg_memory_debug_totalMemUsed += newsize;
  590. sprintf(mallocStr,
  591. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  592. memory,
  593. (unsigned long)newsize,
  594. mg_memory_debug_totalMemUsed,
  595. mg_memory_debug_blockCount,
  596. file,
  597. line);
  598. #if defined(_WIN32)
  599. OutputDebugStringA(mallocStr);
  600. #else
  601. DEBUG_TRACE("%s", mallocStr);
  602. #endif
  603. *(size_t *)data = newsize;
  604. data = (void *)(((char *)data) + sizeof(size_t));
  605. } else {
  606. #if defined(_WIN32)
  607. OutputDebugStringA("MEM: realloc failed\n");
  608. #else
  609. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  610. #endif
  611. return _realloc;
  612. }
  613. } else {
  614. data = mg_malloc_ex(newsize, file, line);
  615. }
  616. } else {
  617. data = 0;
  618. mg_free_ex(memory, file, line);
  619. }
  620. return data;
  621. }
  622. #define mg_malloc(a) mg_malloc_ex(a, __FILE__, __LINE__)
  623. #define mg_calloc(a, b) mg_calloc_ex(a, b, __FILE__, __LINE__)
  624. #define mg_realloc(a, b) mg_realloc_ex(a, b, __FILE__, __LINE__)
  625. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  626. #else
  627. static __inline void *
  628. mg_malloc(size_t a)
  629. {
  630. return malloc(a);
  631. }
  632. static __inline void *
  633. mg_calloc(size_t a, size_t b)
  634. {
  635. return calloc(a, b);
  636. }
  637. static __inline void *
  638. mg_realloc(void *a, size_t b)
  639. {
  640. return realloc(a, b);
  641. }
  642. static __inline void
  643. mg_free(void *a)
  644. {
  645. free(a);
  646. }
  647. #endif
  648. static void mg_vsnprintf(const struct mg_connection *conn,
  649. int *truncated,
  650. char *buf,
  651. size_t buflen,
  652. const char *fmt,
  653. va_list ap);
  654. static void mg_snprintf(const struct mg_connection *conn,
  655. int *truncated,
  656. char *buf,
  657. size_t buflen,
  658. PRINTF_FORMAT_STRING(const char *fmt),
  659. ...) PRINTF_ARGS(5, 6);
  660. /* This following lines are just meant as a reminder to use the mg-functions
  661. * for memory management */
  662. #ifdef malloc
  663. #undef malloc
  664. #endif
  665. #ifdef calloc
  666. #undef calloc
  667. #endif
  668. #ifdef realloc
  669. #undef realloc
  670. #endif
  671. #ifdef free
  672. #undef free
  673. #endif
  674. #ifdef snprintf
  675. #undef snprintf
  676. #endif
  677. #ifdef vsnprintf
  678. #undef vsnprintf
  679. #endif
  680. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  681. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  682. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  683. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  684. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  685. #ifdef _WIN32 /* vsnprintf must not be used in any system, * \
  686. * but this define only works well for Windows. */
  687. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  688. #endif
  689. #define MD5_STATIC static
  690. #include "md5.inl"
  691. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  692. #ifdef NO_SOCKLEN_T
  693. typedef int socklen_t;
  694. #endif /* NO_SOCKLEN_T */
  695. #define _DARWIN_UNLIMITED_SELECT
  696. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  697. #if !defined(MSG_NOSIGNAL)
  698. #define MSG_NOSIGNAL (0)
  699. #endif
  700. #if !defined(SOMAXCONN)
  701. #define SOMAXCONN (100)
  702. #endif
  703. /* Size of the accepted socket queue */
  704. #if !defined(MGSQLEN)
  705. #define MGSQLEN (20)
  706. #endif
  707. #if defined(NO_SSL_DL)
  708. #include <openssl/ssl.h>
  709. #include <openssl/err.h>
  710. #include <openssl/crypto.h>
  711. #include <openssl/x509.h>
  712. #include <openssl/pem.h>
  713. #else
  714. /* SSL loaded dynamically from DLL.
  715. * I put the prototypes here to be independent from OpenSSL source
  716. * installation. */
  717. typedef struct ssl_st SSL;
  718. typedef struct ssl_method_st SSL_METHOD;
  719. typedef struct ssl_ctx_st SSL_CTX;
  720. typedef struct x509_store_ctx_st X509_STORE_CTX;
  721. #define SSL_CTRL_OPTIONS (32)
  722. #define SSL_CTRL_CLEAR_OPTIONS (77)
  723. #define SSL_CTRL_SET_ECDH_AUTO (94)
  724. #define SSL_VERIFY_NONE (0)
  725. #define SSL_VERIFY_PEER (1)
  726. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  727. #define SSL_VERIFY_CLIENT_ONCE (4)
  728. #define SSL_OP_ALL (0x80000BFFL)
  729. #define SSL_OP_NO_SSLv2 (0x01000000L)
  730. #define SSL_OP_NO_SSLv3 (0x02000000L)
  731. #define SSL_OP_NO_TLSv1 (0x04000000L)
  732. #define SSL_OP_NO_TLSv1_2 (0x08000000L)
  733. #define SSL_OP_NO_TLSv1_1 (0x10000000L)
  734. #define SSL_OP_SINGLE_DH_USE (0x00100000L)
  735. struct ssl_func {
  736. const char *name; /* SSL function name */
  737. void (*ptr)(void); /* Function pointer */
  738. };
  739. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  740. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  741. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  742. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  743. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  744. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  745. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  746. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  747. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  748. #define SSLv23_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  749. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  750. #define SSL_CTX_use_PrivateKey_file \
  751. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  752. #define SSL_CTX_use_certificate_file \
  753. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  754. #define SSL_CTX_set_default_passwd_cb \
  755. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  756. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  757. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  758. #define SSL_CTX_use_certificate_chain_file \
  759. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  760. #define SSLv23_client_method (*(SSL_METHOD * (*)(void))ssl_sw[17].ptr)
  761. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  762. #define SSL_CTX_set_verify \
  763. (*(void (*)(SSL_CTX *, \
  764. int, \
  765. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19].ptr)
  766. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  767. #define SSL_CTX_load_verify_locations \
  768. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  769. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  770. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  771. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[24].ptr)
  772. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  773. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[26].ptr)
  774. #define SSL_CIPHER_get_name \
  775. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  776. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  777. #define SSL_CTX_set_session_id_context \
  778. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  779. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  780. #define SSL_CTX_set_cipher_list \
  781. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  782. #define SSL_CTX_set_options(ctx, op) \
  783. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  784. #define SSL_CTX_clear_options(ctx, op) \
  785. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  786. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  787. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  788. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  789. #define CRYPTO_set_locking_callback \
  790. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  791. #define CRYPTO_set_id_callback \
  792. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  793. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  794. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  795. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  796. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  797. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  798. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  799. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  800. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  801. /* set_ssl_option() function updates this array.
  802. * It loads SSL library dynamically and changes NULLs to the actual addresses
  803. * of respective functions. The macros above (like SSL_connect()) are really
  804. * just calling these functions indirectly via the pointer. */
  805. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  806. {"SSL_accept", NULL},
  807. {"SSL_connect", NULL},
  808. {"SSL_read", NULL},
  809. {"SSL_write", NULL},
  810. {"SSL_get_error", NULL},
  811. {"SSL_set_fd", NULL},
  812. {"SSL_new", NULL},
  813. {"SSL_CTX_new", NULL},
  814. {"SSLv23_server_method", NULL},
  815. {"SSL_library_init", NULL},
  816. {"SSL_CTX_use_PrivateKey_file", NULL},
  817. {"SSL_CTX_use_certificate_file", NULL},
  818. {"SSL_CTX_set_default_passwd_cb", NULL},
  819. {"SSL_CTX_free", NULL},
  820. {"SSL_load_error_strings", NULL},
  821. {"SSL_CTX_use_certificate_chain_file", NULL},
  822. {"SSLv23_client_method", NULL},
  823. {"SSL_pending", NULL},
  824. {"SSL_CTX_set_verify", NULL},
  825. {"SSL_shutdown", NULL},
  826. {"SSL_CTX_load_verify_locations", NULL},
  827. {"SSL_CTX_set_default_verify_paths", NULL},
  828. {"SSL_CTX_set_verify_depth", NULL},
  829. {"SSL_get_peer_certificate", NULL},
  830. {"SSL_get_version", NULL},
  831. {"SSL_get_current_cipher", NULL},
  832. {"SSL_CIPHER_get_name", NULL},
  833. {"SSL_CTX_check_private_key", NULL},
  834. {"SSL_CTX_set_session_id_context", NULL},
  835. {"SSL_CTX_ctrl", NULL},
  836. {"SSL_CTX_set_cipher_list", NULL},
  837. {NULL, NULL}};
  838. /* Similar array as ssl_sw. These functions could be located in different
  839. * lib. */
  840. #if !defined(NO_SSL)
  841. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  842. {"CRYPTO_set_locking_callback", NULL},
  843. {"CRYPTO_set_id_callback", NULL},
  844. {"ERR_get_error", NULL},
  845. {"ERR_error_string", NULL},
  846. {"ERR_remove_state", NULL},
  847. {"ERR_free_strings", NULL},
  848. {"ENGINE_cleanup", NULL},
  849. {"CONF_modules_unload", NULL},
  850. {"CRYPTO_cleanup_all_ex_data", NULL},
  851. {"EVP_cleanup", NULL},
  852. {NULL, NULL}};
  853. #endif /* NO_SSL */
  854. #endif /* NO_SSL_DL */
  855. static const char *month_names[] = {"Jan",
  856. "Feb",
  857. "Mar",
  858. "Apr",
  859. "May",
  860. "Jun",
  861. "Jul",
  862. "Aug",
  863. "Sep",
  864. "Oct",
  865. "Nov",
  866. "Dec"};
  867. /* Unified socket address. For IPv6 support, add IPv6 address structure in the
  868. * union u. */
  869. union usa {
  870. struct sockaddr sa;
  871. struct sockaddr_in sin;
  872. #if defined(USE_IPV6)
  873. struct sockaddr_in6 sin6;
  874. #endif
  875. };
  876. /* Describes a string (chunk of memory). */
  877. struct vec {
  878. const char *ptr;
  879. size_t len;
  880. };
  881. struct file {
  882. uint64_t size;
  883. time_t last_modified;
  884. FILE *fp;
  885. const char *membuf; /* Non-NULL if file data is in memory */
  886. int is_directory;
  887. int gzipped; /* set to 1 if the content is gzipped
  888. * in which case we need a content-encoding: gzip header */
  889. };
  890. #define STRUCT_FILE_INITIALIZER \
  891. { \
  892. (uint64_t)0, (time_t)0, (FILE *)NULL, (const char *)NULL, 0, 0 \
  893. }
  894. /* Describes listening socket, or socket which was accept()-ed by the master
  895. * thread and queued for future handling by the worker thread. */
  896. struct socket {
  897. SOCKET sock; /* Listening socket */
  898. union usa lsa; /* Local socket address */
  899. union usa rsa; /* Remote socket address */
  900. unsigned char is_ssl; /* Is port SSL-ed */
  901. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  902. * port */
  903. };
  904. /* NOTE(lsm): this enum shoulds be in sync with the config_options below. */
  905. enum {
  906. CGI_EXTENSIONS,
  907. CGI_ENVIRONMENT,
  908. PUT_DELETE_PASSWORDS_FILE,
  909. CGI_INTERPRETER,
  910. PROTECT_URI,
  911. AUTHENTICATION_DOMAIN,
  912. SSI_EXTENSIONS,
  913. THROTTLE,
  914. ACCESS_LOG_FILE,
  915. ENABLE_DIRECTORY_LISTING,
  916. ERROR_LOG_FILE,
  917. GLOBAL_PASSWORDS_FILE,
  918. INDEX_FILES,
  919. ENABLE_KEEP_ALIVE,
  920. ACCESS_CONTROL_LIST,
  921. EXTRA_MIME_TYPES,
  922. LISTENING_PORTS,
  923. DOCUMENT_ROOT,
  924. SSL_CERTIFICATE,
  925. NUM_THREADS,
  926. RUN_AS_USER,
  927. REWRITE,
  928. HIDE_FILES,
  929. REQUEST_TIMEOUT,
  930. SSL_DO_VERIFY_PEER,
  931. SSL_CA_PATH,
  932. SSL_CA_FILE,
  933. SSL_VERIFY_DEPTH,
  934. SSL_DEFAULT_VERIFY_PATHS,
  935. SSL_CIPHER_LIST,
  936. SSL_PROTOCOL_VERSION,
  937. SSL_SHORT_TRUST,
  938. #if defined(USE_WEBSOCKET)
  939. WEBSOCKET_TIMEOUT,
  940. #endif
  941. DECODE_URL,
  942. #if defined(USE_LUA)
  943. LUA_PRELOAD_FILE,
  944. LUA_SCRIPT_EXTENSIONS,
  945. LUA_SERVER_PAGE_EXTENSIONS,
  946. #endif
  947. #if defined(USE_DUKTAPE)
  948. DUKTAPE_SCRIPT_EXTENSIONS,
  949. #endif
  950. #if defined(USE_WEBSOCKET)
  951. WEBSOCKET_ROOT,
  952. #endif
  953. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  954. LUA_WEBSOCKET_EXTENSIONS,
  955. #endif
  956. ACCESS_CONTROL_ALLOW_ORIGIN,
  957. ERROR_PAGES,
  958. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  959. * socket option typedef TCP_NODELAY. */
  960. STATIC_FILE_MAX_AGE,
  961. NUM_OPTIONS
  962. };
  963. /* Config option name, config types, default value */
  964. static struct mg_option config_options[] = {
  965. {"cgi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  966. {"cgi_environment", CONFIG_TYPE_STRING, NULL},
  967. {"put_delete_auth_file", CONFIG_TYPE_FILE, NULL},
  968. {"cgi_interpreter", CONFIG_TYPE_FILE, NULL},
  969. {"protect_uri", CONFIG_TYPE_STRING, NULL},
  970. {"authentication_domain", CONFIG_TYPE_STRING, "mydomain.com"},
  971. {"ssi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  972. {"throttle", CONFIG_TYPE_STRING, NULL},
  973. {"access_log_file", CONFIG_TYPE_FILE, NULL},
  974. {"enable_directory_listing", CONFIG_TYPE_BOOLEAN, "yes"},
  975. {"error_log_file", CONFIG_TYPE_FILE, NULL},
  976. {"global_auth_file", CONFIG_TYPE_FILE, NULL},
  977. {"index_files",
  978. CONFIG_TYPE_STRING,
  979. #ifdef USE_LUA
  980. "index.xhtml,index.html,index.htm,index.lp,index.lsp,index.lua,index.cgi,"
  981. "index.shtml,index.php"},
  982. #else
  983. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  984. #endif
  985. {"enable_keep_alive", CONFIG_TYPE_BOOLEAN, "no"},
  986. {"access_control_list", CONFIG_TYPE_STRING, NULL},
  987. {"extra_mime_types", CONFIG_TYPE_STRING, NULL},
  988. {"listening_ports", CONFIG_TYPE_STRING, "8080"},
  989. {"document_root", CONFIG_TYPE_DIRECTORY, NULL},
  990. {"ssl_certificate", CONFIG_TYPE_FILE, NULL},
  991. {"num_threads", CONFIG_TYPE_NUMBER, "50"},
  992. {"run_as_user", CONFIG_TYPE_STRING, NULL},
  993. {"url_rewrite_patterns", CONFIG_TYPE_STRING, NULL},
  994. {"hide_files_patterns", CONFIG_TYPE_EXT_PATTERN, NULL},
  995. {"request_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  996. {"ssl_verify_peer", CONFIG_TYPE_BOOLEAN, "no"},
  997. {"ssl_ca_path", CONFIG_TYPE_DIRECTORY, NULL},
  998. {"ssl_ca_file", CONFIG_TYPE_FILE, NULL},
  999. {"ssl_verify_depth", CONFIG_TYPE_NUMBER, "9"},
  1000. {"ssl_default_verify_paths", CONFIG_TYPE_BOOLEAN, "yes"},
  1001. {"ssl_cipher_list", CONFIG_TYPE_STRING, NULL},
  1002. {"ssl_protocol_version", CONFIG_TYPE_NUMBER, "0"},
  1003. {"ssl_short_trust", CONFIG_TYPE_BOOLEAN, "no"},
  1004. #if defined(USE_WEBSOCKET)
  1005. {"websocket_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1006. #endif
  1007. {"decode_url", CONFIG_TYPE_BOOLEAN, "yes"},
  1008. #if defined(USE_LUA)
  1009. {"lua_preload_file", CONFIG_TYPE_FILE, NULL},
  1010. {"lua_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1011. {"lua_server_page_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1012. #endif
  1013. #if defined(USE_DUKTAPE)
  1014. {"_experimental_duktape_script_pattern",
  1015. CONFIG_TYPE_EXT_PATTERN,
  1016. "**.ssjs$"}, /* TODO: redefine parameter */
  1017. #endif
  1018. #if defined(USE_WEBSOCKET)
  1019. {"websocket_root", CONFIG_TYPE_DIRECTORY, NULL},
  1020. #endif
  1021. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1022. {"lua_websocket_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1023. #endif
  1024. {"access_control_allow_origin", CONFIG_TYPE_STRING, "*"},
  1025. {"error_pages", CONFIG_TYPE_DIRECTORY, NULL},
  1026. {"tcp_nodelay", CONFIG_TYPE_NUMBER, "0"},
  1027. {"_experimental_static_file_max_age",
  1028. CONFIG_TYPE_NUMBER,
  1029. "3600"}, /* TODO: redefine parameter */
  1030. {NULL, CONFIG_TYPE_UNKNOWN, NULL}};
  1031. /* Check if the config_options and the corresponding enum have compatible
  1032. * sizes. */
  1033. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1034. == (NUM_OPTIONS + 1),
  1035. "config_options and enum not sync");
  1036. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1037. struct mg_handler_info {
  1038. /* Name/Pattern of the URI. */
  1039. char *uri;
  1040. size_t uri_len;
  1041. /* handler type */
  1042. int handler_type;
  1043. /* Handler for http/https or authorization requests. */
  1044. mg_request_handler handler;
  1045. /* Handler for ws/wss (websocket) requests. */
  1046. mg_websocket_connect_handler connect_handler;
  1047. mg_websocket_ready_handler ready_handler;
  1048. mg_websocket_data_handler data_handler;
  1049. mg_websocket_close_handler close_handler;
  1050. /* Handler for authorization requests */
  1051. mg_authorization_handler auth_handler;
  1052. /* User supplied argument for the handler function. */
  1053. void *cbdata;
  1054. /* next handler in a linked list */
  1055. struct mg_handler_info *next;
  1056. };
  1057. struct mg_context {
  1058. volatile int stop_flag; /* Should we stop event loop */
  1059. SSL_CTX *ssl_ctx; /* SSL context */
  1060. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1061. struct mg_callbacks callbacks; /* User-defined callback function */
  1062. void *user_data; /* User-defined data */
  1063. int context_type; /* 1 = server context, 2 = client context */
  1064. struct socket *listening_sockets;
  1065. in_port_t *listening_ports;
  1066. unsigned int num_listening_sockets;
  1067. volatile int
  1068. running_worker_threads; /* Number of currently running worker threads */
  1069. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  1070. pthread_cond_t thread_cond; /* Condvar for tracking workers terminations */
  1071. struct socket queue[MGSQLEN]; /* Accepted sockets */
  1072. volatile int sq_head; /* Head of the socket queue */
  1073. volatile int sq_tail; /* Tail of the socket queue */
  1074. pthread_cond_t sq_full; /* Signaled when socket is produced */
  1075. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  1076. pthread_t masterthreadid; /* The master thread ID */
  1077. unsigned int
  1078. cfg_worker_threads; /* The number of configured worker threads. */
  1079. pthread_t *workerthreadids; /* The worker thread IDs */
  1080. time_t start_time; /* Server start time, used for authentication */
  1081. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1082. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  1083. unsigned long nonce_count; /* Used nonces, used for authentication */
  1084. char *systemName; /* What operating system is running */
  1085. /* linked list of uri handlers */
  1086. struct mg_handler_info *handlers;
  1087. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1088. /* linked list of shared lua websockets */
  1089. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1090. #endif
  1091. #ifdef USE_TIMERS
  1092. struct ttimers *timers;
  1093. #endif
  1094. };
  1095. struct mg_connection {
  1096. struct mg_request_info request_info;
  1097. struct mg_context *ctx;
  1098. SSL *ssl; /* SSL descriptor */
  1099. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  1100. struct socket client; /* Connected client */
  1101. time_t conn_birth_time; /* Time (wall clock) when connection was
  1102. * established */
  1103. struct timespec req_time; /* Time (since system start) when the request
  1104. * was received */
  1105. int64_t num_bytes_sent; /* Total bytes sent to client */
  1106. int64_t content_len; /* Content-Length header value */
  1107. int64_t consumed_content; /* How many bytes of content have been read */
  1108. int is_chunked; /* Transfer-Encoding is chunked: 0=no, 1=yes:
  1109. * data available, 2: all data read */
  1110. size_t chunk_remainder; /* Unread data from the last chunk */
  1111. char *buf; /* Buffer for received data */
  1112. char *path_info; /* PATH_INFO part of the URL */
  1113. int must_close; /* 1 if connection must be closed */
  1114. int in_error_handler; /* 1 if in handler for user defined error
  1115. * pages */
  1116. int internal_error; /* 1 if an error occured while processing the
  1117. * request */
  1118. int buf_size; /* Buffer size */
  1119. int request_len; /* Size of the request + headers in a buffer */
  1120. int data_len; /* Total size of data in a buffer */
  1121. int status_code; /* HTTP reply status code, e.g. 200 */
  1122. int throttle; /* Throttling, bytes/sec. <= 0 means no
  1123. * throttle */
  1124. time_t last_throttle_time; /* Last time throttled data was sent */
  1125. int64_t last_throttle_bytes; /* Bytes sent this second */
  1126. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  1127. * atomic transmissions for websockets */
  1128. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1129. void *lua_websocket_state; /* Lua_State for a websocket connection */
  1130. #endif
  1131. };
  1132. static pthread_key_t sTlsKey; /* Thread local storage index */
  1133. static int sTlsInit = 0;
  1134. static int thread_idx_max = 0;
  1135. struct mg_workerTLS {
  1136. int is_master;
  1137. unsigned long thread_idx;
  1138. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1139. HANDLE pthread_cond_helper_mutex;
  1140. #endif
  1141. };
  1142. /* Directory entry */
  1143. struct de {
  1144. struct mg_connection *conn;
  1145. char *file_name;
  1146. struct file file;
  1147. };
  1148. #if defined(USE_WEBSOCKET)
  1149. static int is_websocket_protocol(const struct mg_connection *conn);
  1150. #else
  1151. #define is_websocket_protocol(conn) (0)
  1152. #endif
  1153. static int
  1154. mg_atomic_inc(volatile int *addr)
  1155. {
  1156. int ret;
  1157. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1158. /* Depending on the SDK, this function uses either
  1159. * (volatile unsigned int *) or (volatile LONG *),
  1160. * so whatever you use, the other SDK is likely to raise a warning. */
  1161. ret = InterlockedIncrement((volatile long *)addr);
  1162. #elif defined(__GNUC__) \
  1163. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  1164. ret = __sync_add_and_fetch(addr, 1);
  1165. #else
  1166. ret = (++(*addr));
  1167. #endif
  1168. return ret;
  1169. }
  1170. static int
  1171. mg_atomic_dec(volatile int *addr)
  1172. {
  1173. int ret;
  1174. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1175. /* Depending on the SDK, this function uses either
  1176. * (volatile unsigned int *) or (volatile LONG *),
  1177. * so whatever you use, the other SDK is likely to raise a warning. */
  1178. ret = InterlockedDecrement((volatile long *)addr);
  1179. #elif defined(__GNUC__) \
  1180. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  1181. ret = __sync_sub_and_fetch(addr, 1);
  1182. #else
  1183. ret = (--(*addr));
  1184. #endif
  1185. return ret;
  1186. }
  1187. #if !defined(NO_THREAD_NAME)
  1188. #if defined(_WIN32) && defined(_MSC_VER)
  1189. /* Set the thread name for debugging purposes in Visual Studio
  1190. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  1191. */
  1192. #pragma pack(push, 8)
  1193. typedef struct tagTHREADNAME_INFO {
  1194. DWORD dwType; /* Must be 0x1000. */
  1195. LPCSTR szName; /* Pointer to name (in user addr space). */
  1196. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  1197. DWORD dwFlags; /* Reserved for future use, must be zero. */
  1198. } THREADNAME_INFO;
  1199. #pragma pack(pop)
  1200. #elif defined(__linux__)
  1201. #include <sys/prctl.h>
  1202. #include <sys/sendfile.h>
  1203. #endif
  1204. static void
  1205. mg_set_thread_name(const char *name)
  1206. {
  1207. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  1208. mg_snprintf(
  1209. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  1210. #if defined(_WIN32)
  1211. #if defined(_MSC_VER)
  1212. /* Windows and Visual Studio Compiler */
  1213. __try
  1214. {
  1215. THREADNAME_INFO info;
  1216. info.dwType = 0x1000;
  1217. info.szName = threadName;
  1218. info.dwThreadID = ~0U;
  1219. info.dwFlags = 0;
  1220. RaiseException(0x406D1388,
  1221. 0,
  1222. sizeof(info) / sizeof(ULONG_PTR),
  1223. (ULONG_PTR *)&info);
  1224. }
  1225. __except(EXCEPTION_EXECUTE_HANDLER)
  1226. {
  1227. }
  1228. #elif defined(__MINGW32__)
  1229. /* No option known to set thread name for MinGW */
  1230. #endif
  1231. #elif defined(__GLIBC__) \
  1232. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  1233. /* pthread_setname_np first appeared in glibc in version 2.12*/
  1234. (void)pthread_setname_np(pthread_self(), threadName);
  1235. #elif defined(__linux__)
  1236. /* on linux we can use the old prctl function */
  1237. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  1238. #endif
  1239. }
  1240. #else /* !defined(NO_THREAD_NAME) */
  1241. void
  1242. mg_set_thread_name(const char *threadName)
  1243. {
  1244. }
  1245. #endif
  1246. #if defined(MG_LEGACY_INTERFACE)
  1247. const char **
  1248. mg_get_valid_option_names(void)
  1249. {
  1250. /* This function is deprecated. Use mg_get_valid_options instead. */
  1251. static const char *
  1252. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  1253. int i;
  1254. for (i = 0; config_options[i].name != NULL; i++) {
  1255. data[i * 2] = config_options[i].name;
  1256. data[i * 2 + 1] = config_options[i].default_value;
  1257. }
  1258. return data;
  1259. }
  1260. #endif
  1261. const struct mg_option *
  1262. mg_get_valid_options(void)
  1263. {
  1264. return config_options;
  1265. }
  1266. static int
  1267. is_file_in_memory(const struct mg_connection *conn,
  1268. const char *path,
  1269. struct file *filep)
  1270. {
  1271. size_t size = 0;
  1272. if (!conn || !filep) {
  1273. return 0;
  1274. }
  1275. if (conn->ctx->callbacks.open_file) {
  1276. filep->membuf = conn->ctx->callbacks.open_file(conn, path, &size);
  1277. if (filep->membuf != NULL) {
  1278. /* NOTE: override filep->size only on success. Otherwise, it might
  1279. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  1280. filep->size = size;
  1281. }
  1282. }
  1283. return filep->membuf != NULL;
  1284. }
  1285. static int
  1286. is_file_opened(const struct file *filep)
  1287. {
  1288. if (!filep) {
  1289. return 0;
  1290. }
  1291. return filep->membuf != NULL || filep->fp != NULL;
  1292. }
  1293. static int
  1294. mg_fopen(const struct mg_connection *conn,
  1295. const char *path,
  1296. const char *mode,
  1297. struct file *filep)
  1298. {
  1299. struct stat st;
  1300. if (!filep) {
  1301. return 0;
  1302. }
  1303. /* TODO (high): mg_fopen should only open a file, while mg_stat should
  1304. * only get the file status. They should not work on different members of
  1305. * the same structure (bad cohesion). */
  1306. memset(filep, 0, sizeof(*filep));
  1307. if (stat(path, &st) == 0) {
  1308. filep->size = (uint64_t)(st.st_size);
  1309. }
  1310. if (!is_file_in_memory(conn, path, filep)) {
  1311. #ifdef _WIN32
  1312. wchar_t wbuf[PATH_MAX], wmode[20];
  1313. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  1314. MultiByteToWideChar(CP_UTF8, 0, mode, -1, wmode, ARRAY_SIZE(wmode));
  1315. filep->fp = _wfopen(wbuf, wmode);
  1316. #else
  1317. /* Linux et al already use unicode. No need to convert. */
  1318. filep->fp = fopen(path, mode);
  1319. #endif
  1320. }
  1321. return is_file_opened(filep);
  1322. }
  1323. static void
  1324. mg_fclose(struct file *filep)
  1325. {
  1326. if (filep != NULL && filep->fp != NULL) {
  1327. fclose(filep->fp);
  1328. }
  1329. }
  1330. static void
  1331. mg_strlcpy(register char *dst, register const char *src, size_t n)
  1332. {
  1333. for (; *src != '\0' && n > 1; n--) {
  1334. *dst++ = *src++;
  1335. }
  1336. *dst = '\0';
  1337. }
  1338. static int
  1339. lowercase(const char *s)
  1340. {
  1341. return tolower(*(const unsigned char *)s);
  1342. }
  1343. int
  1344. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  1345. {
  1346. int diff = 0;
  1347. if (len > 0) {
  1348. do {
  1349. diff = lowercase(s1++) - lowercase(s2++);
  1350. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  1351. }
  1352. return diff;
  1353. }
  1354. static int
  1355. mg_strcasecmp(const char *s1, const char *s2)
  1356. {
  1357. int diff;
  1358. do {
  1359. diff = lowercase(s1++) - lowercase(s2++);
  1360. } while (diff == 0 && s1[-1] != '\0');
  1361. return diff;
  1362. }
  1363. static char *
  1364. mg_strndup(const char *ptr, size_t len)
  1365. {
  1366. char *p;
  1367. if ((p = (char *)mg_malloc(len + 1)) != NULL) {
  1368. mg_strlcpy(p, ptr, len + 1);
  1369. }
  1370. return p;
  1371. }
  1372. static char *
  1373. mg_strdup(const char *str)
  1374. {
  1375. return mg_strndup(str, strlen(str));
  1376. }
  1377. static const char *
  1378. mg_strcasestr(const char *big_str, const char *small_str)
  1379. {
  1380. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  1381. if (big_len >= small_len) {
  1382. for (i = 0; i <= (big_len - small_len); i++) {
  1383. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  1384. return big_str + i;
  1385. }
  1386. }
  1387. }
  1388. return NULL;
  1389. }
  1390. /* Return null terminated string of given maximum length.
  1391. * Report errors if length is exceeded. */
  1392. static void
  1393. mg_vsnprintf(const struct mg_connection *conn,
  1394. int *truncated,
  1395. char *buf,
  1396. size_t buflen,
  1397. const char *fmt,
  1398. va_list ap)
  1399. {
  1400. int n, ok;
  1401. if (buflen == 0) {
  1402. return;
  1403. }
  1404. #ifdef __clang__
  1405. #pragma clang diagnostic push
  1406. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  1407. /* Using fmt as a non-literal is intended here, since it is mostly called
  1408. * indirectly by mg_snprintf */
  1409. #endif
  1410. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  1411. ok = (n >= 0) && ((size_t)n < buflen);
  1412. #ifdef __clang__
  1413. #pragma clang diagnostic pop
  1414. #endif
  1415. if (ok) {
  1416. if (truncated) {
  1417. *truncated = 0;
  1418. }
  1419. } else {
  1420. if (truncated) {
  1421. *truncated = 1;
  1422. }
  1423. mg_cry(conn,
  1424. "truncating vsnprintf buffer: [%.*s]",
  1425. (int)((buflen > 200) ? 200 : (buflen - 1)),
  1426. buf);
  1427. n = (int)buflen - 1;
  1428. }
  1429. buf[n] = '\0';
  1430. }
  1431. static void
  1432. mg_snprintf(const struct mg_connection *conn,
  1433. int *truncated,
  1434. char *buf,
  1435. size_t buflen,
  1436. const char *fmt,
  1437. ...)
  1438. {
  1439. va_list ap;
  1440. va_start(ap, fmt);
  1441. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  1442. va_end(ap);
  1443. }
  1444. static int
  1445. get_option_index(const char *name)
  1446. {
  1447. int i;
  1448. for (i = 0; config_options[i].name != NULL; i++) {
  1449. if (strcmp(config_options[i].name, name) == 0) {
  1450. return i;
  1451. }
  1452. }
  1453. return -1;
  1454. }
  1455. const char *
  1456. mg_get_option(const struct mg_context *ctx, const char *name)
  1457. {
  1458. int i;
  1459. if ((i = get_option_index(name)) == -1) {
  1460. return NULL;
  1461. } else if (!ctx || ctx->config[i] == NULL) {
  1462. return "";
  1463. } else {
  1464. return ctx->config[i];
  1465. }
  1466. }
  1467. struct mg_context *
  1468. mg_get_context(const struct mg_connection *conn)
  1469. {
  1470. return (conn == NULL) ? (struct mg_context *)NULL : (conn->ctx);
  1471. }
  1472. void *
  1473. mg_get_user_data(const struct mg_context *ctx)
  1474. {
  1475. return (ctx == NULL) ? NULL : ctx->user_data;
  1476. }
  1477. void
  1478. mg_set_user_connection_data(const struct mg_connection *conn, void *data)
  1479. {
  1480. if (conn != NULL) {
  1481. ((struct mg_connection *)conn)->request_info.conn_data = data;
  1482. }
  1483. }
  1484. void *
  1485. mg_get_user_connection_data(const struct mg_connection *conn)
  1486. {
  1487. if (conn != NULL) {
  1488. return conn->request_info.conn_data;
  1489. }
  1490. return NULL;
  1491. }
  1492. size_t
  1493. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  1494. {
  1495. size_t i;
  1496. if (!ctx) {
  1497. return 0;
  1498. }
  1499. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  1500. ssl[i] = ctx->listening_sockets[i].is_ssl;
  1501. ports[i] = ctx->listening_ports[i];
  1502. }
  1503. return i;
  1504. }
  1505. int
  1506. mg_get_server_ports(const struct mg_context *ctx,
  1507. int size,
  1508. struct mg_server_ports *ports)
  1509. {
  1510. int i, cnt = 0;
  1511. if (size <= 0) {
  1512. return -1;
  1513. }
  1514. memset(ports, 0, sizeof(*ports) * (size_t)size);
  1515. if (!ctx) {
  1516. return -1;
  1517. }
  1518. if (!ctx->listening_sockets || !ctx->listening_ports) {
  1519. return -1;
  1520. }
  1521. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  1522. ports[cnt].port = ctx->listening_ports[i];
  1523. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  1524. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  1525. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  1526. /* IPv4 */
  1527. ports[cnt].protocol = 1;
  1528. cnt++;
  1529. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  1530. /* IPv6 */
  1531. ports[cnt].protocol = 3;
  1532. cnt++;
  1533. }
  1534. }
  1535. return cnt;
  1536. }
  1537. static void
  1538. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  1539. {
  1540. buf[0] = '\0';
  1541. if (!usa) {
  1542. return;
  1543. }
  1544. if (usa->sa.sa_family == AF_INET) {
  1545. getnameinfo(&usa->sa,
  1546. sizeof(usa->sin),
  1547. buf,
  1548. (unsigned)len,
  1549. NULL,
  1550. 0,
  1551. NI_NUMERICHOST);
  1552. }
  1553. #if defined(USE_IPV6)
  1554. else if (usa->sa.sa_family == AF_INET6) {
  1555. getnameinfo(&usa->sa,
  1556. sizeof(usa->sin6),
  1557. buf,
  1558. (unsigned)len,
  1559. NULL,
  1560. 0,
  1561. NI_NUMERICHOST);
  1562. }
  1563. #endif
  1564. }
  1565. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  1566. * included in all responses other than 100, 101, 5xx. */
  1567. static void
  1568. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  1569. {
  1570. struct tm *tm;
  1571. tm = gmtime(t);
  1572. if (tm != NULL) {
  1573. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  1574. } else {
  1575. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  1576. buf[buf_len - 1] = '\0';
  1577. }
  1578. }
  1579. /* difftime for struct timespec. Return value is in seconds. */
  1580. static double
  1581. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  1582. {
  1583. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  1584. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  1585. }
  1586. /* Print error message to the opened error log stream. */
  1587. void
  1588. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  1589. {
  1590. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  1591. va_list ap;
  1592. struct file fi;
  1593. time_t timestamp;
  1594. va_start(ap, fmt);
  1595. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  1596. va_end(ap);
  1597. buf[sizeof(buf) - 1] = 0;
  1598. if (!conn) {
  1599. puts(buf);
  1600. return;
  1601. }
  1602. /* Do not lock when getting the callback value, here and below.
  1603. * I suppose this is fine, since function cannot disappear in the
  1604. * same way string option can. */
  1605. if ((conn->ctx->callbacks.log_message == NULL)
  1606. || (conn->ctx->callbacks.log_message(conn, buf) == 0)) {
  1607. if (conn->ctx->config[ERROR_LOG_FILE] != NULL) {
  1608. if (mg_fopen(conn, conn->ctx->config[ERROR_LOG_FILE], "a+", &fi)
  1609. == 0) {
  1610. fi.fp = NULL;
  1611. }
  1612. } else {
  1613. fi.fp = NULL;
  1614. }
  1615. if (fi.fp != NULL) {
  1616. flockfile(fi.fp);
  1617. timestamp = time(NULL);
  1618. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  1619. fprintf(fi.fp,
  1620. "[%010lu] [error] [client %s] ",
  1621. (unsigned long)timestamp,
  1622. src_addr);
  1623. if (conn->request_info.request_method != NULL) {
  1624. fprintf(fi.fp,
  1625. "%s %s: ",
  1626. conn->request_info.request_method,
  1627. conn->request_info.request_uri);
  1628. }
  1629. fprintf(fi.fp, "%s", buf);
  1630. fputc('\n', fi.fp);
  1631. fflush(fi.fp);
  1632. funlockfile(fi.fp);
  1633. mg_fclose(&fi);
  1634. }
  1635. }
  1636. }
  1637. /* Return fake connection structure. Used for logging, if connection
  1638. * is not applicable at the moment of logging. */
  1639. static struct mg_connection *
  1640. fc(struct mg_context *ctx)
  1641. {
  1642. static struct mg_connection fake_connection;
  1643. fake_connection.ctx = ctx;
  1644. return &fake_connection;
  1645. }
  1646. const char *
  1647. mg_version(void)
  1648. {
  1649. return CIVETWEB_VERSION;
  1650. }
  1651. const struct mg_request_info *
  1652. mg_get_request_info(const struct mg_connection *conn)
  1653. {
  1654. if (!conn) {
  1655. return NULL;
  1656. }
  1657. return &conn->request_info;
  1658. }
  1659. /* Skip the characters until one of the delimiters characters found.
  1660. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  1661. * Advance pointer to buffer to the next word. Return found 0-terminated word.
  1662. * Delimiters can be quoted with quotechar. */
  1663. static char *
  1664. skip_quoted(char **buf,
  1665. const char *delimiters,
  1666. const char *whitespace,
  1667. char quotechar)
  1668. {
  1669. char *p, *begin_word, *end_word, *end_whitespace;
  1670. begin_word = *buf;
  1671. end_word = begin_word + strcspn(begin_word, delimiters);
  1672. /* Check for quotechar */
  1673. if (end_word > begin_word) {
  1674. p = end_word - 1;
  1675. while (*p == quotechar) {
  1676. /* While the delimiter is quoted, look for the next delimiter. */
  1677. /* This happens, e.g., in calls from parse_auth_header,
  1678. * if the user name contains a " character. */
  1679. /* If there is anything beyond end_word, copy it. */
  1680. if (*end_word != '\0') {
  1681. size_t end_off = strcspn(end_word + 1, delimiters);
  1682. memmove(p, end_word, end_off + 1);
  1683. p += end_off; /* p must correspond to end_word - 1 */
  1684. end_word += end_off + 1;
  1685. } else {
  1686. *p = '\0';
  1687. break;
  1688. }
  1689. }
  1690. for (p++; p < end_word; p++) {
  1691. *p = '\0';
  1692. }
  1693. }
  1694. if (*end_word == '\0') {
  1695. *buf = end_word;
  1696. } else {
  1697. end_whitespace = end_word + 1 + strspn(end_word + 1, whitespace);
  1698. for (p = end_word; p < end_whitespace; p++) {
  1699. *p = '\0';
  1700. }
  1701. *buf = end_whitespace;
  1702. }
  1703. return begin_word;
  1704. }
  1705. /* Simplified version of skip_quoted without quote char
  1706. * and whitespace == delimiters */
  1707. static char *
  1708. skip(char **buf, const char *delimiters)
  1709. {
  1710. return skip_quoted(buf, delimiters, delimiters, 0);
  1711. }
  1712. /* Return HTTP header value, or NULL if not found. */
  1713. static const char *
  1714. get_header(const struct mg_request_info *ri, const char *name)
  1715. {
  1716. int i;
  1717. if (ri) {
  1718. for (i = 0; i < ri->num_headers; i++) {
  1719. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  1720. return ri->http_headers[i].value;
  1721. }
  1722. }
  1723. }
  1724. return NULL;
  1725. }
  1726. const char *
  1727. mg_get_header(const struct mg_connection *conn, const char *name)
  1728. {
  1729. if (!conn) {
  1730. return NULL;
  1731. }
  1732. return get_header(&conn->request_info, name);
  1733. }
  1734. /* A helper function for traversing a comma separated list of values.
  1735. * It returns a list pointer shifted to the next value, or NULL if the end
  1736. * of the list found.
  1737. * Value is stored in val vector. If value has form "x=y", then eq_val
  1738. * vector is initialized to point to the "y" part, and val vector length
  1739. * is adjusted to point only to "x". */
  1740. static const char *
  1741. next_option(const char *list, struct vec *val, struct vec *eq_val)
  1742. {
  1743. if (val == NULL || list == NULL || *list == '\0') {
  1744. /* End of the list */
  1745. list = NULL;
  1746. } else {
  1747. val->ptr = list;
  1748. if ((list = strchr(val->ptr, ',')) != NULL) {
  1749. /* Comma found. Store length and shift the list ptr */
  1750. val->len = ((size_t)(list - val->ptr));
  1751. list++;
  1752. } else {
  1753. /* This value is the last one */
  1754. list = val->ptr + strlen(val->ptr);
  1755. val->len = ((size_t)(list - val->ptr));
  1756. }
  1757. if (eq_val != NULL) {
  1758. /* Value has form "x=y", adjust pointers and lengths
  1759. * so that val points to "x", and eq_val points to "y". */
  1760. eq_val->len = 0;
  1761. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  1762. if (eq_val->ptr != NULL) {
  1763. eq_val->ptr++; /* Skip over '=' character */
  1764. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  1765. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  1766. }
  1767. }
  1768. }
  1769. return list;
  1770. }
  1771. /* Perform case-insensitive match of string against pattern */
  1772. static int
  1773. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  1774. {
  1775. const char *or_str;
  1776. size_t i;
  1777. int j, len, res;
  1778. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  1779. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  1780. return res > 0 ? res : match_prefix(or_str + 1,
  1781. (size_t)((pattern + pattern_len)
  1782. - (or_str + 1)),
  1783. str);
  1784. }
  1785. for (i = 0, j = 0; i < pattern_len; i++, j++) {
  1786. if (pattern[i] == '?' && str[j] != '\0') {
  1787. continue;
  1788. } else if (pattern[i] == '$') {
  1789. return str[j] == '\0' ? j : -1;
  1790. } else if (pattern[i] == '*') {
  1791. i++;
  1792. if (pattern[i] == '*') {
  1793. i++;
  1794. len = (int)strlen(str + j);
  1795. } else {
  1796. len = (int)strcspn(str + j, "/");
  1797. }
  1798. if (i == pattern_len) {
  1799. return j + len;
  1800. }
  1801. do {
  1802. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  1803. } while (res == -1 && len-- > 0);
  1804. return res == -1 ? -1 : j + res + len;
  1805. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  1806. return -1;
  1807. }
  1808. }
  1809. return j;
  1810. }
  1811. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  1812. * This function must tolerate situations when connection info is not
  1813. * set up, for example if request parsing failed. */
  1814. static int
  1815. should_keep_alive(const struct mg_connection *conn)
  1816. {
  1817. if (conn != NULL) {
  1818. const char *http_version = conn->request_info.http_version;
  1819. const char *header = mg_get_header(conn, "Connection");
  1820. if (conn->must_close || conn->internal_error || conn->status_code == 401
  1821. || mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0
  1822. || (header != NULL && mg_strcasecmp(header, "keep-alive") != 0)
  1823. || (header == NULL && http_version
  1824. && 0 != strcmp(http_version, "1.1"))) {
  1825. return 0;
  1826. }
  1827. return 1;
  1828. }
  1829. return 0;
  1830. }
  1831. static int
  1832. should_decode_url(const struct mg_connection *conn)
  1833. {
  1834. if (!conn || !conn->ctx) {
  1835. return 0;
  1836. }
  1837. return (mg_strcasecmp(conn->ctx->config[DECODE_URL], "yes") == 0);
  1838. }
  1839. static const char *
  1840. suggest_connection_header(const struct mg_connection *conn)
  1841. {
  1842. return should_keep_alive(conn) ? "keep-alive" : "close";
  1843. }
  1844. static int
  1845. send_no_cache_header(struct mg_connection *conn)
  1846. {
  1847. /* Send all current and obsolete cache opt-out directives. */
  1848. return mg_printf(conn,
  1849. "Cache-Control: no-cache, no-store, "
  1850. "must-revalidate, private, max-age=0\r\n"
  1851. "Pragma: no-cache\r\n"
  1852. "Expires: 0\r\n");
  1853. }
  1854. static int
  1855. send_static_cache_header(struct mg_connection *conn)
  1856. {
  1857. /* Read the server config to check how long a file may be cached.
  1858. * The configuration is in seconds. */
  1859. int max_age = atoi(conn->ctx->config[STATIC_FILE_MAX_AGE]);
  1860. if (max_age <= 0) {
  1861. /* 0 means "do not cache". All values <0 are reserved
  1862. * and may be used differently in the future. */
  1863. /* If a file should not be cached, do not only send
  1864. * max-age=0, but also pragmas and Expires headers. */
  1865. return send_no_cache_header(conn);
  1866. }
  1867. /* Use "Cache-Control: max-age" instead of "Expires" header.
  1868. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  1869. /* See also https://www.mnot.net/cache_docs/ */
  1870. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  1871. }
  1872. static void handle_file_based_request(struct mg_connection *conn,
  1873. const char *path,
  1874. struct file *filep);
  1875. static int
  1876. mg_stat(struct mg_connection *conn, const char *path, struct file *filep);
  1877. static const char *
  1878. mg_get_response_code_text(int response_code, struct mg_connection *conn)
  1879. {
  1880. /* See IANA HTTP status code assignment:
  1881. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  1882. */
  1883. switch (response_code) {
  1884. /* RFC2616 Section 10.1 - Informational 1xx */
  1885. case 100:
  1886. return "Continue"; /* RFC2616 Section 10.1.1 */
  1887. case 101:
  1888. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  1889. case 102:
  1890. return "Processing"; /* RFC2518 Section 10.1 */
  1891. /* RFC2616 Section 10.2 - Successful 2xx */
  1892. case 200:
  1893. return "OK"; /* RFC2616 Section 10.2.1 */
  1894. case 201:
  1895. return "Created"; /* RFC2616 Section 10.2.2 */
  1896. case 202:
  1897. return "Accepted"; /* RFC2616 Section 10.2.3 */
  1898. case 203:
  1899. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  1900. case 204:
  1901. return "No Content"; /* RFC2616 Section 10.2.5 */
  1902. case 205:
  1903. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  1904. case 206:
  1905. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  1906. case 207:
  1907. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1 */
  1908. case 208:
  1909. return "Already Reported"; /* RFC5842 Section 7.1 */
  1910. case 226:
  1911. return "IM used"; /* RFC3229 Section 10.4.1 */
  1912. /* RFC2616 Section 10.3 - Redirection 3xx */
  1913. case 300:
  1914. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  1915. case 301:
  1916. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  1917. case 302:
  1918. return "Found"; /* RFC2616 Section 10.3.3 */
  1919. case 303:
  1920. return "See Other"; /* RFC2616 Section 10.3.4 */
  1921. case 304:
  1922. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  1923. case 305:
  1924. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  1925. case 307:
  1926. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  1927. case 308:
  1928. return "Permanent Redirect"; /* RFC7238 Section 3 */
  1929. /* RFC2616 Section 10.4 - Client Error 4xx */
  1930. case 400:
  1931. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  1932. case 401:
  1933. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  1934. case 402:
  1935. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  1936. case 403:
  1937. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  1938. case 404:
  1939. return "Not Found"; /* RFC2616 Section 10.4.5 */
  1940. case 405:
  1941. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  1942. case 406:
  1943. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  1944. case 407:
  1945. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  1946. case 408:
  1947. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  1948. case 409:
  1949. return "Conflict"; /* RFC2616 Section 10.4.10 */
  1950. case 410:
  1951. return "Gone"; /* RFC2616 Section 10.4.11 */
  1952. case 411:
  1953. return "Length Required"; /* RFC2616 Section 10.4.12 */
  1954. case 412:
  1955. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  1956. case 413:
  1957. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  1958. case 414:
  1959. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  1960. case 415:
  1961. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  1962. case 416:
  1963. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17 */
  1964. case 417:
  1965. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  1966. case 421:
  1967. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  1968. case 422:
  1969. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  1970. * Section 11.2 */
  1971. case 423:
  1972. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  1973. case 424:
  1974. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  1975. * Section 11.4 */
  1976. case 426:
  1977. return "Upgrade Required"; /* RFC 2817 Section 4 */
  1978. case 428:
  1979. return "Precondition Required"; /* RFC 6585, Section 3 */
  1980. case 429:
  1981. return "Too Many Requests"; /* RFC 6585, Section 4 */
  1982. case 431:
  1983. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  1984. case 451:
  1985. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  1986. * Section 3 */
  1987. /* RFC2616 Section 10.5 - Server Error 5xx */
  1988. case 500:
  1989. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  1990. case 501:
  1991. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  1992. case 502:
  1993. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  1994. case 503:
  1995. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  1996. case 504:
  1997. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  1998. case 505:
  1999. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  2000. case 506:
  2001. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  2002. case 507:
  2003. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  2004. * Section 11.5 */
  2005. case 508:
  2006. return "Loop Detected"; /* RFC5842 Section 7.1 */
  2007. case 510:
  2008. return "Not Extended"; /* RFC 2774, Section 7 */
  2009. case 511:
  2010. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  2011. /* Other status codes, not shown in the IANA HTTP status code assignment.
  2012. * E.g., "de facto" standards due to common use, ... */
  2013. case 418:
  2014. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  2015. case 419:
  2016. return "Authentication Timeout"; /* common use */
  2017. default:
  2018. /* This error code is unknown. This should not happen. */
  2019. if (conn) {
  2020. mg_cry(conn, "Unknown HTTP response code: %u", response_code);
  2021. }
  2022. /* Return at least a category according to RFC 2616 Section 10. */
  2023. if (response_code >= 100 && response_code < 200) {
  2024. /* Unknown informational status code */
  2025. return "Information";
  2026. }
  2027. if (response_code >= 200 && response_code < 300) {
  2028. /* Unknown success code */
  2029. return "Success";
  2030. }
  2031. if (response_code >= 300 && response_code < 400) {
  2032. /* Unknown redirection code */
  2033. return "Redirection";
  2034. }
  2035. if (response_code >= 400 && response_code < 500) {
  2036. /* Unknown request error code */
  2037. return "Client Error";
  2038. }
  2039. if (response_code >= 500 && response_code < 600) {
  2040. /* Unknown server error code */
  2041. return "Server Error";
  2042. }
  2043. /* Response code not even within reasonable range */
  2044. return "";
  2045. }
  2046. }
  2047. static void send_http_error(struct mg_connection *,
  2048. int,
  2049. PRINTF_FORMAT_STRING(const char *fmt),
  2050. ...) PRINTF_ARGS(3, 4);
  2051. static void
  2052. send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  2053. {
  2054. char buf[MG_BUF_LEN];
  2055. va_list ap;
  2056. int len, i, page_handler_found, scope, truncated;
  2057. char date[64];
  2058. time_t curtime = time(NULL);
  2059. const char *error_handler = NULL;
  2060. struct file error_page_file = STRUCT_FILE_INITIALIZER;
  2061. const char *error_page_file_ext, *tstr;
  2062. const char *status_text = mg_get_response_code_text(status, conn);
  2063. if (conn == NULL) {
  2064. return;
  2065. }
  2066. conn->status_code = status;
  2067. if (conn->in_error_handler || conn->ctx->callbacks.http_error == NULL
  2068. || conn->ctx->callbacks.http_error(conn, status)) {
  2069. if (!conn->in_error_handler) {
  2070. /* Send user defined error pages, if defined */
  2071. error_handler = conn->ctx->config[ERROR_PAGES];
  2072. error_page_file_ext = conn->ctx->config[INDEX_FILES];
  2073. page_handler_found = 0;
  2074. if (error_handler != NULL) {
  2075. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  2076. switch (scope) {
  2077. case 1: /* Handler for specific error, e.g. 404 error */
  2078. mg_snprintf(conn,
  2079. &truncated,
  2080. buf,
  2081. sizeof(buf) - 32,
  2082. "%serror%03u.",
  2083. error_handler,
  2084. status);
  2085. break;
  2086. case 2: /* Handler for error group, e.g., 5xx error handler
  2087. * for all server errors (500-599) */
  2088. mg_snprintf(conn,
  2089. &truncated,
  2090. buf,
  2091. sizeof(buf) - 32,
  2092. "%serror%01uxx.",
  2093. error_handler,
  2094. status / 100);
  2095. break;
  2096. default: /* Handler for all errors */
  2097. mg_snprintf(conn,
  2098. &truncated,
  2099. buf,
  2100. sizeof(buf) - 32,
  2101. "%serror.",
  2102. error_handler);
  2103. break;
  2104. }
  2105. /* String truncation in buf may only occur if error_handler
  2106. * is too long. This string is from the config, not from a
  2107. * client. */
  2108. (void)truncated;
  2109. len = (int)strlen(buf);
  2110. tstr = strchr(error_page_file_ext, '.');
  2111. while (tstr) {
  2112. for (i = 1; i < 32 && tstr[i] != 0 && tstr[i] != ',';
  2113. i++)
  2114. buf[len + i - 1] = tstr[i];
  2115. buf[len + i - 1] = 0;
  2116. if (mg_stat(conn, buf, &error_page_file)) {
  2117. page_handler_found = 1;
  2118. break;
  2119. }
  2120. tstr = strchr(tstr + i, '.');
  2121. }
  2122. }
  2123. }
  2124. if (page_handler_found) {
  2125. conn->in_error_handler = 1;
  2126. handle_file_based_request(conn, buf, &error_page_file);
  2127. conn->in_error_handler = 0;
  2128. return;
  2129. }
  2130. }
  2131. /* No custom error page. Send default error page. */
  2132. gmt_time_string(date, sizeof(date), &curtime);
  2133. conn->must_close = 1;
  2134. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  2135. send_no_cache_header(conn);
  2136. mg_printf(conn,
  2137. "Date: %s\r\n"
  2138. "Connection: close\r\n\r\n",
  2139. date);
  2140. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  2141. if (status > 199 && status != 204 && status != 304) {
  2142. mg_printf(conn, "Error %d: %s\n", status, status_text);
  2143. if (fmt != NULL) {
  2144. va_start(ap, fmt);
  2145. mg_vsnprintf(conn, NULL, buf, sizeof(buf), fmt, ap);
  2146. va_end(ap);
  2147. mg_write(conn, buf, strlen(buf));
  2148. DEBUG_TRACE("Error %i - [%s]", status, buf);
  2149. }
  2150. } else {
  2151. /* No body allowed. Close the connection. */
  2152. DEBUG_TRACE("Error %i", status);
  2153. }
  2154. }
  2155. }
  2156. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  2157. /* Create substitutes for POSIX functions in Win32. */
  2158. #if defined(__MINGW32__)
  2159. /* Show no warning in case system functions are not used. */
  2160. #pragma GCC diagnostic push
  2161. #pragma GCC diagnostic ignored "-Wunused-function"
  2162. #endif
  2163. static int
  2164. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  2165. {
  2166. (void)unused;
  2167. *mutex = CreateMutex(NULL, FALSE, NULL);
  2168. return *mutex == NULL ? -1 : 0;
  2169. }
  2170. static int
  2171. pthread_mutex_destroy(pthread_mutex_t *mutex)
  2172. {
  2173. return CloseHandle(*mutex) == 0 ? -1 : 0;
  2174. }
  2175. static int
  2176. pthread_mutex_lock(pthread_mutex_t *mutex)
  2177. {
  2178. return WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0 ? 0 : -1;
  2179. }
  2180. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  2181. static int
  2182. pthread_mutex_trylock(pthread_mutex_t *mutex)
  2183. {
  2184. switch (WaitForSingleObject(*mutex, 0)) {
  2185. case WAIT_OBJECT_0:
  2186. return 0;
  2187. case WAIT_TIMEOUT:
  2188. return -2; /* EBUSY */
  2189. }
  2190. return -1;
  2191. }
  2192. #endif
  2193. static int
  2194. pthread_mutex_unlock(pthread_mutex_t *mutex)
  2195. {
  2196. return ReleaseMutex(*mutex) == 0 ? -1 : 0;
  2197. }
  2198. #ifndef WIN_PTHREADS_TIME_H
  2199. static int
  2200. clock_gettime(clockid_t clk_id, struct timespec *tp)
  2201. {
  2202. FILETIME ft;
  2203. ULARGE_INTEGER li;
  2204. BOOL ok = FALSE;
  2205. double d;
  2206. static double perfcnt_per_sec = 0.0;
  2207. if (tp) {
  2208. memset(tp, 0, sizeof(*tp));
  2209. if (clk_id == CLOCK_REALTIME) {
  2210. GetSystemTimeAsFileTime(&ft);
  2211. li.LowPart = ft.dwLowDateTime;
  2212. li.HighPart = ft.dwHighDateTime;
  2213. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  2214. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  2215. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  2216. ok = TRUE;
  2217. } else if (clk_id == CLOCK_MONOTONIC) {
  2218. if (perfcnt_per_sec == 0.0) {
  2219. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  2220. perfcnt_per_sec = 1.0 / li.QuadPart;
  2221. }
  2222. if (perfcnt_per_sec != 0.0) {
  2223. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  2224. d = li.QuadPart * perfcnt_per_sec;
  2225. tp->tv_sec = (time_t)d;
  2226. d -= tp->tv_sec;
  2227. tp->tv_nsec = (long)(d * 1.0E9);
  2228. ok = TRUE;
  2229. }
  2230. }
  2231. }
  2232. return ok ? 0 : -1;
  2233. }
  2234. #endif
  2235. static int
  2236. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  2237. {
  2238. (void)unused;
  2239. InitializeCriticalSection(&cv->threadIdSec);
  2240. cv->waitingthreadcount = 0;
  2241. cv->waitingthreadhdls =
  2242. (pthread_t *)mg_calloc(MAX_WORKER_THREADS, sizeof(pthread_t));
  2243. return (cv->waitingthreadhdls != NULL) ? 0 : -1;
  2244. }
  2245. static int
  2246. pthread_cond_timedwait(pthread_cond_t *cv,
  2247. pthread_mutex_t *mutex,
  2248. const struct timespec *abstime)
  2249. {
  2250. struct mg_workerTLS *tls =
  2251. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2252. int ok;
  2253. struct timespec tsnow;
  2254. int64_t nsnow, nswaitabs, nswaitrel;
  2255. DWORD mswaitrel;
  2256. EnterCriticalSection(&cv->threadIdSec);
  2257. assert(cv->waitingthreadcount < MAX_WORKER_THREADS);
  2258. cv->waitingthreadhdls[cv->waitingthreadcount] =
  2259. tls->pthread_cond_helper_mutex;
  2260. cv->waitingthreadcount++;
  2261. LeaveCriticalSection(&cv->threadIdSec);
  2262. if (abstime) {
  2263. clock_gettime(CLOCK_REALTIME, &tsnow);
  2264. nsnow = (((int64_t)tsnow.tv_sec) * 1000000000) + tsnow.tv_nsec;
  2265. nswaitabs =
  2266. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  2267. nswaitrel = nswaitabs - nsnow;
  2268. if (nswaitrel < 0) {
  2269. nswaitrel = 0;
  2270. }
  2271. mswaitrel = (DWORD)(nswaitrel / 1000000);
  2272. } else {
  2273. mswaitrel = INFINITE;
  2274. }
  2275. pthread_mutex_unlock(mutex);
  2276. ok = (WAIT_OBJECT_0
  2277. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  2278. pthread_mutex_lock(mutex);
  2279. return ok ? 0 : -1;
  2280. }
  2281. static int
  2282. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  2283. {
  2284. return pthread_cond_timedwait(cv, mutex, NULL);
  2285. }
  2286. static int
  2287. pthread_cond_signal(pthread_cond_t *cv)
  2288. {
  2289. int i;
  2290. HANDLE wkup = NULL;
  2291. BOOL ok = FALSE;
  2292. EnterCriticalSection(&cv->threadIdSec);
  2293. if (cv->waitingthreadcount) {
  2294. wkup = cv->waitingthreadhdls[0];
  2295. ok = SetEvent(wkup);
  2296. for (i = 1; i < cv->waitingthreadcount; i++) {
  2297. cv->waitingthreadhdls[i - 1] = cv->waitingthreadhdls[i];
  2298. }
  2299. cv->waitingthreadcount--;
  2300. assert(ok);
  2301. }
  2302. LeaveCriticalSection(&cv->threadIdSec);
  2303. return ok ? 0 : 1;
  2304. }
  2305. static int
  2306. pthread_cond_broadcast(pthread_cond_t *cv)
  2307. {
  2308. EnterCriticalSection(&cv->threadIdSec);
  2309. while (cv->waitingthreadcount) {
  2310. pthread_cond_signal(cv);
  2311. }
  2312. LeaveCriticalSection(&cv->threadIdSec);
  2313. return 0;
  2314. }
  2315. static int
  2316. pthread_cond_destroy(pthread_cond_t *cv)
  2317. {
  2318. EnterCriticalSection(&cv->threadIdSec);
  2319. assert(cv->waitingthreadcount == 0);
  2320. mg_free(cv->waitingthreadhdls);
  2321. cv->waitingthreadhdls = 0;
  2322. LeaveCriticalSection(&cv->threadIdSec);
  2323. DeleteCriticalSection(&cv->threadIdSec);
  2324. return 0;
  2325. }
  2326. #if defined(__MINGW32__)
  2327. /* Enable unused function warning again */
  2328. #pragma GCC diagnostic pop
  2329. #endif
  2330. /* For Windows, change all slashes to backslashes in path names. */
  2331. static void
  2332. change_slashes_to_backslashes(char *path)
  2333. {
  2334. int i;
  2335. for (i = 0; path[i] != '\0'; i++) {
  2336. if (path[i] == '/') {
  2337. path[i] = '\\';
  2338. }
  2339. /* remove double backslash (check i > 0 to preserve UNC paths,
  2340. * like \\server\file.txt) */
  2341. if ((path[i] == '\\') && (i > 0)) {
  2342. while (path[i + 1] == '\\' || path[i + 1] == '/') {
  2343. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  2344. }
  2345. }
  2346. }
  2347. }
  2348. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  2349. * wbuf and wbuf_len is a target buffer and its length. */
  2350. static void
  2351. to_unicode(const char *path, wchar_t *wbuf, size_t wbuf_len)
  2352. {
  2353. char buf[PATH_MAX], buf2[PATH_MAX];
  2354. mg_strlcpy(buf, path, sizeof(buf));
  2355. change_slashes_to_backslashes(buf);
  2356. /* Convert to Unicode and back. If doubly-converted string does not
  2357. * match the original, something is fishy, reject. */
  2358. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  2359. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  2360. WideCharToMultiByte(
  2361. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  2362. if (strcmp(buf, buf2) != 0) {
  2363. wbuf[0] = L'\0';
  2364. }
  2365. }
  2366. #if defined(_WIN32_WCE)
  2367. /* Create substitutes for POSIX functions in Win32. */
  2368. #if defined(__MINGW32__)
  2369. /* Show no warning in case system functions are not used. */
  2370. #pragma GCC diagnostic push
  2371. #pragma GCC diagnostic ignored "-Wunused-function"
  2372. #endif
  2373. static time_t
  2374. time(time_t *ptime)
  2375. {
  2376. time_t t;
  2377. SYSTEMTIME st;
  2378. FILETIME ft;
  2379. GetSystemTime(&st);
  2380. SystemTimeToFileTime(&st, &ft);
  2381. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  2382. if (ptime != NULL) {
  2383. *ptime = t;
  2384. }
  2385. return t;
  2386. }
  2387. static struct tm *
  2388. localtime(const time_t *ptime, struct tm *ptm)
  2389. {
  2390. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  2391. FILETIME ft, lft;
  2392. SYSTEMTIME st;
  2393. TIME_ZONE_INFORMATION tzinfo;
  2394. if (ptm == NULL) {
  2395. return NULL;
  2396. }
  2397. *(int64_t *)&ft = t;
  2398. FileTimeToLocalFileTime(&ft, &lft);
  2399. FileTimeToSystemTime(&lft, &st);
  2400. ptm->tm_year = st.wYear - 1900;
  2401. ptm->tm_mon = st.wMonth - 1;
  2402. ptm->tm_wday = st.wDayOfWeek;
  2403. ptm->tm_mday = st.wDay;
  2404. ptm->tm_hour = st.wHour;
  2405. ptm->tm_min = st.wMinute;
  2406. ptm->tm_sec = st.wSecond;
  2407. ptm->tm_yday = 0; /* hope nobody uses this */
  2408. ptm->tm_isdst =
  2409. GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT ? 1 : 0;
  2410. return ptm;
  2411. }
  2412. static struct tm *
  2413. gmtime(const time_t *ptime, struct tm *ptm)
  2414. {
  2415. /* FIXME(lsm): fix this. */
  2416. return localtime(ptime, ptm);
  2417. }
  2418. static size_t
  2419. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  2420. {
  2421. (void)mg_snprintf(NULL, dst, dst_size, "implement strftime() for WinCE");
  2422. return 0;
  2423. }
  2424. #if defined(__MINGW32__)
  2425. /* Enable unused function warning again */
  2426. #pragma GCC diagnostic pop
  2427. #endif
  2428. #endif
  2429. /* Windows happily opens files with some garbage at the end of file name.
  2430. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  2431. * "a.cgi", despite one would expect an error back.
  2432. * This function returns non-0 if path ends with some garbage. */
  2433. static int
  2434. path_cannot_disclose_cgi(const char *path)
  2435. {
  2436. static const char *allowed_last_characters = "_-";
  2437. int last = path[strlen(path) - 1];
  2438. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  2439. }
  2440. static int
  2441. mg_stat(struct mg_connection *conn, const char *path, struct file *filep)
  2442. {
  2443. wchar_t wbuf[PATH_MAX];
  2444. WIN32_FILE_ATTRIBUTE_DATA info;
  2445. time_t creation_time;
  2446. if (!filep) {
  2447. return 0;
  2448. }
  2449. memset(filep, 0, sizeof(*filep));
  2450. if (conn && is_file_in_memory(conn, path, filep)) {
  2451. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  2452. * memset */
  2453. filep->last_modified = time(NULL);
  2454. /* last_modified = now ... assumes the file may change during runtime,
  2455. * so every mg_fopen call may return different data */
  2456. /* last_modified = conn->ctx.start_time;
  2457. * May be used it the data does not change during runtime. This allows
  2458. * browser caching. Since we do not know, we have to assume the file
  2459. * in memory may change. */
  2460. return 1;
  2461. }
  2462. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  2463. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  2464. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  2465. filep->last_modified =
  2466. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  2467. info.ftLastWriteTime.dwHighDateTime);
  2468. /* On Windows, the file creation time can be higher than the
  2469. * modification time, e.g. when a file is copied.
  2470. * Since the Last-Modified timestamp is used for caching
  2471. * it should be based on the most recent timestamp. */
  2472. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  2473. info.ftCreationTime.dwHighDateTime);
  2474. if (creation_time > filep->last_modified) {
  2475. filep->last_modified = creation_time;
  2476. }
  2477. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  2478. /* If file name is fishy, reset the file structure and return
  2479. * error.
  2480. * Note it is important to reset, not just return the error, cause
  2481. * functions like is_file_opened() check the struct. */
  2482. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  2483. memset(filep, 0, sizeof(*filep));
  2484. return 0;
  2485. }
  2486. return 1;
  2487. }
  2488. return 0;
  2489. }
  2490. static int
  2491. mg_remove(const char *path)
  2492. {
  2493. wchar_t wbuf[PATH_MAX];
  2494. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  2495. return DeleteFileW(wbuf) ? 0 : -1;
  2496. }
  2497. static int
  2498. mg_mkdir(const char *path, int mode)
  2499. {
  2500. char buf[PATH_MAX];
  2501. wchar_t wbuf[PATH_MAX];
  2502. (void)mode;
  2503. mg_strlcpy(buf, path, sizeof(buf));
  2504. change_slashes_to_backslashes(buf);
  2505. (void)MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, ARRAY_SIZE(wbuf));
  2506. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  2507. }
  2508. /* Create substitutes for POSIX functions in Win32. */
  2509. #if defined(__MINGW32__)
  2510. /* Show no warning in case system functions are not used. */
  2511. #pragma GCC diagnostic push
  2512. #pragma GCC diagnostic ignored "-Wunused-function"
  2513. #endif
  2514. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  2515. static DIR *
  2516. opendir(const char *name)
  2517. {
  2518. DIR *dir = NULL;
  2519. wchar_t wpath[PATH_MAX];
  2520. DWORD attrs;
  2521. if (name == NULL) {
  2522. SetLastError(ERROR_BAD_ARGUMENTS);
  2523. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  2524. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  2525. } else {
  2526. to_unicode(name, wpath, ARRAY_SIZE(wpath));
  2527. attrs = GetFileAttributesW(wpath);
  2528. if (attrs != 0xFFFFFFFF && ((attrs & FILE_ATTRIBUTE_DIRECTORY)
  2529. == FILE_ATTRIBUTE_DIRECTORY)) {
  2530. (void)wcscat(wpath, L"\\*");
  2531. dir->handle = FindFirstFileW(wpath, &dir->info);
  2532. dir->result.d_name[0] = '\0';
  2533. } else {
  2534. mg_free(dir);
  2535. dir = NULL;
  2536. }
  2537. }
  2538. return dir;
  2539. }
  2540. static int
  2541. closedir(DIR *dir)
  2542. {
  2543. int result = 0;
  2544. if (dir != NULL) {
  2545. if (dir->handle != INVALID_HANDLE_VALUE)
  2546. result = FindClose(dir->handle) ? 0 : -1;
  2547. mg_free(dir);
  2548. } else {
  2549. result = -1;
  2550. SetLastError(ERROR_BAD_ARGUMENTS);
  2551. }
  2552. return result;
  2553. }
  2554. static struct dirent *
  2555. readdir(DIR *dir)
  2556. {
  2557. struct dirent *result = 0;
  2558. if (dir) {
  2559. if (dir->handle != INVALID_HANDLE_VALUE) {
  2560. result = &dir->result;
  2561. (void)WideCharToMultiByte(CP_UTF8,
  2562. 0,
  2563. dir->info.cFileName,
  2564. -1,
  2565. result->d_name,
  2566. sizeof(result->d_name),
  2567. NULL,
  2568. NULL);
  2569. if (!FindNextFileW(dir->handle, &dir->info)) {
  2570. (void)FindClose(dir->handle);
  2571. dir->handle = INVALID_HANDLE_VALUE;
  2572. }
  2573. } else {
  2574. SetLastError(ERROR_FILE_NOT_FOUND);
  2575. }
  2576. } else {
  2577. SetLastError(ERROR_BAD_ARGUMENTS);
  2578. }
  2579. return result;
  2580. }
  2581. #ifndef HAVE_POLL
  2582. static int
  2583. poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  2584. {
  2585. struct timeval tv;
  2586. fd_set set;
  2587. unsigned int i;
  2588. int result;
  2589. SOCKET maxfd = 0;
  2590. memset(&tv, 0, sizeof(tv));
  2591. tv.tv_sec = milliseconds / 1000;
  2592. tv.tv_usec = (milliseconds % 1000) * 1000;
  2593. FD_ZERO(&set);
  2594. for (i = 0; i < n; i++) {
  2595. FD_SET((SOCKET)pfd[i].fd, &set);
  2596. pfd[i].revents = 0;
  2597. if (pfd[i].fd > maxfd) {
  2598. maxfd = pfd[i].fd;
  2599. }
  2600. }
  2601. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  2602. for (i = 0; i < n; i++) {
  2603. if (FD_ISSET(pfd[i].fd, &set)) {
  2604. pfd[i].revents = POLLIN;
  2605. }
  2606. }
  2607. }
  2608. return result;
  2609. }
  2610. #endif /* HAVE_POLL */
  2611. #if defined(__MINGW32__)
  2612. /* Enable unused function warning again */
  2613. #pragma GCC diagnostic pop
  2614. #endif
  2615. static void
  2616. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  2617. {
  2618. (void)conn; /* Unused. */
  2619. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  2620. }
  2621. int
  2622. mg_start_thread(mg_thread_func_t f, void *p)
  2623. {
  2624. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  2625. /* Compile-time option to control stack size, e.g. -DUSE_STACK_SIZE=16384
  2626. */
  2627. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  2628. == ((uintptr_t)(-1L)))
  2629. ? -1
  2630. : 0);
  2631. #else
  2632. return (
  2633. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  2634. ? -1
  2635. : 0);
  2636. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  2637. }
  2638. /* Start a thread storing the thread context. */
  2639. static int
  2640. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  2641. void *p,
  2642. pthread_t *threadidptr)
  2643. {
  2644. uintptr_t uip;
  2645. HANDLE threadhandle;
  2646. int result = -1;
  2647. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  2648. threadhandle = (HANDLE)uip;
  2649. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  2650. *threadidptr = threadhandle;
  2651. result = 0;
  2652. }
  2653. return result;
  2654. }
  2655. /* Wait for a thread to finish. */
  2656. static int
  2657. mg_join_thread(pthread_t threadid)
  2658. {
  2659. int result;
  2660. DWORD dwevent;
  2661. result = -1;
  2662. dwevent = WaitForSingleObject(threadid, INFINITE);
  2663. if (dwevent == WAIT_FAILED) {
  2664. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  2665. } else {
  2666. if (dwevent == WAIT_OBJECT_0) {
  2667. CloseHandle(threadid);
  2668. result = 0;
  2669. }
  2670. }
  2671. return result;
  2672. }
  2673. #if !defined(NO_SSL_DL)
  2674. /* Create substitutes for POSIX functions in Win32. */
  2675. #if defined(__MINGW32__)
  2676. /* Show no warning in case system functions are not used. */
  2677. #pragma GCC diagnostic push
  2678. #pragma GCC diagnostic ignored "-Wunused-function"
  2679. #endif
  2680. static HANDLE
  2681. dlopen(const char *dll_name, int flags)
  2682. {
  2683. wchar_t wbuf[PATH_MAX];
  2684. (void)flags;
  2685. to_unicode(dll_name, wbuf, ARRAY_SIZE(wbuf));
  2686. return LoadLibraryW(wbuf);
  2687. }
  2688. static int
  2689. dlclose(void *handle)
  2690. {
  2691. int result;
  2692. if (FreeLibrary((HMODULE)handle) != 0) {
  2693. result = 0;
  2694. } else {
  2695. result = -1;
  2696. }
  2697. return result;
  2698. }
  2699. #if defined(__MINGW32__)
  2700. /* Enable unused function warning again */
  2701. #pragma GCC diagnostic pop
  2702. #endif
  2703. #endif
  2704. #if !defined(NO_CGI)
  2705. #define SIGKILL (0)
  2706. static int
  2707. kill(pid_t pid, int sig_num)
  2708. {
  2709. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  2710. (void)CloseHandle((HANDLE)pid);
  2711. return 0;
  2712. }
  2713. static void
  2714. trim_trailing_whitespaces(char *s)
  2715. {
  2716. char *e = s + strlen(s) - 1;
  2717. while (e > s && isspace(*(unsigned char *)e)) {
  2718. *e-- = '\0';
  2719. }
  2720. }
  2721. static pid_t
  2722. spawn_process(struct mg_connection *conn,
  2723. const char *prog,
  2724. char *envblk,
  2725. char *envp[],
  2726. int fdin,
  2727. int fdout,
  2728. int fderr,
  2729. const char *dir)
  2730. {
  2731. HANDLE me;
  2732. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  2733. cmdline[PATH_MAX], buf[PATH_MAX];
  2734. int truncated;
  2735. struct file file = STRUCT_FILE_INITIALIZER;
  2736. STARTUPINFOA si;
  2737. PROCESS_INFORMATION pi = {0};
  2738. (void)envp;
  2739. memset(&si, 0, sizeof(si));
  2740. si.cb = sizeof(si);
  2741. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  2742. si.wShowWindow = SW_HIDE;
  2743. me = GetCurrentProcess();
  2744. DuplicateHandle(me,
  2745. (HANDLE)_get_osfhandle(fdin),
  2746. me,
  2747. &si.hStdInput,
  2748. 0,
  2749. TRUE,
  2750. DUPLICATE_SAME_ACCESS);
  2751. DuplicateHandle(me,
  2752. (HANDLE)_get_osfhandle(fdout),
  2753. me,
  2754. &si.hStdOutput,
  2755. 0,
  2756. TRUE,
  2757. DUPLICATE_SAME_ACCESS);
  2758. DuplicateHandle(me,
  2759. (HANDLE)_get_osfhandle(fderr),
  2760. me,
  2761. &si.hStdError,
  2762. 0,
  2763. TRUE,
  2764. DUPLICATE_SAME_ACCESS);
  2765. /* If CGI file is a script, try to read the interpreter line */
  2766. interp = conn->ctx->config[CGI_INTERPRETER];
  2767. if (interp == NULL) {
  2768. buf[0] = buf[1] = '\0';
  2769. /* Read the first line of the script into the buffer */
  2770. mg_snprintf(
  2771. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  2772. if (truncated) {
  2773. pi.hProcess = (pid_t)-1;
  2774. goto spawn_cleanup;
  2775. }
  2776. if (mg_fopen(conn, cmdline, "r", &file)) {
  2777. p = (char *)file.membuf;
  2778. mg_fgets(buf, sizeof(buf), &file, &p);
  2779. mg_fclose(&file);
  2780. buf[sizeof(buf) - 1] = '\0';
  2781. }
  2782. if (buf[0] == '#' && buf[1] == '!') {
  2783. trim_trailing_whitespaces(buf + 2);
  2784. } else {
  2785. buf[2] = '\0';
  2786. }
  2787. interp = buf + 2;
  2788. }
  2789. if (interp[0] != '\0') {
  2790. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  2791. interp = full_interp;
  2792. }
  2793. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  2794. if (interp[0] != '\0') {
  2795. mg_snprintf(conn,
  2796. &truncated,
  2797. cmdline,
  2798. sizeof(cmdline),
  2799. "\"%s\" \"%s\\%s\"",
  2800. interp,
  2801. full_dir,
  2802. prog);
  2803. } else {
  2804. mg_snprintf(conn,
  2805. &truncated,
  2806. cmdline,
  2807. sizeof(cmdline),
  2808. "\"%s\\%s\"",
  2809. full_dir,
  2810. prog);
  2811. }
  2812. if (truncated) {
  2813. pi.hProcess = (pid_t)-1;
  2814. goto spawn_cleanup;
  2815. }
  2816. DEBUG_TRACE("Running [%s]", cmdline);
  2817. if (CreateProcessA(NULL,
  2818. cmdline,
  2819. NULL,
  2820. NULL,
  2821. TRUE,
  2822. CREATE_NEW_PROCESS_GROUP,
  2823. envblk,
  2824. NULL,
  2825. &si,
  2826. &pi) == 0) {
  2827. mg_cry(
  2828. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  2829. pi.hProcess = (pid_t)-1;
  2830. /* goto spawn_cleanup; */
  2831. }
  2832. spawn_cleanup:
  2833. (void)CloseHandle(si.hStdOutput);
  2834. (void)CloseHandle(si.hStdError);
  2835. (void)CloseHandle(si.hStdInput);
  2836. if (pi.hThread != NULL) {
  2837. (void)CloseHandle(pi.hThread);
  2838. }
  2839. return (pid_t)pi.hProcess;
  2840. }
  2841. #endif /* !NO_CGI */
  2842. static int
  2843. set_non_blocking_mode(SOCKET sock)
  2844. {
  2845. unsigned long on = 1;
  2846. return ioctlsocket(sock, (long)FIONBIO, &on);
  2847. }
  2848. #else
  2849. static int
  2850. mg_stat(struct mg_connection *conn, const char *path, struct file *filep)
  2851. {
  2852. struct stat st;
  2853. if (!filep) {
  2854. return 0;
  2855. }
  2856. memset(filep, 0, sizeof(*filep));
  2857. if (conn && is_file_in_memory(conn, path, filep)) {
  2858. return 1;
  2859. }
  2860. if (0 == stat(path, &st)) {
  2861. filep->size = (uint64_t)(st.st_size);
  2862. filep->last_modified = st.st_mtime;
  2863. filep->is_directory = S_ISDIR(st.st_mode);
  2864. return 1;
  2865. }
  2866. return 0;
  2867. }
  2868. static void
  2869. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  2870. {
  2871. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  2872. if (conn) {
  2873. mg_cry(conn,
  2874. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  2875. __func__,
  2876. strerror(ERRNO));
  2877. }
  2878. }
  2879. }
  2880. int
  2881. mg_start_thread(mg_thread_func_t func, void *param)
  2882. {
  2883. pthread_t thread_id;
  2884. pthread_attr_t attr;
  2885. int result;
  2886. (void)pthread_attr_init(&attr);
  2887. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  2888. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  2889. /* Compile-time option to control stack size,
  2890. * e.g. -DUSE_STACK_SIZE=16384 */
  2891. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  2892. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  2893. result = pthread_create(&thread_id, &attr, func, param);
  2894. pthread_attr_destroy(&attr);
  2895. return result;
  2896. }
  2897. /* Start a thread storing the thread context. */
  2898. static int
  2899. mg_start_thread_with_id(mg_thread_func_t func,
  2900. void *param,
  2901. pthread_t *threadidptr)
  2902. {
  2903. pthread_t thread_id;
  2904. pthread_attr_t attr;
  2905. int result;
  2906. (void)pthread_attr_init(&attr);
  2907. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  2908. /* Compile-time option to control stack size,
  2909. * e.g. -DUSE_STACK_SIZE=16384 */
  2910. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  2911. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  2912. result = pthread_create(&thread_id, &attr, func, param);
  2913. pthread_attr_destroy(&attr);
  2914. if ((result == 0) && (threadidptr != NULL)) {
  2915. *threadidptr = thread_id;
  2916. }
  2917. return result;
  2918. }
  2919. /* Wait for a thread to finish. */
  2920. static int
  2921. mg_join_thread(pthread_t threadid)
  2922. {
  2923. int result;
  2924. result = pthread_join(threadid, NULL);
  2925. return result;
  2926. }
  2927. #ifndef NO_CGI
  2928. static pid_t
  2929. spawn_process(struct mg_connection *conn,
  2930. const char *prog,
  2931. char *envblk,
  2932. char *envp[],
  2933. int fdin,
  2934. int fdout,
  2935. int fderr,
  2936. const char *dir)
  2937. {
  2938. pid_t pid;
  2939. const char *interp;
  2940. (void)envblk;
  2941. if (conn == NULL) {
  2942. return 0;
  2943. }
  2944. if ((pid = fork()) == -1) {
  2945. /* Parent */
  2946. send_http_error(conn,
  2947. 500,
  2948. "Error: Creating CGI process\nfork(): %s",
  2949. strerror(ERRNO));
  2950. } else if (pid == 0) {
  2951. /* Child */
  2952. if (chdir(dir) != 0) {
  2953. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  2954. } else if (dup2(fdin, 0) == -1) {
  2955. mg_cry(
  2956. conn, "%s: dup2(%d, 0): %s", __func__, fdin, strerror(ERRNO));
  2957. } else if (dup2(fdout, 1) == -1) {
  2958. mg_cry(
  2959. conn, "%s: dup2(%d, 1): %s", __func__, fdout, strerror(ERRNO));
  2960. } else if (dup2(fderr, 2) == -1) {
  2961. mg_cry(
  2962. conn, "%s: dup2(%d, 2): %s", __func__, fderr, strerror(ERRNO));
  2963. } else {
  2964. /* Keep stderr and stdout in two different pipes.
  2965. * Stdout will be sent back to the client,
  2966. * stderr should go into a server error log. */
  2967. (void)close(fdin);
  2968. (void)close(fdout);
  2969. (void)close(fderr);
  2970. /* After exec, all signal handlers are restored to their default
  2971. * values, with one exception of SIGCHLD. According to
  2972. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler will
  2973. * leave unchanged after exec if it was set to be ignored. Restore
  2974. * it to default action. */
  2975. signal(SIGCHLD, SIG_DFL);
  2976. interp = conn->ctx->config[CGI_INTERPRETER];
  2977. if (interp == NULL) {
  2978. (void)execle(prog, prog, NULL, envp);
  2979. mg_cry(conn,
  2980. "%s: execle(%s): %s",
  2981. __func__,
  2982. prog,
  2983. strerror(ERRNO));
  2984. } else {
  2985. (void)execle(interp, interp, prog, NULL, envp);
  2986. mg_cry(conn,
  2987. "%s: execle(%s %s): %s",
  2988. __func__,
  2989. interp,
  2990. prog,
  2991. strerror(ERRNO));
  2992. }
  2993. }
  2994. exit(EXIT_FAILURE);
  2995. }
  2996. return pid;
  2997. }
  2998. #endif /* !NO_CGI */
  2999. static int
  3000. set_non_blocking_mode(SOCKET sock)
  3001. {
  3002. int flags;
  3003. flags = fcntl(sock, F_GETFL, 0);
  3004. (void)fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  3005. return 0;
  3006. }
  3007. #endif /* _WIN32 */
  3008. /* End of initial operating system specific define block. */
  3009. /* Get a random number (independent of C rand function) */
  3010. static uint64_t
  3011. get_random(void)
  3012. {
  3013. static uint64_t lfsr = 0; /* Linear feedback shift register */
  3014. static uint64_t lcg = 0; /* Linear congruential generator */
  3015. struct timespec now;
  3016. memset(&now, 0, sizeof(now));
  3017. clock_gettime(CLOCK_MONOTONIC, &now);
  3018. if (lfsr == 0) {
  3019. /* lfsr will be only 0 if has not been initialized,
  3020. * so this code is called only once. */
  3021. lfsr = (((uint64_t)now.tv_sec) << 21) ^ ((uint64_t)now.tv_nsec)
  3022. ^ ((uint64_t)(ptrdiff_t)&now) ^ ((uint64_t)pthread_self())
  3023. ^ (((uint64_t)time(NULL)) << 33);
  3024. lcg = (((uint64_t)now.tv_sec) << 25) + (uint64_t)now.tv_nsec
  3025. + (uint64_t)(ptrdiff_t)&now;
  3026. } else {
  3027. /* Get the next step of both random number generators. */
  3028. lfsr = (lfsr >> 1)
  3029. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  3030. << 63);
  3031. lcg = lcg * 6364136223846793005 + 1442695040888963407;
  3032. }
  3033. /* Combining two pseudo-random number generators and a high resolution part
  3034. * of the current server time will make it hard (impossible?) to guess the
  3035. * next number. */
  3036. return (lfsr ^ lcg ^ (uint64_t)now.tv_nsec);
  3037. }
  3038. /* Write data to the IO channel - opened file descriptor, socket or SSL
  3039. * descriptor. Return number of bytes written. */
  3040. static int
  3041. push(struct mg_context *ctx,
  3042. FILE *fp,
  3043. SOCKET sock,
  3044. SSL *ssl,
  3045. const char *buf,
  3046. int len,
  3047. double timeout)
  3048. {
  3049. struct timespec start, now;
  3050. int n, err;
  3051. #ifdef _WIN32
  3052. typedef int len_t;
  3053. #else
  3054. typedef size_t len_t;
  3055. #endif
  3056. if (timeout > 0) {
  3057. memset(&start, 0, sizeof(start));
  3058. memset(&now, 0, sizeof(now));
  3059. clock_gettime(CLOCK_MONOTONIC, &start);
  3060. }
  3061. if (ctx == NULL) {
  3062. return -1;
  3063. }
  3064. #ifdef NO_SSL
  3065. if (ssl) {
  3066. return -1;
  3067. }
  3068. #endif
  3069. do {
  3070. #ifndef NO_SSL
  3071. if (ssl != NULL) {
  3072. n = SSL_write(ssl, buf, len);
  3073. if (n <= 0) {
  3074. err = SSL_get_error(ssl, n);
  3075. if ((err == 5 /* SSL_ERROR_SYSCALL */) && (n == -1)) {
  3076. err = ERRNO;
  3077. } else {
  3078. DEBUG_TRACE("SSL_write() failed, error %d", err);
  3079. return -1;
  3080. }
  3081. } else {
  3082. err = 0;
  3083. }
  3084. } else
  3085. #endif
  3086. if (fp != NULL) {
  3087. n = (int)fwrite(buf, 1, (size_t)len, fp);
  3088. if (ferror(fp)) {
  3089. n = -1;
  3090. err = ERRNO;
  3091. } else {
  3092. err = 0;
  3093. }
  3094. } else {
  3095. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  3096. err = (n < 0) ? ERRNO : 0;
  3097. }
  3098. if (ctx->stop_flag) {
  3099. return -1;
  3100. }
  3101. if ((n > 0) || (n == 0 && len == 0)) {
  3102. /* some data has been read, or no data was requested */
  3103. return n;
  3104. }
  3105. if (n == 0) {
  3106. /* shutdown of the socket at client side */
  3107. return -1;
  3108. }
  3109. if (n < 0) {
  3110. /* socket error - check errno */
  3111. DEBUG_TRACE("send() failed, error %d", err);
  3112. /* TODO: error handling depending on the error code.
  3113. * These codes are different between Windows and Linux.
  3114. */
  3115. return -1;
  3116. }
  3117. /* This code is not reached in the moment.
  3118. * ==> Fix the TODOs above first. */
  3119. if (timeout > 0) {
  3120. clock_gettime(CLOCK_MONOTONIC, &now);
  3121. }
  3122. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  3123. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  3124. used */
  3125. return -1;
  3126. }
  3127. static int64_t
  3128. push_all(struct mg_context *ctx,
  3129. FILE *fp,
  3130. SOCKET sock,
  3131. SSL *ssl,
  3132. const char *buf,
  3133. int64_t len)
  3134. {
  3135. double timeout = -1.0;
  3136. int64_t n, nwritten = 0;
  3137. if (ctx == NULL) {
  3138. return -1;
  3139. }
  3140. if (ctx->config[REQUEST_TIMEOUT]) {
  3141. timeout = atoi(ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  3142. }
  3143. while (len > 0 && ctx->stop_flag == 0) {
  3144. n = push(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  3145. if (n < 0) {
  3146. if (nwritten == 0) {
  3147. nwritten = n; /* Propagate the error */
  3148. }
  3149. break;
  3150. } else if (n == 0) {
  3151. break; /* No more data to write */
  3152. } else {
  3153. nwritten += n;
  3154. len -= n;
  3155. }
  3156. }
  3157. return nwritten;
  3158. }
  3159. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  3160. * Return negative value on error, or number of bytes read on success. */
  3161. static int
  3162. pull(FILE *fp, struct mg_connection *conn, char *buf, int len, double timeout)
  3163. {
  3164. int nread, err;
  3165. struct timespec start, now;
  3166. #ifdef _WIN32
  3167. typedef int len_t;
  3168. #else
  3169. typedef size_t len_t;
  3170. #endif
  3171. if (timeout > 0) {
  3172. memset(&start, 0, sizeof(start));
  3173. memset(&now, 0, sizeof(now));
  3174. clock_gettime(CLOCK_MONOTONIC, &start);
  3175. }
  3176. do {
  3177. if (fp != NULL) {
  3178. /* Use read() instead of fread(), because if we're reading from the
  3179. * CGI pipe, fread() may block until IO buffer is filled up. We
  3180. * cannot afford to block and must pass all read bytes immediately
  3181. * to the client. */
  3182. nread = (int)read(fileno(fp), buf, (size_t)len);
  3183. err = (nread < 0) ? ERRNO : 0;
  3184. #ifndef NO_SSL
  3185. } else if (conn->ssl != NULL) {
  3186. nread = SSL_read(conn->ssl, buf, len);
  3187. if (nread <= 0) {
  3188. err = SSL_get_error(conn->ssl, nread);
  3189. if ((err == 5 /* SSL_ERROR_SYSCALL */) && (nread == -1)) {
  3190. err = ERRNO;
  3191. } else {
  3192. DEBUG_TRACE("SSL_read() failed, error %d", err);
  3193. return -1;
  3194. }
  3195. } else {
  3196. err = 0;
  3197. }
  3198. #endif
  3199. } else {
  3200. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  3201. err = (nread < 0) ? ERRNO : 0;
  3202. }
  3203. if (conn->ctx->stop_flag) {
  3204. return -1;
  3205. }
  3206. if ((nread > 0) || (nread == 0 && len == 0)) {
  3207. /* some data has been read, or no data was requested */
  3208. return nread;
  3209. }
  3210. if (nread == 0) {
  3211. /* shutdown of the socket at client side */
  3212. return -1;
  3213. }
  3214. if (nread < 0) {
  3215. /* socket error - check errno */
  3216. #ifdef _WIN32
  3217. if (err == WSAEWOULDBLOCK) {
  3218. /* standard case if called from close_socket_gracefully */
  3219. return -1;
  3220. } else if (err == WSAETIMEDOUT) {
  3221. /* timeout is handled by the while loop */
  3222. } else {
  3223. DEBUG_TRACE("recv() failed, error %d", err);
  3224. return -1;
  3225. }
  3226. #else
  3227. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  3228. * if the timeout is reached and if the socket was set to non-
  3229. * blocking in close_socket_gracefully, so we can not distinguish
  3230. * here. We have to wait for the timeout in both cases for now.
  3231. */
  3232. if (err == EAGAIN || err == EWOULDBLOCK) {
  3233. /* standard case if called from close_socket_gracefully
  3234. * => should return -1 */
  3235. /* or timeout occured
  3236. * => the code must stay in the while loop */
  3237. } else {
  3238. DEBUG_TRACE("recv() failed, error %d", err);
  3239. return -1;
  3240. }
  3241. #endif
  3242. }
  3243. if (timeout > 0) {
  3244. clock_gettime(CLOCK_MONOTONIC, &now);
  3245. }
  3246. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  3247. /* Timeout occured, but no data available. */
  3248. return -1;
  3249. }
  3250. static int
  3251. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  3252. {
  3253. int n, nread = 0;
  3254. double timeout = -1.0;
  3255. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  3256. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  3257. }
  3258. while (len > 0 && conn->ctx->stop_flag == 0) {
  3259. n = pull(fp, conn, buf + nread, len, timeout);
  3260. if (n < 0) {
  3261. if (nread == 0) {
  3262. nread = n; /* Propagate the error */
  3263. }
  3264. break;
  3265. } else if (n == 0) {
  3266. break; /* No more data to read */
  3267. } else {
  3268. conn->consumed_content += n;
  3269. nread += n;
  3270. len -= n;
  3271. }
  3272. }
  3273. return nread;
  3274. }
  3275. static void
  3276. discard_unread_request_data(struct mg_connection *conn)
  3277. {
  3278. char buf[MG_BUF_LEN];
  3279. size_t to_read;
  3280. int nread;
  3281. if (conn == NULL) {
  3282. return;
  3283. }
  3284. to_read = sizeof(buf);
  3285. if (conn->is_chunked) {
  3286. /* Chunked encoding: 1=chunk not read completely, 2=chunk read
  3287. * completely */
  3288. while (conn->is_chunked == 1) {
  3289. nread = mg_read(conn, buf, to_read);
  3290. if (nread <= 0) {
  3291. break;
  3292. }
  3293. }
  3294. } else {
  3295. /* Not chunked: content length is known */
  3296. while (conn->consumed_content < conn->content_len) {
  3297. if (to_read
  3298. > (size_t)(conn->content_len - conn->consumed_content)) {
  3299. to_read = (size_t)(conn->content_len - conn->consumed_content);
  3300. }
  3301. nread = mg_read(conn, buf, to_read);
  3302. if (nread <= 0) {
  3303. break;
  3304. }
  3305. }
  3306. }
  3307. }
  3308. static int
  3309. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  3310. {
  3311. int64_t n, buffered_len, nread;
  3312. int64_t len64 =
  3313. (int64_t)(len > INT_MAX ? INT_MAX : len); /* since the return value is
  3314. * int, we may not read more
  3315. * bytes */
  3316. const char *body;
  3317. if (conn == NULL) {
  3318. return 0;
  3319. }
  3320. /* If Content-Length is not set for a PUT or POST request, read until
  3321. * socket is closed */
  3322. if (conn->consumed_content == 0 && conn->content_len == -1) {
  3323. conn->content_len = INT64_MAX;
  3324. conn->must_close = 1;
  3325. }
  3326. nread = 0;
  3327. if (conn->consumed_content < conn->content_len) {
  3328. /* Adjust number of bytes to read. */
  3329. int64_t left_to_read = conn->content_len - conn->consumed_content;
  3330. if (left_to_read < len64) {
  3331. /* Do not read more than the total content length of the request.
  3332. */
  3333. len64 = left_to_read;
  3334. }
  3335. /* Return buffered data */
  3336. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  3337. - conn->consumed_content;
  3338. if (buffered_len > 0) {
  3339. if (len64 < buffered_len) {
  3340. buffered_len = len64;
  3341. }
  3342. body = conn->buf + conn->request_len + conn->consumed_content;
  3343. memcpy(buf, body, (size_t)buffered_len);
  3344. len64 -= buffered_len;
  3345. conn->consumed_content += buffered_len;
  3346. nread += buffered_len;
  3347. buf = (char *)buf + buffered_len;
  3348. }
  3349. /* We have returned all buffered data. Read new data from the remote
  3350. * socket.
  3351. */
  3352. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  3353. nread += n;
  3354. } else {
  3355. nread = (nread > 0 ? nread : n);
  3356. }
  3357. }
  3358. return (int)nread;
  3359. }
  3360. static char
  3361. mg_getc(struct mg_connection *conn)
  3362. {
  3363. char c;
  3364. if (conn == NULL) {
  3365. return 0;
  3366. }
  3367. conn->content_len++;
  3368. if (mg_read_inner(conn, &c, 1) <= 0) {
  3369. return (char)0;
  3370. }
  3371. return c;
  3372. }
  3373. int
  3374. mg_read(struct mg_connection *conn, void *buf, size_t len)
  3375. {
  3376. if (len > INT_MAX) {
  3377. len = INT_MAX;
  3378. }
  3379. if (conn == NULL) {
  3380. return 0;
  3381. }
  3382. if (conn->is_chunked) {
  3383. size_t all_read = 0;
  3384. while (len > 0) {
  3385. if (conn->chunk_remainder) {
  3386. /* copy from the remainder of the last received chunk */
  3387. long read_ret;
  3388. size_t read_now =
  3389. ((conn->chunk_remainder > len) ? (len)
  3390. : (conn->chunk_remainder));
  3391. conn->content_len += (int)read_now;
  3392. read_ret =
  3393. mg_read_inner(conn, (char *)buf + all_read, read_now);
  3394. all_read += (size_t)read_ret;
  3395. conn->chunk_remainder -= read_now;
  3396. len -= read_now;
  3397. if (conn->chunk_remainder == 0) {
  3398. /* the rest of the data in the current chunk has been read
  3399. */
  3400. if ((mg_getc(conn) != '\r') || (mg_getc(conn) != '\n')) {
  3401. /* Protocol violation */
  3402. return -1;
  3403. }
  3404. }
  3405. } else {
  3406. /* fetch a new chunk */
  3407. int i = 0;
  3408. char lenbuf[64];
  3409. char *end = 0;
  3410. unsigned long chunkSize = 0;
  3411. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  3412. lenbuf[i] = mg_getc(conn);
  3413. if (i > 0 && lenbuf[i] == '\r' && lenbuf[i - 1] != '\r') {
  3414. continue;
  3415. }
  3416. if (i > 1 && lenbuf[i] == '\n' && lenbuf[i - 1] == '\r') {
  3417. lenbuf[i + 1] = 0;
  3418. chunkSize = strtoul(lenbuf, &end, 16);
  3419. break;
  3420. }
  3421. if (!isalnum(lenbuf[i])) {
  3422. /* illegal character for chunk length */
  3423. return -1;
  3424. }
  3425. }
  3426. if ((end == NULL) || (*end != '\r')) {
  3427. /* chunksize not set correctly */
  3428. return -1;
  3429. }
  3430. conn->chunk_remainder = chunkSize;
  3431. if (chunkSize == 0) {
  3432. /* regular end of content */
  3433. conn->is_chunked = 2;
  3434. break;
  3435. }
  3436. }
  3437. }
  3438. return (int)all_read;
  3439. }
  3440. return mg_read_inner(conn, buf, len);
  3441. }
  3442. int
  3443. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  3444. {
  3445. time_t now;
  3446. int64_t n, total, allowed;
  3447. if (conn == NULL) {
  3448. return 0;
  3449. }
  3450. if (conn->throttle > 0) {
  3451. if ((now = time(NULL)) != conn->last_throttle_time) {
  3452. conn->last_throttle_time = now;
  3453. conn->last_throttle_bytes = 0;
  3454. }
  3455. allowed = conn->throttle - conn->last_throttle_bytes;
  3456. if (allowed > (int64_t)len) {
  3457. allowed = (int64_t)len;
  3458. }
  3459. if ((total = push_all(conn->ctx,
  3460. NULL,
  3461. conn->client.sock,
  3462. conn->ssl,
  3463. (const char *)buf,
  3464. (int64_t)allowed)) == allowed) {
  3465. buf = (char *)buf + total;
  3466. conn->last_throttle_bytes += total;
  3467. while (total < (int64_t)len && conn->ctx->stop_flag == 0) {
  3468. allowed = conn->throttle > (int64_t)len - total
  3469. ? (int64_t)len - total
  3470. : conn->throttle;
  3471. if ((n = push_all(conn->ctx,
  3472. NULL,
  3473. conn->client.sock,
  3474. conn->ssl,
  3475. (const char *)buf,
  3476. (int64_t)allowed)) != allowed) {
  3477. break;
  3478. }
  3479. sleep(1);
  3480. conn->last_throttle_bytes = allowed;
  3481. conn->last_throttle_time = time(NULL);
  3482. buf = (char *)buf + n;
  3483. total += n;
  3484. }
  3485. }
  3486. } else {
  3487. total = push_all(conn->ctx,
  3488. NULL,
  3489. conn->client.sock,
  3490. conn->ssl,
  3491. (const char *)buf,
  3492. (int64_t)len);
  3493. }
  3494. return (int)total;
  3495. }
  3496. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  3497. static int
  3498. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  3499. {
  3500. va_list ap_copy;
  3501. size_t size = MG_BUF_LEN;
  3502. int len = -1;
  3503. *buf = NULL;
  3504. while (len < 0) {
  3505. if (*buf) {
  3506. mg_free(*buf);
  3507. }
  3508. *buf = (char *)mg_malloc(size *= 4);
  3509. if (!*buf) {
  3510. break;
  3511. }
  3512. va_copy(ap_copy, ap);
  3513. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  3514. va_end(ap_copy);
  3515. *buf[size - 1] = 0;
  3516. }
  3517. return len;
  3518. }
  3519. /* Print message to buffer. If buffer is large enough to hold the message,
  3520. * return buffer. If buffer is to small, allocate large enough buffer on heap,
  3521. * and return allocated buffer. */
  3522. static int
  3523. alloc_vprintf(char **out_buf,
  3524. char *prealloc_buf,
  3525. size_t prealloc_size,
  3526. const char *fmt,
  3527. va_list ap)
  3528. {
  3529. va_list ap_copy;
  3530. int len;
  3531. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  3532. * buffer is too small. Also, older versions of msvcrt.dll do not have
  3533. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  3534. * Therefore, we make two passes: on first pass, get required message
  3535. * length.
  3536. * On second pass, actually print the message. */
  3537. va_copy(ap_copy, ap);
  3538. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  3539. va_end(ap_copy);
  3540. if (len < 0) {
  3541. /* C runtime is not standard compliant, vsnprintf() returned -1.
  3542. * Switch to alternative code path that uses incremental allocations.
  3543. */
  3544. va_copy(ap_copy, ap);
  3545. len = alloc_vprintf2(out_buf, fmt, ap);
  3546. va_end(ap_copy);
  3547. } else if ((size_t)(len) >= prealloc_size) {
  3548. /* The pre-allocated buffer not large enough. */
  3549. /* Allocate a new buffer. */
  3550. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  3551. if (!*out_buf) {
  3552. /* Allocation failed. Return -1 as "out of memory" error. */
  3553. return -1;
  3554. }
  3555. /* Buffer allocation successful. Store the string there. */
  3556. va_copy(ap_copy, ap);
  3557. IGNORE_UNUSED_RESULT(
  3558. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  3559. va_end(ap_copy);
  3560. } else {
  3561. /* The pre-allocated buffer is large enough.
  3562. * Use it to store the string and return the address. */
  3563. va_copy(ap_copy, ap);
  3564. IGNORE_UNUSED_RESULT(
  3565. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  3566. va_end(ap_copy);
  3567. *out_buf = prealloc_buf;
  3568. }
  3569. return len;
  3570. }
  3571. static int
  3572. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  3573. {
  3574. char mem[MG_BUF_LEN];
  3575. char *buf = NULL;
  3576. int len;
  3577. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  3578. len = mg_write(conn, buf, (size_t)len);
  3579. }
  3580. if (buf != mem && buf != NULL) {
  3581. mg_free(buf);
  3582. }
  3583. return len;
  3584. }
  3585. int
  3586. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  3587. {
  3588. va_list ap;
  3589. int result;
  3590. va_start(ap, fmt);
  3591. result = mg_vprintf(conn, fmt, ap);
  3592. va_end(ap);
  3593. return result;
  3594. }
  3595. int
  3596. mg_url_decode(const char *src,
  3597. int src_len,
  3598. char *dst,
  3599. int dst_len,
  3600. int is_form_url_encoded)
  3601. {
  3602. int i, j, a, b;
  3603. #define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W')
  3604. for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) {
  3605. if (i < src_len - 2 && src[i] == '%'
  3606. && isxdigit(*(const unsigned char *)(src + i + 1))
  3607. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  3608. a = tolower(*(const unsigned char *)(src + i + 1));
  3609. b = tolower(*(const unsigned char *)(src + i + 2));
  3610. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  3611. i += 2;
  3612. } else if (is_form_url_encoded && src[i] == '+') {
  3613. dst[j] = ' ';
  3614. } else {
  3615. dst[j] = src[i];
  3616. }
  3617. }
  3618. dst[j] = '\0'; /* Null-terminate the destination */
  3619. return i >= src_len ? j : -1;
  3620. }
  3621. int
  3622. mg_get_var(const char *data,
  3623. size_t data_len,
  3624. const char *name,
  3625. char *dst,
  3626. size_t dst_len)
  3627. {
  3628. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  3629. }
  3630. int
  3631. mg_get_var2(const char *data,
  3632. size_t data_len,
  3633. const char *name,
  3634. char *dst,
  3635. size_t dst_len,
  3636. size_t occurrence)
  3637. {
  3638. const char *p, *e, *s;
  3639. size_t name_len;
  3640. int len;
  3641. if (dst == NULL || dst_len == 0) {
  3642. len = -2;
  3643. } else if (data == NULL || name == NULL || data_len == 0) {
  3644. len = -1;
  3645. dst[0] = '\0';
  3646. } else {
  3647. name_len = strlen(name);
  3648. e = data + data_len;
  3649. len = -1;
  3650. dst[0] = '\0';
  3651. /* data is "var1=val1&var2=val2...". Find variable first */
  3652. for (p = data; p + name_len < e; p++) {
  3653. if ((p == data || p[-1] == '&') && p[name_len] == '='
  3654. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  3655. /* Point p to variable value */
  3656. p += name_len + 1;
  3657. /* Point s to the end of the value */
  3658. s = (const char *)memchr(p, '&', (size_t)(e - p));
  3659. if (s == NULL) {
  3660. s = e;
  3661. }
  3662. /* assert(s >= p); */
  3663. if (s < p) {
  3664. return -3;
  3665. }
  3666. /* Decode variable into destination buffer */
  3667. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  3668. /* Redirect error code from -1 to -2 (destination buffer too
  3669. * small). */
  3670. if (len == -1) {
  3671. len = -2;
  3672. }
  3673. break;
  3674. }
  3675. }
  3676. }
  3677. return len;
  3678. }
  3679. int
  3680. mg_get_cookie(const char *cookie_header,
  3681. const char *var_name,
  3682. char *dst,
  3683. size_t dst_size)
  3684. {
  3685. const char *s, *p, *end;
  3686. int name_len, len = -1;
  3687. if (dst == NULL || dst_size == 0) {
  3688. len = -2;
  3689. } else if (var_name == NULL || (s = cookie_header) == NULL) {
  3690. len = -1;
  3691. dst[0] = '\0';
  3692. } else {
  3693. name_len = (int)strlen(var_name);
  3694. end = s + strlen(s);
  3695. dst[0] = '\0';
  3696. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  3697. if (s[name_len] == '=') {
  3698. s += name_len + 1;
  3699. if ((p = strchr(s, ' ')) == NULL) {
  3700. p = end;
  3701. }
  3702. if (p[-1] == ';') {
  3703. p--;
  3704. }
  3705. if (*s == '"' && p[-1] == '"' && p > s + 1) {
  3706. s++;
  3707. p--;
  3708. }
  3709. if ((size_t)(p - s) < dst_size) {
  3710. len = (int)(p - s);
  3711. mg_strlcpy(dst, s, (size_t)len + 1);
  3712. } else {
  3713. len = -3;
  3714. }
  3715. break;
  3716. }
  3717. }
  3718. }
  3719. return len;
  3720. }
  3721. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  3722. static void
  3723. base64_encode(const unsigned char *src, int src_len, char *dst)
  3724. {
  3725. static const char *b64 =
  3726. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3727. int i, j, a, b, c;
  3728. for (i = j = 0; i < src_len; i += 3) {
  3729. a = src[i];
  3730. b = i + 1 >= src_len ? 0 : src[i + 1];
  3731. c = i + 2 >= src_len ? 0 : src[i + 2];
  3732. dst[j++] = b64[a >> 2];
  3733. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  3734. if (i + 1 < src_len) {
  3735. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  3736. }
  3737. if (i + 2 < src_len) {
  3738. dst[j++] = b64[c & 63];
  3739. }
  3740. }
  3741. while (j % 4 != 0) {
  3742. dst[j++] = '=';
  3743. }
  3744. dst[j++] = '\0';
  3745. }
  3746. #endif
  3747. #if defined(USE_LUA)
  3748. static unsigned char
  3749. b64reverse(char letter)
  3750. {
  3751. if (letter >= 'A' && letter <= 'Z') {
  3752. return letter - 'A';
  3753. }
  3754. if (letter >= 'a' && letter <= 'z') {
  3755. return letter - 'a' + 26;
  3756. }
  3757. if (letter >= '0' && letter <= '9') {
  3758. return letter - '0' + 52;
  3759. }
  3760. if (letter == '+') {
  3761. return 62;
  3762. }
  3763. if (letter == '/') {
  3764. return 63;
  3765. }
  3766. if (letter == '=') {
  3767. return 255; /* normal end */
  3768. }
  3769. return 254; /* error */
  3770. }
  3771. static int
  3772. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  3773. {
  3774. int i;
  3775. unsigned char a, b, c, d;
  3776. *dst_len = 0;
  3777. for (i = 0; i < src_len; i += 4) {
  3778. a = b64reverse(src[i]);
  3779. if (a >= 254) {
  3780. return i;
  3781. }
  3782. b = b64reverse(i + 1 >= src_len ? 0 : src[i + 1]);
  3783. if (b >= 254) {
  3784. return i + 1;
  3785. }
  3786. c = b64reverse(i + 2 >= src_len ? 0 : src[i + 2]);
  3787. if (c == 254) {
  3788. return i + 2;
  3789. }
  3790. d = b64reverse(i + 3 >= src_len ? 0 : src[i + 3]);
  3791. if (d == 254) {
  3792. return i + 3;
  3793. }
  3794. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  3795. if (c != 255) {
  3796. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  3797. if (d != 255) {
  3798. dst[(*dst_len)++] = (c << 6) + d;
  3799. }
  3800. }
  3801. }
  3802. return -1;
  3803. }
  3804. #endif
  3805. static int
  3806. is_put_or_delete_method(const struct mg_connection *conn)
  3807. {
  3808. if (conn) {
  3809. const char *s = conn->request_info.request_method;
  3810. return s != NULL && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  3811. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  3812. }
  3813. return 0;
  3814. }
  3815. static void
  3816. interpret_uri(struct mg_connection *conn, /* in: request (must be valid) */
  3817. char *filename, /* out: filename */
  3818. size_t filename_buf_len, /* in: size of filename buffer */
  3819. struct file *filep, /* out: file structure */
  3820. int *is_found, /* out: file is found (directly) */
  3821. int *is_script_resource, /* out: handled by a script? */
  3822. int *is_websocket_request, /* out: websocket connetion? */
  3823. int *is_put_or_delete_request /* out: put/delete a file? */
  3824. )
  3825. {
  3826. /* TODO (high): Restructure this function */
  3827. #if !defined(NO_FILES)
  3828. const char *uri = conn->request_info.local_uri;
  3829. const char *root = conn->ctx->config[DOCUMENT_ROOT];
  3830. const char *rewrite;
  3831. struct vec a, b;
  3832. int match_len;
  3833. char gz_path[PATH_MAX];
  3834. char const *accept_encoding;
  3835. int truncated;
  3836. #if !defined(NO_CGI) || defined(USE_LUA)
  3837. char *p;
  3838. #endif
  3839. #else
  3840. (void)filename_buf_len; /* unused if NO_FILES is defined */
  3841. #endif
  3842. memset(filep, 0, sizeof(*filep));
  3843. *filename = 0;
  3844. *is_found = 0;
  3845. *is_script_resource = 0;
  3846. *is_put_or_delete_request = is_put_or_delete_method(conn);
  3847. #if defined(USE_WEBSOCKET)
  3848. *is_websocket_request = is_websocket_protocol(conn);
  3849. #if !defined(NO_FILES)
  3850. if (*is_websocket_request && conn->ctx->config[WEBSOCKET_ROOT]) {
  3851. root = conn->ctx->config[WEBSOCKET_ROOT];
  3852. }
  3853. #endif /* !NO_FILES */
  3854. #else /* USE_WEBSOCKET */
  3855. *is_websocket_request = 0;
  3856. #endif /* USE_WEBSOCKET */
  3857. #if !defined(NO_FILES)
  3858. /* Note that root == NULL is a regular use case here. This occurs,
  3859. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  3860. * config is not required. */
  3861. if (root == NULL) {
  3862. /* all file related outputs have already been set to 0, just return
  3863. */
  3864. return;
  3865. }
  3866. /* Using buf_len - 1 because memmove() for PATH_INFO may shift part
  3867. * of the path one byte on the right.
  3868. * If document_root is NULL, leave the file empty. */
  3869. mg_snprintf(
  3870. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  3871. if (truncated) {
  3872. goto interpret_cleanup;
  3873. }
  3874. rewrite = conn->ctx->config[REWRITE];
  3875. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  3876. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  3877. mg_snprintf(conn,
  3878. &truncated,
  3879. filename,
  3880. filename_buf_len - 1,
  3881. "%.*s%s",
  3882. (int)b.len,
  3883. b.ptr,
  3884. uri + match_len);
  3885. break;
  3886. }
  3887. }
  3888. if (truncated) {
  3889. goto interpret_cleanup;
  3890. }
  3891. /* Local file path and name, corresponding to requested URI
  3892. * is now stored in "filename" variable. */
  3893. if (mg_stat(conn, filename, filep)) {
  3894. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  3895. /* File exists. Check if it is a script type. */
  3896. if (0
  3897. #if !defined(NO_CGI)
  3898. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  3899. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  3900. filename) > 0
  3901. #endif
  3902. #if defined(USE_LUA)
  3903. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  3904. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  3905. filename) > 0
  3906. #endif
  3907. #if defined(USE_DUKTAPE)
  3908. || match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  3909. strlen(
  3910. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  3911. filename) > 0
  3912. #endif
  3913. ) {
  3914. /* The request addresses a CGI script or a Lua script. The URI
  3915. * corresponds to the script itself (like /path/script.cgi),
  3916. * and there is no additional resource path
  3917. * (like /path/script.cgi/something).
  3918. * Requests that modify (replace or delete) a resource, like
  3919. * PUT and DELETE requests, should replace/delete the script
  3920. * file.
  3921. * Requests that read or write from/to a resource, like GET and
  3922. * POST requests, should call the script and return the
  3923. * generated response. */
  3924. *is_script_resource = !*is_put_or_delete_request;
  3925. }
  3926. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  3927. *is_found = 1;
  3928. return;
  3929. }
  3930. /* If we can't find the actual file, look for the file
  3931. * with the same name but a .gz extension. If we find it,
  3932. * use that and set the gzipped flag in the file struct
  3933. * to indicate that the response need to have the content-
  3934. * encoding: gzip header.
  3935. * We can only do this if the browser declares support. */
  3936. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  3937. if (strstr(accept_encoding, "gzip") != NULL) {
  3938. mg_snprintf(
  3939. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  3940. if (truncated) {
  3941. goto interpret_cleanup;
  3942. }
  3943. if (mg_stat(conn, gz_path, filep)) {
  3944. if (filep) {
  3945. filep->gzipped = 1;
  3946. *is_found = 1;
  3947. }
  3948. /* Currently gz files can not be scripts. */
  3949. return;
  3950. }
  3951. }
  3952. }
  3953. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  3954. /* Support PATH_INFO for CGI scripts. */
  3955. for (p = filename + strlen(filename); p > filename + 1; p--) {
  3956. if (*p == '/') {
  3957. *p = '\0';
  3958. if ((0
  3959. #if !defined(NO_CGI)
  3960. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  3961. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  3962. filename) > 0
  3963. #endif
  3964. #if defined(USE_LUA)
  3965. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  3966. strlen(
  3967. conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  3968. filename) > 0
  3969. #endif
  3970. #if defined(USE_DUKTAPE)
  3971. || match_prefix(
  3972. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  3973. strlen(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  3974. filename) > 0
  3975. #endif
  3976. ) && mg_stat(conn, filename, filep)) {
  3977. /* Shift PATH_INFO block one character right, e.g.
  3978. * "/x.cgi/foo/bar\x00" => "/x.cgi\x00/foo/bar\x00"
  3979. * conn->path_info is pointing to the local variable "path"
  3980. * declared in handle_request(), so PATH_INFO is not valid
  3981. * after handle_request returns. */
  3982. conn->path_info = p + 1;
  3983. memmove(p + 2, p + 1, strlen(p + 1) + 1); /* +1 is for
  3984. * trailing \0 */
  3985. p[1] = '/';
  3986. *is_script_resource = 1;
  3987. break;
  3988. } else {
  3989. *p = '/';
  3990. }
  3991. }
  3992. }
  3993. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  3994. #endif /* !defined(NO_FILES) */
  3995. return;
  3996. #if !defined(NO_FILES)
  3997. /* Reset all outputs */
  3998. interpret_cleanup:
  3999. memset(filep, 0, sizeof(*filep));
  4000. *filename = 0;
  4001. *is_found = 0;
  4002. *is_script_resource = 0;
  4003. *is_websocket_request = 0;
  4004. *is_put_or_delete_request = 0;
  4005. #endif /* !defined(NO_FILES) */
  4006. }
  4007. /* Check whether full request is buffered. Return:
  4008. * -1 if request is malformed
  4009. * 0 if request is not yet fully buffered
  4010. * >0 actual request length, including last \r\n\r\n */
  4011. static int
  4012. get_request_len(const char *buf, int buflen)
  4013. {
  4014. const char *s, *e;
  4015. int len = 0;
  4016. for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
  4017. /* Control characters are not allowed but >=128 is. */
  4018. if (!isprint(*(const unsigned char *)s) && *s != '\r' && *s != '\n'
  4019. && *(const unsigned char *)s < 128) {
  4020. len = -1;
  4021. break; /* [i_a] abort scan as soon as one malformed character is
  4022. * found; */
  4023. /* don't let subsequent \r\n\r\n win us over anyhow */
  4024. } else if (s[0] == '\n' && s[1] == '\n') {
  4025. len = (int)(s - buf) + 2;
  4026. } else if (s[0] == '\n' && &s[1] < e && s[1] == '\r' && s[2] == '\n') {
  4027. len = (int)(s - buf) + 3;
  4028. }
  4029. return len;
  4030. }
  4031. /* Convert month to the month number. Return -1 on error, or month number */
  4032. static int
  4033. get_month_index(const char *s)
  4034. {
  4035. size_t i;
  4036. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  4037. if (!strcmp(s, month_names[i])) {
  4038. return (int)i;
  4039. }
  4040. }
  4041. return -1;
  4042. }
  4043. /* Parse UTC date-time string, and return the corresponding time_t value. */
  4044. static time_t
  4045. parse_date_string(const char *datetime)
  4046. {
  4047. char month_str[32] = {0};
  4048. int second, minute, hour, day, month, year;
  4049. time_t result = (time_t)0;
  4050. struct tm tm;
  4051. if ((sscanf(datetime,
  4052. "%d/%3s/%d %d:%d:%d",
  4053. &day,
  4054. month_str,
  4055. &year,
  4056. &hour,
  4057. &minute,
  4058. &second) == 6) || (sscanf(datetime,
  4059. "%d %3s %d %d:%d:%d",
  4060. &day,
  4061. month_str,
  4062. &year,
  4063. &hour,
  4064. &minute,
  4065. &second) == 6)
  4066. || (sscanf(datetime,
  4067. "%*3s, %d %3s %d %d:%d:%d",
  4068. &day,
  4069. month_str,
  4070. &year,
  4071. &hour,
  4072. &minute,
  4073. &second) == 6) || (sscanf(datetime,
  4074. "%d-%3s-%d %d:%d:%d",
  4075. &day,
  4076. month_str,
  4077. &year,
  4078. &hour,
  4079. &minute,
  4080. &second) == 6)) {
  4081. month = get_month_index(month_str);
  4082. if ((month >= 0) && (year >= 1970)) {
  4083. memset(&tm, 0, sizeof(tm));
  4084. tm.tm_year = year - 1900;
  4085. tm.tm_mon = month;
  4086. tm.tm_mday = day;
  4087. tm.tm_hour = hour;
  4088. tm.tm_min = minute;
  4089. tm.tm_sec = second;
  4090. result = timegm(&tm);
  4091. }
  4092. }
  4093. return result;
  4094. }
  4095. /* Protect against directory disclosure attack by removing '..',
  4096. * excessive '/' and '\' characters */
  4097. static void
  4098. remove_double_dots_and_double_slashes(char *s)
  4099. {
  4100. char *p = s;
  4101. while (*s != '\0') {
  4102. *p++ = *s++;
  4103. if (s[-1] == '/' || s[-1] == '\\') {
  4104. /* Skip all following slashes, backslashes and double-dots */
  4105. while (s[0] != '\0') {
  4106. if (s[0] == '/' || s[0] == '\\') {
  4107. s++;
  4108. } else if (s[0] == '.' && s[1] == '.') {
  4109. s += 2;
  4110. } else {
  4111. break;
  4112. }
  4113. }
  4114. }
  4115. }
  4116. *p = '\0';
  4117. }
  4118. static const struct {
  4119. const char *extension;
  4120. size_t ext_len;
  4121. const char *mime_type;
  4122. } builtin_mime_types[] = {
  4123. /* IANA registered MIME types (http://www.iana.org/assignments/media-types)
  4124. * application types */
  4125. {".doc", 4, "application/msword"},
  4126. {".eps", 4, "application/postscript"},
  4127. {".exe", 4, "application/octet-stream"},
  4128. {".js", 3, "application/javascript"},
  4129. {".json", 5, "application/json"},
  4130. {".pdf", 4, "application/pdf"},
  4131. {".ps", 3, "application/postscript"},
  4132. {".rtf", 4, "application/rtf"},
  4133. {".xhtml", 6, "application/xhtml+xml"},
  4134. {".xsl", 4, "application/xml"},
  4135. {".xslt", 5, "application/xml"},
  4136. /* fonts */
  4137. {".ttf", 4, "application/font-sfnt"},
  4138. {".cff", 4, "application/font-sfnt"},
  4139. {".otf", 4, "application/font-sfnt"},
  4140. {".aat", 4, "application/font-sfnt"},
  4141. {".sil", 4, "application/font-sfnt"},
  4142. {".pfr", 4, "application/font-tdpfr"},
  4143. {".woff", 5, "application/font-woff"},
  4144. /* audio */
  4145. {".mp3", 4, "audio/mpeg"},
  4146. {".oga", 4, "audio/ogg"},
  4147. {".ogg", 4, "audio/ogg"},
  4148. /* image */
  4149. {".gif", 4, "image/gif"},
  4150. {".ief", 4, "image/ief"},
  4151. {".jpeg", 5, "image/jpeg"},
  4152. {".jpg", 4, "image/jpeg"},
  4153. {".jpm", 4, "image/jpm"},
  4154. {".jpx", 4, "image/jpx"},
  4155. {".png", 4, "image/png"},
  4156. {".svg", 4, "image/svg+xml"},
  4157. {".tif", 4, "image/tiff"},
  4158. {".tiff", 5, "image/tiff"},
  4159. /* model */
  4160. {".wrl", 4, "model/vrml"},
  4161. /* text */
  4162. {".css", 4, "text/css"},
  4163. {".csv", 4, "text/csv"},
  4164. {".htm", 4, "text/html"},
  4165. {".html", 5, "text/html"},
  4166. {".sgm", 4, "text/sgml"},
  4167. {".shtm", 5, "text/html"},
  4168. {".shtml", 6, "text/html"},
  4169. {".txt", 4, "text/plain"},
  4170. {".xml", 4, "text/xml"},
  4171. /* video */
  4172. {".mov", 4, "video/quicktime"},
  4173. {".mp4", 4, "video/mp4"},
  4174. {".mpeg", 5, "video/mpeg"},
  4175. {".mpg", 4, "video/mpeg"},
  4176. {".ogv", 4, "video/ogg"},
  4177. {".qt", 3, "video/quicktime"},
  4178. /* not registered types
  4179. * (http://reference.sitepoint.com/html/mime-types-full,
  4180. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  4181. {".arj", 4, "application/x-arj-compressed"},
  4182. {".gz", 3, "application/x-gunzip"},
  4183. {".rar", 4, "application/x-arj-compressed"},
  4184. {".swf", 4, "application/x-shockwave-flash"},
  4185. {".tar", 4, "application/x-tar"},
  4186. {".tgz", 4, "application/x-tar-gz"},
  4187. {".torrent", 8, "application/x-bittorrent"},
  4188. {".ppt", 4, "application/x-mspowerpoint"},
  4189. {".xls", 4, "application/x-msexcel"},
  4190. {".zip", 4, "application/x-zip-compressed"},
  4191. {".aac",
  4192. 4,
  4193. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  4194. {".aif", 4, "audio/x-aif"},
  4195. {".m3u", 4, "audio/x-mpegurl"},
  4196. {".mid", 4, "audio/x-midi"},
  4197. {".ra", 3, "audio/x-pn-realaudio"},
  4198. {".ram", 4, "audio/x-pn-realaudio"},
  4199. {".wav", 4, "audio/x-wav"},
  4200. {".bmp", 4, "image/bmp"},
  4201. {".ico", 4, "image/x-icon"},
  4202. {".pct", 4, "image/x-pct"},
  4203. {".pict", 5, "image/pict"},
  4204. {".rgb", 4, "image/x-rgb"},
  4205. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  4206. {".asf", 4, "video/x-ms-asf"},
  4207. {".avi", 4, "video/x-msvideo"},
  4208. {".m4v", 4, "video/x-m4v"},
  4209. {NULL, 0, NULL}};
  4210. const char *
  4211. mg_get_builtin_mime_type(const char *path)
  4212. {
  4213. const char *ext;
  4214. size_t i, path_len;
  4215. path_len = strlen(path);
  4216. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  4217. ext = path + (path_len - builtin_mime_types[i].ext_len);
  4218. if (path_len > builtin_mime_types[i].ext_len
  4219. && mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {
  4220. return builtin_mime_types[i].mime_type;
  4221. }
  4222. }
  4223. return "text/plain";
  4224. }
  4225. /* Look at the "path" extension and figure what mime type it has.
  4226. * Store mime type in the vector. */
  4227. static void
  4228. get_mime_type(struct mg_context *ctx, const char *path, struct vec *vec)
  4229. {
  4230. struct vec ext_vec, mime_vec;
  4231. const char *list, *ext;
  4232. size_t path_len;
  4233. path_len = strlen(path);
  4234. if (ctx == NULL || vec == NULL) {
  4235. return;
  4236. }
  4237. /* Scan user-defined mime types first, in case user wants to
  4238. * override default mime types. */
  4239. list = ctx->config[EXTRA_MIME_TYPES];
  4240. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  4241. /* ext now points to the path suffix */
  4242. ext = path + path_len - ext_vec.len;
  4243. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  4244. *vec = mime_vec;
  4245. return;
  4246. }
  4247. }
  4248. vec->ptr = mg_get_builtin_mime_type(path);
  4249. vec->len = strlen(vec->ptr);
  4250. }
  4251. /* Stringify binary data. Output buffer must be twice as big as input,
  4252. * because each byte takes 2 bytes in string representation */
  4253. static void
  4254. bin2str(char *to, const unsigned char *p, size_t len)
  4255. {
  4256. static const char *hex = "0123456789abcdef";
  4257. for (; len--; p++) {
  4258. *to++ = hex[p[0] >> 4];
  4259. *to++ = hex[p[0] & 0x0f];
  4260. }
  4261. *to = '\0';
  4262. }
  4263. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes. */
  4264. char *
  4265. mg_md5(char buf[33], ...)
  4266. {
  4267. md5_byte_t hash[16];
  4268. const char *p;
  4269. va_list ap;
  4270. md5_state_t ctx;
  4271. md5_init(&ctx);
  4272. va_start(ap, buf);
  4273. while ((p = va_arg(ap, const char *)) != NULL) {
  4274. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  4275. }
  4276. va_end(ap);
  4277. md5_finish(&ctx, hash);
  4278. bin2str(buf, hash, sizeof(hash));
  4279. return buf;
  4280. }
  4281. /* Check the user's password, return 1 if OK */
  4282. static int
  4283. check_password(const char *method,
  4284. const char *ha1,
  4285. const char *uri,
  4286. const char *nonce,
  4287. const char *nc,
  4288. const char *cnonce,
  4289. const char *qop,
  4290. const char *response)
  4291. {
  4292. char ha2[32 + 1], expected_response[32 + 1];
  4293. /* Some of the parameters may be NULL */
  4294. if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL
  4295. || qop == NULL
  4296. || response == NULL) {
  4297. return 0;
  4298. }
  4299. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  4300. if (strlen(response) != 32) {
  4301. return 0;
  4302. }
  4303. mg_md5(ha2, method, ":", uri, NULL);
  4304. mg_md5(expected_response,
  4305. ha1,
  4306. ":",
  4307. nonce,
  4308. ":",
  4309. nc,
  4310. ":",
  4311. cnonce,
  4312. ":",
  4313. qop,
  4314. ":",
  4315. ha2,
  4316. NULL);
  4317. return mg_strcasecmp(response, expected_response) == 0;
  4318. }
  4319. /* Use the global passwords file, if specified by auth_gpass option,
  4320. * or search for .htpasswd in the requested directory. */
  4321. static void
  4322. open_auth_file(struct mg_connection *conn, const char *path, struct file *filep)
  4323. {
  4324. if (conn != NULL && conn->ctx != NULL) {
  4325. char name[PATH_MAX];
  4326. const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
  4327. struct file file = STRUCT_FILE_INITIALIZER;
  4328. int truncated;
  4329. if (gpass != NULL) {
  4330. /* Use global passwords file */
  4331. if (!mg_fopen(conn, gpass, "r", filep)) {
  4332. #ifdef DEBUG
  4333. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  4334. #endif
  4335. }
  4336. /* Important: using local struct file to test path for is_directory
  4337. * flag. If filep is used, mg_stat() makes it appear as if auth file
  4338. * was opened. */
  4339. } else if (mg_stat(conn, path, &file) && file.is_directory) {
  4340. mg_snprintf(conn,
  4341. &truncated,
  4342. name,
  4343. sizeof(name),
  4344. "%s/%s",
  4345. path,
  4346. PASSWORDS_FILE_NAME);
  4347. if (truncated || !mg_fopen(conn, name, "r", filep)) {
  4348. #ifdef DEBUG
  4349. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  4350. #endif
  4351. }
  4352. } else {
  4353. /* Try to find .htpasswd in requested directory. */
  4354. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  4355. if (e[0] == '/') {
  4356. break;
  4357. }
  4358. }
  4359. mg_snprintf(conn,
  4360. &truncated,
  4361. name,
  4362. sizeof(name),
  4363. "%.*s%s",
  4364. (int)(e - p),
  4365. p,
  4366. PASSWORDS_FILE_NAME);
  4367. if (truncated || !mg_fopen(conn, name, "r", filep)) {
  4368. #ifdef DEBUG
  4369. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  4370. #endif
  4371. }
  4372. }
  4373. }
  4374. }
  4375. /* Parsed Authorization header */
  4376. struct ah {
  4377. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  4378. };
  4379. /* Return 1 on success. Always initializes the ah structure. */
  4380. static int
  4381. parse_auth_header(struct mg_connection *conn,
  4382. char *buf,
  4383. size_t buf_size,
  4384. struct ah *ah)
  4385. {
  4386. char *name, *value, *s;
  4387. const char *auth_header;
  4388. uint64_t nonce;
  4389. if (!ah || !conn) {
  4390. return 0;
  4391. }
  4392. (void)memset(ah, 0, sizeof(*ah));
  4393. if ((auth_header = mg_get_header(conn, "Authorization")) == NULL
  4394. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  4395. return 0;
  4396. }
  4397. /* Make modifiable copy of the auth header */
  4398. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  4399. s = buf;
  4400. /* Parse authorization header */
  4401. for (;;) {
  4402. /* Gobble initial spaces */
  4403. while (isspace(*(unsigned char *)s)) {
  4404. s++;
  4405. }
  4406. name = skip_quoted(&s, "=", " ", 0);
  4407. /* Value is either quote-delimited, or ends at first comma or space. */
  4408. if (s[0] == '\"') {
  4409. s++;
  4410. value = skip_quoted(&s, "\"", " ", '\\');
  4411. if (s[0] == ',') {
  4412. s++;
  4413. }
  4414. } else {
  4415. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  4416. * spaces */
  4417. }
  4418. if (*name == '\0') {
  4419. break;
  4420. }
  4421. if (!strcmp(name, "username")) {
  4422. ah->user = value;
  4423. } else if (!strcmp(name, "cnonce")) {
  4424. ah->cnonce = value;
  4425. } else if (!strcmp(name, "response")) {
  4426. ah->response = value;
  4427. } else if (!strcmp(name, "uri")) {
  4428. ah->uri = value;
  4429. } else if (!strcmp(name, "qop")) {
  4430. ah->qop = value;
  4431. } else if (!strcmp(name, "nc")) {
  4432. ah->nc = value;
  4433. } else if (!strcmp(name, "nonce")) {
  4434. ah->nonce = value;
  4435. }
  4436. }
  4437. #ifndef NO_NONCE_CHECK
  4438. /* Read the nonce from the response. */
  4439. if (ah->nonce == NULL) {
  4440. return 0;
  4441. }
  4442. s = NULL;
  4443. nonce = strtoull(ah->nonce, &s, 10);
  4444. if ((s == NULL) || (*s != 0)) {
  4445. return 0;
  4446. }
  4447. /* Convert the nonce from the client to a number. */
  4448. nonce ^= conn->ctx->auth_nonce_mask;
  4449. /* The converted number corresponds to the time the nounce has been
  4450. * created. This should not be earlier than the server start. */
  4451. /* Server side nonce check is valuable in all situations but one:
  4452. * if the server restarts frequently, but the client should not see
  4453. * that, so the server should accept nonces from previous starts. */
  4454. /* However, the reasonable default is to not accept a nonce from a
  4455. * previous start, so if anyone changed the access rights between
  4456. * two restarts, a new login is required. */
  4457. if (nonce < (uint64_t)conn->ctx->start_time) {
  4458. /* nonce is from a previous start of the server and no longer valid
  4459. * (replay attack?) */
  4460. return 0;
  4461. }
  4462. /* Check if the nonce is too high, so it has not (yet) been used by the
  4463. * server. */
  4464. if (nonce >= ((uint64_t)conn->ctx->start_time + conn->ctx->nonce_count)) {
  4465. return 0;
  4466. }
  4467. #endif
  4468. /* CGI needs it as REMOTE_USER */
  4469. if (ah->user != NULL) {
  4470. conn->request_info.remote_user = mg_strdup(ah->user);
  4471. } else {
  4472. return 0;
  4473. }
  4474. return 1;
  4475. }
  4476. static char *
  4477. mg_fgets(char *buf, size_t size, struct file *filep, char **p)
  4478. {
  4479. char *eof;
  4480. size_t len;
  4481. char *memend;
  4482. if (!filep) {
  4483. return NULL;
  4484. }
  4485. if (filep->membuf != NULL && *p != NULL) {
  4486. memend = (char *)&filep->membuf[filep->size];
  4487. /* Search for \n from p till the end of stream */
  4488. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  4489. if (eof != NULL) {
  4490. eof += 1; /* Include \n */
  4491. } else {
  4492. eof = memend; /* Copy remaining data */
  4493. }
  4494. len = (size_t)(eof - *p) > size - 1 ? size - 1 : (size_t)(eof - *p);
  4495. memcpy(buf, *p, len);
  4496. buf[len] = '\0';
  4497. *p += len;
  4498. return len ? eof : NULL;
  4499. } else if (filep->fp != NULL) {
  4500. return fgets(buf, (int)size, filep->fp);
  4501. } else {
  4502. return NULL;
  4503. }
  4504. }
  4505. struct read_auth_file_struct {
  4506. struct mg_connection *conn;
  4507. struct ah ah;
  4508. char *domain;
  4509. char buf[256 + 256 + 40];
  4510. char *f_user;
  4511. char *f_domain;
  4512. char *f_ha1;
  4513. };
  4514. static int
  4515. read_auth_file(struct file *filep, struct read_auth_file_struct *workdata)
  4516. {
  4517. char *p;
  4518. int is_authorized = 0;
  4519. struct file fp;
  4520. size_t l;
  4521. if (!filep || !workdata) {
  4522. return 0;
  4523. }
  4524. /* Loop over passwords file */
  4525. p = (char *)filep->membuf;
  4526. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  4527. l = strlen(workdata->buf);
  4528. while (l > 0) {
  4529. if (isspace(workdata->buf[l - 1])
  4530. || iscntrl(workdata->buf[l - 1])) {
  4531. l--;
  4532. workdata->buf[l] = 0;
  4533. } else
  4534. break;
  4535. }
  4536. if (l < 1) {
  4537. continue;
  4538. }
  4539. workdata->f_user = workdata->buf;
  4540. if (workdata->f_user[0] == ':') {
  4541. /* user names may not contain a ':' and may not be empty,
  4542. * so lines starting with ':' may be used for a special purpose */
  4543. if (workdata->f_user[1] == '#') {
  4544. /* :# is a comment */
  4545. continue;
  4546. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  4547. if (mg_fopen(workdata->conn, workdata->f_user + 9, "r", &fp)) {
  4548. is_authorized = read_auth_file(&fp, workdata);
  4549. mg_fclose(&fp);
  4550. } else {
  4551. mg_cry(workdata->conn,
  4552. "%s: cannot open authorization file: %s",
  4553. __func__,
  4554. workdata->buf);
  4555. }
  4556. continue;
  4557. }
  4558. /* everything is invalid for the moment (might change in the
  4559. * future) */
  4560. mg_cry(workdata->conn,
  4561. "%s: syntax error in authorization file: %s",
  4562. __func__,
  4563. workdata->buf);
  4564. continue;
  4565. }
  4566. workdata->f_domain = strchr(workdata->f_user, ':');
  4567. if (workdata->f_domain == NULL) {
  4568. mg_cry(workdata->conn,
  4569. "%s: syntax error in authorization file: %s",
  4570. __func__,
  4571. workdata->buf);
  4572. continue;
  4573. }
  4574. *(workdata->f_domain) = 0;
  4575. (workdata->f_domain)++;
  4576. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  4577. if (workdata->f_ha1 == NULL) {
  4578. mg_cry(workdata->conn,
  4579. "%s: syntax error in authorization file: %s",
  4580. __func__,
  4581. workdata->buf);
  4582. continue;
  4583. }
  4584. *(workdata->f_ha1) = 0;
  4585. (workdata->f_ha1)++;
  4586. if (!strcmp(workdata->ah.user, workdata->f_user)
  4587. && !strcmp(workdata->domain, workdata->f_domain)) {
  4588. return check_password(workdata->conn->request_info.request_method,
  4589. workdata->f_ha1,
  4590. workdata->ah.uri,
  4591. workdata->ah.nonce,
  4592. workdata->ah.nc,
  4593. workdata->ah.cnonce,
  4594. workdata->ah.qop,
  4595. workdata->ah.response);
  4596. }
  4597. }
  4598. return is_authorized;
  4599. }
  4600. /* Authorize against the opened passwords file. Return 1 if authorized. */
  4601. static int
  4602. authorize(struct mg_connection *conn, struct file *filep)
  4603. {
  4604. struct read_auth_file_struct workdata;
  4605. char buf[MG_BUF_LEN];
  4606. if (!conn || !conn->ctx) {
  4607. return 0;
  4608. }
  4609. memset(&workdata, 0, sizeof(workdata));
  4610. workdata.conn = conn;
  4611. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  4612. return 0;
  4613. }
  4614. workdata.domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  4615. return read_auth_file(filep, &workdata);
  4616. }
  4617. /* Return 1 if request is authorised, 0 otherwise. */
  4618. static int
  4619. check_authorization(struct mg_connection *conn, const char *path)
  4620. {
  4621. char fname[PATH_MAX];
  4622. struct vec uri_vec, filename_vec;
  4623. const char *list;
  4624. struct file file = STRUCT_FILE_INITIALIZER;
  4625. int authorized = 1, truncated;
  4626. if (!conn || !conn->ctx) {
  4627. return 0;
  4628. }
  4629. list = conn->ctx->config[PROTECT_URI];
  4630. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  4631. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  4632. mg_snprintf(conn,
  4633. &truncated,
  4634. fname,
  4635. sizeof(fname),
  4636. "%.*s",
  4637. (int)filename_vec.len,
  4638. filename_vec.ptr);
  4639. if (truncated || !mg_fopen(conn, fname, "r", &file)) {
  4640. mg_cry(conn,
  4641. "%s: cannot open %s: %s",
  4642. __func__,
  4643. fname,
  4644. strerror(errno));
  4645. }
  4646. break;
  4647. }
  4648. }
  4649. if (!is_file_opened(&file)) {
  4650. open_auth_file(conn, path, &file);
  4651. }
  4652. if (is_file_opened(&file)) {
  4653. authorized = authorize(conn, &file);
  4654. mg_fclose(&file);
  4655. }
  4656. return authorized;
  4657. }
  4658. static void
  4659. send_authorization_request(struct mg_connection *conn)
  4660. {
  4661. char date[64];
  4662. time_t curtime = time(NULL);
  4663. if (conn && conn->ctx) {
  4664. uint64_t nonce = (uint64_t)(conn->ctx->start_time);
  4665. (void)pthread_mutex_lock(&conn->ctx->nonce_mutex);
  4666. nonce += conn->ctx->nonce_count;
  4667. ++conn->ctx->nonce_count;
  4668. (void)pthread_mutex_unlock(&conn->ctx->nonce_mutex);
  4669. nonce ^= conn->ctx->auth_nonce_mask;
  4670. conn->status_code = 401;
  4671. conn->must_close = 1;
  4672. gmt_time_string(date, sizeof(date), &curtime);
  4673. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  4674. send_no_cache_header(conn);
  4675. mg_printf(conn,
  4676. "Date: %s\r\n"
  4677. "Connection: %s\r\n"
  4678. "Content-Length: 0\r\n"
  4679. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  4680. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  4681. date,
  4682. suggest_connection_header(conn),
  4683. conn->ctx->config[AUTHENTICATION_DOMAIN],
  4684. nonce);
  4685. }
  4686. }
  4687. #if !defined(NO_FILES)
  4688. static int
  4689. is_authorized_for_put(struct mg_connection *conn)
  4690. {
  4691. if (conn) {
  4692. struct file file = STRUCT_FILE_INITIALIZER;
  4693. const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
  4694. int ret = 0;
  4695. if (passfile != NULL && mg_fopen(conn, passfile, "r", &file)) {
  4696. ret = authorize(conn, &file);
  4697. mg_fclose(&file);
  4698. }
  4699. return ret;
  4700. }
  4701. return 0;
  4702. }
  4703. #endif
  4704. int
  4705. mg_modify_passwords_file(const char *fname,
  4706. const char *domain,
  4707. const char *user,
  4708. const char *pass)
  4709. {
  4710. int found, i;
  4711. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  4712. FILE *fp, *fp2;
  4713. found = 0;
  4714. fp = fp2 = NULL;
  4715. /* Regard empty password as no password - remove user record. */
  4716. if (pass != NULL && pass[0] == '\0') {
  4717. pass = NULL;
  4718. }
  4719. /* Other arguments must not be empty */
  4720. if (fname == NULL || domain == NULL || user == NULL) {
  4721. return 0;
  4722. }
  4723. /* Using the given file format, user name and domain must not contain ':'
  4724. */
  4725. if (strchr(user, ':') != NULL) {
  4726. return 0;
  4727. }
  4728. if (strchr(domain, ':') != NULL) {
  4729. return 0;
  4730. }
  4731. /* Do not allow control characters like newline in user name and domain.
  4732. * Do not allow excessively long names either. */
  4733. for (i = 0; i < 255 && user[i] != 0; i++) {
  4734. if (iscntrl(user[i])) {
  4735. return 0;
  4736. }
  4737. }
  4738. if (user[i]) {
  4739. return 0;
  4740. }
  4741. for (i = 0; i < 255 && domain[i] != 0; i++) {
  4742. if (iscntrl(domain[i])) {
  4743. return 0;
  4744. }
  4745. }
  4746. if (domain[i]) {
  4747. return 0;
  4748. }
  4749. /* The maximum length of the path to the password file is limited */
  4750. if ((strlen(fname) + 4) >= PATH_MAX) {
  4751. return 0;
  4752. }
  4753. /* Create a temporary file name. Length has been checked before. */
  4754. strcpy(tmp, fname);
  4755. strcat(tmp, ".tmp");
  4756. /* Create the file if does not exist */
  4757. /* Use of fopen here is OK, since fname is only ASCII */
  4758. if ((fp = fopen(fname, "a+")) != NULL) {
  4759. (void)fclose(fp);
  4760. }
  4761. /* Open the given file and temporary file */
  4762. if ((fp = fopen(fname, "r")) == NULL) {
  4763. return 0;
  4764. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  4765. fclose(fp);
  4766. return 0;
  4767. }
  4768. /* Copy the stuff to temporary file */
  4769. while (fgets(line, sizeof(line), fp) != NULL) {
  4770. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  4771. continue;
  4772. }
  4773. u[255] = 0;
  4774. d[255] = 0;
  4775. if (!strcmp(u, user) && !strcmp(d, domain)) {
  4776. found++;
  4777. if (pass != NULL) {
  4778. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  4779. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  4780. }
  4781. } else {
  4782. fprintf(fp2, "%s", line);
  4783. }
  4784. }
  4785. /* If new user, just add it */
  4786. if (!found && pass != NULL) {
  4787. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  4788. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  4789. }
  4790. /* Close files */
  4791. fclose(fp);
  4792. fclose(fp2);
  4793. /* Put the temp file in place of real file */
  4794. IGNORE_UNUSED_RESULT(remove(fname));
  4795. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  4796. return 1;
  4797. }
  4798. static int
  4799. is_valid_port(unsigned long port)
  4800. {
  4801. return port < 0xffff;
  4802. }
  4803. static int
  4804. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  4805. {
  4806. struct addrinfo hints, *res, *ressave;
  4807. int ret = 0;
  4808. memset(&hints, 0, sizeof(struct addrinfo));
  4809. hints.ai_family = af;
  4810. if (getaddrinfo(src, NULL, &hints, &res) != 0) {
  4811. /* bad src string or bad address family */
  4812. return 0;
  4813. }
  4814. ressave = res;
  4815. while (res) {
  4816. if (dstlen >= res->ai_addrlen) {
  4817. memcpy(dst, res->ai_addr, res->ai_addrlen);
  4818. ret = 1;
  4819. }
  4820. res = res->ai_next;
  4821. }
  4822. freeaddrinfo(ressave);
  4823. return ret;
  4824. }
  4825. static int
  4826. connect_socket(struct mg_context *ctx /* may be NULL */,
  4827. const char *host,
  4828. int port,
  4829. int use_ssl,
  4830. char *ebuf,
  4831. size_t ebuf_len,
  4832. SOCKET *sock /* output: socket, must not be NULL */,
  4833. union usa *sa /* output: socket address, must not be NULL */
  4834. )
  4835. {
  4836. int ip_ver = 0;
  4837. *sock = INVALID_SOCKET;
  4838. memset(sa, 0, sizeof(*sa));
  4839. if (ebuf_len > 0) {
  4840. *ebuf = 0;
  4841. }
  4842. if (host == NULL) {
  4843. mg_snprintf(NULL,
  4844. NULL, /* No truncation check for ebuf */
  4845. ebuf,
  4846. ebuf_len,
  4847. "%s",
  4848. "NULL host");
  4849. return 0;
  4850. }
  4851. if (port < 0 || !is_valid_port((unsigned)port)) {
  4852. mg_snprintf(NULL,
  4853. NULL, /* No truncation check for ebuf */
  4854. ebuf,
  4855. ebuf_len,
  4856. "%s",
  4857. "invalid port");
  4858. return 0;
  4859. }
  4860. if (use_ssl && (SSLv23_client_method == NULL)) {
  4861. mg_snprintf(NULL,
  4862. NULL, /* No truncation check for ebuf */
  4863. ebuf,
  4864. ebuf_len,
  4865. "%s",
  4866. "SSL is not initialized");
  4867. return 0;
  4868. }
  4869. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  4870. sa->sin.sin_port = htons((uint16_t)port);
  4871. ip_ver = 4;
  4872. #ifdef USE_IPV6
  4873. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  4874. sa->sin6.sin6_port = htons((uint16_t)port);
  4875. ip_ver = 6;
  4876. } else if (host[0] == '[') {
  4877. /* While getaddrinfo on Windows will work with [::1],
  4878. * getaddrinfo on Linux only works with ::1 (without []). */
  4879. size_t l = strlen(host + 1);
  4880. char *h = l > 1 ? mg_strdup(host + 1) : NULL;
  4881. if (h) {
  4882. h[l - 1] = 0;
  4883. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  4884. sa->sin6.sin6_port = htons((uint16_t)port);
  4885. ip_ver = 6;
  4886. }
  4887. mg_free(h);
  4888. }
  4889. #endif
  4890. }
  4891. if (ip_ver == 0) {
  4892. mg_snprintf(NULL,
  4893. NULL, /* No truncation check for ebuf */
  4894. ebuf,
  4895. ebuf_len,
  4896. "%s",
  4897. "host not found");
  4898. return 0;
  4899. }
  4900. if (ip_ver == 4) {
  4901. *sock = socket(PF_INET, SOCK_STREAM, 0);
  4902. }
  4903. #ifdef USE_IPV6
  4904. else if (ip_ver == 6) {
  4905. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  4906. }
  4907. #endif
  4908. if (*sock == INVALID_SOCKET) {
  4909. mg_snprintf(NULL,
  4910. NULL, /* No truncation check for ebuf */
  4911. ebuf,
  4912. ebuf_len,
  4913. "socket(): %s",
  4914. strerror(ERRNO));
  4915. return 0;
  4916. }
  4917. set_close_on_exec(*sock, fc(ctx));
  4918. if ((ip_ver == 4)
  4919. && (connect(*sock, (struct sockaddr *)&sa->sin, sizeof(sa->sin))
  4920. == 0)) {
  4921. /* connected with IPv4 */
  4922. return 1;
  4923. }
  4924. #ifdef USE_IPV6
  4925. if ((ip_ver == 6)
  4926. && (connect(*sock, (struct sockaddr *)&sa->sin6, sizeof(sa->sin6))
  4927. == 0)) {
  4928. /* connected with IPv6 */
  4929. return 1;
  4930. }
  4931. #endif
  4932. /* Not connected */
  4933. mg_snprintf(NULL,
  4934. NULL, /* No truncation check for ebuf */
  4935. ebuf,
  4936. ebuf_len,
  4937. "connect(%s:%d): %s",
  4938. host,
  4939. port,
  4940. strerror(ERRNO));
  4941. closesocket(*sock);
  4942. *sock = INVALID_SOCKET;
  4943. return 0;
  4944. }
  4945. int
  4946. mg_url_encode(const char *src, char *dst, size_t dst_len)
  4947. {
  4948. static const char *dont_escape = "._-$,;~()";
  4949. static const char *hex = "0123456789abcdef";
  4950. char *pos = dst;
  4951. const char *end = dst + dst_len - 1;
  4952. for (; *src != '\0' && pos < end; src++, pos++) {
  4953. if (isalnum(*(const unsigned char *)src)
  4954. || strchr(dont_escape, *(const unsigned char *)src) != NULL) {
  4955. *pos = *src;
  4956. } else if (pos + 2 < end) {
  4957. pos[0] = '%';
  4958. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  4959. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  4960. pos += 2;
  4961. } else {
  4962. break;
  4963. }
  4964. }
  4965. *pos = '\0';
  4966. return (*src == '\0') ? (int)(pos - dst) : -1;
  4967. }
  4968. static void
  4969. print_dir_entry(struct de *de)
  4970. {
  4971. char size[64], mod[64], href[PATH_MAX];
  4972. struct tm *tm;
  4973. if (de->file.is_directory) {
  4974. mg_snprintf(de->conn,
  4975. NULL, /* Buffer is big enough */
  4976. size,
  4977. sizeof(size),
  4978. "%s",
  4979. "[DIRECTORY]");
  4980. } else {
  4981. /* We use (signed) cast below because MSVC 6 compiler cannot
  4982. * convert unsigned __int64 to double. Sigh. */
  4983. if (de->file.size < 1024) {
  4984. mg_snprintf(de->conn,
  4985. NULL, /* Buffer is big enough */
  4986. size,
  4987. sizeof(size),
  4988. "%d",
  4989. (int)de->file.size);
  4990. } else if (de->file.size < 0x100000) {
  4991. mg_snprintf(de->conn,
  4992. NULL, /* Buffer is big enough */
  4993. size,
  4994. sizeof(size),
  4995. "%.1fk",
  4996. (double)de->file.size / 1024.0);
  4997. } else if (de->file.size < 0x40000000) {
  4998. mg_snprintf(de->conn,
  4999. NULL, /* Buffer is big enough */
  5000. size,
  5001. sizeof(size),
  5002. "%.1fM",
  5003. (double)de->file.size / 1048576);
  5004. } else {
  5005. mg_snprintf(de->conn,
  5006. NULL, /* Buffer is big enough */
  5007. size,
  5008. sizeof(size),
  5009. "%.1fG",
  5010. (double)de->file.size / 1073741824);
  5011. }
  5012. }
  5013. /* Note: mg_snprintf will not cause a buffer overflow above.
  5014. * So, string truncation checks are not required here. */
  5015. tm = localtime(&de->file.last_modified);
  5016. if (tm != NULL) {
  5017. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  5018. } else {
  5019. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  5020. mod[sizeof(mod) - 1] = '\0';
  5021. }
  5022. mg_url_encode(de->file_name, href, sizeof(href));
  5023. de->conn->num_bytes_sent +=
  5024. mg_printf(de->conn,
  5025. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  5026. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  5027. de->conn->request_info.local_uri,
  5028. href,
  5029. de->file.is_directory ? "/" : "",
  5030. de->file_name,
  5031. de->file.is_directory ? "/" : "",
  5032. mod,
  5033. size);
  5034. }
  5035. /* This function is called from send_directory() and used for
  5036. * sorting directory entries by size, or name, or modification time.
  5037. * On windows, __cdecl specification is needed in case if project is built
  5038. * with __stdcall convention. qsort always requires __cdels callback. */
  5039. static int WINCDECL
  5040. compare_dir_entries(const void *p1, const void *p2)
  5041. {
  5042. if (p1 && p2) {
  5043. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  5044. const char *query_string = a->conn->request_info.query_string;
  5045. int cmp_result = 0;
  5046. if (query_string == NULL) {
  5047. query_string = "na";
  5048. }
  5049. if (a->file.is_directory && !b->file.is_directory) {
  5050. return -1; /* Always put directories on top */
  5051. } else if (!a->file.is_directory && b->file.is_directory) {
  5052. return 1; /* Always put directories on top */
  5053. } else if (*query_string == 'n') {
  5054. cmp_result = strcmp(a->file_name, b->file_name);
  5055. } else if (*query_string == 's') {
  5056. cmp_result = a->file.size == b->file.size
  5057. ? 0
  5058. : a->file.size > b->file.size ? 1 : -1;
  5059. } else if (*query_string == 'd') {
  5060. cmp_result =
  5061. (a->file.last_modified == b->file.last_modified)
  5062. ? 0
  5063. : ((a->file.last_modified > b->file.last_modified) ? 1
  5064. : -1);
  5065. }
  5066. return query_string[1] == 'd' ? -cmp_result : cmp_result;
  5067. }
  5068. return 0;
  5069. }
  5070. static int
  5071. must_hide_file(struct mg_connection *conn, const char *path)
  5072. {
  5073. if (conn && conn->ctx) {
  5074. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  5075. const char *pattern = conn->ctx->config[HIDE_FILES];
  5076. return match_prefix(pw_pattern, strlen(pw_pattern), path) > 0
  5077. || (pattern != NULL
  5078. && match_prefix(pattern, strlen(pattern), path) > 0);
  5079. }
  5080. return 0;
  5081. }
  5082. static int
  5083. scan_directory(struct mg_connection *conn,
  5084. const char *dir,
  5085. void *data,
  5086. void (*cb)(struct de *, void *))
  5087. {
  5088. char path[PATH_MAX];
  5089. struct dirent *dp;
  5090. DIR *dirp;
  5091. struct de de;
  5092. int truncated;
  5093. if ((dirp = opendir(dir)) == NULL) {
  5094. return 0;
  5095. } else {
  5096. de.conn = conn;
  5097. while ((dp = readdir(dirp)) != NULL) {
  5098. /* Do not show current dir and hidden files */
  5099. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  5100. || must_hide_file(conn, dp->d_name)) {
  5101. continue;
  5102. }
  5103. mg_snprintf(
  5104. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  5105. /* If we don't memset stat structure to zero, mtime will have
  5106. * garbage and strftime() will segfault later on in
  5107. * print_dir_entry(). memset is required only if mg_stat()
  5108. * fails. For more details, see
  5109. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  5110. memset(&de.file, 0, sizeof(de.file));
  5111. if (truncated) {
  5112. /* If the path is not complete, skip processing. */
  5113. continue;
  5114. }
  5115. if (!mg_stat(conn, path, &de.file)) {
  5116. mg_cry(conn,
  5117. "%s: mg_stat(%s) failed: %s",
  5118. __func__,
  5119. path,
  5120. strerror(ERRNO));
  5121. }
  5122. de.file_name = dp->d_name;
  5123. cb(&de, data);
  5124. }
  5125. (void)closedir(dirp);
  5126. }
  5127. return 1;
  5128. }
  5129. #if !defined(NO_FILES)
  5130. static int
  5131. remove_directory(struct mg_connection *conn, const char *dir)
  5132. {
  5133. char path[PATH_MAX];
  5134. struct dirent *dp;
  5135. DIR *dirp;
  5136. struct de de;
  5137. int truncated;
  5138. int ok = 1;
  5139. if ((dirp = opendir(dir)) == NULL) {
  5140. return 0;
  5141. } else {
  5142. de.conn = conn;
  5143. while ((dp = readdir(dirp)) != NULL) {
  5144. /* Do not show current dir (but show hidden files as they will
  5145. * also be removed) */
  5146. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  5147. continue;
  5148. }
  5149. mg_snprintf(
  5150. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  5151. /* If we don't memset stat structure to zero, mtime will have
  5152. * garbage and strftime() will segfault later on in
  5153. * print_dir_entry(). memset is required only if mg_stat()
  5154. * fails. For more details, see
  5155. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  5156. memset(&de.file, 0, sizeof(de.file));
  5157. if (truncated) {
  5158. /* Do not delete anything shorter */
  5159. ok = 0;
  5160. continue;
  5161. }
  5162. if (!mg_stat(conn, path, &de.file)) {
  5163. mg_cry(conn,
  5164. "%s: mg_stat(%s) failed: %s",
  5165. __func__,
  5166. path,
  5167. strerror(ERRNO));
  5168. ok = 0;
  5169. }
  5170. if (de.file.membuf == NULL) {
  5171. /* file is not in memory */
  5172. if (de.file.is_directory) {
  5173. if (remove_directory(conn, path) == 0) {
  5174. ok = 0;
  5175. }
  5176. } else {
  5177. if (mg_remove(path) == 0) {
  5178. ok = 0;
  5179. }
  5180. }
  5181. } else {
  5182. /* file is in memory. It can not be deleted. */
  5183. ok = 0;
  5184. }
  5185. }
  5186. (void)closedir(dirp);
  5187. IGNORE_UNUSED_RESULT(rmdir(dir));
  5188. }
  5189. return ok;
  5190. }
  5191. #endif
  5192. struct dir_scan_data {
  5193. struct de *entries;
  5194. unsigned int num_entries;
  5195. unsigned int arr_size;
  5196. };
  5197. /* Behaves like realloc(), but frees original pointer on failure */
  5198. static void *
  5199. realloc2(void *ptr, size_t size)
  5200. {
  5201. void *new_ptr = mg_realloc(ptr, size);
  5202. if (new_ptr == NULL) {
  5203. mg_free(ptr);
  5204. }
  5205. return new_ptr;
  5206. }
  5207. static void
  5208. dir_scan_callback(struct de *de, void *data)
  5209. {
  5210. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  5211. if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {
  5212. dsd->arr_size *= 2;
  5213. dsd->entries =
  5214. (struct de *)realloc2(dsd->entries,
  5215. dsd->arr_size * sizeof(dsd->entries[0]));
  5216. }
  5217. if (dsd->entries == NULL) {
  5218. /* TODO(lsm, low): propagate an error to the caller */
  5219. dsd->num_entries = 0;
  5220. } else {
  5221. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  5222. dsd->entries[dsd->num_entries].file = de->file;
  5223. dsd->entries[dsd->num_entries].conn = de->conn;
  5224. dsd->num_entries++;
  5225. }
  5226. }
  5227. static void
  5228. handle_directory_request(struct mg_connection *conn, const char *dir)
  5229. {
  5230. unsigned int i;
  5231. int sort_direction;
  5232. struct dir_scan_data data = {NULL, 0, 128};
  5233. char date[64];
  5234. time_t curtime = time(NULL);
  5235. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  5236. send_http_error(conn,
  5237. 500,
  5238. "Error: Cannot open directory\nopendir(%s): %s",
  5239. dir,
  5240. strerror(ERRNO));
  5241. return;
  5242. }
  5243. gmt_time_string(date, sizeof(date), &curtime);
  5244. if (!conn) {
  5245. return;
  5246. }
  5247. sort_direction = conn->request_info.query_string != NULL
  5248. && conn->request_info.query_string[1] == 'd'
  5249. ? 'a'
  5250. : 'd';
  5251. conn->must_close = 1;
  5252. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  5253. send_static_cache_header(conn);
  5254. mg_printf(conn,
  5255. "Date: %s\r\n"
  5256. "Connection: close\r\n"
  5257. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  5258. date);
  5259. conn->num_bytes_sent +=
  5260. mg_printf(conn,
  5261. "<html><head><title>Index of %s</title>"
  5262. "<style>th {text-align: left;}</style></head>"
  5263. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  5264. "<tr><th><a href=\"?n%c\">Name</a></th>"
  5265. "<th><a href=\"?d%c\">Modified</a></th>"
  5266. "<th><a href=\"?s%c\">Size</a></th></tr>"
  5267. "<tr><td colspan=\"3\"><hr></td></tr>",
  5268. conn->request_info.local_uri,
  5269. conn->request_info.local_uri,
  5270. sort_direction,
  5271. sort_direction,
  5272. sort_direction);
  5273. /* Print first entry - link to a parent directory */
  5274. conn->num_bytes_sent +=
  5275. mg_printf(conn,
  5276. "<tr><td><a href=\"%s%s\">%s</a></td>"
  5277. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  5278. conn->request_info.local_uri,
  5279. "..",
  5280. "Parent directory",
  5281. "-",
  5282. "-");
  5283. /* Sort and print directory entries */
  5284. if (data.entries != NULL) {
  5285. qsort(data.entries,
  5286. (size_t)data.num_entries,
  5287. sizeof(data.entries[0]),
  5288. compare_dir_entries);
  5289. for (i = 0; i < data.num_entries; i++) {
  5290. print_dir_entry(&data.entries[i]);
  5291. mg_free(data.entries[i].file_name);
  5292. }
  5293. mg_free(data.entries);
  5294. }
  5295. conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");
  5296. conn->status_code = 200;
  5297. }
  5298. /* Send len bytes from the opened file to the client. */
  5299. static void
  5300. send_file_data(struct mg_connection *conn,
  5301. struct file *filep,
  5302. int64_t offset,
  5303. int64_t len)
  5304. {
  5305. char buf[MG_BUF_LEN];
  5306. int to_read, num_read, num_written;
  5307. int64_t size;
  5308. if (!filep || !conn) {
  5309. return;
  5310. }
  5311. /* Sanity check the offset */
  5312. size = filep->size > INT64_MAX ? INT64_MAX : (int64_t)(filep->size);
  5313. offset = offset < 0 ? 0 : offset > size ? size : offset;
  5314. if (len > 0 && filep->membuf != NULL && size > 0) {
  5315. /* file stored in memory */
  5316. if (len > size - offset) {
  5317. len = size - offset;
  5318. }
  5319. mg_write(conn, filep->membuf + offset, (size_t)len);
  5320. } else if (len > 0 && filep->fp != NULL) {
  5321. /* file stored on disk */
  5322. #if defined(__linux__)
  5323. /* sendfile is only available for Linux */
  5324. if (conn->throttle == 0 && conn->ssl == 0) {
  5325. off_t sf_offs = (off_t)offset;
  5326. ssize_t sf_sent;
  5327. int sf_file = fileno(filep->fp);
  5328. int loop_cnt = 0;
  5329. do {
  5330. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  5331. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  5332. size_t sf_tosend =
  5333. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  5334. sf_sent =
  5335. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  5336. if (sf_sent > 0) {
  5337. conn->num_bytes_sent += sf_sent;
  5338. len -= sf_sent;
  5339. offset += sf_sent;
  5340. } else if (loop_cnt == 0) {
  5341. /* This file can not be sent using sendfile.
  5342. * This might be the case for pseudo-files in the
  5343. * /sys/ and /proc/ file system.
  5344. * Use the regular user mode copy code instead. */
  5345. break;
  5346. } else if (sf_sent == 0) {
  5347. /* No error, but 0 bytes sent. May be EOF? */
  5348. return;
  5349. }
  5350. loop_cnt++;
  5351. } while ((len > 0) && (sf_sent >= 0));
  5352. if (sf_sent > 0) {
  5353. return; /* OK */
  5354. }
  5355. /* sf_sent<0 means error, thus fall back to the classic way */
  5356. /* This is always the case, if sf_file is not a "normal" file,
  5357. * e.g., for sending data from the output of a CGI process. */
  5358. offset = (int64_t)sf_offs;
  5359. }
  5360. #endif
  5361. if ((offset > 0) && (fseeko(filep->fp, offset, SEEK_SET) != 0)) {
  5362. mg_cry(conn, "%s: fseeko() failed: %s", __func__, strerror(ERRNO));
  5363. send_http_error(
  5364. conn,
  5365. 500,
  5366. "%s",
  5367. "Error: Unable to access file at requested position.");
  5368. } else {
  5369. while (len > 0) {
  5370. /* Calculate how much to read from the file in the buffer */
  5371. to_read = sizeof(buf);
  5372. if ((int64_t)to_read > len) {
  5373. to_read = (int)len;
  5374. }
  5375. /* Read from file, exit the loop on error */
  5376. if ((num_read = (int)fread(buf, 1, (size_t)to_read, filep->fp))
  5377. <= 0) {
  5378. break;
  5379. }
  5380. /* Send read bytes to the client, exit the loop on error */
  5381. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  5382. != num_read) {
  5383. break;
  5384. }
  5385. /* Both read and were successful, adjust counters */
  5386. conn->num_bytes_sent += num_written;
  5387. len -= num_written;
  5388. }
  5389. }
  5390. }
  5391. }
  5392. static int
  5393. parse_range_header(const char *header, int64_t *a, int64_t *b)
  5394. {
  5395. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  5396. }
  5397. static void
  5398. construct_etag(char *buf, size_t buf_len, const struct file *filep)
  5399. {
  5400. if (filep != NULL && buf != NULL) {
  5401. mg_snprintf(NULL,
  5402. NULL, /* All calls to construct_etag use 64 byte buffer */
  5403. buf,
  5404. buf_len,
  5405. "\"%lx.%" INT64_FMT "\"",
  5406. (unsigned long)filep->last_modified,
  5407. filep->size);
  5408. }
  5409. }
  5410. static void
  5411. fclose_on_exec(struct file *filep, struct mg_connection *conn)
  5412. {
  5413. if (filep != NULL && filep->fp != NULL) {
  5414. #ifdef _WIN32
  5415. (void)conn; /* Unused. */
  5416. #else
  5417. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  5418. mg_cry(conn,
  5419. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  5420. __func__,
  5421. strerror(ERRNO));
  5422. }
  5423. #endif
  5424. }
  5425. }
  5426. static void
  5427. handle_static_file_request(struct mg_connection *conn,
  5428. const char *path,
  5429. struct file *filep,
  5430. const char *mime_type)
  5431. {
  5432. char date[64], lm[64], etag[64];
  5433. char range[128]; /* large enough, so there will be no overflow */
  5434. const char *msg = "OK", *hdr;
  5435. time_t curtime = time(NULL);
  5436. int64_t cl, r1, r2;
  5437. struct vec mime_vec;
  5438. int n, truncated;
  5439. char gz_path[PATH_MAX];
  5440. const char *encoding = "";
  5441. const char *cors1, *cors2, *cors3;
  5442. if (conn == NULL || conn->ctx == NULL || filep == NULL) {
  5443. return;
  5444. }
  5445. if (mime_type == NULL) {
  5446. get_mime_type(conn->ctx, path, &mime_vec);
  5447. } else {
  5448. mime_vec.ptr = mime_type;
  5449. mime_vec.len = strlen(mime_type);
  5450. }
  5451. if (filep->size > INT64_MAX) {
  5452. send_http_error(conn,
  5453. 500,
  5454. "Error: File size is too large to send\n%" INT64_FMT,
  5455. filep->size);
  5456. }
  5457. cl = (int64_t)filep->size;
  5458. conn->status_code = 200;
  5459. range[0] = '\0';
  5460. /* if this file is in fact a pre-gzipped file, rewrite its filename
  5461. * it's important to rewrite the filename after resolving
  5462. * the mime type from it, to preserve the actual file's type */
  5463. if (filep->gzipped) {
  5464. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  5465. if (truncated) {
  5466. send_http_error(conn,
  5467. 500,
  5468. "Error: Path of zipped file too long (%s)",
  5469. path);
  5470. return;
  5471. }
  5472. path = gz_path;
  5473. encoding = "Content-Encoding: gzip\r\n";
  5474. }
  5475. if (!mg_fopen(conn, path, "rb", filep)) {
  5476. send_http_error(conn,
  5477. 500,
  5478. "Error: Cannot open file\nfopen(%s): %s",
  5479. path,
  5480. strerror(ERRNO));
  5481. return;
  5482. }
  5483. fclose_on_exec(filep, conn);
  5484. /* If Range: header specified, act accordingly */
  5485. r1 = r2 = 0;
  5486. hdr = mg_get_header(conn, "Range");
  5487. if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 && r1 >= 0
  5488. && r2 >= 0) {
  5489. /* actually, range requests don't play well with a pre-gzipped
  5490. * file (since the range is specified in the uncompressed space) */
  5491. if (filep->gzipped) {
  5492. send_http_error(
  5493. conn,
  5494. 501,
  5495. "%s",
  5496. "Error: Range requests in gzipped files are not supported");
  5497. mg_fclose(filep);
  5498. return;
  5499. }
  5500. conn->status_code = 206;
  5501. cl = n == 2 ? (r2 > cl ? cl : r2) - r1 + 1 : cl - r1;
  5502. mg_snprintf(conn,
  5503. NULL, /* range buffer is big enough */
  5504. range,
  5505. sizeof(range),
  5506. "Content-Range: bytes "
  5507. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  5508. r1,
  5509. r1 + cl - 1,
  5510. filep->size);
  5511. msg = "Partial Content";
  5512. }
  5513. hdr = mg_get_header(conn, "Origin");
  5514. if (hdr) {
  5515. /* Cross-origin resource sharing (CORS), see
  5516. * http://www.html5rocks.com/en/tutorials/cors/,
  5517. * http://www.html5rocks.com/static/images/cors_server_flowchart.png -
  5518. * preflight is not supported for files. */
  5519. cors1 = "Access-Control-Allow-Origin: ";
  5520. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  5521. cors3 = "\r\n";
  5522. } else {
  5523. cors1 = cors2 = cors3 = "";
  5524. }
  5525. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
  5526. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  5527. gmt_time_string(date, sizeof(date), &curtime);
  5528. gmt_time_string(lm, sizeof(lm), &filep->last_modified);
  5529. construct_etag(etag, sizeof(etag), filep);
  5530. (void)mg_printf(conn,
  5531. "HTTP/1.1 %d %s\r\n"
  5532. "%s%s%s"
  5533. "Date: %s\r\n",
  5534. conn->status_code,
  5535. msg,
  5536. cors1,
  5537. cors2,
  5538. cors3,
  5539. date);
  5540. send_static_cache_header(conn);
  5541. (void)mg_printf(conn,
  5542. "Last-Modified: %s\r\n"
  5543. "Etag: %s\r\n"
  5544. "Content-Type: %.*s\r\n"
  5545. "Content-Length: %" INT64_FMT "\r\n"
  5546. "Connection: %s\r\n"
  5547. "Accept-Ranges: bytes\r\n"
  5548. "%s%s\r\n",
  5549. lm,
  5550. etag,
  5551. (int)mime_vec.len,
  5552. mime_vec.ptr,
  5553. cl,
  5554. suggest_connection_header(conn),
  5555. range,
  5556. encoding);
  5557. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  5558. send_file_data(conn, filep, r1, cl);
  5559. }
  5560. mg_fclose(filep);
  5561. }
  5562. void
  5563. mg_send_file(struct mg_connection *conn, const char *path)
  5564. {
  5565. mg_send_mime_file(conn, path, NULL);
  5566. }
  5567. void
  5568. mg_send_mime_file(struct mg_connection *conn,
  5569. const char *path,
  5570. const char *mime_type)
  5571. {
  5572. struct file file = STRUCT_FILE_INITIALIZER;
  5573. if (mg_stat(conn, path, &file)) {
  5574. if (file.is_directory) {
  5575. if (!conn) {
  5576. return;
  5577. }
  5578. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  5579. "yes")) {
  5580. handle_directory_request(conn, path);
  5581. } else {
  5582. send_http_error(conn,
  5583. 403,
  5584. "%s",
  5585. "Error: Directory listing denied");
  5586. }
  5587. } else {
  5588. handle_static_file_request(conn, path, &file, mime_type);
  5589. }
  5590. } else {
  5591. send_http_error(conn, 404, "%s", "Error: File not found");
  5592. }
  5593. }
  5594. /* For a given PUT path, create all intermediate subdirectories.
  5595. * Return 0 if the path itself is a directory.
  5596. * Return 1 if the path leads to a file.
  5597. * Return -1 for if the path is too long.
  5598. * Return -2 if path can not be created.
  5599. */
  5600. static int
  5601. put_dir(struct mg_connection *conn, const char *path)
  5602. {
  5603. char buf[PATH_MAX];
  5604. const char *s, *p;
  5605. struct file file = STRUCT_FILE_INITIALIZER;
  5606. size_t len;
  5607. int res = 1;
  5608. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  5609. len = (size_t)(p - path);
  5610. if (len >= sizeof(buf)) {
  5611. /* path too long */
  5612. res = -1;
  5613. break;
  5614. }
  5615. memcpy(buf, path, len);
  5616. buf[len] = '\0';
  5617. /* Try to create intermediate directory */
  5618. DEBUG_TRACE("mkdir(%s)", buf);
  5619. if (!mg_stat(conn, buf, &file) && mg_mkdir(buf, 0755) != 0) {
  5620. /* path does not exixt and can not be created */
  5621. res = -2;
  5622. break;
  5623. }
  5624. /* Is path itself a directory? */
  5625. if (p[1] == '\0') {
  5626. res = 0;
  5627. }
  5628. }
  5629. return res;
  5630. }
  5631. static void
  5632. remove_bad_file(const struct mg_connection *conn, const char *path)
  5633. {
  5634. int r = mg_remove(path);
  5635. if (r != 0) {
  5636. mg_cry(conn, "%s: Cannot remove invalid file %s", __func__, path);
  5637. }
  5638. }
  5639. long long
  5640. mg_store_body(struct mg_connection *conn, const char *path)
  5641. {
  5642. char buf[MG_BUF_LEN];
  5643. long long len = 0;
  5644. int ret, n;
  5645. struct file fi;
  5646. if (conn->consumed_content != 0) {
  5647. mg_cry(conn, "%s: Contents already consumed", __func__);
  5648. return -11;
  5649. }
  5650. ret = put_dir(conn, path);
  5651. if (ret < 0) {
  5652. /* -1 for path too long,
  5653. * -2 for path can not be created. */
  5654. return ret;
  5655. }
  5656. if (ret != 1) {
  5657. /* Return 0 means, path itself is a directory. */
  5658. return 0;
  5659. }
  5660. if (mg_fopen(conn, path, "w", &fi) == 0) {
  5661. return -12;
  5662. }
  5663. ret = mg_read(conn, buf, sizeof(buf));
  5664. while (ret > 0) {
  5665. n = (int)fwrite(buf, 1, (size_t)ret, fi.fp);
  5666. if (n != ret) {
  5667. fclose(fi.fp);
  5668. remove_bad_file(conn, path);
  5669. return -13;
  5670. }
  5671. ret = mg_read(conn, buf, sizeof(buf));
  5672. }
  5673. /* TODO: mg_fclose should return an error,
  5674. * and every caller should check and handle it. */
  5675. if (fclose(fi.fp) != 0) {
  5676. remove_bad_file(conn, path);
  5677. return -14;
  5678. }
  5679. return len;
  5680. }
  5681. /* Parse HTTP headers from the given buffer, advance buffer to the point
  5682. * where parsing stopped. */
  5683. static void
  5684. parse_http_headers(char **buf, struct mg_request_info *ri)
  5685. {
  5686. int i;
  5687. if (!ri) {
  5688. return;
  5689. }
  5690. ri->num_headers = 0;
  5691. for (i = 0; i < (int)ARRAY_SIZE(ri->http_headers); i++) {
  5692. char *dp = *buf;
  5693. while ((*dp != ':') && (*dp != '\r') && (*dp != 0)) {
  5694. dp++;
  5695. }
  5696. if (!*dp) {
  5697. /* neither : nor \r\n. This is not a valid field. */
  5698. break;
  5699. }
  5700. if (*dp == '\r') {
  5701. if (dp[1] == '\n') {
  5702. /* \r\n */
  5703. ri->http_headers[i].name = *buf;
  5704. ri->http_headers[i].value = 0;
  5705. *buf = dp;
  5706. } else {
  5707. /* stray \r. This is not valid. */
  5708. break;
  5709. }
  5710. } else {
  5711. /* (*dp == ':') */
  5712. *dp = 0;
  5713. ri->http_headers[i].name = *buf;
  5714. do {
  5715. dp++;
  5716. } while (*dp == ' ');
  5717. ri->http_headers[i].value = dp;
  5718. *buf = strstr(dp, "\r\n");
  5719. }
  5720. ri->num_headers = i + 1;
  5721. if (*buf) {
  5722. (*buf)[0] = 0;
  5723. (*buf)[1] = 0;
  5724. *buf += 2;
  5725. } else {
  5726. *buf = dp;
  5727. break;
  5728. }
  5729. if (*buf[0] == '\r') {
  5730. /* This is the end of the header */
  5731. break;
  5732. }
  5733. }
  5734. }
  5735. static int
  5736. is_valid_http_method(const char *method)
  5737. {
  5738. return !strcmp(method, "GET") /* HTTP (RFC 2616) */
  5739. || !strcmp(method, "POST") /* HTTP (RFC 2616) */
  5740. || !strcmp(method, "HEAD") /* HTTP (RFC 2616) */
  5741. || !strcmp(method, "PUT") /* HTTP (RFC 2616) */
  5742. || !strcmp(method, "DELETE") /* HTTP (RFC 2616) */
  5743. || !strcmp(method, "OPTIONS") /* HTTP (RFC 2616) */
  5744. /* TRACE method (RFC 2616) is not supported for security reasons */
  5745. || !strcmp(method, "CONNECT") /* HTTP (RFC 2616) */
  5746. || !strcmp(method, "PROPFIND") /* WEBDAV (RFC 2518) */
  5747. || !strcmp(method, "MKCOL") /* WEBDAV (RFC 2518) */
  5748. /* Unsupported WEBDAV Methods: */
  5749. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  5750. /* + 11 methods from RFC 3253 */
  5751. /* ORDERPATCH (RFC 3648) */
  5752. /* ACL (RFC 3744) */
  5753. /* SEARCH (RFC 5323) */
  5754. /* + MicroSoft extensions
  5755. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  5756. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  5757. || !strcmp(method, "PATCH"); /* PATCH method (RFC 5789) */
  5758. }
  5759. /* Parse HTTP request, fill in mg_request_info structure.
  5760. * This function modifies the buffer by NUL-terminating
  5761. * HTTP request components, header names and header values. */
  5762. static int
  5763. parse_http_message(char *buf, int len, struct mg_request_info *ri)
  5764. {
  5765. int is_request, request_length;
  5766. if (!ri) {
  5767. return 0;
  5768. }
  5769. request_length = get_request_len(buf, len);
  5770. if (request_length > 0) {
  5771. /* Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_addr,
  5772. * remote_port */
  5773. ri->remote_user = ri->request_method = ri->request_uri =
  5774. ri->http_version = NULL;
  5775. ri->num_headers = 0;
  5776. buf[request_length - 1] = '\0';
  5777. /* RFC says that all initial whitespaces should be ingored */
  5778. while (*buf != '\0' && isspace(*(unsigned char *)buf)) {
  5779. buf++;
  5780. }
  5781. ri->request_method = skip(&buf, " ");
  5782. ri->request_uri = skip(&buf, " ");
  5783. ri->http_version = skip(&buf, "\r\n");
  5784. /* HTTP message could be either HTTP request or HTTP response, e.g.
  5785. * "GET / HTTP/1.0 ...." or "HTTP/1.0 200 OK ..." */
  5786. is_request = is_valid_http_method(ri->request_method);
  5787. if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0)
  5788. || (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
  5789. request_length = -1;
  5790. } else {
  5791. if (is_request) {
  5792. ri->http_version += 5;
  5793. }
  5794. parse_http_headers(&buf, ri);
  5795. }
  5796. }
  5797. return request_length;
  5798. }
  5799. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  5800. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  5801. * buffer (which marks the end of HTTP request). Buffer buf may already
  5802. * have some data. The length of the data is stored in nread.
  5803. * Upon every read operation, increase nread by the number of bytes read. */
  5804. static int
  5805. read_request(FILE *fp,
  5806. struct mg_connection *conn,
  5807. char *buf,
  5808. int bufsiz,
  5809. int *nread)
  5810. {
  5811. int request_len, n = 0;
  5812. struct timespec last_action_time;
  5813. double request_timeout;
  5814. if (!conn) {
  5815. return 0;
  5816. }
  5817. memset(&last_action_time, 0, sizeof(last_action_time));
  5818. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  5819. /* value of request_timeout is in seconds, config in milliseconds */
  5820. request_timeout = atof(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5821. } else {
  5822. request_timeout = -1.0;
  5823. }
  5824. request_len = get_request_len(buf, *nread);
  5825. /* first time reading from this connection */
  5826. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  5827. while (
  5828. (conn->ctx->stop_flag == 0) && (*nread < bufsiz) && (request_len == 0)
  5829. && ((mg_difftimespec(&last_action_time, &(conn->req_time))
  5830. <= request_timeout) || (request_timeout < 0))
  5831. && ((n = pull(fp, conn, buf + *nread, bufsiz - *nread, request_timeout))
  5832. > 0)) {
  5833. *nread += n;
  5834. /* assert(*nread <= bufsiz); */
  5835. if (*nread > bufsiz) {
  5836. return -2;
  5837. }
  5838. request_len = get_request_len(buf, *nread);
  5839. if (request_timeout > 0.0) {
  5840. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  5841. }
  5842. }
  5843. return (request_len <= 0 && n <= 0) ? -1 : request_len;
  5844. }
  5845. #if !defined(NO_FILES)
  5846. /* For given directory path, substitute it to valid index file.
  5847. * Return 1 if index file has been found, 0 if not found.
  5848. * If the file is found, it's stats is returned in stp. */
  5849. static int
  5850. substitute_index_file(struct mg_connection *conn,
  5851. char *path,
  5852. size_t path_len,
  5853. struct file *filep)
  5854. {
  5855. if (conn && conn->ctx) {
  5856. const char *list = conn->ctx->config[INDEX_FILES];
  5857. struct file file = STRUCT_FILE_INITIALIZER;
  5858. struct vec filename_vec;
  5859. size_t n = strlen(path);
  5860. int found = 0;
  5861. /* The 'path' given to us points to the directory. Remove all trailing
  5862. * directory separator characters from the end of the path, and
  5863. * then append single directory separator character. */
  5864. while (n > 0 && path[n - 1] == '/') {
  5865. n--;
  5866. }
  5867. path[n] = '/';
  5868. /* Traverse index files list. For each entry, append it to the given
  5869. * path and see if the file exists. If it exists, break the loop */
  5870. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  5871. /* Ignore too long entries that may overflow path buffer */
  5872. if (filename_vec.len > path_len - (n + 2)) {
  5873. continue;
  5874. }
  5875. /* Prepare full path to the index file */
  5876. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  5877. /* Does it exist? */
  5878. if (mg_stat(conn, path, &file)) {
  5879. /* Yes it does, break the loop */
  5880. *filep = file;
  5881. found = 1;
  5882. break;
  5883. }
  5884. }
  5885. /* If no index file exists, restore directory path */
  5886. if (!found) {
  5887. path[n] = '\0';
  5888. }
  5889. return found;
  5890. }
  5891. return 0;
  5892. }
  5893. #endif
  5894. /* Return True if we should reply 304 Not Modified. */
  5895. static int
  5896. is_not_modified(const struct mg_connection *conn, const struct file *filep)
  5897. {
  5898. char etag[64];
  5899. const char *ims = mg_get_header(conn, "If-Modified-Since");
  5900. const char *inm = mg_get_header(conn, "If-None-Match");
  5901. construct_etag(etag, sizeof(etag), filep);
  5902. if (!filep) {
  5903. return 0;
  5904. }
  5905. return (inm != NULL && !mg_strcasecmp(etag, inm))
  5906. || (ims != NULL && (filep->last_modified <= parse_date_string(ims)));
  5907. }
  5908. #if !defined(NO_CGI) || !defined(NO_FILES)
  5909. static int
  5910. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  5911. {
  5912. const char *expect, *body;
  5913. char buf[MG_BUF_LEN];
  5914. int to_read, nread, success = 0;
  5915. int64_t buffered_len;
  5916. double timeout = -1.0;
  5917. if (!conn) {
  5918. return 0;
  5919. }
  5920. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  5921. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5922. }
  5923. expect = mg_get_header(conn, "Expect");
  5924. /* assert(fp != NULL); */
  5925. if (!fp) {
  5926. send_http_error(conn, 500, "%s", "Error: NULL File");
  5927. return 0;
  5928. }
  5929. if (conn->content_len == -1 && !conn->is_chunked) {
  5930. /* Content length is not specified by the client. */
  5931. send_http_error(conn,
  5932. 411,
  5933. "%s",
  5934. "Error: Client did not specify content length");
  5935. } else if ((expect != NULL)
  5936. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  5937. /* Client sent an "Expect: xyz" header and xyz is not 100-continue. */
  5938. send_http_error(conn,
  5939. 417,
  5940. "Error: Can not fulfill expectation %s",
  5941. expect);
  5942. } else {
  5943. if (expect != NULL) {
  5944. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  5945. conn->status_code = 100;
  5946. } else {
  5947. conn->status_code = 200;
  5948. }
  5949. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5950. - conn->consumed_content;
  5951. /* assert(buffered_len >= 0); */
  5952. /* assert(conn->consumed_content == 0); */
  5953. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  5954. send_http_error(conn, 500, "%s", "Error: Size mismatch");
  5955. return 0;
  5956. }
  5957. if (buffered_len > 0) {
  5958. if ((int64_t)buffered_len > conn->content_len) {
  5959. buffered_len = (int)conn->content_len;
  5960. }
  5961. body = conn->buf + conn->request_len + conn->consumed_content;
  5962. push_all(conn->ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  5963. conn->consumed_content += buffered_len;
  5964. }
  5965. nread = 0;
  5966. while (conn->consumed_content < conn->content_len) {
  5967. to_read = sizeof(buf);
  5968. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  5969. to_read = (int)(conn->content_len - conn->consumed_content);
  5970. }
  5971. nread = pull(NULL, conn, buf, to_read, timeout);
  5972. if (nread <= 0
  5973. || push_all(conn->ctx, fp, sock, ssl, buf, nread) != nread) {
  5974. break;
  5975. }
  5976. conn->consumed_content += nread;
  5977. }
  5978. if (conn->consumed_content == conn->content_len) {
  5979. success = (nread >= 0);
  5980. }
  5981. /* Each error code path in this function must send an error */
  5982. if (!success) {
  5983. /* NOTE: Maybe some data has already been sent. */
  5984. /* TODO (low): If some data has been sent, a correct error
  5985. * reply can no longer be sent, so just close the connection */
  5986. send_http_error(conn, 500, "%s", "");
  5987. }
  5988. }
  5989. return success;
  5990. }
  5991. #endif
  5992. #if !defined(NO_CGI)
  5993. /* This structure helps to create an environment for the spawned CGI program.
  5994. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  5995. * last element must be NULL.
  5996. * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  5997. * strings must reside in a contiguous buffer. The end of the buffer is
  5998. * marked by two '\0' characters.
  5999. * We satisfy both worlds: we create an envp array (which is vars), all
  6000. * entries are actually pointers inside buf. */
  6001. struct cgi_environment {
  6002. struct mg_connection *conn;
  6003. /* Data block */
  6004. char *buf; /* Environment buffer */
  6005. size_t buflen; /* Space available in buf */
  6006. size_t bufused; /* Space taken in buf */
  6007. /* Index block */
  6008. char **var; /* char **envp */
  6009. size_t varlen; /* Number of variables available in var */
  6010. size_t varused; /* Number of variables stored in var */
  6011. };
  6012. static void addenv(struct cgi_environment *env,
  6013. PRINTF_FORMAT_STRING(const char *fmt),
  6014. ...) PRINTF_ARGS(2, 3);
  6015. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  6016. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  6017. static void
  6018. addenv(struct cgi_environment *env, const char *fmt, ...)
  6019. {
  6020. size_t n, space;
  6021. int truncated;
  6022. char *added;
  6023. va_list ap;
  6024. /* Calculate how much space is left in the buffer */
  6025. space = (env->buflen - env->bufused);
  6026. /* Calculate an estimate for the required space */
  6027. n = strlen(fmt) + 2 + 128;
  6028. do {
  6029. if (space <= n) {
  6030. /* Allocate new buffer */
  6031. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  6032. added = (char *)mg_realloc(env->buf, n);
  6033. if (!added) {
  6034. /* Out of memory */
  6035. mg_cry(env->conn,
  6036. "%s: Cannot allocate memory for CGI variable [%s]",
  6037. __func__,
  6038. fmt);
  6039. return;
  6040. }
  6041. env->buf = added;
  6042. env->buflen = n;
  6043. space = (env->buflen - env->bufused);
  6044. }
  6045. /* Make a pointer to the free space int the buffer */
  6046. added = env->buf + env->bufused;
  6047. /* Copy VARIABLE=VALUE\0 string into the free space */
  6048. va_start(ap, fmt);
  6049. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  6050. va_end(ap);
  6051. /* Do not add truncated strings to the environment */
  6052. if (truncated) {
  6053. /* Reallocate the buffer */
  6054. space = 0;
  6055. n = 1;
  6056. }
  6057. } while (truncated);
  6058. /* Calculate number of bytes added to the environment */
  6059. n = strlen(added) + 1;
  6060. env->bufused += n;
  6061. /* Now update the variable index */
  6062. space = (env->varlen - env->varused);
  6063. if (space < 2) {
  6064. mg_cry(env->conn,
  6065. "%s: Cannot register CGI variable [%s]",
  6066. __func__,
  6067. fmt);
  6068. return;
  6069. }
  6070. /* Append a pointer to the added string into the envp array */
  6071. env->var[env->varused] = added;
  6072. env->varused++;
  6073. }
  6074. static void
  6075. prepare_cgi_environment(struct mg_connection *conn,
  6076. const char *prog,
  6077. struct cgi_environment *env)
  6078. {
  6079. const char *s;
  6080. struct vec var_vec;
  6081. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  6082. int i, truncated;
  6083. if (conn == NULL || prog == NULL || env == NULL) {
  6084. return;
  6085. }
  6086. env->conn = conn;
  6087. env->buflen = CGI_ENVIRONMENT_SIZE;
  6088. env->bufused = 0;
  6089. env->buf = (char *)mg_malloc(env->buflen);
  6090. env->varlen = MAX_CGI_ENVIR_VARS;
  6091. env->varused = 0;
  6092. env->var = (char **)mg_malloc(env->buflen * sizeof(char *));
  6093. addenv(env, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  6094. addenv(env, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6095. addenv(env, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6096. addenv(env, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  6097. /* Prepare the environment block */
  6098. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  6099. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  6100. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  6101. #if defined(USE_IPV6)
  6102. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  6103. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  6104. } else
  6105. #endif
  6106. {
  6107. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  6108. }
  6109. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  6110. addenv(env, "REMOTE_ADDR=%s", src_addr);
  6111. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  6112. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  6113. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  6114. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  6115. /* SCRIPT_NAME */
  6116. addenv(env,
  6117. "SCRIPT_NAME=%.*s",
  6118. (int)strlen(conn->request_info.local_uri)
  6119. - ((conn->path_info == NULL) ? 0 : (int)strlen(conn->path_info)),
  6120. conn->request_info.local_uri);
  6121. addenv(env, "SCRIPT_FILENAME=%s", prog);
  6122. if (conn->path_info == NULL) {
  6123. addenv(env, "PATH_TRANSLATED=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6124. } else {
  6125. addenv(env,
  6126. "PATH_TRANSLATED=%s%s",
  6127. conn->ctx->config[DOCUMENT_ROOT],
  6128. conn->path_info);
  6129. }
  6130. addenv(env, "HTTPS=%s", conn->ssl == NULL ? "off" : "on");
  6131. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  6132. addenv(env, "CONTENT_TYPE=%s", s);
  6133. }
  6134. if (conn->request_info.query_string != NULL) {
  6135. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  6136. }
  6137. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  6138. addenv(env, "CONTENT_LENGTH=%s", s);
  6139. }
  6140. if ((s = getenv("PATH")) != NULL) {
  6141. addenv(env, "PATH=%s", s);
  6142. }
  6143. if (conn->path_info != NULL) {
  6144. addenv(env, "PATH_INFO=%s", conn->path_info);
  6145. }
  6146. if (conn->status_code > 0) {
  6147. /* CGI error handler should show the status code */
  6148. addenv(env, "STATUS=%d", conn->status_code);
  6149. }
  6150. #if defined(_WIN32)
  6151. if ((s = getenv("COMSPEC")) != NULL) {
  6152. addenv(env, "COMSPEC=%s", s);
  6153. }
  6154. if ((s = getenv("SYSTEMROOT")) != NULL) {
  6155. addenv(env, "SYSTEMROOT=%s", s);
  6156. }
  6157. if ((s = getenv("SystemDrive")) != NULL) {
  6158. addenv(env, "SystemDrive=%s", s);
  6159. }
  6160. if ((s = getenv("ProgramFiles")) != NULL) {
  6161. addenv(env, "ProgramFiles=%s", s);
  6162. }
  6163. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  6164. addenv(env, "ProgramFiles(x86)=%s", s);
  6165. }
  6166. #else
  6167. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  6168. addenv(env, "LD_LIBRARY_PATH=%s", s);
  6169. }
  6170. #endif /* _WIN32 */
  6171. if ((s = getenv("PERLLIB")) != NULL) {
  6172. addenv(env, "PERLLIB=%s", s);
  6173. }
  6174. if (conn->request_info.remote_user != NULL) {
  6175. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  6176. addenv(env, "%s", "AUTH_TYPE=Digest");
  6177. }
  6178. /* Add all headers as HTTP_* variables */
  6179. for (i = 0; i < conn->request_info.num_headers; i++) {
  6180. (void)mg_snprintf(conn,
  6181. &truncated,
  6182. http_var_name,
  6183. sizeof(http_var_name),
  6184. "HTTP_%s",
  6185. conn->request_info.http_headers[i].name);
  6186. if (truncated) {
  6187. mg_cry(conn,
  6188. "%s: HTTP header variable too long [%s]",
  6189. __func__,
  6190. conn->request_info.http_headers[i].name);
  6191. continue;
  6192. }
  6193. /* Convert variable name into uppercase, and change - to _ */
  6194. for (p = http_var_name; *p != '\0'; p++) {
  6195. if (*p == '-') {
  6196. *p = '_';
  6197. }
  6198. *p = (char)toupper(*(unsigned char *)p);
  6199. }
  6200. addenv(env,
  6201. "%s=%s",
  6202. http_var_name,
  6203. conn->request_info.http_headers[i].value);
  6204. }
  6205. /* Add user-specified variables */
  6206. s = conn->ctx->config[CGI_ENVIRONMENT];
  6207. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  6208. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  6209. }
  6210. env->var[env->varused] = NULL;
  6211. env->buf[env->bufused] = '\0';
  6212. }
  6213. static void
  6214. handle_cgi_request(struct mg_connection *conn, const char *prog)
  6215. {
  6216. char *buf;
  6217. size_t buflen;
  6218. int headers_len, data_len, i, truncated;
  6219. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  6220. const char *status, *status_text, *connection_state;
  6221. char *pbuf, dir[PATH_MAX], *p;
  6222. struct mg_request_info ri;
  6223. struct cgi_environment blk;
  6224. FILE *in = NULL, *out = NULL, *err = NULL;
  6225. struct file fout = STRUCT_FILE_INITIALIZER;
  6226. pid_t pid = (pid_t)-1;
  6227. if (conn == NULL) {
  6228. return;
  6229. }
  6230. buf = NULL;
  6231. buflen = 16384;
  6232. prepare_cgi_environment(conn, prog, &blk);
  6233. /* CGI must be executed in its own directory. 'dir' must point to the
  6234. * directory containing executable program, 'p' must point to the
  6235. * executable program name relative to 'dir'. */
  6236. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  6237. if (truncated) {
  6238. mg_cry(conn, "Error: CGI program \"%s\": Path too long", prog);
  6239. send_http_error(conn, 500, "Error: %s", "CGI path too long");
  6240. goto done;
  6241. }
  6242. if ((p = strrchr(dir, '/')) != NULL) {
  6243. *p++ = '\0';
  6244. } else {
  6245. dir[0] = '.', dir[1] = '\0';
  6246. p = (char *)prog;
  6247. }
  6248. if (pipe(fdin) != 0 || pipe(fdout) != 0 || pipe(fderr) != 0) {
  6249. status = strerror(ERRNO);
  6250. mg_cry(conn,
  6251. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  6252. prog,
  6253. status);
  6254. send_http_error(conn, 500, "Error: Cannot create CGI pipe: %s", status);
  6255. goto done;
  6256. }
  6257. pid = spawn_process(
  6258. conn, p, blk.buf, blk.var, fdin[0], fdout[1], fderr[1], dir);
  6259. if (pid == (pid_t)-1) {
  6260. status = strerror(ERRNO);
  6261. mg_cry(conn,
  6262. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  6263. prog,
  6264. status);
  6265. send_http_error(conn,
  6266. 500,
  6267. "Error: Cannot spawn CGI process [%s]: %s",
  6268. prog,
  6269. status);
  6270. goto done;
  6271. }
  6272. /* Make sure child closes all pipe descriptors. It must dup them to 0,1 */
  6273. set_close_on_exec((SOCKET)fdin[0], conn);
  6274. set_close_on_exec((SOCKET)fdin[1], conn);
  6275. set_close_on_exec((SOCKET)fdout[0], conn);
  6276. set_close_on_exec((SOCKET)fdout[1], conn);
  6277. set_close_on_exec((SOCKET)fderr[0], conn);
  6278. set_close_on_exec((SOCKET)fderr[1], conn);
  6279. /* Parent closes only one side of the pipes.
  6280. * If we don't mark them as closed, close() attempt before
  6281. * return from this function throws an exception on Windows.
  6282. * Windows does not like when closed descriptor is closed again. */
  6283. (void)close(fdin[0]);
  6284. (void)close(fdout[1]);
  6285. (void)close(fderr[1]);
  6286. fdin[0] = fdout[1] = fderr[1] = -1;
  6287. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  6288. status = strerror(ERRNO);
  6289. mg_cry(conn,
  6290. "Error: CGI program \"%s\": Can not open stdin: %s",
  6291. prog,
  6292. status);
  6293. send_http_error(conn,
  6294. 500,
  6295. "Error: CGI can not open fdin\nfopen: %s",
  6296. status);
  6297. goto done;
  6298. }
  6299. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  6300. status = strerror(ERRNO);
  6301. mg_cry(conn,
  6302. "Error: CGI program \"%s\": Can not open stdout: %s",
  6303. prog,
  6304. status);
  6305. send_http_error(conn,
  6306. 500,
  6307. "Error: CGI can not open fdout\nfopen: %s",
  6308. status);
  6309. goto done;
  6310. }
  6311. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  6312. status = strerror(ERRNO);
  6313. mg_cry(conn,
  6314. "Error: CGI program \"%s\": Can not open stderr: %s",
  6315. prog,
  6316. status);
  6317. send_http_error(conn,
  6318. 500,
  6319. "Error: CGI can not open fdout\nfopen: %s",
  6320. status);
  6321. goto done;
  6322. }
  6323. setbuf(in, NULL);
  6324. setbuf(out, NULL);
  6325. setbuf(err, NULL);
  6326. fout.fp = out;
  6327. if ((conn->request_info.content_length > 0) || conn->is_chunked) {
  6328. /* This is a POST/PUT request, or another request with body data. */
  6329. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  6330. /* Error sending the body data */
  6331. mg_cry(conn,
  6332. "Error: CGI program \"%s\": Forward body data failed",
  6333. prog);
  6334. goto done;
  6335. }
  6336. }
  6337. /* Close so child gets an EOF. */
  6338. fclose(in);
  6339. in = NULL;
  6340. fdin[1] = -1;
  6341. /* Now read CGI reply into a buffer. We need to set correct
  6342. * status code, thus we need to see all HTTP headers first.
  6343. * Do not send anything back to client, until we buffer in all
  6344. * HTTP headers. */
  6345. data_len = 0;
  6346. buf = (char *)mg_malloc(buflen);
  6347. if (buf == NULL) {
  6348. send_http_error(conn,
  6349. 500,
  6350. "Error: Not enough memory for CGI buffer (%u bytes)",
  6351. (unsigned int)buflen);
  6352. mg_cry(conn,
  6353. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  6354. "bytes)",
  6355. prog,
  6356. (unsigned int)buflen);
  6357. goto done;
  6358. }
  6359. headers_len = read_request(out, conn, buf, (int)buflen, &data_len);
  6360. if (headers_len <= 0) {
  6361. /* Could not parse the CGI response. Check if some error message on
  6362. * stderr. */
  6363. i = pull_all(err, conn, buf, (int)buflen);
  6364. if (i > 0) {
  6365. mg_cry(conn,
  6366. "Error: CGI program \"%s\" sent error "
  6367. "message: [%.*s]",
  6368. prog,
  6369. i,
  6370. buf);
  6371. send_http_error(conn,
  6372. 500,
  6373. "Error: CGI program \"%s\" sent error "
  6374. "message: [%.*s]",
  6375. prog,
  6376. i,
  6377. buf);
  6378. } else {
  6379. mg_cry(conn,
  6380. "Error: CGI program sent malformed or too big "
  6381. "(>%u bytes) HTTP headers: [%.*s]",
  6382. (unsigned)buflen,
  6383. data_len,
  6384. buf);
  6385. send_http_error(conn,
  6386. 500,
  6387. "Error: CGI program sent malformed or too big "
  6388. "(>%u bytes) HTTP headers: [%.*s]",
  6389. (unsigned)buflen,
  6390. data_len,
  6391. buf);
  6392. }
  6393. goto done;
  6394. }
  6395. pbuf = buf;
  6396. buf[headers_len - 1] = '\0';
  6397. parse_http_headers(&pbuf, &ri);
  6398. /* Make up and send the status line */
  6399. status_text = "OK";
  6400. if ((status = get_header(&ri, "Status")) != NULL) {
  6401. conn->status_code = atoi(status);
  6402. status_text = status;
  6403. while (isdigit(*(unsigned char *)status_text) || *status_text == ' ') {
  6404. status_text++;
  6405. }
  6406. } else if (get_header(&ri, "Location") != NULL) {
  6407. conn->status_code = 302;
  6408. } else {
  6409. conn->status_code = 200;
  6410. }
  6411. connection_state = get_header(&ri, "Connection");
  6412. if (connection_state == NULL
  6413. || mg_strcasecmp(connection_state, "keep-alive")) {
  6414. conn->must_close = 1;
  6415. }
  6416. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  6417. /* Send headers */
  6418. for (i = 0; i < ri.num_headers; i++) {
  6419. mg_printf(conn,
  6420. "%s: %s\r\n",
  6421. ri.http_headers[i].name,
  6422. ri.http_headers[i].value);
  6423. }
  6424. mg_write(conn, "\r\n", 2);
  6425. /* Send chunk of data that may have been read after the headers */
  6426. conn->num_bytes_sent +=
  6427. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  6428. /* Read the rest of CGI output and send to the client */
  6429. send_file_data(conn, &fout, 0, INT64_MAX);
  6430. done:
  6431. mg_free(blk.var);
  6432. mg_free(blk.buf);
  6433. if (pid != (pid_t)-1) {
  6434. kill(pid, SIGKILL);
  6435. #if !defined(_WIN32)
  6436. {
  6437. int st;
  6438. while (waitpid(pid, &st, 0) != -1)
  6439. ; /* clean zombies */
  6440. }
  6441. #endif
  6442. }
  6443. if (fdin[0] != -1) {
  6444. close(fdin[0]);
  6445. }
  6446. if (fdout[1] != -1) {
  6447. close(fdout[1]);
  6448. }
  6449. if (in != NULL) {
  6450. fclose(in);
  6451. } else if (fdin[1] != -1) {
  6452. close(fdin[1]);
  6453. }
  6454. if (out != NULL) {
  6455. fclose(out);
  6456. } else if (fdout[0] != -1) {
  6457. close(fdout[0]);
  6458. }
  6459. if (err != NULL) {
  6460. fclose(err);
  6461. } else if (fderr[0] != -1) {
  6462. close(fderr[0]);
  6463. }
  6464. if (buf != NULL) {
  6465. mg_free(buf);
  6466. }
  6467. }
  6468. #endif /* !NO_CGI */
  6469. #if !defined(NO_FILES)
  6470. static void
  6471. mkcol(struct mg_connection *conn, const char *path)
  6472. {
  6473. int rc, body_len;
  6474. struct de de;
  6475. char date[64];
  6476. time_t curtime = time(NULL);
  6477. if (conn == NULL) {
  6478. return;
  6479. }
  6480. /* TODO (mid): Check the send_http_error situations in this function */
  6481. memset(&de.file, 0, sizeof(de.file));
  6482. if (!mg_stat(conn, path, &de.file)) {
  6483. mg_cry(conn,
  6484. "%s: mg_stat(%s) failed: %s",
  6485. __func__,
  6486. path,
  6487. strerror(ERRNO));
  6488. }
  6489. if (de.file.last_modified) {
  6490. /* TODO (high): This check does not seem to make any sense ! */
  6491. send_http_error(
  6492. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6493. return;
  6494. }
  6495. body_len = conn->data_len - conn->request_len;
  6496. if (body_len > 0) {
  6497. send_http_error(
  6498. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6499. return;
  6500. }
  6501. rc = mg_mkdir(path, 0755);
  6502. if (rc == 0) {
  6503. conn->status_code = 201;
  6504. gmt_time_string(date, sizeof(date), &curtime);
  6505. mg_printf(conn,
  6506. "HTTP/1.1 %d Created\r\n"
  6507. "Date: %s\r\n",
  6508. conn->status_code,
  6509. date);
  6510. send_static_cache_header(conn);
  6511. mg_printf(conn,
  6512. "Content-Length: 0\r\n"
  6513. "Connection: %s\r\n\r\n",
  6514. suggest_connection_header(conn));
  6515. } else if (rc == -1) {
  6516. if (errno == EEXIST) {
  6517. send_http_error(
  6518. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6519. } else if (errno == EACCES) {
  6520. send_http_error(
  6521. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6522. } else if (errno == ENOENT) {
  6523. send_http_error(
  6524. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6525. } else {
  6526. send_http_error(conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  6527. }
  6528. }
  6529. }
  6530. static void
  6531. put_file(struct mg_connection *conn, const char *path)
  6532. {
  6533. struct file file = STRUCT_FILE_INITIALIZER;
  6534. const char *range;
  6535. int64_t r1, r2;
  6536. int rc;
  6537. char date[64];
  6538. time_t curtime = time(NULL);
  6539. if (conn == NULL) {
  6540. return;
  6541. }
  6542. if (mg_stat(conn, path, &file)) {
  6543. /* File already exists */
  6544. conn->status_code = 200;
  6545. if (file.is_directory) {
  6546. /* This is an already existing directory,
  6547. * so there is nothing to do for the server. */
  6548. rc = 0;
  6549. } else {
  6550. /* File exists and is not a directory. */
  6551. /* Can it be replaced? */
  6552. if (file.membuf != NULL) {
  6553. /* This is an "in-memory" file, that can not be replaced */
  6554. send_http_error(
  6555. conn,
  6556. 405,
  6557. "Error: Put not possible\nReplacing %s is not supported",
  6558. path);
  6559. return;
  6560. }
  6561. /* Check if the server may write this file */
  6562. if (access(path, W_OK) == 0) {
  6563. /* Access granted */
  6564. conn->status_code = 200;
  6565. rc = 1;
  6566. } else {
  6567. send_http_error(
  6568. conn,
  6569. 403,
  6570. "Error: Put not possible\nReplacing %s is not allowed",
  6571. path);
  6572. return;
  6573. }
  6574. }
  6575. } else {
  6576. /* File should be created */
  6577. conn->status_code = 201;
  6578. rc = put_dir(conn, path);
  6579. }
  6580. if (rc == 0) {
  6581. /* put_dir returns 0 if path is a directory */
  6582. gmt_time_string(date, sizeof(date), &curtime);
  6583. mg_printf(conn,
  6584. "HTTP/1.1 %d %s\r\n",
  6585. conn->status_code,
  6586. mg_get_response_code_text(conn->status_code, NULL));
  6587. send_no_cache_header(conn);
  6588. mg_printf(conn,
  6589. "Date: %s\r\n"
  6590. "Content-Length: 0\r\n"
  6591. "Connection: %s\r\n\r\n",
  6592. date,
  6593. suggest_connection_header(conn));
  6594. /* Request to create a directory has been fulfilled successfully.
  6595. * No need to put a file. */
  6596. return;
  6597. }
  6598. if (rc == -1) {
  6599. /* put_dir returns -1 if the path is too long */
  6600. send_http_error(conn,
  6601. 414,
  6602. "Error: Path too long\nput_dir(%s): %s",
  6603. path,
  6604. strerror(ERRNO));
  6605. return;
  6606. }
  6607. if (rc == -2) {
  6608. /* put_dir returns -2 if the directory can not be created */
  6609. send_http_error(conn,
  6610. 500,
  6611. "Error: Can not create directory\nput_dir(%s): %s",
  6612. path,
  6613. strerror(ERRNO));
  6614. return;
  6615. }
  6616. /* A file should be created or overwritten. */
  6617. if (!mg_fopen(conn, path, "wb+", &file) || file.fp == NULL) {
  6618. mg_fclose(&file);
  6619. send_http_error(conn,
  6620. 500,
  6621. "Error: Can not create file\nfopen(%s): %s",
  6622. path,
  6623. strerror(ERRNO));
  6624. return;
  6625. }
  6626. fclose_on_exec(&file, conn);
  6627. range = mg_get_header(conn, "Content-Range");
  6628. r1 = r2 = 0;
  6629. if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
  6630. conn->status_code = 206; /* Partial content */
  6631. fseeko(file.fp, r1, SEEK_SET);
  6632. }
  6633. if (!forward_body_data(conn, file.fp, INVALID_SOCKET, NULL)) {
  6634. /* forward_body_data failed.
  6635. * The error code has already been sent to the client,
  6636. * and conn->status_code is already set. */
  6637. mg_fclose(&file);
  6638. return;
  6639. }
  6640. gmt_time_string(date, sizeof(date), &curtime);
  6641. mg_printf(conn,
  6642. "HTTP/1.1 %d %s\r\n",
  6643. conn->status_code,
  6644. mg_get_response_code_text(conn->status_code, NULL));
  6645. send_no_cache_header(conn);
  6646. mg_printf(conn,
  6647. "Date: %s\r\n"
  6648. "Content-Length: 0\r\n"
  6649. "Connection: %s\r\n\r\n",
  6650. date,
  6651. suggest_connection_header(conn));
  6652. mg_fclose(&file);
  6653. }
  6654. static void
  6655. delete_file(struct mg_connection *conn, const char *path)
  6656. {
  6657. struct de de;
  6658. memset(&de.file, 0, sizeof(de.file));
  6659. if (!mg_stat(conn, path, &de.file)) {
  6660. /* mg_stat returns 0 if the file does not exist */
  6661. send_http_error(conn,
  6662. 404,
  6663. "Error: Cannot delete file\nFile %s not found",
  6664. path);
  6665. return;
  6666. }
  6667. if (de.file.membuf != NULL) {
  6668. /* the file is cached in memory */
  6669. send_http_error(
  6670. conn,
  6671. 405,
  6672. "Error: Delete not possible\nDeleting %s is not supported",
  6673. path);
  6674. return;
  6675. }
  6676. if (de.file.is_directory) {
  6677. if (remove_directory(conn, path)) {
  6678. /* Delete is successful: Return 204 without content. */
  6679. send_http_error(conn, 204, "%s", "");
  6680. } else {
  6681. /* Delete is not successful: Return 500 (Server error). */
  6682. send_http_error(conn, 500, "Error: Could not delete %s", path);
  6683. }
  6684. return;
  6685. }
  6686. /* This is an existing file (not a directory).
  6687. * Check if write permission is granted. */
  6688. if (access(path, W_OK) != 0) {
  6689. /* File is read only */
  6690. send_http_error(
  6691. conn,
  6692. 403,
  6693. "Error: Delete not possible\nDeleting %s is not allowed",
  6694. path);
  6695. return;
  6696. }
  6697. /* Try to delete it. */
  6698. if (mg_remove(path) == 0) {
  6699. /* Delete was successful: Return 204 without content. */
  6700. send_http_error(conn, 204, "%s", "");
  6701. } else {
  6702. /* Delete not successful (file locked). */
  6703. send_http_error(conn,
  6704. 423,
  6705. "Error: Cannot delete file\nremove(%s): %s",
  6706. path,
  6707. strerror(ERRNO));
  6708. }
  6709. }
  6710. #endif /* !NO_FILES */
  6711. static void
  6712. send_ssi_file(struct mg_connection *, const char *, struct file *, int);
  6713. static void
  6714. do_ssi_include(struct mg_connection *conn,
  6715. const char *ssi,
  6716. char *tag,
  6717. int include_level)
  6718. {
  6719. char file_name[MG_BUF_LEN], path[512], *p;
  6720. struct file file = STRUCT_FILE_INITIALIZER;
  6721. size_t len;
  6722. int truncated = 0;
  6723. if (conn == NULL) {
  6724. return;
  6725. }
  6726. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  6727. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  6728. * always < MG_BUF_LEN. */
  6729. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  6730. /* File name is relative to the webserver root */
  6731. file_name[511] = 0;
  6732. (void)mg_snprintf(conn,
  6733. &truncated,
  6734. path,
  6735. sizeof(path),
  6736. "%s/%s",
  6737. conn->ctx->config[DOCUMENT_ROOT],
  6738. file_name);
  6739. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  6740. /* File name is relative to the webserver working directory
  6741. * or it is absolute system path */
  6742. file_name[511] = 0;
  6743. (void)
  6744. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  6745. } else if (sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1
  6746. || sscanf(tag, " \"%511[^\"]\"", file_name) == 1) {
  6747. /* File name is relative to the currect document */
  6748. file_name[511] = 0;
  6749. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  6750. if (!truncated) {
  6751. if ((p = strrchr(path, '/')) != NULL) {
  6752. p[1] = '\0';
  6753. }
  6754. len = strlen(path);
  6755. (void)mg_snprintf(conn,
  6756. &truncated,
  6757. path + len,
  6758. sizeof(path) - len,
  6759. "%s",
  6760. file_name);
  6761. }
  6762. } else {
  6763. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  6764. return;
  6765. }
  6766. if (truncated) {
  6767. mg_cry(conn, "SSI #include path length overflow: [%s]", tag);
  6768. return;
  6769. }
  6770. if (!mg_fopen(conn, path, "rb", &file)) {
  6771. mg_cry(conn,
  6772. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  6773. tag,
  6774. path,
  6775. strerror(ERRNO));
  6776. } else {
  6777. fclose_on_exec(&file, conn);
  6778. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  6779. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  6780. path) > 0) {
  6781. send_ssi_file(conn, path, &file, include_level + 1);
  6782. } else {
  6783. send_file_data(conn, &file, 0, INT64_MAX);
  6784. }
  6785. mg_fclose(&file);
  6786. }
  6787. }
  6788. #if !defined(NO_POPEN)
  6789. static void
  6790. do_ssi_exec(struct mg_connection *conn, char *tag)
  6791. {
  6792. char cmd[1024] = "";
  6793. struct file file = STRUCT_FILE_INITIALIZER;
  6794. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  6795. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  6796. } else {
  6797. cmd[1023] = 0;
  6798. if ((file.fp = popen(cmd, "r")) == NULL) {
  6799. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  6800. } else {
  6801. send_file_data(conn, &file, 0, INT64_MAX);
  6802. pclose(file.fp);
  6803. }
  6804. }
  6805. }
  6806. #endif /* !NO_POPEN */
  6807. static int
  6808. mg_fgetc(struct file *filep, int offset)
  6809. {
  6810. if (filep == NULL) {
  6811. return EOF;
  6812. }
  6813. if (filep->membuf != NULL && offset >= 0
  6814. && ((unsigned int)(offset)) < filep->size) {
  6815. return ((unsigned char *)filep->membuf)[offset];
  6816. } else if (filep->fp != NULL) {
  6817. return fgetc(filep->fp);
  6818. } else {
  6819. return EOF;
  6820. }
  6821. }
  6822. static void
  6823. send_ssi_file(struct mg_connection *conn,
  6824. const char *path,
  6825. struct file *filep,
  6826. int include_level)
  6827. {
  6828. char buf[MG_BUF_LEN];
  6829. int ch, offset, len, in_ssi_tag;
  6830. if (include_level > 10) {
  6831. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  6832. return;
  6833. }
  6834. in_ssi_tag = len = offset = 0;
  6835. while ((ch = mg_fgetc(filep, offset)) != EOF) {
  6836. if (in_ssi_tag && ch == '>') {
  6837. in_ssi_tag = 0;
  6838. buf[len++] = (char)ch;
  6839. buf[len] = '\0';
  6840. /* assert(len <= (int) sizeof(buf)); */
  6841. if (len > (int)sizeof(buf)) {
  6842. break;
  6843. }
  6844. if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
  6845. /* Not an SSI tag, pass it */
  6846. (void)mg_write(conn, buf, (size_t)len);
  6847. } else {
  6848. if (!memcmp(buf + 5, "include", 7)) {
  6849. do_ssi_include(conn, path, buf + 12, include_level);
  6850. #if !defined(NO_POPEN)
  6851. } else if (!memcmp(buf + 5, "exec", 4)) {
  6852. do_ssi_exec(conn, buf + 9);
  6853. #endif /* !NO_POPEN */
  6854. } else {
  6855. mg_cry(conn,
  6856. "%s: unknown SSI "
  6857. "command: \"%s\"",
  6858. path,
  6859. buf);
  6860. }
  6861. }
  6862. len = 0;
  6863. } else if (in_ssi_tag) {
  6864. if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
  6865. /* Not an SSI tag */
  6866. in_ssi_tag = 0;
  6867. } else if (len == (int)sizeof(buf) - 2) {
  6868. mg_cry(conn, "%s: SSI tag is too large", path);
  6869. len = 0;
  6870. }
  6871. buf[len++] = (char)(ch & 0xff);
  6872. } else if (ch == '<') {
  6873. in_ssi_tag = 1;
  6874. if (len > 0) {
  6875. mg_write(conn, buf, (size_t)len);
  6876. }
  6877. len = 0;
  6878. buf[len++] = (char)(ch & 0xff);
  6879. } else {
  6880. buf[len++] = (char)(ch & 0xff);
  6881. if (len == (int)sizeof(buf)) {
  6882. mg_write(conn, buf, (size_t)len);
  6883. len = 0;
  6884. }
  6885. }
  6886. }
  6887. /* Send the rest of buffered data */
  6888. if (len > 0) {
  6889. mg_write(conn, buf, (size_t)len);
  6890. }
  6891. }
  6892. static void
  6893. handle_ssi_file_request(struct mg_connection *conn,
  6894. const char *path,
  6895. struct file *filep)
  6896. {
  6897. char date[64];
  6898. time_t curtime = time(NULL);
  6899. const char *cors1, *cors2, *cors3;
  6900. if (conn == NULL || path == NULL || filep == NULL) {
  6901. return;
  6902. }
  6903. if (mg_get_header(conn, "Origin")) {
  6904. /* Cross-origin resource sharing (CORS). */
  6905. cors1 = "Access-Control-Allow-Origin: ";
  6906. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  6907. cors3 = "\r\n";
  6908. } else {
  6909. cors1 = cors2 = cors3 = "";
  6910. }
  6911. if (!mg_fopen(conn, path, "rb", filep)) {
  6912. /* File exists (precondition for calling this function),
  6913. * but can not be opened by the server. */
  6914. send_http_error(conn,
  6915. 500,
  6916. "Error: Cannot read file\nfopen(%s): %s",
  6917. path,
  6918. strerror(ERRNO));
  6919. } else {
  6920. conn->must_close = 1;
  6921. gmt_time_string(date, sizeof(date), &curtime);
  6922. fclose_on_exec(filep, conn);
  6923. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  6924. send_no_cache_header(conn);
  6925. mg_printf(conn,
  6926. "%s%s%s"
  6927. "Date: %s\r\n"
  6928. "Content-Type: text/html\r\n"
  6929. "Connection: %s\r\n\r\n",
  6930. cors1,
  6931. cors2,
  6932. cors3,
  6933. date,
  6934. suggest_connection_header(conn));
  6935. send_ssi_file(conn, path, filep, 0);
  6936. mg_fclose(filep);
  6937. }
  6938. }
  6939. #if !defined(NO_FILES)
  6940. static void
  6941. send_options(struct mg_connection *conn)
  6942. {
  6943. char date[64];
  6944. time_t curtime = time(NULL);
  6945. if (!conn) {
  6946. return;
  6947. }
  6948. conn->status_code = 200;
  6949. conn->must_close = 1;
  6950. gmt_time_string(date, sizeof(date), &curtime);
  6951. mg_printf(conn,
  6952. "HTTP/1.1 200 OK\r\n"
  6953. "Date: %s\r\n"
  6954. /* TODO: "Cache-Control" (?) */
  6955. "Connection: %s\r\n"
  6956. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  6957. "PROPFIND, MKCOL\r\n"
  6958. "DAV: 1\r\n\r\n",
  6959. date,
  6960. suggest_connection_header(conn));
  6961. }
  6962. /* Writes PROPFIND properties for a collection element */
  6963. static void
  6964. print_props(struct mg_connection *conn, const char *uri, struct file *filep)
  6965. {
  6966. char mtime[64];
  6967. if (conn == NULL || uri == NULL || filep == NULL) {
  6968. return;
  6969. }
  6970. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  6971. conn->num_bytes_sent +=
  6972. mg_printf(conn,
  6973. "<d:response>"
  6974. "<d:href>%s</d:href>"
  6975. "<d:propstat>"
  6976. "<d:prop>"
  6977. "<d:resourcetype>%s</d:resourcetype>"
  6978. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  6979. "<d:getlastmodified>%s</d:getlastmodified>"
  6980. "</d:prop>"
  6981. "<d:status>HTTP/1.1 200 OK</d:status>"
  6982. "</d:propstat>"
  6983. "</d:response>\n",
  6984. uri,
  6985. filep->is_directory ? "<d:collection/>" : "",
  6986. filep->size,
  6987. mtime);
  6988. }
  6989. static void
  6990. print_dav_dir_entry(struct de *de, void *data)
  6991. {
  6992. char href[PATH_MAX];
  6993. char href_encoded[PATH_MAX];
  6994. int truncated;
  6995. struct mg_connection *conn = (struct mg_connection *)data;
  6996. if (!de || !conn) {
  6997. return;
  6998. }
  6999. mg_snprintf(conn,
  7000. &truncated,
  7001. href,
  7002. sizeof(href),
  7003. "%s%s",
  7004. conn->request_info.local_uri,
  7005. de->file_name);
  7006. if (!truncated) {
  7007. mg_url_encode(href, href_encoded, PATH_MAX - 1);
  7008. print_props(conn, href_encoded, &de->file);
  7009. }
  7010. }
  7011. static void
  7012. handle_propfind(struct mg_connection *conn,
  7013. const char *path,
  7014. struct file *filep)
  7015. {
  7016. const char *depth = mg_get_header(conn, "Depth");
  7017. char date[64];
  7018. time_t curtime = time(NULL);
  7019. gmt_time_string(date, sizeof(date), &curtime);
  7020. if (!conn || !path || !filep || !conn->ctx) {
  7021. return;
  7022. }
  7023. conn->must_close = 1;
  7024. conn->status_code = 207;
  7025. mg_printf(conn,
  7026. "HTTP/1.1 207 Multi-Status\r\n"
  7027. "Date: %s\r\n",
  7028. date);
  7029. send_static_cache_header(conn);
  7030. mg_printf(conn,
  7031. "Connection: %s\r\n"
  7032. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  7033. suggest_connection_header(conn));
  7034. conn->num_bytes_sent +=
  7035. mg_printf(conn,
  7036. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  7037. "<d:multistatus xmlns:d='DAV:'>\n");
  7038. /* Print properties for the requested resource itself */
  7039. print_props(conn, conn->request_info.local_uri, filep);
  7040. /* If it is a directory, print directory entries too if Depth is not 0 */
  7041. if (filep && filep->is_directory
  7042. && !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")
  7043. && (depth == NULL || strcmp(depth, "0") != 0)) {
  7044. scan_directory(conn, path, conn, &print_dav_dir_entry);
  7045. }
  7046. conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");
  7047. }
  7048. #endif
  7049. void
  7050. mg_lock_connection(struct mg_connection *conn)
  7051. {
  7052. if (conn) {
  7053. (void)pthread_mutex_lock(&conn->mutex);
  7054. }
  7055. }
  7056. void
  7057. mg_unlock_connection(struct mg_connection *conn)
  7058. {
  7059. if (conn) {
  7060. (void)pthread_mutex_unlock(&conn->mutex);
  7061. }
  7062. }
  7063. void
  7064. mg_lock_context(struct mg_context *ctx)
  7065. {
  7066. if (ctx) {
  7067. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  7068. }
  7069. }
  7070. void
  7071. mg_unlock_context(struct mg_context *ctx)
  7072. {
  7073. if (ctx) {
  7074. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  7075. }
  7076. }
  7077. #if defined(USE_TIMERS)
  7078. #include "timer.inl"
  7079. #endif /* USE_TIMERS */
  7080. #ifdef USE_LUA
  7081. #include "mod_lua.inl"
  7082. #endif /* USE_LUA */
  7083. #ifdef USE_DUKTAPE
  7084. #include "mod_duktape.inl"
  7085. #endif /* USE_DUKTAPE */
  7086. #if defined(USE_WEBSOCKET)
  7087. /* START OF SHA-1 code
  7088. * Copyright(c) By Steve Reid <steve@edmweb.com> */
  7089. #define SHA1HANDSOFF
  7090. /* According to current tests (May 2015), the <solarisfixes.h> is not required.
  7091. *
  7092. * #if defined(__sun)
  7093. * #include "solarisfixes.h"
  7094. * #endif
  7095. */
  7096. static int
  7097. is_big_endian(void)
  7098. {
  7099. static const int n = 1;
  7100. return ((char *)&n)[0] == 0;
  7101. }
  7102. union char64long16 {
  7103. unsigned char c[64];
  7104. uint32_t l[16];
  7105. };
  7106. #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
  7107. static uint32_t
  7108. blk0(union char64long16 *block, int i)
  7109. {
  7110. /* Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN */
  7111. if (!is_big_endian()) {
  7112. block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00)
  7113. | (rol(block->l[i], 8) & 0x00FF00FF);
  7114. }
  7115. return block->l[i];
  7116. }
  7117. #define blk(i) \
  7118. (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] \
  7119. ^ block->l[(i + 2) & 15] ^ block->l[i & 15], \
  7120. 1))
  7121. #define R0(v, w, x, y, z, i) \
  7122. z += ((w & (x ^ y)) ^ y) + blk0(block, i) + 0x5A827999 + rol(v, 5); \
  7123. w = rol(w, 30);
  7124. #define R1(v, w, x, y, z, i) \
  7125. z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \
  7126. w = rol(w, 30);
  7127. #define R2(v, w, x, y, z, i) \
  7128. z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \
  7129. w = rol(w, 30);
  7130. #define R3(v, w, x, y, z, i) \
  7131. z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \
  7132. w = rol(w, 30);
  7133. #define R4(v, w, x, y, z, i) \
  7134. z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \
  7135. w = rol(w, 30);
  7136. typedef struct {
  7137. uint32_t state[5];
  7138. uint32_t count[2];
  7139. unsigned char buffer[64];
  7140. } SHA1_CTX;
  7141. static void
  7142. SHA1Transform(uint32_t state[5], const unsigned char buffer[64])
  7143. {
  7144. uint32_t a, b, c, d, e;
  7145. union char64long16 block[1];
  7146. memcpy(block, buffer, 64);
  7147. a = state[0];
  7148. b = state[1];
  7149. c = state[2];
  7150. d = state[3];
  7151. e = state[4];
  7152. R0(a, b, c, d, e, 0);
  7153. R0(e, a, b, c, d, 1);
  7154. R0(d, e, a, b, c, 2);
  7155. R0(c, d, e, a, b, 3);
  7156. R0(b, c, d, e, a, 4);
  7157. R0(a, b, c, d, e, 5);
  7158. R0(e, a, b, c, d, 6);
  7159. R0(d, e, a, b, c, 7);
  7160. R0(c, d, e, a, b, 8);
  7161. R0(b, c, d, e, a, 9);
  7162. R0(a, b, c, d, e, 10);
  7163. R0(e, a, b, c, d, 11);
  7164. R0(d, e, a, b, c, 12);
  7165. R0(c, d, e, a, b, 13);
  7166. R0(b, c, d, e, a, 14);
  7167. R0(a, b, c, d, e, 15);
  7168. R1(e, a, b, c, d, 16);
  7169. R1(d, e, a, b, c, 17);
  7170. R1(c, d, e, a, b, 18);
  7171. R1(b, c, d, e, a, 19);
  7172. R2(a, b, c, d, e, 20);
  7173. R2(e, a, b, c, d, 21);
  7174. R2(d, e, a, b, c, 22);
  7175. R2(c, d, e, a, b, 23);
  7176. R2(b, c, d, e, a, 24);
  7177. R2(a, b, c, d, e, 25);
  7178. R2(e, a, b, c, d, 26);
  7179. R2(d, e, a, b, c, 27);
  7180. R2(c, d, e, a, b, 28);
  7181. R2(b, c, d, e, a, 29);
  7182. R2(a, b, c, d, e, 30);
  7183. R2(e, a, b, c, d, 31);
  7184. R2(d, e, a, b, c, 32);
  7185. R2(c, d, e, a, b, 33);
  7186. R2(b, c, d, e, a, 34);
  7187. R2(a, b, c, d, e, 35);
  7188. R2(e, a, b, c, d, 36);
  7189. R2(d, e, a, b, c, 37);
  7190. R2(c, d, e, a, b, 38);
  7191. R2(b, c, d, e, a, 39);
  7192. R3(a, b, c, d, e, 40);
  7193. R3(e, a, b, c, d, 41);
  7194. R3(d, e, a, b, c, 42);
  7195. R3(c, d, e, a, b, 43);
  7196. R3(b, c, d, e, a, 44);
  7197. R3(a, b, c, d, e, 45);
  7198. R3(e, a, b, c, d, 46);
  7199. R3(d, e, a, b, c, 47);
  7200. R3(c, d, e, a, b, 48);
  7201. R3(b, c, d, e, a, 49);
  7202. R3(a, b, c, d, e, 50);
  7203. R3(e, a, b, c, d, 51);
  7204. R3(d, e, a, b, c, 52);
  7205. R3(c, d, e, a, b, 53);
  7206. R3(b, c, d, e, a, 54);
  7207. R3(a, b, c, d, e, 55);
  7208. R3(e, a, b, c, d, 56);
  7209. R3(d, e, a, b, c, 57);
  7210. R3(c, d, e, a, b, 58);
  7211. R3(b, c, d, e, a, 59);
  7212. R4(a, b, c, d, e, 60);
  7213. R4(e, a, b, c, d, 61);
  7214. R4(d, e, a, b, c, 62);
  7215. R4(c, d, e, a, b, 63);
  7216. R4(b, c, d, e, a, 64);
  7217. R4(a, b, c, d, e, 65);
  7218. R4(e, a, b, c, d, 66);
  7219. R4(d, e, a, b, c, 67);
  7220. R4(c, d, e, a, b, 68);
  7221. R4(b, c, d, e, a, 69);
  7222. R4(a, b, c, d, e, 70);
  7223. R4(e, a, b, c, d, 71);
  7224. R4(d, e, a, b, c, 72);
  7225. R4(c, d, e, a, b, 73);
  7226. R4(b, c, d, e, a, 74);
  7227. R4(a, b, c, d, e, 75);
  7228. R4(e, a, b, c, d, 76);
  7229. R4(d, e, a, b, c, 77);
  7230. R4(c, d, e, a, b, 78);
  7231. R4(b, c, d, e, a, 79);
  7232. state[0] += a;
  7233. state[1] += b;
  7234. state[2] += c;
  7235. state[3] += d;
  7236. state[4] += e;
  7237. a = b = c = d = e = 0;
  7238. memset(block, '\0', sizeof(block));
  7239. }
  7240. static void
  7241. SHA1Init(SHA1_CTX *context)
  7242. {
  7243. context->state[0] = 0x67452301;
  7244. context->state[1] = 0xEFCDAB89;
  7245. context->state[2] = 0x98BADCFE;
  7246. context->state[3] = 0x10325476;
  7247. context->state[4] = 0xC3D2E1F0;
  7248. context->count[0] = context->count[1] = 0;
  7249. }
  7250. static void
  7251. SHA1Update(SHA1_CTX *context, const unsigned char *data, uint32_t len)
  7252. {
  7253. uint32_t i, j;
  7254. j = context->count[0];
  7255. if ((context->count[0] += len << 3) < j) {
  7256. context->count[1]++;
  7257. }
  7258. context->count[1] += (len >> 29);
  7259. j = (j >> 3) & 63;
  7260. if ((j + len) > 63) {
  7261. memcpy(&context->buffer[j], data, (i = 64 - j));
  7262. SHA1Transform(context->state, context->buffer);
  7263. for (; i + 63 < len; i += 64) {
  7264. SHA1Transform(context->state, &data[i]);
  7265. }
  7266. j = 0;
  7267. } else
  7268. i = 0;
  7269. memcpy(&context->buffer[j], &data[i], len - i);
  7270. }
  7271. static void
  7272. SHA1Final(unsigned char digest[20], SHA1_CTX *context)
  7273. {
  7274. unsigned i;
  7275. unsigned char finalcount[8], c;
  7276. for (i = 0; i < 8; i++) {
  7277. finalcount[i] = (unsigned char)((context->count[(i >= 4 ? 0 : 1)]
  7278. >> ((3 - (i & 3)) * 8)) & 255);
  7279. }
  7280. c = 0200;
  7281. SHA1Update(context, &c, 1);
  7282. while ((context->count[0] & 504) != 448) {
  7283. c = 0000;
  7284. SHA1Update(context, &c, 1);
  7285. }
  7286. SHA1Update(context, finalcount, 8);
  7287. for (i = 0; i < 20; i++) {
  7288. digest[i] = (unsigned char)((context->state[i >> 2]
  7289. >> ((3 - (i & 3)) * 8)) & 255);
  7290. }
  7291. memset(context, '\0', sizeof(*context));
  7292. memset(&finalcount, '\0', sizeof(finalcount));
  7293. }
  7294. /* END OF SHA1 CODE */
  7295. static int
  7296. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  7297. {
  7298. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  7299. const char *protocol = NULL;
  7300. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  7301. SHA1_CTX sha_ctx;
  7302. int truncated;
  7303. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  7304. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  7305. if (truncated) {
  7306. conn->must_close = 1;
  7307. return 0;
  7308. }
  7309. SHA1Init(&sha_ctx);
  7310. SHA1Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  7311. SHA1Final((unsigned char *)sha, &sha_ctx);
  7312. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  7313. mg_printf(conn,
  7314. "HTTP/1.1 101 Switching Protocols\r\n"
  7315. "Upgrade: websocket\r\n"
  7316. "Connection: Upgrade\r\n"
  7317. "Sec-WebSocket-Accept: %s\r\n",
  7318. b64_sha);
  7319. protocol = mg_get_header(conn, "Sec-WebSocket-Protocol");
  7320. if (protocol) {
  7321. mg_printf(conn, "Sec-WebSocket-Protocol: %s\r\n\r\n", protocol);
  7322. } else {
  7323. mg_printf(conn, "%s", "\r\n");
  7324. }
  7325. return 1;
  7326. }
  7327. static void
  7328. read_websocket(struct mg_connection *conn,
  7329. mg_websocket_data_handler ws_data_handler,
  7330. void *callback_data)
  7331. {
  7332. /* Pointer to the beginning of the portion of the incoming websocket
  7333. * message queue.
  7334. * The original websocket upgrade request is never removed, so the queue
  7335. * begins after it. */
  7336. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  7337. int n, error, exit_by_callback;
  7338. /* body_len is the length of the entire queue in bytes
  7339. * len is the length of the current message
  7340. * data_len is the length of the current message's data payload
  7341. * header_len is the length of the current message's header */
  7342. size_t i, len, mask_len = 0, data_len = 0, header_len, body_len;
  7343. /* "The masking key is a 32-bit value chosen at random by the client."
  7344. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  7345. */
  7346. unsigned char mask[4];
  7347. /* data points to the place where the message is stored when passed to the
  7348. * websocket_data callback. This is either mem on the stack, or a
  7349. * dynamically allocated buffer if it is too large. */
  7350. char mem[4096];
  7351. char *data = mem;
  7352. unsigned char mop; /* mask flag and opcode */
  7353. double timeout = -1.0;
  7354. if (conn->ctx->config[WEBSOCKET_TIMEOUT]) {
  7355. timeout = atoi(conn->ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  7356. }
  7357. if ((timeout <= 0.0) && (conn->ctx->config[REQUEST_TIMEOUT])) {
  7358. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  7359. }
  7360. mg_set_thread_name("wsock");
  7361. /* Loop continuously, reading messages from the socket, invoking the
  7362. * callback, and waiting repeatedly until an error occurs. */
  7363. while (!conn->ctx->stop_flag) {
  7364. header_len = 0;
  7365. assert(conn->data_len >= conn->request_len);
  7366. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  7367. len = buf[1] & 127;
  7368. mask_len = buf[1] & 128 ? 4 : 0;
  7369. if (len < 126 && body_len >= mask_len) {
  7370. data_len = len;
  7371. header_len = 2 + mask_len;
  7372. } else if (len == 126 && body_len >= 4 + mask_len) {
  7373. header_len = 4 + mask_len;
  7374. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  7375. } else if (body_len >= 10 + mask_len) {
  7376. header_len = 10 + mask_len;
  7377. data_len = (((uint64_t)ntohl(*(uint32_t *)(void *)&buf[2]))
  7378. << 32) + ntohl(*(uint32_t *)(void *)&buf[6]);
  7379. }
  7380. }
  7381. if (header_len > 0 && body_len >= header_len) {
  7382. /* Allocate space to hold websocket payload */
  7383. data = mem;
  7384. if (data_len > sizeof(mem)) {
  7385. data = (char *)mg_malloc(data_len);
  7386. if (data == NULL) {
  7387. /* Allocation failed, exit the loop and then close the
  7388. * connection */
  7389. mg_cry(conn, "websocket out of memory; closing connection");
  7390. break;
  7391. }
  7392. }
  7393. /* Copy the mask before we shift the queue and destroy it */
  7394. if (mask_len > 0) {
  7395. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  7396. } else {
  7397. memset(mask, 0, sizeof(mask));
  7398. }
  7399. /* Read frame payload from the first message in the queue into
  7400. * data and advance the queue by moving the memory in place. */
  7401. assert(body_len >= header_len);
  7402. if (data_len + header_len > body_len) {
  7403. mop = buf[0]; /* current mask and opcode */
  7404. /* Overflow case */
  7405. len = body_len - header_len;
  7406. memcpy(data, buf + header_len, len);
  7407. error = 0;
  7408. while (len < data_len) {
  7409. n = pull(
  7410. NULL, conn, data + len, (int)(data_len - len), timeout);
  7411. if (n <= 0) {
  7412. error = 1;
  7413. break;
  7414. }
  7415. len += (size_t)n;
  7416. }
  7417. if (error) {
  7418. mg_cry(conn, "Websocket pull failed; closing connection");
  7419. break;
  7420. }
  7421. conn->data_len = conn->request_len;
  7422. } else {
  7423. mop = buf[0]; /* current mask and opcode, overwritten by
  7424. * memmove() */
  7425. /* Length of the message being read at the front of the
  7426. * queue */
  7427. len = data_len + header_len;
  7428. /* Copy the data payload into the data pointer for the
  7429. * callback */
  7430. memcpy(data, buf + header_len, data_len);
  7431. /* Move the queue forward len bytes */
  7432. memmove(buf, buf + len, body_len - len);
  7433. /* Mark the queue as advanced */
  7434. conn->data_len -= (int)len;
  7435. }
  7436. /* Apply mask if necessary */
  7437. if (mask_len > 0) {
  7438. for (i = 0; i < data_len; ++i) {
  7439. data[i] ^= mask[i & 3];
  7440. }
  7441. }
  7442. /* Exit the loop if callback signals to exit (server side),
  7443. * or "connection close" opcode received (client side). */
  7444. exit_by_callback = 0;
  7445. if ((ws_data_handler != NULL)
  7446. && !ws_data_handler(conn, mop, data, data_len, callback_data)) {
  7447. exit_by_callback = 1;
  7448. }
  7449. if (data != mem) {
  7450. mg_free(data);
  7451. }
  7452. if (exit_by_callback
  7453. || ((mop & 0xf) == WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  7454. /* Opcode == 8, connection close */
  7455. break;
  7456. }
  7457. /* Not breaking the loop, process next websocket frame. */
  7458. } else {
  7459. /* Read from the socket into the next available location in the
  7460. * message queue. */
  7461. if ((n = pull(NULL,
  7462. conn,
  7463. conn->buf + conn->data_len,
  7464. conn->buf_size - conn->data_len,
  7465. timeout)) <= 0) {
  7466. /* Error, no bytes read */
  7467. break;
  7468. }
  7469. conn->data_len += n;
  7470. }
  7471. }
  7472. mg_set_thread_name("worker");
  7473. }
  7474. static int
  7475. mg_websocket_write_exec(struct mg_connection *conn,
  7476. int opcode,
  7477. const char *data,
  7478. size_t dataLen,
  7479. uint32_t masking_key)
  7480. {
  7481. unsigned char header[14];
  7482. size_t headerLen = 1;
  7483. int retval = -1;
  7484. header[0] = 0x80 + (opcode & 0xF);
  7485. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  7486. if (dataLen < 126) {
  7487. /* inline 7-bit length field */
  7488. header[1] = (unsigned char)dataLen;
  7489. headerLen = 2;
  7490. } else if (dataLen <= 0xFFFF) {
  7491. /* 16-bit length field */
  7492. header[1] = 126;
  7493. *(uint16_t *)(void *)(header + 2) = htons((uint16_t)dataLen);
  7494. headerLen = 4;
  7495. } else {
  7496. /* 64-bit length field */
  7497. header[1] = 127;
  7498. *(uint32_t *)(void *)(header + 2) = htonl((uint64_t)dataLen >> 32);
  7499. *(uint32_t *)(void *)(header + 6) = htonl(dataLen & 0xFFFFFFFF);
  7500. headerLen = 10;
  7501. }
  7502. if (masking_key) {
  7503. /* add mask */
  7504. header[1] |= 0x80;
  7505. *(uint32_t *)(void *)(header + headerLen) = masking_key;
  7506. headerLen += 4;
  7507. }
  7508. /* Note that POSIX/Winsock's send() is threadsafe
  7509. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  7510. * but mongoose's mg_printf/mg_write is not (because of the loop in
  7511. * push(), although that is only a problem if the packet is large or
  7512. * outgoing buffer is full). */
  7513. (void)mg_lock_connection(conn);
  7514. retval = mg_write(conn, header, headerLen);
  7515. if (dataLen > 0) {
  7516. retval = mg_write(conn, data, dataLen);
  7517. }
  7518. mg_unlock_connection(conn);
  7519. return retval;
  7520. }
  7521. int
  7522. mg_websocket_write(struct mg_connection *conn,
  7523. int opcode,
  7524. const char *data,
  7525. size_t dataLen)
  7526. {
  7527. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  7528. }
  7529. static void
  7530. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  7531. {
  7532. size_t i = 0;
  7533. i = 0;
  7534. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  7535. /* Convert in 32 bit words, if data is 4 byte aligned */
  7536. while (i < (in_len - 3)) {
  7537. *(uint32_t *)(void *)(out + i) =
  7538. *(uint32_t *)(void *)(in + i) ^ masking_key;
  7539. i += 4;
  7540. }
  7541. }
  7542. if (i != in_len) {
  7543. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  7544. while (i < in_len) {
  7545. *(uint8_t *)(void *)(out + i) =
  7546. *(uint8_t *)(void *)(in + i)
  7547. ^ *(((uint8_t *)&masking_key) + (i % 4));
  7548. i++;
  7549. }
  7550. }
  7551. }
  7552. int
  7553. mg_websocket_client_write(struct mg_connection *conn,
  7554. int opcode,
  7555. const char *data,
  7556. size_t dataLen)
  7557. {
  7558. int retval = -1;
  7559. char *masked_data = (char *)mg_malloc(((dataLen + 7) / 4) * 4);
  7560. uint32_t masking_key = (uint32_t)get_random();
  7561. if (masked_data == NULL) {
  7562. /* Return -1 in an error case */
  7563. mg_cry(conn,
  7564. "Cannot allocate buffer for masked websocket response: "
  7565. "Out of memory");
  7566. return -1;
  7567. }
  7568. mask_data(data, dataLen, masking_key, masked_data);
  7569. retval = mg_websocket_write_exec(
  7570. conn, opcode, masked_data, dataLen, masking_key);
  7571. mg_free(masked_data);
  7572. return retval;
  7573. }
  7574. static void
  7575. handle_websocket_request(struct mg_connection *conn,
  7576. const char *path,
  7577. int is_callback_resource,
  7578. mg_websocket_connect_handler ws_connect_handler,
  7579. mg_websocket_ready_handler ws_ready_handler,
  7580. mg_websocket_data_handler ws_data_handler,
  7581. mg_websocket_close_handler ws_close_handler,
  7582. void *cbData)
  7583. {
  7584. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  7585. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  7586. int lua_websock = 0;
  7587. #if !defined(USE_LUA)
  7588. (void)path;
  7589. #endif
  7590. /* Step 1: Check websocket protocol version. */
  7591. /* Step 1.1: Check Sec-WebSocket-Key. */
  7592. if (!websock_key) {
  7593. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  7594. * requires a Sec-WebSocket-Key header.
  7595. */
  7596. /* It could be the hixie draft version
  7597. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  7598. */
  7599. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  7600. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  7601. char key3[8];
  7602. if ((key1 != NULL) && (key2 != NULL)) {
  7603. /* This version uses 8 byte body data in a GET request */
  7604. conn->content_len = 8;
  7605. if (8 == mg_read(conn, key3, 8)) {
  7606. /* This is the hixie version */
  7607. send_http_error(conn,
  7608. 426,
  7609. "%s",
  7610. "Protocol upgrade to RFC 6455 required");
  7611. return;
  7612. }
  7613. }
  7614. /* This is an unknown version */
  7615. send_http_error(conn, 400, "%s", "Malformed websocket request");
  7616. return;
  7617. }
  7618. /* Step 1.2: Check websocket protocol version. */
  7619. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  7620. if (version == NULL || strcmp(version, "13") != 0) {
  7621. /* Reject wrong versions */
  7622. send_http_error(conn, 426, "%s", "Protocol upgrade required");
  7623. return;
  7624. }
  7625. /* Step 1.3: Could check for "Host", but we do not really nead this
  7626. * value for anything, so just ignore it. */
  7627. /* Step 2: If a callback is responsible, call it. */
  7628. if (is_callback_resource) {
  7629. if (ws_connect_handler != NULL
  7630. && ws_connect_handler(conn, cbData) != 0) {
  7631. /* C callback has returned non-zero, do not proceed with
  7632. * handshake.
  7633. */
  7634. /* Note that C callbacks are no longer called when Lua is
  7635. * responsible, so C can no longer filter callbacks for Lua. */
  7636. return;
  7637. }
  7638. }
  7639. #if defined(USE_LUA)
  7640. /* Step 3: No callback. Check if Lua is responsible. */
  7641. else {
  7642. /* Step 3.1: Check if Lua is responsible. */
  7643. if (conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  7644. lua_websock =
  7645. match_prefix(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  7646. strlen(
  7647. conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  7648. path);
  7649. }
  7650. if (lua_websock) {
  7651. /* Step 3.2: Lua is responsible: call it. */
  7652. conn->lua_websocket_state = lua_websocket_new(path, conn);
  7653. if (!conn->lua_websocket_state) {
  7654. /* Lua rejected the new client */
  7655. return;
  7656. }
  7657. }
  7658. }
  7659. #endif
  7660. /* Step 4: Check if there is a responsible websocket handler. */
  7661. if (!is_callback_resource && !lua_websock) {
  7662. /* There is no callback, an Lua is not responsible either. */
  7663. /* Reply with a 404 Not Found or with nothing at all?
  7664. * TODO (mid): check the websocket standards, how to reply to
  7665. * requests to invalid websocket addresses. */
  7666. send_http_error(conn, 404, "%s", "Not found");
  7667. return;
  7668. }
  7669. /* Step 5: The websocket connection has been accepted */
  7670. if (!send_websocket_handshake(conn, websock_key)) {
  7671. send_http_error(conn, 500, "%s", "Websocket handshake failed");
  7672. return;
  7673. }
  7674. /* Step 6: Call the ready handler */
  7675. if (is_callback_resource) {
  7676. if (ws_ready_handler != NULL) {
  7677. ws_ready_handler(conn, cbData);
  7678. }
  7679. #if defined(USE_LUA)
  7680. } else if (lua_websock) {
  7681. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  7682. /* the ready handler returned false */
  7683. return;
  7684. }
  7685. #endif
  7686. }
  7687. /* Step 7: Enter the read loop */
  7688. if (is_callback_resource) {
  7689. read_websocket(conn, ws_data_handler, cbData);
  7690. #if defined(USE_LUA)
  7691. } else if (lua_websock) {
  7692. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  7693. #endif
  7694. }
  7695. /* Step 8: Call the close handler */
  7696. if (ws_close_handler) {
  7697. ws_close_handler(conn, cbData);
  7698. }
  7699. }
  7700. static int
  7701. is_websocket_protocol(const struct mg_connection *conn)
  7702. {
  7703. const char *upgrade, *connection;
  7704. /* A websocket protocoll has the following HTTP headers:
  7705. *
  7706. * Connection: Upgrade
  7707. * Upgrade: Websocket
  7708. */
  7709. upgrade = mg_get_header(conn, "Upgrade");
  7710. if (upgrade == NULL) {
  7711. return 0; /* fail early, don't waste time checking other header
  7712. * fields
  7713. */
  7714. }
  7715. if (!mg_strcasestr(upgrade, "websocket")) {
  7716. return 0;
  7717. }
  7718. connection = mg_get_header(conn, "Connection");
  7719. if (connection == NULL) {
  7720. return 0;
  7721. }
  7722. if (!mg_strcasestr(connection, "upgrade")) {
  7723. return 0;
  7724. }
  7725. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  7726. * "Sec-WebSocket-Version" are also required.
  7727. * Don't check them here, since even an unsupported websocket protocol
  7728. * request still IS a websocket request (in contrast to a standard HTTP
  7729. * request). It will fail later in handle_websocket_request.
  7730. */
  7731. return 1;
  7732. }
  7733. #endif /* !USE_WEBSOCKET */
  7734. static int
  7735. isbyte(int n)
  7736. {
  7737. return n >= 0 && n <= 255;
  7738. }
  7739. static int
  7740. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  7741. {
  7742. int n, a, b, c, d, slash = 32, len = 0;
  7743. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5
  7744. || sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) && isbyte(a)
  7745. && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0
  7746. && slash < 33) {
  7747. len = n;
  7748. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  7749. | (uint32_t)d;
  7750. *mask = slash ? 0xffffffffU << (32 - slash) : 0;
  7751. }
  7752. return len;
  7753. }
  7754. static int
  7755. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  7756. {
  7757. int throttle = 0;
  7758. struct vec vec, val;
  7759. uint32_t net, mask;
  7760. char mult;
  7761. double v;
  7762. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  7763. mult = ',';
  7764. if (sscanf(val.ptr, "%lf%c", &v, &mult) < 1 || v < 0
  7765. || (lowercase(&mult) != 'k' && lowercase(&mult) != 'm'
  7766. && mult != ',')) {
  7767. continue;
  7768. }
  7769. v *= lowercase(&mult) == 'k' ? 1024 : lowercase(&mult) == 'm' ? 1048576
  7770. : 1;
  7771. if (vec.len == 1 && vec.ptr[0] == '*') {
  7772. throttle = (int)v;
  7773. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  7774. if ((remote_ip & mask) == net) {
  7775. throttle = (int)v;
  7776. }
  7777. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  7778. throttle = (int)v;
  7779. }
  7780. }
  7781. return throttle;
  7782. }
  7783. static uint32_t
  7784. get_remote_ip(const struct mg_connection *conn)
  7785. {
  7786. if (!conn) {
  7787. return 0;
  7788. }
  7789. return ntohl(*(uint32_t *)&conn->client.rsa.sin.sin_addr);
  7790. }
  7791. /* Experimental replacement for mg_upload. */
  7792. #include "handle_form.inl"
  7793. /* Replacement for mg_upload (Note: mg_upload is deprecated) */
  7794. struct mg_upload_user_data {
  7795. struct mg_connection *conn;
  7796. const char *destination_dir;
  7797. int num_uploaded_files;
  7798. };
  7799. /* Helper function for deprecated mg_upload. */
  7800. static int
  7801. mg_upload_field_found(const char *key,
  7802. const char *filename,
  7803. char *path,
  7804. size_t pathlen,
  7805. void *user_data)
  7806. {
  7807. int truncated = 0;
  7808. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  7809. (void)key;
  7810. if (!filename) {
  7811. mg_cry(fud->conn, "%s: No filename set", __func__);
  7812. return FORM_FIELD_STORAGE_ABORT;
  7813. }
  7814. mg_snprintf(fud->conn,
  7815. &truncated,
  7816. path,
  7817. pathlen - 1,
  7818. "%s/%s",
  7819. fud->destination_dir,
  7820. filename);
  7821. if (!truncated) {
  7822. mg_cry(fud->conn, "%s: File path too long", __func__);
  7823. return FORM_FIELD_STORAGE_ABORT;
  7824. }
  7825. return FORM_FIELD_STORAGE_STORE;
  7826. }
  7827. /* Helper function for deprecated mg_upload. */
  7828. static int
  7829. mg_upload_field_get(const char *key,
  7830. const char *value,
  7831. size_t value_size,
  7832. void *user_data)
  7833. {
  7834. /* Function should never be called */
  7835. (void)key;
  7836. (void)value;
  7837. (void)value_size;
  7838. (void)user_data;
  7839. return 0;
  7840. }
  7841. /* Helper function for deprecated mg_upload. */
  7842. static int
  7843. mg_upload_field_stored(const char *path, size_t file_size, void *user_data)
  7844. {
  7845. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  7846. (void)file_size;
  7847. fud->num_uploaded_files++;
  7848. fud->conn->ctx->callbacks.upload(fud->conn, path);
  7849. return 0;
  7850. }
  7851. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  7852. int
  7853. mg_upload(struct mg_connection *conn, const char *destination_dir)
  7854. {
  7855. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  7856. struct mg_form_data_handler fdh = {mg_upload_field_found,
  7857. mg_upload_field_get,
  7858. mg_upload_field_stored,
  7859. 0};
  7860. int ret;
  7861. fdh.user_data = (void *)&fud;
  7862. ret = mg_handle_form_request(conn, &fdh);
  7863. if (ret < 0) {
  7864. mg_cry(conn, "%s: Error while parsing the request", __func__);
  7865. }
  7866. return fud.num_uploaded_files;
  7867. }
  7868. static int
  7869. get_first_ssl_listener_index(const struct mg_context *ctx)
  7870. {
  7871. unsigned int i;
  7872. int idx = -1;
  7873. if (ctx) {
  7874. for (i = 0; idx == -1 && i < ctx->num_listening_sockets; i++) {
  7875. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  7876. }
  7877. }
  7878. return idx;
  7879. }
  7880. static void
  7881. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  7882. {
  7883. char host[1025];
  7884. const char *host_header;
  7885. size_t hostlen;
  7886. host_header = mg_get_header(conn, "Host");
  7887. hostlen = sizeof(host);
  7888. if (host_header != NULL) {
  7889. char *pos;
  7890. mg_strlcpy(host, host_header, hostlen);
  7891. host[hostlen - 1] = '\0';
  7892. pos = strchr(host, ':');
  7893. if (pos != NULL) {
  7894. *pos = '\0';
  7895. }
  7896. } else {
  7897. /* Cannot get host from the Host: header.
  7898. * Fallback to our IP address. */
  7899. if (conn) {
  7900. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  7901. }
  7902. }
  7903. /* Send host, port, uri and (if it exists) ?query_string */
  7904. if (conn) {
  7905. mg_printf(conn,
  7906. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  7907. host,
  7908. (int)ntohs(
  7909. conn->ctx->listening_sockets[ssl_index].lsa.sin.sin_port),
  7910. conn->request_info.local_uri,
  7911. (conn->request_info.query_string == NULL) ? "" : "?",
  7912. (conn->request_info.query_string == NULL)
  7913. ? ""
  7914. : conn->request_info.query_string);
  7915. }
  7916. }
  7917. static void
  7918. mg_set_handler_type(struct mg_context *ctx,
  7919. const char *uri,
  7920. int handler_type,
  7921. int is_delete_request,
  7922. mg_request_handler handler,
  7923. mg_websocket_connect_handler connect_handler,
  7924. mg_websocket_ready_handler ready_handler,
  7925. mg_websocket_data_handler data_handler,
  7926. mg_websocket_close_handler close_handler,
  7927. mg_authorization_handler auth_handler,
  7928. void *cbdata)
  7929. {
  7930. struct mg_handler_info *tmp_rh, **lastref;
  7931. size_t urilen = strlen(uri);
  7932. if (handler_type == WEBSOCKET_HANDLER) {
  7933. /* assert(handler == NULL); */
  7934. /* assert(is_delete_request || connect_handler!=NULL ||
  7935. * ready_handler!=NULL || data_handler!=NULL ||
  7936. * close_handler!=NULL);
  7937. */
  7938. /* assert(auth_handler == NULL); */
  7939. if (handler != NULL) {
  7940. return;
  7941. }
  7942. if (!is_delete_request && connect_handler == NULL
  7943. && ready_handler == NULL
  7944. && data_handler == NULL
  7945. && close_handler == NULL) {
  7946. return;
  7947. }
  7948. if (auth_handler != NULL) {
  7949. return;
  7950. }
  7951. } else if (handler_type == REQUEST_HANDLER) {
  7952. /* assert(connect_handler==NULL && ready_handler==NULL &&
  7953. * data_handler==NULL && close_handler==NULL); */
  7954. /* assert(is_delete_request || (handler!=NULL));
  7955. */
  7956. /* assert(auth_handler == NULL); */
  7957. if (connect_handler != NULL || ready_handler != NULL
  7958. || data_handler != NULL
  7959. || close_handler != NULL) {
  7960. return;
  7961. }
  7962. if (!is_delete_request && (handler == NULL)) {
  7963. return;
  7964. }
  7965. if (auth_handler != NULL) {
  7966. return;
  7967. }
  7968. } else { /* AUTH_HANDLER */
  7969. /* assert(handler == NULL); */
  7970. /* assert(connect_handler==NULL && ready_handler==NULL &&
  7971. * data_handler==NULL && close_handler==NULL); */
  7972. /* assert(auth_handler != NULL); */
  7973. if (handler != NULL) {
  7974. return;
  7975. }
  7976. if (connect_handler != NULL || ready_handler != NULL
  7977. || data_handler != NULL
  7978. || close_handler != NULL) {
  7979. return;
  7980. }
  7981. if (!is_delete_request && (auth_handler == NULL)) {
  7982. return;
  7983. }
  7984. }
  7985. if (!ctx) {
  7986. return;
  7987. }
  7988. mg_lock_context(ctx);
  7989. /* first try to find an existing handler */
  7990. lastref = &(ctx->handlers);
  7991. for (tmp_rh = ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  7992. if (tmp_rh->handler_type == handler_type) {
  7993. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  7994. if (!is_delete_request) {
  7995. /* update existing handler */
  7996. if (handler_type == REQUEST_HANDLER) {
  7997. tmp_rh->handler = handler;
  7998. } else if (handler_type == WEBSOCKET_HANDLER) {
  7999. tmp_rh->connect_handler = connect_handler;
  8000. tmp_rh->ready_handler = ready_handler;
  8001. tmp_rh->data_handler = data_handler;
  8002. tmp_rh->close_handler = close_handler;
  8003. } else { /* AUTH_HANDLER */
  8004. tmp_rh->auth_handler = auth_handler;
  8005. }
  8006. tmp_rh->cbdata = cbdata;
  8007. } else {
  8008. /* remove existing handler */
  8009. *lastref = tmp_rh->next;
  8010. mg_free(tmp_rh->uri);
  8011. mg_free(tmp_rh);
  8012. }
  8013. mg_unlock_context(ctx);
  8014. return;
  8015. }
  8016. }
  8017. lastref = &(tmp_rh->next);
  8018. }
  8019. if (is_delete_request) {
  8020. /* no handler to set, this was a remove request to a non-existing
  8021. * handler */
  8022. mg_unlock_context(ctx);
  8023. return;
  8024. }
  8025. tmp_rh =
  8026. (struct mg_handler_info *)mg_calloc(sizeof(struct mg_handler_info), 1);
  8027. if (tmp_rh == NULL) {
  8028. mg_unlock_context(ctx);
  8029. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  8030. return;
  8031. }
  8032. tmp_rh->uri = mg_strdup(uri);
  8033. if (!tmp_rh->uri) {
  8034. mg_unlock_context(ctx);
  8035. mg_free(tmp_rh);
  8036. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  8037. return;
  8038. }
  8039. tmp_rh->uri_len = urilen;
  8040. if (handler_type == REQUEST_HANDLER) {
  8041. tmp_rh->handler = handler;
  8042. } else if (handler_type == WEBSOCKET_HANDLER) {
  8043. tmp_rh->connect_handler = connect_handler;
  8044. tmp_rh->ready_handler = ready_handler;
  8045. tmp_rh->data_handler = data_handler;
  8046. tmp_rh->close_handler = close_handler;
  8047. } else { /* AUTH_HANDLER */
  8048. tmp_rh->auth_handler = auth_handler;
  8049. }
  8050. tmp_rh->cbdata = cbdata;
  8051. tmp_rh->handler_type = handler_type;
  8052. tmp_rh->next = NULL;
  8053. *lastref = tmp_rh;
  8054. mg_unlock_context(ctx);
  8055. }
  8056. void
  8057. mg_set_request_handler(struct mg_context *ctx,
  8058. const char *uri,
  8059. mg_request_handler handler,
  8060. void *cbdata)
  8061. {
  8062. mg_set_handler_type(ctx,
  8063. uri,
  8064. REQUEST_HANDLER,
  8065. handler == NULL,
  8066. handler,
  8067. NULL,
  8068. NULL,
  8069. NULL,
  8070. NULL,
  8071. NULL,
  8072. cbdata);
  8073. }
  8074. void
  8075. mg_set_websocket_handler(struct mg_context *ctx,
  8076. const char *uri,
  8077. mg_websocket_connect_handler connect_handler,
  8078. mg_websocket_ready_handler ready_handler,
  8079. mg_websocket_data_handler data_handler,
  8080. mg_websocket_close_handler close_handler,
  8081. void *cbdata)
  8082. {
  8083. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  8084. && (data_handler == NULL)
  8085. && (close_handler == NULL);
  8086. mg_set_handler_type(ctx,
  8087. uri,
  8088. WEBSOCKET_HANDLER,
  8089. is_delete_request,
  8090. NULL,
  8091. connect_handler,
  8092. ready_handler,
  8093. data_handler,
  8094. close_handler,
  8095. NULL,
  8096. cbdata);
  8097. }
  8098. void
  8099. mg_set_auth_handler(struct mg_context *ctx,
  8100. const char *uri,
  8101. mg_request_handler handler,
  8102. void *cbdata)
  8103. {
  8104. mg_set_handler_type(ctx,
  8105. uri,
  8106. AUTH_HANDLER,
  8107. handler == NULL,
  8108. NULL,
  8109. NULL,
  8110. NULL,
  8111. NULL,
  8112. NULL,
  8113. handler,
  8114. cbdata);
  8115. }
  8116. static int
  8117. get_request_handler(struct mg_connection *conn,
  8118. int handler_type,
  8119. mg_request_handler *handler,
  8120. mg_websocket_connect_handler *connect_handler,
  8121. mg_websocket_ready_handler *ready_handler,
  8122. mg_websocket_data_handler *data_handler,
  8123. mg_websocket_close_handler *close_handler,
  8124. mg_authorization_handler *auth_handler,
  8125. void **cbdata)
  8126. {
  8127. const struct mg_request_info *request_info = mg_get_request_info(conn);
  8128. if (request_info) {
  8129. const char *uri = request_info->local_uri;
  8130. size_t urilen = strlen(uri);
  8131. struct mg_handler_info *tmp_rh;
  8132. if (!conn || !conn->ctx) {
  8133. return 0;
  8134. }
  8135. mg_lock_context(conn->ctx);
  8136. /* first try for an exact match */
  8137. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8138. tmp_rh = tmp_rh->next) {
  8139. if (tmp_rh->handler_type == handler_type) {
  8140. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  8141. if (handler_type == WEBSOCKET_HANDLER) {
  8142. *connect_handler = tmp_rh->connect_handler;
  8143. *ready_handler = tmp_rh->ready_handler;
  8144. *data_handler = tmp_rh->data_handler;
  8145. *close_handler = tmp_rh->close_handler;
  8146. } else if (handler_type == REQUEST_HANDLER) {
  8147. *handler = tmp_rh->handler;
  8148. } else { /* AUTH_HANDLER */
  8149. *auth_handler = tmp_rh->auth_handler;
  8150. }
  8151. *cbdata = tmp_rh->cbdata;
  8152. mg_unlock_context(conn->ctx);
  8153. return 1;
  8154. }
  8155. }
  8156. }
  8157. /* next try for a partial match, we will accept uri/something */
  8158. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8159. tmp_rh = tmp_rh->next) {
  8160. if (tmp_rh->handler_type == handler_type) {
  8161. if (tmp_rh->uri_len < urilen && uri[tmp_rh->uri_len] == '/'
  8162. && memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0) {
  8163. if (handler_type == WEBSOCKET_HANDLER) {
  8164. *connect_handler = tmp_rh->connect_handler;
  8165. *ready_handler = tmp_rh->ready_handler;
  8166. *data_handler = tmp_rh->data_handler;
  8167. *close_handler = tmp_rh->close_handler;
  8168. } else if (handler_type == REQUEST_HANDLER) {
  8169. *handler = tmp_rh->handler;
  8170. } else { /* AUTH_HANDLER */
  8171. *auth_handler = tmp_rh->auth_handler;
  8172. }
  8173. *cbdata = tmp_rh->cbdata;
  8174. mg_unlock_context(conn->ctx);
  8175. return 1;
  8176. }
  8177. }
  8178. }
  8179. /* finally try for pattern match */
  8180. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8181. tmp_rh = tmp_rh->next) {
  8182. if (tmp_rh->handler_type == handler_type) {
  8183. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  8184. if (handler_type == WEBSOCKET_HANDLER) {
  8185. *connect_handler = tmp_rh->connect_handler;
  8186. *ready_handler = tmp_rh->ready_handler;
  8187. *data_handler = tmp_rh->data_handler;
  8188. *close_handler = tmp_rh->close_handler;
  8189. } else if (handler_type == REQUEST_HANDLER) {
  8190. *handler = tmp_rh->handler;
  8191. } else { /* AUTH_HANDLER */
  8192. *auth_handler = tmp_rh->auth_handler;
  8193. }
  8194. *cbdata = tmp_rh->cbdata;
  8195. mg_unlock_context(conn->ctx);
  8196. return 1;
  8197. }
  8198. }
  8199. }
  8200. mg_unlock_context(conn->ctx);
  8201. }
  8202. return 0; /* none found */
  8203. }
  8204. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  8205. static int
  8206. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  8207. void *cbdata)
  8208. {
  8209. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  8210. if (pcallbacks->websocket_connect) {
  8211. return pcallbacks->websocket_connect(conn);
  8212. }
  8213. /* No handler set - assume "OK" */
  8214. return 0;
  8215. }
  8216. static void
  8217. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  8218. {
  8219. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  8220. if (pcallbacks->websocket_ready) {
  8221. pcallbacks->websocket_ready(conn);
  8222. }
  8223. }
  8224. static int
  8225. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  8226. int bits,
  8227. char *data,
  8228. size_t len,
  8229. void *cbdata)
  8230. {
  8231. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  8232. if (pcallbacks->websocket_data) {
  8233. return pcallbacks->websocket_data(conn, bits, data, len);
  8234. }
  8235. /* No handler set - assume "OK" */
  8236. return 1;
  8237. }
  8238. #endif
  8239. /* This is the heart of the Civetweb's logic.
  8240. * This function is called when the request is read, parsed and validated,
  8241. * and Civetweb must decide what action to take: serve a file, or
  8242. * a directory, or call embedded function, etcetera. */
  8243. static void
  8244. handle_request(struct mg_connection *conn)
  8245. {
  8246. if (conn) {
  8247. struct mg_request_info *ri = &conn->request_info;
  8248. char path[PATH_MAX];
  8249. int uri_len, ssl_index;
  8250. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  8251. is_put_or_delete_request = 0, is_callback_resource = 0;
  8252. int i;
  8253. struct file file = STRUCT_FILE_INITIALIZER;
  8254. mg_request_handler callback_handler = NULL;
  8255. mg_websocket_connect_handler ws_connect_handler = NULL;
  8256. mg_websocket_ready_handler ws_ready_handler = NULL;
  8257. mg_websocket_data_handler ws_data_handler = NULL;
  8258. mg_websocket_close_handler ws_close_handler = NULL;
  8259. void *callback_data = NULL;
  8260. mg_authorization_handler auth_handler = NULL;
  8261. void *auth_callback_data = NULL;
  8262. #if !defined(NO_FILES)
  8263. time_t curtime = time(NULL);
  8264. char date[64];
  8265. #endif
  8266. path[0] = 0;
  8267. if (!ri) {
  8268. return;
  8269. }
  8270. /* 1. get the request url */
  8271. /* 1.1. split into url and query string */
  8272. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  8273. != NULL) {
  8274. *((char *)conn->request_info.query_string++) = '\0';
  8275. }
  8276. uri_len = (int)strlen(ri->local_uri);
  8277. /* 1.2. decode url (if config says so) */
  8278. if (should_decode_url(conn)) {
  8279. mg_url_decode(
  8280. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  8281. }
  8282. /* 1.3. clean URIs, so a path like allowed_dir/../forbidden_file is
  8283. * not
  8284. * possible */
  8285. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  8286. /* step 1. completed, the url is known now */
  8287. DEBUG_TRACE("URL: %s", ri->local_uri);
  8288. /* 2. do a https redirect, if required */
  8289. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  8290. ssl_index = get_first_ssl_listener_index(conn->ctx);
  8291. if (ssl_index >= 0) {
  8292. redirect_to_https_port(conn, ssl_index);
  8293. } else {
  8294. /* A http to https forward port has been specified,
  8295. * but no https port to forward to. */
  8296. send_http_error(conn,
  8297. 503,
  8298. "%s",
  8299. "Error: SSL forward not configured properly");
  8300. mg_cry(conn, "Can not redirect to SSL, no SSL port available");
  8301. }
  8302. return;
  8303. }
  8304. /* 3. if this ip has limited speed, set it for this connection */
  8305. conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
  8306. get_remote_ip(conn),
  8307. ri->local_uri);
  8308. /* 4. call a "handle everything" callback, if registered */
  8309. if (conn->ctx->callbacks.begin_request != NULL) {
  8310. /* Note that since V1.7 the "begin_request" function is called
  8311. * before an authorization check. If an authorization check is
  8312. * required, use a request_handler instead. */
  8313. i = conn->ctx->callbacks.begin_request(conn);
  8314. if (i > 0) {
  8315. /* callback already processed the request. Store the
  8316. return value as a status code for the access log. */
  8317. conn->status_code = i;
  8318. return;
  8319. } else if (i == 0) {
  8320. /* civetweb should process the request */
  8321. } else {
  8322. /* unspecified - may change with the next version */
  8323. return;
  8324. }
  8325. }
  8326. /* request not yet handled by a handler or redirect, so the request
  8327. * is processed here */
  8328. /* 5. interpret the url to find out how the request must be handled
  8329. */
  8330. /* 5.1. first test, if the request targets the regular http(s)://
  8331. * protocol namespace or the websocket ws(s):// protocol namespace.
  8332. */
  8333. is_websocket_request = is_websocket_protocol(conn);
  8334. /* 5.2. check if the request will be handled by a callback */
  8335. if (get_request_handler(conn,
  8336. is_websocket_request ? WEBSOCKET_HANDLER
  8337. : REQUEST_HANDLER,
  8338. &callback_handler,
  8339. &ws_connect_handler,
  8340. &ws_ready_handler,
  8341. &ws_data_handler,
  8342. &ws_close_handler,
  8343. NULL,
  8344. &callback_data)) {
  8345. /* 5.2.1. A callback will handle this request. All requests
  8346. * handled
  8347. * by a callback have to be considered as requests to a script
  8348. * resource. */
  8349. is_callback_resource = 1;
  8350. is_script_resource = 1;
  8351. is_put_or_delete_request = is_put_or_delete_method(conn);
  8352. } else {
  8353. no_callback_resource:
  8354. /* 5.2.2. No callback is responsible for this request. The URI
  8355. * addresses a file based resource (static content or Lua/cgi
  8356. * scripts in the file system). */
  8357. is_callback_resource = 0;
  8358. interpret_uri(conn,
  8359. path,
  8360. sizeof(path),
  8361. &file,
  8362. &is_found,
  8363. &is_script_resource,
  8364. &is_websocket_request,
  8365. &is_put_or_delete_request);
  8366. }
  8367. /* 6. authorization check */
  8368. /* 6.1. a custom authorization handler is installed */
  8369. if (get_request_handler(conn,
  8370. AUTH_HANDLER,
  8371. NULL,
  8372. NULL,
  8373. NULL,
  8374. NULL,
  8375. NULL,
  8376. &auth_handler,
  8377. &auth_callback_data)) {
  8378. if (!auth_handler(conn, auth_callback_data)) {
  8379. return;
  8380. }
  8381. } else if (is_put_or_delete_request && !is_script_resource
  8382. && !is_callback_resource) {
  8383. /* 6.2. this request is a PUT/DELETE to a real file */
  8384. /* 6.2.1. thus, the server must have real files */
  8385. #if defined(NO_FILES)
  8386. if (1) {
  8387. #else
  8388. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  8389. #endif
  8390. /* This server does not have any real files, thus the
  8391. * PUT/DELETE methods are not valid. */
  8392. send_http_error(conn,
  8393. 405,
  8394. "%s method not allowed",
  8395. conn->request_info.request_method);
  8396. return;
  8397. }
  8398. #if !defined(NO_FILES)
  8399. /* 6.2.2. Check if put authorization for static files is available.
  8400. */
  8401. if (!is_authorized_for_put(conn)) {
  8402. send_authorization_request(conn);
  8403. return;
  8404. }
  8405. #endif
  8406. } else {
  8407. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  8408. * or it is a PUT or DELETE request to a resource that does not
  8409. * correspond to a file. Check authorization. */
  8410. if (!check_authorization(conn, path)) {
  8411. send_authorization_request(conn);
  8412. return;
  8413. }
  8414. }
  8415. /* request is authorized or does not need authorization */
  8416. /* 7. check if there are request handlers for this uri */
  8417. if (is_callback_resource) {
  8418. if (!is_websocket_request) {
  8419. i = callback_handler(conn, callback_data);
  8420. if (i > 0) {
  8421. /* Do nothing, callback has served the request. Store
  8422. * the
  8423. * return value as status code for the log and discard
  8424. * all
  8425. * data from the client not used by the callback. */
  8426. conn->status_code = i;
  8427. discard_unread_request_data(conn);
  8428. } else {
  8429. /* TODO (high): what if the handler did NOT handle the
  8430. * request */
  8431. /* The last version did handle this as a file request,
  8432. * but
  8433. * since a file request is not always a script resource,
  8434. * the authorization check might be different */
  8435. interpret_uri(conn,
  8436. path,
  8437. sizeof(path),
  8438. &file,
  8439. &is_found,
  8440. &is_script_resource,
  8441. &is_websocket_request,
  8442. &is_put_or_delete_request);
  8443. callback_handler = NULL;
  8444. /* TODO (very low): goto is deprecated but for the
  8445. * moment,
  8446. * a goto is simpler than some curious loop. */
  8447. /* The situation "callback does not handle the request"
  8448. * needs to be reconsidered anyway. */
  8449. goto no_callback_resource;
  8450. }
  8451. } else {
  8452. #if defined(USE_WEBSOCKET)
  8453. handle_websocket_request(conn,
  8454. path,
  8455. is_callback_resource,
  8456. ws_connect_handler,
  8457. ws_ready_handler,
  8458. ws_data_handler,
  8459. ws_close_handler,
  8460. callback_data);
  8461. #endif
  8462. }
  8463. return;
  8464. }
  8465. /* 8. handle websocket requests */
  8466. #if defined(USE_WEBSOCKET)
  8467. if (is_websocket_request) {
  8468. if (is_script_resource) {
  8469. /* Websocket Lua script */
  8470. handle_websocket_request(conn,
  8471. path,
  8472. 0 /* Lua Script */,
  8473. NULL,
  8474. NULL,
  8475. NULL,
  8476. NULL,
  8477. &conn->ctx->callbacks);
  8478. } else {
  8479. #if defined(MG_LEGACY_INTERFACE)
  8480. handle_websocket_request(
  8481. conn,
  8482. path,
  8483. !is_script_resource /* could be deprecated global callback */,
  8484. deprecated_websocket_connect_wrapper,
  8485. deprecated_websocket_ready_wrapper,
  8486. deprecated_websocket_data_wrapper,
  8487. NULL,
  8488. &conn->ctx->callbacks);
  8489. #else
  8490. send_http_error(conn, 404, "%s", "Not found");
  8491. #endif
  8492. }
  8493. return;
  8494. } else
  8495. #endif
  8496. #if defined(NO_FILES)
  8497. /* 9a. In case the server uses only callbacks, this uri is
  8498. * unknown.
  8499. * Then, all request handling ends here. */
  8500. send_http_error(conn, 404, "%s", "Not Found");
  8501. #else
  8502. /* 9b. This request is either for a static file or resource handled
  8503. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  8504. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  8505. send_http_error(conn, 404, "%s", "Not Found");
  8506. return;
  8507. }
  8508. /* 10. File is handled by a script. */
  8509. if (is_script_resource) {
  8510. handle_file_based_request(conn, path, &file);
  8511. return;
  8512. }
  8513. /* 11. Handle put/delete/mkcol requests */
  8514. if (is_put_or_delete_request) {
  8515. /* 11.1. PUT method */
  8516. if (!strcmp(ri->request_method, "PUT")) {
  8517. put_file(conn, path);
  8518. return;
  8519. }
  8520. /* 11.2. DELETE method */
  8521. if (!strcmp(ri->request_method, "DELETE")) {
  8522. delete_file(conn, path);
  8523. return;
  8524. }
  8525. /* 11.3. MKCOL method */
  8526. if (!strcmp(ri->request_method, "MKCOL")) {
  8527. mkcol(conn, path);
  8528. return;
  8529. }
  8530. /* 11.4. PATCH method
  8531. * This method is not supported for static resources,
  8532. * only for scripts (Lua, CGI) and callbacks. */
  8533. send_http_error(conn,
  8534. 405,
  8535. "%s method not allowed",
  8536. conn->request_info.request_method);
  8537. return;
  8538. }
  8539. /* 11. File does not exist, or it was configured that it should be
  8540. * hidden */
  8541. if (!is_found || (must_hide_file(conn, path))) {
  8542. send_http_error(conn, 404, "%s", "Not found");
  8543. return;
  8544. }
  8545. /* 12. Directory uris should end with a slash */
  8546. if (file.is_directory && ri->local_uri[uri_len - 1] != '/') {
  8547. gmt_time_string(date, sizeof(date), &curtime);
  8548. mg_printf(conn,
  8549. "HTTP/1.1 301 Moved Permanently\r\n"
  8550. "Location: %s/\r\n"
  8551. "Date: %s\r\n"
  8552. /* "Cache-Control: private\r\n" (= default) */
  8553. "Content-Length: 0\r\n"
  8554. "Connection: %s\r\n\r\n",
  8555. ri->request_uri,
  8556. date,
  8557. suggest_connection_header(conn));
  8558. return;
  8559. }
  8560. /* 13. Handle other methods than GET/HEAD */
  8561. /* 13.1. Handle PROPFIND */
  8562. if (!strcmp(ri->request_method, "PROPFIND")) {
  8563. handle_propfind(conn, path, &file);
  8564. return;
  8565. }
  8566. /* 13.2. Handle OPTIONS for files */
  8567. if (!strcmp(ri->request_method, "OPTIONS")) {
  8568. /* This standard handler is only used for real files.
  8569. * Scripts should support the OPTIONS method themselves, to allow a
  8570. * maximum flexibility.
  8571. * Lua and CGI scripts may fully support CORS this way (including
  8572. * preflights). */
  8573. send_options(conn);
  8574. return;
  8575. }
  8576. /* 13.3. everything but GET and HEAD (e.g. POST) */
  8577. if (0 != strcmp(ri->request_method, "GET")
  8578. && 0 != strcmp(ri->request_method, "HEAD")) {
  8579. send_http_error(conn,
  8580. 405,
  8581. "%s method not allowed",
  8582. conn->request_info.request_method);
  8583. return;
  8584. }
  8585. /* 14. directories */
  8586. if (file.is_directory) {
  8587. if (substitute_index_file(conn, path, sizeof(path), &file)) {
  8588. /* 14.1. use a substitute file */
  8589. /* TODO (high): substitute index may be a script resource.
  8590. * define what should be possible in this case. */
  8591. } else {
  8592. /* 14.2. no substitute file */
  8593. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  8594. "yes")) {
  8595. handle_directory_request(conn, path);
  8596. } else {
  8597. send_http_error(conn,
  8598. 403,
  8599. "%s",
  8600. "Error: Directory listing denied");
  8601. }
  8602. return;
  8603. }
  8604. }
  8605. handle_file_based_request(conn, path, &file);
  8606. #endif /* !defined(NO_FILES) */
  8607. #if 0
  8608. /* Perform redirect and auth checks before calling begin_request()
  8609. * handler.
  8610. * Otherwise, begin_request() would need to perform auth checks and
  8611. * redirects. */
  8612. #endif
  8613. }
  8614. return;
  8615. }
  8616. static void
  8617. handle_file_based_request(struct mg_connection *conn,
  8618. const char *path,
  8619. struct file *file)
  8620. {
  8621. if (!conn || !conn->ctx) {
  8622. return;
  8623. }
  8624. if (0) {
  8625. #ifdef USE_LUA
  8626. } else if (match_prefix(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  8627. strlen(
  8628. conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  8629. path) > 0) {
  8630. /* Lua server page: an SSI like page containing mostly plain html
  8631. * code
  8632. * plus some tags with server generated contents. */
  8633. handle_lsp_request(conn, path, file, NULL);
  8634. } else if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  8635. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  8636. path) > 0) {
  8637. /* Lua in-server module script: a CGI like script used to generate
  8638. * the
  8639. * entire reply. */
  8640. mg_exec_lua_script(conn, path, NULL);
  8641. #endif
  8642. #if defined(USE_DUKTAPE)
  8643. } else if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  8644. strlen(
  8645. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  8646. path) > 0) {
  8647. /* Call duktape to generate the page */
  8648. mg_exec_duktape_script(conn, path);
  8649. #endif
  8650. #if !defined(NO_CGI)
  8651. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  8652. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  8653. path) > 0) {
  8654. /* CGI scripts may support all HTTP methods */
  8655. handle_cgi_request(conn, path);
  8656. #endif /* !NO_CGI */
  8657. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  8658. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  8659. path) > 0) {
  8660. handle_ssi_file_request(conn, path, file);
  8661. } else if ((!conn->in_error_handler) && is_not_modified(conn, file)) {
  8662. /* Send 304 "Not Modified" - this must not send any body data */
  8663. send_http_error(conn, 304, "%s", "");
  8664. } else {
  8665. handle_static_file_request(conn, path, file, NULL);
  8666. }
  8667. }
  8668. static void
  8669. close_all_listening_sockets(struct mg_context *ctx)
  8670. {
  8671. unsigned int i;
  8672. if (!ctx) {
  8673. return;
  8674. }
  8675. for (i = 0; i < ctx->num_listening_sockets; i++) {
  8676. closesocket(ctx->listening_sockets[i].sock);
  8677. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  8678. }
  8679. mg_free(ctx->listening_sockets);
  8680. ctx->listening_sockets = NULL;
  8681. mg_free(ctx->listening_ports);
  8682. ctx->listening_ports = NULL;
  8683. }
  8684. /* Valid listening port specification is: [ip_address:]port[s]
  8685. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 1.2.3.4:8080s
  8686. * Examples for IPv6: [::]:80, [::1]:80,
  8687. * [FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:443s
  8688. * see https://tools.ietf.org/html/rfc3513#section-2.2 */
  8689. static int
  8690. parse_port_string(const struct vec *vec, struct socket *so)
  8691. {
  8692. unsigned int a, b, c, d, port;
  8693. int ch, len;
  8694. #if defined(USE_IPV6)
  8695. char buf[100] = {0};
  8696. #endif
  8697. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  8698. * Also, all-zeroes in the socket address means binding to all addresses
  8699. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  8700. memset(so, 0, sizeof(*so));
  8701. so->lsa.sin.sin_family = AF_INET;
  8702. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  8703. == 5) {
  8704. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  8705. so->lsa.sin.sin_addr.s_addr =
  8706. htonl((a << 24) | (b << 16) | (c << 8) | d);
  8707. so->lsa.sin.sin_port = htons((uint16_t)port);
  8708. #if defined(USE_IPV6)
  8709. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  8710. && mg_inet_pton(
  8711. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  8712. /* IPv6 address, examples: see above */
  8713. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  8714. */
  8715. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  8716. #endif
  8717. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  8718. /* If only port is specified, bind to IPv4, INADDR_ANY */
  8719. so->lsa.sin.sin_port = htons((uint16_t)port);
  8720. } else {
  8721. /* Parsing failure. Make port invalid. */
  8722. port = 0;
  8723. len = 0;
  8724. }
  8725. /* sscanf and the option splitting code ensure the following condition
  8726. */
  8727. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  8728. return 0;
  8729. }
  8730. ch = vec->ptr[len]; /* Next character after the port number */
  8731. so->is_ssl = (ch == 's');
  8732. so->ssl_redir = (ch == 'r');
  8733. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  8734. return is_valid_port(port)
  8735. && (ch == '\0' || ch == 's' || ch == 'r' || ch == ',');
  8736. }
  8737. static int
  8738. set_ports_option(struct mg_context *ctx)
  8739. {
  8740. const char *list;
  8741. int on = 1;
  8742. #if defined(USE_IPV6)
  8743. int off = 0;
  8744. #endif
  8745. struct vec vec;
  8746. struct socket so, *ptr;
  8747. in_port_t *portPtr;
  8748. union usa usa;
  8749. socklen_t len;
  8750. int portsTotal = 0;
  8751. int portsOk = 0;
  8752. if (!ctx) {
  8753. return 0;
  8754. }
  8755. memset(&so, 0, sizeof(so));
  8756. memset(&usa, 0, sizeof(usa));
  8757. len = sizeof(usa);
  8758. list = ctx->config[LISTENING_PORTS];
  8759. while ((list = next_option(list, &vec, NULL)) != NULL) {
  8760. portsTotal++;
  8761. if (!parse_port_string(&vec, &so)) {
  8762. mg_cry(fc(ctx),
  8763. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  8764. (int)vec.len,
  8765. vec.ptr,
  8766. portsTotal,
  8767. "[IP_ADDRESS:]PORT[s|r]");
  8768. continue;
  8769. }
  8770. if (so.is_ssl && ctx->ssl_ctx == NULL) {
  8771. mg_cry(fc(ctx),
  8772. "Cannot add SSL socket (entry %i). Is -ssl_certificate "
  8773. "option set?",
  8774. portsTotal);
  8775. continue;
  8776. }
  8777. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  8778. == INVALID_SOCKET) {
  8779. mg_cry(fc(ctx), "cannot create socket (entry %i)", portsTotal);
  8780. continue;
  8781. }
  8782. #ifdef _WIN32
  8783. /* Windows SO_REUSEADDR lets many procs binds to a
  8784. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  8785. * if someone already has the socket -- DTL */
  8786. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  8787. * Windows might need a few seconds before
  8788. * the same port can be used again in the
  8789. * same process, so a short Sleep may be
  8790. * required between mg_stop and mg_start.
  8791. */
  8792. if (setsockopt(so.sock,
  8793. SOL_SOCKET,
  8794. SO_EXCLUSIVEADDRUSE,
  8795. (SOCK_OPT_TYPE)&on,
  8796. sizeof(on)) != 0) {
  8797. mg_cry(fc(ctx),
  8798. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  8799. portsTotal);
  8800. }
  8801. #else
  8802. if (setsockopt(so.sock,
  8803. SOL_SOCKET,
  8804. SO_REUSEADDR,
  8805. (SOCK_OPT_TYPE)&on,
  8806. sizeof(on)) != 0) {
  8807. mg_cry(fc(ctx),
  8808. "cannot set socket option SO_REUSEADDR (entry %i)",
  8809. portsTotal);
  8810. }
  8811. #endif
  8812. #if defined(USE_IPV6)
  8813. if (so.lsa.sa.sa_family == AF_INET6
  8814. && setsockopt(so.sock,
  8815. IPPROTO_IPV6,
  8816. IPV6_V6ONLY,
  8817. (void *)&off,
  8818. sizeof(off)) != 0) {
  8819. mg_cry(fc(ctx),
  8820. "cannot set socket option IPV6_V6ONLY (entry %i)",
  8821. portsTotal);
  8822. }
  8823. #endif
  8824. if (so.lsa.sa.sa_family == AF_INET) {
  8825. len = sizeof(so.lsa.sin);
  8826. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  8827. mg_cry(fc(ctx),
  8828. "cannot bind to %.*s: %d (%s)",
  8829. (int)vec.len,
  8830. vec.ptr,
  8831. (int)ERRNO,
  8832. strerror(errno));
  8833. closesocket(so.sock);
  8834. so.sock = INVALID_SOCKET;
  8835. continue;
  8836. }
  8837. }
  8838. #if defined(USE_IPV6)
  8839. else if (so.lsa.sa.sa_family == AF_INET6) {
  8840. len = sizeof(so.lsa.sin6);
  8841. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  8842. mg_cry(fc(ctx),
  8843. "cannot bind to IPv6 %.*s: %d (%s)",
  8844. (int)vec.len,
  8845. vec.ptr,
  8846. (int)ERRNO,
  8847. strerror(errno));
  8848. closesocket(so.sock);
  8849. so.sock = INVALID_SOCKET;
  8850. continue;
  8851. }
  8852. }
  8853. #endif
  8854. else {
  8855. mg_cry(fc(ctx),
  8856. "cannot bind: address family not supported (entry %i)",
  8857. portsTotal);
  8858. continue;
  8859. }
  8860. if (listen(so.sock, SOMAXCONN) != 0) {
  8861. mg_cry(fc(ctx),
  8862. "cannot listen to %.*s: %d (%s)",
  8863. (int)vec.len,
  8864. vec.ptr,
  8865. (int)ERRNO,
  8866. strerror(errno));
  8867. closesocket(so.sock);
  8868. so.sock = INVALID_SOCKET;
  8869. continue;
  8870. }
  8871. if (getsockname(so.sock, &(usa.sa), &len) != 0) {
  8872. int err = (int)ERRNO;
  8873. mg_cry(fc(ctx),
  8874. "call to getsockname failed %.*s: %d (%s)",
  8875. (int)vec.len,
  8876. vec.ptr,
  8877. err,
  8878. strerror(errno));
  8879. closesocket(so.sock);
  8880. so.sock = INVALID_SOCKET;
  8881. continue;
  8882. }
  8883. if ((ptr = (struct socket *)
  8884. mg_realloc(ctx->listening_sockets,
  8885. (ctx->num_listening_sockets + 1)
  8886. * sizeof(ctx->listening_sockets[0]))) == NULL) {
  8887. mg_cry(fc(ctx), "%s", "Out of memory");
  8888. closesocket(so.sock);
  8889. so.sock = INVALID_SOCKET;
  8890. continue;
  8891. }
  8892. if ((portPtr =
  8893. (in_port_t *)mg_realloc(ctx->listening_ports,
  8894. (ctx->num_listening_sockets + 1)
  8895. * sizeof(ctx->listening_ports[0])))
  8896. == NULL) {
  8897. mg_cry(fc(ctx), "%s", "Out of memory");
  8898. closesocket(so.sock);
  8899. so.sock = INVALID_SOCKET;
  8900. mg_free(ptr);
  8901. continue;
  8902. }
  8903. set_close_on_exec(so.sock, fc(ctx));
  8904. ctx->listening_sockets = ptr;
  8905. ctx->listening_sockets[ctx->num_listening_sockets] = so;
  8906. ctx->listening_ports = portPtr;
  8907. ctx->listening_ports[ctx->num_listening_sockets] =
  8908. ntohs(usa.sin.sin_port);
  8909. ctx->num_listening_sockets++;
  8910. portsOk++;
  8911. }
  8912. if (portsOk != portsTotal) {
  8913. close_all_listening_sockets(ctx);
  8914. portsOk = 0;
  8915. }
  8916. return portsOk;
  8917. }
  8918. static const char *
  8919. header_val(const struct mg_connection *conn, const char *header)
  8920. {
  8921. const char *header_value;
  8922. if ((header_value = mg_get_header(conn, header)) == NULL) {
  8923. return "-";
  8924. } else {
  8925. return header_value;
  8926. }
  8927. }
  8928. static void
  8929. log_access(const struct mg_connection *conn)
  8930. {
  8931. const struct mg_request_info *ri;
  8932. struct file fi;
  8933. char date[64], src_addr[IP_ADDR_STR_LEN];
  8934. struct tm *tm;
  8935. const char *referer;
  8936. const char *user_agent;
  8937. char buf[4096];
  8938. if (!conn || !conn->ctx) {
  8939. return;
  8940. }
  8941. if (conn->ctx->config[ACCESS_LOG_FILE] != NULL) {
  8942. if (mg_fopen(conn, conn->ctx->config[ACCESS_LOG_FILE], "a+", &fi)
  8943. == 0) {
  8944. fi.fp = NULL;
  8945. }
  8946. } else {
  8947. fi.fp = NULL;
  8948. }
  8949. if (fi.fp == NULL && conn->ctx->callbacks.log_message == NULL) {
  8950. return;
  8951. }
  8952. tm = localtime(&conn->conn_birth_time);
  8953. if (tm != NULL) {
  8954. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  8955. } else {
  8956. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  8957. date[sizeof(date) - 1] = '\0';
  8958. }
  8959. ri = &conn->request_info;
  8960. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  8961. referer = header_val(conn, "Referer");
  8962. user_agent = header_val(conn, "User-Agent");
  8963. mg_snprintf(conn,
  8964. NULL, /* Ignore truncation in access log */
  8965. buf,
  8966. sizeof(buf),
  8967. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  8968. src_addr,
  8969. ri->remote_user == NULL ? "-" : ri->remote_user,
  8970. date,
  8971. ri->request_method ? ri->request_method : "-",
  8972. ri->request_uri ? ri->request_uri : "-",
  8973. ri->query_string ? "?" : "",
  8974. ri->query_string ? ri->query_string : "",
  8975. ri->http_version,
  8976. conn->status_code,
  8977. conn->num_bytes_sent,
  8978. referer,
  8979. user_agent);
  8980. if (conn->ctx->callbacks.log_access) {
  8981. conn->ctx->callbacks.log_access(conn, buf);
  8982. }
  8983. if (fi.fp) {
  8984. flockfile(fi.fp);
  8985. fprintf(fi.fp, "%s\n", buf);
  8986. fflush(fi.fp);
  8987. funlockfile(fi.fp);
  8988. mg_fclose(&fi);
  8989. }
  8990. }
  8991. /* Verify given socket address against the ACL.
  8992. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  8993. */
  8994. static int
  8995. check_acl(struct mg_context *ctx, uint32_t remote_ip)
  8996. {
  8997. int allowed, flag;
  8998. uint32_t net, mask;
  8999. struct vec vec;
  9000. if (ctx) {
  9001. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  9002. /* If any ACL is set, deny by default */
  9003. allowed = list == NULL ? '+' : '-';
  9004. while ((list = next_option(list, &vec, NULL)) != NULL) {
  9005. flag = vec.ptr[0];
  9006. if ((flag != '+' && flag != '-')
  9007. || parse_net(&vec.ptr[1], &net, &mask) == 0) {
  9008. mg_cry(fc(ctx),
  9009. "%s: subnet must be [+|-]x.x.x.x[/x]",
  9010. __func__);
  9011. return -1;
  9012. }
  9013. if (net == (remote_ip & mask)) {
  9014. allowed = flag;
  9015. }
  9016. }
  9017. return allowed == '+';
  9018. }
  9019. return -1;
  9020. }
  9021. #if !defined(_WIN32)
  9022. static int
  9023. set_uid_option(struct mg_context *ctx)
  9024. {
  9025. struct passwd *pw;
  9026. if (ctx) {
  9027. const char *uid = ctx->config[RUN_AS_USER];
  9028. int success = 0;
  9029. if (uid == NULL) {
  9030. success = 1;
  9031. } else {
  9032. if ((pw = getpwnam(uid)) == NULL) {
  9033. mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  9034. } else if (setgid(pw->pw_gid) == -1) {
  9035. mg_cry(fc(ctx),
  9036. "%s: setgid(%s): %s",
  9037. __func__,
  9038. uid,
  9039. strerror(errno));
  9040. } else if (setgroups(0, NULL)) {
  9041. mg_cry(fc(ctx),
  9042. "%s: setgroups(): %s",
  9043. __func__,
  9044. strerror(errno));
  9045. } else if (setuid(pw->pw_uid) == -1) {
  9046. mg_cry(fc(ctx),
  9047. "%s: setuid(%s): %s",
  9048. __func__,
  9049. uid,
  9050. strerror(errno));
  9051. } else {
  9052. success = 1;
  9053. }
  9054. }
  9055. return success;
  9056. }
  9057. return 0;
  9058. }
  9059. #endif /* !_WIN32 */
  9060. static void
  9061. tls_dtor(void *key)
  9062. {
  9063. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  9064. /* key == pthread_getspecific(sTlsKey); */
  9065. if (tls) {
  9066. if (tls->is_master == 2) {
  9067. tls->is_master = -3; /* Mark memory as dead */
  9068. mg_free(tls);
  9069. }
  9070. }
  9071. pthread_setspecific(sTlsKey, NULL);
  9072. }
  9073. #if !defined(NO_SSL)
  9074. /* Must be set if sizeof(pthread_t) > sizeof(unsigned long) */
  9075. static unsigned long
  9076. ssl_id_callback(void)
  9077. {
  9078. #ifdef _WIN32
  9079. return GetCurrentThreadId();
  9080. #else
  9081. #ifdef __clang__
  9082. #pragma clang diagnostic push
  9083. #pragma clang diagnostic ignored "-Wunreachable-code"
  9084. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  9085. * or not, so one of the two conditions will be unreachable by construction.
  9086. * Unfortunately the C standard does not define a way to check this at
  9087. * compile time, since the #if preprocessor conditions can not use the sizeof
  9088. * operator as an argument. */
  9089. #endif
  9090. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  9091. /* This is the problematic case for CRYPTO_set_id_callback:
  9092. * The OS pthread_t can not be cast to unsigned long. */
  9093. struct mg_workerTLS *tls =
  9094. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  9095. if (tls == NULL) {
  9096. /* SSL called from an unknown thread: Create some thread index.
  9097. */
  9098. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  9099. tls->is_master = -2; /* -2 means "3rd party thread" */
  9100. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  9101. pthread_setspecific(sTlsKey, tls);
  9102. }
  9103. return tls->thread_idx;
  9104. } else {
  9105. return (unsigned long)pthread_self();
  9106. }
  9107. #ifdef __clang__
  9108. #pragma clang diagnostic pop
  9109. #endif
  9110. #endif
  9111. }
  9112. static int ssl_use_pem_file(struct mg_context *ctx, const char *pem);
  9113. static const char * ssl_error(void);
  9114. static int
  9115. refresh_trust(struct mg_connection *conn)
  9116. {
  9117. static int reload_lock = 0;
  9118. static long int data_check = 0;
  9119. char *pem;
  9120. if ((pem = conn->ctx->config[SSL_CERTIFICATE]) == NULL
  9121. && conn->ctx->callbacks.init_ssl == NULL) {
  9122. return 0;
  9123. }
  9124. struct stat cert_buf;
  9125. long int t = data_check;
  9126. if (stat(pem, &cert_buf) != -1) {
  9127. t = (long int) cert_buf.st_mtime;
  9128. }
  9129. if (data_check != t) {
  9130. data_check = t;
  9131. int should_verify_peer =
  9132. (conn->ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  9133. && (mg_strcasecmp(conn->ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0);
  9134. if (should_verify_peer) {
  9135. char *ca_path = conn->ctx->config[SSL_CA_PATH];
  9136. char *ca_file = conn->ctx->config[SSL_CA_FILE];
  9137. if (SSL_CTX_load_verify_locations(conn->ctx->ssl_ctx, ca_file, ca_path)
  9138. != 1) {
  9139. mg_cry(fc(conn->ctx),
  9140. "SSL_CTX_load_verify_locations error: %s "
  9141. "ssl_verify_peer requires setting "
  9142. "either ssl_ca_path or ssl_ca_file. Is any of them "
  9143. "present in "
  9144. "the .conf file?",
  9145. ssl_error());
  9146. return 0;
  9147. }
  9148. }
  9149. if (!reload_lock) {
  9150. reload_lock = 1;
  9151. if (ssl_use_pem_file(conn->ctx, pem) == 0) {
  9152. return 0;
  9153. }
  9154. reload_lock = 0;
  9155. }
  9156. }
  9157. /* lock while cert is reloading */
  9158. while (reload_lock) {
  9159. sleep(1);
  9160. }
  9161. return 1;
  9162. }
  9163. static pthread_mutex_t *ssl_mutexes;
  9164. static int
  9165. sslize(struct mg_connection *conn, SSL_CTX *s, int (*func)(SSL *))
  9166. {
  9167. int ret, err;
  9168. if (!conn) {
  9169. return 0;
  9170. }
  9171. int short_trust =
  9172. (conn->ctx->config[SSL_SHORT_TRUST] != NULL)
  9173. && (mg_strcasecmp(conn->ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  9174. if (short_trust) {
  9175. int trust_ret = refresh_trust(conn);
  9176. if (!trust_ret) {
  9177. return trust_ret;
  9178. }
  9179. }
  9180. conn->ssl = SSL_new(s);
  9181. if (conn->ssl == NULL) {
  9182. return 0;
  9183. }
  9184. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  9185. if (ret != 1) {
  9186. err = SSL_get_error(conn->ssl, ret);
  9187. (void)err; /* TODO: set some error message */
  9188. SSL_free(conn->ssl);
  9189. conn->ssl = NULL;
  9190. /* maybe not? CRYPTO_cleanup_all_ex_data(); */
  9191. /* see https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  9192. ERR_remove_state(0);
  9193. return 0;
  9194. }
  9195. ret = func(conn->ssl);
  9196. if (ret != 1) {
  9197. err = SSL_get_error(conn->ssl, ret);
  9198. (void)err; /* TODO: set some error message */
  9199. SSL_free(conn->ssl);
  9200. conn->ssl = NULL;
  9201. /* maybe not? CRYPTO_cleanup_all_ex_data(); */
  9202. /* see https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  9203. ERR_remove_state(0);
  9204. return 0;
  9205. }
  9206. return 1;
  9207. }
  9208. /* Return OpenSSL error message (from CRYPTO lib) */
  9209. static const char *
  9210. ssl_error(void)
  9211. {
  9212. unsigned long err;
  9213. err = ERR_get_error();
  9214. return err == 0 ? "" : ERR_error_string(err, NULL);
  9215. }
  9216. static void
  9217. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  9218. {
  9219. (void)line;
  9220. (void)file;
  9221. if (mode & 1) {
  9222. /* 1 is CRYPTO_LOCK */
  9223. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  9224. } else {
  9225. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  9226. }
  9227. }
  9228. #if !defined(NO_SSL_DL)
  9229. static void *
  9230. load_dll(struct mg_context *ctx, const char *dll_name, struct ssl_func *sw)
  9231. {
  9232. union {
  9233. void *p;
  9234. void (*fp)(void);
  9235. } u;
  9236. void *dll_handle;
  9237. struct ssl_func *fp;
  9238. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  9239. mg_cry(fc(ctx), "%s: cannot load %s", __func__, dll_name);
  9240. return NULL;
  9241. }
  9242. for (fp = sw; fp->name != NULL; fp++) {
  9243. #ifdef _WIN32
  9244. /* GetProcAddress() returns pointer to function */
  9245. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  9246. #else
  9247. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  9248. * pointers to function pointers. We need to use a union to make a
  9249. * cast. */
  9250. u.p = dlsym(dll_handle, fp->name);
  9251. #endif /* _WIN32 */
  9252. if (u.fp == NULL) {
  9253. mg_cry(fc(ctx),
  9254. "%s: %s: cannot find %s",
  9255. __func__,
  9256. dll_name,
  9257. fp->name);
  9258. dlclose(dll_handle);
  9259. return NULL;
  9260. } else {
  9261. fp->ptr = u.fp;
  9262. }
  9263. }
  9264. return dll_handle;
  9265. }
  9266. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  9267. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  9268. #endif /* NO_SSL_DL */
  9269. #if defined(SSL_ALREADY_INITIALIZED)
  9270. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  9271. #else
  9272. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  9273. #endif
  9274. static int
  9275. initialize_ssl(struct mg_context *ctx)
  9276. {
  9277. int i;
  9278. size_t size;
  9279. #if !defined(NO_SSL_DL)
  9280. if (!cryptolib_dll_handle) {
  9281. cryptolib_dll_handle = load_dll(ctx, CRYPTO_LIB, crypto_sw);
  9282. if (!cryptolib_dll_handle) {
  9283. return 0;
  9284. }
  9285. }
  9286. #endif /* NO_SSL_DL */
  9287. if (mg_atomic_inc(&cryptolib_users) > 1) {
  9288. return 1;
  9289. }
  9290. /* Initialize locking callbacks, needed for thread safety.
  9291. * http://www.openssl.org/support/faq.html#PROG1
  9292. */
  9293. i = CRYPTO_num_locks();
  9294. if (i < 0) {
  9295. i = 0;
  9296. }
  9297. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  9298. if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  9299. mg_cry(fc(ctx),
  9300. "%s: cannot allocate mutexes: %s",
  9301. __func__,
  9302. ssl_error());
  9303. return 0;
  9304. }
  9305. for (i = 0; i < CRYPTO_num_locks(); i++) {
  9306. pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr);
  9307. }
  9308. CRYPTO_set_locking_callback(&ssl_locking_callback);
  9309. CRYPTO_set_id_callback(&ssl_id_callback);
  9310. return 1;
  9311. }
  9312. static int
  9313. ssl_use_pem_file(struct mg_context *ctx, const char *pem)
  9314. {
  9315. if (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0) {
  9316. mg_cry(fc(ctx),
  9317. "%s: cannot open certificate file %s: %s",
  9318. __func__,
  9319. pem,
  9320. ssl_error());
  9321. return 0;
  9322. }
  9323. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  9324. if (SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0) {
  9325. mg_cry(fc(ctx),
  9326. "%s: cannot open private key file %s: %s",
  9327. __func__,
  9328. pem,
  9329. ssl_error());
  9330. return 0;
  9331. }
  9332. if (SSL_CTX_check_private_key(ctx->ssl_ctx) == 0) {
  9333. mg_cry(fc(ctx),
  9334. "%s: certificate and private key do not match: %s",
  9335. __func__,
  9336. pem);
  9337. return 0;
  9338. }
  9339. if (SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem) == 0) {
  9340. mg_cry(fc(ctx),
  9341. "%s: cannot use certificate chain file %s: %s",
  9342. __func__,
  9343. pem,
  9344. ssl_error());
  9345. return 0;
  9346. }
  9347. return 1;
  9348. }
  9349. static long
  9350. ssl_get_protocol(int version_id)
  9351. {
  9352. long ret = SSL_OP_ALL;
  9353. if (version_id > 0)
  9354. ret |= SSL_OP_NO_SSLv2;
  9355. if (version_id > 1)
  9356. ret |= SSL_OP_NO_SSLv3;
  9357. if (version_id > 2)
  9358. ret |= SSL_OP_NO_TLSv1;
  9359. if (version_id > 3)
  9360. ret |= SSL_OP_NO_TLSv1_1;
  9361. return ret;
  9362. }
  9363. /* Dynamically load SSL library. Set up ctx->ssl_ctx pointer. */
  9364. static int
  9365. set_ssl_option(struct mg_context *ctx)
  9366. {
  9367. const char *pem;
  9368. int callback_ret;
  9369. int should_verify_peer;
  9370. const char *ca_path;
  9371. const char *ca_file;
  9372. int use_default_verify_paths;
  9373. int verify_depth;
  9374. time_t now_rt = time(NULL);
  9375. struct timespec now_mt;
  9376. md5_byte_t ssl_context_id[16];
  9377. md5_state_t md5state;
  9378. int protocol_ver;
  9379. /* If PEM file is not specified and the init_ssl callback
  9380. * is not specified, skip SSL initialization. */
  9381. if (!ctx) {
  9382. return 0;
  9383. }
  9384. if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL
  9385. && ctx->callbacks.init_ssl == NULL) {
  9386. return 1;
  9387. }
  9388. if (!initialize_ssl(ctx)) {
  9389. return 0;
  9390. }
  9391. #if !defined(NO_SSL_DL)
  9392. if (!ssllib_dll_handle) {
  9393. ssllib_dll_handle = load_dll(ctx, SSL_LIB, ssl_sw);
  9394. if (!ssllib_dll_handle) {
  9395. return 0;
  9396. }
  9397. }
  9398. #endif /* NO_SSL_DL */
  9399. /* Initialize SSL library */
  9400. SSL_library_init();
  9401. SSL_load_error_strings();
  9402. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  9403. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  9404. return 0;
  9405. }
  9406. SSL_CTX_clear_options(ctx->ssl_ctx,
  9407. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  9408. | SSL_OP_NO_TLSv1_1);
  9409. protocol_ver = atoi(ctx->config[SSL_PROTOCOL_VERSION]);
  9410. SSL_CTX_set_options(ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  9411. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  9412. SSL_CTX_set_ecdh_auto(ctx->ssl_ctx, 1);
  9413. /* If a callback has been specified, call it. */
  9414. callback_ret =
  9415. (ctx->callbacks.init_ssl == NULL)
  9416. ? 0
  9417. : (ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data));
  9418. /* If callback returns 0, civetweb sets up the SSL certificate.
  9419. * If it returns 1, civetweb assumes the calback already did this.
  9420. * If it returns -1, initializing ssl fails. */
  9421. if (callback_ret < 0) {
  9422. mg_cry(fc(ctx), "SSL callback returned error: %i", callback_ret);
  9423. return 0;
  9424. }
  9425. if (callback_ret > 0) {
  9426. if (pem != NULL) {
  9427. (void)SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
  9428. }
  9429. return 1;
  9430. }
  9431. /* Use some UID as session context ID. */
  9432. md5_init(&md5state);
  9433. md5_append(&md5state, (const md5_byte_t *)&now_rt, sizeof(now_rt));
  9434. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  9435. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  9436. md5_append(&md5state,
  9437. (const md5_byte_t *)ctx->config[LISTENING_PORTS],
  9438. strlen(ctx->config[LISTENING_PORTS]));
  9439. md5_append(&md5state, (const md5_byte_t *)ctx, sizeof(*ctx));
  9440. md5_finish(&md5state, ssl_context_id);
  9441. SSL_CTX_set_session_id_context(ctx->ssl_ctx,
  9442. (const unsigned char *)&ssl_context_id,
  9443. sizeof(ssl_context_id));
  9444. if (pem != NULL) {
  9445. if (!ssl_use_pem_file(ctx, pem)) {
  9446. return 0;
  9447. }
  9448. }
  9449. should_verify_peer =
  9450. (ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  9451. && (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0);
  9452. use_default_verify_paths =
  9453. (ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  9454. && (mg_strcasecmp(ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes") == 0);
  9455. if (should_verify_peer) {
  9456. ca_path = ctx->config[SSL_CA_PATH];
  9457. ca_file = ctx->config[SSL_CA_FILE];
  9458. if (SSL_CTX_load_verify_locations(ctx->ssl_ctx, ca_file, ca_path)
  9459. != 1) {
  9460. mg_cry(fc(ctx),
  9461. "SSL_CTX_load_verify_locations error: %s "
  9462. "ssl_verify_peer requires setting "
  9463. "either ssl_ca_path or ssl_ca_file. Is any of them "
  9464. "present in "
  9465. "the .conf file?",
  9466. ssl_error());
  9467. return 0;
  9468. }
  9469. SSL_CTX_set_verify(ctx->ssl_ctx,
  9470. SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  9471. NULL);
  9472. if (use_default_verify_paths
  9473. && SSL_CTX_set_default_verify_paths(ctx->ssl_ctx) != 1) {
  9474. mg_cry(fc(ctx),
  9475. "SSL_CTX_set_default_verify_paths error: %s",
  9476. ssl_error());
  9477. return 0;
  9478. }
  9479. if (ctx->config[SSL_VERIFY_DEPTH]) {
  9480. verify_depth = atoi(ctx->config[SSL_VERIFY_DEPTH]);
  9481. SSL_CTX_set_verify_depth(ctx->ssl_ctx, verify_depth);
  9482. }
  9483. }
  9484. if (ctx->config[SSL_CIPHER_LIST] != NULL) {
  9485. if (SSL_CTX_set_cipher_list(ctx->ssl_ctx, ctx->config[SSL_CIPHER_LIST])
  9486. != 1) {
  9487. mg_cry(fc(ctx), "SSL_CTX_set_cipher_list error: %s", ssl_error());
  9488. }
  9489. }
  9490. return 1;
  9491. }
  9492. static void
  9493. uninitialize_ssl(struct mg_context *ctx)
  9494. {
  9495. int i;
  9496. (void)ctx;
  9497. if (mg_atomic_dec(&cryptolib_users) == 0) {
  9498. /* Shutdown according to
  9499. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  9500. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  9501. */
  9502. CRYPTO_set_locking_callback(NULL);
  9503. CRYPTO_set_id_callback(NULL);
  9504. ENGINE_cleanup();
  9505. CONF_modules_unload(1);
  9506. ERR_free_strings();
  9507. EVP_cleanup();
  9508. CRYPTO_cleanup_all_ex_data();
  9509. ERR_remove_state(0);
  9510. for (i = 0; i < CRYPTO_num_locks(); i++) {
  9511. pthread_mutex_destroy(&ssl_mutexes[i]);
  9512. }
  9513. mg_free(ssl_mutexes);
  9514. ssl_mutexes = NULL;
  9515. }
  9516. }
  9517. #endif /* !NO_SSL */
  9518. static int
  9519. set_gpass_option(struct mg_context *ctx)
  9520. {
  9521. if (ctx) {
  9522. struct file file = STRUCT_FILE_INITIALIZER;
  9523. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  9524. if (path != NULL && !mg_stat(fc(ctx), path, &file)) {
  9525. mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  9526. return 0;
  9527. }
  9528. return 1;
  9529. }
  9530. return 0;
  9531. }
  9532. static int
  9533. set_acl_option(struct mg_context *ctx)
  9534. {
  9535. return check_acl(ctx, (uint32_t)0x7f000001UL) != -1;
  9536. }
  9537. static void
  9538. reset_per_request_attributes(struct mg_connection *conn)
  9539. {
  9540. if (!conn) {
  9541. return;
  9542. }
  9543. conn->path_info = NULL;
  9544. conn->num_bytes_sent = conn->consumed_content = 0;
  9545. conn->status_code = -1;
  9546. conn->is_chunked = 0;
  9547. conn->must_close = conn->request_len = conn->throttle = 0;
  9548. conn->request_info.content_length = -1;
  9549. conn->request_info.remote_user = NULL;
  9550. conn->request_info.request_method = NULL;
  9551. conn->request_info.request_uri = NULL;
  9552. conn->request_info.local_uri = NULL;
  9553. conn->request_info.uri = NULL; /* TODO: cleanup uri,
  9554. * local_uri and request_uri */
  9555. conn->request_info.http_version = NULL;
  9556. conn->request_info.num_headers = 0;
  9557. conn->data_len = 0;
  9558. conn->chunk_remainder = 0;
  9559. conn->internal_error = 0;
  9560. }
  9561. static int
  9562. set_sock_timeout(SOCKET sock, int milliseconds)
  9563. {
  9564. int r0 = 0, r1, r2;
  9565. #ifdef _WIN32
  9566. /* Windows specific */
  9567. DWORD tv = (DWORD)milliseconds;
  9568. #else
  9569. /* Linux, ... (not Windows) */
  9570. struct timeval tv;
  9571. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  9572. * max. time waiting for the acknowledged of TCP data before the connection
  9573. * will be forcefully closed and ETIMEDOUT is returned to the application.
  9574. * If this option is not set, the default timeout of 20-30 minutes is used.
  9575. */
  9576. /* #define TCP_USER_TIMEOUT (18) */
  9577. #if defined(TCP_USER_TIMEOUT)
  9578. unsigned int uto = (unsigned int)milliseconds;
  9579. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  9580. #endif
  9581. memset(&tv, 0, sizeof(tv));
  9582. tv.tv_sec = milliseconds / 1000;
  9583. tv.tv_usec = (milliseconds * 1000) % 1000000;
  9584. #endif /* _WIN32 */
  9585. r1 = setsockopt(
  9586. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  9587. r2 = setsockopt(
  9588. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  9589. return r0 || r1 || r2;
  9590. }
  9591. static int
  9592. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  9593. {
  9594. if (setsockopt(sock,
  9595. IPPROTO_TCP,
  9596. TCP_NODELAY,
  9597. (SOCK_OPT_TYPE)&nodelay_on,
  9598. sizeof(nodelay_on)) != 0) {
  9599. /* Error */
  9600. return 1;
  9601. }
  9602. /* OK */
  9603. return 0;
  9604. }
  9605. static void
  9606. close_socket_gracefully(struct mg_connection *conn)
  9607. {
  9608. #if defined(_WIN32)
  9609. char buf[MG_BUF_LEN];
  9610. int n;
  9611. #endif
  9612. struct linger linger;
  9613. if (!conn) {
  9614. return;
  9615. }
  9616. /* Set linger option to avoid socket hanging out after close. This
  9617. * prevent
  9618. * ephemeral port exhaust problem under high QPS. */
  9619. linger.l_onoff = 1;
  9620. linger.l_linger = 1;
  9621. if (setsockopt(conn->client.sock,
  9622. SOL_SOCKET,
  9623. SO_LINGER,
  9624. (char *)&linger,
  9625. sizeof(linger)) != 0) {
  9626. mg_cry(conn,
  9627. "%s: setsockopt(SOL_SOCKET SO_LINGER) failed: %s",
  9628. __func__,
  9629. strerror(ERRNO));
  9630. }
  9631. /* Send FIN to the client */
  9632. shutdown(conn->client.sock, SHUT_WR);
  9633. set_non_blocking_mode(conn->client.sock);
  9634. #if defined(_WIN32)
  9635. /* Read and discard pending incoming data. If we do not do that and
  9636. * close
  9637. * the socket, the data in the send buffer may be discarded. This
  9638. * behaviour is seen on Windows, when client keeps sending data
  9639. * when server decides to close the connection; then when client
  9640. * does recv() it gets no data back. */
  9641. do {
  9642. n = pull(
  9643. NULL, conn, buf, sizeof(buf), 1E-10 /* TODO: allow 0 as timeout */);
  9644. } while (n > 0);
  9645. #endif
  9646. /* Now we know that our FIN is ACK-ed, safe to close */
  9647. closesocket(conn->client.sock);
  9648. conn->client.sock = INVALID_SOCKET;
  9649. }
  9650. static void
  9651. close_connection(struct mg_connection *conn)
  9652. {
  9653. if (!conn || !conn->ctx) {
  9654. return;
  9655. }
  9656. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  9657. if (conn->lua_websocket_state) {
  9658. lua_websocket_close(conn, conn->lua_websocket_state);
  9659. conn->lua_websocket_state = NULL;
  9660. }
  9661. #endif
  9662. /* call the connection_close callback if assigned */
  9663. if ((conn->ctx->callbacks.connection_close != NULL)
  9664. && (conn->ctx->context_type == 1)) {
  9665. conn->ctx->callbacks.connection_close(conn);
  9666. }
  9667. mg_lock_connection(conn);
  9668. conn->must_close = 1;
  9669. #ifndef NO_SSL
  9670. if (conn->ssl != NULL) {
  9671. /* Run SSL_shutdown twice to ensure completly close SSL connection
  9672. */
  9673. SSL_shutdown(conn->ssl);
  9674. SSL_free(conn->ssl);
  9675. /* maybe not? CRYPTO_cleanup_all_ex_data(); */
  9676. /* see https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  9677. ERR_remove_state(0);
  9678. conn->ssl = NULL;
  9679. }
  9680. #endif
  9681. if (conn->client.sock != INVALID_SOCKET) {
  9682. close_socket_gracefully(conn);
  9683. conn->client.sock = INVALID_SOCKET;
  9684. }
  9685. mg_unlock_connection(conn);
  9686. }
  9687. void
  9688. mg_close_connection(struct mg_connection *conn)
  9689. {
  9690. struct mg_context *client_ctx = NULL;
  9691. unsigned int i;
  9692. if (conn == NULL) {
  9693. return;
  9694. }
  9695. if (conn->ctx->context_type == 2) {
  9696. client_ctx = conn->ctx;
  9697. /* client context: loops must end */
  9698. conn->ctx->stop_flag = 1;
  9699. }
  9700. #ifndef NO_SSL
  9701. if (conn->client_ssl_ctx != NULL) {
  9702. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  9703. }
  9704. #endif
  9705. close_connection(conn);
  9706. if (client_ctx != NULL) {
  9707. /* join worker thread and free context */
  9708. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  9709. if (client_ctx->workerthreadids[i] != 0) {
  9710. mg_join_thread(client_ctx->workerthreadids[i]);
  9711. }
  9712. }
  9713. mg_free(client_ctx->workerthreadids);
  9714. mg_free(client_ctx);
  9715. (void)pthread_mutex_destroy(&conn->mutex);
  9716. mg_free(conn);
  9717. }
  9718. }
  9719. static struct mg_connection *
  9720. mg_connect_client_impl(const struct mg_client_options *client_options,
  9721. int use_ssl,
  9722. char *ebuf,
  9723. size_t ebuf_len)
  9724. {
  9725. static struct mg_context fake_ctx;
  9726. struct mg_connection *conn = NULL;
  9727. SOCKET sock;
  9728. union usa sa;
  9729. if (!connect_socket(&fake_ctx,
  9730. client_options->host,
  9731. client_options->port,
  9732. use_ssl,
  9733. ebuf,
  9734. ebuf_len,
  9735. &sock,
  9736. &sa)) {
  9737. ;
  9738. } else if ((conn = (struct mg_connection *)
  9739. mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) {
  9740. mg_snprintf(NULL,
  9741. NULL, /* No truncation check for ebuf */
  9742. ebuf,
  9743. ebuf_len,
  9744. "calloc(): %s",
  9745. strerror(ERRNO));
  9746. closesocket(sock);
  9747. #ifndef NO_SSL
  9748. } else if (use_ssl
  9749. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  9750. == NULL) {
  9751. mg_snprintf(NULL,
  9752. NULL, /* No truncation check for ebuf */
  9753. ebuf,
  9754. ebuf_len,
  9755. "SSL_CTX_new error");
  9756. closesocket(sock);
  9757. mg_free(conn);
  9758. conn = NULL;
  9759. #endif /* NO_SSL */
  9760. } else {
  9761. #ifdef USE_IPV6
  9762. socklen_t len = (sa.sa.sa_family == AF_INET)
  9763. ? sizeof(conn->client.rsa.sin)
  9764. : sizeof(conn->client.rsa.sin6);
  9765. struct sockaddr *psa =
  9766. (sa.sa.sa_family == AF_INET)
  9767. ? (struct sockaddr *)&(conn->client.rsa.sin)
  9768. : (struct sockaddr *)&(conn->client.rsa.sin6);
  9769. #else
  9770. socklen_t len = sizeof(conn->client.rsa.sin);
  9771. struct sockaddr *psa = (struct sockaddr *)&(conn->client.rsa.sin);
  9772. #endif
  9773. conn->buf_size = MAX_REQUEST_SIZE;
  9774. conn->buf = (char *)(conn + 1);
  9775. conn->ctx = &fake_ctx;
  9776. conn->client.sock = sock;
  9777. conn->client.lsa = sa;
  9778. if (getsockname(sock, psa, &len) != 0) {
  9779. mg_cry(conn,
  9780. "%s: getsockname() failed: %s",
  9781. __func__,
  9782. strerror(ERRNO));
  9783. }
  9784. conn->client.is_ssl = use_ssl ? 1 : 0;
  9785. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  9786. #ifndef NO_SSL
  9787. if (use_ssl) {
  9788. fake_ctx.ssl_ctx = conn->client_ssl_ctx;
  9789. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  9790. SSL_CTX_set_verify call is needed to switch off server
  9791. * certificate checking, which is off by default in OpenSSL and
  9792. on
  9793. * in yaSSL. */
  9794. // TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  9795. // SSL_VERIFY_PEER,
  9796. // verify_ssl_server);
  9797. if (client_options->client_cert) {
  9798. if (!ssl_use_pem_file(&fake_ctx, client_options->client_cert)) {
  9799. mg_snprintf(NULL,
  9800. NULL, /* No truncation check for ebuf */
  9801. ebuf,
  9802. ebuf_len,
  9803. "Can not use SSL client certificate");
  9804. SSL_CTX_free(conn->client_ssl_ctx);
  9805. closesocket(sock);
  9806. mg_free(conn);
  9807. conn = NULL;
  9808. }
  9809. }
  9810. if (client_options->server_cert) {
  9811. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  9812. client_options->server_cert,
  9813. NULL);
  9814. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  9815. } else {
  9816. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  9817. }
  9818. if (!sslize(conn, conn->client_ssl_ctx, SSL_connect)) {
  9819. mg_snprintf(NULL,
  9820. NULL, /* No truncation check for ebuf */
  9821. ebuf,
  9822. ebuf_len,
  9823. "SSL connection error");
  9824. SSL_CTX_free(conn->client_ssl_ctx);
  9825. closesocket(sock);
  9826. mg_free(conn);
  9827. conn = NULL;
  9828. }
  9829. }
  9830. #endif
  9831. }
  9832. return conn;
  9833. }
  9834. CIVETWEB_API struct mg_connection *
  9835. mg_connect_client_secure(const struct mg_client_options *client_options,
  9836. char *error_buffer,
  9837. size_t error_buffer_size)
  9838. {
  9839. return mg_connect_client_impl(client_options,
  9840. 1,
  9841. error_buffer,
  9842. error_buffer_size);
  9843. }
  9844. struct mg_connection *
  9845. mg_connect_client(const char *host,
  9846. int port,
  9847. int use_ssl,
  9848. char *error_buffer,
  9849. size_t error_buffer_size)
  9850. {
  9851. struct mg_client_options opts;
  9852. memset(&opts, 0, sizeof(opts));
  9853. opts.host = host;
  9854. opts.port = port;
  9855. return mg_connect_client_impl(&opts,
  9856. use_ssl,
  9857. error_buffer,
  9858. error_buffer_size);
  9859. }
  9860. static const struct {
  9861. const char *proto;
  9862. size_t proto_len;
  9863. unsigned default_port;
  9864. } abs_uri_protocols[] = {{"http://", 7, 80},
  9865. {"https://", 8, 443},
  9866. {"ws://", 5, 80},
  9867. {"wss://", 6, 443},
  9868. {NULL, 0, 0}};
  9869. /* Check if the uri is valid.
  9870. * return 0 for invalid uri,
  9871. * return 1 for *,
  9872. * return 2 for relative uri,
  9873. * return 3 for absolute uri without port,
  9874. * return 4 for absolute uri with port */
  9875. static int
  9876. get_uri_type(const char *uri)
  9877. {
  9878. int i;
  9879. char *hostend, *portbegin, *portend;
  9880. unsigned long port;
  9881. /* According to the HTTP standard
  9882. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  9883. * URI can be an asterisk (*) or should start with slash (relative uri),
  9884. * or it should start with the protocol (absolute uri). */
  9885. if (uri[0] == '*' && uri[1] == '\0') {
  9886. /* asterisk */
  9887. return 1;
  9888. }
  9889. if (uri[0] == '/') {
  9890. /* relative uri */
  9891. return 2;
  9892. }
  9893. /* It could be an absolute uri: */
  9894. /* This function only checks if the uri is valid, not if it is
  9895. * addressing the current server. So civetweb can also be used
  9896. * as a proxy server. */
  9897. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  9898. if (mg_strncasecmp(uri,
  9899. abs_uri_protocols[i].proto,
  9900. abs_uri_protocols[i].proto_len) == 0) {
  9901. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  9902. if (!hostend) {
  9903. return 0;
  9904. }
  9905. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  9906. if (!portbegin) {
  9907. return 3;
  9908. }
  9909. port = strtoul(portbegin + 1, &portend, 10);
  9910. if ((portend != hostend) || !port || !is_valid_port(port)) {
  9911. return 0;
  9912. }
  9913. return 4;
  9914. }
  9915. }
  9916. return 0;
  9917. }
  9918. /* Return NULL or the relative uri at the current server */
  9919. static const char *
  9920. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  9921. {
  9922. const char *server_domain;
  9923. size_t server_domain_len;
  9924. size_t request_domain_len = 0;
  9925. unsigned long port = 0;
  9926. int i;
  9927. const char *hostbegin = NULL;
  9928. const char *hostend = NULL;
  9929. const char *portbegin;
  9930. char *portend;
  9931. /* DNS is case insensitive, so use case insensitive string compare here
  9932. */
  9933. server_domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  9934. if (!server_domain) {
  9935. return 0;
  9936. }
  9937. server_domain_len = strlen(server_domain);
  9938. if (!server_domain_len) {
  9939. return 0;
  9940. }
  9941. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  9942. if (mg_strncasecmp(uri,
  9943. abs_uri_protocols[i].proto,
  9944. abs_uri_protocols[i].proto_len) == 0) {
  9945. hostbegin = uri + abs_uri_protocols[i].proto_len;
  9946. hostend = strchr(hostbegin, '/');
  9947. if (!hostend) {
  9948. return 0;
  9949. }
  9950. portbegin = strchr(hostbegin, ':');
  9951. if ((!portbegin) || (portbegin > hostend)) {
  9952. port = abs_uri_protocols[i].default_port;
  9953. request_domain_len = (size_t)(hostend - hostbegin);
  9954. } else {
  9955. port = strtoul(portbegin + 1, &portend, 10);
  9956. if ((portend != hostend) || !port || !is_valid_port(port)) {
  9957. return 0;
  9958. }
  9959. request_domain_len = (size_t)(portbegin - hostbegin);
  9960. }
  9961. /* protocol found, port set */
  9962. break;
  9963. }
  9964. }
  9965. if (!port) {
  9966. /* port remains 0 if the protocol is not found */
  9967. return 0;
  9968. }
  9969. #if defined(USE_IPV6)
  9970. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  9971. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  9972. /* Request is directed to a different port */
  9973. return 0;
  9974. }
  9975. } else
  9976. #endif
  9977. {
  9978. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  9979. /* Request is directed to a different port */
  9980. return 0;
  9981. }
  9982. }
  9983. if ((request_domain_len != server_domain_len)
  9984. || (0 != memcmp(server_domain, hostbegin, server_domain_len))) {
  9985. /* Request is directed to another server */
  9986. return 0;
  9987. }
  9988. return hostend;
  9989. }
  9990. static int
  9991. getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  9992. {
  9993. const char *cl;
  9994. if (ebuf_len > 0) {
  9995. ebuf[0] = '\0';
  9996. }
  9997. *err = 0;
  9998. reset_per_request_attributes(conn);
  9999. if (!conn) {
  10000. mg_snprintf(conn,
  10001. NULL, /* No truncation check for ebuf */
  10002. ebuf,
  10003. ebuf_len,
  10004. "%s",
  10005. "Internal error");
  10006. *err = 500;
  10007. return 0;
  10008. }
  10009. /* Set the time the request was received. This value should be used for
  10010. * timeouts. */
  10011. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  10012. conn->request_len =
  10013. read_request(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  10014. /* assert(conn->request_len < 0 || conn->data_len >= conn->request_len);
  10015. */
  10016. if (conn->request_len >= 0 && conn->data_len < conn->request_len) {
  10017. mg_snprintf(conn,
  10018. NULL, /* No truncation check for ebuf */
  10019. ebuf,
  10020. ebuf_len,
  10021. "%s",
  10022. "Invalid request size");
  10023. *err = 500;
  10024. return 0;
  10025. }
  10026. if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
  10027. mg_snprintf(conn,
  10028. NULL, /* No truncation check for ebuf */
  10029. ebuf,
  10030. ebuf_len,
  10031. "%s",
  10032. "Request Too Large");
  10033. *err = 413;
  10034. return 0;
  10035. } else if (conn->request_len <= 0) {
  10036. if (conn->data_len > 0) {
  10037. mg_snprintf(conn,
  10038. NULL, /* No truncation check for ebuf */
  10039. ebuf,
  10040. ebuf_len,
  10041. "%s",
  10042. "Client sent malformed request");
  10043. *err = 400;
  10044. } else {
  10045. /* Server did not send anything -> just close the connection */
  10046. conn->must_close = 1;
  10047. mg_snprintf(conn,
  10048. NULL, /* No truncation check for ebuf */
  10049. ebuf,
  10050. ebuf_len,
  10051. "%s",
  10052. "Client did not send a request");
  10053. *err = 0;
  10054. }
  10055. return 0;
  10056. } else if (parse_http_message(conn->buf,
  10057. conn->buf_size,
  10058. &conn->request_info) <= 0) {
  10059. mg_snprintf(conn,
  10060. NULL, /* No truncation check for ebuf */
  10061. ebuf,
  10062. ebuf_len,
  10063. "%s",
  10064. "Bad Request");
  10065. *err = 400;
  10066. return 0;
  10067. } else {
  10068. /* Message is a valid request or response */
  10069. if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) {
  10070. /* Request/response has content length set */
  10071. char *endptr = NULL;
  10072. conn->content_len = strtoll(cl, &endptr, 10);
  10073. if (endptr == cl) {
  10074. mg_snprintf(conn,
  10075. NULL, /* No truncation check for ebuf */
  10076. ebuf,
  10077. ebuf_len,
  10078. "%s",
  10079. "Bad Request");
  10080. *err = 411;
  10081. return 0;
  10082. }
  10083. /* Publish the content length back to the request info. */
  10084. conn->request_info.content_length = conn->content_len;
  10085. } else if ((cl = get_header(&conn->request_info, "Transfer-Encoding"))
  10086. != NULL
  10087. && strcmp(cl, "chunked") == 0) {
  10088. conn->is_chunked = 1;
  10089. } else if (!mg_strcasecmp(conn->request_info.request_method, "POST")
  10090. || !mg_strcasecmp(conn->request_info.request_method,
  10091. "PUT")) {
  10092. /* POST or PUT request without content length set */
  10093. conn->content_len = -1;
  10094. } else if (!mg_strncasecmp(conn->request_info.request_method,
  10095. "HTTP/",
  10096. 5)) {
  10097. /* Response without content length set */
  10098. conn->content_len = -1;
  10099. } else {
  10100. /* Other request */
  10101. conn->content_len = 0;
  10102. }
  10103. }
  10104. return 1;
  10105. }
  10106. int
  10107. mg_get_response(struct mg_connection *conn,
  10108. char *ebuf,
  10109. size_t ebuf_len,
  10110. int timeout)
  10111. {
  10112. if (conn) {
  10113. /* Implementation of API function for HTTP clients */
  10114. int err, ret;
  10115. struct mg_context *octx = conn->ctx;
  10116. struct mg_context rctx = *(conn->ctx);
  10117. char txt[32]; /* will not overflow */
  10118. if (timeout >= 0) {
  10119. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  10120. rctx.config[REQUEST_TIMEOUT] = txt;
  10121. set_sock_timeout(conn->client.sock, timeout);
  10122. } else {
  10123. rctx.config[REQUEST_TIMEOUT] = NULL;
  10124. }
  10125. conn->ctx = &rctx;
  10126. ret = getreq(conn, ebuf, ebuf_len, &err);
  10127. conn->ctx = octx;
  10128. /* TODO: 1) uri is deprecated;
  10129. * 2) here, ri.uri is the http response code */
  10130. conn->request_info.uri = conn->request_info.request_uri;
  10131. /* TODO (mid): Define proper return values - maybe return length?
  10132. * For the first test use <0 for error and >0 for OK */
  10133. return (ret == 0) ? -1 : +1;
  10134. }
  10135. return -1;
  10136. }
  10137. struct mg_connection *
  10138. mg_download(const char *host,
  10139. int port,
  10140. int use_ssl,
  10141. char *ebuf,
  10142. size_t ebuf_len,
  10143. const char *fmt,
  10144. ...)
  10145. {
  10146. struct mg_connection *conn;
  10147. va_list ap;
  10148. int i;
  10149. int reqerr;
  10150. va_start(ap, fmt);
  10151. ebuf[0] = '\0';
  10152. /* open a connection */
  10153. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  10154. if (conn != NULL) {
  10155. i = mg_vprintf(conn, fmt, ap);
  10156. if (i <= 0) {
  10157. mg_snprintf(conn,
  10158. NULL, /* No truncation check for ebuf */
  10159. ebuf,
  10160. ebuf_len,
  10161. "%s",
  10162. "Error sending request");
  10163. } else {
  10164. getreq(conn, ebuf, ebuf_len, &reqerr);
  10165. /* TODO: 1) uri is deprecated;
  10166. * 2) here, ri.uri is the http response code */
  10167. conn->request_info.uri = conn->request_info.request_uri;
  10168. }
  10169. }
  10170. /* if an error occured, close the connection */
  10171. if (ebuf[0] != '\0' && conn != NULL) {
  10172. mg_close_connection(conn);
  10173. conn = NULL;
  10174. }
  10175. va_end(ap);
  10176. return conn;
  10177. }
  10178. struct websocket_client_thread_data {
  10179. struct mg_connection *conn;
  10180. mg_websocket_data_handler data_handler;
  10181. mg_websocket_close_handler close_handler;
  10182. void *callback_data;
  10183. };
  10184. #if defined(USE_WEBSOCKET)
  10185. #ifdef _WIN32
  10186. static unsigned __stdcall websocket_client_thread(void *data)
  10187. #else
  10188. static void *
  10189. websocket_client_thread(void *data)
  10190. #endif
  10191. {
  10192. struct websocket_client_thread_data *cdata =
  10193. (struct websocket_client_thread_data *)data;
  10194. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  10195. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  10196. if (cdata->close_handler != NULL) {
  10197. cdata->close_handler(cdata->conn, cdata->callback_data);
  10198. }
  10199. mg_free((void *)cdata);
  10200. #ifdef _WIN32
  10201. return 0;
  10202. #else
  10203. return NULL;
  10204. #endif
  10205. }
  10206. #endif
  10207. struct mg_connection *
  10208. mg_connect_websocket_client(const char *host,
  10209. int port,
  10210. int use_ssl,
  10211. char *error_buffer,
  10212. size_t error_buffer_size,
  10213. const char *path,
  10214. const char *origin,
  10215. mg_websocket_data_handler data_func,
  10216. mg_websocket_close_handler close_func,
  10217. void *user_data)
  10218. {
  10219. struct mg_connection *conn = NULL;
  10220. #if defined(USE_WEBSOCKET)
  10221. struct mg_context *newctx = NULL;
  10222. struct websocket_client_thread_data *thread_data;
  10223. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  10224. static const char *handshake_req;
  10225. if (origin != NULL) {
  10226. handshake_req = "GET %s HTTP/1.1\r\n"
  10227. "Host: %s\r\n"
  10228. "Upgrade: websocket\r\n"
  10229. "Connection: Upgrade\r\n"
  10230. "Sec-WebSocket-Key: %s\r\n"
  10231. "Sec-WebSocket-Version: 13\r\n"
  10232. "Origin: %s\r\n"
  10233. "\r\n";
  10234. } else {
  10235. handshake_req = "GET %s HTTP/1.1\r\n"
  10236. "Host: %s\r\n"
  10237. "Upgrade: websocket\r\n"
  10238. "Connection: Upgrade\r\n"
  10239. "Sec-WebSocket-Key: %s\r\n"
  10240. "Sec-WebSocket-Version: 13\r\n"
  10241. "\r\n";
  10242. }
  10243. /* Establish the client connection and request upgrade */
  10244. conn = mg_download(host,
  10245. port,
  10246. use_ssl,
  10247. error_buffer,
  10248. error_buffer_size,
  10249. handshake_req,
  10250. path,
  10251. host,
  10252. magic,
  10253. origin);
  10254. /* Connection object will be null if something goes wrong */
  10255. if (conn == NULL || (strcmp(conn->request_info.request_uri, "101") != 0)) {
  10256. if (!*error_buffer) {
  10257. /* if there is a connection, but it did not return 101,
  10258. * error_buffer is not yet set */
  10259. mg_snprintf(conn,
  10260. NULL, /* No truncation check for ebuf */
  10261. error_buffer,
  10262. error_buffer_size,
  10263. "Unexpected server reply");
  10264. }
  10265. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  10266. if (conn != NULL) {
  10267. mg_free(conn);
  10268. conn = NULL;
  10269. }
  10270. return conn;
  10271. }
  10272. /* For client connections, mg_context is fake. Since we need to set a
  10273. * callback function, we need to create a copy and modify it. */
  10274. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  10275. memcpy(newctx, conn->ctx, sizeof(struct mg_context));
  10276. newctx->user_data = user_data;
  10277. newctx->context_type = 2; /* client context type */
  10278. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  10279. newctx->workerthreadids =
  10280. (pthread_t *)mg_calloc(newctx->cfg_worker_threads, sizeof(pthread_t));
  10281. conn->ctx = newctx;
  10282. thread_data = (struct websocket_client_thread_data *)
  10283. mg_calloc(sizeof(struct websocket_client_thread_data), 1);
  10284. thread_data->conn = conn;
  10285. thread_data->data_handler = data_func;
  10286. thread_data->close_handler = close_func;
  10287. thread_data->callback_data = NULL;
  10288. /* Start a thread to read the websocket client connection
  10289. * This thread will automatically stop when mg_disconnect is
  10290. * called on the client connection */
  10291. if (mg_start_thread_with_id(websocket_client_thread,
  10292. (void *)thread_data,
  10293. newctx->workerthreadids) != 0) {
  10294. mg_free((void *)thread_data);
  10295. mg_free((void *)newctx->workerthreadids);
  10296. mg_free((void *)newctx);
  10297. mg_free((void *)conn);
  10298. conn = NULL;
  10299. DEBUG_TRACE("%s",
  10300. "Websocket client connect thread could not be started\r\n");
  10301. }
  10302. #else
  10303. /* Appease "unused parameter" warnings */
  10304. (void)host;
  10305. (void)port;
  10306. (void)use_ssl;
  10307. (void)error_buffer;
  10308. (void)error_buffer_size;
  10309. (void)path;
  10310. (void)origin;
  10311. (void)user_data;
  10312. (void)data_func;
  10313. (void)close_func;
  10314. #endif
  10315. return conn;
  10316. }
  10317. static void
  10318. process_new_connection(struct mg_connection *conn)
  10319. {
  10320. if (conn && conn->ctx) {
  10321. struct mg_request_info *ri = &conn->request_info;
  10322. int keep_alive_enabled, keep_alive, discard_len;
  10323. char ebuf[100];
  10324. const char *hostend;
  10325. int reqerr, uri_type;
  10326. keep_alive_enabled =
  10327. !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  10328. /* Important: on new connection, reset the receiving buffer. Credit
  10329. * goes to crule42. */
  10330. conn->data_len = 0;
  10331. do {
  10332. if (!getreq(conn, ebuf, sizeof(ebuf), &reqerr)) {
  10333. /* The request sent by the client could not be understood by
  10334. * the server, or it was incomplete or a timeout. Send an
  10335. * error message and close the connection. */
  10336. if (reqerr > 0) {
  10337. /*assert(ebuf[0] != '\0');*/
  10338. send_http_error(conn, reqerr, "%s", ebuf);
  10339. }
  10340. } else if (strcmp(ri->http_version, "1.0")
  10341. && strcmp(ri->http_version, "1.1")) {
  10342. mg_snprintf(conn,
  10343. NULL, /* No truncation check for ebuf */
  10344. ebuf,
  10345. sizeof(ebuf),
  10346. "Bad HTTP version: [%s]",
  10347. ri->http_version);
  10348. send_http_error(conn, 505, "%s", ebuf);
  10349. }
  10350. if (ebuf[0] == '\0') {
  10351. uri_type = get_uri_type(conn->request_info.request_uri);
  10352. switch (uri_type) {
  10353. case 1:
  10354. /* Asterisk */
  10355. conn->request_info.local_uri = NULL;
  10356. break;
  10357. case 2:
  10358. /* relative uri */
  10359. conn->request_info.local_uri =
  10360. conn->request_info.request_uri;
  10361. break;
  10362. case 3:
  10363. case 4:
  10364. /* absolute uri (with/without port) */
  10365. hostend = get_rel_url_at_current_server(
  10366. conn->request_info.request_uri, conn);
  10367. if (hostend) {
  10368. conn->request_info.local_uri = hostend;
  10369. } else {
  10370. conn->request_info.local_uri = NULL;
  10371. }
  10372. break;
  10373. default:
  10374. mg_snprintf(conn,
  10375. NULL, /* No truncation check for ebuf */
  10376. ebuf,
  10377. sizeof(ebuf),
  10378. "Invalid URI: [%s]",
  10379. ri->request_uri);
  10380. send_http_error(conn, 400, "%s", ebuf);
  10381. break;
  10382. }
  10383. /* TODO: cleanup uri, local_uri and request_uri */
  10384. conn->request_info.uri = conn->request_info.local_uri;
  10385. }
  10386. if (ebuf[0] == '\0') {
  10387. if (conn->request_info.local_uri) {
  10388. /* handle request to local server */
  10389. handle_request(conn);
  10390. if (conn->ctx->callbacks.end_request != NULL) {
  10391. conn->ctx->callbacks.end_request(conn,
  10392. conn->status_code);
  10393. }
  10394. log_access(conn);
  10395. } else {
  10396. /* TODO: handle non-local request (PROXY) */
  10397. conn->must_close = 1;
  10398. }
  10399. } else {
  10400. conn->must_close = 1;
  10401. }
  10402. if (ri->remote_user != NULL) {
  10403. mg_free((void *)ri->remote_user);
  10404. /* Important! When having connections with and without auth
  10405. * would cause double free and then crash */
  10406. ri->remote_user = NULL;
  10407. }
  10408. /* NOTE(lsm): order is important here. should_keep_alive() call
  10409. * is
  10410. * using parsed request, which will be invalid after memmove's
  10411. * below.
  10412. * Therefore, memorize should_keep_alive() result now for later
  10413. * use
  10414. * in loop exit condition. */
  10415. keep_alive = conn->ctx->stop_flag == 0 && keep_alive_enabled
  10416. && conn->content_len >= 0 && should_keep_alive(conn);
  10417. /* Discard all buffered data for this request */
  10418. discard_len = conn->content_len >= 0 && conn->request_len > 0
  10419. && conn->request_len + conn->content_len
  10420. < (int64_t)conn->data_len
  10421. ? (int)(conn->request_len + conn->content_len)
  10422. : conn->data_len;
  10423. /*assert(discard_len >= 0);*/
  10424. if (discard_len < 0)
  10425. break;
  10426. conn->data_len -= discard_len;
  10427. if (conn->data_len > 0) {
  10428. memmove(conn->buf,
  10429. conn->buf + discard_len,
  10430. (size_t)conn->data_len);
  10431. }
  10432. /* assert(conn->data_len >= 0); */
  10433. /* assert(conn->data_len <= conn->buf_size); */
  10434. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  10435. break;
  10436. }
  10437. } while (keep_alive);
  10438. }
  10439. }
  10440. /* Worker threads take accepted socket from the queue */
  10441. static int
  10442. consume_socket(struct mg_context *ctx, struct socket *sp)
  10443. {
  10444. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  10445. if (!ctx) {
  10446. return 0;
  10447. }
  10448. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10449. DEBUG_TRACE("%s", "going idle");
  10450. /* If the queue is empty, wait. We're idle at this point. */
  10451. while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
  10452. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  10453. }
  10454. /* If we're stopping, sq_head may be equal to sq_tail. */
  10455. if (ctx->sq_head > ctx->sq_tail) {
  10456. /* Copy socket from the queue and increment tail */
  10457. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  10458. ctx->sq_tail++;
  10459. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  10460. /* Wrap pointers if needed */
  10461. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  10462. ctx->sq_tail -= QUEUE_SIZE(ctx);
  10463. ctx->sq_head -= QUEUE_SIZE(ctx);
  10464. }
  10465. }
  10466. (void)pthread_cond_signal(&ctx->sq_empty);
  10467. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10468. return !ctx->stop_flag;
  10469. #undef QUEUE_SIZE
  10470. }
  10471. static void *
  10472. worker_thread_run(void *thread_func_param)
  10473. {
  10474. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  10475. struct mg_connection *conn;
  10476. struct mg_workerTLS tls;
  10477. #if defined(MG_LEGACY_INTERFACE)
  10478. uint32_t addr;
  10479. #endif
  10480. mg_set_thread_name("worker");
  10481. tls.is_master = 0;
  10482. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  10483. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10484. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  10485. #endif
  10486. conn =
  10487. (struct mg_connection *)mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE);
  10488. if (conn == NULL) {
  10489. mg_cry(fc(ctx), "%s", "Cannot create new connection struct, OOM");
  10490. } else {
  10491. pthread_setspecific(sTlsKey, &tls);
  10492. conn->buf_size = MAX_REQUEST_SIZE;
  10493. conn->buf = (char *)(conn + 1);
  10494. conn->ctx = ctx;
  10495. conn->request_info.user_data = ctx->user_data;
  10496. /* Allocate a mutex for this connection to allow communication both
  10497. * within the request handler and from elsewhere in the application
  10498. */
  10499. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  10500. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  10501. * signal sq_empty condvar to wake up the master waiting in
  10502. * produce_socket() */
  10503. while (consume_socket(ctx, &conn->client)) {
  10504. conn->conn_birth_time = time(NULL);
  10505. /* Fill in IP, port info early so even if SSL setup below fails,
  10506. * error handler would have the corresponding info.
  10507. * Thanks to Johannes Winkelmann for the patch.
  10508. */
  10509. #if defined(USE_IPV6)
  10510. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  10511. conn->request_info.remote_port =
  10512. ntohs(conn->client.rsa.sin6.sin6_port);
  10513. } else
  10514. #endif
  10515. {
  10516. conn->request_info.remote_port =
  10517. ntohs(conn->client.rsa.sin.sin_port);
  10518. }
  10519. sockaddr_to_string(conn->request_info.remote_addr,
  10520. sizeof(conn->request_info.remote_addr),
  10521. &conn->client.rsa);
  10522. #if defined(MG_LEGACY_INTERFACE)
  10523. /* This legacy interface only works for the IPv4 case */
  10524. addr = ntohl(conn->client.rsa.sin.sin_addr.s_addr);
  10525. memcpy(&conn->request_info.remote_ip, &addr, 4);
  10526. #endif
  10527. conn->request_info.is_ssl = conn->client.is_ssl;
  10528. if (!conn->client.is_ssl
  10529. #ifndef NO_SSL
  10530. || sslize(conn, conn->ctx->ssl_ctx, SSL_accept)
  10531. #endif
  10532. ) {
  10533. process_new_connection(conn);
  10534. }
  10535. close_connection(conn);
  10536. }
  10537. }
  10538. /* Signal master that we're done with connection and exiting */
  10539. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10540. ctx->running_worker_threads--;
  10541. (void)pthread_cond_signal(&ctx->thread_cond);
  10542. /* assert(ctx->running_worker_threads >= 0); */
  10543. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10544. pthread_setspecific(sTlsKey, NULL);
  10545. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10546. CloseHandle(tls.pthread_cond_helper_mutex);
  10547. #endif
  10548. pthread_mutex_destroy(&conn->mutex);
  10549. mg_free(conn);
  10550. DEBUG_TRACE("%s", "exiting");
  10551. return NULL;
  10552. }
  10553. /* Threads have different return types on Windows and Unix. */
  10554. #ifdef _WIN32
  10555. static unsigned __stdcall worker_thread(void *thread_func_param)
  10556. {
  10557. worker_thread_run(thread_func_param);
  10558. return 0;
  10559. }
  10560. #else
  10561. static void *
  10562. worker_thread(void *thread_func_param)
  10563. {
  10564. worker_thread_run(thread_func_param);
  10565. return NULL;
  10566. }
  10567. #endif /* _WIN32 */
  10568. /* Master thread adds accepted socket to a queue */
  10569. static void
  10570. produce_socket(struct mg_context *ctx, const struct socket *sp)
  10571. {
  10572. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  10573. if (!ctx) {
  10574. return;
  10575. }
  10576. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10577. /* If the queue is full, wait */
  10578. while (ctx->stop_flag == 0
  10579. && ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx)) {
  10580. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  10581. }
  10582. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  10583. /* Copy socket to the queue and increment head */
  10584. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  10585. ctx->sq_head++;
  10586. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  10587. }
  10588. (void)pthread_cond_signal(&ctx->sq_full);
  10589. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10590. #undef QUEUE_SIZE
  10591. }
  10592. static void
  10593. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  10594. {
  10595. struct socket so;
  10596. char src_addr[IP_ADDR_STR_LEN];
  10597. socklen_t len = sizeof(so.rsa);
  10598. int on = 1;
  10599. int timeout;
  10600. if (!listener) {
  10601. return;
  10602. }
  10603. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  10604. == INVALID_SOCKET) {
  10605. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  10606. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  10607. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  10608. closesocket(so.sock);
  10609. so.sock = INVALID_SOCKET;
  10610. } else {
  10611. /* Put so socket structure into the queue */
  10612. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  10613. set_close_on_exec(so.sock, fc(ctx));
  10614. so.is_ssl = listener->is_ssl;
  10615. so.ssl_redir = listener->ssl_redir;
  10616. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  10617. mg_cry(fc(ctx),
  10618. "%s: getsockname() failed: %s",
  10619. __func__,
  10620. strerror(ERRNO));
  10621. }
  10622. /* Set TCP keep-alive. This is needed because if HTTP-level
  10623. * keep-alive
  10624. * is enabled, and client resets the connection, server won't get
  10625. * TCP FIN or RST and will keep the connection open forever. With
  10626. * TCP keep-alive, next keep-alive handshake will figure out that
  10627. * the client is down and will close the server end.
  10628. * Thanks to Igor Klopov who suggested the patch. */
  10629. if (setsockopt(so.sock,
  10630. SOL_SOCKET,
  10631. SO_KEEPALIVE,
  10632. (SOCK_OPT_TYPE)&on,
  10633. sizeof(on)) != 0) {
  10634. mg_cry(fc(ctx),
  10635. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  10636. __func__,
  10637. strerror(ERRNO));
  10638. }
  10639. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  10640. * to effectively fill up the underlying IP packet payload and reduce
  10641. * the overhead of sending lots of small buffers. However this hurts
  10642. * the server's throughput (ie. operations per second) when HTTP 1.1
  10643. * persistent connections are used and the responses are relatively
  10644. * small (eg. less than 1400 bytes).
  10645. */
  10646. if ((ctx != NULL) && (ctx->config[CONFIG_TCP_NODELAY] != NULL)
  10647. && (!strcmp(ctx->config[CONFIG_TCP_NODELAY], "1"))) {
  10648. if (set_tcp_nodelay(so.sock, 1) != 0) {
  10649. mg_cry(fc(ctx),
  10650. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  10651. __func__,
  10652. strerror(ERRNO));
  10653. }
  10654. }
  10655. if (ctx && ctx->config[REQUEST_TIMEOUT]) {
  10656. timeout = atoi(ctx->config[REQUEST_TIMEOUT]);
  10657. } else {
  10658. timeout = -1;
  10659. }
  10660. /* Set socket timeout to the given value, but not more than a
  10661. * a certain limit (SOCKET_TIMEOUT_QUANTUM, default 10 seconds),
  10662. * so the server can exit after that time if requested. */
  10663. if ((timeout > 0) && (timeout < SOCKET_TIMEOUT_QUANTUM)) {
  10664. set_sock_timeout(so.sock, timeout);
  10665. } else {
  10666. set_sock_timeout(so.sock, SOCKET_TIMEOUT_QUANTUM);
  10667. }
  10668. produce_socket(ctx, &so);
  10669. }
  10670. }
  10671. static void
  10672. master_thread_run(void *thread_func_param)
  10673. {
  10674. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  10675. struct mg_workerTLS tls;
  10676. struct pollfd *pfd;
  10677. unsigned int i;
  10678. unsigned int workerthreadcount;
  10679. if (!ctx) {
  10680. return;
  10681. }
  10682. mg_set_thread_name("master");
  10683. /* Increase priority of the master thread */
  10684. #if defined(_WIN32)
  10685. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  10686. #elif defined(USE_MASTER_THREAD_PRIORITY)
  10687. int min_prio = sched_get_priority_min(SCHED_RR);
  10688. int max_prio = sched_get_priority_max(SCHED_RR);
  10689. if ((min_prio >= 0) && (max_prio >= 0)
  10690. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  10691. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  10692. struct sched_param sched_param = {0};
  10693. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  10694. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  10695. }
  10696. #endif
  10697. /* Initialize thread local storage */
  10698. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10699. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  10700. #endif
  10701. tls.is_master = 1;
  10702. pthread_setspecific(sTlsKey, &tls);
  10703. /* Server starts *now* */
  10704. ctx->start_time = time(NULL);
  10705. /* Allocate memory for the listening sockets, and start the server */
  10706. pfd =
  10707. (struct pollfd *)mg_calloc(ctx->num_listening_sockets, sizeof(pfd[0]));
  10708. while (pfd != NULL && ctx->stop_flag == 0) {
  10709. for (i = 0; i < ctx->num_listening_sockets; i++) {
  10710. pfd[i].fd = ctx->listening_sockets[i].sock;
  10711. pfd[i].events = POLLIN;
  10712. }
  10713. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  10714. for (i = 0; i < ctx->num_listening_sockets; i++) {
  10715. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  10716. * successful poll, and POLLIN is defined as
  10717. * (POLLRDNORM | POLLRDBAND)
  10718. * Therefore, we're checking pfd[i].revents & POLLIN, not
  10719. * pfd[i].revents == POLLIN. */
  10720. if (ctx->stop_flag == 0 && (pfd[i].revents & POLLIN)) {
  10721. accept_new_connection(&ctx->listening_sockets[i], ctx);
  10722. }
  10723. }
  10724. }
  10725. }
  10726. mg_free(pfd);
  10727. DEBUG_TRACE("%s", "stopping workers");
  10728. /* Stop signal received: somebody called mg_stop. Quit. */
  10729. close_all_listening_sockets(ctx);
  10730. /* Wakeup workers that are waiting for connections to handle. */
  10731. pthread_cond_broadcast(&ctx->sq_full);
  10732. /* Wait until all threads finish */
  10733. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10734. while (ctx->running_worker_threads > 0) {
  10735. (void)pthread_cond_wait(&ctx->thread_cond, &ctx->thread_mutex);
  10736. }
  10737. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10738. /* Join all worker threads to avoid leaking threads. */
  10739. workerthreadcount = ctx->cfg_worker_threads;
  10740. for (i = 0; i < workerthreadcount; i++) {
  10741. if (ctx->workerthreadids[i] != 0) {
  10742. mg_join_thread(ctx->workerthreadids[i]);
  10743. }
  10744. }
  10745. #if !defined(NO_SSL)
  10746. if (ctx->ssl_ctx != NULL) {
  10747. uninitialize_ssl(ctx);
  10748. }
  10749. #endif
  10750. DEBUG_TRACE("%s", "exiting");
  10751. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10752. CloseHandle(tls.pthread_cond_helper_mutex);
  10753. #endif
  10754. pthread_setspecific(sTlsKey, NULL);
  10755. /* Signal mg_stop() that we're done.
  10756. * WARNING: This must be the very last thing this
  10757. * thread does, as ctx becomes invalid after this line. */
  10758. ctx->stop_flag = 2;
  10759. }
  10760. /* Threads have different return types on Windows and Unix. */
  10761. #ifdef _WIN32
  10762. static unsigned __stdcall master_thread(void *thread_func_param)
  10763. {
  10764. master_thread_run(thread_func_param);
  10765. return 0;
  10766. }
  10767. #else
  10768. static void *
  10769. master_thread(void *thread_func_param)
  10770. {
  10771. master_thread_run(thread_func_param);
  10772. return NULL;
  10773. }
  10774. #endif /* _WIN32 */
  10775. static void
  10776. free_context(struct mg_context *ctx)
  10777. {
  10778. int i;
  10779. struct mg_handler_info *tmp_rh;
  10780. if (ctx == NULL) {
  10781. return;
  10782. }
  10783. if (ctx->callbacks.exit_context) {
  10784. ctx->callbacks.exit_context(ctx);
  10785. }
  10786. /* All threads exited, no sync is needed. Destroy thread mutex and
  10787. * condvars
  10788. */
  10789. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  10790. (void)pthread_cond_destroy(&ctx->thread_cond);
  10791. (void)pthread_cond_destroy(&ctx->sq_empty);
  10792. (void)pthread_cond_destroy(&ctx->sq_full);
  10793. /* Destroy other context global data structures mutex */
  10794. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  10795. #if defined(USE_TIMERS)
  10796. timers_exit(ctx);
  10797. #endif
  10798. /* Deallocate config parameters */
  10799. for (i = 0; i < NUM_OPTIONS; i++) {
  10800. if (ctx->config[i] != NULL) {
  10801. #if defined(_MSC_VER)
  10802. #pragma warning(suppress : 6001)
  10803. #endif
  10804. mg_free(ctx->config[i]);
  10805. }
  10806. }
  10807. /* Deallocate request handlers */
  10808. while (ctx->handlers) {
  10809. tmp_rh = ctx->handlers;
  10810. ctx->handlers = tmp_rh->next;
  10811. mg_free(tmp_rh->uri);
  10812. mg_free(tmp_rh);
  10813. }
  10814. #ifndef NO_SSL
  10815. /* Deallocate SSL context */
  10816. if (ctx->ssl_ctx != NULL) {
  10817. SSL_CTX_free(ctx->ssl_ctx);
  10818. }
  10819. #endif /* !NO_SSL */
  10820. /* Deallocate worker thread ID array */
  10821. if (ctx->workerthreadids != NULL) {
  10822. mg_free(ctx->workerthreadids);
  10823. }
  10824. /* Deallocate the tls variable */
  10825. if (mg_atomic_dec(&sTlsInit) == 0) {
  10826. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10827. DeleteCriticalSection(&global_log_file_lock);
  10828. #endif /* _WIN32 && !__SYMBIAN32__ */
  10829. #if !defined(_WIN32)
  10830. pthread_mutexattr_destroy(&pthread_mutex_attr);
  10831. #endif
  10832. pthread_key_delete(sTlsKey);
  10833. }
  10834. /* deallocate system name string */
  10835. mg_free(ctx->systemName);
  10836. /* Deallocate context itself */
  10837. mg_free(ctx);
  10838. }
  10839. void
  10840. mg_stop(struct mg_context *ctx)
  10841. {
  10842. pthread_t mt;
  10843. if (!ctx) {
  10844. return;
  10845. }
  10846. /* We don't use a lock here. Calling mg_stop with the same ctx from
  10847. * two threads is not allowed. */
  10848. mt = ctx->masterthreadid;
  10849. if (mt == 0) {
  10850. return;
  10851. }
  10852. ctx->masterthreadid = 0;
  10853. ctx->stop_flag = 1;
  10854. /* Wait until mg_fini() stops */
  10855. while (ctx->stop_flag != 2) {
  10856. (void)mg_sleep(10);
  10857. }
  10858. mg_join_thread(mt);
  10859. free_context(ctx);
  10860. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10861. (void)WSACleanup();
  10862. #endif /* _WIN32 && !__SYMBIAN32__ */
  10863. }
  10864. static void
  10865. get_system_name(char **sysName)
  10866. {
  10867. #if defined(_WIN32)
  10868. #if !defined(__SYMBIAN32__)
  10869. char name[128];
  10870. DWORD dwVersion = 0;
  10871. DWORD dwMajorVersion = 0;
  10872. DWORD dwMinorVersion = 0;
  10873. DWORD dwBuild = 0;
  10874. #ifdef _MSC_VER
  10875. #pragma warning(push)
  10876. // GetVersion was declared deprecated
  10877. #pragma warning(disable : 4996)
  10878. #endif
  10879. dwVersion = GetVersion();
  10880. #ifdef _MSC_VER
  10881. #pragma warning(pop)
  10882. #endif
  10883. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  10884. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  10885. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  10886. (void)dwBuild;
  10887. sprintf(name,
  10888. "Windows %u.%u",
  10889. (unsigned)dwMajorVersion,
  10890. (unsigned)dwMinorVersion);
  10891. *sysName = mg_strdup(name);
  10892. #else
  10893. *sysName = mg_strdup("Symbian");
  10894. #endif
  10895. #else
  10896. struct utsname name;
  10897. memset(&name, 0, sizeof(name));
  10898. uname(&name);
  10899. *sysName = mg_strdup(name.sysname);
  10900. #endif
  10901. }
  10902. struct mg_context *
  10903. mg_start(const struct mg_callbacks *callbacks,
  10904. void *user_data,
  10905. const char **options)
  10906. {
  10907. struct mg_context *ctx;
  10908. const char *name, *value, *default_value;
  10909. int idx, ok, workerthreadcount;
  10910. unsigned int i;
  10911. void (*exit_callback)(const struct mg_context *ctx) = 0;
  10912. struct mg_workerTLS tls;
  10913. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10914. WSADATA data;
  10915. WSAStartup(MAKEWORD(2, 2), &data);
  10916. #endif /* _WIN32 && !__SYMBIAN32__ */
  10917. /* Allocate context and initialize reasonable general case defaults. */
  10918. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  10919. return NULL;
  10920. }
  10921. /* Random number generator will initialize at the first call */
  10922. ctx->auth_nonce_mask =
  10923. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  10924. if (mg_atomic_inc(&sTlsInit) == 1) {
  10925. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10926. InitializeCriticalSection(&global_log_file_lock);
  10927. #endif /* _WIN32 && !__SYMBIAN32__ */
  10928. #if !defined(_WIN32)
  10929. pthread_mutexattr_init(&pthread_mutex_attr);
  10930. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  10931. #endif
  10932. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  10933. /* Fatal error - abort start. However, this situation should
  10934. * never
  10935. * occur in practice. */
  10936. mg_atomic_dec(&sTlsInit);
  10937. mg_cry(fc(ctx), "Cannot initialize thread local storage");
  10938. mg_free(ctx);
  10939. return NULL;
  10940. }
  10941. } else {
  10942. /* TODO (low): istead of sleeping, check if sTlsKey is already
  10943. * initialized. */
  10944. mg_sleep(1);
  10945. }
  10946. tls.is_master = -1;
  10947. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  10948. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10949. tls.pthread_cond_helper_mutex = NULL;
  10950. #endif
  10951. pthread_setspecific(sTlsKey, &tls);
  10952. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr);
  10953. ok &= 0 == pthread_cond_init(&ctx->thread_cond, NULL);
  10954. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  10955. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  10956. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr);
  10957. if (!ok) {
  10958. /* Fatal error - abort start. However, this situation should never
  10959. * occur in practice. */
  10960. mg_cry(fc(ctx), "Cannot initialize thread synchronization objects");
  10961. mg_free(ctx);
  10962. pthread_setspecific(sTlsKey, NULL);
  10963. return NULL;
  10964. }
  10965. if (callbacks) {
  10966. ctx->callbacks = *callbacks;
  10967. exit_callback = callbacks->exit_context;
  10968. ctx->callbacks.exit_context = 0;
  10969. }
  10970. ctx->user_data = user_data;
  10971. ctx->handlers = NULL;
  10972. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  10973. ctx->shared_lua_websockets = 0;
  10974. #endif
  10975. while (options && (name = *options++) != NULL) {
  10976. if ((idx = get_option_index(name)) == -1) {
  10977. mg_cry(fc(ctx), "Invalid option: %s", name);
  10978. free_context(ctx);
  10979. pthread_setspecific(sTlsKey, NULL);
  10980. return NULL;
  10981. } else if ((value = *options++) == NULL) {
  10982. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  10983. free_context(ctx);
  10984. pthread_setspecific(sTlsKey, NULL);
  10985. return NULL;
  10986. }
  10987. if (ctx->config[idx] != NULL) {
  10988. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  10989. mg_free(ctx->config[idx]);
  10990. }
  10991. ctx->config[idx] = mg_strdup(value);
  10992. DEBUG_TRACE("[%s] -> [%s]", name, value);
  10993. }
  10994. /* Set default value if needed */
  10995. for (i = 0; config_options[i].name != NULL; i++) {
  10996. default_value = config_options[i].default_value;
  10997. if (ctx->config[i] == NULL && default_value != NULL) {
  10998. ctx->config[i] = mg_strdup(default_value);
  10999. }
  11000. }
  11001. #if defined(NO_FILES)
  11002. if (ctx->config[DOCUMENT_ROOT] != NULL) {
  11003. mg_cry(fc(ctx), "%s", "Document root must not be set");
  11004. free_context(ctx);
  11005. pthread_setspecific(sTlsKey, NULL);
  11006. return NULL;
  11007. }
  11008. #endif
  11009. get_system_name(&ctx->systemName);
  11010. /* NOTE(lsm): order is important here. SSL certificates must
  11011. * be initialized before listening ports. UID must be set last. */
  11012. if (!set_gpass_option(ctx) ||
  11013. #if !defined(NO_SSL)
  11014. !set_ssl_option(ctx) ||
  11015. #endif
  11016. !set_ports_option(ctx) ||
  11017. #if !defined(_WIN32)
  11018. !set_uid_option(ctx) ||
  11019. #endif
  11020. !set_acl_option(ctx)) {
  11021. free_context(ctx);
  11022. pthread_setspecific(sTlsKey, NULL);
  11023. return NULL;
  11024. }
  11025. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  11026. /* Ignore SIGPIPE signal, so if browser cancels the request, it
  11027. * won't kill the whole process. */
  11028. (void)signal(SIGPIPE, SIG_IGN);
  11029. #endif /* !_WIN32 && !__SYMBIAN32__ */
  11030. workerthreadcount = atoi(ctx->config[NUM_THREADS]);
  11031. if (workerthreadcount > MAX_WORKER_THREADS) {
  11032. mg_cry(fc(ctx), "Too many worker threads");
  11033. free_context(ctx);
  11034. pthread_setspecific(sTlsKey, NULL);
  11035. return NULL;
  11036. }
  11037. if (workerthreadcount > 0) {
  11038. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  11039. ctx->workerthreadids =
  11040. (pthread_t *)mg_calloc(ctx->cfg_worker_threads, sizeof(pthread_t));
  11041. if (ctx->workerthreadids == NULL) {
  11042. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  11043. free_context(ctx);
  11044. pthread_setspecific(sTlsKey, NULL);
  11045. return NULL;
  11046. }
  11047. }
  11048. #if defined(USE_TIMERS)
  11049. if (timers_init(ctx) != 0) {
  11050. mg_cry(fc(ctx), "Error creating timers");
  11051. free_context(ctx);
  11052. pthread_setspecific(sTlsKey, NULL);
  11053. return NULL;
  11054. }
  11055. #endif
  11056. /* Context has been created - init user libraries */
  11057. if (ctx->callbacks.init_context) {
  11058. ctx->callbacks.init_context(ctx);
  11059. }
  11060. ctx->callbacks.exit_context = exit_callback;
  11061. ctx->context_type = 1; /* server context */
  11062. /* Start master (listening) thread */
  11063. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  11064. /* Start worker threads */
  11065. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  11066. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11067. ctx->running_worker_threads++;
  11068. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11069. if (mg_start_thread_with_id(worker_thread,
  11070. ctx,
  11071. &ctx->workerthreadids[i]) != 0) {
  11072. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11073. ctx->running_worker_threads--;
  11074. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11075. if (i > 0) {
  11076. mg_cry(fc(ctx),
  11077. "Cannot start worker thread %i: error %ld",
  11078. i + 1,
  11079. (long)ERRNO);
  11080. } else {
  11081. mg_cry(fc(ctx),
  11082. "Cannot create threads: error %ld",
  11083. (long)ERRNO);
  11084. free_context(ctx);
  11085. pthread_setspecific(sTlsKey, NULL);
  11086. return NULL;
  11087. }
  11088. break;
  11089. }
  11090. }
  11091. pthread_setspecific(sTlsKey, NULL);
  11092. return ctx;
  11093. }
  11094. /* Feature check API function */
  11095. unsigned
  11096. mg_check_feature(unsigned feature)
  11097. {
  11098. static const unsigned feature_set = 0
  11099. /* Set bits for available features according to API documentation.
  11100. * This bit mask is created at compile time, according to the active
  11101. * preprocessor defines. It is a single const value at runtime. */
  11102. #if !defined(NO_FILES)
  11103. | 1
  11104. #endif
  11105. #if !defined(NO_SSL)
  11106. | 2
  11107. #endif
  11108. #if !defined(NO_CGI)
  11109. | 4
  11110. #endif
  11111. #if defined(USE_IPV6)
  11112. | 8
  11113. #endif
  11114. #if defined(USE_WEBSOCKET)
  11115. | 16
  11116. #endif
  11117. #if defined(USE_LUA)
  11118. | 32
  11119. #endif
  11120. #if defined(USE_DUKTAPE)
  11121. | 64
  11122. #endif
  11123. /* Set some extra bits not defined in the API documentation.
  11124. * These bits may change without further notice. */
  11125. #if defined(MG_LEGACY_INTERFACE)
  11126. | 128
  11127. #endif
  11128. #if defined(MEMORY_DEBUGGING)
  11129. | 256
  11130. #endif
  11131. #if defined(USE_TIMERS)
  11132. | 512
  11133. #endif
  11134. #if !defined(NO_NONCE_CHECK)
  11135. | 1024
  11136. #endif
  11137. #if !defined(NO_POPEN)
  11138. | 2048
  11139. #endif
  11140. ;
  11141. return (feature & feature_set);
  11142. }