civetweb.c 302 KB

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