civetweb.c 287 KB

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