civetweb.c 300 KB

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